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": "user]\n :user/userId 100\n :user/userEmail \"[email protected]\"}\n {:db/id #db/id[:db.part/user]\n :user/us",
"end": 3208,
"score": 0.9999279975891113,
"start": 3190,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user]\n :user/userId 101\n :user/userEmail \"[email protected]\"}\n {:db/id #db/id[:db.part/user]\n :user/us",
"end": 3308,
"score": 0.999928891658783,
"start": 3289,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user]\n :user/userId 102\n :user/userEmail \"[email protected]\"}]])\n",
"end": 3411,
"score": 0.9999277591705322,
"start": 3389,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
vendor/vase/test/com/cognitect/vase/test_db_helper.clj
|
mtnygard/growing-one-system
| 4 |
(ns com.cognitect.vase.test-db-helper
(:require [clojure.test :as t]
[datomic.api :as d])
(:import [java.util UUID]))
(defn new-database
"This generates a new, empty Datomic database for use within unit tests."
[txes]
(let [uri (str "datomic:mem://test" (UUID/randomUUID))
_ (d/create-database uri)
conn (d/connect uri)]
(doseq [t txes]
@(d/transact conn t))
{:uri uri
:connection conn}))
(def ^:dynamic *current-db-connection* nil)
(def ^:dynamic *current-db-uri* nil)
(defmacro with-database
"Executes all requests in the body with the same database."
[txes & body]
`(let [dbm# (new-database ~txes)]
(binding [*current-db-uri* (:uri dbm#)
*current-db-connection* (:connection dbm#)]
~@body)))
(defn connection
([]
(or *current-db-connection* (:connection (new-database []))))
([txes]
(or *current-db-connection* (:connection (new-database txes)))))
(def query-test-txes
[[{:db/id #db/id[:db.part/db]
:db/ident :company/name
:db/unique :db.unique/value
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :user/userId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A Users unique identifier"
:db/unique :db.unique/identity}
{:db/id #db/id[:db.part/db]
:db/ident :user/userEmail
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The users email"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :user/userBio
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A short blurb about the user"
:db/fulltext true :db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :user/userActive?
:db/valueType :db.type/boolean
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "User active flag."
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/loanId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The unique offer ID"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/fees
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "All of the loan fees"
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/notes
:db/valueType :db.type/string
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "Notes about the loan"}
{:db/id #db/id[:db.part/db]
:db/ident :user/loanOffers
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "The collection of loan offers"}]
[{:db/id #db/id[:db.part/user]
:user/userId 100
:user/userEmail "[email protected]"}
{:db/id #db/id[:db.part/user]
:user/userId 101
:user/userEmail "[email protected]"}
{:db/id #db/id[:db.part/user]
:user/userId 102
:user/userEmail "[email protected]"}]])
|
43664
|
(ns com.cognitect.vase.test-db-helper
(:require [clojure.test :as t]
[datomic.api :as d])
(:import [java.util UUID]))
(defn new-database
"This generates a new, empty Datomic database for use within unit tests."
[txes]
(let [uri (str "datomic:mem://test" (UUID/randomUUID))
_ (d/create-database uri)
conn (d/connect uri)]
(doseq [t txes]
@(d/transact conn t))
{:uri uri
:connection conn}))
(def ^:dynamic *current-db-connection* nil)
(def ^:dynamic *current-db-uri* nil)
(defmacro with-database
"Executes all requests in the body with the same database."
[txes & body]
`(let [dbm# (new-database ~txes)]
(binding [*current-db-uri* (:uri dbm#)
*current-db-connection* (:connection dbm#)]
~@body)))
(defn connection
([]
(or *current-db-connection* (:connection (new-database []))))
([txes]
(or *current-db-connection* (:connection (new-database txes)))))
(def query-test-txes
[[{:db/id #db/id[:db.part/db]
:db/ident :company/name
:db/unique :db.unique/value
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :user/userId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A Users unique identifier"
:db/unique :db.unique/identity}
{:db/id #db/id[:db.part/db]
:db/ident :user/userEmail
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The users email"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :user/userBio
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A short blurb about the user"
:db/fulltext true :db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :user/userActive?
:db/valueType :db.type/boolean
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "User active flag."
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/loanId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The unique offer ID"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/fees
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "All of the loan fees"
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/notes
:db/valueType :db.type/string
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "Notes about the loan"}
{:db/id #db/id[:db.part/db]
:db/ident :user/loanOffers
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "The collection of loan offers"}]
[{:db/id #db/id[:db.part/user]
:user/userId 100
:user/userEmail "<EMAIL>"}
{:db/id #db/id[:db.part/user]
:user/userId 101
:user/userEmail "<EMAIL>"}
{:db/id #db/id[:db.part/user]
:user/userId 102
:user/userEmail "<EMAIL>"}]])
| true |
(ns com.cognitect.vase.test-db-helper
(:require [clojure.test :as t]
[datomic.api :as d])
(:import [java.util UUID]))
(defn new-database
"This generates a new, empty Datomic database for use within unit tests."
[txes]
(let [uri (str "datomic:mem://test" (UUID/randomUUID))
_ (d/create-database uri)
conn (d/connect uri)]
(doseq [t txes]
@(d/transact conn t))
{:uri uri
:connection conn}))
(def ^:dynamic *current-db-connection* nil)
(def ^:dynamic *current-db-uri* nil)
(defmacro with-database
"Executes all requests in the body with the same database."
[txes & body]
`(let [dbm# (new-database ~txes)]
(binding [*current-db-uri* (:uri dbm#)
*current-db-connection* (:connection dbm#)]
~@body)))
(defn connection
([]
(or *current-db-connection* (:connection (new-database []))))
([txes]
(or *current-db-connection* (:connection (new-database txes)))))
(def query-test-txes
[[{:db/id #db/id[:db.part/db]
:db/ident :company/name
:db/unique :db.unique/value
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :user/userId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A Users unique identifier"
:db/unique :db.unique/identity}
{:db/id #db/id[:db.part/db]
:db/ident :user/userEmail
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The users email"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :user/userBio
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "A short blurb about the user"
:db/fulltext true :db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :user/userActive?
:db/valueType :db.type/boolean
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "User active flag."
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/loanId
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "The unique offer ID"
:db/unique :db.unique/value}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/fees
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db
:db/doc "All of the loan fees"
:db/index true}
{:db/id #db/id[:db.part/db]
:db/ident :loanOffer/notes
:db/valueType :db.type/string
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "Notes about the loan"}
{:db/id #db/id[:db.part/db]
:db/ident :user/loanOffers
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db
:db/doc "The collection of loan offers"}]
[{:db/id #db/id[:db.part/user]
:user/userId 100
:user/userEmail "PI:EMAIL:<EMAIL>END_PI"}
{:db/id #db/id[:db.part/user]
:user/userId 101
:user/userEmail "PI:EMAIL:<EMAIL>END_PI"}
{:db/id #db/id[:db.part/user]
:user/userId 102
:user/userEmail "PI:EMAIL:<EMAIL>END_PI"}]])
|
[
{
"context": "csrf-paths]\n (fn [request]\n (let [auth-token \"auth-token\"]\n (log/info (str \"Request path: \" (:uri req",
"end": 496,
"score": 0.86149662733078,
"start": 486,
"tag": "PASSWORD",
"value": "auth-token"
}
] |
src/clj/clojurecademy/middleware/session_and_cookie.clj
|
harunpehlivan/clojurecademy
| 651 |
(ns clojurecademy.middleware.session-and-cookie
(:require [clojurecademy.util.resource :as resource.util]
[clojurecademy.middleware.anti-forgery :as anti-forgery]
[clojure.tools.logging :as log]
[kezban.core :refer :all]))
(defn- get-request?
[{method :request-method}]
(or (= method :head)
(= method :get)
(= method :options)))
(defn wrap-session-and-cookie
[handler ignored-csrf-paths]
(fn [request]
(let [auth-token "auth-token"]
(log/info (str "Request path: " (:uri request)))
(if (and (in? (:uri request) ignored-csrf-paths) (not (get-request? request)))
(handler request)
(let [response (handler request)
cookie-val (:value (get (:cookies request) auth-token))
token anti-forgery/*anti-forgery-token*]
(if (= cookie-val token)
response
(assoc response :cookies {auth-token {:value token :same-site :strict :path "/"}})))))))
|
11320
|
(ns clojurecademy.middleware.session-and-cookie
(:require [clojurecademy.util.resource :as resource.util]
[clojurecademy.middleware.anti-forgery :as anti-forgery]
[clojure.tools.logging :as log]
[kezban.core :refer :all]))
(defn- get-request?
[{method :request-method}]
(or (= method :head)
(= method :get)
(= method :options)))
(defn wrap-session-and-cookie
[handler ignored-csrf-paths]
(fn [request]
(let [auth-token "<PASSWORD>"]
(log/info (str "Request path: " (:uri request)))
(if (and (in? (:uri request) ignored-csrf-paths) (not (get-request? request)))
(handler request)
(let [response (handler request)
cookie-val (:value (get (:cookies request) auth-token))
token anti-forgery/*anti-forgery-token*]
(if (= cookie-val token)
response
(assoc response :cookies {auth-token {:value token :same-site :strict :path "/"}})))))))
| true |
(ns clojurecademy.middleware.session-and-cookie
(:require [clojurecademy.util.resource :as resource.util]
[clojurecademy.middleware.anti-forgery :as anti-forgery]
[clojure.tools.logging :as log]
[kezban.core :refer :all]))
(defn- get-request?
[{method :request-method}]
(or (= method :head)
(= method :get)
(= method :options)))
(defn wrap-session-and-cookie
[handler ignored-csrf-paths]
(fn [request]
(let [auth-token "PI:PASSWORD:<PASSWORD>END_PI"]
(log/info (str "Request path: " (:uri request)))
(if (and (in? (:uri request) ignored-csrf-paths) (not (get-request? request)))
(handler request)
(let [response (handler request)
cookie-val (:value (get (:cookies request) auth-token))
token anti-forgery/*anti-forgery-token*]
(if (= cookie-val token)
response
(assoc response :cookies {auth-token {:value token :same-site :strict :path "/"}})))))))
|
[
{
"context": " \"0\"\n \"0\"\n \"skynet\"\n \"192.168.1.6\"\n \"8452\"\n \"8\"\n \"1\"\n ",
"end": 1188,
"score": 0.9997192025184631,
"start": 1179,
"tag": "IP_ADDRESS",
"value": "192.168.1"
},
{
"context": "ler/parse-battleopened \"BATTLEOPENED 1 0 0 skynet 192.168.1.6 8452 8 1 0 -1706632985 Spring\t104.0.1-1510-g89bb8",
"end": 1574,
"score": 0.9997348189353943,
"start": 1563,
"tag": "IP_ADDRESS",
"value": "192.168.1.6"
},
{
"context": " :user-id \"8\"\n :username \"skynet\"}}}}}\n @state-atom)))\n (let [state-ato",
"end": 3913,
"score": 0.9982077479362488,
"start": 3907,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " {:server1\n {:users\n {\"ChanServ\"\n {\n :country \"US\"\n ",
"end": 4170,
"score": 0.9965533018112183,
"start": 4162,
"tag": "USERNAME",
"value": "ChanServ"
},
{
"context": " :user-id \"0\"\n :username \"ChanServ\"}}}}}\n @state-atom)))\n (let [state-ato",
"end": 4347,
"score": 0.9994329214096069,
"start": 4339,
"tag": "USERNAME",
"value": "ChanServ"
},
{
"context": " :user-id \"2218\"\n :username \"[teh]host20\"}}}}}\n @state-atom)))\n (let [state-ato",
"end": 4808,
"score": 0.9974614977836609,
"start": 4798,
"tag": "USERNAME",
"value": "teh]host20"
},
{
"context": " {:server1\n {:users\n {\"skynet\"\n {\n :country \"??\"\n ",
"end": 5052,
"score": 0.9969121813774109,
"start": 5046,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :user-id \"8\"\n :username \"skynet\"}}}}}\n @state-atom)))\n (let [state-ato",
"end": 5220,
"score": 0.9996655583381653,
"start": 5214,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " {:server1\n {:users\n {\"Zecrus\"\n {\n :country \"US\"\n ",
"end": 5511,
"score": 0.9995719790458679,
"start": 5505,
"tag": "USERNAME",
"value": "Zecrus"
},
{
"context": " :user-id \"67\"\n :username \"Zecrus\"}}}}}\n @state-atom)))\n (testing \"join ",
"end": 5722,
"score": 0.9997075200080872,
"start": 5716,
"tag": "USERNAME",
"value": "Zecrus"
},
{
"context": "ver1\n {:channels\n {\"@skynet\"\n {:messages\n [{",
"end": 6206,
"score": 0.8752511143684387,
"start": 6200,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :timestamp now\n :username \"skynet\"}]}}\n :my-channels {\"@skynet\" {}}\n",
"end": 6377,
"score": 0.9972522258758545,
"start": 6371,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": "net\" {}}\n :users\n {\"skynet\"\n {\n :country \"?",
"end": 6474,
"score": 0.9627900719642639,
"start": 6468,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :user-id \"8\"\n :username \"skynet\"}}}}}\n @state-atom)))))\n\n\n(deftest ha",
"end": 6654,
"score": 0.9965813755989075,
"start": 6648,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": "kynet\" {}}\n :users {\"skynet\" {}}}}})\n now 12345]\n (with-redefs ",
"end": 6970,
"score": 0.8623399138450623,
"start": 6964,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " {\n :channels\n {\"@skynet\"\n {:messages\n [{",
"end": 7238,
"score": 0.8103803396224976,
"start": 7231,
"tag": "USERNAME",
"value": "@skynet"
},
{
"context": " :timestamp now\n :username \"skynet\"}]}}\n :my-channels {\"@skynet\" {}}\n",
"end": 7410,
"score": 0.9969620704650879,
"start": 7404,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :timestamp now\n :username \"[teh]cluster1[01]\"\n :spads {:spads-message-type :",
"end": 8241,
"score": 0.9643101096153259,
"start": 8226,
"tag": "USERNAME",
"value": "teh]cluster1[01"
},
{
"context": " :users\n {\"skynet\"\n {:battle-status\n ",
"end": 9085,
"score": 0.9761042594909668,
"start": 9079,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :sync 0}}}}\n :username \"skynet\"\n :client-data {:compfla",
"end": 9455,
"score": 0.9987945556640625,
"start": 9449,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": ")]\n (handler/handle state-atom server-key \"SAIDBATTLEEX host1 * Global setting changed by skynet (teamS",
"end": 9873,
"score": 0.78464275598526,
"start": 9863,
"tag": "KEY",
"value": "SAIDBATTLE"
},
{
"context": " false\n :users\n {\"skynet\"\n {:battle-status\n ",
"end": 10162,
"score": 0.982550323009491,
"start": 10156,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :username \"host1\"\n ",
"end": 10731,
"score": 0.9991991519927979,
"start": 10726,
"tag": "USERNAME",
"value": "host1"
},
{
"context": " :relay nil}]}}\n :username \"skynet\"\n :client-data {:compflags #{\"u\"}}",
"end": 10964,
"score": 0.9995535016059875,
"start": 10958,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :username \"user1\"}]\n ",
"end": 13959,
"score": 0.9987589120864868,
"start": 13954,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :username \"someone\"}]\n :us",
"end": 14860,
"score": 0.9993371963500977,
"start": 14853,
"tag": "USERNAME",
"value": "someone"
},
{
"context": ":server1\n {:users\n {\"skynet\"\n {:client-status\n ",
"end": 16027,
"score": 0.9043951034545898,
"start": 16021,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": "sername host}}\n :username me\n :users\n ",
"end": 16820,
"score": 0.9642989635467529,
"start": 16818,
"tag": "USERNAME",
"value": "me"
},
{
"context": " {:host-username host}}\n :username me\n :users\n {host\n ",
"end": 17791,
"score": 0.8946173787117004,
"start": 17789,
"tag": "USERNAME",
"value": "me"
},
{
"context": "battle\n {:users\n {\"skynet\"\n {:battle-status\n ",
"end": 18725,
"score": 0.9887561798095703,
"start": 18719,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " {:users\n {\"skynet\"\n {:battle-status\n ",
"end": 19396,
"score": 0.994166374206543,
"start": 19390,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :sync 0}}}}\n :username \"skynet\"}}})\n messages-atom (atom [])]\n (wi",
"end": 20124,
"score": 0.9980955123901367,
"start": 20118,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " false\n :users\n {\"skynet\"\n {:battle-status\n ",
"end": 20640,
"score": 0.9933565258979797,
"start": 20634,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :team-color \"0\"}}}\n :username \"skynet\"}}}\n @state-atom))\n (is (= [\"MYB",
"end": 21224,
"score": 0.9985318183898926,
"start": 21218,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :sync 0}}}}\n :username \"skynet\"\n :client-data {:compfla",
"end": 22438,
"score": 0.9988552927970886,
"start": 22432,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": "les {\"0\" {:users nil}}\n :username \"skynet\"\n :client-data {:compflags #{\"u\"}}",
"end": 23341,
"score": 0.9982309937477112,
"start": 23335,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :users\n {\"skynet\"\n {:battle-status\n ",
"end": 24079,
"score": 0.9856886863708496,
"start": 24073,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :sync 0}}}}\n :username \"skynet\"\n :client-data {:compfla",
"end": 24449,
"score": 0.9985373020172119,
"start": 24443,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " false\n :users\n {\"skynet\"\n {:battle-status\n ",
"end": 25175,
"score": 0.9890069961547852,
"start": 25169,
"tag": "USERNAME",
"value": "skynet"
},
{
"context": " :username \"host1\"\n ",
"end": 25744,
"score": 0.9988728761672974,
"start": 25739,
"tag": "USERNAME",
"value": "host1"
},
{
"context": "els {\"__battle__0\" {}}\n :username \"skynet\"\n :client-data {:compflags #{\"u\"}}",
"end": 26025,
"score": 0.9990854263305664,
"start": 26019,
"tag": "USERNAME",
"value": "skynet"
}
] |
test/clj/spring_lobby/client/handler_test.clj
|
badosu/skylobby
| 7 |
(ns spring-lobby.client.handler-test
(:require
[clojure.test :refer [deftest is testing]]
[skylobby.util :as u]
[spring-lobby.client.handler :as handler]
[spring-lobby.client.message :as message]
[spring-lobby.client.util :as cu]))
(set! *warn-on-reflection* true)
(deftest parse-addbot
(is (= ["12" "kekbot1" "skynet9001" "0" "0" "KAIK|0.13"]
(rest (handler/parse-addbot "ADDBOT 12 kekbot1 skynet9001 0 0 KAIK|0.13"))))
(is (= ["4" "Bot2" "skynet9001" "4195534" "16744322" "MFAI : normal (air)|<not-versioned>"]
(rest (handler/parse-addbot "ADDBOT 4 Bot2 skynet9001 4195534 16744322 MFAI : normal (air)|<not-versioned>"))))
(is (= ["13674" "BARbstable(1)" "owner" "4195334" "16747775" "BARb"]
(rest (handler/parse-addbot "ADDBOT 13674 BARbstable(1) owner 4195334 16747775 BARb")))))
(deftest parse-ai
(is (= ["MFAI : normal (air)" "|<not-versioned>" "<not-versioned>"]
(rest (handler/parse-ai "MFAI : normal (air)|<not-versioned>"))))
(is (= ["BARb" nil nil]
(rest (handler/parse-ai "BARb")))))
(deftest parse-battleopened
(is (= ["1"
"0"
"0"
"skynet"
"192.168.1.6"
"8452"
"8"
"1"
"0"
"-1706632985"
"Spring"
"104.0.1-1510-g89bb8e3 maintenance"
"Mini_SuperSpeedMetal"
"deth"
"Balanced Annihilation V10.24"
"\t__battle__8"
"__battle__8"]
(rest
(handler/parse-battleopened "BATTLEOPENED 1 0 0 skynet 192.168.1.6 8452 8 1 0 -1706632985 Spring 104.0.1-1510-g89bb8e3 maintenance Mini_SuperSpeedMetal deth Balanced Annihilation V10.24 __battle__8")))))
(deftest parse-updatebattleinfo
(is (= ["1"
"0"
"0"
"1465550451"
"Archers_Valley_v6"]
(rest
(handler/parse-updatebattleinfo "UPDATEBATTLEINFO 1 0 0 1465550451 Archers_Valley_v6")))))
(deftest parse-joinbattle
(is (= ["32" "-1706632985" " __battle__1" "__battle__1"]
(rest
(handler/parse-joinbattle "JOINBATTLE 32 -1706632985 __battle__1")))))
(deftest parse-adduser
(is (= ["skynet"
"??"
nil
nil
"8"
" SpringLobby 0.270 (win x32)"
"SpringLobby 0.270 (win x32)"]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)"))))
(is (= ["ChanServ"
"US"
nil
nil
"0"
" ChanServ"
"ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US 0 ChanServ"))))
(is (= ["[teh]host20"
"HU"
nil
nil
"2218"
" SPADS v0.12.18"
"SPADS v0.12.18"]
(rest (handler/parse-adduser "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18"))))
(is (= ["skynet"
"??"
nil
nil
"8"
nil
nil]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8"))))
(is (= ["Zecrus"
"US"
" 0"
"0"
"67"
" SpringLobby 0.270-49-gab254fe7d (windows64)"
"SpringLobby 0.270-49-gab254fe7d (windows64)"]
(rest (handler/parse-adduser "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)"))))
(is (= ["ChanServ" "US" nil nil "None" " ChanServ" "ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US None ChanServ")))))
(deftest handle-ADDUSER
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent "SpringLobby 0.270 (win x32)"
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER ChanServ US 0 ChanServ")
(is (= {:by-server
{:server1
{:users
{"ChanServ"
{
:country "US"
:cpu nil
:user-agent "ChanServ"
:user-id "0"
:username "ChanServ"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18")
(is (= {:by-server
{:server1
{:users
{"[teh]host20"
{
:country "HU"
:cpu nil
:user-agent "SPADS v0.12.18"
:user-id "2218"
:username "[teh]host20"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)")
(is (= {:by-server
{:server1
{:users
{"Zecrus"
{
:country "US"
:cpu "0"
:user-agent "SpringLobby 0.270-49-gab254fe7d (windows64)"
:user-id "67"
:username "Zecrus"}}}}}
@state-atom)))
(testing "join message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8"))
(is (= {:by-server
{:server1
{:channels
{"@skynet"
{:messages
[{:message-type :join
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))))
(deftest handle-REMOVEUSER
(testing "leave message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}
:users {"skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "REMOVEUSER skynet"))
(is (= {:by-server
{:server1
{
:channels
{"@skynet"
{:messages
[{:message-type :leave
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users {}}}}
@state-atom)))))
(deftest handle-SAIDBATTLEEX
(testing "message"
(let [state-atom (atom {:by-server {:server1 {:battle {:battle-id "1"}}}})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDBATTLEEX [teh]cluster1[01] * Hi skynet! Current battle type is team."))
(is (= {:by-server
{:server1
{:battle {:battle-id "1"}
:channels
{"__battle__1"
{:messages
[{:message-type :ex
:text "* Hi skynet! Current battle type is team."
:timestamp now
:username "[teh]cluster1[01]"
:spads {:spads-message-type :greeting,
:spads-parsed ["Hi skynet! Current battle type is team."
"skynet"
"team"],
:text "* Hi skynet! Current battle type is team."}
:vote nil
:relay nil}]}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDBATTLEEX host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-SAIDFROM
(let [state-atom (atom {})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDFROM evolution user:springrts.com :)"))
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:messages
[{:message-type nil
:text ":)"
:timestamp now
:username "user:springrts.com"
:spads nil
:vote nil
:relay nil}]}}}}}
@state-atom))))
(deftest handle-CLIENTSFROM
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key
"CLIENTSFROM evolution appservice user1:discord user:springrts.com user3:discord user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user3:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}
"user:springrts.com" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-JOINEDFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "JOINEDFROM evolution appservice user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest left
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/left state-atom server-key "__battle__1" "user1"))
(is (= {
:by-server {:server1 {:battle {
:channel-name "__battle__1"}
:channels {"__battle__1" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "user1"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFT
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "LEFT __battle__1234 someone"))
(is (= {:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}
:channels {"__battle__1234" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "someone"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFTFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "LEFTFROM evolution user1:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-CLIENTSTATUS
(testing "zero"
(let [state-atom (atom {})
game-started (atom false)
server-key :server1]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))]
(handler/handle state-atom server-key "CLIENTSTATUS skynet 0"))
(is (= {:by-server
{:server1
{:users
{"skynet"
{:client-status
{:access false
:away false
:bot false
:ingame false
:rank 0}}}}}}
@state-atom))
(is (false? @game-started))))
(testing "start game"
(let [host "skynet"
me "me"
state-atom (atom
{:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me {:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host {:client-status {:ingame false}}}}}})
game-started (atom false)
server-key :server1
client-status-str (cu/encode-client-status
(assoc
cu/default-client-status
:ingame true))
now 12345]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))
u/curr-millis (constantly now)]
(handler/handle state-atom server-key (str "CLIENTSTATUS " host " " client-status-str)))
(is (= {:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me
{:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host
{:client-status
{:access false
:away false
:bot false
:ingame true
:rank 0}
:game-start-time now}}}}}
@state-atom))
(is (true? @game-started)))))
(deftest handle-CLIENTBATTLESTATUS
(testing "add user"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:battle {}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS skynet 0 0"))
(is (= {:by-server
{server-key
{:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}}}}
@state-atom))
(is (= []
@messages-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS other 0 0"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}
:username "skynet"}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-LEFTBATTLE
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "LEFTBATTLE 0 other"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:battles {"0" {:users nil}}
:username "skynet"
:client-data {:compflags #{"u"}}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest teamsize-changed-message?
(is (false? (handler/teamsize-changed-message? "")))
(is (true? (handler/teamsize-changed-message? "* Global setting changed by skynet (teamSize=16)"))))
(deftest handle-SAIDEX
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDEX __battle__0 host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:my-channels {"__battle__0" {}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
|
65000
|
(ns spring-lobby.client.handler-test
(:require
[clojure.test :refer [deftest is testing]]
[skylobby.util :as u]
[spring-lobby.client.handler :as handler]
[spring-lobby.client.message :as message]
[spring-lobby.client.util :as cu]))
(set! *warn-on-reflection* true)
(deftest parse-addbot
(is (= ["12" "kekbot1" "skynet9001" "0" "0" "KAIK|0.13"]
(rest (handler/parse-addbot "ADDBOT 12 kekbot1 skynet9001 0 0 KAIK|0.13"))))
(is (= ["4" "Bot2" "skynet9001" "4195534" "16744322" "MFAI : normal (air)|<not-versioned>"]
(rest (handler/parse-addbot "ADDBOT 4 Bot2 skynet9001 4195534 16744322 MFAI : normal (air)|<not-versioned>"))))
(is (= ["13674" "BARbstable(1)" "owner" "4195334" "16747775" "BARb"]
(rest (handler/parse-addbot "ADDBOT 13674 BARbstable(1) owner 4195334 16747775 BARb")))))
(deftest parse-ai
(is (= ["MFAI : normal (air)" "|<not-versioned>" "<not-versioned>"]
(rest (handler/parse-ai "MFAI : normal (air)|<not-versioned>"))))
(is (= ["BARb" nil nil]
(rest (handler/parse-ai "BARb")))))
(deftest parse-battleopened
(is (= ["1"
"0"
"0"
"skynet"
"192.168.1.6"
"8452"
"8"
"1"
"0"
"-1706632985"
"Spring"
"104.0.1-1510-g89bb8e3 maintenance"
"Mini_SuperSpeedMetal"
"deth"
"Balanced Annihilation V10.24"
"\t__battle__8"
"__battle__8"]
(rest
(handler/parse-battleopened "BATTLEOPENED 1 0 0 skynet 192.168.1.6 8452 8 1 0 -1706632985 Spring 104.0.1-1510-g89bb8e3 maintenance Mini_SuperSpeedMetal deth Balanced Annihilation V10.24 __battle__8")))))
(deftest parse-updatebattleinfo
(is (= ["1"
"0"
"0"
"1465550451"
"Archers_Valley_v6"]
(rest
(handler/parse-updatebattleinfo "UPDATEBATTLEINFO 1 0 0 1465550451 Archers_Valley_v6")))))
(deftest parse-joinbattle
(is (= ["32" "-1706632985" " __battle__1" "__battle__1"]
(rest
(handler/parse-joinbattle "JOINBATTLE 32 -1706632985 __battle__1")))))
(deftest parse-adduser
(is (= ["skynet"
"??"
nil
nil
"8"
" SpringLobby 0.270 (win x32)"
"SpringLobby 0.270 (win x32)"]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)"))))
(is (= ["ChanServ"
"US"
nil
nil
"0"
" ChanServ"
"ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US 0 ChanServ"))))
(is (= ["[teh]host20"
"HU"
nil
nil
"2218"
" SPADS v0.12.18"
"SPADS v0.12.18"]
(rest (handler/parse-adduser "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18"))))
(is (= ["skynet"
"??"
nil
nil
"8"
nil
nil]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8"))))
(is (= ["Zecrus"
"US"
" 0"
"0"
"67"
" SpringLobby 0.270-49-gab254fe7d (windows64)"
"SpringLobby 0.270-49-gab254fe7d (windows64)"]
(rest (handler/parse-adduser "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)"))))
(is (= ["ChanServ" "US" nil nil "None" " ChanServ" "ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US None ChanServ")))))
(deftest handle-ADDUSER
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent "SpringLobby 0.270 (win x32)"
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER ChanServ US 0 ChanServ")
(is (= {:by-server
{:server1
{:users
{"ChanServ"
{
:country "US"
:cpu nil
:user-agent "ChanServ"
:user-id "0"
:username "ChanServ"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18")
(is (= {:by-server
{:server1
{:users
{"[teh]host20"
{
:country "HU"
:cpu nil
:user-agent "SPADS v0.12.18"
:user-id "2218"
:username "[teh]host20"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)")
(is (= {:by-server
{:server1
{:users
{"Zecrus"
{
:country "US"
:cpu "0"
:user-agent "SpringLobby 0.270-49-gab254fe7d (windows64)"
:user-id "67"
:username "Zecrus"}}}}}
@state-atom)))
(testing "join message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8"))
(is (= {:by-server
{:server1
{:channels
{"@skynet"
{:messages
[{:message-type :join
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))))
(deftest handle-REMOVEUSER
(testing "leave message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}
:users {"skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "REMOVEUSER skynet"))
(is (= {:by-server
{:server1
{
:channels
{"@skynet"
{:messages
[{:message-type :leave
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users {}}}}
@state-atom)))))
(deftest handle-SAIDBATTLEEX
(testing "message"
(let [state-atom (atom {:by-server {:server1 {:battle {:battle-id "1"}}}})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDBATTLEEX [teh]cluster1[01] * Hi skynet! Current battle type is team."))
(is (= {:by-server
{:server1
{:battle {:battle-id "1"}
:channels
{"__battle__1"
{:messages
[{:message-type :ex
:text "* Hi skynet! Current battle type is team."
:timestamp now
:username "[teh]cluster1[01]"
:spads {:spads-message-type :greeting,
:spads-parsed ["Hi skynet! Current battle type is team."
"skynet"
"team"],
:text "* Hi skynet! Current battle type is team."}
:vote nil
:relay nil}]}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "<KEY>EX host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-SAIDFROM
(let [state-atom (atom {})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDFROM evolution user:springrts.com :)"))
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:messages
[{:message-type nil
:text ":)"
:timestamp now
:username "user:springrts.com"
:spads nil
:vote nil
:relay nil}]}}}}}
@state-atom))))
(deftest handle-CLIENTSFROM
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key
"CLIENTSFROM evolution appservice user1:discord user:springrts.com user3:discord user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user3:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}
"user:springrts.com" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-JOINEDFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "JOINEDFROM evolution appservice user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest left
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/left state-atom server-key "__battle__1" "user1"))
(is (= {
:by-server {:server1 {:battle {
:channel-name "__battle__1"}
:channels {"__battle__1" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "user1"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFT
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "LEFT __battle__1234 someone"))
(is (= {:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}
:channels {"__battle__1234" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "someone"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFTFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "LEFTFROM evolution user1:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-CLIENTSTATUS
(testing "zero"
(let [state-atom (atom {})
game-started (atom false)
server-key :server1]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))]
(handler/handle state-atom server-key "CLIENTSTATUS skynet 0"))
(is (= {:by-server
{:server1
{:users
{"skynet"
{:client-status
{:access false
:away false
:bot false
:ingame false
:rank 0}}}}}}
@state-atom))
(is (false? @game-started))))
(testing "start game"
(let [host "skynet"
me "me"
state-atom (atom
{:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me {:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host {:client-status {:ingame false}}}}}})
game-started (atom false)
server-key :server1
client-status-str (cu/encode-client-status
(assoc
cu/default-client-status
:ingame true))
now 12345]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))
u/curr-millis (constantly now)]
(handler/handle state-atom server-key (str "CLIENTSTATUS " host " " client-status-str)))
(is (= {:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me
{:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host
{:client-status
{:access false
:away false
:bot false
:ingame true
:rank 0}
:game-start-time now}}}}}
@state-atom))
(is (true? @game-started)))))
(deftest handle-CLIENTBATTLESTATUS
(testing "add user"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:battle {}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS skynet 0 0"))
(is (= {:by-server
{server-key
{:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}}}}
@state-atom))
(is (= []
@messages-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS other 0 0"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}
:username "skynet"}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-LEFTBATTLE
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "LEFTBATTLE 0 other"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:battles {"0" {:users nil}}
:username "skynet"
:client-data {:compflags #{"u"}}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest teamsize-changed-message?
(is (false? (handler/teamsize-changed-message? "")))
(is (true? (handler/teamsize-changed-message? "* Global setting changed by skynet (teamSize=16)"))))
(deftest handle-SAIDEX
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDEX __battle__0 host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:my-channels {"__battle__0" {}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
| true |
(ns spring-lobby.client.handler-test
(:require
[clojure.test :refer [deftest is testing]]
[skylobby.util :as u]
[spring-lobby.client.handler :as handler]
[spring-lobby.client.message :as message]
[spring-lobby.client.util :as cu]))
(set! *warn-on-reflection* true)
(deftest parse-addbot
(is (= ["12" "kekbot1" "skynet9001" "0" "0" "KAIK|0.13"]
(rest (handler/parse-addbot "ADDBOT 12 kekbot1 skynet9001 0 0 KAIK|0.13"))))
(is (= ["4" "Bot2" "skynet9001" "4195534" "16744322" "MFAI : normal (air)|<not-versioned>"]
(rest (handler/parse-addbot "ADDBOT 4 Bot2 skynet9001 4195534 16744322 MFAI : normal (air)|<not-versioned>"))))
(is (= ["13674" "BARbstable(1)" "owner" "4195334" "16747775" "BARb"]
(rest (handler/parse-addbot "ADDBOT 13674 BARbstable(1) owner 4195334 16747775 BARb")))))
(deftest parse-ai
(is (= ["MFAI : normal (air)" "|<not-versioned>" "<not-versioned>"]
(rest (handler/parse-ai "MFAI : normal (air)|<not-versioned>"))))
(is (= ["BARb" nil nil]
(rest (handler/parse-ai "BARb")))))
(deftest parse-battleopened
(is (= ["1"
"0"
"0"
"skynet"
"192.168.1.6"
"8452"
"8"
"1"
"0"
"-1706632985"
"Spring"
"104.0.1-1510-g89bb8e3 maintenance"
"Mini_SuperSpeedMetal"
"deth"
"Balanced Annihilation V10.24"
"\t__battle__8"
"__battle__8"]
(rest
(handler/parse-battleopened "BATTLEOPENED 1 0 0 skynet 192.168.1.6 8452 8 1 0 -1706632985 Spring 104.0.1-1510-g89bb8e3 maintenance Mini_SuperSpeedMetal deth Balanced Annihilation V10.24 __battle__8")))))
(deftest parse-updatebattleinfo
(is (= ["1"
"0"
"0"
"1465550451"
"Archers_Valley_v6"]
(rest
(handler/parse-updatebattleinfo "UPDATEBATTLEINFO 1 0 0 1465550451 Archers_Valley_v6")))))
(deftest parse-joinbattle
(is (= ["32" "-1706632985" " __battle__1" "__battle__1"]
(rest
(handler/parse-joinbattle "JOINBATTLE 32 -1706632985 __battle__1")))))
(deftest parse-adduser
(is (= ["skynet"
"??"
nil
nil
"8"
" SpringLobby 0.270 (win x32)"
"SpringLobby 0.270 (win x32)"]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)"))))
(is (= ["ChanServ"
"US"
nil
nil
"0"
" ChanServ"
"ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US 0 ChanServ"))))
(is (= ["[teh]host20"
"HU"
nil
nil
"2218"
" SPADS v0.12.18"
"SPADS v0.12.18"]
(rest (handler/parse-adduser "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18"))))
(is (= ["skynet"
"??"
nil
nil
"8"
nil
nil]
(rest (handler/parse-adduser "ADDUSER skynet ?? 8"))))
(is (= ["Zecrus"
"US"
" 0"
"0"
"67"
" SpringLobby 0.270-49-gab254fe7d (windows64)"
"SpringLobby 0.270-49-gab254fe7d (windows64)"]
(rest (handler/parse-adduser "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)"))))
(is (= ["ChanServ" "US" nil nil "None" " ChanServ" "ChanServ"]
(rest (handler/parse-adduser "ADDUSER ChanServ US None ChanServ")))))
(deftest handle-ADDUSER
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8 SpringLobby 0.270 (win x32)")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent "SpringLobby 0.270 (win x32)"
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER ChanServ US 0 ChanServ")
(is (= {:by-server
{:server1
{:users
{"ChanServ"
{
:country "US"
:cpu nil
:user-agent "ChanServ"
:user-id "0"
:username "ChanServ"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER [teh]host20 HU 2218 SPADS v0.12.18")
(is (= {:by-server
{:server1
{:users
{"[teh]host20"
{
:country "HU"
:cpu nil
:user-agent "SPADS v0.12.18"
:user-id "2218"
:username "[teh]host20"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8")
(is (= {:by-server
{:server1
{:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key "ADDUSER Zecrus US 0 67 SpringLobby 0.270-49-gab254fe7d (windows64)")
(is (= {:by-server
{:server1
{:users
{"Zecrus"
{
:country "US"
:cpu "0"
:user-agent "SpringLobby 0.270-49-gab254fe7d (windows64)"
:user-id "67"
:username "Zecrus"}}}}}
@state-atom)))
(testing "join message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "ADDUSER skynet ?? 8"))
(is (= {:by-server
{:server1
{:channels
{"@skynet"
{:messages
[{:message-type :join
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users
{"skynet"
{
:country "??"
:cpu nil
:user-agent nil
:user-id "8"
:username "skynet"}}}}}
@state-atom)))))
(deftest handle-REMOVEUSER
(testing "leave message"
(let [
server-key :server1
state-atom (atom {:by-server
{server-key
{:my-channels {"@skynet" {}}
:users {"skynet" {}}}}})
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "REMOVEUSER skynet"))
(is (= {:by-server
{:server1
{
:channels
{"@skynet"
{:messages
[{:message-type :leave
:text ""
:timestamp now
:username "skynet"}]}}
:my-channels {"@skynet" {}}
:users {}}}}
@state-atom)))))
(deftest handle-SAIDBATTLEEX
(testing "message"
(let [state-atom (atom {:by-server {:server1 {:battle {:battle-id "1"}}}})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDBATTLEEX [teh]cluster1[01] * Hi skynet! Current battle type is team."))
(is (= {:by-server
{:server1
{:battle {:battle-id "1"}
:channels
{"__battle__1"
{:messages
[{:message-type :ex
:text "* Hi skynet! Current battle type is team."
:timestamp now
:username "[teh]cluster1[01]"
:spads {:spads-message-type :greeting,
:spads-parsed ["Hi skynet! Current battle type is team."
"skynet"
"team"],
:text "* Hi skynet! Current battle type is team."}
:vote nil
:relay nil}]}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "PI:KEY:<KEY>END_PIEX host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-SAIDFROM
(let [state-atom (atom {})
server-key :server1
now 12345]
(with-redefs [u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDFROM evolution user:springrts.com :)"))
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:messages
[{:message-type nil
:text ":)"
:timestamp now
:username "user:springrts.com"
:spads nil
:vote nil
:relay nil}]}}}}}
@state-atom))))
(deftest handle-CLIENTSFROM
(let [state-atom (atom {})
server-key :server1]
(handler/handle state-atom server-key
"CLIENTSFROM evolution appservice user1:discord user:springrts.com user3:discord user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user3:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}
"user:springrts.com" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-JOINEDFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "JOINEDFROM evolution appservice user4:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest left
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/left state-atom server-key "__battle__1" "user1"))
(is (= {
:by-server {:server1 {:battle {
:channel-name "__battle__1"}
:channels {"__battle__1" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "user1"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFT
(let [state-atom (atom
{:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}}}})
server-key :server1
now 12345]
(with-redefs [
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "LEFT __battle__1234 someone"))
(is (= {:by-server
{:server1
{:battle
{:channel-name "__battle__1234"}
:channels {"__battle__1234" {:messages [{:message-type :leave
:text ""
:timestamp now
:username "someone"}]
:users nil}}}}}
@state-atom))))
(deftest handle-LEFTFROM
(let [state-atom (atom
{:by-server
{:server1
{:channels
{"evolution"
{:users
{"user1:discord" {:bridge "appservice"}
"user4:discord" {:bridge "appservice"}}}}}}})
server-key :server1]
(handler/handle state-atom server-key "LEFTFROM evolution user1:discord")
(is (= {:by-server
{:server1
{:channels
{"evolution"
{:users
{"user4:discord" {:bridge "appservice"}}}}}}}
@state-atom))))
(deftest handle-CLIENTSTATUS
(testing "zero"
(let [state-atom (atom {})
game-started (atom false)
server-key :server1]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))]
(handler/handle state-atom server-key "CLIENTSTATUS skynet 0"))
(is (= {:by-server
{:server1
{:users
{"skynet"
{:client-status
{:access false
:away false
:bot false
:ingame false
:rank 0}}}}}}
@state-atom))
(is (false? @game-started))))
(testing "start game"
(let [host "skynet"
me "me"
state-atom (atom
{:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me {:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host {:client-status {:ingame false}}}}}})
game-started (atom false)
server-key :server1
client-status-str (cu/encode-client-status
(assoc
cu/default-client-status
:ingame true))
now 12345]
(with-redefs [handler/start-game-if-synced (fn [& _] (reset! game-started true))
u/curr-millis (constantly now)]
(handler/handle state-atom server-key (str "CLIENTSTATUS " host " " client-status-str)))
(is (= {:by-server
{:server1
{:battle
{:battle-id :battle1
:users
{me
{:battle-status {:mode true}}
host {}}}
:battles
{:battle1
{:host-username host}}
:username me
:users
{host
{:client-status
{:access false
:away false
:bot false
:ingame true
:rank 0}
:game-start-time now}}}}}
@state-atom))
(is (true? @game-started)))))
(deftest handle-CLIENTBATTLESTATUS
(testing "add user"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:battle {}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS skynet 0 0"))
(is (= {:by-server
{server-key
{:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}}}}
@state-atom))
(is (= []
@messages-atom))))
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "CLIENTBATTLESTATUS other 0 0"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}
:team-color "0"}}}
:username "skynet"}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest handle-LEFTBATTLE
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}
"other"
{:battle-status
{:ally 0
:handicap 0
:id 1
:mode true
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)]
(handler/handle state-atom server-key "LEFTBATTLE 0 other"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:battle-id "0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:battles {"0" {:users nil}}
:username "skynet"
:client-data {:compflags #{"u"}}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
(deftest teamsize-changed-message?
(is (false? (handler/teamsize-changed-message? "")))
(is (true? (handler/teamsize-changed-message? "* Global setting changed by skynet (teamSize=16)"))))
(deftest handle-SAIDEX
(testing "auto unspec"
(let [
server-key :server1
state-atom (atom
{:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:username "skynet"
:client-data {:compflags #{"u"}}}}})
messages-atom (atom [])
now 1631909524841]
(with-redefs [message/send-message (fn [_state-atom _client-data message] (swap! messages-atom conj message))
handler/auto-unspec-ready? (constantly true)
u/curr-millis (constantly now)]
(handler/handle state-atom server-key "SAIDEX __battle__0 host1 * Global setting changed by skynet (teamSize=16)"))
(is (= {:by-server
{server-key
{:auto-unspec true
:battle
{:channel-name "__battle__0"
:desired-ready false
:users
{"skynet"
{:battle-status
{:ally 0
:handicap 0
:id 0
:mode false
:ready false
:side 0
:sync 0}}}}
:channels {"__battle__0" {:messages [{:message-type :ex
:text "* Global setting changed by skynet (teamSize=16)"
:timestamp now
:username "host1"
:spads nil
:vote nil
:relay nil}]}}
:my-channels {"__battle__0" {}}
:username "skynet"
:client-data {:compflags #{"u"}}}}
:needs-focus {:server1 {"battle" {:battle true}}}}
@state-atom))
(is (= ["MYBATTLESTATUS 1024 0"]
@messages-atom)))))
|
[
{
"context": "g Call\")\n (prompt-select :corp (find-card \"Oaktown Renovation\" (:hand (get-corp))))\n (prompt-choice :cor",
"end": 10104,
"score": 0.8116592764854431,
"start": 10086,
"tag": "NAME",
"value": "Oaktown Renovation"
},
{
"context": "t-corp))]\n (trash-from-hand state :runner \"DaVinci\")\n (is (= corp-creds (:credit (get-corp)",
"end": 17639,
"score": 0.5202510952949524,
"start": 17638,
"tag": "USERNAME",
"value": "V"
},
{
"context": "-runner [(qty \"Cache\" 2) (qty \"Fall Guy\" 1) (qty \"Mr. Li\" 1)]))\n (take-credits state :corp)\n (pl",
"end": 40807,
"score": 0.7236063480377197,
"start": 40805,
"tag": "NAME",
"value": "Mr"
},
{
"context": "nner [(qty \"Cache\" 2) (qty \"Fall Guy\" 1) (qty \"Mr. Li\" 1)]))\n (take-credits state :corp)\n (play-f",
"end": 40811,
"score": 0.5431931018829346,
"start": 40809,
"tag": "NAME",
"value": "Li"
},
{
"context": "r \"Cache\")\n (prompt-select :runner (find-card \"Mr. Li\" (:hand (get-runner))))\n (is (empty? (:pro",
"end": 41092,
"score": 0.5146377086639404,
"start": 41090,
"tag": "NAME",
"value": "Mr"
},
{
"context": "ner took 6 tags\"))))\n\n(deftest mushin-no-shin\n ;; Mushin No Shin - Add 3 advancements to a card; prevent rez/score",
"end": 49334,
"score": 0.8878127932548523,
"start": 49320,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "rn\n (do-game\n (new-game (default-corp [(qty \"Mushin No Shin\" 2) (qty \"Ronin\" 1) (qty \"Profiteering\" 1)])\n ",
"end": 49477,
"score": 0.5887705683708191,
"start": 49466,
"tag": "NAME",
"value": "ushin No Sh"
},
{
"context": "default-runner))\n (play-from-hand state :corp \"Mushin No Shin\")\n (prompt-select :corp (find-card \"Ronin\" (:h",
"end": 49604,
"score": 0.9979432225227356,
"start": 49590,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "in No Shin\")\n (prompt-select :corp (find-card \"Ronin\" (:hand (get-corp))))\n (let [ronin (get-conten",
"end": 49649,
"score": 0.9945055842399597,
"start": 49644,
"tag": "NAME",
"value": "Ronin"
},
{
"context": "n now rezzed\")\n (play-from-hand state :corp \"Mushin No Shin\")\n (prompt-select :corp (find-card \"Profitee",
"end": 50149,
"score": 0.9988536238670349,
"start": 50135,
"tag": "NAME",
"value": "Mushin No Shin"
},
{
"context": "ecognition\")\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 55520,
"score": 0.9997386932373047,
"start": 55507,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Quandary\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 55663,
"score": 0.9991242289543152,
"start": 55655,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 55737,
"score": 0.9996771216392517,
"start": 55723,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 56039,
"score": 0.9996472001075745,
"start": 56025,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Quandary\" (:deck (get-corp))))\n (prompt-choice :corp (f",
"end": 56107,
"score": 0.9995462894439697,
"start": 56099,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "get-corp))))\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp)))) ;this is the top card of R&",
"end": 56255,
"score": 0.9996389150619507,
"start": 56242,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": " R&D\n (prompt-choice :corp \"Done\")\n (is (= \"Caprice Nisei\" (:title (first (:deck (get-corp))))))\n (is (=",
"end": 56365,
"score": 0.9996693730354309,
"start": 56352,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": ":title (second (:deck (get-corp))))))\n (is (= \"Quandary\" (:title (second (rest (:deck (get-corp)))))))\n ",
"end": 56493,
"score": 0.8225421905517578,
"start": 56485,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "(second (rest (:deck (get-corp)))))))\n (is (= \"Jackson Howard\" (:title (second (rest (rest (:deck (get-corp))))",
"end": 56567,
"score": 0.9995881915092468,
"start": 56553,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": " (prompt-choice :corp \"New remote\")\n (is (= \"Caprice Nisei\" (:title (get-content state :remote1 0)))\n \"",
"end": 58752,
"score": 0.9998378753662109,
"start": 58739,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "\" (:title (get-content state :remote1 0)))\n \"Caprice Nisei installed by Psychokinesis\")\n ;; Test in",
"end": 58809,
"score": 0.9614788293838501,
"start": 58802,
"tag": "NAME",
"value": "Caprice"
},
{
"context": " (get-content state :remote1 0)))\n \"Caprice Nisei installed by Psychokinesis\")\n ;; Test install",
"end": 58814,
"score": 0.889658510684967,
"start": 58811,
"tag": "NAME",
"value": "ise"
},
{
"context": "er :credit 3)\n (play-from-hand state :runner \"Hades Shard\")\n (card-ability state :runner (get-in @",
"end": 73695,
"score": 0.5759709477424622,
"start": 73691,
"tag": "NAME",
"value": "ades"
},
{
"context": "efault-corp [(qty \"Subliminal Messaging\" 1) (qty \"Jackson Howard\" 1)])\n (default-runner))\n (play-f",
"end": 81707,
"score": 0.9954525232315063,
"start": 81693,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "inal Messaging\")\n (play-from-hand state :corp \"Jackson Howard\" \"New remote\")\n (take-credits state :corp)\n ",
"end": 81849,
"score": 0.9980690479278564,
"start": 81835,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "g\")\n (play-from-hand state :runner \"Jarogniew Mercs\")\n (take-credits state :runner)\n (is (=",
"end": 91047,
"score": 0.5605653524398804,
"start": 91042,
"tag": "NAME",
"value": "Mercs"
}
] |
test/clj/game_test/cards/operations.clj
|
Odie/netrunner
| 0 |
(ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards)
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest accelerated-diagnostics-with-current
;; Accelerated Diagnostics - Interaction with Current
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1)
(qty "Enhanced Login Protocol" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 3)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:corp :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund"))))
(deftest an-offer-you-cant-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-corp [(qty "Celebrity Gift" 1) (qty "An Offer You Can't Refuse" 1)])
(default-runner))
(play-from-hand state :corp "An Offer You Can't Refuse")
(prompt-choice :corp "R&D")
(core/move state :corp (find-card "Celebrity Gift" (:hand (get-corp))) :discard)
(is (= 2 (count (:discard (get-corp)))))
(prompt-choice :runner "No")
(is (= 1 (:agenda-point (get-corp))) "An Offer the Runner refused")
(is (= 1 (count (:scored (get-corp)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-corp))))
(is (= 1 (count (:discard (get-corp)))))
(is (find-card "Celebrity Gift" (:discard (get-corp))))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "Hunter" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Oaktown Renovation" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast-runner-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 1)])
(default-runner))
(play-from-hand state :corp "Cerebral Cast")
(is (= 3 (:click (get-corp))) "Cerebral Cast precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (= 0 (count (:discard (get-runner)))) "Runner took no damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags")))
(deftest cerebral-cast-corp-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 2)])
(default-runner))
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 brain damage")
(is (= 1 (count (:discard (get-runner)))) "Runner took a brain damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags from brain damage choice")
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 tag")
(is (= 1 (count (:discard (get-runner)))) "Runner took no additional damage")
(is (= 1 (:tag (get-runner))) "Runner took a tag from Cerebral Cast choice")))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest commercialization-single-advancement
;; Commercialization - Single advancement token
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 1)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 6 (:credit (get-corp))) "Gained 1 for single advanced ice from Commercialization")))
(deftest commercialization-double-advancement
;; Commercialization - Two advancement tokens
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 2)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 7 (:credit (get-corp))) "Gained 2 for double advanced ice from Commercialization")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on runner install, runner trash installed card
;; Also regression test for #3160
(do-game
(new-game (default-corp [(qty "Death and Taxes" 1) (qty "PAD Campaign" 1)])
(default-runner [(qty "Aumakua" 1) (qty "DaVinci" 1) (qty "Fall Guy" 1)]))
(play-from-hand state :corp "Death and Taxes")
(is (= (- 5 2) (:credit (get-corp))) "Corp paid 2 to play Death and Taxes")
(play-from-hand state :corp "PAD Campaign" "New remote")
(take-credits state :corp)
(let [corp-creds (:credit (get-corp))]
(trash-from-hand state :runner "DaVinci")
(is (= corp-creds (:credit (get-corp))) "Corp did not gain credit when runner trashes / discards from hand")
(play-from-hand state :runner "Aumakua")
(is (= (+ 1 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Aumakua")
(play-from-hand state :runner "Fall Guy")
(is (= (+ 2 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Fall Guy")
(card-ability state :runner (get-resource state 0) 1)
(is (= (+ 3 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed Fall Guy")
(run-empty-server state :remote1)
(prompt-choice :runner "Yes") ;; Runner trashes PAD Campaign
(is (= (+ 4 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-corp [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-runner))
(starting-hand state :corp ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-select :corp (first (next (:hand (get-corp)))))
(prompt-select :corp (first (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 1 (count (:discard (get-corp)))) "1 card still discarded")
(is (= 1 (count (:deck (get-corp)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-runner))) "Runner gained 2 credits")
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-choice :corp "Done")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (first (next (:discard (get-corp)))))
(is (= 0 (count (:discard (get-corp)))) "No cards left in archives")
(is (= 3 (count (:deck (get-corp)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-runner))) "Runner gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the runner lose 4 credits if able
(do-game
(new-game (default-corp [(qty "Economic Warfare" 3)])
(default-runner))
(play-from-hand state :corp "Economic Warfare")
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(is (= 3 (count (:hand (get-corp)))) "Corp still has 3 cards")
(take-credits state :corp)
(run-on state :archives)
(run-successful state)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 4 (:credit (get-runner))) "Runner has 4 credits")
(play-from-hand state :corp "Economic Warfare")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :corp)
(run-on state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 3 (:credit (get-runner))) "Runner has 3 credits")))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to trash installed card not of Runner's faction
(do-game
(new-game (default-corp [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Inti" 1) (qty "Caldera" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Inti")
(play-from-hand state :runner "Caldera")
(take-credits state :runner)
(play-from-hand state :corp "Enforcing Loyalty")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-program state 0))
(is (empty? (:discard (get-runner))) "Can't target Inti; matches Runner faction")
(prompt-select :corp (get-resource state 0))
(is (= 1 (count (:discard (get-runner)))) "Caldera trashed")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-new-angeles-sol
;; Enhanced Login Protocol trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Enhanced Login Protocol" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:discard (get-corp))))
(run-on state :archives)
(is (= 1 (:click (get-runner))) "Runner has 1 click")))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest hatchet-job
;; Hatchet Job - Win trace to add installed non-virtual to grip
(do-game
(new-game (default-corp [(qty "Hatchet Job" 1)])
(default-runner [(qty "Upya" 1) (qty "Ghost Runner" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Ghost Runner")
(play-from-hand state :runner "Upya")
(take-credits state :runner)
(play-from-hand state :corp "Hatchet Job")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(is (empty? (:hand (get-runner))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-corp)))))
(prompt-select :corp (get-program state 0))
(is (= 1 (count (:hand (get-runner)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest high-profile-target
(testing "when the runner has no tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(testing "when the runner has one tag"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (count (:hand (get-runner)))) "Runner has 3 cards in hand")))
(testing "when the runner has two tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 2)
(play-from-hand state :corp "High-Profile Target")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(testing "when the runner has enough tags to die"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest high-profile-target-flatline
;; High-Profile Target - three tags, gg
(do-game
(new-game (default-corp [(qty "High-Profile Target" 10)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "Mr. Li" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "Mr. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest ipo-terminal
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-corp [(qty "IPO" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "IPO")
(is (= 13 (:credit (get-corp))))
(is (= 0 (:click (get-corp))) "Terminal ends turns")))
(deftest lag-time
(do-game
(new-game (default-corp [(qty "Lag Time" 1) (qty "Vanilla" 1) (qty "Lotus Field" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Vanilla" "HQ")
(play-from-hand state :corp "Lotus Field" "R&D")
(play-from-hand state :corp "Lag Time")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(is (= 1 (:current-strength (get-ice state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-ice state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "when the runner is not tagged"
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(play-from-hand state :corp "Market Forces")
(is (= 6 (count (:hand (get-corp))))
"Market Forces is not played")
(is (= 3 (:click (get-corp)))
"the corp does not spend a click")
(is (= 5 (:credit (get-corp)) (:credit (get-runner)))
"credits are unaffected")))
(letfn [(market-forces-credit-test
[{:keys [tag-count runner-creds expected-credit-diff]}]
(testing (str "when the runner has " tag-count " tags and " runner-creds " credits")
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(swap! state assoc-in [:corp :credit] 0)
(swap! state assoc-in [:runner :credit] runner-creds)
(core/gain state :runner :tag tag-count)
(play-from-hand state :corp "Market Forces")
(is (= expected-credit-diff (:credit (get-corp)))
(str "the corp gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- runner-creds (:credit (get-runner))))
(str "the runner loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:runner-creds 10
:expected-credit-diff 3}
{:tag-count 2
:runner-creds 10
:expected-credit-diff 6}
{:tag-count 3
:runner-creds 10
:expected-credit-diff 9}
{:tag-count 3
:runner-creds 0
:expected-credit-diff 0}
{:tag-count 3
:runner-creds 5
:expected-credit-diff 5}]))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-corp [(qty "Mass Commercialization" 1)
(qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :runner)
(core/advance state :corp {:card (refresh (get-ice state :hq 0))})
(core/advance state :corp {:card (refresh (get-ice state :archives 0))})
(core/advance state :corp {:card (refresh (get-ice state :rd 0))})
(take-credits state :runner)
(play-from-hand state :corp "Mass Commercialization")
(is (= 8 (:credit (get-corp))) "Gained 6 for 3 advanced ice from Mass Commercialization")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; Mushin No Shin - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "Mushin No Shin" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "Mushin No Shin")
(prompt-select :corp (find-card "Ronin" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "Ronin did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "Mushin No Shin")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "Jackson Howard" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "Caprice Nisei" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "Quandary" (:title (second (rest (:deck (get-corp)))))))
(is (= "Jackson Howard" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, install an Asset, Agenda, or Upgrade in a Remote Server
(do-game
(new-game (default-corp [(qty "Psychokinesis" 3) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Psychokinesis","Psychokinesis","Psychokinesis"])
;; Test installing an Upgrade
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Caprice Nisei" (:title (get-content state :remote1 0)))
"Caprice Nisei installed by Psychokinesis")
;; Test installing an Asset
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Adonis Campaign" (:title (get-content state :remote2 0)))
"Adonis Campaign installed by Psychokinesis")
;; Test installing an Agenda
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Global Food Initiative" (:title (get-content state :remote3 0)))
"Global Food Initiative installed by Psychokinesis")
;; Test selecting "None"
(core/gain state :corp :click 1)
(core/move state :corp (find-card "Psychokinesis" (:discard (get-corp))) :hand)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp "None")
(is (= nil (:title (get-content state :remote4 0)))
"Nothing is installed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-corp [(qty "Red Planet Couriers" 1) (qty "Ice Wall" 2)
(qty "GRNDL Refinery" 1) (qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 4)
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "GRNDL Refinery" "New remote")
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(let [gt (get-content state :remote1 0)
gr (get-content state :remote2 0)
iw1 (get-ice state :hq 0)
iw2 (get-ice state :rd 0)]
(core/add-prop state :corp gr :advance-counter 3)
(core/add-prop state :corp iw1 :advance-counter 2)
(core/add-prop state :corp iw2 :advance-counter 1)
(play-from-hand state :corp "Red Planet Couriers")
(prompt-select :corp gt)
(is (nil? (:advance-counter (refresh gr))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw1))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw2))) "Advancements removed")
(is (= 6 (:advance-counter (refresh gt))) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and trash 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-corp [(qty "Reverse Infection" 2)])
(default-runner [(qty "Virus Breeding Ground" 1) (qty "Datasucker" 1) (qty "Sure Gamble" 3)]))
(starting-hand state :runner ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Gain 2 [Credits]")
(is (= 7 (:credit (get-corp))) "Corp gained 2 credits")
(take-credits state :corp)
(play-from-hand state :runner "Virus Breeding Ground")
(play-from-hand state :runner "Datasucker")
(take-credits state :runner)
(core/add-counter state :runner (get-resource state 0) :virus 4)
(core/add-counter state :runner (get-program state 0) :virus 3)
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Purge virus counters.")
(is (= 9 (:credit (get-corp))) "Corp did not gain credits")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-program state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-runner)))) "Two cards trashed from stack")))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Runner event of turn
(do-game
(new-game (default-corp [(qty "Rolling Brownout" 1) (qty "Beanstalk Royalties" 1)
(qty "Domestic Sleepers" 1)])
(default-runner [(qty "Easy Mark" 3)]))
(play-from-hand state :corp "Rolling Brownout")
(play-from-hand state :corp "Beanstalk Royalties")
(is (= 5 (:credit (get-corp))) "Beanstalk netted only 2c")
(play-from-hand state :corp "Domestic Sleepers" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Easy Mark")
(is (= 7 (:credit (get-runner))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-corp))) "Corp gained 1c from Brownout")
(play-from-hand state :runner "Easy Mark")
(is (= 6 (:credit (get-corp))) "No Corp credit gain from 2nd event")
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(play-from-hand state :runner "Easy Mark")
(is (= 12 (:credit (get-runner))) "Easy Mark netted 3c after Brownout trashed")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 10)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest self-growth-program
;; Self-Growth Program - Add 2 installed cards to grip if runner is tagged
(do-game
(new-game (default-corp [(qty "Self-Growth Program" 1)])
(default-runner [(qty "Clone Chip" 1) (qty "Inti" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Clone Chip")
(play-from-hand state :runner "Inti")
(take-credits state :runner)
(play-from-hand state :corp "Self-Growth Program")
(is (= 3 (:click (get-corp))) "Self-Growth Program precondition not met; card not played")
(core/gain state :runner :tag 1)
(is (= 0 (count (:hand (get-runner)))) "Runner hand is empty")
(let [inti (get-in @state [:runner :rig :program 0])
cc (get-in @state [:runner :rig :hardware 0])]
(play-from-hand state :corp "Self-Growth Program")
(prompt-select :corp inti)
(prompt-select :corp cc))
(is (= 2 (count (:hand (get-runner)))) "2 cards returned to hand")
(is (= 0 (count (get-in @state [:runner :rig :program]))) "No programs installed")
(is (= 0 (count (get-in @state [:runner :rig :hardware]))) "No hardware installed")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest service-outage-new-angeles-sol
;; Service Outage trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage"
(:discard (get-corp))))
(take-credits state :runner)
(take-credits state :corp)
(is (= 7 (:credit (get-runner))) "Runner has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-runner)))
"Runner spends 1 credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ICE Barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary ICE Barrier"))))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with Jackson
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "Jackson Howard" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Jackson Howard" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest success-bad-publicity
;; Success - Works with bad publicity
(do-game
(new-game (default-corp [(qty "NAPD Contract" 1) (qty "Project Beale" 1) (qty "Success" 1)])
(default-runner))
(play-from-hand state :corp "NAPD Contract" "New remote")
(play-from-hand state :corp "Project Beale" "New remote")
(core/gain state :corp :bad-publicity 9)
(core/gain state :corp :credit 8)
(core/gain state :corp :click 15)
(let [napd (get-content state :remote1 0)
beale (get-content state :remote2 0)]
(dotimes [_ 13] (core/advance state :corp {:card (refresh napd)}))
(is (= 13 (:advance-counter (refresh napd))))
(core/score state :corp {:card (refresh napd)})
(is (= 2 (:agenda-point (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-corp))))))
(prompt-select :corp (refresh beale))
(is (= 13 (:advance-counter (refresh beale))))
(core/score state :corp {:card (refresh beale)})
(is (= 7 (:agenda-point (get-corp)))))))
(deftest success-public-agenda
;; Success - Works with public agendas
(do-game
(new-game (default-corp [(qty "Oaktown Renovation" 1) (qty "Vanity Project" 1) (qty "Success" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "Vanity Project" (:hand (get-corp))))
(is (= 4 (:agenda-point (get-corp))))
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp))
(is (= "Vanity Project" (:title (first (:rfg (get-corp))))))
(let [oaktown (get-content state :remote1 0)]
(prompt-select :corp (refresh oaktown))
(is (= 6 (:advance-counter (refresh oaktown))))
(is (= 19 (:credit (get-corp))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :corp {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-corp)))))))
(deftest success-jemison
;; Success interaction with Jemison, regression test for issue #2704
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifice. Audacity. Success."
[(qty "Success" 1)
(qty "High-Risk Investment" 1)
(qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "High-Risk Investment" (:hand (get-corp))))
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "Success")
(prompt-select :corp (get-in (get-corp) [:scored 0]))
(let [gto (get-content state :remote1 0)]
;; Prompt for Jemison
(prompt-select :corp (refresh gto))
(is (= 4 (:advance-counter (refresh gto))) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :corp (refresh gto))
(is (= (+ 4 5) (:advance-counter (refresh gto))) "Advance 5 times from Success"))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest the-all-seeing-i-prevent-trash
;; Counts number of cards if one card is prevented trashed with fall guy
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 1) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Fall Guy")
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (count (:hand (get-corp)))) "Corp could not play All Seeing I when runner was not tagged")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "The All-Seeing I")
(let [fall-guy (get-resource state 1)]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done")
(is (= 1 (res)) "One installed resource saved by Fall Guy")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap"))))
(deftest the-all-seeing-i-hosted-cards
;; Checks that All-seeing I does not double-trash hosted cards, trashes hosted cards
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 2) (qty "Off-Campus Apartment" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Off-Campus Apartment")
(let [oca (get-resource state 0)
fg1 (get-in (get-runner) [:hand 0])
fg2 (get-in (get-runner) [:hand 1])]
(card-ability state :runner oca 0)
(prompt-select :runner fg1)
(card-ability state :runner oca 0)
(prompt-select :runner fg2))
(core/gain state :runner :tag 1)
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(prompt-choice :runner "Done")
(prompt-choice :runner "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-installed state :runner))]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done") ;; This assumes hosted cards get put in trash-list before host
(is (= 1 (count (core/all-active-installed state :runner))) "One installed card (Off-Campus)")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap")
)
)
(deftest the-all-seeing-i-jarogniew-mercs
;; The All-Seeing I should not trash Jarogniew Mercs if there are other installed resources
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 4)])
(default-runner [(qty "Jarogniew Mercs" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Jarogniew Mercs")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources")
(take-credits state :corp)
(play-from-hand state :runner "Jarogniew Mercs") ;; Testing if order matters
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources"))))
(deftest threat-assessment
;; Threat Assessment - play only if runner trashed a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-corp [(qty "Threat Assessment" 3) (qty "Adonis Campaign" 1)])
(default-runner [(qty "Desperado" 1) (qty "Corroder" 1)]))
(play-from-hand state :corp "Adonis Campaign" "New remote")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Yes") ;trash
(core/gain state :runner :credit 5)
(play-from-hand state :runner "Desperado")
(play-from-hand state :runner "Corroder")
(take-credits state :runner)
(is (= 0 (:tag (get-runner))) "Runner starts with 0 tags")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Desperado" (-> (get-runner) :rig :hardware)))
(prompt-choice :runner "2 tags")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags")
(is (= 1 (count (-> (get-runner) :rig :hardware))) "Didn't trash Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-corp))))) "Threat Assessment removed from game")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Corroder" (-> (get-runner) :rig :program)))
(prompt-choice :runner "Move Corroder")
(is (= 2 (:tag (get-runner))) "Runner didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-runner))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-corp)))))
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Threat Assessment")
(is (empty? (:prompt (get-corp))) "Threat Assessment triggered with no trash")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Runner tags; or 1 tag if 0
(do-game
(new-game (default-corp [(qty "Threat Level Alpha" 2)])
(default-runner))
(core/gain state :corp :click 2)
(core/gain state :corp :credit 2)
(is (= 0 (:tag (get-runner))))
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag because they had 0")
(core/gain state :runner :tag 2)
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 6 (:tag (get-runner))) "Runner took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-corp [(qty "Transparency Initiative" 1) (qty "Oaktown Renovation" 1)
(qty "Project Atlas" 1) (qty "Hostile Takeover" 1) (qty "Casting Call" 1)])
(default-runner))
(core/gain state :corp :click 5)
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Project Atlas" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(let [oaktown (get-content state :remote1 0)
atlas (get-content state :remote2 0)
hostile (get-content state :remote3 0)]
(play-from-hand state :corp "Transparency Initiative")
(prompt-select :corp (refresh oaktown))
;; doesn't work on face-up agendas
(is (= 0 (count (:hosted (refresh oaktown)))))
(prompt-select :corp (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :corp (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-corp))))
(core/advance state :corp {:card (refresh hostile)})
(is (= 5 (:credit (get-corp))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :corp {:card (refresh oaktown)})
(is (= 6 (:credit (get-corp))) "Transparency initiative didn't fire")
(core/advance state :corp {:card (refresh atlas)})
(is (= 5 (:credit (get-corp))) "Transparency initiative didn't fire"))))
(deftest wake-up-call-en-passant
;; Wake Up Call - should fire after using En Passant to trash ice
(do-game
(new-game (default-corp [(qty "Enigma" 1) (qty "Wake Up Call" 1)])
(default-runner [(qty "En Passant" 1) (qty "Maya" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "Ok")
(is (= 0 (count (:discard (get-corp)))) "Corp starts with no discards")
(play-from-hand state :runner "En Passant")
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (count (:discard (get-corp)))) "Corp trashes installed ice")
(take-credits state :runner)
(is (= 1 (count (:discard (get-runner)))) "Runner starts with 1 trashed card (En Passant)")
(play-from-hand state :corp "Wake Up Call")
(prompt-select :corp (get-in @state [:runner :rig :hardware 0]))
(prompt-choice :runner "Trash Maya")
(is (= 2 (count (:discard (get-runner)))) "Maya is trashed")
(is (= 1 (count (:rfg (get-corp)))) "Wake Up Call is removed from the game")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid ICE and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(core/gain state :corp :credit 20)
(core/gain state :corp :click 10)
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:corp :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
|
25321
|
(ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards)
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest accelerated-diagnostics-with-current
;; Accelerated Diagnostics - Interaction with Current
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1)
(qty "Enhanced Login Protocol" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 3)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:corp :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund"))))
(deftest an-offer-you-cant-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-corp [(qty "Celebrity Gift" 1) (qty "An Offer You Can't Refuse" 1)])
(default-runner))
(play-from-hand state :corp "An Offer You Can't Refuse")
(prompt-choice :corp "R&D")
(core/move state :corp (find-card "Celebrity Gift" (:hand (get-corp))) :discard)
(is (= 2 (count (:discard (get-corp)))))
(prompt-choice :runner "No")
(is (= 1 (:agenda-point (get-corp))) "An Offer the Runner refused")
(is (= 1 (count (:scored (get-corp)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-corp))))
(is (= 1 (count (:discard (get-corp)))))
(is (find-card "Celebrity Gift" (:discard (get-corp))))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "Hunter" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "<NAME>" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast-runner-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 1)])
(default-runner))
(play-from-hand state :corp "Cerebral Cast")
(is (= 3 (:click (get-corp))) "Cerebral Cast precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (= 0 (count (:discard (get-runner)))) "Runner took no damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags")))
(deftest cerebral-cast-corp-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 2)])
(default-runner))
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 brain damage")
(is (= 1 (count (:discard (get-runner)))) "Runner took a brain damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags from brain damage choice")
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 tag")
(is (= 1 (count (:discard (get-runner)))) "Runner took no additional damage")
(is (= 1 (:tag (get-runner))) "Runner took a tag from Cerebral Cast choice")))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest commercialization-single-advancement
;; Commercialization - Single advancement token
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 1)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 6 (:credit (get-corp))) "Gained 1 for single advanced ice from Commercialization")))
(deftest commercialization-double-advancement
;; Commercialization - Two advancement tokens
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 2)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 7 (:credit (get-corp))) "Gained 2 for double advanced ice from Commercialization")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on runner install, runner trash installed card
;; Also regression test for #3160
(do-game
(new-game (default-corp [(qty "Death and Taxes" 1) (qty "PAD Campaign" 1)])
(default-runner [(qty "Aumakua" 1) (qty "DaVinci" 1) (qty "Fall Guy" 1)]))
(play-from-hand state :corp "Death and Taxes")
(is (= (- 5 2) (:credit (get-corp))) "Corp paid 2 to play Death and Taxes")
(play-from-hand state :corp "PAD Campaign" "New remote")
(take-credits state :corp)
(let [corp-creds (:credit (get-corp))]
(trash-from-hand state :runner "DaVinci")
(is (= corp-creds (:credit (get-corp))) "Corp did not gain credit when runner trashes / discards from hand")
(play-from-hand state :runner "Aumakua")
(is (= (+ 1 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Aumakua")
(play-from-hand state :runner "Fall Guy")
(is (= (+ 2 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Fall Guy")
(card-ability state :runner (get-resource state 0) 1)
(is (= (+ 3 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed Fall Guy")
(run-empty-server state :remote1)
(prompt-choice :runner "Yes") ;; Runner trashes PAD Campaign
(is (= (+ 4 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-corp [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-runner))
(starting-hand state :corp ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-select :corp (first (next (:hand (get-corp)))))
(prompt-select :corp (first (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 1 (count (:discard (get-corp)))) "1 card still discarded")
(is (= 1 (count (:deck (get-corp)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-runner))) "Runner gained 2 credits")
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-choice :corp "Done")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (first (next (:discard (get-corp)))))
(is (= 0 (count (:discard (get-corp)))) "No cards left in archives")
(is (= 3 (count (:deck (get-corp)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-runner))) "Runner gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the runner lose 4 credits if able
(do-game
(new-game (default-corp [(qty "Economic Warfare" 3)])
(default-runner))
(play-from-hand state :corp "Economic Warfare")
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(is (= 3 (count (:hand (get-corp)))) "Corp still has 3 cards")
(take-credits state :corp)
(run-on state :archives)
(run-successful state)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 4 (:credit (get-runner))) "Runner has 4 credits")
(play-from-hand state :corp "Economic Warfare")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :corp)
(run-on state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 3 (:credit (get-runner))) "Runner has 3 credits")))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to trash installed card not of Runner's faction
(do-game
(new-game (default-corp [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Inti" 1) (qty "Caldera" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Inti")
(play-from-hand state :runner "Caldera")
(take-credits state :runner)
(play-from-hand state :corp "Enforcing Loyalty")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-program state 0))
(is (empty? (:discard (get-runner))) "Can't target Inti; matches Runner faction")
(prompt-select :corp (get-resource state 0))
(is (= 1 (count (:discard (get-runner)))) "Caldera trashed")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-new-angeles-sol
;; Enhanced Login Protocol trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Enhanced Login Protocol" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:discard (get-corp))))
(run-on state :archives)
(is (= 1 (:click (get-runner))) "Runner has 1 click")))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest hatchet-job
;; Hatchet Job - Win trace to add installed non-virtual to grip
(do-game
(new-game (default-corp [(qty "Hatchet Job" 1)])
(default-runner [(qty "Upya" 1) (qty "Ghost Runner" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Ghost Runner")
(play-from-hand state :runner "Upya")
(take-credits state :runner)
(play-from-hand state :corp "Hatchet Job")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(is (empty? (:hand (get-runner))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-corp)))))
(prompt-select :corp (get-program state 0))
(is (= 1 (count (:hand (get-runner)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest high-profile-target
(testing "when the runner has no tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(testing "when the runner has one tag"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (count (:hand (get-runner)))) "Runner has 3 cards in hand")))
(testing "when the runner has two tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 2)
(play-from-hand state :corp "High-Profile Target")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(testing "when the runner has enough tags to die"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest high-profile-target-flatline
;; High-Profile Target - three tags, gg
(do-game
(new-game (default-corp [(qty "High-Profile Target" 10)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "<NAME>. <NAME>" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "<NAME>. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest ipo-terminal
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-corp [(qty "IPO" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "IPO")
(is (= 13 (:credit (get-corp))))
(is (= 0 (:click (get-corp))) "Terminal ends turns")))
(deftest lag-time
(do-game
(new-game (default-corp [(qty "Lag Time" 1) (qty "Vanilla" 1) (qty "Lotus Field" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Vanilla" "HQ")
(play-from-hand state :corp "Lotus Field" "R&D")
(play-from-hand state :corp "Lag Time")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(is (= 1 (:current-strength (get-ice state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-ice state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "when the runner is not tagged"
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(play-from-hand state :corp "Market Forces")
(is (= 6 (count (:hand (get-corp))))
"Market Forces is not played")
(is (= 3 (:click (get-corp)))
"the corp does not spend a click")
(is (= 5 (:credit (get-corp)) (:credit (get-runner)))
"credits are unaffected")))
(letfn [(market-forces-credit-test
[{:keys [tag-count runner-creds expected-credit-diff]}]
(testing (str "when the runner has " tag-count " tags and " runner-creds " credits")
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(swap! state assoc-in [:corp :credit] 0)
(swap! state assoc-in [:runner :credit] runner-creds)
(core/gain state :runner :tag tag-count)
(play-from-hand state :corp "Market Forces")
(is (= expected-credit-diff (:credit (get-corp)))
(str "the corp gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- runner-creds (:credit (get-runner))))
(str "the runner loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:runner-creds 10
:expected-credit-diff 3}
{:tag-count 2
:runner-creds 10
:expected-credit-diff 6}
{:tag-count 3
:runner-creds 10
:expected-credit-diff 9}
{:tag-count 3
:runner-creds 0
:expected-credit-diff 0}
{:tag-count 3
:runner-creds 5
:expected-credit-diff 5}]))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-corp [(qty "Mass Commercialization" 1)
(qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :runner)
(core/advance state :corp {:card (refresh (get-ice state :hq 0))})
(core/advance state :corp {:card (refresh (get-ice state :archives 0))})
(core/advance state :corp {:card (refresh (get-ice state :rd 0))})
(take-credits state :runner)
(play-from-hand state :corp "Mass Commercialization")
(is (= 8 (:credit (get-corp))) "Gained 6 for 3 advanced ice from Mass Commercialization")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; <NAME> - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "M<NAME>in" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "<NAME>")
(prompt-select :corp (find-card "<NAME>" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "Ronin did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "<NAME>")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "Jackson Howard" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "<NAME>" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "<NAME>" (:title (second (rest (:deck (get-corp)))))))
(is (= "<NAME>" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, install an Asset, Agenda, or Upgrade in a Remote Server
(do-game
(new-game (default-corp [(qty "Psychokinesis" 3) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Psychokinesis","Psychokinesis","Psychokinesis"])
;; Test installing an Upgrade
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "<NAME>" (:title (get-content state :remote1 0)))
"<NAME> N<NAME>i installed by Psychokinesis")
;; Test installing an Asset
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Adonis Campaign" (:title (get-content state :remote2 0)))
"Adonis Campaign installed by Psychokinesis")
;; Test installing an Agenda
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Global Food Initiative" (:title (get-content state :remote3 0)))
"Global Food Initiative installed by Psychokinesis")
;; Test selecting "None"
(core/gain state :corp :click 1)
(core/move state :corp (find-card "Psychokinesis" (:discard (get-corp))) :hand)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp "None")
(is (= nil (:title (get-content state :remote4 0)))
"Nothing is installed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-corp [(qty "Red Planet Couriers" 1) (qty "Ice Wall" 2)
(qty "GRNDL Refinery" 1) (qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 4)
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "GRNDL Refinery" "New remote")
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(let [gt (get-content state :remote1 0)
gr (get-content state :remote2 0)
iw1 (get-ice state :hq 0)
iw2 (get-ice state :rd 0)]
(core/add-prop state :corp gr :advance-counter 3)
(core/add-prop state :corp iw1 :advance-counter 2)
(core/add-prop state :corp iw2 :advance-counter 1)
(play-from-hand state :corp "Red Planet Couriers")
(prompt-select :corp gt)
(is (nil? (:advance-counter (refresh gr))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw1))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw2))) "Advancements removed")
(is (= 6 (:advance-counter (refresh gt))) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and trash 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-corp [(qty "Reverse Infection" 2)])
(default-runner [(qty "Virus Breeding Ground" 1) (qty "Datasucker" 1) (qty "Sure Gamble" 3)]))
(starting-hand state :runner ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Gain 2 [Credits]")
(is (= 7 (:credit (get-corp))) "Corp gained 2 credits")
(take-credits state :corp)
(play-from-hand state :runner "Virus Breeding Ground")
(play-from-hand state :runner "Datasucker")
(take-credits state :runner)
(core/add-counter state :runner (get-resource state 0) :virus 4)
(core/add-counter state :runner (get-program state 0) :virus 3)
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Purge virus counters.")
(is (= 9 (:credit (get-corp))) "Corp did not gain credits")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-program state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-runner)))) "Two cards trashed from stack")))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Runner event of turn
(do-game
(new-game (default-corp [(qty "Rolling Brownout" 1) (qty "Beanstalk Royalties" 1)
(qty "Domestic Sleepers" 1)])
(default-runner [(qty "Easy Mark" 3)]))
(play-from-hand state :corp "Rolling Brownout")
(play-from-hand state :corp "Beanstalk Royalties")
(is (= 5 (:credit (get-corp))) "Beanstalk netted only 2c")
(play-from-hand state :corp "Domestic Sleepers" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Easy Mark")
(is (= 7 (:credit (get-runner))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-corp))) "Corp gained 1c from Brownout")
(play-from-hand state :runner "Easy Mark")
(is (= 6 (:credit (get-corp))) "No Corp credit gain from 2nd event")
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(play-from-hand state :runner "Easy Mark")
(is (= 12 (:credit (get-runner))) "Easy Mark netted 3c after Brownout trashed")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 10)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest self-growth-program
;; Self-Growth Program - Add 2 installed cards to grip if runner is tagged
(do-game
(new-game (default-corp [(qty "Self-Growth Program" 1)])
(default-runner [(qty "Clone Chip" 1) (qty "Inti" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Clone Chip")
(play-from-hand state :runner "Inti")
(take-credits state :runner)
(play-from-hand state :corp "Self-Growth Program")
(is (= 3 (:click (get-corp))) "Self-Growth Program precondition not met; card not played")
(core/gain state :runner :tag 1)
(is (= 0 (count (:hand (get-runner)))) "Runner hand is empty")
(let [inti (get-in @state [:runner :rig :program 0])
cc (get-in @state [:runner :rig :hardware 0])]
(play-from-hand state :corp "Self-Growth Program")
(prompt-select :corp inti)
(prompt-select :corp cc))
(is (= 2 (count (:hand (get-runner)))) "2 cards returned to hand")
(is (= 0 (count (get-in @state [:runner :rig :program]))) "No programs installed")
(is (= 0 (count (get-in @state [:runner :rig :hardware]))) "No hardware installed")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "H<NAME> Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest service-outage-new-angeles-sol
;; Service Outage trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage"
(:discard (get-corp))))
(take-credits state :runner)
(take-credits state :corp)
(is (= 7 (:credit (get-runner))) "Runner has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-runner)))
"Runner spends 1 credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ICE Barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary ICE Barrier"))))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with Jackson
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "<NAME>" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "<NAME>" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest success-bad-publicity
;; Success - Works with bad publicity
(do-game
(new-game (default-corp [(qty "NAPD Contract" 1) (qty "Project Beale" 1) (qty "Success" 1)])
(default-runner))
(play-from-hand state :corp "NAPD Contract" "New remote")
(play-from-hand state :corp "Project Beale" "New remote")
(core/gain state :corp :bad-publicity 9)
(core/gain state :corp :credit 8)
(core/gain state :corp :click 15)
(let [napd (get-content state :remote1 0)
beale (get-content state :remote2 0)]
(dotimes [_ 13] (core/advance state :corp {:card (refresh napd)}))
(is (= 13 (:advance-counter (refresh napd))))
(core/score state :corp {:card (refresh napd)})
(is (= 2 (:agenda-point (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-corp))))))
(prompt-select :corp (refresh beale))
(is (= 13 (:advance-counter (refresh beale))))
(core/score state :corp {:card (refresh beale)})
(is (= 7 (:agenda-point (get-corp)))))))
(deftest success-public-agenda
;; Success - Works with public agendas
(do-game
(new-game (default-corp [(qty "Oaktown Renovation" 1) (qty "Vanity Project" 1) (qty "Success" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "Vanity Project" (:hand (get-corp))))
(is (= 4 (:agenda-point (get-corp))))
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp))
(is (= "Vanity Project" (:title (first (:rfg (get-corp))))))
(let [oaktown (get-content state :remote1 0)]
(prompt-select :corp (refresh oaktown))
(is (= 6 (:advance-counter (refresh oaktown))))
(is (= 19 (:credit (get-corp))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :corp {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-corp)))))))
(deftest success-jemison
;; Success interaction with Jemison, regression test for issue #2704
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifice. Audacity. Success."
[(qty "Success" 1)
(qty "High-Risk Investment" 1)
(qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "High-Risk Investment" (:hand (get-corp))))
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "Success")
(prompt-select :corp (get-in (get-corp) [:scored 0]))
(let [gto (get-content state :remote1 0)]
;; Prompt for Jemison
(prompt-select :corp (refresh gto))
(is (= 4 (:advance-counter (refresh gto))) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :corp (refresh gto))
(is (= (+ 4 5) (:advance-counter (refresh gto))) "Advance 5 times from Success"))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest the-all-seeing-i-prevent-trash
;; Counts number of cards if one card is prevented trashed with fall guy
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 1) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Fall Guy")
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (count (:hand (get-corp)))) "Corp could not play All Seeing I when runner was not tagged")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "The All-Seeing I")
(let [fall-guy (get-resource state 1)]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done")
(is (= 1 (res)) "One installed resource saved by Fall Guy")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap"))))
(deftest the-all-seeing-i-hosted-cards
;; Checks that All-seeing I does not double-trash hosted cards, trashes hosted cards
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 2) (qty "Off-Campus Apartment" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Off-Campus Apartment")
(let [oca (get-resource state 0)
fg1 (get-in (get-runner) [:hand 0])
fg2 (get-in (get-runner) [:hand 1])]
(card-ability state :runner oca 0)
(prompt-select :runner fg1)
(card-ability state :runner oca 0)
(prompt-select :runner fg2))
(core/gain state :runner :tag 1)
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(prompt-choice :runner "Done")
(prompt-choice :runner "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-installed state :runner))]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done") ;; This assumes hosted cards get put in trash-list before host
(is (= 1 (count (core/all-active-installed state :runner))) "One installed card (Off-Campus)")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap")
)
)
(deftest the-all-seeing-i-jarogniew-mercs
;; The All-Seeing I should not trash Jarogniew Mercs if there are other installed resources
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 4)])
(default-runner [(qty "Jarogniew Mercs" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Jarogniew <NAME>")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources")
(take-credits state :corp)
(play-from-hand state :runner "Jarogniew Mercs") ;; Testing if order matters
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources"))))
(deftest threat-assessment
;; Threat Assessment - play only if runner trashed a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-corp [(qty "Threat Assessment" 3) (qty "Adonis Campaign" 1)])
(default-runner [(qty "Desperado" 1) (qty "Corroder" 1)]))
(play-from-hand state :corp "Adonis Campaign" "New remote")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Yes") ;trash
(core/gain state :runner :credit 5)
(play-from-hand state :runner "Desperado")
(play-from-hand state :runner "Corroder")
(take-credits state :runner)
(is (= 0 (:tag (get-runner))) "Runner starts with 0 tags")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Desperado" (-> (get-runner) :rig :hardware)))
(prompt-choice :runner "2 tags")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags")
(is (= 1 (count (-> (get-runner) :rig :hardware))) "Didn't trash Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-corp))))) "Threat Assessment removed from game")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Corroder" (-> (get-runner) :rig :program)))
(prompt-choice :runner "Move Corroder")
(is (= 2 (:tag (get-runner))) "Runner didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-runner))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-corp)))))
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Threat Assessment")
(is (empty? (:prompt (get-corp))) "Threat Assessment triggered with no trash")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Runner tags; or 1 tag if 0
(do-game
(new-game (default-corp [(qty "Threat Level Alpha" 2)])
(default-runner))
(core/gain state :corp :click 2)
(core/gain state :corp :credit 2)
(is (= 0 (:tag (get-runner))))
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag because they had 0")
(core/gain state :runner :tag 2)
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 6 (:tag (get-runner))) "Runner took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-corp [(qty "Transparency Initiative" 1) (qty "Oaktown Renovation" 1)
(qty "Project Atlas" 1) (qty "Hostile Takeover" 1) (qty "Casting Call" 1)])
(default-runner))
(core/gain state :corp :click 5)
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Project Atlas" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(let [oaktown (get-content state :remote1 0)
atlas (get-content state :remote2 0)
hostile (get-content state :remote3 0)]
(play-from-hand state :corp "Transparency Initiative")
(prompt-select :corp (refresh oaktown))
;; doesn't work on face-up agendas
(is (= 0 (count (:hosted (refresh oaktown)))))
(prompt-select :corp (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :corp (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-corp))))
(core/advance state :corp {:card (refresh hostile)})
(is (= 5 (:credit (get-corp))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :corp {:card (refresh oaktown)})
(is (= 6 (:credit (get-corp))) "Transparency initiative didn't fire")
(core/advance state :corp {:card (refresh atlas)})
(is (= 5 (:credit (get-corp))) "Transparency initiative didn't fire"))))
(deftest wake-up-call-en-passant
;; Wake Up Call - should fire after using En Passant to trash ice
(do-game
(new-game (default-corp [(qty "Enigma" 1) (qty "Wake Up Call" 1)])
(default-runner [(qty "En Passant" 1) (qty "Maya" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "Ok")
(is (= 0 (count (:discard (get-corp)))) "Corp starts with no discards")
(play-from-hand state :runner "En Passant")
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (count (:discard (get-corp)))) "Corp trashes installed ice")
(take-credits state :runner)
(is (= 1 (count (:discard (get-runner)))) "Runner starts with 1 trashed card (En Passant)")
(play-from-hand state :corp "Wake Up Call")
(prompt-select :corp (get-in @state [:runner :rig :hardware 0]))
(prompt-choice :runner "Trash Maya")
(is (= 2 (count (:discard (get-runner)))) "Maya is trashed")
(is (= 1 (count (:rfg (get-corp)))) "Wake Up Call is removed from the game")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid ICE and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(core/gain state :corp :credit 20)
(core/gain state :corp :click 10)
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:corp :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
| true |
(ns game-test.cards.operations
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards)
(deftest twenty-four-seven-news-cycle-breaking-news
;; 24/7 News Cycle - Breaking News interaction
(do-game
(new-game (default-corp [(qty "Breaking News" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Breaking News" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(score-agenda state :corp ag2)
(take-credits state :corp)
(is (= 0 (:tag (get-runner)))) ; tags cleared
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Breaking News")
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner given 2 tags")
(take-credits state :corp 2)
(is (= 2 (:tag (get-runner))) "Tags remained after Corp ended turn"))))
(deftest twenty-four-seven-news-cycle-posted-bounty
;; 24/7 News Cycle and Posted Bounty interaction -- Issue #1043
(do-game
(new-game (default-corp [(qty "Posted Bounty" 2) (qty "24/7 News Cycle" 3)])
(default-runner))
(play-from-hand state :corp "Posted Bounty" "New remote")
(play-from-hand state :corp "Posted Bounty" "New remote")
(let [ag1 (get-content state :remote1 0)
ag2 (get-content state :remote2 0)]
(score-agenda state :corp ag1)
(prompt-choice :corp "No")
(score-agenda state :corp ag2)
(prompt-choice :corp "No")
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))) "Forfeited Posted Bounty")
(prompt-select :corp (find-card "Posted Bounty" (:scored (get-corp))))
(prompt-choice :corp "Yes") ; "Forfeit Posted Bounty to give 1 tag?"
(is (= 1 (:tag (get-runner))) "Runner given 1 tag")
(is (= 1 (:bad-publicity (get-corp))) "Corp has 1 bad publicity")
(is (= 0 (:agenda-point (get-corp))) "Forfeited Posted Bounty to 24/7 News Cycle"))))
(deftest twenty-four-seven-news-cycle-swaps
;; 24/7 News Cycle - Swapped agendas are able to be used. #1555
(do-game
(new-game (default-corp [(qty "24/7 News Cycle" 1) (qty "Chronos Project" 1)
(qty "Philotic Entanglement" 1) (qty "Profiteering" 1)])
(default-runner [(qty "Turntable" 3)]))
(score-agenda state :corp (find-card "Chronos Project" (:hand (get-corp))))
(score-agenda state :corp (find-card "Philotic Entanglement" (:hand (get-corp))))
(take-credits state :corp)
(play-from-hand state :runner "Turntable")
(core/steal state :runner (find-card "Profiteering" (:hand (get-corp))))
(prompt-choice :runner "Yes")
(prompt-select :runner (find-card "Philotic Entanglement" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(take-credits state :runner)
(play-from-hand state :corp "24/7 News Cycle")
(prompt-select :corp (find-card "Chronos Project" (:scored (get-corp))))
(is (= "Chronos Project" (:title (first (:rfg (get-corp))))))
;; shouldn't work on an agenda in the Runner's scored area
(is (= 2 (count (:hand (get-runner)))))
(prompt-select :corp (find-card "Philotic Entanglement" (:scored (get-runner))))
(is (= 2 (count (:hand (get-runner)))))
;; resolve 'when scored' ability on swapped Profiteering
(is (= 8 (:credit (get-corp))))
(prompt-select :corp (find-card "Profiteering" (:scored (get-corp))))
(prompt-choice :corp "3")
(is (= 1 (:agenda-point (get-corp))))
(is (= 3 (:bad-publicity (get-corp))))
(is (= 23 (:credit (get-corp))) "Gained 15 credits")))
(deftest accelerated-diagnostics
;; Accelerated Diagnostics - Interaction with prompt effects, like Shipment from SanSan
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1) (qty "Back Channels" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
bc (find-card "Back Channels" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund")
(prompt-select :corp bc)
(prompt-select :corp (refresh co))
(is (= 15 (:credit (get-corp))) "Corp gained 6 credits for Back Channels"))))
(deftest accelerated-diagnostics-with-current
;; Accelerated Diagnostics - Interaction with Current
(do-game
(new-game (default-corp [(qty "Accelerated Diagnostics" 1) (qty "Cerebral Overwriter" 1)
(qty "Enhanced Login Protocol" 1) (qty "Shipment from SanSan" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(starting-hand state :corp ["Accelerated Diagnostics" "Cerebral Overwriter"])
(play-from-hand state :corp "Cerebral Overwriter" "New remote")
(core/gain state :corp :credit 3)
(play-from-hand state :corp "Accelerated Diagnostics")
(let [playarea (get-in @state [:corp :play-area])
hf (find-card "Hedge Fund" playarea)
ss (find-card "Shipment from SanSan" playarea)
elp (find-card "Enhanced Login Protocol" playarea)
co (get-content state :remote1 0)]
(is (= 3 (count playarea)) "3 cards in play area")
(prompt-select :corp elp)
(is (= "Enhanced Login Protocol" (:title (first (get-in @state [:corp :current]))))
"Enhanced Login Protocol active in Current area")
(prompt-select :corp ss)
(prompt-choice :corp "2")
(prompt-select :corp co)
(is (= 2 (:advance-counter (refresh co))) "Cerebral Overwriter gained 2 advancements")
(prompt-select :corp hf)
(is (= 9 (:credit (get-corp))) "Corp gained credits from Hedge Fund"))))
(deftest an-offer-you-cant-refuse
;; An Offer You Can't Refuse - exact card added to score area, not the last discarded one
(do-game
(new-game (default-corp [(qty "Celebrity Gift" 1) (qty "An Offer You Can't Refuse" 1)])
(default-runner))
(play-from-hand state :corp "An Offer You Can't Refuse")
(prompt-choice :corp "R&D")
(core/move state :corp (find-card "Celebrity Gift" (:hand (get-corp))) :discard)
(is (= 2 (count (:discard (get-corp)))))
(prompt-choice :runner "No")
(is (= 1 (:agenda-point (get-corp))) "An Offer the Runner refused")
(is (= 1 (count (:scored (get-corp)))))
(is (find-card "An Offer You Can't Refuse" (:scored (get-corp))))
(is (= 1 (count (:discard (get-corp)))))
(is (find-card "Celebrity Gift" (:discard (get-corp))))))
(deftest big-brother
;; Big Brother - Give the Runner 2 tags if already tagged
(do-game
(new-game (default-corp [(qty "Big Brother" 1)])
(default-runner))
(play-from-hand state :corp "Big Brother")
(is (= 1 (count (:hand (get-corp)))) "Card not played because Runner has no tags")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Big Brother")
(is (= 3 (:tag (get-runner))) "Runner gained 2 tags")))
(deftest biotic-labor
;; Biotic Labor - Gain 2 clicks
(do-game
(new-game (default-corp [(qty "Biotic Labor" 1)])
(default-runner))
(play-from-hand state :corp "Biotic Labor")
(is (= 1 (:credit (get-corp))))
(is (= 4 (:click (get-corp))) "Spent 1 click to gain 2 additional clicks")))
(deftest blue-level-clearance
;; Blue Level Clearance - Gain 5 credits and draw 2 cards
(do-game
(new-game (default-corp [(qty "Blue Level Clearance" 3)
(qty "Hedge Fund" 3)
(qty "Sweeps Week" 2)])
(default-runner))
(play-from-hand state :corp "Blue Level Clearance")
(is (= 8 (:credit (get-corp))) "Gained 5 credits")
(is (= 1 (:click (get-corp))))
(is (= 7 (count (:hand (get-corp)))) "Drew 2 cards")))
(deftest casting-call
;; Casting Call - Only do card-init on the Public agendas. Issue #1128
(do-game
(new-game (default-corp [(qty "Casting Call" 2) (qty "Oaktown Renovation" 1)
(qty "Improved Tracers" 1) (qty "Hunter" 1)])
(default-runner))
(core/gain state :corp :click 1)
(play-from-hand state :corp "Hunter" "HQ")
(let [hunter (get-ice state :hq 0)]
(core/rez state :corp hunter)
(is (= 4 (:current-strength (refresh hunter))))
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Improved Tracers" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [imptrac (get-content state :remote1 0)]
(is (get-in (refresh imptrac) [:rezzed]) "Improved Tracers is faceup")
(is (= 4 (:current-strength (refresh hunter))) "Hunter hasn't gained strength")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "PI:NAME:<NAME>END_PI" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(let [oak (get-content state :remote2 0)]
(core/advance state :corp {:card (refresh oak)})
(is (= 5 (:credit (get-corp))) "Events on Public agenda work; gained 2 credits from advancing")
(take-credits state :corp)
(run-empty-server state "Server 2")
(prompt-select :runner oak)
(prompt-choice :runner "Steal")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags from accessing agenda with Casting Call hosted on it"))))))
(deftest cerebral-cast-runner-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 1)])
(default-runner))
(play-from-hand state :corp "Cerebral Cast")
(is (= 3 (:click (get-corp))) "Cerebral Cast precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (= 0 (count (:discard (get-runner)))) "Runner took no damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags")))
(deftest cerebral-cast-corp-wins
;; Cerebral Cast: if the runner succefully ran last turn, psi game to give runner choice of tag or BD
(do-game
(new-game (default-corp [(qty "Cerebral Cast" 2)])
(default-runner))
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 brain damage")
(is (= 1 (count (:discard (get-runner)))) "Runner took a brain damage")
(is (= 0 (:tag (get-runner))) "Runner took no tags from brain damage choice")
(play-from-hand state :corp "Cerebral Cast")
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :runner "1 tag")
(is (= 1 (count (:discard (get-runner)))) "Runner took no additional damage")
(is (= 1 (:tag (get-runner))) "Runner took a tag from Cerebral Cast choice")))
(deftest cerebral-static-chaos-theory
;; Cerebral Static - vs Chaos Theory
(do-game
(new-game (default-corp [(qty "Cerebral Static" 1) (qty "Lag Time" 1)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Sure Gamble" 3)]))
(is (= 5 (:memory (get-runner))) "CT starts with 5 memory")
(play-from-hand state :corp "Cerebral Static")
(is (= 4 (:memory (get-runner))) "Cerebral Static causes CT to have 4 memory")
(play-from-hand state :corp "Lag Time")
(is (= 5 (:memory (get-runner))) "CT 5 memory restored")))
(deftest closed-accounts
;; Closed Accounts - Play if Runner is tagged to make Runner lose all credits
(do-game
(new-game (default-corp [(qty "Closed Accounts" 1)])
(default-runner))
(play-from-hand state :corp "Closed Accounts")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Closed Accounts precondition not met; card not played")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Closed Accounts")
(is (= 0 (:credit (get-runner))) "Runner lost all credits")))
(deftest commercialization-single-advancement
;; Commercialization - Single advancement token
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 1)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 6 (:credit (get-corp))) "Gained 1 for single advanced ice from Commercialization")))
(deftest commercialization-double-advancement
;; Commercialization - Two advancement tokens
(do-game
(new-game (default-corp [(qty "Commercialization" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(core/add-counter state :corp (refresh (get-ice state :hq 0)) :advancement 2)
(play-from-hand state :corp "Commercialization")
(prompt-select :corp (refresh (get-ice state :hq 0)))
(is (= 7 (:credit (get-corp))) "Gained 2 for double advanced ice from Commercialization")))
(deftest consulting-visit
;; Consulting Visit - Only show single copies of operations corp can afford as choices. Play chosen operation
(do-game
(new-game (default-corp [(qty "Consulting Visit" 1)
(qty "Beanstalk Royalties" 2)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Consulting Visit"])
(play-from-hand state :corp "Consulting Visit")
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Beanstalk Royalties" (:deck (get-corp))))
(is (= 6 (:credit (get-corp)))))))
(deftest consulting-visit-mumbad
;; Consulting Visit - Works properly when played with Mumbad City Hall
(do-game
(new-game (default-corp [(qty "Mumbad City Hall" 1)
(qty "Beanstalk Royalties" 1)
(qty "Green Level Clearance" 1)
(qty "Breaking News" 1)
(qty "Hedge Fund" 1)
(qty "Consulting Visit" 1)
(qty "Mumba Temple" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(starting-hand state :corp ["Mumbad City Hall"])
(play-from-hand state :corp "Mumbad City Hall" "New remote")
(let [hall (get-content state :remote1 0)
get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(card-ability state :corp hall 0)
(is (= (list "Consulting Visit" "Mumba Temple" nil) (prompt-names)))
(prompt-choice :corp (find-card "Consulting Visit" (:deck (get-corp))))
(is (= 3 (:credit (get-corp))))
(is (= (list "Beanstalk Royalties" "Green Level Clearance" nil) (prompt-names)))
(prompt-choice :corp (find-card "Green Level Clearance" (:deck (get-corp))))
(is (= 5 (:credit (get-corp)))))))
(deftest death-and-taxes
;; Death and Taxes gain credit on runner install, runner trash installed card
;; Also regression test for #3160
(do-game
(new-game (default-corp [(qty "Death and Taxes" 1) (qty "PAD Campaign" 1)])
(default-runner [(qty "Aumakua" 1) (qty "DaVinci" 1) (qty "Fall Guy" 1)]))
(play-from-hand state :corp "Death and Taxes")
(is (= (- 5 2) (:credit (get-corp))) "Corp paid 2 to play Death and Taxes")
(play-from-hand state :corp "PAD Campaign" "New remote")
(take-credits state :corp)
(let [corp-creds (:credit (get-corp))]
(trash-from-hand state :runner "DaVinci")
(is (= corp-creds (:credit (get-corp))) "Corp did not gain credit when runner trashes / discards from hand")
(play-from-hand state :runner "Aumakua")
(is (= (+ 1 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Aumakua")
(play-from-hand state :runner "Fall Guy")
(is (= (+ 2 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner installed Fall Guy")
(card-ability state :runner (get-resource state 0) 1)
(is (= (+ 3 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed Fall Guy")
(run-empty-server state :remote1)
(prompt-choice :runner "Yes") ;; Runner trashes PAD Campaign
(is (= (+ 4 corp-creds) (:credit (get-corp))) "Corp gained 1 when runner trashed PAD Campaign"))))
(deftest defective-brainchips
;; Defective Brainchips - Do 1 add'l brain damage the first time Runner takes some each turn
(do-game
(new-game (default-corp [(qty "Defective Brainchips" 1) (qty "Viktor 1.0" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Shiv" 2)]))
(play-from-hand state :corp "Defective Brainchips")
(play-from-hand state :corp "Viktor 1.0" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [vik (get-ice state :hq 0)]
(core/rez state :corp vik)
(card-subroutine state :corp vik 0)
(is (= 2 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 2 (:brain-damage (get-runner))) "Brainchips dealt 1 additional brain dmg")
(card-subroutine state :corp vik 0)
(is (= 3 (count (:discard (get-runner)))) "2 cards lost to brain damage")
(is (= 3 (:brain-damage (get-runner))) "Brainchips didn't do additional brain dmg"))))
(deftest distract-the-masses
(do-game
(new-game (default-corp [(qty "Distract the Masses" 2) (qty "Hedge Fund" 3)])
(default-runner))
(starting-hand state :corp ["Hedge Fund" "Hedge Fund" "Hedge Fund" "Distract the Masses" "Distract the Masses"])
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-select :corp (first (next (:hand (get-corp)))))
(prompt-select :corp (first (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 1 (count (:discard (get-corp)))) "1 card still discarded")
(is (= 1 (count (:deck (get-corp)))) "1 card shuffled into R&D")
(is (= 1 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 7 (:credit (get-runner))) "Runner gained 2 credits")
(play-from-hand state :corp "Distract the Masses")
(prompt-select :corp (first (:hand (get-corp))))
(prompt-choice :corp "Done")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (first (next (:discard (get-corp)))))
(is (= 0 (count (:discard (get-corp)))) "No cards left in archives")
(is (= 3 (count (:deck (get-corp)))) "2 more cards shuffled into R&D")
(is (= 2 (count (:rfg (get-corp)))) "Distract the Masses removed from game")
(is (= 9 (:credit (get-runner))) "Runner gained 2 credits")))
(deftest diversified-portfolio
(do-game
(new-game (default-corp [(qty "Diversified Portfolio" 1)
(qty "Paper Wall" 1)
(qty "PAD Campaign" 3)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "PAD Campaign" "New remote")
(play-from-hand state :corp "Diversified Portfolio")
(is (= 7 (:credit (get-corp))) "Ignored remote with ICE but no server contents")))
(deftest economic-warfare
;; Economic Warfare - If successful run last turn, make the runner lose 4 credits if able
(do-game
(new-game (default-corp [(qty "Economic Warfare" 3)])
(default-runner))
(play-from-hand state :corp "Economic Warfare")
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(is (= 3 (count (:hand (get-corp)))) "Corp still has 3 cards")
(take-credits state :corp)
(run-on state :archives)
(run-successful state)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 4 (:credit (get-runner))) "Runner has 4 credits")
(play-from-hand state :corp "Economic Warfare")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :corp)
(run-on state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Economic Warfare")
(is (= 3 (:credit (get-runner))) "Runner has 3 credits")))
(deftest election-day
(do-game
(new-game (default-corp [(qty "Election Day" 7)])
(default-runner))
(is (= 6 (count (:hand (get-corp)))) "Corp starts with 5 + 1 cards")
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Election Day" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Election Day")
(is (= 1 (count (:hand (get-corp)))) "Could not play Election Day")
(take-credits state :corp)
(take-credits state :runner)
(is (= 2 (count (:hand (get-corp)))) "Corp has now 1 + 1 cards before Election Day")
(play-from-hand state :corp "Election Day")
(is (= 5 (count (:hand (get-corp)))) "Corp has now 5 cards due to Election Day")))
(deftest enforcing-loyalty
;; Enforcing Loyalty - Win trace to trash installed card not of Runner's faction
(do-game
(new-game (default-corp [(qty "Enforcing Loyalty" 2)])
(make-deck "Chaos Theory: Wünderkind" [(qty "Inti" 1) (qty "Caldera" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Inti")
(play-from-hand state :runner "Caldera")
(take-credits state :runner)
(play-from-hand state :corp "Enforcing Loyalty")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-program state 0))
(is (empty? (:discard (get-runner))) "Can't target Inti; matches Runner faction")
(prompt-select :corp (get-resource state 0))
(is (= 1 (count (:discard (get-runner)))) "Caldera trashed")))
(deftest enhanced-login-protocol
;; Enhanced Login Protocol - First click run each turn costs an additional click
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner 3)
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 1 (:click (get-runner))) "Runner has 1 click")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Employee Strike")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest enhanced-login-protocol-card-ability
;; Enhanced Login Protocol - Card ability runs don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 2 clicks")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run"))))
(deftest enhanced-login-protocol-new-angeles-sol
;; Enhanced Login Protocol trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Enhanced Login Protocol" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:discard (get-corp))))
(run-on state :archives)
(is (= 1 (:click (get-runner))) "Runner has 1 click")))
(deftest enhanced-login-protocol-run-events
;; Enhanced Login Protocol - Run event don't cost additional clicks
(do-game
(new-game (default-corp [(qty "Enhanced Login Protocol" 1)])
(default-runner [(qty "Out of the Ashes" 1)]))
(play-from-hand state :corp "Enhanced Login Protocol")
(take-credits state :corp)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(play-from-hand state :runner "Out of the Ashes")
(prompt-choice :runner "Archives")
(is (= 3 (:click (get-runner)))
"Runner doesn't spend 1 additional click to run with a run event")
(run-successful state)
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(run-on state :archives)
(is (= 2 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-first-run
;; Enhanced Login Protocol - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 3 (:click (get-runner))) "Runner has 3 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner spends 1 additional click to make a run")))
(deftest enhanced-login-protocol-runner-turn-second-run
;; Enhanced Login Protocol - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News"
[(qty "Enhanced Login Protocol" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 2)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Enhanced Login Protocol"
(:hand (get-corp))))
(is (find-card "Enhanced Login Protocol" (:current (get-corp)))
"Enhanced Login Protocol is in play")
(is (= 2 (:click (get-runner))) "Runner has 2 clicks")
(run-on state :archives)
(is (= 1 (:click (get-runner)))
"Runner doesn't spend 1 additional click to make a run")))
(deftest exchange-of-information
;; Exchange of Information - Swapping agendas works correctly
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(score-agenda state :corp (find-card "Market Research" (:hand (get-corp))))
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(take-credits state :corp)
(is (= 0 (:tag (get-runner))) "Runner lost 2 tags")
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(is (= 4 (:agenda-point (get-runner))))
(is (= 3 (:agenda-point (get-corp))))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-runner))))
(is (= 4 (:agenda-point (get-corp))))))
(deftest exchange-of-information-breaking-news
;; Exchange of Information - Swapping a just scored Breaking News keeps the tags
(do-game
(new-game (default-corp [(qty "Exchange of Information" 1)
(qty "Market Research" 1)
(qty "Breaking News" 1)
(qty "Project Beale" 1)
(qty "Explode-a-palooza" 1)])
(default-runner))
(take-credits state :corp)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(core/steal state :runner (find-card "Explode-a-palooza" (:hand (get-corp))))
(take-credits state :runner)
(score-agenda state :corp (find-card "Breaking News" (:hand (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner gained 2 tags")
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "Breaking News" (:scored (get-corp))))
(is (= 2 (:tag (get-runner))) "Still has tags after swap and before end of turn")
(take-credits state :corp)
(is (= 3 (:agenda-point (get-runner))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:tag (get-runner))) "Runner does not lose tags at end of turn")))
(deftest exchange-of-information-fifteen-minutes
;; Exchange of Information - Swapping a 15 Minutes still keeps the ability. #1783
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "15 Minutes" 1)
(qty "Project Beale" 1)])
(default-runner))
(score-agenda state :corp (find-card "15 Minutes" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Project Beale" (:hand (get-corp))))
(take-credits state :runner)
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Project Beale" (:scored (get-runner))))
(prompt-select :corp (find-card "15 Minutes" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(is (= 0 (count (:deck (get-corp)))))
;; shuffle back into R&D from runner's scored area
(let [fifm (get-in @state [:runner :scored 0])]
(card-ability state :corp fifm 0))
(is (= 2 (:agenda-point (get-corp))))
(is (= 0 (:agenda-point (get-runner))))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))
(take-credits state :corp)
(core/steal state :runner (find-card "15 Minutes" (:deck (get-corp))))
(take-credits state :runner)
(is (= 2 (:agenda-point (get-corp))))
(is (= 1 (:agenda-point (get-runner))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "15 Minutes" (:scored (get-runner))))
(prompt-select :corp (find-card "Project Beale" (:scored (get-corp))))
(is (= 1 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
;; shuffle back into R&D from corp's scored area
(let [fifm (get-in @state [:corp :scored 0])]
(card-ability state :corp fifm 0))
(is (= "15 Minutes" (:title (first (:deck (get-corp))))))))
(deftest exchange-of-information-mandatory-upgrades
;; Exchange of Information - Swapping a Mandatory Upgrades gives the Corp an additional click per turn. #1687
(do-game
(new-game (default-corp [(qty "Exchange of Information" 2) (qty "Mandatory Upgrades" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(score-agenda state :corp (find-card "Global Food Initiative" (:hand (get-corp))))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(core/steal state :runner (find-card "Mandatory Upgrades" (:hand (get-corp))))
(take-credits state :runner)
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-runner))))
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-corp))))
(is (= 2 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 3 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 4 (:click (get-corp))))
(is (= 4 (:click-per-turn (get-corp))))
(play-from-hand state :corp "Exchange of Information")
(prompt-select :corp (find-card "Global Food Initiative" (:scored (get-runner))))
(prompt-select :corp (find-card "Mandatory Upgrades" (:scored (get-corp))))
(is (= 3 (:agenda-point (get-corp))))
(is (= 2 (:agenda-point (get-runner))))
(is (= 2 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(is (= 3 (:click (get-corp))))
(is (= 3 (:click-per-turn (get-corp))))))
(deftest hatchet-job
;; Hatchet Job - Win trace to add installed non-virtual to grip
(do-game
(new-game (default-corp [(qty "Hatchet Job" 1)])
(default-runner [(qty "Upya" 1) (qty "Ghost Runner" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Ghost Runner")
(play-from-hand state :runner "Upya")
(take-credits state :runner)
(play-from-hand state :corp "Hatchet Job")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(is (empty? (:hand (get-runner))) "Can't choose virtual card")
(is (not (empty? (:prompt (get-corp)))))
(prompt-select :corp (get-program state 0))
(is (= 1 (count (:hand (get-runner)))) "Upya returned to grip")))
(deftest hedge-fund
(do-game
(new-game (default-corp) (default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Hedge Fund")
(is (= 9 (:credit (get-corp))))))
(deftest high-profile-target
(testing "when the runner has no tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(testing "when the runner has one tag"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "High-Profile Target")
(is (= 3 (count (:hand (get-runner)))) "Runner has 3 cards in hand")))
(testing "when the runner has two tags"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 2)
(play-from-hand state :corp "High-Profile Target")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(testing "when the runner has enough tags to die"
(do-game
(new-game (default-corp [(qty "High-Profile Target" 6)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline"))))
(deftest high-profile-target-flatline
;; High-Profile Target - three tags, gg
(do-game
(new-game (default-corp [(qty "High-Profile Target" 10)])
(default-runner))
(core/gain state :runner :tag 3)
(play-from-hand state :corp "High-Profile Target")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest housekeeping
;; Housekeeping - Runner must trash a card from Grip on first install of a turn
(do-game
(new-game (default-corp [(qty "Housekeeping" 1)])
(default-runner [(qty "Cache" 2) (qty "Fall Guy" 1) (qty "PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Fall Guy")
(take-credits state :runner)
(play-from-hand state :corp "Housekeeping")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(prompt-select :runner (find-card "PI:NAME:<NAME>END_PI. Li" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "Fall Guy prevention didn't trigger")
(is (= 1 (count (:discard (get-runner)))) "Card trashed")
(play-from-hand state :runner "Cache")
(is (empty? (:prompt (get-runner))) "Housekeeping didn't trigger on 2nd install")))
(deftest invasion-of-privacy
;; Invasion of Privacy - Full test
(do-game
(new-game (default-corp [(qty "Invasion of Privacy" 3)])
(default-runner [(qty "Sure Gamble" 2) (qty "Fall Guy" 1) (qty "Cache" 2)]))
(core/gain state :corp :click 3 :credit 6)
;; trash 2 cards
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 5 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" "Sure Gamble" nil) (prompt-names)))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner)))))
(is (= 3 (count (:hand (get-runner)))))
;; able to trash 2 cards but only 1 available target in Runner's hand
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 3 (count (:hand (get-runner)))))
(let [get-prompt (fn [] (first (#(get-in @state [:corp :prompt]))))
prompt-names (fn [] (map #(:title %) (:choices (get-prompt))))]
(is (= (list "Fall Guy" nil) (prompt-names)))
(prompt-choice :corp (find-card "Fall Guy" (:hand (get-runner))))
(is (empty? (get-in @state [:corp :prompt])) "No prompt for second card"))
(is (= 2 (count (:hand (get-runner)))))
;; failed trace - take the bad publicity
(play-from-hand state :corp "Invasion of Privacy")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 2) ; Runner matches
(is (= 1 (:bad-publicity (get-corp))))))
(deftest ipo-terminal
;; IPO - credits with Terminal operations
(do-game
(new-game
(default-corp [(qty "IPO" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "IPO")
(is (= 13 (:credit (get-corp))))
(is (= 0 (:click (get-corp))) "Terminal ends turns")))
(deftest lag-time
(do-game
(new-game (default-corp [(qty "Lag Time" 1) (qty "Vanilla" 1) (qty "Lotus Field" 1)])
(default-runner))
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Vanilla" "HQ")
(play-from-hand state :corp "Lotus Field" "R&D")
(play-from-hand state :corp "Lag Time")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(is (= 1 (:current-strength (get-ice state :hq 0))) "Vanilla at 1 strength")
(is (= 5 (:current-strength (get-ice state :rd 0))) "Lotus Field at 5 strength")))
(deftest lateral-growth
(do-game
(new-game (default-corp [(qty "Lateral Growth" 1) (qty "Breaking News" 1)])
(default-runner))
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Lateral Growth")
(prompt-select :corp (find-card "Breaking News" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Breaking News" (:title (get-content state :remote1 0)))
"Breaking News installed by Lateral Growth")
(is (= 7 (:credit (get-corp))))))
(deftest manhunt-every-run
;; Manhunt - only fires once per turn. Unreported issue.
(do-game
(new-game (default-corp [(qty "Manhunt" 1) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Manhunt")
(take-credits state :corp)
(run-empty-server state "HQ")
(is (:prompt (get-corp)) "Manhunt trace initiated")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")
(run-empty-server state "HQ")
(is (empty? (:prompt (get-corp))) "No Manhunt trace on second run")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest market-forces
(testing "when the runner is not tagged"
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(play-from-hand state :corp "Market Forces")
(is (= 6 (count (:hand (get-corp))))
"Market Forces is not played")
(is (= 3 (:click (get-corp)))
"the corp does not spend a click")
(is (= 5 (:credit (get-corp)) (:credit (get-runner)))
"credits are unaffected")))
(letfn [(market-forces-credit-test
[{:keys [tag-count runner-creds expected-credit-diff]}]
(testing (str "when the runner has " tag-count " tags and " runner-creds " credits")
(do-game
(new-game (default-corp [(qty "Market Forces" 6)])
(default-runner))
(swap! state assoc-in [:corp :credit] 0)
(swap! state assoc-in [:runner :credit] runner-creds)
(core/gain state :runner :tag tag-count)
(play-from-hand state :corp "Market Forces")
(is (= expected-credit-diff (:credit (get-corp)))
(str "the corp gains " expected-credit-diff " credits"))
(is (= expected-credit-diff (- runner-creds (:credit (get-runner))))
(str "the runner loses " expected-credit-diff " credits")))))]
(doall (map market-forces-credit-test
[{:tag-count 1
:runner-creds 10
:expected-credit-diff 3}
{:tag-count 2
:runner-creds 10
:expected-credit-diff 6}
{:tag-count 3
:runner-creds 10
:expected-credit-diff 9}
{:tag-count 3
:runner-creds 0
:expected-credit-diff 0}
{:tag-count 3
:runner-creds 5
:expected-credit-diff 5}]))))
(deftest mass-commercialization
;; Mass Commercialization
(do-game
(new-game (default-corp [(qty "Mass Commercialization" 1)
(qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :runner)
(core/advance state :corp {:card (refresh (get-ice state :hq 0))})
(core/advance state :corp {:card (refresh (get-ice state :archives 0))})
(core/advance state :corp {:card (refresh (get-ice state :rd 0))})
(take-credits state :runner)
(play-from-hand state :corp "Mass Commercialization")
(is (= 8 (:credit (get-corp))) "Gained 6 for 3 advanced ice from Mass Commercialization")))
(deftest midseason-replacements
;; Midseason Replacements - Trace to give Runner tags after they steal an agenda
(do-game
(new-game (default-corp [(qty "Midseason Replacements" 1) (qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Midseason Replacements")
(is (= 3 (:click (get-corp))) "Midseason precondition not met; Corp not charged a click")
(play-from-hand state :corp "Breaking News" "New remote")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(let [bn (get-content state :remote1 0)]
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(is (= 1 (:agenda-point (get-runner))) "Stole Breaking News")
(take-credits state :runner)
(play-from-hand state :corp "Midseason Replacements")
(prompt-choice :corp 0) ; default trace
(prompt-choice :runner 0) ; Runner won't match
(is (= 6 (:tag (get-runner))) "Runner took 6 tags"))))
(deftest mushin-no-shin
;; PI:NAME:<NAME>END_PI - Add 3 advancements to a card; prevent rez/score of that card the rest of the turn
(do-game
(new-game (default-corp [(qty "MPI:NAME:<NAME>END_PIin" 2) (qty "Ronin" 1) (qty "Profiteering" 1)])
(default-runner))
(play-from-hand state :corp "PI:NAME:<NAME>END_PI")
(prompt-select :corp (find-card "PI:NAME:<NAME>END_PI" (:hand (get-corp))))
(let [ronin (get-content state :remote1 0)]
(is (= 3 (:advance-counter (refresh ronin))) "3 advancements placed on Ronin")
(core/rez state :corp (refresh ronin))
(is (not (get-in (refresh ronin) [:rezzed])) "Ronin did not rez")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh ronin))
(is (get-in (refresh ronin) [:rezzed]) "Ronin now rezzed")
(play-from-hand state :corp "PI:NAME:<NAME>END_PI")
(prompt-select :corp (find-card "Profiteering" (:hand (get-corp))))
(let [prof (get-content state :remote2 0)]
(core/score state :corp (refresh prof))
(is (empty? (:scored (get-corp))) "Profiteering not scored")
(is (= 0 (:agenda-point (get-corp))))
(take-credits state :corp)
(take-credits state :runner)
(core/score state :corp (refresh prof))
(prompt-choice :corp "0")
(is (= 1 (:agenda-point (get-corp))) "Profiteering was able to be scored")))))
(deftest neural-emp
;; Neural EMP - Play if Runner made a run the previous turn to do 1 net damage
(do-game
(new-game (default-corp [(qty "Neural EMP" 1)])
(default-runner))
(play-from-hand state :corp "Neural EMP")
(is (= 3 (:click (get-corp))) "Neural precondition not met; card not played")
(take-credits state :corp)
(run-empty-server state "Archives")
(take-credits state :runner)
(play-from-hand state :corp "Neural EMP")
(is (= 1 (count (:discard (get-runner)))) "Runner took 1 net damage")))
(deftest oversight-ai
;; Oversight AI - Rez a piece of ICE ignoring all costs
(do-game
(new-game (default-corp [(qty "Oversight AI" 1) (qty "Archer" 1)])
(default-runner))
(play-from-hand state :corp "Archer" "R&D")
(let [archer (get-ice state :rd 0)]
(play-from-hand state :corp "Oversight AI")
(prompt-select :corp archer)
(is (get-in (refresh archer) [:rezzed]))
(is (= 4 (:credit (get-corp))) "Archer rezzed at no credit cost")
(is (= "Oversight AI" (:title (first (:hosted (refresh archer)))))
"Archer hosting OAI as a condition"))))
(deftest patch
;; Patch - +2 current strength
(do-game
(new-game (default-corp [(qty "Patch" 1) (qty "Vanilla" 1)])
(default-runner))
(play-from-hand state :corp "Vanilla" "HQ")
(core/rez state :corp (get-ice state :hq 0))
(play-from-hand state :corp "Patch")
(prompt-select :corp (get-ice state :hq 0))
(is (= 2 (:current-strength (get-ice state :hq 0))) "Vanilla at 2 strength")))
(deftest paywall-implementation
;; Paywall Implementation - Gain 1 credit for every successful run
(do-game
(new-game (default-corp [(qty "Paywall Implementation" 1)])
(default-runner))
(play-from-hand state :corp "Paywall Implementation")
(is (= "Paywall Implementation" (:title (first (get-in @state [:corp :current]))))
"Paywall active in Current area")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))))
(run-empty-server state "Archives")
(is (= 8 (:credit (get-corp))) "Gained 1 credit from successful run")
(run-empty-server state "Archives")
(is (= 9 (:credit (get-corp))) "Gained 1 credit from successful run")))
(deftest peak-efficiency
;; Peak Efficiency - Gain 1 credit for each rezzed ICE
(do-game
(new-game (default-corp [(qty "Peak Efficiency" 1) (qty "Paper Wall" 3) (qty "Wraparound" 1)])
(default-runner))
(core/gain state :corp :click 3)
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "R&D")
(play-from-hand state :corp "Paper Wall" "New remote")
(play-from-hand state :corp "Wraparound" "New remote")
(core/rez state :corp (get-ice state :hq 0))
(core/rez state :corp (get-ice state :rd 0))
(core/rez state :corp (get-ice state :remote1 0))
(play-from-hand state :corp "Peak Efficiency")
(is (= 7 (:credit (get-corp))) "Gained 3 credits for 3 rezzed ICE; unrezzed ICE ignored")))
(deftest power-shutdown
;; Power Shutdown - Trash cards from R&D to force Runner to trash a program or hardware
(do-game
(new-game (default-corp [(qty "Power Shutdown" 3) (qty "Hive" 3)])
(default-runner [(qty "Grimoire" 1) (qty "Cache" 1)]))
(play-from-hand state :corp "Power Shutdown")
(is (empty? (:discard (get-corp))) "Not played, no run last turn")
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Grimoire")
(run-empty-server state :archives)
(take-credits state :runner)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Hive" (:hand (get-corp))) :deck)
(play-from-hand state :corp "Power Shutdown")
(prompt-choice :corp 2)
(is (= 3 (count (:discard (get-corp)))) "2 cards trashed from R&D")
(is (= 1 (count (:deck (get-corp)))) "1 card remaining in R&D")
(prompt-select :runner (get-in @state [:runner :rig :hardware 0])) ; try targeting Grimoire
(is (empty? (:discard (get-runner))) "Grimoire too expensive to be targeted")
(prompt-select :runner (get-in @state [:runner :rig :program 0]))
(is (= 1 (count (:discard (get-runner)))) "Cache trashed")))
(deftest precognition
;; Precognition - Full test
(do-game
(new-game (default-corp [(qty "Precognition" 1) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Quandary" 1) (qty "Jackson Howard" 1) (qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Precognition"])
(play-from-hand state :corp "Precognition")
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "PI:NAME:<NAME>END_PI" (:title (first (:deck (get-corp))))))
(is (= "Adonis Campaign" (:title (second (:deck (get-corp))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (:deck (get-corp)))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (rest (:deck (get-corp))))))))
(is (= "Global Food Initiative" (:title (second (rest (rest (rest (:deck (get-corp)))))))))))
(deftest preemptive-action
;; Preemptive Action - Shuffles cards into R&D and removes itself from game
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)
(qty "Preemptive Action" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Preemptive Action")
(prompt-select :corp (first (:discard (get-corp))))
(prompt-select :corp (second (:discard (get-corp))))
(prompt-select :corp (last (:discard (get-corp))))
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp)))))))
(deftest psychographics
;; Psychographics - Place advancements up to the number of Runner tags on a card
(do-game
(new-game (default-corp [(qty "Psychographics" 1) (qty "Project Junebug" 1)])
(default-runner))
(core/gain state :runner :tag 4)
(play-from-hand state :corp "Project Junebug" "New remote")
(let [pj (get-content state :remote1 0)]
(play-from-hand state :corp "Psychographics")
(prompt-choice :corp 4)
(prompt-select :corp pj)
(is (= 1 (:credit (get-corp))) "Spent 4 credits")
(is (= 4 (:advance-counter (refresh pj))) "Junebug has 4 advancements"))))
(deftest psychokinesis
;; Pyschokinesis - Terminal Event (end the turn); Look at R&D, install an Asset, Agenda, or Upgrade in a Remote Server
(do-game
(new-game (default-corp [(qty "Psychokinesis" 3) (qty "Caprice Nisei" 1) (qty "Adonis Campaign" 1)
(qty "Global Food Initiative" 1)])
(default-runner))
(starting-hand state :corp ["Psychokinesis","Psychokinesis","Psychokinesis"])
;; Test installing an Upgrade
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "PI:NAME:<NAME>END_PI" (:title (get-content state :remote1 0)))
"PI:NAME:<NAME>END_PI NPI:NAME:<NAME>END_PIi installed by Psychokinesis")
;; Test installing an Asset
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Adonis Campaign" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Adonis Campaign" (:title (get-content state :remote2 0)))
"Adonis Campaign installed by Psychokinesis")
;; Test installing an Agenda
(core/gain state :corp :click 1)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp (find-card "Global Food Initiative" (:deck (get-corp))))
(prompt-choice :corp "New remote")
(is (= "Global Food Initiative" (:title (get-content state :remote3 0)))
"Global Food Initiative installed by Psychokinesis")
;; Test selecting "None"
(core/gain state :corp :click 1)
(core/move state :corp (find-card "Psychokinesis" (:discard (get-corp))) :hand)
(play-from-hand state :corp "Psychokinesis")
(prompt-choice :corp "None")
(is (= nil (:title (get-content state :remote4 0)))
"Nothing is installed by Psychokinesis")))
(deftest punitive-counterstrike
;; Punitive Counterstrike - deal meat damage equal to printed agenda points
(do-game
(new-game (default-corp [(qty "Global Food Initiative" 1) (qty "Punitive Counterstrike" 1)])
(default-runner))
(play-from-hand state :corp "Global Food Initiative" "New remote")
(take-credits state :corp)
(run-empty-server state :remote1)
(prompt-choice :runner "Steal")
(is (= 2 (:agenda-point (get-runner))) "Runner scored 2 points")
(take-credits state :runner)
(play-from-hand state :corp "Punitive Counterstrike")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (empty? (:hand (get-runner))) "Runner took 3 meat damage")))
(deftest red-planet-couriers
;; Red Planet Couriers - Move all advancements on cards to 1 advanceable card
(do-game
(new-game (default-corp [(qty "Red Planet Couriers" 1) (qty "Ice Wall" 2)
(qty "GRNDL Refinery" 1) (qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 4)
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "GRNDL Refinery" "New remote")
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Ice Wall" "R&D")
(let [gt (get-content state :remote1 0)
gr (get-content state :remote2 0)
iw1 (get-ice state :hq 0)
iw2 (get-ice state :rd 0)]
(core/add-prop state :corp gr :advance-counter 3)
(core/add-prop state :corp iw1 :advance-counter 2)
(core/add-prop state :corp iw2 :advance-counter 1)
(play-from-hand state :corp "Red Planet Couriers")
(prompt-select :corp gt)
(is (nil? (:advance-counter (refresh gr))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw1))) "Advancements removed")
(is (nil? (:advance-counter (refresh iw2))) "Advancements removed")
(is (= 6 (:advance-counter (refresh gt))) "Gained 6 advancements"))))
(deftest reuse
;; Reuse - Gain 2 credits for each card trashed from HQ
(do-game
(new-game (default-corp [(qty "Reuse" 2) (qty "Hive" 1) (qty "IQ" 1)
(qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Reuse")
(prompt-select :corp (find-card "Ice Wall" (:hand (get-corp))))
(prompt-select :corp (find-card "Hive" (:hand (get-corp))))
(prompt-select :corp (find-card "IQ" (:hand (get-corp))))
(prompt-choice :corp "Done")
(is (= 4 (count (:discard (get-corp)))) "3 cards trashed plus operation played")
(is (= 11 (:credit (get-corp))) "Gained 6 credits")
(is (= 1 (:click (get-corp))) "Spent 2 clicks")))
(deftest reverse-infection
;; Reverse Infection - purge and trash 1 card from stack for every 3 counters purged - or gain 2 credits
(do-game
(new-game (default-corp [(qty "Reverse Infection" 2)])
(default-runner [(qty "Virus Breeding Ground" 1) (qty "Datasucker" 1) (qty "Sure Gamble" 3)]))
(starting-hand state :runner ["Virus Breeding Ground" "Datasucker"])
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Gain 2 [Credits]")
(is (= 7 (:credit (get-corp))) "Corp gained 2 credits")
(take-credits state :corp)
(play-from-hand state :runner "Virus Breeding Ground")
(play-from-hand state :runner "Datasucker")
(take-credits state :runner)
(core/add-counter state :runner (get-resource state 0) :virus 4)
(core/add-counter state :runner (get-program state 0) :virus 3)
(play-from-hand state :corp "Reverse Infection")
(prompt-choice :corp "Purge virus counters.")
(is (= 9 (:credit (get-corp))) "Corp did not gain credits")
(is (zero? (get-counters (get-resource state 0) :virus)) "Viruses purged from VBG")
(is (zero? (get-counters (get-program state 0) :virus)) "Viruses purged from Datasucker")
(is (= 2 (count (:discard (get-runner)))) "Two cards trashed from stack")))
(deftest rolling-brownout
;; Rolling Brownout - Increase cost of events/operations by 1, gain 1c on first Runner event of turn
(do-game
(new-game (default-corp [(qty "Rolling Brownout" 1) (qty "Beanstalk Royalties" 1)
(qty "Domestic Sleepers" 1)])
(default-runner [(qty "Easy Mark" 3)]))
(play-from-hand state :corp "Rolling Brownout")
(play-from-hand state :corp "Beanstalk Royalties")
(is (= 5 (:credit (get-corp))) "Beanstalk netted only 2c")
(play-from-hand state :corp "Domestic Sleepers" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Easy Mark")
(is (= 7 (:credit (get-runner))) "Easy Mark netted only 2c")
(is (= 6 (:credit (get-corp))) "Corp gained 1c from Brownout")
(play-from-hand state :runner "Easy Mark")
(is (= 6 (:credit (get-corp))) "No Corp credit gain from 2nd event")
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(play-from-hand state :runner "Easy Mark")
(is (= 12 (:credit (get-runner))) "Easy Mark netted 3c after Brownout trashed")))
(deftest salems-hospitality
;; Salem's Hospitality - Full test
(do-game
(new-game (default-corp [(qty "Salem's Hospitality" 3)])
(default-runner [(qty "I've Had Worse" 3) (qty "Faust" 1)
(qty "Levy AR Lab Access" 1)]))
(play-from-hand state :corp "Salem's Hospitality")
(is (= 5 (count (:hand (get-runner)))))
(prompt-choice :corp "I've Had Worse")
(is (= 2 (count (:hand (get-runner)))))
(play-from-hand state :corp "Salem's Hospitality")
(prompt-choice :corp "Plascrete Carapace")
(is (= 2 (count (:hand (get-runner)))))))
(deftest scorched-earth
;; Scorched Earth - burn 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 1 (count (:hand (get-runner)))) "Runner has 1 card in hand")))
(deftest scorched-earth-no-tag
;; Scorched Earth - not tagged
(do-game
(new-game (default-corp [(qty "Scorched Earth" 1)])
(default-runner [(qty "Sure Gamble" 3) (qty "Lucky Find" 3)]))
(play-from-hand state :corp "Scorched Earth")
(is (= 3 (:click (get-corp))) "Corp not charged a click")
(is (= 5 (count (:hand (get-runner)))) "Runner did not take damage")))
(deftest scorched-earth-flatline
;; Scorched Earth - murderize 'em
(do-game
(new-game (default-corp [(qty "Scorched Earth" 10)])
(default-runner))
(core/gain state :runner :tag 1)
(play-from-hand state :corp "Scorched Earth")
(is (= 0 (count (:hand (get-runner)))) "Runner has 0 cards in hand")
(is (= :corp (:winner @state)) "Corp wins")
(is (= "Flatline" (:reason @state)) "Win condition reports flatline")))
(deftest self-growth-program
;; Self-Growth Program - Add 2 installed cards to grip if runner is tagged
(do-game
(new-game (default-corp [(qty "Self-Growth Program" 1)])
(default-runner [(qty "Clone Chip" 1) (qty "Inti" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Clone Chip")
(play-from-hand state :runner "Inti")
(take-credits state :runner)
(play-from-hand state :corp "Self-Growth Program")
(is (= 3 (:click (get-corp))) "Self-Growth Program precondition not met; card not played")
(core/gain state :runner :tag 1)
(is (= 0 (count (:hand (get-runner)))) "Runner hand is empty")
(let [inti (get-in @state [:runner :rig :program 0])
cc (get-in @state [:runner :rig :hardware 0])]
(play-from-hand state :corp "Self-Growth Program")
(prompt-select :corp inti)
(prompt-select :corp cc))
(is (= 2 (count (:hand (get-runner)))) "2 cards returned to hand")
(is (= 0 (count (get-in @state [:runner :rig :program]))) "No programs installed")
(is (= 0 (count (get-in @state [:runner :rig :hardware]))) "No hardware installed")))
(deftest service-outage
;; Service Outage - First click run each turn costs a credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Employee Strike" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner spends 1 credit to make the first run")
(run-successful state)
(run-on state :archives)
(is (= 4 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make the second run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 6)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(run-on state :archives)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 2)
(play-from-hand state :runner "Employee Strike")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")))
(deftest service-outage-card-ability
;; Service Outage - First card ability run each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(take-credits state :runner 1)
(is (= 2 (:credit (get-runner))) "Runner has 2 credits")
(let [sneakdoor (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sneakdoor 0)
(is (= 1 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a card ability")
(run-successful state)
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(core/lose state :runner :credit 1)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits")
(card-ability state :runner sneakdoor 0)
(is (not (:run @state)) "No run was initiated")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 0 (:credit (get-runner))) "Runner has 0 credits"))))
(deftest service-outage-run-events
;; Service Outage - First run event each turn costs an additional credit
(do-game
(new-game (default-corp [(qty "Service Outage" 1)])
(default-runner [(qty "Out of the Ashes" 2)]))
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(is (= 5 (:credit (get-runner))) "Runner has 5 credits")
(play-from-hand state :runner "Out of the Ashes")
(is (= 3 (:credit (get-runner)))
"Runner spends 1 additional credit to run with a run event")
(prompt-choice :runner "Archives")
(run-successful state)
(run-on state :archives)
(is (= 3 (:credit (get-runner)))
"Runner doesn't spend 1 credit to make a run")
(run-successful state)
(take-credits state :runner)
(take-credits state :corp)
(prompt-choice :runner "No") ; Out of the Ashes prompt
(core/lose state :runner :credit 4)
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(play-from-hand state :runner "Out of the Ashes")
(is (empty? (get-in @state [:runner :prompt]))
"Out of the Ashes was not played")
(is (= 4 (:click (get-runner))) "Runner has 4 clicks")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")))
(deftest service-outage-runner-turn-first-run
;; Service Outage - Works when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(core/gain state :runner :credit 3)
(play-from-hand state :runner "Hades Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 0 (:credit (get-runner)))
"Runner spends 1 additional credit to make a run")))
(deftest service-outage-runner-turn-second-run
;; Service Outage - Doesn't fire if already run when played on the runner's turn
(do-game
(new-game (make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner [(qty "Hades Shard" 1)]))
(trash-from-hand state :corp "Breaking News")
(take-credits state :corp)
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "OK")
(core/gain state :runner :credit 3)
(play-from-hand state :runner "HPI:NAME:<NAME>END_PI Shard")
(card-ability state :runner (get-in @state [:runner :rig :resource 0]) 0)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage" (:hand (get-corp))))
(is (find-card "Service Outage" (:current (get-corp)))
"Service Outage is in play")
(is (= 1 (:credit (get-runner))) "Runner has 1 credit")
(run-on state :archives)
(is (= 1 (:credit (get-runner)))
"Runner doesn't spend 1 additional credit to make a run")))
(deftest service-outage-new-angeles-sol
;; Service Outage trashed and reinstalled on steal doesn't double remove penalty
(do-game
(new-game
(make-deck "New Angeles Sol: Your News" [(qty "Service Outage" 1)
(qty "Breaking News" 1)])
(default-runner))
(play-from-hand state :corp "Breaking News" "New remote")
(play-from-hand state :corp "Service Outage")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Steal")
(prompt-choice :corp "Yes")
(prompt-select :corp (find-card "Service Outage"
(:discard (get-corp))))
(take-credits state :runner)
(take-credits state :corp)
(is (= 7 (:credit (get-runner))) "Runner has 7 credits")
(run-on state :archives)
(is (= 6 (:credit (get-runner)))
"Runner spends 1 credit to make a run")))
(deftest shipment-from-sansan
;; Shipment from SanSan - placing advancements
(do-game
(new-game (default-corp [(qty "Shipment from SanSan" 3) (qty "Ice Wall" 3)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(let [iwall (get-ice state :hq 0)]
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "2")
(prompt-select :corp iwall)
(is (= 5 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh iwall)))))))
(deftest stock-buy-back
;; Stock Buy-Back - Gain 3c for every agenda in Runner's area
(do-game
(new-game (default-corp [(qty "Hostile Takeover" 2) (qty "Stock Buy-Back" 3)])
(default-runner))
(play-from-hand state :corp "Hostile Takeover" "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(take-credits state :corp)
(run-empty-server state "Server 1")
(prompt-choice :runner "Steal")
(run-empty-server state "Server 2")
(prompt-choice :runner "Steal")
(take-credits state :runner)
(is (= 2 (count (:scored (get-runner)))))
(play-from-hand state :corp "Stock Buy-Back")
(is (= 11 (:credit (get-corp))))))
(deftest sub-boost
;; Sub Boost - Give ICE Barrier
(do-game
(new-game (default-corp [(qty "Sub Boost" 1) (qty "Quandary" 1)])
(default-runner))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Sub Boost")
(let [qu (get-ice state :hq 0)]
(core/rez state :corp qu)
(prompt-select :corp qu)
(is (core/has-subtype? (refresh qu) "Code Gate") "Quandary has Code Gate")
(is (core/has-subtype? (refresh qu) "Barrier") "Quandary ICE Barrier"))))
(deftest subcontract-scorched
;; Subcontract - Don't allow second operation until damage prevention completes
(do-game
(new-game (default-corp [(qty "Scorched Earth" 2) (qty "Subcontract" 1)])
(default-runner [(qty "Plascrete Carapace" 1)]))
(take-credits state :corp)
(core/gain state :runner :tag 1)
(play-from-hand state :runner "Plascrete Carapace")
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Scorched Earth" (:hand (get-corp))))
(is (and (= 1 (count (:prompt (get-corp)))) (= :waiting (-> (get-corp) :prompt first :prompt-type)))
"Corp does not have Subcontract prompt until damage prevention completes")
(prompt-choice :runner "Done")
(is (not-empty (:prompt (get-corp))) "Corp can now play second Subcontract operation")))
(deftest subcontract-terminal
;; Subcontract - interaction with Terminal operations
(do-game
(new-game
(default-corp [(qty "Hard-Hitting News" 2) (qty "Subcontract" 1)])
(default-runner))
(core/gain state :runner :tag 1)
(take-credits state :corp)
(run-empty-server state :archives)
(take-credits state :runner)
(play-from-hand state :corp "Subcontract")
(prompt-select :corp (find-card "Hard-Hitting News" (:hand (get-corp))))
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 5 (:tag (get-runner))) "Runner has 5 tags")
(is (empty? (:prompt (get-corp))) "Corp does not have a second Subcontract selection prompt")))
(deftest subliminal-messaging
;; Subliminal Messaging - Playing/trashing/milling will all prompt returning to hand
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 3)])
(make-deck "Noise: Hacker Extraordinaire" [(qty "Cache" 3) (qty "Utopia Shard" 1)]))
(play-from-hand state :corp "Subliminal Messaging")
(is (= 6 (:credit (get-corp))))
(is (= 3 (:click (get-corp))) "First Subliminal Messaging gains 1 click")
(play-from-hand state :corp "Subliminal Messaging")
(is (= 7 (:credit (get-corp))))
(is (= 2 (:click (get-corp))) "Second Subliminal Messaging does not gain 1 click")
(trash-from-hand state :corp "Subliminal Messaging")
(is (= 0 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(core/move state :corp (find-card "Subliminal Messaging" (:hand (get-corp))) :deck)
(take-credits state :corp)
(play-from-hand state :runner "Cache")
(play-from-hand state :runner "Utopia Shard")
(let [utopia (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner utopia 0))
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 3 (count (:hand (get-corp)))) "All 3 Subliminals returned to HQ")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(is (= 2 (count (:hand (get-corp)))))
(is (= 1 (count (:discard (get-corp)))) "1 Subliminal not returned because runner made a run last turn")))
(deftest subliminal-messaging-archived
;; Subliminal Messaging - Scenario involving Subliminal being added to HQ with Archived Memories
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2) (qty "Archived Memories" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "Archived Memories")
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(is (= 2 (count (:discard (get-corp)))))
(is (= 1 (count (:hand (get-corp)))))
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(is (empty? (get-in @state [:corp :prompt])) "Only 1 Subliminal prompt")
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (empty? (get-in @state [:corp :prompt]))
"Only 2 Subliminal prompts - there will be a third if flag not cleared")))
(deftest subliminal-messaging-jackson
;; Subliminal Messaging - Scenario involving Subliminal being reshuffled into R&D with Jackson
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 1) (qty "PI:NAME:<NAME>END_PI" 1)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(play-from-hand state :corp "PI:NAME:<NAME>END_PI" "New remote")
(take-credits state :corp)
(let [jhow (get-content state :remote1 0)]
(core/rez state :corp jhow)
(card-ability state :corp jhow 1)
(prompt-select :corp (find-card "Subliminal Messaging" (:discard (get-corp))))
(prompt-choice :corp "Done")
(is (= 0 (count (:discard (get-corp)))))
(is (= 1 (count (:rfg (get-corp))))))
(take-credits state :runner)
(play-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(is (= 1 (count (:hand (get-corp)))) "Subliminal returned to HQ")
(is (empty? (get-in @state [:corp :prompt]))
"Subliminal prompt cleared - there will be a second prompt if flag not cleared")))
(deftest subliminal-messaging-made-run
;; Subliminal Messaging - Runner made run, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(is (empty? (get-in @state [:corp :prompt])) "No prompt here because runner made a run last turn")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest subliminal-messaging-no
;; Subliminal Messaging - User declines to return to hand, ensure game asks again next turn
(do-game
(new-game (default-corp [(qty "Subliminal Messaging" 2)])
(default-runner))
(play-from-hand state :corp "Subliminal Messaging")
(trash-from-hand state :corp "Subliminal Messaging")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "No")
(prompt-choice :corp "No")
(is (= 0 (count (:hand (get-corp)))) "Neither Subliminal returned to HQ")
(is (= 2 (count (:discard (get-corp)))) "Both Subliminals in Archives")
(take-credits state :corp)
(take-credits state :runner)
(prompt-choice :corp "Yes")
(prompt-choice :corp "Yes")
(is (= 2 (count (:hand (get-corp)))) "Both Subliminals returned to HQ")
(is (= 0 (count (:discard (get-corp)))) "No Subliminals in Archives")))
(deftest success-bad-publicity
;; Success - Works with bad publicity
(do-game
(new-game (default-corp [(qty "NAPD Contract" 1) (qty "Project Beale" 1) (qty "Success" 1)])
(default-runner))
(play-from-hand state :corp "NAPD Contract" "New remote")
(play-from-hand state :corp "Project Beale" "New remote")
(core/gain state :corp :bad-publicity 9)
(core/gain state :corp :credit 8)
(core/gain state :corp :click 15)
(let [napd (get-content state :remote1 0)
beale (get-content state :remote2 0)]
(dotimes [_ 13] (core/advance state :corp {:card (refresh napd)}))
(is (= 13 (:advance-counter (refresh napd))))
(core/score state :corp {:card (refresh napd)})
(is (= 2 (:agenda-point (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp 0))
(is (= "NAPD Contract" (:title (first (:rfg (get-corp))))))
(prompt-select :corp (refresh beale))
(is (= 13 (:advance-counter (refresh beale))))
(core/score state :corp {:card (refresh beale)})
(is (= 7 (:agenda-point (get-corp)))))))
(deftest success-public-agenda
;; Success - Works with public agendas
(do-game
(new-game (default-corp [(qty "Oaktown Renovation" 1) (qty "Vanity Project" 1) (qty "Success" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "Vanity Project" (:hand (get-corp))))
(is (= 4 (:agenda-point (get-corp))))
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(is (= 5 (:credit (get-corp))))
(play-from-hand state :corp "Success")
(prompt-select :corp (get-scored state :corp))
(is (= "Vanity Project" (:title (first (:rfg (get-corp))))))
(let [oaktown (get-content state :remote1 0)]
(prompt-select :corp (refresh oaktown))
(is (= 6 (:advance-counter (refresh oaktown))))
(is (= 19 (:credit (get-corp))) "Gain 2 + 2 + 2 + 2 + 3 + 3 = 14 credits for advancing Oaktown")
(core/score state :corp {:card (refresh oaktown)})
(is (= 2 (:agenda-point (get-corp)))))))
(deftest success-jemison
;; Success interaction with Jemison, regression test for issue #2704
(do-game
(new-game (make-deck "Jemison Astronautics: Sacrifice. Audacity. Success."
[(qty "Success" 1)
(qty "High-Risk Investment" 1)
(qty "Government Takeover" 1)])
(default-runner))
(core/gain state :corp :click 1)
(score-agenda state :corp (find-card "High-Risk Investment" (:hand (get-corp))))
(play-from-hand state :corp "Government Takeover" "New remote")
(play-from-hand state :corp "Success")
(prompt-select :corp (get-in (get-corp) [:scored 0]))
(let [gto (get-content state :remote1 0)]
;; Prompt for Jemison
(prompt-select :corp (refresh gto))
(is (= 4 (:advance-counter (refresh gto))) "Added 4 counters from Jemison trigger")
;; Prompt for Success
(prompt-select :corp (refresh gto))
(is (= (+ 4 5) (:advance-counter (refresh gto))) "Advance 5 times from Success"))))
(deftest successful-demonstration
;; Successful Demonstration - Play if only Runner made unsuccessful run last turn; gain 7 credits
(do-game
(new-game (default-corp [(qty "Successful Demonstration" 1)])
(default-runner))
(play-from-hand state :corp "Successful Demonstration")
(is (and (= 3 (:click (get-corp)))
(= 5 (:credit (get-runner))))
"Successful Demonstration precondition not met; card not played")
(take-credits state :corp)
(run-on state "R&D")
(run-jack-out state)
(take-credits state :runner)
(play-from-hand state :corp "Successful Demonstration")
(is (= 13 (:credit (get-corp))) "Paid 2 to play event; gained 7 credits")))
(deftest the-all-seeing-i-prevent-trash
;; Counts number of cards if one card is prevented trashed with fall guy
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 1) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Fall Guy")
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (count (:hand (get-corp)))) "Corp could not play All Seeing I when runner was not tagged")
(core/gain state :runner :tag 1)
(play-from-hand state :corp "The All-Seeing I")
(let [fall-guy (get-resource state 1)]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done")
(is (= 1 (res)) "One installed resource saved by Fall Guy")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap"))))
(deftest the-all-seeing-i-hosted-cards
;; Checks that All-seeing I does not double-trash hosted cards, trashes hosted cards
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 1)])
(default-runner [(qty "Fall Guy" 2) (qty "Off-Campus Apartment" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Off-Campus Apartment")
(let [oca (get-resource state 0)
fg1 (get-in (get-runner) [:hand 0])
fg2 (get-in (get-runner) [:hand 1])]
(card-ability state :runner oca 0)
(prompt-select :runner fg1)
(card-ability state :runner oca 0)
(prompt-select :runner fg2))
(core/gain state :runner :tag 1)
(take-credits state :runner)
(play-from-hand state :corp "The All-Seeing I")
(prompt-choice :runner "Done")
(prompt-choice :runner "Done")
(let [fall-guy (find-card "Fall Guy" (core/all-active-installed state :runner))]
(card-ability state :runner fall-guy 0))
(prompt-choice :runner "Done") ;; This assumes hosted cards get put in trash-list before host
(is (= 1 (count (core/all-active-installed state :runner))) "One installed card (Off-Campus)")
(is (= 2 (count (:discard (get-runner)))) "Two cards in heap")
)
)
(deftest the-all-seeing-i-jarogniew-mercs
;; The All-Seeing I should not trash Jarogniew Mercs if there are other installed resources
(do-game
(new-game (default-corp [(qty "The All-Seeing I" 4)])
(default-runner [(qty "Jarogniew Mercs" 2) (qty "Same Old Thing" 2)]))
(letfn [(res [] (count (get-in (get-runner) [:rig :resource])))]
(take-credits state :corp)
(play-from-hand state :runner "Same Old Thing")
(play-from-hand state :runner "Jarogniew PI:NAME:<NAME>END_PI")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources")
(take-credits state :corp)
(play-from-hand state :runner "Jarogniew Mercs") ;; Testing if order matters
(play-from-hand state :runner "Same Old Thing")
(take-credits state :runner)
(is (= 2 (res)) "There are two installed resources")
(play-from-hand state :corp "The All-Seeing I")
(is (= 1 (res)) "Jarogniew Mercs still installed")
(play-from-hand state :corp "The All-Seeing I")
(is (= 0 (res)) "There are no installed resources"))))
(deftest threat-assessment
;; Threat Assessment - play only if runner trashed a card last turn, move a card to the stack or take 2 tags
(do-game
(new-game (default-corp [(qty "Threat Assessment" 3) (qty "Adonis Campaign" 1)])
(default-runner [(qty "Desperado" 1) (qty "Corroder" 1)]))
(play-from-hand state :corp "Adonis Campaign" "New remote")
(take-credits state :corp)
(run-on state :remote1)
(run-successful state)
(prompt-choice :runner "Yes") ;trash
(core/gain state :runner :credit 5)
(play-from-hand state :runner "Desperado")
(play-from-hand state :runner "Corroder")
(take-credits state :runner)
(is (= 0 (:tag (get-runner))) "Runner starts with 0 tags")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Desperado" (-> (get-runner) :rig :hardware)))
(prompt-choice :runner "2 tags")
(is (= 2 (:tag (get-runner))) "Runner took 2 tags")
(is (= 1 (count (-> (get-runner) :rig :hardware))) "Didn't trash Desperado")
(is (= "Threat Assessment" (:title (first (:rfg (get-corp))))) "Threat Assessment removed from game")
(play-from-hand state :corp "Threat Assessment")
(prompt-select :corp (find-card "Corroder" (-> (get-runner) :rig :program)))
(prompt-choice :runner "Move Corroder")
(is (= 2 (:tag (get-runner))) "Runner didn't take tags")
(is (= "Corroder" (:title (first (:deck (get-runner))))) "Moved Corroder to the deck")
(is (= 2 (count (:rfg (get-corp)))))
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Threat Assessment")
(is (empty? (:prompt (get-corp))) "Threat Assessment triggered with no trash")))
(deftest threat-level-alpha
;; Threat Level Alpha - Win trace to give tags = Runner tags; or 1 tag if 0
(do-game
(new-game (default-corp [(qty "Threat Level Alpha" 2)])
(default-runner))
(core/gain state :corp :click 2)
(core/gain state :corp :credit 2)
(is (= 0 (:tag (get-runner))))
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag because they had 0")
(core/gain state :runner :tag 2)
(play-from-hand state :corp "Threat Level Alpha")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 6 (:tag (get-runner))) "Runner took 3 tag because they had 3")))
(deftest transparency-initiative
;; Transparency Initiative - Full test
(do-game
(new-game (default-corp [(qty "Transparency Initiative" 1) (qty "Oaktown Renovation" 1)
(qty "Project Atlas" 1) (qty "Hostile Takeover" 1) (qty "Casting Call" 1)])
(default-runner))
(core/gain state :corp :click 5)
(play-from-hand state :corp "Oaktown Renovation" "New remote")
(play-from-hand state :corp "Casting Call")
(prompt-select :corp (find-card "Project Atlas" (:hand (get-corp))))
(prompt-choice :corp "New remote")
(play-from-hand state :corp "Hostile Takeover" "New remote")
(let [oaktown (get-content state :remote1 0)
atlas (get-content state :remote2 0)
hostile (get-content state :remote3 0)]
(play-from-hand state :corp "Transparency Initiative")
(prompt-select :corp (refresh oaktown))
;; doesn't work on face-up agendas
(is (= 0 (count (:hosted (refresh oaktown)))))
(prompt-select :corp (refresh atlas))
(is (= 1 (count (:hosted (refresh atlas)))) "Casting Call")
;; works on facedown agenda
(prompt-select :corp (refresh hostile))
(is (= 1 (count (:hosted (refresh hostile)))))
;; gains Public subtype
(is (core/has-subtype? (refresh hostile) "Public"))
;; gain 1 credit when advancing
(is (= 5 (:credit (get-corp))))
(core/advance state :corp {:card (refresh hostile)})
(is (= 5 (:credit (get-corp))))
;; make sure advancing other agendas doesn't gain 1
(core/advance state :corp {:card (refresh oaktown)})
(is (= 6 (:credit (get-corp))) "Transparency initiative didn't fire")
(core/advance state :corp {:card (refresh atlas)})
(is (= 5 (:credit (get-corp))) "Transparency initiative didn't fire"))))
(deftest wake-up-call-en-passant
;; Wake Up Call - should fire after using En Passant to trash ice
(do-game
(new-game (default-corp [(qty "Enigma" 1) (qty "Wake Up Call" 1)])
(default-runner [(qty "En Passant" 1) (qty "Maya" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Maya")
(run-on state :hq)
(run-successful state)
(prompt-choice :runner "Ok")
(is (= 0 (count (:discard (get-corp)))) "Corp starts with no discards")
(play-from-hand state :runner "En Passant")
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (count (:discard (get-corp)))) "Corp trashes installed ice")
(take-credits state :runner)
(is (= 1 (count (:discard (get-runner)))) "Runner starts with 1 trashed card (En Passant)")
(play-from-hand state :corp "Wake Up Call")
(prompt-select :corp (get-in @state [:runner :rig :hardware 0]))
(prompt-choice :runner "Trash Maya")
(is (= 2 (count (:discard (get-runner)))) "Maya is trashed")
(is (= 1 (count (:rfg (get-corp)))) "Wake Up Call is removed from the game")))
(deftest wetwork-refit
;; Wetwork Refit - Only works on Bioroid ICE and adds a subroutine
(do-game
(new-game (default-corp [(qty "Eli 1.0" 1)
(qty "Vanilla" 1)
(qty "Wetwork Refit" 3)])
(default-runner))
(core/gain state :corp :credit 20)
(core/gain state :corp :click 10)
(play-from-hand state :corp "Eli 1.0" "R&D")
(play-from-hand state :corp "Vanilla" "HQ")
(let [eli (get-ice state :rd 0)
vanilla (get-ice state :hq 0)]
(play-from-hand state :corp "Wetwork Refit")
(is (not-any? #{"Eli 1.0"} (get-in @state [:corp :prompt :choices]))
"Unrezzed Eli 1.0 is not a choice to host Wetwork Refit")
(prompt-choice :corp "Done")
(take-credits state :corp)
(take-credits state :runner)
(core/rez state :corp (refresh eli))
(core/rez state :corp (refresh vanilla))
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh eli))
(is (= "Wetwork Refit" (:title (first (:hosted (refresh eli)))))
"Wetwork Refit is hosted on Eli 1.0")
(is (= 2 (count (:subroutines (refresh eli))))
"Eli 1.0 has 2 different subroutines")
(is (= "Do 1 brain damage" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has a brain damage subroutine as his first subroutine")
(core/move state :corp (first (:hosted (refresh eli))) :hand)
(is (empty? (:hosted (refresh eli))) "No cards are hosted on Eli 1.0")
(is (= 1 (count (:subroutines (refresh eli))))
"Eli 1.0 has 1 different subroutine")
(is (= "End the run" (:label (first (:subroutines (refresh eli)))))
"Eli 1.0 has an end the run subroutine as his first subroutine")
(play-from-hand state :corp "Wetwork Refit")
(prompt-select :corp (refresh vanilla))
(is (not= "Wetwork Refit" (:title (first (:hosted (refresh vanilla)))))
"Wetwork Refit is not hosted on Vanilla"))))
|
[
{
"context": ";; Copyright (c) 2020-2021 Saidone\n\n(ns ^:figwheel-hooks wa-tor.core\n (:require\n ",
"end": 34,
"score": 0.9984233379364014,
"start": 27,
"tag": "NAME",
"value": "Saidone"
}
] |
src/wa_tor/core.cljs
|
saidone75/wa-tor
| 6 |
;; Copyright (c) 2020-2021 Saidone
(ns ^:figwheel-hooks wa-tor.core
(:require
[goog.dom :as gdom]
[reagent.dom :as rdom]
[wa-tor.board :as board]))
(defonce app-state (board/create-board!))
(defn get-app-element []
(gdom/getElement "app"))
(defn board []
[:div {:class "outer-div"}
[:div.board {:id "board"}
(board/splash)
(board/usage-panel)
(board/stats-panel)
(board/draw-board)]])
(defn mount [el]
(rdom/render [board] el))
(defn mount-app-element []
(when-let [el (get-app-element)]
(mount el)))
(mount-app-element)
(defn ^:after-load on-reload []
(mount-app-element))
(defn version [] "1.4-SNAPSHOT")
(aset js/window "version" wa-tor.core/version)
|
100739
|
;; Copyright (c) 2020-2021 <NAME>
(ns ^:figwheel-hooks wa-tor.core
(:require
[goog.dom :as gdom]
[reagent.dom :as rdom]
[wa-tor.board :as board]))
(defonce app-state (board/create-board!))
(defn get-app-element []
(gdom/getElement "app"))
(defn board []
[:div {:class "outer-div"}
[:div.board {:id "board"}
(board/splash)
(board/usage-panel)
(board/stats-panel)
(board/draw-board)]])
(defn mount [el]
(rdom/render [board] el))
(defn mount-app-element []
(when-let [el (get-app-element)]
(mount el)))
(mount-app-element)
(defn ^:after-load on-reload []
(mount-app-element))
(defn version [] "1.4-SNAPSHOT")
(aset js/window "version" wa-tor.core/version)
| true |
;; Copyright (c) 2020-2021 PI:NAME:<NAME>END_PI
(ns ^:figwheel-hooks wa-tor.core
(:require
[goog.dom :as gdom]
[reagent.dom :as rdom]
[wa-tor.board :as board]))
(defonce app-state (board/create-board!))
(defn get-app-element []
(gdom/getElement "app"))
(defn board []
[:div {:class "outer-div"}
[:div.board {:id "board"}
(board/splash)
(board/usage-panel)
(board/stats-panel)
(board/draw-board)]])
(defn mount [el]
(rdom/render [board] el))
(defn mount-app-element []
(when-let [el (get-app-element)]
(mount el)))
(mount-app-element)
(defn ^:after-load on-reload []
(mount-app-element))
(defn version [] "1.4-SNAPSHOT")
(aset js/window "version" wa-tor.core/version)
|
[
{
"context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg",
"end": 33,
"score": 0.9998757839202881,
"start": 17,
"tag": "NAME",
"value": "Andrew A. Raines"
},
{
"context": "0\n :threads 1}\n {:from \"[email protected]\"\n :to \"[email protected]\"}\n {:keys [hos",
"end": 1865,
"score": 0.9998779296875,
"start": 1853,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ds 1}\n {:from \"[email protected]\"\n :to \"[email protected]\"}\n {:keys [host port from to num delay thr",
"end": 1893,
"score": 0.9998411536216736,
"start": 1881,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/postal/core.clj
|
poenneby/postal
| 371 |
;; Copyright (c) Andrew A. Raines
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use,
;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following
;; conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;; OTHER DEALINGS IN THE SOFTWARE.
(ns postal.core
(:use [postal.sendmail :only [sendmail-send]]
[postal.smtp :only [smtp-send]]
[postal.stress :only [spam]]))
(defn send-message
([{:keys [host] :as server}
{:keys [from to bcc subject body] :or {to "" subject ""} :as msg}]
(when-not (or (and from to)
(and from bcc))
(throw (Exception. "message needs at least :from and :to or :from and :bcc")))
(if host
(smtp-send server msg)
(sendmail-send msg)))
([msg]
(send-message (meta msg) msg)))
(defn stress [profile]
(let [defaults #^{:host "localhost"
:port 25
:num 1
:delay 100
:threads 1}
{:from "[email protected]"
:to "[email protected]"}
{:keys [host port from to num delay threads]}
(merge (meta defaults) defaults (meta profile) profile)]
(println (format "sent %s msgs to %s:%s"
(spam host port from to num delay threads)
host port))))
|
86319
|
;; Copyright (c) <NAME>
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use,
;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following
;; conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;; OTHER DEALINGS IN THE SOFTWARE.
(ns postal.core
(:use [postal.sendmail :only [sendmail-send]]
[postal.smtp :only [smtp-send]]
[postal.stress :only [spam]]))
(defn send-message
([{:keys [host] :as server}
{:keys [from to bcc subject body] :or {to "" subject ""} :as msg}]
(when-not (or (and from to)
(and from bcc))
(throw (Exception. "message needs at least :from and :to or :from and :bcc")))
(if host
(smtp-send server msg)
(sendmail-send msg)))
([msg]
(send-message (meta msg) msg)))
(defn stress [profile]
(let [defaults #^{:host "localhost"
:port 25
:num 1
:delay 100
:threads 1}
{:from "<EMAIL>"
:to "<EMAIL>"}
{:keys [host port from to num delay threads]}
(merge (meta defaults) defaults (meta profile) profile)]
(println (format "sent %s msgs to %s:%s"
(spam host port from to num delay threads)
host port))))
| true |
;; Copyright (c) PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use,
;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following
;; conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;; OTHER DEALINGS IN THE SOFTWARE.
(ns postal.core
(:use [postal.sendmail :only [sendmail-send]]
[postal.smtp :only [smtp-send]]
[postal.stress :only [spam]]))
(defn send-message
([{:keys [host] :as server}
{:keys [from to bcc subject body] :or {to "" subject ""} :as msg}]
(when-not (or (and from to)
(and from bcc))
(throw (Exception. "message needs at least :from and :to or :from and :bcc")))
(if host
(smtp-send server msg)
(sendmail-send msg)))
([msg]
(send-message (meta msg) msg)))
(defn stress [profile]
(let [defaults #^{:host "localhost"
:port 25
:num 1
:delay 100
:threads 1}
{:from "PI:EMAIL:<EMAIL>END_PI"
:to "PI:EMAIL:<EMAIL>END_PI"}
{:keys [host port from to num delay threads]}
(merge (meta defaults) defaults (meta profile) profile)]
(println (format "sent %s msgs to %s:%s"
(spam host port from to num delay threads)
host port))))
|
[
{
"context": ")))\n\n(def ui-person (prim/factory Person {:keyfn :db/id}))\n\n(defsc People [this {:keys [people]}]\n {:ini",
"end": 2183,
"score": 0.788163959980011,
"start": 2178,
"tag": "KEY",
"value": "db/id"
}
] |
src/book/book/demos/loading_data_basics.cljs
|
levitanong/fulcro
| 0 |
(ns book.demos.loading-data-basics
(:require
[fulcro.client :as fc]
[fulcro.client.data-fetch :as df]
[book.demos.util :refer [now]]
[fulcro.client.mutations :as m]
[fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defsc InitialAppState initial-state]]
[fulcro.client.data-fetch :as df]
[fulcro.server :as server]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def all-users [{:db/id 1 :person/name "A" :kind :friend}
{:db/id 2 :person/name "B" :kind :friend}
{:db/id 3 :person/name "C" :kind :enemy}
{:db/id 4 :person/name "D" :kind :friend}])
(server/defquery-entity :load-samples.person/by-id
(value [{:keys [] :as env} id p]
(let [person (first (filter #(= id (:db/id %)) all-users))]
(assoc person :person/age-ms (now)))))
(server/defquery-root :load-samples/people
(value [env {:keys [kind]}]
(let [result (->> all-users
(filter (fn [p] (= kind (:kind p))))
(mapv (fn [p] (-> p
(select-keys [:db/id :person/name])
(assoc :person/age-ms (now))))))]
result)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defsc Person [this {:keys [db/id person/name person/age-ms] :as props}]
{:query [:db/id :person/name :person/age-ms :ui/fetch-state]
:ident (fn [] [:load-samples.person/by-id id])}
(dom/li
(str name " (last queried at " age-ms ")")
(dom/button {:onClick (fn []
; Load relative to an ident (of this component).
; This will refresh the entity in the db. The helper function
; (df/refresh! this) is identical to this, but shorter to write.
(df/load this (prim/ident this props) Person))} "Update")))
(def ui-person (prim/factory Person {:keyfn :db/id}))
(defsc People [this {:keys [people]}]
{:initial-state (fn [{:keys [kind]}] {:people/kind kind})
:query [:people/kind {:people (prim/get-query Person)}]
:ident [:lists/by-type :people/kind]}
(dom/ul
; we're loading a whole list. To sense/show a loading marker the :ui/fetch-state has to be queried in Person.
; Note the whole list is what we're loading, so the render lambda is a map over all of the incoming people.
(df/lazily-loaded #(map ui-person %) people)))
(def ui-people (prim/factory People {:keyfn :people/kind}))
(defsc Root [this {:keys [friends enemies]}]
{:initial-state (fn [{:keys [kind]}] {:friends (prim/get-initial-state People {:kind :friends})
:enemies (prim/get-initial-state People {:kind :enemies})})
:query [{:enemies (prim/get-query People)} {:friends (prim/get-query People)}]}
(dom/div
(dom/h4 "Friends")
(ui-people friends)
(dom/h4 "Enemies")
(ui-people enemies)))
(defn initialize
"To be used in :started-callback to pre-load things."
[app]
; This is a sample of loading a list of people into a given target, including
; use of params. The generated network query will result in params
; appearing in the server-side query, and :people will be the dispatch
; key. The subquery will also be available (from Person). See the server code above.
(df/load app :load-samples/people Person {:target [:lists/by-type :enemies :people]
:params {:kind :enemy}})
(df/load app :load-samples/people Person {:target [:lists/by-type :friends :people]
:params {:kind :friend}}))
|
64868
|
(ns book.demos.loading-data-basics
(:require
[fulcro.client :as fc]
[fulcro.client.data-fetch :as df]
[book.demos.util :refer [now]]
[fulcro.client.mutations :as m]
[fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defsc InitialAppState initial-state]]
[fulcro.client.data-fetch :as df]
[fulcro.server :as server]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def all-users [{:db/id 1 :person/name "A" :kind :friend}
{:db/id 2 :person/name "B" :kind :friend}
{:db/id 3 :person/name "C" :kind :enemy}
{:db/id 4 :person/name "D" :kind :friend}])
(server/defquery-entity :load-samples.person/by-id
(value [{:keys [] :as env} id p]
(let [person (first (filter #(= id (:db/id %)) all-users))]
(assoc person :person/age-ms (now)))))
(server/defquery-root :load-samples/people
(value [env {:keys [kind]}]
(let [result (->> all-users
(filter (fn [p] (= kind (:kind p))))
(mapv (fn [p] (-> p
(select-keys [:db/id :person/name])
(assoc :person/age-ms (now))))))]
result)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defsc Person [this {:keys [db/id person/name person/age-ms] :as props}]
{:query [:db/id :person/name :person/age-ms :ui/fetch-state]
:ident (fn [] [:load-samples.person/by-id id])}
(dom/li
(str name " (last queried at " age-ms ")")
(dom/button {:onClick (fn []
; Load relative to an ident (of this component).
; This will refresh the entity in the db. The helper function
; (df/refresh! this) is identical to this, but shorter to write.
(df/load this (prim/ident this props) Person))} "Update")))
(def ui-person (prim/factory Person {:keyfn :<KEY>}))
(defsc People [this {:keys [people]}]
{:initial-state (fn [{:keys [kind]}] {:people/kind kind})
:query [:people/kind {:people (prim/get-query Person)}]
:ident [:lists/by-type :people/kind]}
(dom/ul
; we're loading a whole list. To sense/show a loading marker the :ui/fetch-state has to be queried in Person.
; Note the whole list is what we're loading, so the render lambda is a map over all of the incoming people.
(df/lazily-loaded #(map ui-person %) people)))
(def ui-people (prim/factory People {:keyfn :people/kind}))
(defsc Root [this {:keys [friends enemies]}]
{:initial-state (fn [{:keys [kind]}] {:friends (prim/get-initial-state People {:kind :friends})
:enemies (prim/get-initial-state People {:kind :enemies})})
:query [{:enemies (prim/get-query People)} {:friends (prim/get-query People)}]}
(dom/div
(dom/h4 "Friends")
(ui-people friends)
(dom/h4 "Enemies")
(ui-people enemies)))
(defn initialize
"To be used in :started-callback to pre-load things."
[app]
; This is a sample of loading a list of people into a given target, including
; use of params. The generated network query will result in params
; appearing in the server-side query, and :people will be the dispatch
; key. The subquery will also be available (from Person). See the server code above.
(df/load app :load-samples/people Person {:target [:lists/by-type :enemies :people]
:params {:kind :enemy}})
(df/load app :load-samples/people Person {:target [:lists/by-type :friends :people]
:params {:kind :friend}}))
| true |
(ns book.demos.loading-data-basics
(:require
[fulcro.client :as fc]
[fulcro.client.data-fetch :as df]
[book.demos.util :refer [now]]
[fulcro.client.mutations :as m]
[fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defsc InitialAppState initial-state]]
[fulcro.client.data-fetch :as df]
[fulcro.server :as server]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def all-users [{:db/id 1 :person/name "A" :kind :friend}
{:db/id 2 :person/name "B" :kind :friend}
{:db/id 3 :person/name "C" :kind :enemy}
{:db/id 4 :person/name "D" :kind :friend}])
(server/defquery-entity :load-samples.person/by-id
(value [{:keys [] :as env} id p]
(let [person (first (filter #(= id (:db/id %)) all-users))]
(assoc person :person/age-ms (now)))))
(server/defquery-root :load-samples/people
(value [env {:keys [kind]}]
(let [result (->> all-users
(filter (fn [p] (= kind (:kind p))))
(mapv (fn [p] (-> p
(select-keys [:db/id :person/name])
(assoc :person/age-ms (now))))))]
result)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defsc Person [this {:keys [db/id person/name person/age-ms] :as props}]
{:query [:db/id :person/name :person/age-ms :ui/fetch-state]
:ident (fn [] [:load-samples.person/by-id id])}
(dom/li
(str name " (last queried at " age-ms ")")
(dom/button {:onClick (fn []
; Load relative to an ident (of this component).
; This will refresh the entity in the db. The helper function
; (df/refresh! this) is identical to this, but shorter to write.
(df/load this (prim/ident this props) Person))} "Update")))
(def ui-person (prim/factory Person {:keyfn :PI:KEY:<KEY>END_PI}))
(defsc People [this {:keys [people]}]
{:initial-state (fn [{:keys [kind]}] {:people/kind kind})
:query [:people/kind {:people (prim/get-query Person)}]
:ident [:lists/by-type :people/kind]}
(dom/ul
; we're loading a whole list. To sense/show a loading marker the :ui/fetch-state has to be queried in Person.
; Note the whole list is what we're loading, so the render lambda is a map over all of the incoming people.
(df/lazily-loaded #(map ui-person %) people)))
(def ui-people (prim/factory People {:keyfn :people/kind}))
(defsc Root [this {:keys [friends enemies]}]
{:initial-state (fn [{:keys [kind]}] {:friends (prim/get-initial-state People {:kind :friends})
:enemies (prim/get-initial-state People {:kind :enemies})})
:query [{:enemies (prim/get-query People)} {:friends (prim/get-query People)}]}
(dom/div
(dom/h4 "Friends")
(ui-people friends)
(dom/h4 "Enemies")
(ui-people enemies)))
(defn initialize
"To be used in :started-callback to pre-load things."
[app]
; This is a sample of loading a list of people into a given target, including
; use of params. The generated network query will result in params
; appearing in the server-side query, and :people will be the dispatch
; key. The subquery will also be available (from Person). See the server code above.
(df/load app :load-samples/people Person {:target [:lists/by-type :enemies :people]
:params {:kind :enemy}})
(df/load app :load-samples/people Person {:target [:lists/by-type :friends :people]
:params {:kind :friend}}))
|
[
{
"context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: [email protected]\n;; ",
"end": 31,
"score": 0.9998773336410522,
"start": 19,
"tag": "NAME",
"value": "Di Sera Luca"
},
{
"context": " Copyright 2020, Di Sera Luca\n;; Contacts: [email protected]\n;; https://github.com/diseraluc",
"end": 74,
"score": 0.9999316334724426,
"start": 53,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/",
"end": 125,
"score": 0.9996901750564575,
"start": 115,
"tag": "USERNAME",
"value": "diseraluca"
},
{
"context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License",
"end": 197,
"score": 0.9995481967926025,
"start": 175,
"tag": "USERNAME",
"value": "luca-di-sera-200023167"
}
] |
pmal/test/mock/core_test.clj
|
diseraluca/pmal
| 0 |
;; Copyright 2020, Di Sera Luca
;; Contacts: [email protected]
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns mock.core-test
(:require [clojure.test :refer :all]
[mock.core :refer :all]))
(deftest test-mock
(is (function? (mock #'prn (constantly nil)))
"mock called with two argument returns a function.")
(let [result "mocked!"
mocked #'prn
mockf (constantly result)
callee #(mocked :args)]
(is (= result
((mock mocked mockf) callee))
"Calling the function returned by mock with a function as argument, will call the passed in function with each call to mocked substituted with mockf.")
;; TODO: This property must have a name. find it and clean the description.
(is (= (mock mocked mockf callee)
((mock mocked mockf) callee))
"Calling mock with three arguments, let them be arg1,arg2 and arg3, is equivalent to applying mock to arg1 and arg2 and then calling the result with arg3.")))
|
89334
|
;; Copyright 2020, <NAME>
;; Contacts: <EMAIL>
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns mock.core-test
(:require [clojure.test :refer :all]
[mock.core :refer :all]))
(deftest test-mock
(is (function? (mock #'prn (constantly nil)))
"mock called with two argument returns a function.")
(let [result "mocked!"
mocked #'prn
mockf (constantly result)
callee #(mocked :args)]
(is (= result
((mock mocked mockf) callee))
"Calling the function returned by mock with a function as argument, will call the passed in function with each call to mocked substituted with mockf.")
;; TODO: This property must have a name. find it and clean the description.
(is (= (mock mocked mockf callee)
((mock mocked mockf) callee))
"Calling mock with three arguments, let them be arg1,arg2 and arg3, is equivalent to applying mock to arg1 and arg2 and then calling the result with arg3.")))
| true |
;; Copyright 2020, PI:NAME:<NAME>END_PI
;; Contacts: PI:EMAIL:<EMAIL>END_PI
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns mock.core-test
(:require [clojure.test :refer :all]
[mock.core :refer :all]))
(deftest test-mock
(is (function? (mock #'prn (constantly nil)))
"mock called with two argument returns a function.")
(let [result "mocked!"
mocked #'prn
mockf (constantly result)
callee #(mocked :args)]
(is (= result
((mock mocked mockf) callee))
"Calling the function returned by mock with a function as argument, will call the passed in function with each call to mocked substituted with mockf.")
;; TODO: This property must have a name. find it and clean the description.
(is (= (mock mocked mockf callee)
((mock mocked mockf) callee))
"Calling mock with three arguments, let them be arg1,arg2 and arg3, is equivalent to applying mock to arg1 and arg2 and then calling the result with arg3.")))
|
[
{
"context": "-------------------------------------------\n;; (C) Vassil Kateliev, 2021 \t\t(http://www.kateliev.com)\n;;-------------",
"end": 199,
"score": 0.999884307384491,
"start": 184,
"tag": "NAME",
"value": "Vassil Kateliev"
}
] |
cli/clojure/fr-gs-kern-clean/src/fr_gs_kern_clean/core.clj
|
kateliev/FontRig
| 0 |
;; SCRIPT: FontRig: fr-gs-kern-clean
;; NOTE: Clean kerning values withing given range - Glyphs app font format
;; -----------------------------------------------------------
;; (C) Vassil Kateliev, 2021 (http://www.kateliev.com)
;;------------------------------------------------------------
;; No warranties. By using this you agree
;; that you use it at your own risk!
;; - Dependancies -------------------------
(ns fr-gs-kern-clean.core
(:require [clojure.java.io :as io]
[clojure.walk]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as str])
(:import (com.dd.plist NSArray NSDictionary NSNumber NSString PropertyListParser)))
;; - Init ------------------------------
(def application {:name "fr-gs-kern-clean" :version "1.3"})
;; -- CLI Configuration
(def cli-options
;; An option with a required argument
[["-le" "--less-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
["-ge" "--greater-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
;; A boolean option defaulting to nil
["-h" "--help"]])
;; - Objects -----------------------------
;; -- Glyphs parser ----------------------
;; -- NS to Clojure
(defmulti ^:private nsobject->object class)
(defmethod nsobject->object NSNumber [^NSNumber obj]
(cond (.isBoolean obj) (.boolValue obj)
(.isInteger obj) (.longValue obj)
:else (.doubleValue obj)))
(defmethod nsobject->object NSString [^NSString obj]
(.getContent obj))
(defmethod nsobject->object NSArray [^NSArray obj]
(map nsobject->object (.getArray obj)))
(defmethod nsobject->object NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (nsobject->object (.getValue e))])
(.. obj getHashMap entrySet))))
;; --- Clojure to NS
(defmulti ^:private object->nsobject class)
(defmethod object->nsobject :default [obj] (NSNumber. obj))
(defmethod object->nsobject java.lang.String [^java.lang.String obj] (NSString. obj))
(defmethod object->nsobject NSArray [^NSArray obj]
(map object->nsobject (.getArray obj)))
(defmethod object->nsobject NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (object->nsobject (.getValue e))])
(.. obj getHashMap entrySet))))
;; - Functions ----------------------------
(defn remove-kern-value-cond [gs-font-kerning cond-function]
(clojure.walk/postwalk #(if (map? %) (into {} (map cond-function %)) %) gs-font-kerning))
(defn value-check [data filter-below filter-above]
(let [[k v] data]
(when-not (and (string? v)
(or (> filter-above (Integer/parseInt v) 0)
(< 0 (Integer/parseInt v) filter-below)))
[k v])))
(defn rename-file [filename]
(let [filename-split (str/split filename #"\.")]
(str/join "." (concat (drop-last filename-split) ["new"] [(last filename-split)]))))
(defn read-plist [^String source-file]
(nsobject->object
(PropertyListParser/parse source-file)))
(defn read-plist-raw [^String source-file]
(PropertyListParser/parse source-file))
(defn write-plist [object destination-file]
(PropertyListParser/saveAsASCII object (io/file destination-file)))
;; -- Main --------------------------------
(defn -main [& args]
(def cli-options (parse-opts args cli-options))
(def src-file (first (cli-options :arguments)))
;(println cli-options)
;; - Parse glyphs file
(if (.exists (io/file src-file))
((println (format "Processing file: %s" src-file))
;; - Parse file
(def gs-font-source (read-plist src-file))
;; - Process
(def new-kerning
(remove-kern-value-cond
(gs-font-source "kerning")
(fn [x] (value-check x ((cli-options :options) :less-than) ((cli-options :options) :greater-than)))))
(assoc gs-font-source :kerning new-kerning)
(println (type gs-font-source))
(write-plist gs-font-source (rename-file src-file)))
(println (format "%s : Please specify a valid input file and options..." (clojure.string/join " " (vals application))))))
|
93331
|
;; SCRIPT: FontRig: fr-gs-kern-clean
;; NOTE: Clean kerning values withing given range - Glyphs app font format
;; -----------------------------------------------------------
;; (C) <NAME>, 2021 (http://www.kateliev.com)
;;------------------------------------------------------------
;; No warranties. By using this you agree
;; that you use it at your own risk!
;; - Dependancies -------------------------
(ns fr-gs-kern-clean.core
(:require [clojure.java.io :as io]
[clojure.walk]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as str])
(:import (com.dd.plist NSArray NSDictionary NSNumber NSString PropertyListParser)))
;; - Init ------------------------------
(def application {:name "fr-gs-kern-clean" :version "1.3"})
;; -- CLI Configuration
(def cli-options
;; An option with a required argument
[["-le" "--less-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
["-ge" "--greater-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
;; A boolean option defaulting to nil
["-h" "--help"]])
;; - Objects -----------------------------
;; -- Glyphs parser ----------------------
;; -- NS to Clojure
(defmulti ^:private nsobject->object class)
(defmethod nsobject->object NSNumber [^NSNumber obj]
(cond (.isBoolean obj) (.boolValue obj)
(.isInteger obj) (.longValue obj)
:else (.doubleValue obj)))
(defmethod nsobject->object NSString [^NSString obj]
(.getContent obj))
(defmethod nsobject->object NSArray [^NSArray obj]
(map nsobject->object (.getArray obj)))
(defmethod nsobject->object NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (nsobject->object (.getValue e))])
(.. obj getHashMap entrySet))))
;; --- Clojure to NS
(defmulti ^:private object->nsobject class)
(defmethod object->nsobject :default [obj] (NSNumber. obj))
(defmethod object->nsobject java.lang.String [^java.lang.String obj] (NSString. obj))
(defmethod object->nsobject NSArray [^NSArray obj]
(map object->nsobject (.getArray obj)))
(defmethod object->nsobject NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (object->nsobject (.getValue e))])
(.. obj getHashMap entrySet))))
;; - Functions ----------------------------
(defn remove-kern-value-cond [gs-font-kerning cond-function]
(clojure.walk/postwalk #(if (map? %) (into {} (map cond-function %)) %) gs-font-kerning))
(defn value-check [data filter-below filter-above]
(let [[k v] data]
(when-not (and (string? v)
(or (> filter-above (Integer/parseInt v) 0)
(< 0 (Integer/parseInt v) filter-below)))
[k v])))
(defn rename-file [filename]
(let [filename-split (str/split filename #"\.")]
(str/join "." (concat (drop-last filename-split) ["new"] [(last filename-split)]))))
(defn read-plist [^String source-file]
(nsobject->object
(PropertyListParser/parse source-file)))
(defn read-plist-raw [^String source-file]
(PropertyListParser/parse source-file))
(defn write-plist [object destination-file]
(PropertyListParser/saveAsASCII object (io/file destination-file)))
;; -- Main --------------------------------
(defn -main [& args]
(def cli-options (parse-opts args cli-options))
(def src-file (first (cli-options :arguments)))
;(println cli-options)
;; - Parse glyphs file
(if (.exists (io/file src-file))
((println (format "Processing file: %s" src-file))
;; - Parse file
(def gs-font-source (read-plist src-file))
;; - Process
(def new-kerning
(remove-kern-value-cond
(gs-font-source "kerning")
(fn [x] (value-check x ((cli-options :options) :less-than) ((cli-options :options) :greater-than)))))
(assoc gs-font-source :kerning new-kerning)
(println (type gs-font-source))
(write-plist gs-font-source (rename-file src-file)))
(println (format "%s : Please specify a valid input file and options..." (clojure.string/join " " (vals application))))))
| true |
;; SCRIPT: FontRig: fr-gs-kern-clean
;; NOTE: Clean kerning values withing given range - Glyphs app font format
;; -----------------------------------------------------------
;; (C) PI:NAME:<NAME>END_PI, 2021 (http://www.kateliev.com)
;;------------------------------------------------------------
;; No warranties. By using this you agree
;; that you use it at your own risk!
;; - Dependancies -------------------------
(ns fr-gs-kern-clean.core
(:require [clojure.java.io :as io]
[clojure.walk]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as str])
(:import (com.dd.plist NSArray NSDictionary NSNumber NSString PropertyListParser)))
;; - Init ------------------------------
(def application {:name "fr-gs-kern-clean" :version "1.3"})
;; -- CLI Configuration
(def cli-options
;; An option with a required argument
[["-le" "--less-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
["-ge" "--greater-than value" "Kerning Value"
:default 0
:parse-fn #(Integer/parseInt %)]
;; A boolean option defaulting to nil
["-h" "--help"]])
;; - Objects -----------------------------
;; -- Glyphs parser ----------------------
;; -- NS to Clojure
(defmulti ^:private nsobject->object class)
(defmethod nsobject->object NSNumber [^NSNumber obj]
(cond (.isBoolean obj) (.boolValue obj)
(.isInteger obj) (.longValue obj)
:else (.doubleValue obj)))
(defmethod nsobject->object NSString [^NSString obj]
(.getContent obj))
(defmethod nsobject->object NSArray [^NSArray obj]
(map nsobject->object (.getArray obj)))
(defmethod nsobject->object NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (nsobject->object (.getValue e))])
(.. obj getHashMap entrySet))))
;; --- Clojure to NS
(defmulti ^:private object->nsobject class)
(defmethod object->nsobject :default [obj] (NSNumber. obj))
(defmethod object->nsobject java.lang.String [^java.lang.String obj] (NSString. obj))
(defmethod object->nsobject NSArray [^NSArray obj]
(map object->nsobject (.getArray obj)))
(defmethod object->nsobject NSDictionary [^NSDictionary obj]
(into {}
(map (fn [^"java.util.LinkedHashMap$Entry" e]
[(.getKey e) (object->nsobject (.getValue e))])
(.. obj getHashMap entrySet))))
;; - Functions ----------------------------
(defn remove-kern-value-cond [gs-font-kerning cond-function]
(clojure.walk/postwalk #(if (map? %) (into {} (map cond-function %)) %) gs-font-kerning))
(defn value-check [data filter-below filter-above]
(let [[k v] data]
(when-not (and (string? v)
(or (> filter-above (Integer/parseInt v) 0)
(< 0 (Integer/parseInt v) filter-below)))
[k v])))
(defn rename-file [filename]
(let [filename-split (str/split filename #"\.")]
(str/join "." (concat (drop-last filename-split) ["new"] [(last filename-split)]))))
(defn read-plist [^String source-file]
(nsobject->object
(PropertyListParser/parse source-file)))
(defn read-plist-raw [^String source-file]
(PropertyListParser/parse source-file))
(defn write-plist [object destination-file]
(PropertyListParser/saveAsASCII object (io/file destination-file)))
;; -- Main --------------------------------
(defn -main [& args]
(def cli-options (parse-opts args cli-options))
(def src-file (first (cli-options :arguments)))
;(println cli-options)
;; - Parse glyphs file
(if (.exists (io/file src-file))
((println (format "Processing file: %s" src-file))
;; - Parse file
(def gs-font-source (read-plist src-file))
;; - Process
(def new-kerning
(remove-kern-value-cond
(gs-font-source "kerning")
(fn [x] (value-check x ((cli-options :options) :less-than) ((cli-options :options) :greater-than)))))
(assoc gs-font-source :kerning new-kerning)
(println (type gs-font-source))
(write-plist gs-font-source (rename-file src-file)))
(println (format "%s : Please specify a valid input file and options..." (clojure.string/join " " (vals application))))))
|
[
{
"context": "test.clj\n\n \"Testing core features.\"\n\n {:author \"Adam Helinski\"}\n\n (:require [clojure.test :as T]\n [",
"end": 74,
"score": 0.9994447231292725,
"start": 61,
"tag": "NAME",
"value": "Adam Helinski"
}
] |
project/clojurify/src/clj/test/convex/test/clj.clj
|
rosejn/convex.cljc
| 30 |
(ns convex.test.clj
"Testing core features."
{:author "Adam Helinski"}
(:require [clojure.test :as T]
[convex.clj :as $.clj]))
;;;;;;;;;;
(T/deftest foo
(T/is (= 4
(+ 2
2))))
|
26478
|
(ns convex.test.clj
"Testing core features."
{:author "<NAME>"}
(:require [clojure.test :as T]
[convex.clj :as $.clj]))
;;;;;;;;;;
(T/deftest foo
(T/is (= 4
(+ 2
2))))
| true |
(ns convex.test.clj
"Testing core features."
{:author "PI:NAME:<NAME>END_PI"}
(:require [clojure.test :as T]
[convex.clj :as $.clj]))
;;;;;;;;;;
(T/deftest foo
(T/is (= 4
(+ 2
2))))
|
[
{
"context": "]]\n \n ])\n\n(defcard reagent-component\n \"lorenz ipsum\"\n (reagent/as-element [reagent-component-example",
"end": 467,
"score": 0.914070725440979,
"start": 455,
"tag": "NAME",
"value": "lorenz ipsum"
}
] |
env/dev/clj/pinkgorilla/bongo.cljs
|
agilecreativity/gorilla-notebook
| 0 |
(ns pinkgorilla.bongo
(:require
[devcards.core]
[reagent.core :as reagent])
(:require-macros
[devcards.core :as dc :refer [defcard defcard-rg defcard-doc]]))
(defn reagent-component-example []
[:div "hey there"
[:div.flex-auto.sans-serif.f6.bg-white.bb.b--near-white.bw2
[:div.sans-serif.pa2.f7.b.flex.items-center.pointer.hover-opacity-parent
[:span "asdf"]
]]
])
(defcard reagent-component
"lorenz ipsum"
(reagent/as-element [reagent-component-example]))
|
88770
|
(ns pinkgorilla.bongo
(:require
[devcards.core]
[reagent.core :as reagent])
(:require-macros
[devcards.core :as dc :refer [defcard defcard-rg defcard-doc]]))
(defn reagent-component-example []
[:div "hey there"
[:div.flex-auto.sans-serif.f6.bg-white.bb.b--near-white.bw2
[:div.sans-serif.pa2.f7.b.flex.items-center.pointer.hover-opacity-parent
[:span "asdf"]
]]
])
(defcard reagent-component
"<NAME>"
(reagent/as-element [reagent-component-example]))
| true |
(ns pinkgorilla.bongo
(:require
[devcards.core]
[reagent.core :as reagent])
(:require-macros
[devcards.core :as dc :refer [defcard defcard-rg defcard-doc]]))
(defn reagent-component-example []
[:div "hey there"
[:div.flex-auto.sans-serif.f6.bg-white.bb.b--near-white.bw2
[:div.sans-serif.pa2.f7.b.flex.items-center.pointer.hover-opacity-parent
[:span "asdf"]
]]
])
(defcard reagent-component
"PI:NAME:<NAME>END_PI"
(reagent/as-element [reagent-component-example]))
|
[
{
"context": " Rothko Chapel 2\" (:title data)))\n ; (is (= \"William Winant, Deborah Dietrich, Karen Rosenak, David Abel\" (:c",
"end": 406,
"score": 0.9997957944869995,
"start": 392,
"tag": "NAME",
"value": "William Winant"
},
{
"context": "2\" (:title data)))\n ; (is (= \"William Winant, Deborah Dietrich, Karen Rosenak, David Abel\" (:composer data)))))\n",
"end": 424,
"score": 0.9998689293861389,
"start": 408,
"tag": "NAME",
"value": "Deborah Dietrich"
},
{
"context": "\n ; (is (= \"William Winant, Deborah Dietrich, Karen Rosenak, David Abel\" (:composer data)))))\n (testing \"q2 ",
"end": 439,
"score": 0.9998651742935181,
"start": 426,
"tag": "NAME",
"value": "Karen Rosenak"
},
{
"context": " \"William Winant, Deborah Dietrich, Karen Rosenak, David Abel\" (:composer data)))))\n (testing \"q2 parsing\"\n ",
"end": 451,
"score": 0.9997366070747375,
"start": 441,
"tag": "NAME",
"value": "David Abel"
},
{
"context": " Mysteries of Love\" (:title data)))\n (is (= \"Angelo Badalamenti\" (:composer data)))))\n (testing \"yle parsing\"\n ",
"end": 666,
"score": 0.9976407289505005,
"start": 648,
"tag": "NAME",
"value": "Angelo Badalamenti"
},
{
"context": "nia nro 1 c-molli \" (:title data)))\n (is (= \"Brahms, Johannes [1833-1897]\" (:composer data))))))\n",
"end": 850,
"score": 0.6399094462394714,
"start": 847,
"tag": "NAME",
"value": "Bra"
},
{
"context": "nro 1 c-molli \" (:title data)))\n (is (= \"Brahms, Johannes [1833-1897]\" (:composer data))))))\n",
"end": 853,
"score": 0.6278270483016968,
"start": 851,
"tag": "NAME",
"value": "ms"
},
{
"context": " 1 c-molli \" (:title data)))\n (is (= \"Brahms, Johannes [1833-1897]\" (:composer data))))))\n",
"end": 863,
"score": 0.8992857336997986,
"start": 855,
"tag": "NAME",
"value": "Johannes"
}
] |
test/now_playing_api/feed_test.clj
|
bhoggard/now-playing-api
| 0 |
(ns now-playing-api.feed-test
(:require [clojure.test :refer :all]
[cheshire.core :refer :all]
[clojure.xml :as xml]
[now-playing-api.feed :refer :all]))
(deftest test-feed
; (testing "earwaves parsing"
; (let [data (translate-somafm (xml/parse "test/data/earwaves.xml"))]
; (is (= "Feldman: Rothko Chapel 2" (:title data)))
; (is (= "William Winant, Deborah Dietrich, Karen Rosenak, David Abel" (:composer data)))))
(testing "q2 parsing"
(let [data (translate-q2 (parse-string (slurp "test/data/q2.json")))]
(is (= "Blue Velvet: Mysteries of Love" (:title data)))
(is (= "Angelo Badalamenti" (:composer data)))))
(testing "yle parsing"
(let [data (translate-yle (xml/parse "test/data/yle.xml"))]
(is (= "Sinfonia nro 1 c-molli " (:title data)))
(is (= "Brahms, Johannes [1833-1897]" (:composer data))))))
|
57879
|
(ns now-playing-api.feed-test
(:require [clojure.test :refer :all]
[cheshire.core :refer :all]
[clojure.xml :as xml]
[now-playing-api.feed :refer :all]))
(deftest test-feed
; (testing "earwaves parsing"
; (let [data (translate-somafm (xml/parse "test/data/earwaves.xml"))]
; (is (= "Feldman: Rothko Chapel 2" (:title data)))
; (is (= "<NAME>, <NAME>, <NAME>, <NAME>" (:composer data)))))
(testing "q2 parsing"
(let [data (translate-q2 (parse-string (slurp "test/data/q2.json")))]
(is (= "Blue Velvet: Mysteries of Love" (:title data)))
(is (= "<NAME>" (:composer data)))))
(testing "yle parsing"
(let [data (translate-yle (xml/parse "test/data/yle.xml"))]
(is (= "Sinfonia nro 1 c-molli " (:title data)))
(is (= "<NAME>h<NAME>, <NAME> [1833-1897]" (:composer data))))))
| true |
(ns now-playing-api.feed-test
(:require [clojure.test :refer :all]
[cheshire.core :refer :all]
[clojure.xml :as xml]
[now-playing-api.feed :refer :all]))
(deftest test-feed
; (testing "earwaves parsing"
; (let [data (translate-somafm (xml/parse "test/data/earwaves.xml"))]
; (is (= "Feldman: Rothko Chapel 2" (:title data)))
; (is (= "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" (:composer data)))))
(testing "q2 parsing"
(let [data (translate-q2 (parse-string (slurp "test/data/q2.json")))]
(is (= "Blue Velvet: Mysteries of Love" (:title data)))
(is (= "PI:NAME:<NAME>END_PI" (:composer data)))))
(testing "yle parsing"
(let [data (translate-yle (xml/parse "test/data/yle.xml"))]
(is (= "Sinfonia nro 1 c-molli " (:title data)))
(is (= "PI:NAME:<NAME>END_PIhPI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI [1833-1897]" (:composer data))))))
|
[
{
"context": "be derived from very simple assumptions, just like Sherlock Holmes does.\"\n\n \"(We can also decouple complex s",
"end": 835,
"score": 0.552267849445343,
"start": 827,
"tag": "NAME",
"value": "Sherlock"
},
{
"context": "om very simple assumptions, just like Sherlock Holmes does.\"\n\n \"(We can also decouple complex systems ",
"end": 842,
"score": 0.5379151701927185,
"start": 839,
"tag": "NAME",
"value": "mes"
},
{
"context": " [{:db/id \"USA\" :country/code :usa}\n {:db/id \"Robert\" :person/criminal? false :person/name \"Robert\" :p",
"end": 1799,
"score": 0.9990549087524414,
"start": 1793,
"tag": "NAME",
"value": "Robert"
},
{
"context": "id \"Robert\" :person/criminal? false :person/name \"Robert\" :person/citizens-of [{:db/id \"USA\"}]}\n {:db/",
"end": 1845,
"score": 0.9994018077850342,
"start": 1839,
"tag": "NAME",
"value": "Robert"
},
{
"context": "\" :object/type :missiles :object/sold-by {:db/id \"Robert\"}}\n {:db/id \"Sokovia\" :country/code :sokovia ",
"end": 1963,
"score": 0.999677300453186,
"start": 1957,
"tag": "NAME",
"value": "Robert"
},
{
"context": "cur new-db (dec max-iter))))))\n\n(defcard-doc\n \"## Robert's in trouble\"\n\n \"Consider this problem statement:\n",
"end": 3681,
"score": 0.9575105309486389,
"start": 3673,
"tag": "NAME",
"value": "Robert's"
},
{
"context": " missiles, and all the missiles were sold to it by Robert, who is an American citizen.\n >\n > Prove that R",
"end": 3913,
"score": 0.9994743466377258,
"start": 3907,
"tag": "NAME",
"value": "Robert"
},
{
"context": "rt, who is an American citizen.\n >\n > Prove that Robert is criminal\"\n\n \"We collect the evidence at our d",
"end": 3968,
"score": 0.9992406368255615,
"start": 3962,
"tag": "NAME",
"value": "Robert"
},
{
"context": "\n\n(deftest robert-trial-test\n (testing \"We assume Robert is innocent until proven otherwise\"\n (is (= {:",
"end": 5011,
"score": 0.9995579123497009,
"start": 5005,
"tag": "NAME",
"value": "Robert"
},
{
"context": "ime-db (d/pull [:person/criminal?] [:person/name \"Robert\"])))))\n (testing \"We can prove Robert is a crimi",
"end": 5147,
"score": 0.9997239112854004,
"start": 5141,
"tag": "NAME",
"value": "Robert"
},
{
"context": "erson/name \"Robert\"])))))\n (testing \"We can prove Robert is a criminal following a forward chaining infere",
"end": 5186,
"score": 0.998887836933136,
"start": 5180,
"tag": "NAME",
"value": "Robert"
},
{
"context": "rules) (d/pull [:person/criminal?] [:person/name \"Robert\"]))))))\n\n(defcard-doc \"Too bad Robert, computer s",
"end": 5353,
"score": 0.9997153878211975,
"start": 5347,
"tag": "NAME",
"value": "Robert"
},
{
"context": "person/name \"Robert\"]))))))\n\n(defcard-doc \"Too bad Robert, computer says you're a criminal\")\n\n\n\n",
"end": 5391,
"score": 0.9921916127204895,
"start": 5385,
"tag": "NAME",
"value": "Robert"
}
] |
devcards/src/minikusari/tutorial2.cljs
|
frankiesardo/minikusari
| 48 |
(ns minikusari.tutorial2
(:require
[minikusari.core :refer [r]]
[devcards.core]
[datascript.core :as d])
(:require-macros
[devcards.core :as dc :refer [defcard-doc deftest]]
[cljs.test :refer [testing is]]))
(defcard-doc
"# Forward Chaining Inference for the modern detective"
"> Key concepts: `infer` loop"
"We know the basics of minikusari rules, but they don't seem too useful for now, don't they."
"I mean, we can basically transact a bit of extra data whenever some conditions are met, but what can we do with it?"
"Well, everything becomes more interesting when it's recursive: what if the transaction data returned by the rules is added to the db, and then rules are run again against the new db?"
"We can chain facts that can be derived from very simple assumptions, just like Sherlock Holmes does."
"(We can also decouple complex systems where different actions trigger changes to related data sources, like a payment and shipping system causing changes on your order system, but let's just stick to Sherlock for now)")
(def crime-db
(d/db-with
(d/empty-db {:country/code {:db/unique :db.unique/identity}
:person/name {:db/unique :db.unique/identity}
:person/citizens-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/enemy-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/owns {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:object/sold-by {:db/valueType :db.type/ref}})
[{:db/id "USA" :country/code :usa}
{:db/id "Robert" :person/criminal? false :person/name "Robert" :person/citizens-of [{:db/id "USA"}]}
{:db/id "Missiles" :object/type :missiles :object/sold-by {:db/id "Robert"}}
{:db/id "Sokovia" :country/code :sokovia :country/enemy-of [{:db/id "USA"}] :country/owns [{:db/id "Missiles"}]}]))
(def rules
'[;; American law
{:when [[?p :person/american? true]
[?c :country/hostile? true]
[?o :object/weapon? true]
[?i :invoice/seller ?p]
[?i :invoice/buyer ?c]
[?i :invoice/object ?o]]
:then [[:db/add ?p :person/criminal? true]]}
;; A USA citizen is American
{:when [[?p :person/citizens-of ?c]
[?c :country/code :usa]]
:then [[:db/add ?p :person/american? true]]}
;; An enemy is hostile
{:when [[?c1 :country/enemy-of ?c2]
[?c2 :country/code :usa]]
:then [[:db/add ?c1 :country/hostile? true]]}
;; A missile is a weapon
{:when [[?o :object/type :missiles]]
:then [[:db/add ?o :object/weapon? true]]}
;; If someone sold it and someone bought it, there should be an invoice somewhere, right?
{:when [[?c :country/owns ?o]
[?o :object/sold-by ?p]
(not [?i :invoice/object ?o])]
:then [[:db/add "invoice" :invoice/seller ?p]
[:db/add "invoice" :invoice/buyer ?c]
[:db/add "invoice" :invoice/object ?o]]}])
(defn infer
"Takes a db and a list of rules. Returns a new db with all inferred facts.
Keeps adding data derived from the rules to the db until db doesn't change.
Stops after max 100 iterations."
[db rules]
(loop [db db max-iter 100]
(let [tx-data (for [rule rules tx (r rule db)] tx)
new-db (d/db-with db tx-data)]
(cond
(= db new-db) new-db
(= 1 max-iter) new-db
:else (recur new-db (dec max-iter))))))
(defcard-doc
"## Robert's in trouble"
"Consider this problem statement:
> As per the law, it is a crime for an American to sell weapons to hostile nations. Sokovia, an enemy of America, has some missiles, and all the missiles were sold to it by Robert, who is an American citizen.
>
> Prove that Robert is criminal"
"We collect the evidence at our disposal and place it in our crime-db"
(dc/mkdn-pprint-source crime-db)
"We have to add a little bit of schema to this db so we can follow links between countries, objects and people
If we create a rule that matches the definition given by the law, it would look something like"
(dc/mkdn-pprint-code (first rules))
"We have a problem now: our rule does not match the shape of our data. We have to add additional rule that derive more facts until this rule is applicable.
Let's code a basic `infer` loop"
(dc/mkdn-pprint-source infer)
"Now we can keep generating data until we get to the correct shape that matches our initial rule.
Let's add a few more rules, for example: that a missile is a weapon, an enemy is hostile, etc."
(dc/mkdn-pprint-source rules)
"NB: in the last rule there is a `not` exists condition to avoid generating an infinite amount of invoices
Let's see our infer loop in action")
(deftest robert-trial-test
(testing "We assume Robert is innocent until proven otherwise"
(is (= {:person/criminal? false} (-> crime-db (d/pull [:person/criminal?] [:person/name "Robert"])))))
(testing "We can prove Robert is a criminal following a forward chaining inference"
(is (= {:person/criminal? true} (-> crime-db (infer rules) (d/pull [:person/criminal?] [:person/name "Robert"]))))))
(defcard-doc "Too bad Robert, computer says you're a criminal")
|
34571
|
(ns minikusari.tutorial2
(:require
[minikusari.core :refer [r]]
[devcards.core]
[datascript.core :as d])
(:require-macros
[devcards.core :as dc :refer [defcard-doc deftest]]
[cljs.test :refer [testing is]]))
(defcard-doc
"# Forward Chaining Inference for the modern detective"
"> Key concepts: `infer` loop"
"We know the basics of minikusari rules, but they don't seem too useful for now, don't they."
"I mean, we can basically transact a bit of extra data whenever some conditions are met, but what can we do with it?"
"Well, everything becomes more interesting when it's recursive: what if the transaction data returned by the rules is added to the db, and then rules are run again against the new db?"
"We can chain facts that can be derived from very simple assumptions, just like <NAME> Hol<NAME> does."
"(We can also decouple complex systems where different actions trigger changes to related data sources, like a payment and shipping system causing changes on your order system, but let's just stick to Sherlock for now)")
(def crime-db
(d/db-with
(d/empty-db {:country/code {:db/unique :db.unique/identity}
:person/name {:db/unique :db.unique/identity}
:person/citizens-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/enemy-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/owns {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:object/sold-by {:db/valueType :db.type/ref}})
[{:db/id "USA" :country/code :usa}
{:db/id "<NAME>" :person/criminal? false :person/name "<NAME>" :person/citizens-of [{:db/id "USA"}]}
{:db/id "Missiles" :object/type :missiles :object/sold-by {:db/id "<NAME>"}}
{:db/id "Sokovia" :country/code :sokovia :country/enemy-of [{:db/id "USA"}] :country/owns [{:db/id "Missiles"}]}]))
(def rules
'[;; American law
{:when [[?p :person/american? true]
[?c :country/hostile? true]
[?o :object/weapon? true]
[?i :invoice/seller ?p]
[?i :invoice/buyer ?c]
[?i :invoice/object ?o]]
:then [[:db/add ?p :person/criminal? true]]}
;; A USA citizen is American
{:when [[?p :person/citizens-of ?c]
[?c :country/code :usa]]
:then [[:db/add ?p :person/american? true]]}
;; An enemy is hostile
{:when [[?c1 :country/enemy-of ?c2]
[?c2 :country/code :usa]]
:then [[:db/add ?c1 :country/hostile? true]]}
;; A missile is a weapon
{:when [[?o :object/type :missiles]]
:then [[:db/add ?o :object/weapon? true]]}
;; If someone sold it and someone bought it, there should be an invoice somewhere, right?
{:when [[?c :country/owns ?o]
[?o :object/sold-by ?p]
(not [?i :invoice/object ?o])]
:then [[:db/add "invoice" :invoice/seller ?p]
[:db/add "invoice" :invoice/buyer ?c]
[:db/add "invoice" :invoice/object ?o]]}])
(defn infer
"Takes a db and a list of rules. Returns a new db with all inferred facts.
Keeps adding data derived from the rules to the db until db doesn't change.
Stops after max 100 iterations."
[db rules]
(loop [db db max-iter 100]
(let [tx-data (for [rule rules tx (r rule db)] tx)
new-db (d/db-with db tx-data)]
(cond
(= db new-db) new-db
(= 1 max-iter) new-db
:else (recur new-db (dec max-iter))))))
(defcard-doc
"## <NAME> in trouble"
"Consider this problem statement:
> As per the law, it is a crime for an American to sell weapons to hostile nations. Sokovia, an enemy of America, has some missiles, and all the missiles were sold to it by <NAME>, who is an American citizen.
>
> Prove that <NAME> is criminal"
"We collect the evidence at our disposal and place it in our crime-db"
(dc/mkdn-pprint-source crime-db)
"We have to add a little bit of schema to this db so we can follow links between countries, objects and people
If we create a rule that matches the definition given by the law, it would look something like"
(dc/mkdn-pprint-code (first rules))
"We have a problem now: our rule does not match the shape of our data. We have to add additional rule that derive more facts until this rule is applicable.
Let's code a basic `infer` loop"
(dc/mkdn-pprint-source infer)
"Now we can keep generating data until we get to the correct shape that matches our initial rule.
Let's add a few more rules, for example: that a missile is a weapon, an enemy is hostile, etc."
(dc/mkdn-pprint-source rules)
"NB: in the last rule there is a `not` exists condition to avoid generating an infinite amount of invoices
Let's see our infer loop in action")
(deftest robert-trial-test
(testing "We assume <NAME> is innocent until proven otherwise"
(is (= {:person/criminal? false} (-> crime-db (d/pull [:person/criminal?] [:person/name "<NAME>"])))))
(testing "We can prove <NAME> is a criminal following a forward chaining inference"
(is (= {:person/criminal? true} (-> crime-db (infer rules) (d/pull [:person/criminal?] [:person/name "<NAME>"]))))))
(defcard-doc "Too bad <NAME>, computer says you're a criminal")
| true |
(ns minikusari.tutorial2
(:require
[minikusari.core :refer [r]]
[devcards.core]
[datascript.core :as d])
(:require-macros
[devcards.core :as dc :refer [defcard-doc deftest]]
[cljs.test :refer [testing is]]))
(defcard-doc
"# Forward Chaining Inference for the modern detective"
"> Key concepts: `infer` loop"
"We know the basics of minikusari rules, but they don't seem too useful for now, don't they."
"I mean, we can basically transact a bit of extra data whenever some conditions are met, but what can we do with it?"
"Well, everything becomes more interesting when it's recursive: what if the transaction data returned by the rules is added to the db, and then rules are run again against the new db?"
"We can chain facts that can be derived from very simple assumptions, just like PI:NAME:<NAME>END_PI HolPI:NAME:<NAME>END_PI does."
"(We can also decouple complex systems where different actions trigger changes to related data sources, like a payment and shipping system causing changes on your order system, but let's just stick to Sherlock for now)")
(def crime-db
(d/db-with
(d/empty-db {:country/code {:db/unique :db.unique/identity}
:person/name {:db/unique :db.unique/identity}
:person/citizens-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/enemy-of {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:country/owns {:db/cardinality :db.cardinality/many
:db/valueType :db.type/ref}
:object/sold-by {:db/valueType :db.type/ref}})
[{:db/id "USA" :country/code :usa}
{:db/id "PI:NAME:<NAME>END_PI" :person/criminal? false :person/name "PI:NAME:<NAME>END_PI" :person/citizens-of [{:db/id "USA"}]}
{:db/id "Missiles" :object/type :missiles :object/sold-by {:db/id "PI:NAME:<NAME>END_PI"}}
{:db/id "Sokovia" :country/code :sokovia :country/enemy-of [{:db/id "USA"}] :country/owns [{:db/id "Missiles"}]}]))
(def rules
'[;; American law
{:when [[?p :person/american? true]
[?c :country/hostile? true]
[?o :object/weapon? true]
[?i :invoice/seller ?p]
[?i :invoice/buyer ?c]
[?i :invoice/object ?o]]
:then [[:db/add ?p :person/criminal? true]]}
;; A USA citizen is American
{:when [[?p :person/citizens-of ?c]
[?c :country/code :usa]]
:then [[:db/add ?p :person/american? true]]}
;; An enemy is hostile
{:when [[?c1 :country/enemy-of ?c2]
[?c2 :country/code :usa]]
:then [[:db/add ?c1 :country/hostile? true]]}
;; A missile is a weapon
{:when [[?o :object/type :missiles]]
:then [[:db/add ?o :object/weapon? true]]}
;; If someone sold it and someone bought it, there should be an invoice somewhere, right?
{:when [[?c :country/owns ?o]
[?o :object/sold-by ?p]
(not [?i :invoice/object ?o])]
:then [[:db/add "invoice" :invoice/seller ?p]
[:db/add "invoice" :invoice/buyer ?c]
[:db/add "invoice" :invoice/object ?o]]}])
(defn infer
"Takes a db and a list of rules. Returns a new db with all inferred facts.
Keeps adding data derived from the rules to the db until db doesn't change.
Stops after max 100 iterations."
[db rules]
(loop [db db max-iter 100]
(let [tx-data (for [rule rules tx (r rule db)] tx)
new-db (d/db-with db tx-data)]
(cond
(= db new-db) new-db
(= 1 max-iter) new-db
:else (recur new-db (dec max-iter))))))
(defcard-doc
"## PI:NAME:<NAME>END_PI in trouble"
"Consider this problem statement:
> As per the law, it is a crime for an American to sell weapons to hostile nations. Sokovia, an enemy of America, has some missiles, and all the missiles were sold to it by PI:NAME:<NAME>END_PI, who is an American citizen.
>
> Prove that PI:NAME:<NAME>END_PI is criminal"
"We collect the evidence at our disposal and place it in our crime-db"
(dc/mkdn-pprint-source crime-db)
"We have to add a little bit of schema to this db so we can follow links between countries, objects and people
If we create a rule that matches the definition given by the law, it would look something like"
(dc/mkdn-pprint-code (first rules))
"We have a problem now: our rule does not match the shape of our data. We have to add additional rule that derive more facts until this rule is applicable.
Let's code a basic `infer` loop"
(dc/mkdn-pprint-source infer)
"Now we can keep generating data until we get to the correct shape that matches our initial rule.
Let's add a few more rules, for example: that a missile is a weapon, an enemy is hostile, etc."
(dc/mkdn-pprint-source rules)
"NB: in the last rule there is a `not` exists condition to avoid generating an infinite amount of invoices
Let's see our infer loop in action")
(deftest robert-trial-test
(testing "We assume PI:NAME:<NAME>END_PI is innocent until proven otherwise"
(is (= {:person/criminal? false} (-> crime-db (d/pull [:person/criminal?] [:person/name "PI:NAME:<NAME>END_PI"])))))
(testing "We can prove PI:NAME:<NAME>END_PI is a criminal following a forward chaining inference"
(is (= {:person/criminal? true} (-> crime-db (infer rules) (d/pull [:person/criminal?] [:person/name "PI:NAME:<NAME>END_PI"]))))))
(defcard-doc "Too bad PI:NAME:<NAME>END_PI, computer says you're a criminal")
|
[
{
"context": " data))))))\n\n (.emit socket \"conn\" #js {:nick \"notbrent-cljs\"\n :username \"notbren",
"end": 654,
"score": 0.7498388290405273,
"start": 641,
"tag": "USERNAME",
"value": "notbrent-cljs"
},
{
"context": "nt-cljs\"\n :username \"notbrent-cljs\"\n :realname \"brent v",
"end": 710,
"score": 0.9995706677436829,
"start": 697,
"tag": "USERNAME",
"value": "notbrent-cljs"
},
{
"context": "nt-cljs\"\n :realname \"brent vatne\"\n :channels \"#test\"}",
"end": 764,
"score": 0.9996563196182251,
"start": 753,
"tag": "NAME",
"value": "brent vatne"
}
] |
client/cljs/src/shout_client/socket.cljs
|
brentvatne/shout-cljs-client
| 0 |
(ns shout-client.socket
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs.core.async :as async]
[clojure.walk :refer [keywordize-keys]]
[flux.dispatcher :as dispatcher :refer [dispatch!]]))
(def events
["msg" "error" "join" "nick" "network"])
(defn join [socket {:keys [network-id channel]}]
(.emit socket "input" #js {:target network-id :text (str "/join " channel)}))
(defn init []
(let [socket (js/io)]
(.on socket "*"
(fn [data] (let [event (keyword (.-_event data))]
(dispatch! event (keywordize-keys (js->clj data))))))
(.emit socket "conn" #js {:nick "notbrent-cljs"
:username "notbrent-cljs"
:realname "brent vatne"
:channels "#test"})
(.on socket "network" (fn [data]
(go (<! (async/timeout 1000))
(join socket {:network-id (.. data -network -id) :channel "#test"}))))))
|
2944
|
(ns shout-client.socket
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs.core.async :as async]
[clojure.walk :refer [keywordize-keys]]
[flux.dispatcher :as dispatcher :refer [dispatch!]]))
(def events
["msg" "error" "join" "nick" "network"])
(defn join [socket {:keys [network-id channel]}]
(.emit socket "input" #js {:target network-id :text (str "/join " channel)}))
(defn init []
(let [socket (js/io)]
(.on socket "*"
(fn [data] (let [event (keyword (.-_event data))]
(dispatch! event (keywordize-keys (js->clj data))))))
(.emit socket "conn" #js {:nick "notbrent-cljs"
:username "notbrent-cljs"
:realname "<NAME>"
:channels "#test"})
(.on socket "network" (fn [data]
(go (<! (async/timeout 1000))
(join socket {:network-id (.. data -network -id) :channel "#test"}))))))
| true |
(ns shout-client.socket
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs.core.async :as async]
[clojure.walk :refer [keywordize-keys]]
[flux.dispatcher :as dispatcher :refer [dispatch!]]))
(def events
["msg" "error" "join" "nick" "network"])
(defn join [socket {:keys [network-id channel]}]
(.emit socket "input" #js {:target network-id :text (str "/join " channel)}))
(defn init []
(let [socket (js/io)]
(.on socket "*"
(fn [data] (let [event (keyword (.-_event data))]
(dispatch! event (keywordize-keys (js->clj data))))))
(.emit socket "conn" #js {:nick "notbrent-cljs"
:username "notbrent-cljs"
:realname "PI:NAME:<NAME>END_PI"
:channels "#test"})
(.on socket "network" (fn [data]
(go (<! (async/timeout 1000))
(join socket {:network-id (.. data -network -id) :channel "#test"}))))))
|
[
{
"context": "flasj-slsajes___secret___\")\n\n(defonce users {\"user-1\" \"pass-1\"})\n\n(defonce permissions {\"user-1\" \"all\"",
"end": 392,
"score": 0.8587669134140015,
"start": 391,
"tag": "USERNAME",
"value": "1"
},
{
"context": "-slsajes___secret___\")\n\n(defonce users {\"user-1\" \"pass-1\"})\n\n(defonce permissions {\"user-1\" \"all\"\n ",
"end": 401,
"score": 0.6748907566070557,
"start": 395,
"tag": "PASSWORD",
"value": "pass-1"
}
] |
src/clj/fullstack/api.clj
|
danielmarreirosdeoliveira/fullstack-clj
| 0 |
(ns fullstack.api
(:require [ring.util.response :refer [resource-response]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[compojure.core :as c]
[compojure.route :as route]
[fullstack.auth :as auth]
[fullstack.dispatch :as dispatch]))
(defonce secret "salkjflasj-slsajes___secret___")
(defonce users {"user-1" "pass-1"})
(defonce permissions {"user-1" "all"
"anonymous" "none"})
(c/defroutes login-route
(wrap-json-body (auth/make-login-handler secret users)
{:keywords? true}))
(c/defroutes query-route
(-> dispatch/handler
(auth/wrap-permissions secret permissions)
(wrap-json-response)
(wrap-json-body {:keywords? true})))
(c/defroutes app
(c/context "/api" []
(c/POST "/" [] query-route)
(c/POST "/login" [] login-route))
(route/resources "/")
(route/not-found (fn [_req] (resource-response "public/index.html"))))
|
68961
|
(ns fullstack.api
(:require [ring.util.response :refer [resource-response]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[compojure.core :as c]
[compojure.route :as route]
[fullstack.auth :as auth]
[fullstack.dispatch :as dispatch]))
(defonce secret "salkjflasj-slsajes___secret___")
(defonce users {"user-1" "<PASSWORD>"})
(defonce permissions {"user-1" "all"
"anonymous" "none"})
(c/defroutes login-route
(wrap-json-body (auth/make-login-handler secret users)
{:keywords? true}))
(c/defroutes query-route
(-> dispatch/handler
(auth/wrap-permissions secret permissions)
(wrap-json-response)
(wrap-json-body {:keywords? true})))
(c/defroutes app
(c/context "/api" []
(c/POST "/" [] query-route)
(c/POST "/login" [] login-route))
(route/resources "/")
(route/not-found (fn [_req] (resource-response "public/index.html"))))
| true |
(ns fullstack.api
(:require [ring.util.response :refer [resource-response]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[compojure.core :as c]
[compojure.route :as route]
[fullstack.auth :as auth]
[fullstack.dispatch :as dispatch]))
(defonce secret "salkjflasj-slsajes___secret___")
(defonce users {"user-1" "PI:PASSWORD:<PASSWORD>END_PI"})
(defonce permissions {"user-1" "all"
"anonymous" "none"})
(c/defroutes login-route
(wrap-json-body (auth/make-login-handler secret users)
{:keywords? true}))
(c/defroutes query-route
(-> dispatch/handler
(auth/wrap-permissions secret permissions)
(wrap-json-response)
(wrap-json-body {:keywords? true})))
(c/defroutes app
(c/context "/api" []
(c/POST "/" [] query-route)
(c/POST "/login" [] login-route))
(route/resources "/")
(route/not-found (fn [_req] (resource-response "public/index.html"))))
|
[
{
"context": "onfig-val)\n)\n\n(def accounts {\n\t\"ac1\" (ref {:name \"Rajesh\" :balance 5000}) \n\t\"ac2\" (ref {:name \"Brijesh\" :b",
"end": 623,
"score": 0.9996976852416992,
"start": 617,
"tag": "NAME",
"value": "Rajesh"
},
{
"context": "ame \"Rajesh\" :balance 5000}) \n\t\"ac2\" (ref {:name \"Brijesh\" :balance 10000})\n})\n\n;(transfer-money \"ac2\" \"ac1",
"end": 669,
"score": 0.9997773170471191,
"start": 662,
"tag": "NAME",
"value": "Brijesh"
}
] |
proj-b/src/apptest2/core.clj
|
jayaraj-poroor/clojure-training
| 1 |
(ns apptest2.core
(:gen-class)
;Illustrates modular development - requiring from another file.
(:require [apptest2.accounts :as acc] [apptest2.mod.employees :as emp])
(:import (java.io File FileReader))
(:use clojure.tools.trace)
)
;invoking functions "require'ed from another namespace.
(acc/f)
;(emp/f)
;(do-stuff)
(File. "somefile")
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(def config (atom {:name "xyz" :db "abc"}))
(defn add-config [config-key config-val]
(swap! config assoc config-key config-val)
)
(def accounts {
"ac1" (ref {:name "Rajesh" :balance 5000})
"ac2" (ref {:name "Brijesh" :balance 10000})
})
;(transfer-money "ac2" "ac1" 500)
;Useful for debugging - instead of defn use deftrace.
(deftrace update-balance[account delta]
(let [new-balance (+ (:balance account) delta)]
(assoc account :balance new-balance)
)
)
;(update-balance (accounts "ac1") 50)
;Illustrates refs and STM
(defn transfer-money [from to amount]
(let [from-ac (accounts from) to-ac (accounts to)]
(dosync
(alter from-ac update-balance (- amount))
(alter to-ac update-balance amount)
)
)
)
|
11044
|
(ns apptest2.core
(:gen-class)
;Illustrates modular development - requiring from another file.
(:require [apptest2.accounts :as acc] [apptest2.mod.employees :as emp])
(:import (java.io File FileReader))
(:use clojure.tools.trace)
)
;invoking functions "require'ed from another namespace.
(acc/f)
;(emp/f)
;(do-stuff)
(File. "somefile")
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(def config (atom {:name "xyz" :db "abc"}))
(defn add-config [config-key config-val]
(swap! config assoc config-key config-val)
)
(def accounts {
"ac1" (ref {:name "<NAME>" :balance 5000})
"ac2" (ref {:name "<NAME>" :balance 10000})
})
;(transfer-money "ac2" "ac1" 500)
;Useful for debugging - instead of defn use deftrace.
(deftrace update-balance[account delta]
(let [new-balance (+ (:balance account) delta)]
(assoc account :balance new-balance)
)
)
;(update-balance (accounts "ac1") 50)
;Illustrates refs and STM
(defn transfer-money [from to amount]
(let [from-ac (accounts from) to-ac (accounts to)]
(dosync
(alter from-ac update-balance (- amount))
(alter to-ac update-balance amount)
)
)
)
| true |
(ns apptest2.core
(:gen-class)
;Illustrates modular development - requiring from another file.
(:require [apptest2.accounts :as acc] [apptest2.mod.employees :as emp])
(:import (java.io File FileReader))
(:use clojure.tools.trace)
)
;invoking functions "require'ed from another namespace.
(acc/f)
;(emp/f)
;(do-stuff)
(File. "somefile")
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(def config (atom {:name "xyz" :db "abc"}))
(defn add-config [config-key config-val]
(swap! config assoc config-key config-val)
)
(def accounts {
"ac1" (ref {:name "PI:NAME:<NAME>END_PI" :balance 5000})
"ac2" (ref {:name "PI:NAME:<NAME>END_PI" :balance 10000})
})
;(transfer-money "ac2" "ac1" 500)
;Useful for debugging - instead of defn use deftrace.
(deftrace update-balance[account delta]
(let [new-balance (+ (:balance account) delta)]
(assoc account :balance new-balance)
)
)
;(update-balance (accounts "ac1") 50)
;Illustrates refs and STM
(defn transfer-money [from to amount]
(let [from-ac (accounts from) to-ac (accounts to)]
(dosync
(alter from-ac update-balance (- amount))
(alter to-ac update-balance amount)
)
)
)
|
[
{
"context": "y\n;because the buffers are large.\n(ns ^{ :author \"Alex Seewald\" }\n philharmonia-samples.sampled-saxophone\n (:u",
"end": 198,
"score": 0.9998767971992493,
"start": 186,
"tag": "NAME",
"value": "Alex Seewald"
}
] |
data/train/clojure/57956302bee4d91f1bcbf2831e9c936eb228d4e1sampled_saxophone.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-saxophone
(:use [philharmonia-samples.sample-utils]
[overtone.live]))
(def saxophone-samples (path-to-described-samples (str sampleroot "/saxophone")))
(def defaults (array-map :note "64" :duration "025" :loudness "forte" :style "normal"))
(def features (featureset [:note :duration :loudness :style] (keys saxophone-samples)))
(def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6})
(def ^:private tmp (play-gen saxophone-samples defaults features distance-maxes))
(def saxophone (:ugen tmp))
(def saxophone-inst (:effect tmp))
(def saxophonei (:effect tmp))
|
14070
|
;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-saxophone
(:use [philharmonia-samples.sample-utils]
[overtone.live]))
(def saxophone-samples (path-to-described-samples (str sampleroot "/saxophone")))
(def defaults (array-map :note "64" :duration "025" :loudness "forte" :style "normal"))
(def features (featureset [:note :duration :loudness :style] (keys saxophone-samples)))
(def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6})
(def ^:private tmp (play-gen saxophone-samples defaults features distance-maxes))
(def saxophone (:ugen tmp))
(def saxophone-inst (:effect tmp))
(def saxophonei (: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-saxophone
(:use [philharmonia-samples.sample-utils]
[overtone.live]))
(def saxophone-samples (path-to-described-samples (str sampleroot "/saxophone")))
(def defaults (array-map :note "64" :duration "025" :loudness "forte" :style "normal"))
(def features (featureset [:note :duration :loudness :style] (keys saxophone-samples)))
(def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6})
(def ^:private tmp (play-gen saxophone-samples defaults features distance-maxes))
(def saxophone (:ugen tmp))
(def saxophone-inst (:effect tmp))
(def saxophonei (:effect tmp))
|
[
{
"context": "r 176)\n :data-key \"water-temperature\"\n :id \"water",
"end": 1488,
"score": 0.8572607040405273,
"start": 1471,
"tag": "KEY",
"value": "water-temperature"
}
] |
src/main/app/ui/dashboard/water_temperature.cljs
|
joshuawood2894/fulcro_postgresql_mqtt_template
| 0 |
(ns app.ui.dashboard.water-temperature
(:require
[app.model.dashboard.water-temperature :as mwt]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.water-temperature :as dl]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]))
(defsc WaterTemperatureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Water Temperature in Degrees
Celsius"
mwt/toggle-water-temperature-settings! (:toggle-settings props))
:cover (if (empty? (:water-temperature props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:water-temperature props)
:x-axis-label "Time"
:y-axis-label "Water Temperature"
:unit-symbol (char 176)
:data-key "water-temperature"
:id "water-temperature-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mwt/set-water-temperature-start-end-datetime!
mwt/set-water-temperature-color!
mwt/set-water-temperature-min-bound!
mwt/set-water-temperature-max-bound!
mwt/redo-water-temperature-min-max-bound!
(:chart-type props)
mwt/set-water-temperature-chart-type!)}))
(def ui-water-temperature-chart (comp/factory WaterTemperatureChart))
(defsc WaterTemperatureData [this {:water-temperature-data/keys [water-temperature
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:water-temperature-data/water-temperature (comp/get-query dl/WaterTemperatureReading)}
:water-temperature-data/start-date :water-temperature-data/end-date
:water-temperature-data/toggle-settings :water-temperature-data/color
:water-temperature-data/min-bound :water-temperature-data/max-bound
:water-temperature-data/chart-type]
:ident (fn [] [:component/id :water-temperature-data])
:initial-state {:water-temperature-data/toggle-settings false
:water-temperature-data/min-bound js/NaN
:water-temperature-data/max-bound js/NaN
:water-temperature-data/chart-type "line"
:water-temperature-data/color ant/blue-primary
:water-temperature-data/start-date (js/Date.)
:water-temperature-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:water-temperature-data/water-temperature [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:water-temperature 22}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:water-temperature 22}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:water-temperature 23}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:water-temperature 21}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:water-temperature 20}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:water-temperature 18}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:water-temperature 19}]}}
(ui-water-temperature-chart {:water-temperature water-temperature
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-water-temperature-data (comp/factory WaterTemperatureData))
|
5223
|
(ns app.ui.dashboard.water-temperature
(:require
[app.model.dashboard.water-temperature :as mwt]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.water-temperature :as dl]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]))
(defsc WaterTemperatureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Water Temperature in Degrees
Celsius"
mwt/toggle-water-temperature-settings! (:toggle-settings props))
:cover (if (empty? (:water-temperature props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:water-temperature props)
:x-axis-label "Time"
:y-axis-label "Water Temperature"
:unit-symbol (char 176)
:data-key "<KEY>"
:id "water-temperature-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mwt/set-water-temperature-start-end-datetime!
mwt/set-water-temperature-color!
mwt/set-water-temperature-min-bound!
mwt/set-water-temperature-max-bound!
mwt/redo-water-temperature-min-max-bound!
(:chart-type props)
mwt/set-water-temperature-chart-type!)}))
(def ui-water-temperature-chart (comp/factory WaterTemperatureChart))
(defsc WaterTemperatureData [this {:water-temperature-data/keys [water-temperature
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:water-temperature-data/water-temperature (comp/get-query dl/WaterTemperatureReading)}
:water-temperature-data/start-date :water-temperature-data/end-date
:water-temperature-data/toggle-settings :water-temperature-data/color
:water-temperature-data/min-bound :water-temperature-data/max-bound
:water-temperature-data/chart-type]
:ident (fn [] [:component/id :water-temperature-data])
:initial-state {:water-temperature-data/toggle-settings false
:water-temperature-data/min-bound js/NaN
:water-temperature-data/max-bound js/NaN
:water-temperature-data/chart-type "line"
:water-temperature-data/color ant/blue-primary
:water-temperature-data/start-date (js/Date.)
:water-temperature-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:water-temperature-data/water-temperature [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:water-temperature 22}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:water-temperature 22}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:water-temperature 23}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:water-temperature 21}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:water-temperature 20}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:water-temperature 18}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:water-temperature 19}]}}
(ui-water-temperature-chart {:water-temperature water-temperature
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-water-temperature-data (comp/factory WaterTemperatureData))
| true |
(ns app.ui.dashboard.water-temperature
(:require
[app.model.dashboard.water-temperature :as mwt]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.water-temperature :as dl]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]))
(defsc WaterTemperatureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Water Temperature in Degrees
Celsius"
mwt/toggle-water-temperature-settings! (:toggle-settings props))
:cover (if (empty? (:water-temperature props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:water-temperature props)
:x-axis-label "Time"
:y-axis-label "Water Temperature"
:unit-symbol (char 176)
:data-key "PI:KEY:<KEY>END_PI"
:id "water-temperature-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mwt/set-water-temperature-start-end-datetime!
mwt/set-water-temperature-color!
mwt/set-water-temperature-min-bound!
mwt/set-water-temperature-max-bound!
mwt/redo-water-temperature-min-max-bound!
(:chart-type props)
mwt/set-water-temperature-chart-type!)}))
(def ui-water-temperature-chart (comp/factory WaterTemperatureChart))
(defsc WaterTemperatureData [this {:water-temperature-data/keys [water-temperature
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:water-temperature-data/water-temperature (comp/get-query dl/WaterTemperatureReading)}
:water-temperature-data/start-date :water-temperature-data/end-date
:water-temperature-data/toggle-settings :water-temperature-data/color
:water-temperature-data/min-bound :water-temperature-data/max-bound
:water-temperature-data/chart-type]
:ident (fn [] [:component/id :water-temperature-data])
:initial-state {:water-temperature-data/toggle-settings false
:water-temperature-data/min-bound js/NaN
:water-temperature-data/max-bound js/NaN
:water-temperature-data/chart-type "line"
:water-temperature-data/color ant/blue-primary
:water-temperature-data/start-date (js/Date.)
:water-temperature-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:water-temperature-data/water-temperature [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:water-temperature 22}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:water-temperature 22}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:water-temperature 23}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:water-temperature 21}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:water-temperature 20}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:water-temperature 18}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:water-temperature 19}]}}
(ui-water-temperature-chart {:water-temperature water-temperature
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-water-temperature-data (comp/factory WaterTemperatureData))
|
[
{
"context": "on.types ObjectId]))\n\n(def uid \"mongo\")\n(def pwd \"secret\")\n\n(DateTimeZone/setDefault DateTimeZone/UTC)\n\n(d",
"end": 672,
"score": 0.9994483590126038,
"start": 666,
"tag": "PASSWORD",
"value": "secret"
}
] |
src/notes/handler.clj
|
citerus/notes
| 3 |
(ns notes.handler
(:use [notes.paas]
[compojure.core]
[hiccup.core]
[hiccup.form]
[hiccup.page]
[hiccup.element]
[hiccup.util]
[ring.util.response]
[clj-time.core :only [now]])
(:require [clojure.string :as s]
[compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.io :as io]
[monger.core :as mg]
[monger.collection :as mc]
[monger.query :as mq]
[monger.joda-time]
[ring.adapter.jetty :as jetty])
(:import [org.joda.time DateTime DateTimeZone]
[org.bson.types ObjectId]))
(def uid "mongo")
(def pwd "secret")
(DateTimeZone/setDefault DateTimeZone/UTC)
(defn connect-mongo! []
(mg/connect-via-uri! (mongo-connection-uri uid pwd)))
(defn save-note! [note]
(mc/insert "notes" note))
(defn find-notes []
(mq/with-collection "notes"
(mq/find {})
(mq/sort {:ts -1})))
(defn delete-note! [id]
(mc/remove-by-id "notes" (ObjectId. id)))
(defn front-page [notes]
(html
(html5
[:head [:title "Notes"]
(include-css "css/bootstrap.min.css")
(include-css "css/notes.css")
(include-css "css/jquery-ui-1.10.2.custom.min.css")]
[:body [:div.navbar.navbar-fixed-top [:div.navbar-inner [:div.container (link-to {:class "brand"} "#" "Notes!")]]]
[:header
[:div.container (image {:id "note"} "img/note.png")
[:div#header-txt [:h1 "Notes!"]
[:p.lead [:small " Create and read awesome notes, right here!"]]]]]
[:div.container
[:div.row-fluid
[:div.span4 [:div#add-note.affix-top {:data-spy "affix", :data-offset-top "215"}
(form-to [:post "./"]
[:fieldset [:label "Heading"]
(text-field :heading )
[:label "Note"]
(text-area {:rows 5} :body )
[:button.btn {:type "submit"} "Create Note!"]])]]
[:div.span8 (for [{:keys [_id, heading, body, added? ts]} notes]
[(if added? :div#added.note :div.note) [:div.row-fluid [:div.span11 [:legend (escape-html heading)]]
[:div.span1 [:div.del (form-to [:delete "./"] (hidden-field :id _id) [:button.btn.btn-mini.btn-link {:type "submit"} [:i.icon-remove ]])]]]
[:div (s/replace (escape-html body) #"\n" "<br>")]
[:p.text-info [:small ts]]])]]]
[:footer
[:div.container
[:p.muted.credit (if-let [name (node-name)] (str "Node " name)) " " [:i.icon-star-empty ] " By " (link-to "http://www.citerus.se/" "Citerus") " " [:i.icon-star-empty ]
" Styling support by " (link-to "http://twitter.github.com/bootstrap/index.html" "Bootstrap. ") [:i.icon-star-empty ]
" Icons by " (link-to "http://glyphicons.com/" "Glyphicons")]]]
(include-js "js/jquery-1.9.1.min.js", "js/jquery-ui-1.10.2.custom.min.js", "js/bootstrap.min.js", "js/notes.js")])))
(defroutes app-routes
(GET "/" [] (front-page (find-notes)))
(POST "/" [heading body]
(do
(save-note! {:heading heading :body body :ts (now)})
(let [notes (find-notes)]
(front-page (cons (assoc (first notes) :added? true) (rest notes))))))
(DELETE "/" [id]
(do
(delete-note! id)
(front-page (find-notes))))
(route/resources "/")
(route/not-found "Not Found"))
(def app (handler/site app-routes))
(defn init [](connect-mongo!))
(defn -main [port]
(do
(connect-mongo!)
(jetty/run-jetty app {:port (Integer. port)})))
|
86861
|
(ns notes.handler
(:use [notes.paas]
[compojure.core]
[hiccup.core]
[hiccup.form]
[hiccup.page]
[hiccup.element]
[hiccup.util]
[ring.util.response]
[clj-time.core :only [now]])
(:require [clojure.string :as s]
[compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.io :as io]
[monger.core :as mg]
[monger.collection :as mc]
[monger.query :as mq]
[monger.joda-time]
[ring.adapter.jetty :as jetty])
(:import [org.joda.time DateTime DateTimeZone]
[org.bson.types ObjectId]))
(def uid "mongo")
(def pwd "<PASSWORD>")
(DateTimeZone/setDefault DateTimeZone/UTC)
(defn connect-mongo! []
(mg/connect-via-uri! (mongo-connection-uri uid pwd)))
(defn save-note! [note]
(mc/insert "notes" note))
(defn find-notes []
(mq/with-collection "notes"
(mq/find {})
(mq/sort {:ts -1})))
(defn delete-note! [id]
(mc/remove-by-id "notes" (ObjectId. id)))
(defn front-page [notes]
(html
(html5
[:head [:title "Notes"]
(include-css "css/bootstrap.min.css")
(include-css "css/notes.css")
(include-css "css/jquery-ui-1.10.2.custom.min.css")]
[:body [:div.navbar.navbar-fixed-top [:div.navbar-inner [:div.container (link-to {:class "brand"} "#" "Notes!")]]]
[:header
[:div.container (image {:id "note"} "img/note.png")
[:div#header-txt [:h1 "Notes!"]
[:p.lead [:small " Create and read awesome notes, right here!"]]]]]
[:div.container
[:div.row-fluid
[:div.span4 [:div#add-note.affix-top {:data-spy "affix", :data-offset-top "215"}
(form-to [:post "./"]
[:fieldset [:label "Heading"]
(text-field :heading )
[:label "Note"]
(text-area {:rows 5} :body )
[:button.btn {:type "submit"} "Create Note!"]])]]
[:div.span8 (for [{:keys [_id, heading, body, added? ts]} notes]
[(if added? :div#added.note :div.note) [:div.row-fluid [:div.span11 [:legend (escape-html heading)]]
[:div.span1 [:div.del (form-to [:delete "./"] (hidden-field :id _id) [:button.btn.btn-mini.btn-link {:type "submit"} [:i.icon-remove ]])]]]
[:div (s/replace (escape-html body) #"\n" "<br>")]
[:p.text-info [:small ts]]])]]]
[:footer
[:div.container
[:p.muted.credit (if-let [name (node-name)] (str "Node " name)) " " [:i.icon-star-empty ] " By " (link-to "http://www.citerus.se/" "Citerus") " " [:i.icon-star-empty ]
" Styling support by " (link-to "http://twitter.github.com/bootstrap/index.html" "Bootstrap. ") [:i.icon-star-empty ]
" Icons by " (link-to "http://glyphicons.com/" "Glyphicons")]]]
(include-js "js/jquery-1.9.1.min.js", "js/jquery-ui-1.10.2.custom.min.js", "js/bootstrap.min.js", "js/notes.js")])))
(defroutes app-routes
(GET "/" [] (front-page (find-notes)))
(POST "/" [heading body]
(do
(save-note! {:heading heading :body body :ts (now)})
(let [notes (find-notes)]
(front-page (cons (assoc (first notes) :added? true) (rest notes))))))
(DELETE "/" [id]
(do
(delete-note! id)
(front-page (find-notes))))
(route/resources "/")
(route/not-found "Not Found"))
(def app (handler/site app-routes))
(defn init [](connect-mongo!))
(defn -main [port]
(do
(connect-mongo!)
(jetty/run-jetty app {:port (Integer. port)})))
| true |
(ns notes.handler
(:use [notes.paas]
[compojure.core]
[hiccup.core]
[hiccup.form]
[hiccup.page]
[hiccup.element]
[hiccup.util]
[ring.util.response]
[clj-time.core :only [now]])
(:require [clojure.string :as s]
[compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.io :as io]
[monger.core :as mg]
[monger.collection :as mc]
[monger.query :as mq]
[monger.joda-time]
[ring.adapter.jetty :as jetty])
(:import [org.joda.time DateTime DateTimeZone]
[org.bson.types ObjectId]))
(def uid "mongo")
(def pwd "PI:PASSWORD:<PASSWORD>END_PI")
(DateTimeZone/setDefault DateTimeZone/UTC)
(defn connect-mongo! []
(mg/connect-via-uri! (mongo-connection-uri uid pwd)))
(defn save-note! [note]
(mc/insert "notes" note))
(defn find-notes []
(mq/with-collection "notes"
(mq/find {})
(mq/sort {:ts -1})))
(defn delete-note! [id]
(mc/remove-by-id "notes" (ObjectId. id)))
(defn front-page [notes]
(html
(html5
[:head [:title "Notes"]
(include-css "css/bootstrap.min.css")
(include-css "css/notes.css")
(include-css "css/jquery-ui-1.10.2.custom.min.css")]
[:body [:div.navbar.navbar-fixed-top [:div.navbar-inner [:div.container (link-to {:class "brand"} "#" "Notes!")]]]
[:header
[:div.container (image {:id "note"} "img/note.png")
[:div#header-txt [:h1 "Notes!"]
[:p.lead [:small " Create and read awesome notes, right here!"]]]]]
[:div.container
[:div.row-fluid
[:div.span4 [:div#add-note.affix-top {:data-spy "affix", :data-offset-top "215"}
(form-to [:post "./"]
[:fieldset [:label "Heading"]
(text-field :heading )
[:label "Note"]
(text-area {:rows 5} :body )
[:button.btn {:type "submit"} "Create Note!"]])]]
[:div.span8 (for [{:keys [_id, heading, body, added? ts]} notes]
[(if added? :div#added.note :div.note) [:div.row-fluid [:div.span11 [:legend (escape-html heading)]]
[:div.span1 [:div.del (form-to [:delete "./"] (hidden-field :id _id) [:button.btn.btn-mini.btn-link {:type "submit"} [:i.icon-remove ]])]]]
[:div (s/replace (escape-html body) #"\n" "<br>")]
[:p.text-info [:small ts]]])]]]
[:footer
[:div.container
[:p.muted.credit (if-let [name (node-name)] (str "Node " name)) " " [:i.icon-star-empty ] " By " (link-to "http://www.citerus.se/" "Citerus") " " [:i.icon-star-empty ]
" Styling support by " (link-to "http://twitter.github.com/bootstrap/index.html" "Bootstrap. ") [:i.icon-star-empty ]
" Icons by " (link-to "http://glyphicons.com/" "Glyphicons")]]]
(include-js "js/jquery-1.9.1.min.js", "js/jquery-ui-1.10.2.custom.min.js", "js/bootstrap.min.js", "js/notes.js")])))
(defroutes app-routes
(GET "/" [] (front-page (find-notes)))
(POST "/" [heading body]
(do
(save-note! {:heading heading :body body :ts (now)})
(let [notes (find-notes)]
(front-page (cons (assoc (first notes) :added? true) (rest notes))))))
(DELETE "/" [id]
(do
(delete-note! id)
(front-page (find-notes))))
(route/resources "/")
(route/not-found "Not Found"))
(def app (handler/site app-routes))
(defn init [](connect-mongo!))
(defn -main [port]
(do
(connect-mongo!)
(jetty/run-jetty app {:port (Integer. port)})))
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<[email protected]>)\n;; Copyright:: Copyright (c)",
"end": 25,
"score": 0.9998548626899719,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<[email protected]>)\n;; Copyright:: Copyright (c) 2011 Opscode, Inc.",
"end": 44,
"score": 0.9999307990074158,
"start": 28,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
config/software/chef-server-cookbooks.clj
|
racker/omnibus
| 2 |
;;
;; Author:: Adam Jacob (<[email protected]>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server-cookbooks" :source "chef-server-cookbooks"
:steps [
{:command "mkdir" :args [ "-p" "/opt/opscode/embedded/cookbooks" ]}
{:command "bash" :args [ "-c" "cp -ra * /opt/opscode/embedded/cookbooks/" ] }
{:command "ln" :args [ "-sf" "/opt/opscode/embedded/cookbooks/bin/chef-server-ctl" "/opt/opscode/bin/chef-server-ctl" ] }
])
|
71143
|
;;
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server-cookbooks" :source "chef-server-cookbooks"
:steps [
{:command "mkdir" :args [ "-p" "/opt/opscode/embedded/cookbooks" ]}
{:command "bash" :args [ "-c" "cp -ra * /opt/opscode/embedded/cookbooks/" ] }
{:command "ln" :args [ "-sf" "/opt/opscode/embedded/cookbooks/bin/chef-server-ctl" "/opt/opscode/bin/chef-server-ctl" ] }
])
| true |
;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server-cookbooks" :source "chef-server-cookbooks"
:steps [
{:command "mkdir" :args [ "-p" "/opt/opscode/embedded/cookbooks" ]}
{:command "bash" :args [ "-c" "cp -ra * /opt/opscode/embedded/cookbooks/" ] }
{:command "ln" :args [ "-sf" "/opt/opscode/embedded/cookbooks/bin/chef-server-ctl" "/opt/opscode/bin/chef-server-ctl" ] }
])
|
[
{
"context": " :swagger/default \"Martin scorcose\"\n }\n ",
"end": 1661,
"score": 0.999876081943512,
"start": 1646,
"tag": "NAME",
"value": "Martin scorcose"
},
{
"context": " :actors (create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\")\n",
"end": 2434,
"score": 0.9998882412910461,
"start": 2422,
"tag": "NAME",
"value": "Ryan Gosling"
},
{
"context": " :actors (create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\")\n\n\n ",
"end": 2450,
"score": 0.9998815655708313,
"start": 2436,
"tag": "NAME",
"value": "Rudy Eisenzopf"
},
{
"context": "create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\")\n\n\n })\n\n\n(s/def",
"end": 2464,
"score": 0.9998735189437866,
"start": 2452,
"tag": "NAME",
"value": "Casey Groves"
},
{
"context": "fault \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\")\n\n\n })\n\n\n(s/defschema UpdateMovi",
"end": 2481,
"score": 0.9998624920845032,
"start": 2466,
"tag": "NAME",
"value": "Charlie Talbert"
},
{
"context": " :actors (create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\") ",
"end": 4220,
"score": 0.9998899698257446,
"start": 4208,
"tag": "NAME",
"value": "Ryan Gosling"
},
{
"context": " :actors (create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\") ,\n ",
"end": 4236,
"score": 0.9998776316642761,
"start": 4222,
"tag": "NAME",
"value": "Rudy Eisenzopf"
},
{
"context": "create-with-default \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\") ,\n :id int?",
"end": 4250,
"score": 0.9998584985733032,
"start": 4238,
"tag": "NAME",
"value": "Casey Groves"
},
{
"context": "fault \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\") ,\n :id int?\n\n ",
"end": 4267,
"score": 0.9998632669448853,
"start": 4252,
"tag": "NAME",
"value": "Charlie Talbert"
}
] |
workspace/moviebookingappv1/src/clj/moviebookingappv1/routes/apis.clj
|
muthuishere/clojure-web-fundamentals
| 0 |
(ns moviebookingappv1.routes.apis
(:require
[reitit.swagger :as swagger]
[clojure.java.io :as io]
[reitit.swagger-ui :as swagger-ui]
[reitit.ring.coercion :as coercion]
[reitit.coercion.spec :as spec-coercion]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.multipart :as multipart]
[reitit.ring.middleware.parameters :as parameters]
[moviebookingappv1.middleware.formats :as formats]
[ring.util.http-response :refer :all]
[moviebookingappv1.services.movies :refer :all]
[clojure.java.io :as io]
[schema.core :as s]
[clojure.spec.alpha :as spec]
[spec-tools.core :as spec-core]
))
;
;(clojure.spec.alpha/def ::results
; (spec-tools.core/spec
; {:spec (clojure.spec.alpha/and int? #(< 0 % 100))
; :description "between 1-100"
; :swagger/default 10
; :reason "invalid number"}))
; [clojure.spec.alpha :as spec]
; [spec-tools.core :as spec-core]
(defn create-with-default [default]
(spec-core/spec
{:spec string?
:swagger/default default
}
)
)
(def movie-data {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "Martin scorcose"
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert")
})
(s/defschema UpdateMovieRequest movie-data)
(s/defschema Movie (merge movie-data {:id pos-int?})
)
(s/defschema OldMovie {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert") ,
:id int?
}
)
(defn copy-file [source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
(defn movie-routes []
["" {:swagger {:tags ["movies"]}}
["/movies" {
:get {
:handler all-movies
:summary "List All Movies"
:responses {200 {:body
[Movie]
}}
}
:post {
:handler insert-movie
:parameters {
:body Movie
}
}
}]
["/movies/:id" {
:get {
:handler movie-by-id
:parameters {
:path {:id int?}
}
}
:put {
:handler update-movie-by-id
:parameters {
:path {:id int?}
:body UpdateMovieRequest
}
}
:delete {
:handler delete-movie-by-id
:parameters {
:path {:id int?}
}
}
}]
]
)
(defn service-routes []
["/api"
{:coercion spec-coercion/coercion
:muuntaja formats/instance
:swagger {:id ::api}
:middleware [;; query-params & form-params
parameters/parameters-middleware
;; content-negotiation
muuntaja/format-negotiate-middleware
;; encoding response body
muuntaja/format-response-middleware
;; exception handling
coercion/coerce-exceptions-middleware
;; decoding request body
muuntaja/format-request-middleware
;; coercing response bodys
coercion/coerce-response-middleware
;; coercing request parameters
coercion/coerce-request-middleware
;; multipart
multipart/multipart-middleware]}
;; swagger documentation
["" {:no-doc true
:swagger {:info {:title "Movies API"
:description "https://deemwar.com"}}}
["/swagger.json"
{:get (swagger/create-swagger-handler)}]
["/api-docs/*"
{:get (swagger-ui/create-swagger-ui-handler
{:url "/api/swagger.json"
:config {:validator-url nil}})}]]
(movie-routes)
["/ping"
{:get (constantly (ok {:message "pong"}))}]
["/math"
{:swagger {:tags ["math"]}
}
["/plus"
{:get {:summary "plus with spec query parameters"
:parameters {:query {:x int?, :y int?}}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (+ x y)}})}
:post {
:summary "plus with spec body parameters new"
:parameters {
:body {:x (spec-core/spec
{:spec int?
:swagger/default 125
}
)
:y int?
}
}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (+ x y)}})}}]]
["/files"
{:swagger {:tags ["files"]}}
["/upload"
{:post {:summary "upload a file"
:parameters {:multipart {:file multipart/temp-file-part}}
:responses {200 {:body {:name string?, :size int?}}}
:handler (fn [{{{:keys [file]} :multipart} :parameters}]
(println (type file))
(println file)
(io/copy (file :tempfile) (io/file "ar.pdf"))
{:status 200
:body {
:result "Saved Sucessfully"
:name (:filename file)
:size (:size file)}}
)}}]
["/download"
{:get {:summary "downloads a file"
:swagger {:produces ["image/png"]}
:handler (fn [_]
{:status 200
:headers {"Content-Type" "image/png"}
:body (-> "public/img/warning_clojure.png"
(io/resource)
(io/input-stream))
})}}]]])
|
7790
|
(ns moviebookingappv1.routes.apis
(:require
[reitit.swagger :as swagger]
[clojure.java.io :as io]
[reitit.swagger-ui :as swagger-ui]
[reitit.ring.coercion :as coercion]
[reitit.coercion.spec :as spec-coercion]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.multipart :as multipart]
[reitit.ring.middleware.parameters :as parameters]
[moviebookingappv1.middleware.formats :as formats]
[ring.util.http-response :refer :all]
[moviebookingappv1.services.movies :refer :all]
[clojure.java.io :as io]
[schema.core :as s]
[clojure.spec.alpha :as spec]
[spec-tools.core :as spec-core]
))
;
;(clojure.spec.alpha/def ::results
; (spec-tools.core/spec
; {:spec (clojure.spec.alpha/and int? #(< 0 % 100))
; :description "between 1-100"
; :swagger/default 10
; :reason "invalid number"}))
; [clojure.spec.alpha :as spec]
; [spec-tools.core :as spec-core]
(defn create-with-default [default]
(spec-core/spec
{:spec string?
:swagger/default default
}
)
)
(def movie-data {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "<NAME>"
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "<NAME>, <NAME>, <NAME>, <NAME>")
})
(s/defschema UpdateMovieRequest movie-data)
(s/defschema Movie (merge movie-data {:id pos-int?})
)
(s/defschema OldMovie {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "<NAME>, <NAME>, <NAME>, <NAME>") ,
:id int?
}
)
(defn copy-file [source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
(defn movie-routes []
["" {:swagger {:tags ["movies"]}}
["/movies" {
:get {
:handler all-movies
:summary "List All Movies"
:responses {200 {:body
[Movie]
}}
}
:post {
:handler insert-movie
:parameters {
:body Movie
}
}
}]
["/movies/:id" {
:get {
:handler movie-by-id
:parameters {
:path {:id int?}
}
}
:put {
:handler update-movie-by-id
:parameters {
:path {:id int?}
:body UpdateMovieRequest
}
}
:delete {
:handler delete-movie-by-id
:parameters {
:path {:id int?}
}
}
}]
]
)
(defn service-routes []
["/api"
{:coercion spec-coercion/coercion
:muuntaja formats/instance
:swagger {:id ::api}
:middleware [;; query-params & form-params
parameters/parameters-middleware
;; content-negotiation
muuntaja/format-negotiate-middleware
;; encoding response body
muuntaja/format-response-middleware
;; exception handling
coercion/coerce-exceptions-middleware
;; decoding request body
muuntaja/format-request-middleware
;; coercing response bodys
coercion/coerce-response-middleware
;; coercing request parameters
coercion/coerce-request-middleware
;; multipart
multipart/multipart-middleware]}
;; swagger documentation
["" {:no-doc true
:swagger {:info {:title "Movies API"
:description "https://deemwar.com"}}}
["/swagger.json"
{:get (swagger/create-swagger-handler)}]
["/api-docs/*"
{:get (swagger-ui/create-swagger-ui-handler
{:url "/api/swagger.json"
:config {:validator-url nil}})}]]
(movie-routes)
["/ping"
{:get (constantly (ok {:message "pong"}))}]
["/math"
{:swagger {:tags ["math"]}
}
["/plus"
{:get {:summary "plus with spec query parameters"
:parameters {:query {:x int?, :y int?}}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (+ x y)}})}
:post {
:summary "plus with spec body parameters new"
:parameters {
:body {:x (spec-core/spec
{:spec int?
:swagger/default 125
}
)
:y int?
}
}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (+ x y)}})}}]]
["/files"
{:swagger {:tags ["files"]}}
["/upload"
{:post {:summary "upload a file"
:parameters {:multipart {:file multipart/temp-file-part}}
:responses {200 {:body {:name string?, :size int?}}}
:handler (fn [{{{:keys [file]} :multipart} :parameters}]
(println (type file))
(println file)
(io/copy (file :tempfile) (io/file "ar.pdf"))
{:status 200
:body {
:result "Saved Sucessfully"
:name (:filename file)
:size (:size file)}}
)}}]
["/download"
{:get {:summary "downloads a file"
:swagger {:produces ["image/png"]}
:handler (fn [_]
{:status 200
:headers {"Content-Type" "image/png"}
:body (-> "public/img/warning_clojure.png"
(io/resource)
(io/input-stream))
})}}]]])
| true |
(ns moviebookingappv1.routes.apis
(:require
[reitit.swagger :as swagger]
[clojure.java.io :as io]
[reitit.swagger-ui :as swagger-ui]
[reitit.ring.coercion :as coercion]
[reitit.coercion.spec :as spec-coercion]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.multipart :as multipart]
[reitit.ring.middleware.parameters :as parameters]
[moviebookingappv1.middleware.formats :as formats]
[ring.util.http-response :refer :all]
[moviebookingappv1.services.movies :refer :all]
[clojure.java.io :as io]
[schema.core :as s]
[clojure.spec.alpha :as spec]
[spec-tools.core :as spec-core]
))
;
;(clojure.spec.alpha/def ::results
; (spec-tools.core/spec
; {:spec (clojure.spec.alpha/and int? #(< 0 % 100))
; :description "between 1-100"
; :swagger/default 10
; :reason "invalid number"}))
; [clojure.spec.alpha :as spec]
; [spec-tools.core :as spec-core]
(defn create-with-default [default]
(spec-core/spec
{:spec string?
:swagger/default default
}
)
)
(def movie-data {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "PI:NAME:<NAME>END_PI"
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI")
})
(s/defschema UpdateMovieRequest movie-data)
(s/defschema Movie (merge movie-data {:id pos-int?})
)
(s/defschema OldMovie {
:plot
(spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
)
:director (spec-core/spec
{:spec string?
:swagger/default "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight."
}
),
:genres (spec-core/spec
{:spec (spec/coll-of string?)
:swagger/default ["Biography" "Comedy" "Drama"]
}
)
:title (create-with-default "The Big Short") ,
:year (create-with-default "2015") ,
:runtime (create-with-default "130") ,
:posterUrl (create-with-default "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg") ,
:actors (create-with-default "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI") ,
:id int?
}
)
(defn copy-file [source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
(defn movie-routes []
["" {:swagger {:tags ["movies"]}}
["/movies" {
:get {
:handler all-movies
:summary "List All Movies"
:responses {200 {:body
[Movie]
}}
}
:post {
:handler insert-movie
:parameters {
:body Movie
}
}
}]
["/movies/:id" {
:get {
:handler movie-by-id
:parameters {
:path {:id int?}
}
}
:put {
:handler update-movie-by-id
:parameters {
:path {:id int?}
:body UpdateMovieRequest
}
}
:delete {
:handler delete-movie-by-id
:parameters {
:path {:id int?}
}
}
}]
]
)
(defn service-routes []
["/api"
{:coercion spec-coercion/coercion
:muuntaja formats/instance
:swagger {:id ::api}
:middleware [;; query-params & form-params
parameters/parameters-middleware
;; content-negotiation
muuntaja/format-negotiate-middleware
;; encoding response body
muuntaja/format-response-middleware
;; exception handling
coercion/coerce-exceptions-middleware
;; decoding request body
muuntaja/format-request-middleware
;; coercing response bodys
coercion/coerce-response-middleware
;; coercing request parameters
coercion/coerce-request-middleware
;; multipart
multipart/multipart-middleware]}
;; swagger documentation
["" {:no-doc true
:swagger {:info {:title "Movies API"
:description "https://deemwar.com"}}}
["/swagger.json"
{:get (swagger/create-swagger-handler)}]
["/api-docs/*"
{:get (swagger-ui/create-swagger-ui-handler
{:url "/api/swagger.json"
:config {:validator-url nil}})}]]
(movie-routes)
["/ping"
{:get (constantly (ok {:message "pong"}))}]
["/math"
{:swagger {:tags ["math"]}
}
["/plus"
{:get {:summary "plus with spec query parameters"
:parameters {:query {:x int?, :y int?}}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (+ x y)}})}
:post {
:summary "plus with spec body parameters new"
:parameters {
:body {:x (spec-core/spec
{:spec int?
:swagger/default 125
}
)
:y int?
}
}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (+ x y)}})}}]]
["/files"
{:swagger {:tags ["files"]}}
["/upload"
{:post {:summary "upload a file"
:parameters {:multipart {:file multipart/temp-file-part}}
:responses {200 {:body {:name string?, :size int?}}}
:handler (fn [{{{:keys [file]} :multipart} :parameters}]
(println (type file))
(println file)
(io/copy (file :tempfile) (io/file "ar.pdf"))
{:status 200
:body {
:result "Saved Sucessfully"
:name (:filename file)
:size (:size file)}}
)}}]
["/download"
{:get {:summary "downloads a file"
:swagger {:produces ["image/png"]}
:handler (fn [_]
{:status 200
:headers {"Content-Type" "image/png"}
:body (-> "public/img/warning_clojure.png"
(io/resource)
(io/input-stream))
})}}]]])
|
[
{
"context": "test round-trips-docs\n (let [alice {:crux.db/id :alice, :name \"Alice\"}\n alice-key (c/new-id alice",
"end": 210,
"score": 0.5926448702812195,
"start": 205,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "ps-docs\n (let [alice {:crux.db/id :alice, :name \"Alice\"}\n alice-key (c/new-id alice)\n bob ",
"end": 224,
"score": 0.9969465136528015,
"start": 219,
"tag": "NAME",
"value": "Alice"
},
{
"context": "w-id alice)\n bob {:crux.db/id :bob, :name \"Bob\"}\n bob-key (c/new-id bob)\n max-key ",
"end": 303,
"score": 0.9570183753967285,
"start": 300,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ob-key (c/new-id bob)\n max-key (c/new-id {:crux.db/id :max, :name \"Max\"})\n people {alice-key ",
"end": 372,
"score": 0.7373714447021484,
"start": 365,
"tag": "KEY",
"value": "crux.db"
}
] |
crux-test/src/crux/doc_store_test.clj
|
deobald/crux
| 0 |
(ns crux.doc-store-test
(:require [clojure.test :as t]
[crux.db :as db]
[crux.codec :as c]))
(def ^:dynamic *doc-store*)
(t/deftest round-trips-docs
(let [alice {:crux.db/id :alice, :name "Alice"}
alice-key (c/new-id alice)
bob {:crux.db/id :bob, :name "Bob"}
bob-key (c/new-id bob)
max-key (c/new-id {:crux.db/id :max, :name "Max"})
people {alice-key alice, bob-key bob}]
(db/submit-docs *doc-store* people)
(t/is (= {alice-key alice}
(db/fetch-docs *doc-store* #{alice-key})))
(t/is (= people
(db/fetch-docs *doc-store* (conj (keys people) max-key))))
(let [evicted-alice {:crux.db/id :alice, :crux.db/evicted? true}]
(db/submit-docs *doc-store* {alice-key evicted-alice})
(t/is (= {alice-key evicted-alice, bob-key bob}
(db/fetch-docs *doc-store* (keys people)))))))
(defn test-doc-store [ns]
(let [once-fixture-fn (t/join-fixtures (::t/once-fixtures (meta ns)))
each-fixture-fn (t/join-fixtures (::t/each-fixtures (meta ns)))]
(once-fixture-fn
(fn []
(doseq [v (vals (ns-interns 'crux.doc-store-test))]
(when (:test (meta v))
(each-fixture-fn (fn []
(t/test-var v)))))))))
(defn test-ns-hook []
;; no-op, these tests are called from elsewhere
)
|
1873
|
(ns crux.doc-store-test
(:require [clojure.test :as t]
[crux.db :as db]
[crux.codec :as c]))
(def ^:dynamic *doc-store*)
(t/deftest round-trips-docs
(let [alice {:crux.db/id :alice, :name "<NAME>"}
alice-key (c/new-id alice)
bob {:crux.db/id :bob, :name "<NAME>"}
bob-key (c/new-id bob)
max-key (c/new-id {:<KEY>/id :max, :name "Max"})
people {alice-key alice, bob-key bob}]
(db/submit-docs *doc-store* people)
(t/is (= {alice-key alice}
(db/fetch-docs *doc-store* #{alice-key})))
(t/is (= people
(db/fetch-docs *doc-store* (conj (keys people) max-key))))
(let [evicted-alice {:crux.db/id :alice, :crux.db/evicted? true}]
(db/submit-docs *doc-store* {alice-key evicted-alice})
(t/is (= {alice-key evicted-alice, bob-key bob}
(db/fetch-docs *doc-store* (keys people)))))))
(defn test-doc-store [ns]
(let [once-fixture-fn (t/join-fixtures (::t/once-fixtures (meta ns)))
each-fixture-fn (t/join-fixtures (::t/each-fixtures (meta ns)))]
(once-fixture-fn
(fn []
(doseq [v (vals (ns-interns 'crux.doc-store-test))]
(when (:test (meta v))
(each-fixture-fn (fn []
(t/test-var v)))))))))
(defn test-ns-hook []
;; no-op, these tests are called from elsewhere
)
| true |
(ns crux.doc-store-test
(:require [clojure.test :as t]
[crux.db :as db]
[crux.codec :as c]))
(def ^:dynamic *doc-store*)
(t/deftest round-trips-docs
(let [alice {:crux.db/id :alice, :name "PI:NAME:<NAME>END_PI"}
alice-key (c/new-id alice)
bob {:crux.db/id :bob, :name "PI:NAME:<NAME>END_PI"}
bob-key (c/new-id bob)
max-key (c/new-id {:PI:KEY:<KEY>END_PI/id :max, :name "Max"})
people {alice-key alice, bob-key bob}]
(db/submit-docs *doc-store* people)
(t/is (= {alice-key alice}
(db/fetch-docs *doc-store* #{alice-key})))
(t/is (= people
(db/fetch-docs *doc-store* (conj (keys people) max-key))))
(let [evicted-alice {:crux.db/id :alice, :crux.db/evicted? true}]
(db/submit-docs *doc-store* {alice-key evicted-alice})
(t/is (= {alice-key evicted-alice, bob-key bob}
(db/fetch-docs *doc-store* (keys people)))))))
(defn test-doc-store [ns]
(let [once-fixture-fn (t/join-fixtures (::t/once-fixtures (meta ns)))
each-fixture-fn (t/join-fixtures (::t/each-fixtures (meta ns)))]
(once-fixture-fn
(fn []
(doseq [v (vals (ns-interns 'crux.doc-store-test))]
(when (:test (meta v))
(each-fixture-fn (fn []
(t/test-var v)))))))))
(defn test-ns-hook []
;; no-op, these tests are called from elsewhere
)
|
[
{
"context": "advance-counter 1 {:placed true}))}]})\n\n(defcard \"Award Bait\"\n {:flags {:rd-reveal (req true)}\n :access {:a",
"end": 9603,
"score": 0.9655091762542725,
"start": 9593,
"tag": "NAME",
"value": "Award Bait"
},
{
"context": "range-rd\n :stolen arrange-rd})))\n\n(defcard \"Bellona\"\n {:steal-cost-bonus (req [:credit 5])\n :on-sc",
"end": 13075,
"score": 0.9308967590332031,
"start": 13068,
"tag": "NAME",
"value": "Bellona"
},
{
"context": " (effect-completed eid))}}}]})\n\n(defcard \"Degree Mill\"\n {:steal-cost-bonus (req [:shuffle-installed-to",
"end": 25384,
"score": 0.7304061055183411,
"start": 25373,
"tag": "NAME",
"value": "Degree Mill"
},
{
"context": "d-prop target :advance-counter 1))}]})\n\n(defcard \"Flower Sermon\"\n {:on-score {:silent (req true)\n :",
"end": 32534,
"score": 0.896743655204773,
"start": 32521,
"tag": "NAME",
"value": "Flower Sermon"
},
{
"context": " true\n :waiting-prompt \"Corp to use Flower Sermon\"\n :effect (req (wait-f",
"end": 32898,
"score": 0.5379554033279419,
"start": 32897,
"tag": "NAME",
"value": "F"
},
{
"context": "))\n :silent (req true)}})\n\n(defcard \"Geothermal Fracking\"\n {:on-score {:effect (effect (add-counter card ",
"end": 34307,
"score": 0.8586834073066711,
"start": 34288,
"tag": "NAME",
"value": "Geothermal Fracking"
},
{
"context": "? (get-counters card :agenda)) 1 2))})\n\n(defcard \"Merger\"\n {:agendapoints-runner (req 3)})\n\n(defcard \"",
"end": 47784,
"score": 0.9734633564949036,
"start": 47781,
"tag": "NAME",
"value": "Mer"
},
{
"context": "get-counters card :agenda)) 1 2))})\n\n(defcard \"Merger\"\n {:agendapoints-runner (req 3)})\n\n(defcard \"Met",
"end": 47787,
"score": 0.478189617395401,
"start": 47784,
"tag": "NAME",
"value": "ger"
}
] |
src/clj/game/cards/agendas.clj
|
cmsd2/netrunner
| 0 |
(ns game.cards.agendas
(:require [game.core :refer :all]
[game.utils :refer :all]
[jinteki.utils :refer :all]
[clojure.string :as string]
[clojure.set :as clj-set]))
(defn ice-boost-agenda [subtype]
(letfn [(count-ice [corp]
(reduce (fn [c server]
(+ c (count (filter #(and (has-subtype? % subtype)
(rezzed? %))
(:ices server)))))
0
(flatten (seq (:servers corp)))))]
{:on-score {:msg (msg "gain " (count-ice corp) " [Credits]")
:interactive (req true)
:async true
:effect (effect (gain-credits eid (count-ice corp)))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target subtype))
:value 1}]}))
;; Card definitions
(defcard "15 Minutes"
{:abilities [{:cost [:click 1]
:msg "shuffle 15 Minutes into R&D"
:label "Shuffle 15 Minutes into R&D"
:effect (effect (move :corp card :deck nil)
(shuffle! :corp :deck)
(update-all-agenda-points))}]
:flags {:has-abilities-when-stolen true}})
(defcard "Above the Law"
{:on-score
{:interactive (req true)
:prompt "Select resource"
:req (req (some #(and (installed? %)
(resource? %))
(all-active-installed state :runner)))
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (card-str state target))
:async true
:effect (effect (trash eid target))}})
(defcard "Accelerated Beta Test"
(letfn [(abt [titles choices]
{:async true
:prompt (str "The top 3 cards of R&D: " titles)
:choices (concat (filter ice? choices) ["Done"])
:effect (req (if (= target "Done")
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
(wait-for (corp-install state side target nil
{:ignore-all-cost true
:install-state :rezzed-no-cost})
(let [choices (remove-once #(= target %) choices)]
(cond
;; Shuffle ends the ability
(get-in (get-card state card) [:special :shuffle-occurred])
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
;; There are still ice left
(seq (filter ice? choices))
(continue-ability
state side (abt titles choices) card nil)
;; Trash what's left
:else
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true})))))))})
(suffer [titles choices]
{:prompt (str "The top 3 cards of R&D: " titles
". None are ice. Say goodbye!")
:choices ["I have no regrets"]
:async true
:effect (effect (system-msg (str "trashes " (quantify (count choices) "card")))
(trash-cards eid choices {:unpreventable true}))})]
{:on-score
{:interactive (req true)
:optional
{:prompt "Look at the top 3 cards of R&D?"
:yes-ability
{:async true
:msg "look at the top 3 cards of R&D"
:effect (req (register-events
state side card
[{:event :corp-shuffle-deck
:effect (effect (update! (assoc-in card [:special :shuffle-occurred] true)))}])
(let [choices (take 3 (:deck corp))
titles (string/join ", " (map :title choices))]
(continue-ability
state side
(if (seq (filter ice? choices))
(abt titles choices)
(suffer titles choices))
card nil)))}}}}))
(defcard "Advanced Concept Hopper"
{:events
[{:event :run
:req (req (first-event? state side :run))
:player :corp
:once :per-turn
:async true
:waiting-prompt "Corp to use Advanced Concept Hopper"
:prompt "Use Advanced Concept Hopper to draw 1 card or gain 1 [Credits]?"
:choices ["Draw 1 card" "Gain 1 [Credits]" "No action"]
:effect (req (case target
"Gain 1 [Credits]"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to gain 1 [Credits]"))
(gain-credits state :corp eid 1))
"Draw 1 card"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to draw 1 card"))
(draw state :corp eid 1 nil))
"No action"
(do (system-msg state :corp (str "doesn't use Advanced Concept Hopper"))
(effect-completed state side eid))))}]})
(defcard "Ancestral Imager"
{:events [{:event :jack-out
:msg "do 1 net damage"
:async true
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "AR-Enhanced Security"
{:events [{:event :runner-trash
:async true
:interactive (req true)
:once-per-instance true
:req (req (and (some #(corp? (:card %)) targets)
(first-event? state side :runner-trash
(fn [targets] (some #(corp? (:card %)) targets)))))
:msg "give the Runner a tag"
:effect (effect (gain-tags eid 1))}]})
(defcard "Architect Deployment Test"
{:on-score
{:interactive (req true)
:async true
:msg "look at the top 5 cards of R&D"
:prompt (msg "The top cards of R&D are (top->bottom) " (string/join ", " (map :title (take 5 (:deck corp)))))
:choices ["OK"]
:effect (effect (continue-ability
{:prompt "Install a card?"
:choices (cancellable (filter corp-installable-type? (take 5 (:deck corp))))
:async true
:effect (effect (corp-install eid target nil
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))
:cancel-effect (effect (system-msg "does not install any of the top 5 cards")
(effect-completed eid))}
card nil))}})
(defcard "Armed Intimidation"
{:on-score
{:player :runner
:async true
:waiting-prompt "Runner to suffer 5 meat damage or take 2 tags"
:prompt "Choose Armed Intimidation score effect"
:choices ["Suffer 5 meat damage" "Take 2 tags"]
:effect (req (case target
"Suffer 5 meat damage"
(do (system-msg state :runner "chooses to suffer 5 meat damage from Armed Intimidation")
(damage state :runner eid :meat 5 {:card card :unboostable true}))
"Take 2 tags"
(do (system-msg state :runner "chooses to take 2 tags from Armed Intimidation")
(gain-tags state :runner eid 2 {:card card}))
; else
(effect-completed state side eid)))}})
(defcard "Armored Servers"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req run)
:label "increase cost to break subroutines or jack out"
:msg "make the Runner trash a card from their grip to jack out or break subroutines for the remainder of the run"
:effect (effect (register-floating-effect
card
{:type :break-sub-additional-cost
:duration :end-of-run
:value (req (repeat (count (:broken-subs (second targets))) [:trash-from-hand 1]))})
(register-floating-effect
card
{:type :jack-out-additional-cost
:duration :end-of-run
:value [:trash-from-hand 1]}))}]})
(defcard "AstroScript Pilot Program"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:msg (msg "place 1 advancement token on " (card-str state target))
:choices {:card can-be-advanced?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "Award Bait"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not-empty (filter #(can-be-advanced? %) (all-installed state :corp))))
:waiting-prompt "Corp to place advancement tokens with Award Bait"
:prompt "How many advancement tokens?"
:choices ["0" "1" "2"]
:effect (effect (continue-ability
(let [c (str->int target)]
{:choices {:card can-be-advanced?}
:msg (msg "place " (quantify c "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter c {:placed true}))})
card nil))}})
(defcard "Bacterial Programming"
(letfn [(hq-step [remaining to-trash to-hq]
{:async true
:prompt "Select a card to move to HQ"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(wait-for (trash-cards state :corp to-trash {:unpreventable true})
(doseq [h to-hq]
(move state :corp h :hand))
(if (seq remaining)
(continue-ability state :corp (reorder-choice :corp (vec remaining)) card nil)
(do (system-msg state :corp
(str "uses Bacterial Programming to add " (count to-hq)
" cards to HQ, discard " (count to-trash)
", and arrange the top cards of R&D"))
(effect-completed state :corp eid))))
(continue-ability state :corp (hq-step
(clj-set/difference (set remaining) (set [target]))
to-trash
(conj to-hq target)) card nil)))})
(trash-step [remaining to-trash]
{:async true
:prompt "Select a card to discard"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(continue-ability state :corp (hq-step remaining to-trash '()) card nil)
(continue-ability state :corp (trash-step
(clj-set/difference (set remaining) (set [target]))
(conj to-trash target)) card nil)))})]
(let [arrange-rd
{:interactive (req true)
:optional
{:waiting-prompt "Corp to use Bacterial Programming"
:prompt "Arrange top 7 cards of R&D?"
:yes-ability
{:async true
:effect (req (let [c (take 7 (:deck corp))]
(when (:access @state)
(swap! state assoc-in [:run :shuffled-during-access :rd] true))
(continue-ability state :corp (trash-step c '()) card nil)))}}}]
{:on-score arrange-rd
:stolen arrange-rd})))
(defcard "Bellona"
{:steal-cost-bonus (req [:credit 5])
:on-score {:async true
:msg "gain 5 [Credits]"
:effect (effect (gain-credits :corp eid 5))}})
(defcard "Better Citizen Program"
{:events [{:event :play-event
:optional
{:player :corp
:req (req (and (has-subtype? (:card context) "Run")
(first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))
(no-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for playing a run event"
:effect (effect (gain-tags :corp eid 1))}}}
{:event :runner-install
:silent (req true)
:optional
{:player :corp
:req (req (and (not (:facedown context))
(has-subtype? (:card context) "Icebreaker")
(first-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))
(no-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for installing an icebreaker"
:effect (effect (gain-tags :corp eid 1))}}}]})
(defcard "Bifrost Array"
{:on-score
{:optional
{:req (req (seq (filter #(not= (:title %) "Bifrost Array") (:scored corp))))
:prompt "Trigger the ability of a scored agenda?"
:yes-ability
{:prompt "Select an agenda to trigger its \"when scored\" ability"
:choices {:card #(and (agenda? %)
(not= (:title %) "Bifrost Array")
(in-scored? %)
(when-scored? %))}
:msg (msg "trigger the \"when scored\" ability of " (:title target))
:async true
:effect (effect (continue-ability (:on-score (card-def target)) target nil))}}}})
(defcard "Brain Rewiring"
{:on-score
{:optional
{:waiting-prompt "Corp to use Brain Rewiring"
:prompt "Pay credits to add random cards from Runner's Grip to the bottom of their Stack?"
:yes-ability
{:prompt "How many credits?"
:choices {:number (req (min (:credit corp)
(count (:hand runner))))}
:async true
:effect (req (if (pos? target)
(wait-for
(pay state :corp card :credit target)
(let [from (take target (shuffle (:hand runner)))]
(doseq [c from]
(move state :runner c :deck))
(system-msg state side (str "uses Brain Rewiring to pay " target
" [Credits] and add " target
" cards from the Runner's Grip"
" to the bottom of their Stack."
" The Runner draws 1 card"))
(draw state :runner eid 1 nil)))
(effect-completed state side eid)))}}}})
(defcard "Braintrust"
{:on-score {:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2)))
:silent (req true)}
:constant-effects [{:type :rez-cost
:req (req (ice? target))
:value (req (- (get-counters card :agenda)))}]})
(defcard "Breaking News"
{:on-score {:async true
:silent (req true)
:msg "give the Runner 2 tags"
:effect (effect (gain-tags :corp eid 2))}
:events (let [event {:unregister-once-resolved true
:req (effect (first-event? :agenda-scored #(same-card? card (:card (first %)))))
:msg "make the Runner lose 2 tags"
:effect (effect (lose :runner :tag 2))}]
[(assoc event :event :corp-turn-ends)
(assoc event :event :runner-turn-ends)])})
(defcard "Broad Daylight"
(letfn [(add-counters [state side card eid]
(add-counter state :corp card :agenda (count-bad-pub state))
(effect-completed state side eid))]
{:on-score
{:optional
{:prompt "Take 1 bad publicity?"
:async true
:yes-ability {:async true
:effect (req (wait-for (gain-bad-publicity state :corp 1)
(system-msg state :corp "used Broad Daylight to take 1 bad publicity")
(add-counters state side card eid)))}
:no-ability {:async true
:effect (effect (add-counters card eid))}}}
:abilities [{:cost [:click 1 :agenda 1]
:async true
:label "Do 2 meat damage"
:once :per-turn
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}]}))
(defcard "CFC Excavation Contract"
(letfn [(bucks [state]
(->> (all-active-installed state :corp)
(filter #(has-subtype? % "Bioroid"))
(count)
(* 2)))]
{:on-score
{:async true
:msg (msg "gain " (bucks state) " [Credits]")
:effect (effect (gain-credits :corp eid (bucks state)))}}))
(defcard "Character Assassination"
{:on-score
{:prompt "Select a resource to trash"
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (:title target))
:interactive (req true)
:async true
:effect (effect (trash eid target {:unpreventable true}))}})
(defcard "Chronos Project"
{:on-score
{:req (req (not (zone-locked? state :runner :discard)))
:msg "remove all cards in the Runner's Heap from the game"
:interactive (req true)
:effect (effect (move-zone :runner :discard :rfg))}})
(defcard "City Works Project"
(letfn [(meat-damage [s c] (+ 2 (get-counters (get-card s c) :advancement)))]
{:install-state :face-up
:access {:req (req installed)
:msg (msg "do " (meat-damage state card) " meat damage")
:async true
:effect (effect (damage eid :meat (meat-damage state card) {:card card}))}}))
(defcard "Clone Retirement"
{:on-score {:msg "remove 1 bad publicity"
:effect (effect (lose-bad-publicity 1))
:silent (req true)}
:stolen {:msg "force the Corp to take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}})
(defcard "Corporate Oversight A"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Oversight B"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a central server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(#{"HQ" "Archives" "R&D"} %)
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Sales Team"
(let [e {:req (req (pos? (get-counters card :credit)))
:msg "gain 1 [Credits]"
:async true
:effect (req (add-counter state side card :credit -1)
(gain-credits state :corp eid 1))}]
{:on-score {:effect (effect (add-counter card :credit 10))
:silent (req true)}
:events [(assoc e :event :runner-turn-begins)
(assoc e :event :corp-turn-begins)]}))
(defcard "Corporate War"
{:on-score
{:msg (msg (if (> (:credit corp) 6) "gain 7 [Credits]" "lose all credits"))
:interactive (req true)
:async true
:effect (req (if (> (:credit corp) 6)
(gain-credits state :corp eid 7)
(lose-credits state :corp eid :all)))}})
(defcard "Crisis Management"
(let [ability {:req (req tagged)
:async true
:label "Do 1 meat damage (start of turn)"
:once :per-turn
:msg "do 1 meat damage"
:effect (effect (damage eid :meat 1 {:card card}))}]
{:events [(assoc ability :event :corp-turn-begins)]
:abilities [ability]}))
(defcard "Cyberdex Sandbox"
{:on-score {:optional
{:prompt "Purge virus counters with Cyberdex Sandbox?"
:yes-ability {:msg (msg "purge virus counters")
:effect (effect (purge))}}}
:events [{:event :purge
:req (req (first-event? state :corp :purge))
:once :per-turn
:msg "gain 4 [Credits]"
:async true
:effect (req (gain-credits state :corp eid 4))}]})
(defcard "Dedicated Neural Net"
{:events [{:event :successful-run
:interactive (req true)
:psi {:req (req (= :hq (target-server context)))
:once :per-turn
:not-equal {:effect (effect (register-floating-effect
card
{:type :corp-choose-hq-access
:duration :end-of-access
:value true})
(effect-completed eid))}}}]})
(defcard "Degree Mill"
{:steal-cost-bonus (req [:shuffle-installed-to-stack 2])})
(defcard "Director Haas' Pet Project"
(letfn [(install-ability [server-name n]
{:prompt "Select a card to install"
:show-discard true
:choices {:card #(and (corp? %)
(not (operation? %))
(or (in-hand? %)
(in-discard? %)))}
:msg (msg (corp-install-msg target)
(when (zero? n)
", creating a new remote server")
", ignoring all install costs")
:async true
:effect (req (wait-for (corp-install state side target server-name {:ignore-all-cost true})
(continue-ability state side
(when (< n 2)
(install-ability (last (get-remote-names state)) (inc n)))
card nil)))})]
{:on-score
{:optional
{:prompt "Install cards in a new remote server?"
:yes-ability (install-ability "New remote" 0)}}}))
(defcard "Divested Trust"
{:events
[{:event :agenda-stolen
:async true
:interactive (req true)
:effect (req (if (:winner @state)
(effect-completed state side eid)
(let [card (find-latest state card)
stolen-agenda (find-latest state (:card context))
title (:title stolen-agenda)
prompt (str "Forfeit Divested Trust to add " title
" to HQ and gain 5[Credits]?")
message (str "add " title " to HQ and gain 5 [Credits]")
agenda-side (if (in-runner-scored? state side stolen-agenda)
:runner :corp)
card-side (if (in-runner-scored? state side card)
:runner :corp)]
(continue-ability
state side
{:optional
{:waiting-prompt "Corp to use Divested Trust"
:prompt prompt
:yes-ability
{:msg message
:async true
:effect (req (wait-for (forfeit state card-side card)
(move state side stolen-agenda :hand)
(update-all-agenda-points state side)
(gain-credits state side eid 5)))}}}
card nil))))}]})
(defcard "Domestic Sleepers"
{:agendapoints-corp (req (if (pos? (get-counters card :agenda)) 1 0))
:abilities [{:cost [:click 3]
:msg "place 1 agenda counter on Domestic Sleepers"
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}]})
(defcard "Eden Fragment"
{:constant-effects [{:type :ignore-install-cost
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:value true}]
:events [{:event :corp-install
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:msg "ignore the install cost of the first ICE this turn"}]})
(defcard "Efficiency Committee"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:click 1 :agenda 1]
:effect (effect (gain :click 2)
(register-turn-flag!
card :can-advance
(fn [state side card]
((constantly false)
(toast state :corp "Cannot advance cards this turn due to Efficiency Committee." "warning")))))
:msg "gain [Click][Click]"}]})
(defcard "Elective Upgrade"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:click 1 :agenda 1]
:once :per-turn
:effect (effect (gain :click 2))
:msg "gain [Click][Click]"}]})
(defcard "Encrypted Portals"
(ice-boost-agenda "Code Gate"))
(defcard "Escalate Vitriol"
{:abilities [{:label "Gain 1 [Credit] for each Runner tag"
:cost [:click 1]
:once :per-turn
:msg (msg "gain " (count-tags state) " [Credits]")
:async true
:effect (effect (gain-credits eid (count-tags state)))}]})
(defcard "Executive Retreat"
{:on-score {:effect (effect (add-counter card :agenda 1)
(shuffle-into-deck :hand))
:interactive (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "draw 5 cards"
:effect (effect (draw 5))}]})
(defcard "Explode-a-palooza"
{:flags {:rd-reveal (req true)}
:access {:optional
{:waiting-prompt "Corp to use Explode-a-palooza"
:prompt "Gain 5 [Credits] with Explode-a-palooza ability?"
:yes-ability
{:msg "gain 5 [Credits]"
:async true
:effect (effect (gain-credits :corp eid 5))}}}})
(defcard "False Lead"
{:abilities [{:req (req (<= 2 (:click runner)))
:label "runner loses [Click][Click]"
:msg "force the Runner to lose [Click][Click]"
:cost [:forfeit-self]
:effect (effect (lose :runner :click 2))}]})
(defcard "Fetal AI"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not (in-discard? card)))
:msg "do 2 net damage"
:effect (effect (damage eid :net 2 {:card card}))}
:steal-cost-bonus (req [:credit 2])})
(defcard "Firmware Updates"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:choices {:card #(and (ice? %)
(can-be-advanced? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "place 1 advancement token on " (card-str state target))
:once :per-turn
:effect (effect (add-prop target :advance-counter 1))}]})
(defcard "Flower Sermon"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 5))}
:abilities [{:cost [:agenda 1]
:label "reveal and draw"
:once :per-turn
:msg (msg "reveal " (:title (first (:deck corp))) " and draw 2 cards")
:async true
:waiting-prompt "Corp to use Flower Sermon"
:effect (req (wait-for
(reveal state side (first (:deck corp)))
(wait-for
(draw state side 2 nil)
(continue-ability
state side
{:req (req (pos? (count (:hand corp))))
:prompt "Choose a card in HQ to move to the top of R&D"
:msg "add 1 card in HQ to the top of R&D"
:choices {:card #(and (in-hand? %)
(corp? %))}
:effect (effect (move target :deck {:front true})
(effect-completed eid))}
card nil))))}]})
(defcard "Fly on the Wall"
{:on-score {:msg "give the runner 1 tag"
:async true
:effect (req (gain-tags state :runner eid 1))}})
(defcard "Genetic Resequencing"
{:on-score {:choices {:card in-scored?}
:msg (msg "add 1 agenda counter on " (:title target))
:effect (effect (add-counter target :agenda 1)
(update-all-agenda-points))
:silent (req true)}})
(defcard "Geothermal Fracking"
{:on-score {:effect (effect (add-counter card :agenda 2))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "gain 7 [Credits] and take 1 bad publicity"
:async true
:effect (req (wait-for (gain-credits state side 7)
(gain-bad-publicity state side eid 1)))}]})
(defcard "Gila Hands Arcology"
{:abilities [{:cost [:click 2]
:msg "gain 3 [Credits]"
:async true
:effect (effect (gain-credits eid 3))}]})
(defcard "Glenn Station"
{:abilities [{:label "Host a card from HQ on Glenn Station"
:req (req (and (not-empty (:hand corp))
(empty? (filter corp? (:hosted card)))))
:cost [:click 1]
:msg "host a card from HQ"
:prompt "Choose a card to host on Glenn Station"
:choices {:card #(and (corp? %) (in-hand? %))}
:effect (effect (host card target {:facedown true}))}
{:label "Add a card on Glenn Station to HQ"
:req (req (not-empty (filter corp? (:hosted card))))
:cost [:click 1]
:msg "add a hosted card to HQ"
:prompt "Choose a card on Glenn Station"
:choices {:all true
:req (req (let [hosted-corp-cards
(->> (:hosted card)
(filter corp?)
(map :cid)
(into #{}))]
(hosted-corp-cards (:cid target))))}
:effect (effect (move target :hand))}]})
(defcard "Global Food Initiative"
{:agendapoints-runner (req 2)})
(defcard "Government Contracts"
{:abilities [{:cost [:click 2]
:async true
:effect (effect (gain-credits eid 4))
:msg "gain 4 [Credits]"}]})
(defcard "Government Takeover"
{:abilities [{:cost [:click 1]
:async true
:effect (effect (gain-credits eid 3))
:msg "gain 3 [Credits]"}]})
(defcard "Graft"
(letfn [(graft [n] {:prompt "Choose a card to add to HQ with Graft"
:async true
:choices (req (cancellable (:deck corp) :sorted))
:msg (msg "add " (:title target) " to HQ from R&D")
:cancel-effect (req (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))
:effect (req (move state side target :hand)
(if (< n 3)
(continue-ability state side (graft (inc n)) card nil)
(do (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))))})]
{:on-score
{:async true
:msg "add up to 3 cards from R&D to HQ"
:effect (effect (continue-ability (graft 1) card nil))}}))
(defcard "Hades Fragment"
{:flags {:corp-phase-12 (req (and (not-empty (get-in @state [:corp :discard]))
(is-scored? state :corp card)))}
:abilities [{:prompt "Select a card to add to the bottom of R&D"
:label "add card to bottom of R&D"
:show-discard true
:choices {:card #(and (corp? %)
(in-discard? %))}
:effect (effect (move target :deck))
:msg (msg "add "
(if (:seen target)
(:title target)
"a card")
" to the bottom of R&D")}]})
(defcard "Helium-3 Deposit"
{:on-score
{:async true
:interactive (req true)
:prompt "How many power counters?"
:choices ["0" "1" "2"]
:effect (req (let [c (str->int target)]
(continue-ability
state side
{:choices {:card #(pos? (get-counters % :power))}
:msg (msg "add " c " power counters on " (:title target))
:effect (effect (add-counter target :power c))}
card nil)))}})
(defcard "High-Risk Investment"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:label "gain credits"
:msg (msg "gain " (:credit runner) " [Credits]")
:async true
:effect (effect (gain-credits eid (:credit runner)))}]})
(defcard "Hollywood Renovation"
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:effect (req (let [n (if (>= (get-counters (get-card state card) :advancement) 6) 2 1)]
(continue-ability
state side
{:choices {:card #(and (not (same-card? % card))
(can-be-advanced? %))}
:msg (msg "place " (quantify n "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter n {:placed true}))}
card nil)))}]})
(defcard "Hostile Takeover"
{:on-score {: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)))
:interactive (req true)}})
(defcard "House of Knives"
{:on-score {:effect (effect (add-counter card :agenda 3))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg "do 1 net damage"
:req (req (:run @state))
:once :per-run
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Hyperloop Extension"
(let [he {:async true
:effect (req (system-msg state side (str "uses Hyperloop Extension to gain 3 [Credits]"))
(gain-credits state :corp eid 3))}]
{:on-score he
:stolen he}))
(defcard "Ikawah Project"
{:steal-cost-bonus (req [:credit 2 :click 1])})
(defcard "Illicit Sales"
{:on-score
{:async true
:effect (req (wait-for (resolve-ability
state side
{:optional
{:prompt "Take 1 bad publicity from Illicit Sales?"
:yes-ability {:msg "take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}}}
card nil)
(let [n (* 3 (count-bad-pub state))]
(system-msg state side (str "gains " n " [Credits] from Illicit Sales"))
(gain-credits state side eid n))))}})
(defcard "Improved Protein Source"
(let [ability {:async true
:interactive (req true)
:msg "make the Runner gain 4 [Credits]"
:effect (effect (gain-credits :runner eid 4))}]
{:on-score ability
:stolen ability}))
(defcard "Improved Tracers"
{:on-score {:silent (req true)
:effect (req (update-all-ice state side))}
:swapped {:effect (req (update-all-ice state side))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target "Tracer"))
:value 1}]
:events [{:event :pre-init-trace
:req (req (and (has-subtype? target "Tracer")
(= :subroutine (:source-type (second targets)))))
:effect (effect (init-trace-bonus 1))}]})
(defcard "Jumon"
{:events
[{:event :corp-turn-ends
:req (req (some #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))
(all-installed state :corp)))
:prompt "Select a card to place 2 advancement tokens on"
:player :corp
:choices {:card #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))}
:msg (msg "place 2 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 2 {:placed true}))}]})
(defcard "Labyrinthine Servers"
{:on-score {:silent (req true)
:effect (effect (add-counter card :power 2))}
:interactions {:prevent [{:type #{:jack-out}
:req (req (pos? (get-counters card :power)))}]}
:abilities [{:req (req (:run @state))
:cost [:power 1]
:msg "prevent the Runner from jacking out"
:effect (effect (jack-out-prevent))}]})
(defcard "License Acquisition"
{:on-score {:interactive (req true)
:prompt "Select an asset or upgrade to install from Archives or HQ"
:show-discard true
:choices {:card #(and (corp? %)
(or (asset? %) (upgrade? %))
(or (in-hand? %) (in-discard? %)))}
:msg (msg "install and rez " (:title target) ", ignoring all costs")
:async true
:effect (effect (corp-install eid target nil {:install-state :rezzed-no-cost}))}})
(defcard "Longevity Serum"
{:on-score
{:prompt "Select any number of cards in HQ to trash"
:choices {:max (req (count (:hand corp)))
:card #(and (corp? %)
(in-hand? %))}
:msg (msg "trash " (quantify (count targets) "card") " in HQ")
:async true
:effect (req (wait-for (trash-cards state side targets {:unpreventable true})
(shuffle-into-rd-effect state side eid card 3)))}})
(defcard "Luminal Transubstantiation"
{:on-score
{:silent (req true)
:effect (req (gain state :corp :click 3)
(register-turn-flag!
state side card :can-score
(fn [state side card]
((constantly false)
(toast state :corp "Cannot score cards this turn due to Luminal Transubstantiation." "warning")))))}})
(defcard "Mandatory Seed Replacement"
(letfn [(msr [] {:prompt "Select two pieces of ICE to swap positions"
:choices {:card #(and (installed? %)
(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 "swaps the position of "
(card-str state (first targets))
" and "
(card-str state (second targets))))
(continue-ability state side (msr) card nil))
(do (system-msg state :corp (str "has finished rearranging ICE"))
(effect-completed state side eid))))})]
{:on-score {:async true
:msg "rearrange any number of ICE"
:effect (effect (continue-ability (msr) card nil))}}))
(defcard "Mandatory Upgrades"
{:on-score {:msg "gain an additional [Click] per turn"
:silent (req true)
:effect (req (gain state :corp :click-per-turn 1))}
:swapped {:msg "gain an additional [Click] per turn"
:effect (req (when (= (:active-player @state) :corp)
(gain state :corp :click 1))
(gain state :corp :click-per-turn 1))}
:leave-play (req (lose state :corp
:click 1
:click-per-turn 1))})
(defcard "Market Research"
{:on-score {:interactive (req true)
:req (req tagged)
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 2 3))})
(defcard "Medical Breakthrough"
{:flags {:has-events-when-stolen true}
:constant-effects [{:type :advancement-requirement
:req (req (= (:title target) "Medical Breakthrough"))
:value -1}]})
(defcard "Megaprix Qualifier"
{:on-score {:silent (req true)
:req (req (< 1 (count (filter #(= (:title %) "Megaprix Qualifier")
(concat (:scored corp) (:scored runner))))))
:effect (effect (add-counter card :agenda 1))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 1 2))})
(defcard "Merger"
{:agendapoints-runner (req 3)})
(defcard "Meteor Mining"
{:on-score {:interactive (req true)
:async true
:prompt "Use Meteor Mining?"
:choices (req (if (< (count-tags state) 2)
["Gain 7 [Credits]" "No action"]
["Gain 7 [Credits]" "Do 7 meat damage" "No action"]))
:effect (req (case target
"Gain 7 [Credits]"
(do (system-msg state side "uses Meteor Mining to gain 7 [Credits]")
(gain-credits state side eid 7))
"Do 7 meat damage"
(do (system-msg state side "uses Meteor Mining do 7 meat damage")
(damage state side eid :meat 7 {:card card}))
"No action"
(do (system-msg state side "does not use Meteor Mining")
(effect-completed state side eid))))}})
(defcard "NAPD Contract"
{:steal-cost-bonus (req [:credit 4])
:advancement-requirement (req (count-bad-pub state))})
(defcard "Net Quarantine"
(let [nq {:async true
:effect (req (let [extra (int (/ (:runner-spent target) 2))]
(if (pos? extra)
(do (system-msg state :corp (str "uses Net Quarantine to gain " extra "[Credits]"))
(gain-credits state side eid extra))
(effect-completed state side eid))))}]
{:events [{:event :pre-init-trace
:once :per-turn
:silent (req true)
:effect (req (system-msg state :corp "uses Net Quarantine to reduce Runner's base link to zero")
(swap! state assoc-in [:trace :force-link] 0))}
(assoc nq :event :successful-trace)
(assoc nq :event :unsuccessful-trace)]}))
(defcard "New Construction"
{:install-state :face-up
:events [{:event :advance
:optional
{:req (req (same-card? card target))
:prompt "Install a card from HQ in a new remote?"
:yes-ability {:prompt "Select a card to install"
:choices {:card #(and (not (operation? %))
(not (ice? %))
(corp? %)
(in-hand? %))}
:msg (msg "install a card from HQ"
(when (<= 5 (get-counters (get-card state card) :advancement))
" and rez it, ignoring all costs"))
:async true
:effect (effect (corp-install
eid target "New remote"
(when (<= 5 (get-counters (get-card state card) :advancement))
{:install-state :rezzed-no-cost})))}}}]})
(defcard "NEXT Wave 2"
{:on-score
{:async true
:effect
(effect
(continue-ability
(when (some #(and (rezzed? %)
(ice? %)
(has-subtype? % "NEXT"))
(all-installed state :corp))
{:optional
{:prompt "Do 1 brain damage with NEXT Wave 2?"
:yes-ability {:msg "do 1 brain damage"
:async true
:effect (effect (damage eid :brain 1 {:card card}))}}})
card nil))}})
(defcard "Nisei MK II"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:req (req (:run @state))
:cost [:agenda 1]
:msg "end the run"
:async true
:effect (effect (end-run eid card))}]})
(defcard "Oaktown Renovation"
{:install-state :face-up
:events [{:event :advance
:req (req (same-card? card target))
:msg (msg "gain " (if (>= (get-counters (get-card state card) :advancement) 5) "3" "2") " [Credits]")
:async true
:effect (effect (gain-credits eid (if (<= 5 (get-counters (get-card state card) :advancement)) 3 2)))}]})
(defcard "Obokata Protocol"
{:steal-cost-bonus (req [:net 4])})
(defcard "Orbital Superiority"
{:on-score
{:msg (msg (if (is-tagged? state) "do 4 meat damage" "give the Runner 1 tag"))
:async true
:effect (req (if (is-tagged? state)
(damage state :corp eid :meat 4 {:card card})
(gain-tags state :corp eid 1)))}})
(defcard "Paper Trail"
{:on-score
{:trace
{:base 6
:successful
{:msg "trash all connection and job resources"
:async true
:effect (req (let [resources (filter #(or (has-subtype? % "Job")
(has-subtype? % "Connection"))
(all-active-installed state :runner))]
(trash-cards state side eid resources)))}}}})
(defcard "Personality Profiles"
(let [pp {:req (req (pos? (count (:hand runner))))
:async true
:effect (req (let [c (first (shuffle (:hand runner)))]
(system-msg state side (str "uses Personality Profiles to force the Runner to trash "
(:title c) " from their Grip at random"))
(trash state side eid c nil)))}]
{:events [(assoc pp :event :searched-stack)
(assoc pp
:event :runner-install
:req (req (and (some #{:discard} (:previous-zone (:card context)))
(pos? (count (:hand runner))))))]}))
(defcard "Philotic Entanglement"
{:on-score {:interactive (req true)
:req (req (pos? (count (:scored runner))))
:msg (msg "do " (count (:scored runner)) " net damage")
:effect (effect (damage eid :net (count (:scored runner)) {:card card}))}})
(defcard "Posted Bounty"
{:on-score {:optional
{:prompt "Forfeit Posted Bounty to give the Runner 1 tag and take 1 bad publicity?"
:yes-ability
{:msg "give the Runner 1 tag and take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1)
(gain-tags :corp eid 1)
(forfeit card))}}}})
(defcard "Priority Requisition"
{:on-score {:interactive (req true)
:choices {:card #(and (ice? %)
(not (rezzed? %))
(installed? %))}
:async true
:effect (effect (rez eid target {:ignore-cost :all-costs}))}})
(defcard "Private Security Force"
{:abilities [{:req (req tagged)
:cost [:click 1]
:effect (effect (damage eid :meat 1 {:card card}))
:msg "do 1 meat damage"}]})
(defcard "Profiteering"
{:on-score {:interactive (req true)
:choices ["0" "1" "2" "3"]
:prompt "How many bad publicity?"
:msg (msg "take " target " bad publicity and gain " (* 5 (str->int target)) " [Credits]")
:async true
:effect (req (let [bp (count-bad-pub state)]
(wait-for (gain-bad-publicity state :corp (str->int target))
(if (< bp (count-bad-pub state))
(gain-credits state :corp eid (* 5 (str->int target)))
(effect-completed state side eid)))))}})
(defcard "Project Ares"
(letfn [(trash-count-str [card]
(quantify (- (get-counters card :advancement) 4) "installed card"))]
{:on-score {:player :runner
:silent (req true)
:req (req (and (< 4 (get-counters (:card context) :advancement))
(pos? (count (all-installed state :runner)))))
:waiting-prompt "Runner to trash installed cards"
:prompt (msg "Select " (trash-count-str (:card context)) " installed cards to trash")
:choices {:max (req (min (- (get-counters (:card context) :advancement) 4)
(count (all-installed state :runner))))
:card #(and (runner? %)
(installed? %))}
:msg (msg "force the Runner to trash " (trash-count-str (:card context)) " and take 1 bad publicity")
:async true
:effect (req (wait-for (trash-cards state side targets)
(system-msg state side (str "trashes " (string/join ", " (map :title targets))))
(gain-bad-publicity state :corp eid 1)))}}))
(defcard "Project Atlas"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (max 0 (- (get-counters (:card context) :advancement) 3))))}
:abilities [{:cost [:agenda 1]
:prompt "Choose a card"
:label "Search R&D and add 1 card to HQ"
;; we need the req or the prompt will still show
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add " (:title target) " to HQ from R&D")
:choices (req (cancellable (:deck corp) :sorted))
:cancel-effect (effect (system-msg "cancels the effect of Project Atlas"))
:effect (effect (shuffle! :deck)
(move target :hand))}]})
(defcard "Project Beale"
{:agendapoints-runner (req 2)
:agendapoints-corp (req (+ 2 (get-counters card :agenda)))
:on-score {:interactive (req true)
:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2))
(update-all-agenda-points)
(check-win-by-agenda))}})
(defcard "Project Kusanagi"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 2)))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :kusanagi])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :kusanagi])))}]
:abilities [{:label "Give a piece of ICE \"[Subroutine] Do 1 net damage\""
:prompt "Choose a piece of ICE"
:choices {:card #(and (ice? %)
(rezzed? %))}
:cost [:agenda 1]
:msg (str "make a piece of ICE gain \"[Subroutine] Do 1 net damage\" "
"after all its other subroutines for the remainder of the run")
:effect (effect (add-extra-sub! (get-card state target)
(do-net-damage 1)
(:cid card) {:back true})
(update! (update-in card [:special :kusanagi] #(conj % target))))}]})
(defcard "Project Vacheron"
(let [vacheron-ability
{:req (req (and (in-scored? card)
(not= (first (:previous-zone card)) :discard)
(same-card? card (or (:card context) target))))
:msg (msg "add 4 agenda counters on " (:title card))
:effect (effect (add-counter (get-card state card) :agenda 4)
(update! (assoc-in (get-card state card) [:special :vacheron] true)))}]
{:agendapoints-runner (req (if (or (= (first (:previous-zone card)) :discard)
(and (get-in card [:special :vacheron])
(zero? (get-counters card :agenda)))) 3 0))
:stolen vacheron-ability
:events [(assoc vacheron-ability :event :as-agenda)
{:event :runner-turn-begins
:req (req (pos? (get-counters card :agenda)))
:msg (msg "remove 1 agenda token from " (:title card))
:effect (req (when (pos? (get-counters card :agenda))
(add-counter state side card :agenda -1))
(update-all-agenda-points state side)
(when (zero? (get-counters (get-card state card) :agenda))
(let [points (get-agenda-points (get-card state card))]
(system-msg state :runner
(str "gains " (quantify points "agenda point")
" from " (:title card)))))
(check-win-by-agenda state side))}]
:flags {:has-events-when-stolen true}}))
(defcard "Project Vitruvius"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "Add 1 card from Archives to HQ"
:prompt "Choose a card in Archives to add to HQ"
:show-discard true
:choices {:card #(and (in-discard? %)
(corp? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add "
(if (:seen target)
(:title target) "an unseen card ")
" to HQ from Archives")
:effect (effect (move target :hand))}]})
(defcard "Project Wotan"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :wotan])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :wotan])))}]
:abilities [{:req (req (and current-ice
(rezzed? current-ice)
(has-subtype? current-ice "Bioroid")
(= :approach-ice (:phase run))))
:cost [:agenda 1]
:msg (str "make the approached piece of Bioroid ICE gain \"[Subroutine] End the run\""
"after all its other subroutines for the remainder of this run")
:effect (effect (add-extra-sub! (get-card state current-ice)
{:label "End the run"
:msg "end the run"
:async true
:effect (effect (end-run eid card))}
(:cid card) {:back true})
(update! (update-in card [:special :wotan] #(conj % current-ice))))}]})
(defcard "Project Yagi-Uda"
(letfn [(put-back-counter [state side card]
(update! state side (assoc-in card [:counter :agenda] (+ 1 (get-counters card :agenda)))))
(choose-swap [to-swap]
{:prompt (str "Select a card in HQ to swap with " (:title to-swap))
:choices {:not-self true
:card #(and (corp? %)
(in-hand? %)
(if (ice? to-swap)
(ice? %)
(or (agenda? %)
(asset? %)
(upgrade? %))))}
:msg (msg "swap " (card-str state to-swap) " with a card from HQ")
:effect (effect (swap-cards to-swap target))
:cancel-effect (effect (put-back-counter card))})
(choose-card [run-server]
{:waiting-prompt "Corp to use Project Yagi-Uda"
:prompt "Choose a card in or protecting the attacked server."
:choices {:card #(= (first run-server) (second (get-zone %)))}
:effect (effect (continue-ability (choose-swap target) card nil))
:cancel-effect (effect (put-back-counter card))})]
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "swap card in HQ with installed card"
:req (req run)
:effect (effect (continue-ability (choose-card (:server run)) card nil))}]}))
(defcard "Puppet Master"
{:events [{:event :successful-run
:player :corp
:interactive (req true)
:waiting-prompt "Corp to use Puppet Master"
:prompt "Select a card to place 1 advancement token on"
:choices {:card can-be-advanced?}
:msg (msg "place 1 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 1 {:placed true}))}]})
(defcard "Quantum Predictive Model"
{:flags {:rd-reveal (req true)}
:access {:req (req tagged)
:player :runner
:async true
:interactive (req true)
:prompt "Quantum Predictive Model was added to the corp's score area"
:choices ["OK"]
:msg "add it to their score area and gain 1 agenda point"
:effect (effect (as-agenda :corp eid card 1))}})
(defcard "Rebranding Team"
{:on-score {:msg "make all assets gain Advertisement"}
:swapped {:msg "make all assets gain Advertisement"}
:constant-effects [{:type :gain-subtype
:req (req (asset? target))
:value "Advertisement"}]})
(defcard "Reeducation"
(letfn [(corp-final [chosen original]
{:prompt (str "The bottom cards of R&D will be " (string/join ", " (map :title chosen)) ".")
:choices ["Done" "Start over"]
:async true
:msg (req (let [n (count chosen)]
(str "add " n " cards from HQ to the bottom of R&D and draw " n " cards."
" The Runner randomly adds " (if (<= n (count (:hand runner))) n 0)
" cards from their Grip to the bottom of the Stack")))
:effect (req (let [n (count chosen)]
(if (= target "Done")
(do (doseq [c (reverse chosen)] (move state :corp c :deck))
(draw state :corp n)
; if corp chooses more cards than runner's hand, don't shuffle runner hand back into Stack
(when (<= n (count (:hand runner)))
(doseq [r (take n (shuffle (:hand runner)))] (move state :runner r :deck)))
(effect-completed state side eid))
(continue-ability state side (corp-choice original '() original) card nil))))})
(corp-choice [remaining chosen original] ; Corp chooses cards until they press 'Done'
{:prompt "Choose a card to move to bottom of R&D"
:choices (conj (vec remaining) "Done")
:async true
:effect (req (let [chosen (cons target chosen)]
(if (not= target "Done")
(continue-ability
state side
(corp-choice (remove-once #(= target %) remaining) chosen original)
card nil)
(if (pos? (count (remove #(= % "Done") chosen)))
(continue-ability state side (corp-final (remove #(= % "Done") chosen) original) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid))))))})]
{:on-score {:async true
:waiting-prompt "Corp to add cards from HQ to bottom of R&D"
:effect (req (let [from (get-in @state [:corp :hand])]
(if (pos? (count from))
(continue-ability state :corp (corp-choice from '() from) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid)))))}}))
(defcard "Remastered Edition"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg (msg "place 1 advancement token on " (card-str state target))
:label "place 1 advancement token"
:choices {:card installed?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "Remote Data Farm"
{:on-score {:silent (req true)
:msg "increase their maximum hand size by 2"}
:constant-effects [(corp-hand-size+ 2)]})
(defcard "Remote Enforcement"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Research Grant"
{:on-score {:interactive (req true)
:silent (req (empty? (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:async true
:effect (effect (continue-ability
{:prompt "Select another installed copy of Research Grant to score"
:choices {:card #(= (:title %) "Research Grant")}
:interactive (req true)
:async true
:req (req (seq (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:effect (effect (score eid (get-card state target) {:no-req true}))
:msg "score another installed copy of Research Grant"}
card nil))}})
(defcard "Restructured Datapool"
{:abilities [{:cost [:click 1]
:label "give runner 1 tag"
:trace {:base 2
:successful {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}}}]})
(defcard "SDS Drone Deployment"
{:steal-cost-bonus (req [:program 1])
:on-score {:req (req (seq (all-installed-runner-type state :program)))
:waiting-prompt "Corp to trash a card"
:prompt "Select a program to trash"
:choices {:card #(and (installed? %)
(program? %))
:all true}
:msg (msg "trash " (:title target))
:async true
:effect (effect (trash eid target))}})
(defcard "Self-Destruct Chips"
{:on-score {:silent (req true)
:msg "decrease the Runner's maximum hand size by 1"}
:constant-effects [(runner-hand-size+ -1)]})
(defcard "Sensor Net Activation"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req (some #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))
(all-installed state :corp)))
:label "Choose a bioroid to rez, ignoring all costs"
:prompt "Choose a bioroid to rez, ignoring all costs"
:choices {:card #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))}
:msg (msg "rez " (card-str state target) ", ignoring all costs")
:async true
:effect (req (wait-for (rez state side target {:ignore-cost :all-costs})
(let [c (:card async-result)]
(register-events
state side card
[{:event (if (= side :corp) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:effect (effect (derez c))}])
(effect-completed state side eid))))}]})
(defcard "Sentinel Defense Program"
{:events [{:event :pre-resolve-damage
:req (req (and (= target :brain)
(pos? (last targets))))
:msg "do 1 net damage"
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Show of Force"
{:on-score {:async true
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}})
(defcard "SSL Endorsement"
(let [add-credits (effect (add-counter card :credit 9))]
{:flags {:has-events-when-stolen true}
:on-score {:effect add-credits
:interactive (req true)}
:abilities [(set-autoresolve :auto-fire "whether to take credits off SSL")]
:stolen {:effect add-credits}
:events [{:event :corp-turn-begins
:optional
{:req (req (pos? (get-counters card :credit)))
:once :per-turn
:prompt "Gain 3 [Credits] from SSL Endorsement?"
:autoresolve (get-autoresolve :auto-fire)
:yes-ability
{:async true
:msg (msg "gain " (min 3 (get-counters card :credit)) " [Credits]")
:effect (req (if (pos? (get-counters card :credit))
(do (add-counter state side card :credit -3)
(gain-credits state :corp eid 3))
(effect-completed state side eid)))}}}]}))
(defcard "Standoff"
(letfn [(stand [side]
{:async true
:prompt "Choose one of your installed cards to trash due to Standoff"
:choices {:card #(and (installed? %)
(same-side? side (:side %)))}
:cancel-effect (req (if (= side :runner)
(wait-for (draw state :corp 1 nil)
(clear-wait-prompt state :corp)
(system-msg state :runner "declines to trash a card due to Standoff")
(system-msg state :corp "draws a card and gains 5 [Credits] from Standoff")
(gain-credits state :corp eid 5))
(do (system-msg state :corp "declines to trash a card from Standoff")
(clear-wait-prompt state :runner)
(effect-completed state :corp eid))))
:effect (req (wait-for (trash state side target {:unpreventable true})
(system-msg state side (str "trashes " (card-str state target) " due to Standoff"))
(clear-wait-prompt state (other-side side))
(show-wait-prompt state side (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability state (other-side side) (stand (other-side side)) card nil)))})]
{:on-score
{:interactive (req true)
:async true
:effect (effect (show-wait-prompt (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability :runner (stand :runner) card nil))}}))
(defcard "Sting!"
(letfn [(count-opp-stings [state side]
(count (filter #(= (:title %) "Sting!") (get-in @state [(other-side side) :scored]))))]
{:on-score {:msg (msg "deal " (inc (count-opp-stings state :corp)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :corp)) {:card card}))}
:stolen {:msg (msg "deal " (inc (count-opp-stings state :runner)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :runner)) {:card card}))}}))
(defcard "Successful Field Test"
(letfn [(sft [n max-ops]
{:prompt "Select a card in HQ to install with Successful Field Test"
:async true
:choices {:card #(and (corp? %)
(not (operation? %))
(in-hand? %))}
:effect (req (wait-for
(corp-install state side target nil {:ignore-all-cost true})
(continue-ability state side (when (< n max-ops) (sft (inc n) max-ops)) card nil)))})]
{:on-score {:async true
:msg "install cards from HQ, ignoring all costs"
:effect (req (let [max-ops (count (filter (complement operation?) (:hand corp)))]
(continue-ability state side (sft 1 max-ops) card nil)))}}))
(defcard "Superconducting Hub"
{:constant-effects [{:type :hand-size
:req (req (= :corp side))
:value 2}]
:on-score
{:optional
{:prompt "Draw 2 cards?"
:yes-ability {:msg "draw 2 cards"
:async true
:effect (effect (draw :corp eid 2 nil))}}}})
(defcard "Superior Cyberwalls"
(ice-boost-agenda "Barrier"))
(defcard "TGTBT"
{:flags {:rd-reveal (req true)}
:access {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}})
(defcard "The Cleaners"
{:events [{:event :pre-damage
:req (req (and (= target :meat)
(= side :corp)))
:msg "do 1 additional meat damage"
:effect (effect (damage-bonus :meat 1))}]})
(defcard "The Future is Now"
{:on-score {:interactive (req true)
:prompt "Choose a card to add to HQ"
:choices (req (:deck corp))
:msg (msg "add a card from R&D to HQ and shuffle R&D")
:req (req (pos? (count (:deck corp))))
:effect (effect (shuffle! :deck)
(move target :hand))}})
(defcard "The Future Perfect"
{:flags {:rd-reveal (req true)}
:access {:psi {:req (req (not installed))
:not-equal
{:msg "prevent it from being stolen"
:effect (effect (register-run-flag!
card :can-steal
(fn [_ _ c] (not (same-card? c card))))
(effect-completed eid))}}}})
(defcard "Timely Public Release"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:cost [:agenda 1]
:label "Install a piece of ice in any position, ignoring all costs"
:prompt "Select a piece of ice to install"
:show-discard true
:choices {:card #(and (ice? %)
(or (in-hand? %)
(in-discard? %)))}
:msg (msg "install "
(if (and (in-discard? target)
(or (faceup? target)
(not (facedown? target))))
(:title target)
"ICE")
" from " (zone->name (get-zone target)))
:async true
:effect (effect
(continue-ability
(let [chosen-ice target]
{:prompt "Choose a server"
:choices (req servers)
:async true
:effect (effect
(continue-ability
(let [chosen-server target
num-ice (count (get-in (:corp @state)
(conj (server->zone state target) :ices)))]
{:prompt "Which position to install in? (0 is innermost)"
:choices (vec (reverse (map str (range (inc num-ice)))))
:async true
:effect (req (let [target (Integer/parseInt target)]
(wait-for (corp-install
state side chosen-ice chosen-server
{:ignore-all-cost true :index target})
(when (and run
(= (zone->name (first (:server run)))
chosen-server))
(let [curr-pos (get-in @state [:run :position])]
(when (< target curr-pos)
(swap! state update-in [:run :position] inc))))
(effect-completed state side eid))))})
card nil))})
card nil))}]})
(defcard "Tomorrow's Headline"
(let [ability
{:interactive (req true)
:msg "give Runner 1 tag"
:async true
:effect (req (gain-tags state :corp eid 1))}]
{:on-score ability
:stolen ability}))
(defcard "Transport Monopoly"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:agenda 1]
:req (req run)
:msg "prevent this run from becoming successful"
:effect (effect (register-floating-effect
card
{:type :block-successful-run
:duration :end-of-run
:value true}))}]})
(defcard "Underway Renovation"
(letfn [(adv4? [s c] (if (>= (get-counters (get-card s c) :advancement) 4) 2 1))]
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:msg (msg (if (pos? (count (:deck runner)))
(str "trash "
(string/join ", " (map :title (take (adv4? state card) (:deck runner))))
" from the Runner's stack")
"trash from the Runner's stack but it is empty"))
:effect (effect (mill :corp eid :runner (adv4? state card)))}]}))
(defcard "Unorthodox Predictions"
{:implementation "Prevention of subroutine breaking is not enforced"
:on-score {:prompt "Choose an ICE type for Unorthodox Predictions"
:choices ["Barrier" "Code Gate" "Sentry"]
:msg (msg "prevent subroutines on " target " ICE from being broken until next turn.")}})
(defcard "Utopia Fragment"
{:events [{:event :pre-steal-cost
:req (req (pos? (get-counters target :advancement)))
:effect (req (let [counter (get-counters target :advancement)]
(steal-cost-bonus state side [:credit (* 2 counter)])))}]})
(defcard "Vanity Project"
;; No special implementation
{})
(defcard "Veterans Program"
{:on-score {:interactive (req true)
:msg "lose 2 bad publicity"
:effect (effect (lose-bad-publicity 2))}})
(defcard "Viral Weaponization"
{:on-score
{:effect
(effect
(register-events
card
[{:event (if (= :corp (:active-player @state)) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:msg (msg "do " (count (:hand runner)) " net damage")
:async true
:effect (effect (damage eid :net (count (:hand runner)) {:card card}))}]))}})
(defcard "Voting Machine Initiative"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :runner-turn-begins
:optional
{:player :corp
:req (req (pos? (get-counters card :agenda)))
:waiting-prompt "Corp to use Voting Machine Initiative"
:prompt "Use Voting Machine Initiative to make the Runner lose 1 [Click]?"
:yes-ability
{:msg "make the Runner lose 1 [Click]"
:effect (effect (lose :runner :click 1)
(add-counter card :agenda -1))}}}]})
(defcard "Vulnerability Audit"
{:flags {:can-score (req (let [result (not= :this-turn (installed? card))]
(when-not result
(toast state :corp "Cannot score Vulnerability Audit the turn it was installed." "warning"))
result))}})
(defcard "Vulcan Coverup"
{:on-score {:interactive (req true)
:msg "do 2 meat damage"
:async true
:effect (effect (damage eid :meat 2 {:card card}))}
:stolen {:msg "force the Corp to take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1))}})
(defcard "Water Monopoly"
{:constant-effects [{:type :install-cost
:req (req (and (resource? target)
(not (has-subtype? target "Virtual"))
(not (:facedown (second targets)))))
:value 1}]})
|
55506
|
(ns game.cards.agendas
(:require [game.core :refer :all]
[game.utils :refer :all]
[jinteki.utils :refer :all]
[clojure.string :as string]
[clojure.set :as clj-set]))
(defn ice-boost-agenda [subtype]
(letfn [(count-ice [corp]
(reduce (fn [c server]
(+ c (count (filter #(and (has-subtype? % subtype)
(rezzed? %))
(:ices server)))))
0
(flatten (seq (:servers corp)))))]
{:on-score {:msg (msg "gain " (count-ice corp) " [Credits]")
:interactive (req true)
:async true
:effect (effect (gain-credits eid (count-ice corp)))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target subtype))
:value 1}]}))
;; Card definitions
(defcard "15 Minutes"
{:abilities [{:cost [:click 1]
:msg "shuffle 15 Minutes into R&D"
:label "Shuffle 15 Minutes into R&D"
:effect (effect (move :corp card :deck nil)
(shuffle! :corp :deck)
(update-all-agenda-points))}]
:flags {:has-abilities-when-stolen true}})
(defcard "Above the Law"
{:on-score
{:interactive (req true)
:prompt "Select resource"
:req (req (some #(and (installed? %)
(resource? %))
(all-active-installed state :runner)))
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (card-str state target))
:async true
:effect (effect (trash eid target))}})
(defcard "Accelerated Beta Test"
(letfn [(abt [titles choices]
{:async true
:prompt (str "The top 3 cards of R&D: " titles)
:choices (concat (filter ice? choices) ["Done"])
:effect (req (if (= target "Done")
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
(wait-for (corp-install state side target nil
{:ignore-all-cost true
:install-state :rezzed-no-cost})
(let [choices (remove-once #(= target %) choices)]
(cond
;; Shuffle ends the ability
(get-in (get-card state card) [:special :shuffle-occurred])
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
;; There are still ice left
(seq (filter ice? choices))
(continue-ability
state side (abt titles choices) card nil)
;; Trash what's left
:else
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true})))))))})
(suffer [titles choices]
{:prompt (str "The top 3 cards of R&D: " titles
". None are ice. Say goodbye!")
:choices ["I have no regrets"]
:async true
:effect (effect (system-msg (str "trashes " (quantify (count choices) "card")))
(trash-cards eid choices {:unpreventable true}))})]
{:on-score
{:interactive (req true)
:optional
{:prompt "Look at the top 3 cards of R&D?"
:yes-ability
{:async true
:msg "look at the top 3 cards of R&D"
:effect (req (register-events
state side card
[{:event :corp-shuffle-deck
:effect (effect (update! (assoc-in card [:special :shuffle-occurred] true)))}])
(let [choices (take 3 (:deck corp))
titles (string/join ", " (map :title choices))]
(continue-ability
state side
(if (seq (filter ice? choices))
(abt titles choices)
(suffer titles choices))
card nil)))}}}}))
(defcard "Advanced Concept Hopper"
{:events
[{:event :run
:req (req (first-event? state side :run))
:player :corp
:once :per-turn
:async true
:waiting-prompt "Corp to use Advanced Concept Hopper"
:prompt "Use Advanced Concept Hopper to draw 1 card or gain 1 [Credits]?"
:choices ["Draw 1 card" "Gain 1 [Credits]" "No action"]
:effect (req (case target
"Gain 1 [Credits]"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to gain 1 [Credits]"))
(gain-credits state :corp eid 1))
"Draw 1 card"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to draw 1 card"))
(draw state :corp eid 1 nil))
"No action"
(do (system-msg state :corp (str "doesn't use Advanced Concept Hopper"))
(effect-completed state side eid))))}]})
(defcard "Ancestral Imager"
{:events [{:event :jack-out
:msg "do 1 net damage"
:async true
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "AR-Enhanced Security"
{:events [{:event :runner-trash
:async true
:interactive (req true)
:once-per-instance true
:req (req (and (some #(corp? (:card %)) targets)
(first-event? state side :runner-trash
(fn [targets] (some #(corp? (:card %)) targets)))))
:msg "give the Runner a tag"
:effect (effect (gain-tags eid 1))}]})
(defcard "Architect Deployment Test"
{:on-score
{:interactive (req true)
:async true
:msg "look at the top 5 cards of R&D"
:prompt (msg "The top cards of R&D are (top->bottom) " (string/join ", " (map :title (take 5 (:deck corp)))))
:choices ["OK"]
:effect (effect (continue-ability
{:prompt "Install a card?"
:choices (cancellable (filter corp-installable-type? (take 5 (:deck corp))))
:async true
:effect (effect (corp-install eid target nil
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))
:cancel-effect (effect (system-msg "does not install any of the top 5 cards")
(effect-completed eid))}
card nil))}})
(defcard "Armed Intimidation"
{:on-score
{:player :runner
:async true
:waiting-prompt "Runner to suffer 5 meat damage or take 2 tags"
:prompt "Choose Armed Intimidation score effect"
:choices ["Suffer 5 meat damage" "Take 2 tags"]
:effect (req (case target
"Suffer 5 meat damage"
(do (system-msg state :runner "chooses to suffer 5 meat damage from Armed Intimidation")
(damage state :runner eid :meat 5 {:card card :unboostable true}))
"Take 2 tags"
(do (system-msg state :runner "chooses to take 2 tags from Armed Intimidation")
(gain-tags state :runner eid 2 {:card card}))
; else
(effect-completed state side eid)))}})
(defcard "Armored Servers"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req run)
:label "increase cost to break subroutines or jack out"
:msg "make the Runner trash a card from their grip to jack out or break subroutines for the remainder of the run"
:effect (effect (register-floating-effect
card
{:type :break-sub-additional-cost
:duration :end-of-run
:value (req (repeat (count (:broken-subs (second targets))) [:trash-from-hand 1]))})
(register-floating-effect
card
{:type :jack-out-additional-cost
:duration :end-of-run
:value [:trash-from-hand 1]}))}]})
(defcard "AstroScript Pilot Program"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:msg (msg "place 1 advancement token on " (card-str state target))
:choices {:card can-be-advanced?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "<NAME>"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not-empty (filter #(can-be-advanced? %) (all-installed state :corp))))
:waiting-prompt "Corp to place advancement tokens with Award Bait"
:prompt "How many advancement tokens?"
:choices ["0" "1" "2"]
:effect (effect (continue-ability
(let [c (str->int target)]
{:choices {:card can-be-advanced?}
:msg (msg "place " (quantify c "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter c {:placed true}))})
card nil))}})
(defcard "Bacterial Programming"
(letfn [(hq-step [remaining to-trash to-hq]
{:async true
:prompt "Select a card to move to HQ"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(wait-for (trash-cards state :corp to-trash {:unpreventable true})
(doseq [h to-hq]
(move state :corp h :hand))
(if (seq remaining)
(continue-ability state :corp (reorder-choice :corp (vec remaining)) card nil)
(do (system-msg state :corp
(str "uses Bacterial Programming to add " (count to-hq)
" cards to HQ, discard " (count to-trash)
", and arrange the top cards of R&D"))
(effect-completed state :corp eid))))
(continue-ability state :corp (hq-step
(clj-set/difference (set remaining) (set [target]))
to-trash
(conj to-hq target)) card nil)))})
(trash-step [remaining to-trash]
{:async true
:prompt "Select a card to discard"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(continue-ability state :corp (hq-step remaining to-trash '()) card nil)
(continue-ability state :corp (trash-step
(clj-set/difference (set remaining) (set [target]))
(conj to-trash target)) card nil)))})]
(let [arrange-rd
{:interactive (req true)
:optional
{:waiting-prompt "Corp to use Bacterial Programming"
:prompt "Arrange top 7 cards of R&D?"
:yes-ability
{:async true
:effect (req (let [c (take 7 (:deck corp))]
(when (:access @state)
(swap! state assoc-in [:run :shuffled-during-access :rd] true))
(continue-ability state :corp (trash-step c '()) card nil)))}}}]
{:on-score arrange-rd
:stolen arrange-rd})))
(defcard "<NAME>"
{:steal-cost-bonus (req [:credit 5])
:on-score {:async true
:msg "gain 5 [Credits]"
:effect (effect (gain-credits :corp eid 5))}})
(defcard "Better Citizen Program"
{:events [{:event :play-event
:optional
{:player :corp
:req (req (and (has-subtype? (:card context) "Run")
(first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))
(no-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for playing a run event"
:effect (effect (gain-tags :corp eid 1))}}}
{:event :runner-install
:silent (req true)
:optional
{:player :corp
:req (req (and (not (:facedown context))
(has-subtype? (:card context) "Icebreaker")
(first-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))
(no-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for installing an icebreaker"
:effect (effect (gain-tags :corp eid 1))}}}]})
(defcard "Bifrost Array"
{:on-score
{:optional
{:req (req (seq (filter #(not= (:title %) "Bifrost Array") (:scored corp))))
:prompt "Trigger the ability of a scored agenda?"
:yes-ability
{:prompt "Select an agenda to trigger its \"when scored\" ability"
:choices {:card #(and (agenda? %)
(not= (:title %) "Bifrost Array")
(in-scored? %)
(when-scored? %))}
:msg (msg "trigger the \"when scored\" ability of " (:title target))
:async true
:effect (effect (continue-ability (:on-score (card-def target)) target nil))}}}})
(defcard "Brain Rewiring"
{:on-score
{:optional
{:waiting-prompt "Corp to use Brain Rewiring"
:prompt "Pay credits to add random cards from Runner's Grip to the bottom of their Stack?"
:yes-ability
{:prompt "How many credits?"
:choices {:number (req (min (:credit corp)
(count (:hand runner))))}
:async true
:effect (req (if (pos? target)
(wait-for
(pay state :corp card :credit target)
(let [from (take target (shuffle (:hand runner)))]
(doseq [c from]
(move state :runner c :deck))
(system-msg state side (str "uses Brain Rewiring to pay " target
" [Credits] and add " target
" cards from the Runner's Grip"
" to the bottom of their Stack."
" The Runner draws 1 card"))
(draw state :runner eid 1 nil)))
(effect-completed state side eid)))}}}})
(defcard "Braintrust"
{:on-score {:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2)))
:silent (req true)}
:constant-effects [{:type :rez-cost
:req (req (ice? target))
:value (req (- (get-counters card :agenda)))}]})
(defcard "Breaking News"
{:on-score {:async true
:silent (req true)
:msg "give the Runner 2 tags"
:effect (effect (gain-tags :corp eid 2))}
:events (let [event {:unregister-once-resolved true
:req (effect (first-event? :agenda-scored #(same-card? card (:card (first %)))))
:msg "make the Runner lose 2 tags"
:effect (effect (lose :runner :tag 2))}]
[(assoc event :event :corp-turn-ends)
(assoc event :event :runner-turn-ends)])})
(defcard "Broad Daylight"
(letfn [(add-counters [state side card eid]
(add-counter state :corp card :agenda (count-bad-pub state))
(effect-completed state side eid))]
{:on-score
{:optional
{:prompt "Take 1 bad publicity?"
:async true
:yes-ability {:async true
:effect (req (wait-for (gain-bad-publicity state :corp 1)
(system-msg state :corp "used Broad Daylight to take 1 bad publicity")
(add-counters state side card eid)))}
:no-ability {:async true
:effect (effect (add-counters card eid))}}}
:abilities [{:cost [:click 1 :agenda 1]
:async true
:label "Do 2 meat damage"
:once :per-turn
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}]}))
(defcard "CFC Excavation Contract"
(letfn [(bucks [state]
(->> (all-active-installed state :corp)
(filter #(has-subtype? % "Bioroid"))
(count)
(* 2)))]
{:on-score
{:async true
:msg (msg "gain " (bucks state) " [Credits]")
:effect (effect (gain-credits :corp eid (bucks state)))}}))
(defcard "Character Assassination"
{:on-score
{:prompt "Select a resource to trash"
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (:title target))
:interactive (req true)
:async true
:effect (effect (trash eid target {:unpreventable true}))}})
(defcard "Chronos Project"
{:on-score
{:req (req (not (zone-locked? state :runner :discard)))
:msg "remove all cards in the Runner's Heap from the game"
:interactive (req true)
:effect (effect (move-zone :runner :discard :rfg))}})
(defcard "City Works Project"
(letfn [(meat-damage [s c] (+ 2 (get-counters (get-card s c) :advancement)))]
{:install-state :face-up
:access {:req (req installed)
:msg (msg "do " (meat-damage state card) " meat damage")
:async true
:effect (effect (damage eid :meat (meat-damage state card) {:card card}))}}))
(defcard "Clone Retirement"
{:on-score {:msg "remove 1 bad publicity"
:effect (effect (lose-bad-publicity 1))
:silent (req true)}
:stolen {:msg "force the Corp to take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}})
(defcard "Corporate Oversight A"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Oversight B"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a central server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(#{"HQ" "Archives" "R&D"} %)
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Sales Team"
(let [e {:req (req (pos? (get-counters card :credit)))
:msg "gain 1 [Credits]"
:async true
:effect (req (add-counter state side card :credit -1)
(gain-credits state :corp eid 1))}]
{:on-score {:effect (effect (add-counter card :credit 10))
:silent (req true)}
:events [(assoc e :event :runner-turn-begins)
(assoc e :event :corp-turn-begins)]}))
(defcard "Corporate War"
{:on-score
{:msg (msg (if (> (:credit corp) 6) "gain 7 [Credits]" "lose all credits"))
:interactive (req true)
:async true
:effect (req (if (> (:credit corp) 6)
(gain-credits state :corp eid 7)
(lose-credits state :corp eid :all)))}})
(defcard "Crisis Management"
(let [ability {:req (req tagged)
:async true
:label "Do 1 meat damage (start of turn)"
:once :per-turn
:msg "do 1 meat damage"
:effect (effect (damage eid :meat 1 {:card card}))}]
{:events [(assoc ability :event :corp-turn-begins)]
:abilities [ability]}))
(defcard "Cyberdex Sandbox"
{:on-score {:optional
{:prompt "Purge virus counters with Cyberdex Sandbox?"
:yes-ability {:msg (msg "purge virus counters")
:effect (effect (purge))}}}
:events [{:event :purge
:req (req (first-event? state :corp :purge))
:once :per-turn
:msg "gain 4 [Credits]"
:async true
:effect (req (gain-credits state :corp eid 4))}]})
(defcard "Dedicated Neural Net"
{:events [{:event :successful-run
:interactive (req true)
:psi {:req (req (= :hq (target-server context)))
:once :per-turn
:not-equal {:effect (effect (register-floating-effect
card
{:type :corp-choose-hq-access
:duration :end-of-access
:value true})
(effect-completed eid))}}}]})
(defcard "<NAME>"
{:steal-cost-bonus (req [:shuffle-installed-to-stack 2])})
(defcard "Director Haas' Pet Project"
(letfn [(install-ability [server-name n]
{:prompt "Select a card to install"
:show-discard true
:choices {:card #(and (corp? %)
(not (operation? %))
(or (in-hand? %)
(in-discard? %)))}
:msg (msg (corp-install-msg target)
(when (zero? n)
", creating a new remote server")
", ignoring all install costs")
:async true
:effect (req (wait-for (corp-install state side target server-name {:ignore-all-cost true})
(continue-ability state side
(when (< n 2)
(install-ability (last (get-remote-names state)) (inc n)))
card nil)))})]
{:on-score
{:optional
{:prompt "Install cards in a new remote server?"
:yes-ability (install-ability "New remote" 0)}}}))
(defcard "Divested Trust"
{:events
[{:event :agenda-stolen
:async true
:interactive (req true)
:effect (req (if (:winner @state)
(effect-completed state side eid)
(let [card (find-latest state card)
stolen-agenda (find-latest state (:card context))
title (:title stolen-agenda)
prompt (str "Forfeit Divested Trust to add " title
" to HQ and gain 5[Credits]?")
message (str "add " title " to HQ and gain 5 [Credits]")
agenda-side (if (in-runner-scored? state side stolen-agenda)
:runner :corp)
card-side (if (in-runner-scored? state side card)
:runner :corp)]
(continue-ability
state side
{:optional
{:waiting-prompt "Corp to use Divested Trust"
:prompt prompt
:yes-ability
{:msg message
:async true
:effect (req (wait-for (forfeit state card-side card)
(move state side stolen-agenda :hand)
(update-all-agenda-points state side)
(gain-credits state side eid 5)))}}}
card nil))))}]})
(defcard "Domestic Sleepers"
{:agendapoints-corp (req (if (pos? (get-counters card :agenda)) 1 0))
:abilities [{:cost [:click 3]
:msg "place 1 agenda counter on Domestic Sleepers"
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}]})
(defcard "Eden Fragment"
{:constant-effects [{:type :ignore-install-cost
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:value true}]
:events [{:event :corp-install
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:msg "ignore the install cost of the first ICE this turn"}]})
(defcard "Efficiency Committee"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:click 1 :agenda 1]
:effect (effect (gain :click 2)
(register-turn-flag!
card :can-advance
(fn [state side card]
((constantly false)
(toast state :corp "Cannot advance cards this turn due to Efficiency Committee." "warning")))))
:msg "gain [Click][Click]"}]})
(defcard "Elective Upgrade"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:click 1 :agenda 1]
:once :per-turn
:effect (effect (gain :click 2))
:msg "gain [Click][Click]"}]})
(defcard "Encrypted Portals"
(ice-boost-agenda "Code Gate"))
(defcard "Escalate Vitriol"
{:abilities [{:label "Gain 1 [Credit] for each Runner tag"
:cost [:click 1]
:once :per-turn
:msg (msg "gain " (count-tags state) " [Credits]")
:async true
:effect (effect (gain-credits eid (count-tags state)))}]})
(defcard "Executive Retreat"
{:on-score {:effect (effect (add-counter card :agenda 1)
(shuffle-into-deck :hand))
:interactive (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "draw 5 cards"
:effect (effect (draw 5))}]})
(defcard "Explode-a-palooza"
{:flags {:rd-reveal (req true)}
:access {:optional
{:waiting-prompt "Corp to use Explode-a-palooza"
:prompt "Gain 5 [Credits] with Explode-a-palooza ability?"
:yes-ability
{:msg "gain 5 [Credits]"
:async true
:effect (effect (gain-credits :corp eid 5))}}}})
(defcard "False Lead"
{:abilities [{:req (req (<= 2 (:click runner)))
:label "runner loses [Click][Click]"
:msg "force the Runner to lose [Click][Click]"
:cost [:forfeit-self]
:effect (effect (lose :runner :click 2))}]})
(defcard "Fetal AI"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not (in-discard? card)))
:msg "do 2 net damage"
:effect (effect (damage eid :net 2 {:card card}))}
:steal-cost-bonus (req [:credit 2])})
(defcard "Firmware Updates"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:choices {:card #(and (ice? %)
(can-be-advanced? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "place 1 advancement token on " (card-str state target))
:once :per-turn
:effect (effect (add-prop target :advance-counter 1))}]})
(defcard "<NAME>"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 5))}
:abilities [{:cost [:agenda 1]
:label "reveal and draw"
:once :per-turn
:msg (msg "reveal " (:title (first (:deck corp))) " and draw 2 cards")
:async true
:waiting-prompt "Corp to use <NAME>lower Sermon"
:effect (req (wait-for
(reveal state side (first (:deck corp)))
(wait-for
(draw state side 2 nil)
(continue-ability
state side
{:req (req (pos? (count (:hand corp))))
:prompt "Choose a card in HQ to move to the top of R&D"
:msg "add 1 card in HQ to the top of R&D"
:choices {:card #(and (in-hand? %)
(corp? %))}
:effect (effect (move target :deck {:front true})
(effect-completed eid))}
card nil))))}]})
(defcard "Fly on the Wall"
{:on-score {:msg "give the runner 1 tag"
:async true
:effect (req (gain-tags state :runner eid 1))}})
(defcard "Genetic Resequencing"
{:on-score {:choices {:card in-scored?}
:msg (msg "add 1 agenda counter on " (:title target))
:effect (effect (add-counter target :agenda 1)
(update-all-agenda-points))
:silent (req true)}})
(defcard "<NAME>"
{:on-score {:effect (effect (add-counter card :agenda 2))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "gain 7 [Credits] and take 1 bad publicity"
:async true
:effect (req (wait-for (gain-credits state side 7)
(gain-bad-publicity state side eid 1)))}]})
(defcard "Gila Hands Arcology"
{:abilities [{:cost [:click 2]
:msg "gain 3 [Credits]"
:async true
:effect (effect (gain-credits eid 3))}]})
(defcard "Glenn Station"
{:abilities [{:label "Host a card from HQ on Glenn Station"
:req (req (and (not-empty (:hand corp))
(empty? (filter corp? (:hosted card)))))
:cost [:click 1]
:msg "host a card from HQ"
:prompt "Choose a card to host on Glenn Station"
:choices {:card #(and (corp? %) (in-hand? %))}
:effect (effect (host card target {:facedown true}))}
{:label "Add a card on Glenn Station to HQ"
:req (req (not-empty (filter corp? (:hosted card))))
:cost [:click 1]
:msg "add a hosted card to HQ"
:prompt "Choose a card on Glenn Station"
:choices {:all true
:req (req (let [hosted-corp-cards
(->> (:hosted card)
(filter corp?)
(map :cid)
(into #{}))]
(hosted-corp-cards (:cid target))))}
:effect (effect (move target :hand))}]})
(defcard "Global Food Initiative"
{:agendapoints-runner (req 2)})
(defcard "Government Contracts"
{:abilities [{:cost [:click 2]
:async true
:effect (effect (gain-credits eid 4))
:msg "gain 4 [Credits]"}]})
(defcard "Government Takeover"
{:abilities [{:cost [:click 1]
:async true
:effect (effect (gain-credits eid 3))
:msg "gain 3 [Credits]"}]})
(defcard "Graft"
(letfn [(graft [n] {:prompt "Choose a card to add to HQ with Graft"
:async true
:choices (req (cancellable (:deck corp) :sorted))
:msg (msg "add " (:title target) " to HQ from R&D")
:cancel-effect (req (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))
:effect (req (move state side target :hand)
(if (< n 3)
(continue-ability state side (graft (inc n)) card nil)
(do (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))))})]
{:on-score
{:async true
:msg "add up to 3 cards from R&D to HQ"
:effect (effect (continue-ability (graft 1) card nil))}}))
(defcard "Hades Fragment"
{:flags {:corp-phase-12 (req (and (not-empty (get-in @state [:corp :discard]))
(is-scored? state :corp card)))}
:abilities [{:prompt "Select a card to add to the bottom of R&D"
:label "add card to bottom of R&D"
:show-discard true
:choices {:card #(and (corp? %)
(in-discard? %))}
:effect (effect (move target :deck))
:msg (msg "add "
(if (:seen target)
(:title target)
"a card")
" to the bottom of R&D")}]})
(defcard "Helium-3 Deposit"
{:on-score
{:async true
:interactive (req true)
:prompt "How many power counters?"
:choices ["0" "1" "2"]
:effect (req (let [c (str->int target)]
(continue-ability
state side
{:choices {:card #(pos? (get-counters % :power))}
:msg (msg "add " c " power counters on " (:title target))
:effect (effect (add-counter target :power c))}
card nil)))}})
(defcard "High-Risk Investment"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:label "gain credits"
:msg (msg "gain " (:credit runner) " [Credits]")
:async true
:effect (effect (gain-credits eid (:credit runner)))}]})
(defcard "Hollywood Renovation"
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:effect (req (let [n (if (>= (get-counters (get-card state card) :advancement) 6) 2 1)]
(continue-ability
state side
{:choices {:card #(and (not (same-card? % card))
(can-be-advanced? %))}
:msg (msg "place " (quantify n "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter n {:placed true}))}
card nil)))}]})
(defcard "Hostile Takeover"
{:on-score {: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)))
:interactive (req true)}})
(defcard "House of Knives"
{:on-score {:effect (effect (add-counter card :agenda 3))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg "do 1 net damage"
:req (req (:run @state))
:once :per-run
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Hyperloop Extension"
(let [he {:async true
:effect (req (system-msg state side (str "uses Hyperloop Extension to gain 3 [Credits]"))
(gain-credits state :corp eid 3))}]
{:on-score he
:stolen he}))
(defcard "Ikawah Project"
{:steal-cost-bonus (req [:credit 2 :click 1])})
(defcard "Illicit Sales"
{:on-score
{:async true
:effect (req (wait-for (resolve-ability
state side
{:optional
{:prompt "Take 1 bad publicity from Illicit Sales?"
:yes-ability {:msg "take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}}}
card nil)
(let [n (* 3 (count-bad-pub state))]
(system-msg state side (str "gains " n " [Credits] from Illicit Sales"))
(gain-credits state side eid n))))}})
(defcard "Improved Protein Source"
(let [ability {:async true
:interactive (req true)
:msg "make the Runner gain 4 [Credits]"
:effect (effect (gain-credits :runner eid 4))}]
{:on-score ability
:stolen ability}))
(defcard "Improved Tracers"
{:on-score {:silent (req true)
:effect (req (update-all-ice state side))}
:swapped {:effect (req (update-all-ice state side))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target "Tracer"))
:value 1}]
:events [{:event :pre-init-trace
:req (req (and (has-subtype? target "Tracer")
(= :subroutine (:source-type (second targets)))))
:effect (effect (init-trace-bonus 1))}]})
(defcard "Jumon"
{:events
[{:event :corp-turn-ends
:req (req (some #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))
(all-installed state :corp)))
:prompt "Select a card to place 2 advancement tokens on"
:player :corp
:choices {:card #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))}
:msg (msg "place 2 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 2 {:placed true}))}]})
(defcard "Labyrinthine Servers"
{:on-score {:silent (req true)
:effect (effect (add-counter card :power 2))}
:interactions {:prevent [{:type #{:jack-out}
:req (req (pos? (get-counters card :power)))}]}
:abilities [{:req (req (:run @state))
:cost [:power 1]
:msg "prevent the Runner from jacking out"
:effect (effect (jack-out-prevent))}]})
(defcard "License Acquisition"
{:on-score {:interactive (req true)
:prompt "Select an asset or upgrade to install from Archives or HQ"
:show-discard true
:choices {:card #(and (corp? %)
(or (asset? %) (upgrade? %))
(or (in-hand? %) (in-discard? %)))}
:msg (msg "install and rez " (:title target) ", ignoring all costs")
:async true
:effect (effect (corp-install eid target nil {:install-state :rezzed-no-cost}))}})
(defcard "Longevity Serum"
{:on-score
{:prompt "Select any number of cards in HQ to trash"
:choices {:max (req (count (:hand corp)))
:card #(and (corp? %)
(in-hand? %))}
:msg (msg "trash " (quantify (count targets) "card") " in HQ")
:async true
:effect (req (wait-for (trash-cards state side targets {:unpreventable true})
(shuffle-into-rd-effect state side eid card 3)))}})
(defcard "Luminal Transubstantiation"
{:on-score
{:silent (req true)
:effect (req (gain state :corp :click 3)
(register-turn-flag!
state side card :can-score
(fn [state side card]
((constantly false)
(toast state :corp "Cannot score cards this turn due to Luminal Transubstantiation." "warning")))))}})
(defcard "Mandatory Seed Replacement"
(letfn [(msr [] {:prompt "Select two pieces of ICE to swap positions"
:choices {:card #(and (installed? %)
(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 "swaps the position of "
(card-str state (first targets))
" and "
(card-str state (second targets))))
(continue-ability state side (msr) card nil))
(do (system-msg state :corp (str "has finished rearranging ICE"))
(effect-completed state side eid))))})]
{:on-score {:async true
:msg "rearrange any number of ICE"
:effect (effect (continue-ability (msr) card nil))}}))
(defcard "Mandatory Upgrades"
{:on-score {:msg "gain an additional [Click] per turn"
:silent (req true)
:effect (req (gain state :corp :click-per-turn 1))}
:swapped {:msg "gain an additional [Click] per turn"
:effect (req (when (= (:active-player @state) :corp)
(gain state :corp :click 1))
(gain state :corp :click-per-turn 1))}
:leave-play (req (lose state :corp
:click 1
:click-per-turn 1))})
(defcard "Market Research"
{:on-score {:interactive (req true)
:req (req tagged)
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 2 3))})
(defcard "Medical Breakthrough"
{:flags {:has-events-when-stolen true}
:constant-effects [{:type :advancement-requirement
:req (req (= (:title target) "Medical Breakthrough"))
:value -1}]})
(defcard "Megaprix Qualifier"
{:on-score {:silent (req true)
:req (req (< 1 (count (filter #(= (:title %) "Megaprix Qualifier")
(concat (:scored corp) (:scored runner))))))
:effect (effect (add-counter card :agenda 1))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 1 2))})
(defcard "<NAME> <NAME>"
{:agendapoints-runner (req 3)})
(defcard "Meteor Mining"
{:on-score {:interactive (req true)
:async true
:prompt "Use Meteor Mining?"
:choices (req (if (< (count-tags state) 2)
["Gain 7 [Credits]" "No action"]
["Gain 7 [Credits]" "Do 7 meat damage" "No action"]))
:effect (req (case target
"Gain 7 [Credits]"
(do (system-msg state side "uses Meteor Mining to gain 7 [Credits]")
(gain-credits state side eid 7))
"Do 7 meat damage"
(do (system-msg state side "uses Meteor Mining do 7 meat damage")
(damage state side eid :meat 7 {:card card}))
"No action"
(do (system-msg state side "does not use Meteor Mining")
(effect-completed state side eid))))}})
(defcard "NAPD Contract"
{:steal-cost-bonus (req [:credit 4])
:advancement-requirement (req (count-bad-pub state))})
(defcard "Net Quarantine"
(let [nq {:async true
:effect (req (let [extra (int (/ (:runner-spent target) 2))]
(if (pos? extra)
(do (system-msg state :corp (str "uses Net Quarantine to gain " extra "[Credits]"))
(gain-credits state side eid extra))
(effect-completed state side eid))))}]
{:events [{:event :pre-init-trace
:once :per-turn
:silent (req true)
:effect (req (system-msg state :corp "uses Net Quarantine to reduce Runner's base link to zero")
(swap! state assoc-in [:trace :force-link] 0))}
(assoc nq :event :successful-trace)
(assoc nq :event :unsuccessful-trace)]}))
(defcard "New Construction"
{:install-state :face-up
:events [{:event :advance
:optional
{:req (req (same-card? card target))
:prompt "Install a card from HQ in a new remote?"
:yes-ability {:prompt "Select a card to install"
:choices {:card #(and (not (operation? %))
(not (ice? %))
(corp? %)
(in-hand? %))}
:msg (msg "install a card from HQ"
(when (<= 5 (get-counters (get-card state card) :advancement))
" and rez it, ignoring all costs"))
:async true
:effect (effect (corp-install
eid target "New remote"
(when (<= 5 (get-counters (get-card state card) :advancement))
{:install-state :rezzed-no-cost})))}}}]})
(defcard "NEXT Wave 2"
{:on-score
{:async true
:effect
(effect
(continue-ability
(when (some #(and (rezzed? %)
(ice? %)
(has-subtype? % "NEXT"))
(all-installed state :corp))
{:optional
{:prompt "Do 1 brain damage with NEXT Wave 2?"
:yes-ability {:msg "do 1 brain damage"
:async true
:effect (effect (damage eid :brain 1 {:card card}))}}})
card nil))}})
(defcard "Nisei MK II"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:req (req (:run @state))
:cost [:agenda 1]
:msg "end the run"
:async true
:effect (effect (end-run eid card))}]})
(defcard "Oaktown Renovation"
{:install-state :face-up
:events [{:event :advance
:req (req (same-card? card target))
:msg (msg "gain " (if (>= (get-counters (get-card state card) :advancement) 5) "3" "2") " [Credits]")
:async true
:effect (effect (gain-credits eid (if (<= 5 (get-counters (get-card state card) :advancement)) 3 2)))}]})
(defcard "Obokata Protocol"
{:steal-cost-bonus (req [:net 4])})
(defcard "Orbital Superiority"
{:on-score
{:msg (msg (if (is-tagged? state) "do 4 meat damage" "give the Runner 1 tag"))
:async true
:effect (req (if (is-tagged? state)
(damage state :corp eid :meat 4 {:card card})
(gain-tags state :corp eid 1)))}})
(defcard "Paper Trail"
{:on-score
{:trace
{:base 6
:successful
{:msg "trash all connection and job resources"
:async true
:effect (req (let [resources (filter #(or (has-subtype? % "Job")
(has-subtype? % "Connection"))
(all-active-installed state :runner))]
(trash-cards state side eid resources)))}}}})
(defcard "Personality Profiles"
(let [pp {:req (req (pos? (count (:hand runner))))
:async true
:effect (req (let [c (first (shuffle (:hand runner)))]
(system-msg state side (str "uses Personality Profiles to force the Runner to trash "
(:title c) " from their Grip at random"))
(trash state side eid c nil)))}]
{:events [(assoc pp :event :searched-stack)
(assoc pp
:event :runner-install
:req (req (and (some #{:discard} (:previous-zone (:card context)))
(pos? (count (:hand runner))))))]}))
(defcard "Philotic Entanglement"
{:on-score {:interactive (req true)
:req (req (pos? (count (:scored runner))))
:msg (msg "do " (count (:scored runner)) " net damage")
:effect (effect (damage eid :net (count (:scored runner)) {:card card}))}})
(defcard "Posted Bounty"
{:on-score {:optional
{:prompt "Forfeit Posted Bounty to give the Runner 1 tag and take 1 bad publicity?"
:yes-ability
{:msg "give the Runner 1 tag and take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1)
(gain-tags :corp eid 1)
(forfeit card))}}}})
(defcard "Priority Requisition"
{:on-score {:interactive (req true)
:choices {:card #(and (ice? %)
(not (rezzed? %))
(installed? %))}
:async true
:effect (effect (rez eid target {:ignore-cost :all-costs}))}})
(defcard "Private Security Force"
{:abilities [{:req (req tagged)
:cost [:click 1]
:effect (effect (damage eid :meat 1 {:card card}))
:msg "do 1 meat damage"}]})
(defcard "Profiteering"
{:on-score {:interactive (req true)
:choices ["0" "1" "2" "3"]
:prompt "How many bad publicity?"
:msg (msg "take " target " bad publicity and gain " (* 5 (str->int target)) " [Credits]")
:async true
:effect (req (let [bp (count-bad-pub state)]
(wait-for (gain-bad-publicity state :corp (str->int target))
(if (< bp (count-bad-pub state))
(gain-credits state :corp eid (* 5 (str->int target)))
(effect-completed state side eid)))))}})
(defcard "Project Ares"
(letfn [(trash-count-str [card]
(quantify (- (get-counters card :advancement) 4) "installed card"))]
{:on-score {:player :runner
:silent (req true)
:req (req (and (< 4 (get-counters (:card context) :advancement))
(pos? (count (all-installed state :runner)))))
:waiting-prompt "Runner to trash installed cards"
:prompt (msg "Select " (trash-count-str (:card context)) " installed cards to trash")
:choices {:max (req (min (- (get-counters (:card context) :advancement) 4)
(count (all-installed state :runner))))
:card #(and (runner? %)
(installed? %))}
:msg (msg "force the Runner to trash " (trash-count-str (:card context)) " and take 1 bad publicity")
:async true
:effect (req (wait-for (trash-cards state side targets)
(system-msg state side (str "trashes " (string/join ", " (map :title targets))))
(gain-bad-publicity state :corp eid 1)))}}))
(defcard "Project Atlas"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (max 0 (- (get-counters (:card context) :advancement) 3))))}
:abilities [{:cost [:agenda 1]
:prompt "Choose a card"
:label "Search R&D and add 1 card to HQ"
;; we need the req or the prompt will still show
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add " (:title target) " to HQ from R&D")
:choices (req (cancellable (:deck corp) :sorted))
:cancel-effect (effect (system-msg "cancels the effect of Project Atlas"))
:effect (effect (shuffle! :deck)
(move target :hand))}]})
(defcard "Project Beale"
{:agendapoints-runner (req 2)
:agendapoints-corp (req (+ 2 (get-counters card :agenda)))
:on-score {:interactive (req true)
:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2))
(update-all-agenda-points)
(check-win-by-agenda))}})
(defcard "Project Kusanagi"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 2)))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :kusanagi])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :kusanagi])))}]
:abilities [{:label "Give a piece of ICE \"[Subroutine] Do 1 net damage\""
:prompt "Choose a piece of ICE"
:choices {:card #(and (ice? %)
(rezzed? %))}
:cost [:agenda 1]
:msg (str "make a piece of ICE gain \"[Subroutine] Do 1 net damage\" "
"after all its other subroutines for the remainder of the run")
:effect (effect (add-extra-sub! (get-card state target)
(do-net-damage 1)
(:cid card) {:back true})
(update! (update-in card [:special :kusanagi] #(conj % target))))}]})
(defcard "Project Vacheron"
(let [vacheron-ability
{:req (req (and (in-scored? card)
(not= (first (:previous-zone card)) :discard)
(same-card? card (or (:card context) target))))
:msg (msg "add 4 agenda counters on " (:title card))
:effect (effect (add-counter (get-card state card) :agenda 4)
(update! (assoc-in (get-card state card) [:special :vacheron] true)))}]
{:agendapoints-runner (req (if (or (= (first (:previous-zone card)) :discard)
(and (get-in card [:special :vacheron])
(zero? (get-counters card :agenda)))) 3 0))
:stolen vacheron-ability
:events [(assoc vacheron-ability :event :as-agenda)
{:event :runner-turn-begins
:req (req (pos? (get-counters card :agenda)))
:msg (msg "remove 1 agenda token from " (:title card))
:effect (req (when (pos? (get-counters card :agenda))
(add-counter state side card :agenda -1))
(update-all-agenda-points state side)
(when (zero? (get-counters (get-card state card) :agenda))
(let [points (get-agenda-points (get-card state card))]
(system-msg state :runner
(str "gains " (quantify points "agenda point")
" from " (:title card)))))
(check-win-by-agenda state side))}]
:flags {:has-events-when-stolen true}}))
(defcard "Project Vitruvius"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "Add 1 card from Archives to HQ"
:prompt "Choose a card in Archives to add to HQ"
:show-discard true
:choices {:card #(and (in-discard? %)
(corp? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add "
(if (:seen target)
(:title target) "an unseen card ")
" to HQ from Archives")
:effect (effect (move target :hand))}]})
(defcard "Project Wotan"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :wotan])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :wotan])))}]
:abilities [{:req (req (and current-ice
(rezzed? current-ice)
(has-subtype? current-ice "Bioroid")
(= :approach-ice (:phase run))))
:cost [:agenda 1]
:msg (str "make the approached piece of Bioroid ICE gain \"[Subroutine] End the run\""
"after all its other subroutines for the remainder of this run")
:effect (effect (add-extra-sub! (get-card state current-ice)
{:label "End the run"
:msg "end the run"
:async true
:effect (effect (end-run eid card))}
(:cid card) {:back true})
(update! (update-in card [:special :wotan] #(conj % current-ice))))}]})
(defcard "Project Yagi-Uda"
(letfn [(put-back-counter [state side card]
(update! state side (assoc-in card [:counter :agenda] (+ 1 (get-counters card :agenda)))))
(choose-swap [to-swap]
{:prompt (str "Select a card in HQ to swap with " (:title to-swap))
:choices {:not-self true
:card #(and (corp? %)
(in-hand? %)
(if (ice? to-swap)
(ice? %)
(or (agenda? %)
(asset? %)
(upgrade? %))))}
:msg (msg "swap " (card-str state to-swap) " with a card from HQ")
:effect (effect (swap-cards to-swap target))
:cancel-effect (effect (put-back-counter card))})
(choose-card [run-server]
{:waiting-prompt "Corp to use Project Yagi-Uda"
:prompt "Choose a card in or protecting the attacked server."
:choices {:card #(= (first run-server) (second (get-zone %)))}
:effect (effect (continue-ability (choose-swap target) card nil))
:cancel-effect (effect (put-back-counter card))})]
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "swap card in HQ with installed card"
:req (req run)
:effect (effect (continue-ability (choose-card (:server run)) card nil))}]}))
(defcard "Puppet Master"
{:events [{:event :successful-run
:player :corp
:interactive (req true)
:waiting-prompt "Corp to use Puppet Master"
:prompt "Select a card to place 1 advancement token on"
:choices {:card can-be-advanced?}
:msg (msg "place 1 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 1 {:placed true}))}]})
(defcard "Quantum Predictive Model"
{:flags {:rd-reveal (req true)}
:access {:req (req tagged)
:player :runner
:async true
:interactive (req true)
:prompt "Quantum Predictive Model was added to the corp's score area"
:choices ["OK"]
:msg "add it to their score area and gain 1 agenda point"
:effect (effect (as-agenda :corp eid card 1))}})
(defcard "Rebranding Team"
{:on-score {:msg "make all assets gain Advertisement"}
:swapped {:msg "make all assets gain Advertisement"}
:constant-effects [{:type :gain-subtype
:req (req (asset? target))
:value "Advertisement"}]})
(defcard "Reeducation"
(letfn [(corp-final [chosen original]
{:prompt (str "The bottom cards of R&D will be " (string/join ", " (map :title chosen)) ".")
:choices ["Done" "Start over"]
:async true
:msg (req (let [n (count chosen)]
(str "add " n " cards from HQ to the bottom of R&D and draw " n " cards."
" The Runner randomly adds " (if (<= n (count (:hand runner))) n 0)
" cards from their Grip to the bottom of the Stack")))
:effect (req (let [n (count chosen)]
(if (= target "Done")
(do (doseq [c (reverse chosen)] (move state :corp c :deck))
(draw state :corp n)
; if corp chooses more cards than runner's hand, don't shuffle runner hand back into Stack
(when (<= n (count (:hand runner)))
(doseq [r (take n (shuffle (:hand runner)))] (move state :runner r :deck)))
(effect-completed state side eid))
(continue-ability state side (corp-choice original '() original) card nil))))})
(corp-choice [remaining chosen original] ; Corp chooses cards until they press 'Done'
{:prompt "Choose a card to move to bottom of R&D"
:choices (conj (vec remaining) "Done")
:async true
:effect (req (let [chosen (cons target chosen)]
(if (not= target "Done")
(continue-ability
state side
(corp-choice (remove-once #(= target %) remaining) chosen original)
card nil)
(if (pos? (count (remove #(= % "Done") chosen)))
(continue-ability state side (corp-final (remove #(= % "Done") chosen) original) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid))))))})]
{:on-score {:async true
:waiting-prompt "Corp to add cards from HQ to bottom of R&D"
:effect (req (let [from (get-in @state [:corp :hand])]
(if (pos? (count from))
(continue-ability state :corp (corp-choice from '() from) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid)))))}}))
(defcard "Remastered Edition"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg (msg "place 1 advancement token on " (card-str state target))
:label "place 1 advancement token"
:choices {:card installed?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "Remote Data Farm"
{:on-score {:silent (req true)
:msg "increase their maximum hand size by 2"}
:constant-effects [(corp-hand-size+ 2)]})
(defcard "Remote Enforcement"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Research Grant"
{:on-score {:interactive (req true)
:silent (req (empty? (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:async true
:effect (effect (continue-ability
{:prompt "Select another installed copy of Research Grant to score"
:choices {:card #(= (:title %) "Research Grant")}
:interactive (req true)
:async true
:req (req (seq (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:effect (effect (score eid (get-card state target) {:no-req true}))
:msg "score another installed copy of Research Grant"}
card nil))}})
(defcard "Restructured Datapool"
{:abilities [{:cost [:click 1]
:label "give runner 1 tag"
:trace {:base 2
:successful {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}}}]})
(defcard "SDS Drone Deployment"
{:steal-cost-bonus (req [:program 1])
:on-score {:req (req (seq (all-installed-runner-type state :program)))
:waiting-prompt "Corp to trash a card"
:prompt "Select a program to trash"
:choices {:card #(and (installed? %)
(program? %))
:all true}
:msg (msg "trash " (:title target))
:async true
:effect (effect (trash eid target))}})
(defcard "Self-Destruct Chips"
{:on-score {:silent (req true)
:msg "decrease the Runner's maximum hand size by 1"}
:constant-effects [(runner-hand-size+ -1)]})
(defcard "Sensor Net Activation"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req (some #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))
(all-installed state :corp)))
:label "Choose a bioroid to rez, ignoring all costs"
:prompt "Choose a bioroid to rez, ignoring all costs"
:choices {:card #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))}
:msg (msg "rez " (card-str state target) ", ignoring all costs")
:async true
:effect (req (wait-for (rez state side target {:ignore-cost :all-costs})
(let [c (:card async-result)]
(register-events
state side card
[{:event (if (= side :corp) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:effect (effect (derez c))}])
(effect-completed state side eid))))}]})
(defcard "Sentinel Defense Program"
{:events [{:event :pre-resolve-damage
:req (req (and (= target :brain)
(pos? (last targets))))
:msg "do 1 net damage"
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Show of Force"
{:on-score {:async true
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}})
(defcard "SSL Endorsement"
(let [add-credits (effect (add-counter card :credit 9))]
{:flags {:has-events-when-stolen true}
:on-score {:effect add-credits
:interactive (req true)}
:abilities [(set-autoresolve :auto-fire "whether to take credits off SSL")]
:stolen {:effect add-credits}
:events [{:event :corp-turn-begins
:optional
{:req (req (pos? (get-counters card :credit)))
:once :per-turn
:prompt "Gain 3 [Credits] from SSL Endorsement?"
:autoresolve (get-autoresolve :auto-fire)
:yes-ability
{:async true
:msg (msg "gain " (min 3 (get-counters card :credit)) " [Credits]")
:effect (req (if (pos? (get-counters card :credit))
(do (add-counter state side card :credit -3)
(gain-credits state :corp eid 3))
(effect-completed state side eid)))}}}]}))
(defcard "Standoff"
(letfn [(stand [side]
{:async true
:prompt "Choose one of your installed cards to trash due to Standoff"
:choices {:card #(and (installed? %)
(same-side? side (:side %)))}
:cancel-effect (req (if (= side :runner)
(wait-for (draw state :corp 1 nil)
(clear-wait-prompt state :corp)
(system-msg state :runner "declines to trash a card due to Standoff")
(system-msg state :corp "draws a card and gains 5 [Credits] from Standoff")
(gain-credits state :corp eid 5))
(do (system-msg state :corp "declines to trash a card from Standoff")
(clear-wait-prompt state :runner)
(effect-completed state :corp eid))))
:effect (req (wait-for (trash state side target {:unpreventable true})
(system-msg state side (str "trashes " (card-str state target) " due to Standoff"))
(clear-wait-prompt state (other-side side))
(show-wait-prompt state side (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability state (other-side side) (stand (other-side side)) card nil)))})]
{:on-score
{:interactive (req true)
:async true
:effect (effect (show-wait-prompt (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability :runner (stand :runner) card nil))}}))
(defcard "Sting!"
(letfn [(count-opp-stings [state side]
(count (filter #(= (:title %) "Sting!") (get-in @state [(other-side side) :scored]))))]
{:on-score {:msg (msg "deal " (inc (count-opp-stings state :corp)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :corp)) {:card card}))}
:stolen {:msg (msg "deal " (inc (count-opp-stings state :runner)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :runner)) {:card card}))}}))
(defcard "Successful Field Test"
(letfn [(sft [n max-ops]
{:prompt "Select a card in HQ to install with Successful Field Test"
:async true
:choices {:card #(and (corp? %)
(not (operation? %))
(in-hand? %))}
:effect (req (wait-for
(corp-install state side target nil {:ignore-all-cost true})
(continue-ability state side (when (< n max-ops) (sft (inc n) max-ops)) card nil)))})]
{:on-score {:async true
:msg "install cards from HQ, ignoring all costs"
:effect (req (let [max-ops (count (filter (complement operation?) (:hand corp)))]
(continue-ability state side (sft 1 max-ops) card nil)))}}))
(defcard "Superconducting Hub"
{:constant-effects [{:type :hand-size
:req (req (= :corp side))
:value 2}]
:on-score
{:optional
{:prompt "Draw 2 cards?"
:yes-ability {:msg "draw 2 cards"
:async true
:effect (effect (draw :corp eid 2 nil))}}}})
(defcard "Superior Cyberwalls"
(ice-boost-agenda "Barrier"))
(defcard "TGTBT"
{:flags {:rd-reveal (req true)}
:access {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}})
(defcard "The Cleaners"
{:events [{:event :pre-damage
:req (req (and (= target :meat)
(= side :corp)))
:msg "do 1 additional meat damage"
:effect (effect (damage-bonus :meat 1))}]})
(defcard "The Future is Now"
{:on-score {:interactive (req true)
:prompt "Choose a card to add to HQ"
:choices (req (:deck corp))
:msg (msg "add a card from R&D to HQ and shuffle R&D")
:req (req (pos? (count (:deck corp))))
:effect (effect (shuffle! :deck)
(move target :hand))}})
(defcard "The Future Perfect"
{:flags {:rd-reveal (req true)}
:access {:psi {:req (req (not installed))
:not-equal
{:msg "prevent it from being stolen"
:effect (effect (register-run-flag!
card :can-steal
(fn [_ _ c] (not (same-card? c card))))
(effect-completed eid))}}}})
(defcard "Timely Public Release"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:cost [:agenda 1]
:label "Install a piece of ice in any position, ignoring all costs"
:prompt "Select a piece of ice to install"
:show-discard true
:choices {:card #(and (ice? %)
(or (in-hand? %)
(in-discard? %)))}
:msg (msg "install "
(if (and (in-discard? target)
(or (faceup? target)
(not (facedown? target))))
(:title target)
"ICE")
" from " (zone->name (get-zone target)))
:async true
:effect (effect
(continue-ability
(let [chosen-ice target]
{:prompt "Choose a server"
:choices (req servers)
:async true
:effect (effect
(continue-ability
(let [chosen-server target
num-ice (count (get-in (:corp @state)
(conj (server->zone state target) :ices)))]
{:prompt "Which position to install in? (0 is innermost)"
:choices (vec (reverse (map str (range (inc num-ice)))))
:async true
:effect (req (let [target (Integer/parseInt target)]
(wait-for (corp-install
state side chosen-ice chosen-server
{:ignore-all-cost true :index target})
(when (and run
(= (zone->name (first (:server run)))
chosen-server))
(let [curr-pos (get-in @state [:run :position])]
(when (< target curr-pos)
(swap! state update-in [:run :position] inc))))
(effect-completed state side eid))))})
card nil))})
card nil))}]})
(defcard "Tomorrow's Headline"
(let [ability
{:interactive (req true)
:msg "give Runner 1 tag"
:async true
:effect (req (gain-tags state :corp eid 1))}]
{:on-score ability
:stolen ability}))
(defcard "Transport Monopoly"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:agenda 1]
:req (req run)
:msg "prevent this run from becoming successful"
:effect (effect (register-floating-effect
card
{:type :block-successful-run
:duration :end-of-run
:value true}))}]})
(defcard "Underway Renovation"
(letfn [(adv4? [s c] (if (>= (get-counters (get-card s c) :advancement) 4) 2 1))]
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:msg (msg (if (pos? (count (:deck runner)))
(str "trash "
(string/join ", " (map :title (take (adv4? state card) (:deck runner))))
" from the Runner's stack")
"trash from the Runner's stack but it is empty"))
:effect (effect (mill :corp eid :runner (adv4? state card)))}]}))
(defcard "Unorthodox Predictions"
{:implementation "Prevention of subroutine breaking is not enforced"
:on-score {:prompt "Choose an ICE type for Unorthodox Predictions"
:choices ["Barrier" "Code Gate" "Sentry"]
:msg (msg "prevent subroutines on " target " ICE from being broken until next turn.")}})
(defcard "Utopia Fragment"
{:events [{:event :pre-steal-cost
:req (req (pos? (get-counters target :advancement)))
:effect (req (let [counter (get-counters target :advancement)]
(steal-cost-bonus state side [:credit (* 2 counter)])))}]})
(defcard "Vanity Project"
;; No special implementation
{})
(defcard "Veterans Program"
{:on-score {:interactive (req true)
:msg "lose 2 bad publicity"
:effect (effect (lose-bad-publicity 2))}})
(defcard "Viral Weaponization"
{:on-score
{:effect
(effect
(register-events
card
[{:event (if (= :corp (:active-player @state)) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:msg (msg "do " (count (:hand runner)) " net damage")
:async true
:effect (effect (damage eid :net (count (:hand runner)) {:card card}))}]))}})
(defcard "Voting Machine Initiative"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :runner-turn-begins
:optional
{:player :corp
:req (req (pos? (get-counters card :agenda)))
:waiting-prompt "Corp to use Voting Machine Initiative"
:prompt "Use Voting Machine Initiative to make the Runner lose 1 [Click]?"
:yes-ability
{:msg "make the Runner lose 1 [Click]"
:effect (effect (lose :runner :click 1)
(add-counter card :agenda -1))}}}]})
(defcard "Vulnerability Audit"
{:flags {:can-score (req (let [result (not= :this-turn (installed? card))]
(when-not result
(toast state :corp "Cannot score Vulnerability Audit the turn it was installed." "warning"))
result))}})
(defcard "Vulcan Coverup"
{:on-score {:interactive (req true)
:msg "do 2 meat damage"
:async true
:effect (effect (damage eid :meat 2 {:card card}))}
:stolen {:msg "force the Corp to take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1))}})
(defcard "Water Monopoly"
{:constant-effects [{:type :install-cost
:req (req (and (resource? target)
(not (has-subtype? target "Virtual"))
(not (:facedown (second targets)))))
:value 1}]})
| true |
(ns game.cards.agendas
(:require [game.core :refer :all]
[game.utils :refer :all]
[jinteki.utils :refer :all]
[clojure.string :as string]
[clojure.set :as clj-set]))
(defn ice-boost-agenda [subtype]
(letfn [(count-ice [corp]
(reduce (fn [c server]
(+ c (count (filter #(and (has-subtype? % subtype)
(rezzed? %))
(:ices server)))))
0
(flatten (seq (:servers corp)))))]
{:on-score {:msg (msg "gain " (count-ice corp) " [Credits]")
:interactive (req true)
:async true
:effect (effect (gain-credits eid (count-ice corp)))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target subtype))
:value 1}]}))
;; Card definitions
(defcard "15 Minutes"
{:abilities [{:cost [:click 1]
:msg "shuffle 15 Minutes into R&D"
:label "Shuffle 15 Minutes into R&D"
:effect (effect (move :corp card :deck nil)
(shuffle! :corp :deck)
(update-all-agenda-points))}]
:flags {:has-abilities-when-stolen true}})
(defcard "Above the Law"
{:on-score
{:interactive (req true)
:prompt "Select resource"
:req (req (some #(and (installed? %)
(resource? %))
(all-active-installed state :runner)))
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (card-str state target))
:async true
:effect (effect (trash eid target))}})
(defcard "Accelerated Beta Test"
(letfn [(abt [titles choices]
{:async true
:prompt (str "The top 3 cards of R&D: " titles)
:choices (concat (filter ice? choices) ["Done"])
:effect (req (if (= target "Done")
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
(wait-for (corp-install state side target nil
{:ignore-all-cost true
:install-state :rezzed-no-cost})
(let [choices (remove-once #(= target %) choices)]
(cond
;; Shuffle ends the ability
(get-in (get-card state card) [:special :shuffle-occurred])
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true}))
;; There are still ice left
(seq (filter ice? choices))
(continue-ability
state side (abt titles choices) card nil)
;; Trash what's left
:else
(do (unregister-events state side card)
(trash-cards state side eid choices {:unpreventable true})))))))})
(suffer [titles choices]
{:prompt (str "The top 3 cards of R&D: " titles
". None are ice. Say goodbye!")
:choices ["I have no regrets"]
:async true
:effect (effect (system-msg (str "trashes " (quantify (count choices) "card")))
(trash-cards eid choices {:unpreventable true}))})]
{:on-score
{:interactive (req true)
:optional
{:prompt "Look at the top 3 cards of R&D?"
:yes-ability
{:async true
:msg "look at the top 3 cards of R&D"
:effect (req (register-events
state side card
[{:event :corp-shuffle-deck
:effect (effect (update! (assoc-in card [:special :shuffle-occurred] true)))}])
(let [choices (take 3 (:deck corp))
titles (string/join ", " (map :title choices))]
(continue-ability
state side
(if (seq (filter ice? choices))
(abt titles choices)
(suffer titles choices))
card nil)))}}}}))
(defcard "Advanced Concept Hopper"
{:events
[{:event :run
:req (req (first-event? state side :run))
:player :corp
:once :per-turn
:async true
:waiting-prompt "Corp to use Advanced Concept Hopper"
:prompt "Use Advanced Concept Hopper to draw 1 card or gain 1 [Credits]?"
:choices ["Draw 1 card" "Gain 1 [Credits]" "No action"]
:effect (req (case target
"Gain 1 [Credits]"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to gain 1 [Credits]"))
(gain-credits state :corp eid 1))
"Draw 1 card"
(do (system-msg state :corp (str "uses Advanced Concept Hopper to draw 1 card"))
(draw state :corp eid 1 nil))
"No action"
(do (system-msg state :corp (str "doesn't use Advanced Concept Hopper"))
(effect-completed state side eid))))}]})
(defcard "Ancestral Imager"
{:events [{:event :jack-out
:msg "do 1 net damage"
:async true
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "AR-Enhanced Security"
{:events [{:event :runner-trash
:async true
:interactive (req true)
:once-per-instance true
:req (req (and (some #(corp? (:card %)) targets)
(first-event? state side :runner-trash
(fn [targets] (some #(corp? (:card %)) targets)))))
:msg "give the Runner a tag"
:effect (effect (gain-tags eid 1))}]})
(defcard "Architect Deployment Test"
{:on-score
{:interactive (req true)
:async true
:msg "look at the top 5 cards of R&D"
:prompt (msg "The top cards of R&D are (top->bottom) " (string/join ", " (map :title (take 5 (:deck corp)))))
:choices ["OK"]
:effect (effect (continue-ability
{:prompt "Install a card?"
:choices (cancellable (filter corp-installable-type? (take 5 (:deck corp))))
:async true
:effect (effect (corp-install eid target nil
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))
:cancel-effect (effect (system-msg "does not install any of the top 5 cards")
(effect-completed eid))}
card nil))}})
(defcard "Armed Intimidation"
{:on-score
{:player :runner
:async true
:waiting-prompt "Runner to suffer 5 meat damage or take 2 tags"
:prompt "Choose Armed Intimidation score effect"
:choices ["Suffer 5 meat damage" "Take 2 tags"]
:effect (req (case target
"Suffer 5 meat damage"
(do (system-msg state :runner "chooses to suffer 5 meat damage from Armed Intimidation")
(damage state :runner eid :meat 5 {:card card :unboostable true}))
"Take 2 tags"
(do (system-msg state :runner "chooses to take 2 tags from Armed Intimidation")
(gain-tags state :runner eid 2 {:card card}))
; else
(effect-completed state side eid)))}})
(defcard "Armored Servers"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req run)
:label "increase cost to break subroutines or jack out"
:msg "make the Runner trash a card from their grip to jack out or break subroutines for the remainder of the run"
:effect (effect (register-floating-effect
card
{:type :break-sub-additional-cost
:duration :end-of-run
:value (req (repeat (count (:broken-subs (second targets))) [:trash-from-hand 1]))})
(register-floating-effect
card
{:type :jack-out-additional-cost
:duration :end-of-run
:value [:trash-from-hand 1]}))}]})
(defcard "AstroScript Pilot Program"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:msg (msg "place 1 advancement token on " (card-str state target))
:choices {:card can-be-advanced?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "PI:NAME:<NAME>END_PI"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not-empty (filter #(can-be-advanced? %) (all-installed state :corp))))
:waiting-prompt "Corp to place advancement tokens with Award Bait"
:prompt "How many advancement tokens?"
:choices ["0" "1" "2"]
:effect (effect (continue-ability
(let [c (str->int target)]
{:choices {:card can-be-advanced?}
:msg (msg "place " (quantify c "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter c {:placed true}))})
card nil))}})
(defcard "Bacterial Programming"
(letfn [(hq-step [remaining to-trash to-hq]
{:async true
:prompt "Select a card to move to HQ"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(wait-for (trash-cards state :corp to-trash {:unpreventable true})
(doseq [h to-hq]
(move state :corp h :hand))
(if (seq remaining)
(continue-ability state :corp (reorder-choice :corp (vec remaining)) card nil)
(do (system-msg state :corp
(str "uses Bacterial Programming to add " (count to-hq)
" cards to HQ, discard " (count to-trash)
", and arrange the top cards of R&D"))
(effect-completed state :corp eid))))
(continue-ability state :corp (hq-step
(clj-set/difference (set remaining) (set [target]))
to-trash
(conj to-hq target)) card nil)))})
(trash-step [remaining to-trash]
{:async true
:prompt "Select a card to discard"
:choices (conj (vec remaining) "Done")
:effect (req (if (= "Done" target)
(continue-ability state :corp (hq-step remaining to-trash '()) card nil)
(continue-ability state :corp (trash-step
(clj-set/difference (set remaining) (set [target]))
(conj to-trash target)) card nil)))})]
(let [arrange-rd
{:interactive (req true)
:optional
{:waiting-prompt "Corp to use Bacterial Programming"
:prompt "Arrange top 7 cards of R&D?"
:yes-ability
{:async true
:effect (req (let [c (take 7 (:deck corp))]
(when (:access @state)
(swap! state assoc-in [:run :shuffled-during-access :rd] true))
(continue-ability state :corp (trash-step c '()) card nil)))}}}]
{:on-score arrange-rd
:stolen arrange-rd})))
(defcard "PI:NAME:<NAME>END_PI"
{:steal-cost-bonus (req [:credit 5])
:on-score {:async true
:msg "gain 5 [Credits]"
:effect (effect (gain-credits :corp eid 5))}})
(defcard "Better Citizen Program"
{:events [{:event :play-event
:optional
{:player :corp
:req (req (and (has-subtype? (:card context) "Run")
(first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))
(no-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for playing a run event"
:effect (effect (gain-tags :corp eid 1))}}}
{:event :runner-install
:silent (req true)
:optional
{:player :corp
:req (req (and (not (:facedown context))
(has-subtype? (:card context) "Icebreaker")
(first-event? state :runner :runner-install #(has-subtype? (:card (first %)) "Icebreaker"))
(no-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run"))))
:waiting-prompt "Corp to use Better Citizen Program"
:prompt "Give the runner 1 tag?"
:yes-ability
{:async true
:msg "give the Runner a tag for installing an icebreaker"
:effect (effect (gain-tags :corp eid 1))}}}]})
(defcard "Bifrost Array"
{:on-score
{:optional
{:req (req (seq (filter #(not= (:title %) "Bifrost Array") (:scored corp))))
:prompt "Trigger the ability of a scored agenda?"
:yes-ability
{:prompt "Select an agenda to trigger its \"when scored\" ability"
:choices {:card #(and (agenda? %)
(not= (:title %) "Bifrost Array")
(in-scored? %)
(when-scored? %))}
:msg (msg "trigger the \"when scored\" ability of " (:title target))
:async true
:effect (effect (continue-ability (:on-score (card-def target)) target nil))}}}})
(defcard "Brain Rewiring"
{:on-score
{:optional
{:waiting-prompt "Corp to use Brain Rewiring"
:prompt "Pay credits to add random cards from Runner's Grip to the bottom of their Stack?"
:yes-ability
{:prompt "How many credits?"
:choices {:number (req (min (:credit corp)
(count (:hand runner))))}
:async true
:effect (req (if (pos? target)
(wait-for
(pay state :corp card :credit target)
(let [from (take target (shuffle (:hand runner)))]
(doseq [c from]
(move state :runner c :deck))
(system-msg state side (str "uses Brain Rewiring to pay " target
" [Credits] and add " target
" cards from the Runner's Grip"
" to the bottom of their Stack."
" The Runner draws 1 card"))
(draw state :runner eid 1 nil)))
(effect-completed state side eid)))}}}})
(defcard "Braintrust"
{:on-score {:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2)))
:silent (req true)}
:constant-effects [{:type :rez-cost
:req (req (ice? target))
:value (req (- (get-counters card :agenda)))}]})
(defcard "Breaking News"
{:on-score {:async true
:silent (req true)
:msg "give the Runner 2 tags"
:effect (effect (gain-tags :corp eid 2))}
:events (let [event {:unregister-once-resolved true
:req (effect (first-event? :agenda-scored #(same-card? card (:card (first %)))))
:msg "make the Runner lose 2 tags"
:effect (effect (lose :runner :tag 2))}]
[(assoc event :event :corp-turn-ends)
(assoc event :event :runner-turn-ends)])})
(defcard "Broad Daylight"
(letfn [(add-counters [state side card eid]
(add-counter state :corp card :agenda (count-bad-pub state))
(effect-completed state side eid))]
{:on-score
{:optional
{:prompt "Take 1 bad publicity?"
:async true
:yes-ability {:async true
:effect (req (wait-for (gain-bad-publicity state :corp 1)
(system-msg state :corp "used Broad Daylight to take 1 bad publicity")
(add-counters state side card eid)))}
:no-ability {:async true
:effect (effect (add-counters card eid))}}}
:abilities [{:cost [:click 1 :agenda 1]
:async true
:label "Do 2 meat damage"
:once :per-turn
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}]}))
(defcard "CFC Excavation Contract"
(letfn [(bucks [state]
(->> (all-active-installed state :corp)
(filter #(has-subtype? % "Bioroid"))
(count)
(* 2)))]
{:on-score
{:async true
:msg (msg "gain " (bucks state) " [Credits]")
:effect (effect (gain-credits :corp eid (bucks state)))}}))
(defcard "Character Assassination"
{:on-score
{:prompt "Select a resource to trash"
:choices {:card #(and (installed? %)
(resource? %))}
:msg (msg "trash " (:title target))
:interactive (req true)
:async true
:effect (effect (trash eid target {:unpreventable true}))}})
(defcard "Chronos Project"
{:on-score
{:req (req (not (zone-locked? state :runner :discard)))
:msg "remove all cards in the Runner's Heap from the game"
:interactive (req true)
:effect (effect (move-zone :runner :discard :rfg))}})
(defcard "City Works Project"
(letfn [(meat-damage [s c] (+ 2 (get-counters (get-card s c) :advancement)))]
{:install-state :face-up
:access {:req (req installed)
:msg (msg "do " (meat-damage state card) " meat damage")
:async true
:effect (effect (damage eid :meat (meat-damage state card) {:card card}))}}))
(defcard "Clone Retirement"
{:on-score {:msg "remove 1 bad publicity"
:effect (effect (lose-bad-publicity 1))
:silent (req true)}
:stolen {:msg "force the Corp to take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}})
(defcard "Corporate Oversight A"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Oversight B"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a central server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(#{"HQ" "Archives" "R&D"} %)
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:ignore-all-cost true
:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Corporate Sales Team"
(let [e {:req (req (pos? (get-counters card :credit)))
:msg "gain 1 [Credits]"
:async true
:effect (req (add-counter state side card :credit -1)
(gain-credits state :corp eid 1))}]
{:on-score {:effect (effect (add-counter card :credit 10))
:silent (req true)}
:events [(assoc e :event :runner-turn-begins)
(assoc e :event :corp-turn-begins)]}))
(defcard "Corporate War"
{:on-score
{:msg (msg (if (> (:credit corp) 6) "gain 7 [Credits]" "lose all credits"))
:interactive (req true)
:async true
:effect (req (if (> (:credit corp) 6)
(gain-credits state :corp eid 7)
(lose-credits state :corp eid :all)))}})
(defcard "Crisis Management"
(let [ability {:req (req tagged)
:async true
:label "Do 1 meat damage (start of turn)"
:once :per-turn
:msg "do 1 meat damage"
:effect (effect (damage eid :meat 1 {:card card}))}]
{:events [(assoc ability :event :corp-turn-begins)]
:abilities [ability]}))
(defcard "Cyberdex Sandbox"
{:on-score {:optional
{:prompt "Purge virus counters with Cyberdex Sandbox?"
:yes-ability {:msg (msg "purge virus counters")
:effect (effect (purge))}}}
:events [{:event :purge
:req (req (first-event? state :corp :purge))
:once :per-turn
:msg "gain 4 [Credits]"
:async true
:effect (req (gain-credits state :corp eid 4))}]})
(defcard "Dedicated Neural Net"
{:events [{:event :successful-run
:interactive (req true)
:psi {:req (req (= :hq (target-server context)))
:once :per-turn
:not-equal {:effect (effect (register-floating-effect
card
{:type :corp-choose-hq-access
:duration :end-of-access
:value true})
(effect-completed eid))}}}]})
(defcard "PI:NAME:<NAME>END_PI"
{:steal-cost-bonus (req [:shuffle-installed-to-stack 2])})
(defcard "Director Haas' Pet Project"
(letfn [(install-ability [server-name n]
{:prompt "Select a card to install"
:show-discard true
:choices {:card #(and (corp? %)
(not (operation? %))
(or (in-hand? %)
(in-discard? %)))}
:msg (msg (corp-install-msg target)
(when (zero? n)
", creating a new remote server")
", ignoring all install costs")
:async true
:effect (req (wait-for (corp-install state side target server-name {:ignore-all-cost true})
(continue-ability state side
(when (< n 2)
(install-ability (last (get-remote-names state)) (inc n)))
card nil)))})]
{:on-score
{:optional
{:prompt "Install cards in a new remote server?"
:yes-ability (install-ability "New remote" 0)}}}))
(defcard "Divested Trust"
{:events
[{:event :agenda-stolen
:async true
:interactive (req true)
:effect (req (if (:winner @state)
(effect-completed state side eid)
(let [card (find-latest state card)
stolen-agenda (find-latest state (:card context))
title (:title stolen-agenda)
prompt (str "Forfeit Divested Trust to add " title
" to HQ and gain 5[Credits]?")
message (str "add " title " to HQ and gain 5 [Credits]")
agenda-side (if (in-runner-scored? state side stolen-agenda)
:runner :corp)
card-side (if (in-runner-scored? state side card)
:runner :corp)]
(continue-ability
state side
{:optional
{:waiting-prompt "Corp to use Divested Trust"
:prompt prompt
:yes-ability
{:msg message
:async true
:effect (req (wait-for (forfeit state card-side card)
(move state side stolen-agenda :hand)
(update-all-agenda-points state side)
(gain-credits state side eid 5)))}}}
card nil))))}]})
(defcard "Domestic Sleepers"
{:agendapoints-corp (req (if (pos? (get-counters card :agenda)) 1 0))
:abilities [{:cost [:click 3]
:msg "place 1 agenda counter on Domestic Sleepers"
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}]})
(defcard "Eden Fragment"
{:constant-effects [{:type :ignore-install-cost
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:value true}]
:events [{:event :corp-install
:req (req (and (ice? target)
(->> (turn-events state side :corp-install)
(map #(:card (first %)))
(filter ice?)
empty?)))
:msg "ignore the install cost of the first ICE this turn"}]})
(defcard "Efficiency Committee"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:click 1 :agenda 1]
:effect (effect (gain :click 2)
(register-turn-flag!
card :can-advance
(fn [state side card]
((constantly false)
(toast state :corp "Cannot advance cards this turn due to Efficiency Committee." "warning")))))
:msg "gain [Click][Click]"}]})
(defcard "Elective Upgrade"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:click 1 :agenda 1]
:once :per-turn
:effect (effect (gain :click 2))
:msg "gain [Click][Click]"}]})
(defcard "Encrypted Portals"
(ice-boost-agenda "Code Gate"))
(defcard "Escalate Vitriol"
{:abilities [{:label "Gain 1 [Credit] for each Runner tag"
:cost [:click 1]
:once :per-turn
:msg (msg "gain " (count-tags state) " [Credits]")
:async true
:effect (effect (gain-credits eid (count-tags state)))}]})
(defcard "Executive Retreat"
{:on-score {:effect (effect (add-counter card :agenda 1)
(shuffle-into-deck :hand))
:interactive (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "draw 5 cards"
:effect (effect (draw 5))}]})
(defcard "Explode-a-palooza"
{:flags {:rd-reveal (req true)}
:access {:optional
{:waiting-prompt "Corp to use Explode-a-palooza"
:prompt "Gain 5 [Credits] with Explode-a-palooza ability?"
:yes-ability
{:msg "gain 5 [Credits]"
:async true
:effect (effect (gain-credits :corp eid 5))}}}})
(defcard "False Lead"
{:abilities [{:req (req (<= 2 (:click runner)))
:label "runner loses [Click][Click]"
:msg "force the Runner to lose [Click][Click]"
:cost [:forfeit-self]
:effect (effect (lose :runner :click 2))}]})
(defcard "Fetal AI"
{:flags {:rd-reveal (req true)}
:access {:async true
:req (req (not (in-discard? card)))
:msg "do 2 net damage"
:effect (effect (damage eid :net 2 {:card card}))}
:steal-cost-bonus (req [:credit 2])})
(defcard "Firmware Updates"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:abilities [{:cost [:agenda 1]
:label "place 1 advancement counter"
:choices {:card #(and (ice? %)
(can-be-advanced? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "place 1 advancement token on " (card-str state target))
:once :per-turn
:effect (effect (add-prop target :advance-counter 1))}]})
(defcard "PI:NAME:<NAME>END_PI"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 5))}
:abilities [{:cost [:agenda 1]
:label "reveal and draw"
:once :per-turn
:msg (msg "reveal " (:title (first (:deck corp))) " and draw 2 cards")
:async true
:waiting-prompt "Corp to use PI:NAME:<NAME>END_PIlower Sermon"
:effect (req (wait-for
(reveal state side (first (:deck corp)))
(wait-for
(draw state side 2 nil)
(continue-ability
state side
{:req (req (pos? (count (:hand corp))))
:prompt "Choose a card in HQ to move to the top of R&D"
:msg "add 1 card in HQ to the top of R&D"
:choices {:card #(and (in-hand? %)
(corp? %))}
:effect (effect (move target :deck {:front true})
(effect-completed eid))}
card nil))))}]})
(defcard "Fly on the Wall"
{:on-score {:msg "give the runner 1 tag"
:async true
:effect (req (gain-tags state :runner eid 1))}})
(defcard "Genetic Resequencing"
{:on-score {:choices {:card in-scored?}
:msg (msg "add 1 agenda counter on " (:title target))
:effect (effect (add-counter target :agenda 1)
(update-all-agenda-points))
:silent (req true)}})
(defcard "PI:NAME:<NAME>END_PI"
{:on-score {:effect (effect (add-counter card :agenda 2))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:msg "gain 7 [Credits] and take 1 bad publicity"
:async true
:effect (req (wait-for (gain-credits state side 7)
(gain-bad-publicity state side eid 1)))}]})
(defcard "Gila Hands Arcology"
{:abilities [{:cost [:click 2]
:msg "gain 3 [Credits]"
:async true
:effect (effect (gain-credits eid 3))}]})
(defcard "Glenn Station"
{:abilities [{:label "Host a card from HQ on Glenn Station"
:req (req (and (not-empty (:hand corp))
(empty? (filter corp? (:hosted card)))))
:cost [:click 1]
:msg "host a card from HQ"
:prompt "Choose a card to host on Glenn Station"
:choices {:card #(and (corp? %) (in-hand? %))}
:effect (effect (host card target {:facedown true}))}
{:label "Add a card on Glenn Station to HQ"
:req (req (not-empty (filter corp? (:hosted card))))
:cost [:click 1]
:msg "add a hosted card to HQ"
:prompt "Choose a card on Glenn Station"
:choices {:all true
:req (req (let [hosted-corp-cards
(->> (:hosted card)
(filter corp?)
(map :cid)
(into #{}))]
(hosted-corp-cards (:cid target))))}
:effect (effect (move target :hand))}]})
(defcard "Global Food Initiative"
{:agendapoints-runner (req 2)})
(defcard "Government Contracts"
{:abilities [{:cost [:click 2]
:async true
:effect (effect (gain-credits eid 4))
:msg "gain 4 [Credits]"}]})
(defcard "Government Takeover"
{:abilities [{:cost [:click 1]
:async true
:effect (effect (gain-credits eid 3))
:msg "gain 3 [Credits]"}]})
(defcard "Graft"
(letfn [(graft [n] {:prompt "Choose a card to add to HQ with Graft"
:async true
:choices (req (cancellable (:deck corp) :sorted))
:msg (msg "add " (:title target) " to HQ from R&D")
:cancel-effect (req (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))
:effect (req (move state side target :hand)
(if (< n 3)
(continue-ability state side (graft (inc n)) card nil)
(do (shuffle! state side :deck)
(system-msg state side (str "shuffles R&D"))
(effect-completed state side eid))))})]
{:on-score
{:async true
:msg "add up to 3 cards from R&D to HQ"
:effect (effect (continue-ability (graft 1) card nil))}}))
(defcard "Hades Fragment"
{:flags {:corp-phase-12 (req (and (not-empty (get-in @state [:corp :discard]))
(is-scored? state :corp card)))}
:abilities [{:prompt "Select a card to add to the bottom of R&D"
:label "add card to bottom of R&D"
:show-discard true
:choices {:card #(and (corp? %)
(in-discard? %))}
:effect (effect (move target :deck))
:msg (msg "add "
(if (:seen target)
(:title target)
"a card")
" to the bottom of R&D")}]})
(defcard "Helium-3 Deposit"
{:on-score
{:async true
:interactive (req true)
:prompt "How many power counters?"
:choices ["0" "1" "2"]
:effect (req (let [c (str->int target)]
(continue-ability
state side
{:choices {:card #(pos? (get-counters % :power))}
:msg (msg "add " c " power counters on " (:title target))
:effect (effect (add-counter target :power c))}
card nil)))}})
(defcard "High-Risk Investment"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:click 1 :agenda 1]
:label "gain credits"
:msg (msg "gain " (:credit runner) " [Credits]")
:async true
:effect (effect (gain-credits eid (:credit runner)))}]})
(defcard "Hollywood Renovation"
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:effect (req (let [n (if (>= (get-counters (get-card state card) :advancement) 6) 2 1)]
(continue-ability
state side
{:choices {:card #(and (not (same-card? % card))
(can-be-advanced? %))}
:msg (msg "place " (quantify n "advancement token")
" on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter n {:placed true}))}
card nil)))}]})
(defcard "Hostile Takeover"
{:on-score {: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)))
:interactive (req true)}})
(defcard "House of Knives"
{:on-score {:effect (effect (add-counter card :agenda 3))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg "do 1 net damage"
:req (req (:run @state))
:once :per-run
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Hyperloop Extension"
(let [he {:async true
:effect (req (system-msg state side (str "uses Hyperloop Extension to gain 3 [Credits]"))
(gain-credits state :corp eid 3))}]
{:on-score he
:stolen he}))
(defcard "Ikawah Project"
{:steal-cost-bonus (req [:credit 2 :click 1])})
(defcard "Illicit Sales"
{:on-score
{:async true
:effect (req (wait-for (resolve-ability
state side
{:optional
{:prompt "Take 1 bad publicity from Illicit Sales?"
:yes-ability {:msg "take 1 bad publicity"
:effect (effect (gain-bad-publicity :corp 1))}}}
card nil)
(let [n (* 3 (count-bad-pub state))]
(system-msg state side (str "gains " n " [Credits] from Illicit Sales"))
(gain-credits state side eid n))))}})
(defcard "Improved Protein Source"
(let [ability {:async true
:interactive (req true)
:msg "make the Runner gain 4 [Credits]"
:effect (effect (gain-credits :runner eid 4))}]
{:on-score ability
:stolen ability}))
(defcard "Improved Tracers"
{:on-score {:silent (req true)
:effect (req (update-all-ice state side))}
:swapped {:effect (req (update-all-ice state side))}
:constant-effects [{:type :ice-strength
:req (req (has-subtype? target "Tracer"))
:value 1}]
:events [{:event :pre-init-trace
:req (req (and (has-subtype? target "Tracer")
(= :subroutine (:source-type (second targets)))))
:effect (effect (init-trace-bonus 1))}]})
(defcard "Jumon"
{:events
[{:event :corp-turn-ends
:req (req (some #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))
(all-installed state :corp)))
:prompt "Select a card to place 2 advancement tokens on"
:player :corp
:choices {:card #(and (= (last (get-zone %)) :content)
(is-remote? (second (get-zone %))))}
:msg (msg "place 2 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 2 {:placed true}))}]})
(defcard "Labyrinthine Servers"
{:on-score {:silent (req true)
:effect (effect (add-counter card :power 2))}
:interactions {:prevent [{:type #{:jack-out}
:req (req (pos? (get-counters card :power)))}]}
:abilities [{:req (req (:run @state))
:cost [:power 1]
:msg "prevent the Runner from jacking out"
:effect (effect (jack-out-prevent))}]})
(defcard "License Acquisition"
{:on-score {:interactive (req true)
:prompt "Select an asset or upgrade to install from Archives or HQ"
:show-discard true
:choices {:card #(and (corp? %)
(or (asset? %) (upgrade? %))
(or (in-hand? %) (in-discard? %)))}
:msg (msg "install and rez " (:title target) ", ignoring all costs")
:async true
:effect (effect (corp-install eid target nil {:install-state :rezzed-no-cost}))}})
(defcard "Longevity Serum"
{:on-score
{:prompt "Select any number of cards in HQ to trash"
:choices {:max (req (count (:hand corp)))
:card #(and (corp? %)
(in-hand? %))}
:msg (msg "trash " (quantify (count targets) "card") " in HQ")
:async true
:effect (req (wait-for (trash-cards state side targets {:unpreventable true})
(shuffle-into-rd-effect state side eid card 3)))}})
(defcard "Luminal Transubstantiation"
{:on-score
{:silent (req true)
:effect (req (gain state :corp :click 3)
(register-turn-flag!
state side card :can-score
(fn [state side card]
((constantly false)
(toast state :corp "Cannot score cards this turn due to Luminal Transubstantiation." "warning")))))}})
(defcard "Mandatory Seed Replacement"
(letfn [(msr [] {:prompt "Select two pieces of ICE to swap positions"
:choices {:card #(and (installed? %)
(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 "swaps the position of "
(card-str state (first targets))
" and "
(card-str state (second targets))))
(continue-ability state side (msr) card nil))
(do (system-msg state :corp (str "has finished rearranging ICE"))
(effect-completed state side eid))))})]
{:on-score {:async true
:msg "rearrange any number of ICE"
:effect (effect (continue-ability (msr) card nil))}}))
(defcard "Mandatory Upgrades"
{:on-score {:msg "gain an additional [Click] per turn"
:silent (req true)
:effect (req (gain state :corp :click-per-turn 1))}
:swapped {:msg "gain an additional [Click] per turn"
:effect (req (when (= (:active-player @state) :corp)
(gain state :corp :click 1))
(gain state :corp :click-per-turn 1))}
:leave-play (req (lose state :corp
:click 1
:click-per-turn 1))})
(defcard "Market Research"
{:on-score {:interactive (req true)
:req (req tagged)
:effect (effect (add-counter card :agenda 1)
(update-all-agenda-points)
(check-win-by-agenda))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 2 3))})
(defcard "Medical Breakthrough"
{:flags {:has-events-when-stolen true}
:constant-effects [{:type :advancement-requirement
:req (req (= (:title target) "Medical Breakthrough"))
:value -1}]})
(defcard "Megaprix Qualifier"
{:on-score {:silent (req true)
:req (req (< 1 (count (filter #(= (:title %) "Megaprix Qualifier")
(concat (:scored corp) (:scored runner))))))
:effect (effect (add-counter card :agenda 1))}
:agendapoints-corp (req (if (zero? (get-counters card :agenda)) 1 2))})
(defcard "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
{:agendapoints-runner (req 3)})
(defcard "Meteor Mining"
{:on-score {:interactive (req true)
:async true
:prompt "Use Meteor Mining?"
:choices (req (if (< (count-tags state) 2)
["Gain 7 [Credits]" "No action"]
["Gain 7 [Credits]" "Do 7 meat damage" "No action"]))
:effect (req (case target
"Gain 7 [Credits]"
(do (system-msg state side "uses Meteor Mining to gain 7 [Credits]")
(gain-credits state side eid 7))
"Do 7 meat damage"
(do (system-msg state side "uses Meteor Mining do 7 meat damage")
(damage state side eid :meat 7 {:card card}))
"No action"
(do (system-msg state side "does not use Meteor Mining")
(effect-completed state side eid))))}})
(defcard "NAPD Contract"
{:steal-cost-bonus (req [:credit 4])
:advancement-requirement (req (count-bad-pub state))})
(defcard "Net Quarantine"
(let [nq {:async true
:effect (req (let [extra (int (/ (:runner-spent target) 2))]
(if (pos? extra)
(do (system-msg state :corp (str "uses Net Quarantine to gain " extra "[Credits]"))
(gain-credits state side eid extra))
(effect-completed state side eid))))}]
{:events [{:event :pre-init-trace
:once :per-turn
:silent (req true)
:effect (req (system-msg state :corp "uses Net Quarantine to reduce Runner's base link to zero")
(swap! state assoc-in [:trace :force-link] 0))}
(assoc nq :event :successful-trace)
(assoc nq :event :unsuccessful-trace)]}))
(defcard "New Construction"
{:install-state :face-up
:events [{:event :advance
:optional
{:req (req (same-card? card target))
:prompt "Install a card from HQ in a new remote?"
:yes-ability {:prompt "Select a card to install"
:choices {:card #(and (not (operation? %))
(not (ice? %))
(corp? %)
(in-hand? %))}
:msg (msg "install a card from HQ"
(when (<= 5 (get-counters (get-card state card) :advancement))
" and rez it, ignoring all costs"))
:async true
:effect (effect (corp-install
eid target "New remote"
(when (<= 5 (get-counters (get-card state card) :advancement))
{:install-state :rezzed-no-cost})))}}}]})
(defcard "NEXT Wave 2"
{:on-score
{:async true
:effect
(effect
(continue-ability
(when (some #(and (rezzed? %)
(ice? %)
(has-subtype? % "NEXT"))
(all-installed state :corp))
{:optional
{:prompt "Do 1 brain damage with NEXT Wave 2?"
:yes-ability {:msg "do 1 brain damage"
:async true
:effect (effect (damage eid :brain 1 {:card card}))}}})
card nil))}})
(defcard "Nisei MK II"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:req (req (:run @state))
:cost [:agenda 1]
:msg "end the run"
:async true
:effect (effect (end-run eid card))}]})
(defcard "Oaktown Renovation"
{:install-state :face-up
:events [{:event :advance
:req (req (same-card? card target))
:msg (msg "gain " (if (>= (get-counters (get-card state card) :advancement) 5) "3" "2") " [Credits]")
:async true
:effect (effect (gain-credits eid (if (<= 5 (get-counters (get-card state card) :advancement)) 3 2)))}]})
(defcard "Obokata Protocol"
{:steal-cost-bonus (req [:net 4])})
(defcard "Orbital Superiority"
{:on-score
{:msg (msg (if (is-tagged? state) "do 4 meat damage" "give the Runner 1 tag"))
:async true
:effect (req (if (is-tagged? state)
(damage state :corp eid :meat 4 {:card card})
(gain-tags state :corp eid 1)))}})
(defcard "Paper Trail"
{:on-score
{:trace
{:base 6
:successful
{:msg "trash all connection and job resources"
:async true
:effect (req (let [resources (filter #(or (has-subtype? % "Job")
(has-subtype? % "Connection"))
(all-active-installed state :runner))]
(trash-cards state side eid resources)))}}}})
(defcard "Personality Profiles"
(let [pp {:req (req (pos? (count (:hand runner))))
:async true
:effect (req (let [c (first (shuffle (:hand runner)))]
(system-msg state side (str "uses Personality Profiles to force the Runner to trash "
(:title c) " from their Grip at random"))
(trash state side eid c nil)))}]
{:events [(assoc pp :event :searched-stack)
(assoc pp
:event :runner-install
:req (req (and (some #{:discard} (:previous-zone (:card context)))
(pos? (count (:hand runner))))))]}))
(defcard "Philotic Entanglement"
{:on-score {:interactive (req true)
:req (req (pos? (count (:scored runner))))
:msg (msg "do " (count (:scored runner)) " net damage")
:effect (effect (damage eid :net (count (:scored runner)) {:card card}))}})
(defcard "Posted Bounty"
{:on-score {:optional
{:prompt "Forfeit Posted Bounty to give the Runner 1 tag and take 1 bad publicity?"
:yes-ability
{:msg "give the Runner 1 tag and take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1)
(gain-tags :corp eid 1)
(forfeit card))}}}})
(defcard "Priority Requisition"
{:on-score {:interactive (req true)
:choices {:card #(and (ice? %)
(not (rezzed? %))
(installed? %))}
:async true
:effect (effect (rez eid target {:ignore-cost :all-costs}))}})
(defcard "Private Security Force"
{:abilities [{:req (req tagged)
:cost [:click 1]
:effect (effect (damage eid :meat 1 {:card card}))
:msg "do 1 meat damage"}]})
(defcard "Profiteering"
{:on-score {:interactive (req true)
:choices ["0" "1" "2" "3"]
:prompt "How many bad publicity?"
:msg (msg "take " target " bad publicity and gain " (* 5 (str->int target)) " [Credits]")
:async true
:effect (req (let [bp (count-bad-pub state)]
(wait-for (gain-bad-publicity state :corp (str->int target))
(if (< bp (count-bad-pub state))
(gain-credits state :corp eid (* 5 (str->int target)))
(effect-completed state side eid)))))}})
(defcard "Project Ares"
(letfn [(trash-count-str [card]
(quantify (- (get-counters card :advancement) 4) "installed card"))]
{:on-score {:player :runner
:silent (req true)
:req (req (and (< 4 (get-counters (:card context) :advancement))
(pos? (count (all-installed state :runner)))))
:waiting-prompt "Runner to trash installed cards"
:prompt (msg "Select " (trash-count-str (:card context)) " installed cards to trash")
:choices {:max (req (min (- (get-counters (:card context) :advancement) 4)
(count (all-installed state :runner))))
:card #(and (runner? %)
(installed? %))}
:msg (msg "force the Runner to trash " (trash-count-str (:card context)) " and take 1 bad publicity")
:async true
:effect (req (wait-for (trash-cards state side targets)
(system-msg state side (str "trashes " (string/join ", " (map :title targets))))
(gain-bad-publicity state :corp eid 1)))}}))
(defcard "Project Atlas"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (max 0 (- (get-counters (:card context) :advancement) 3))))}
:abilities [{:cost [:agenda 1]
:prompt "Choose a card"
:label "Search R&D and add 1 card to HQ"
;; we need the req or the prompt will still show
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add " (:title target) " to HQ from R&D")
:choices (req (cancellable (:deck corp) :sorted))
:cancel-effect (effect (system-msg "cancels the effect of Project Atlas"))
:effect (effect (shuffle! :deck)
(move target :hand))}]})
(defcard "Project Beale"
{:agendapoints-runner (req 2)
:agendapoints-corp (req (+ 2 (get-counters card :agenda)))
:on-score {:interactive (req true)
:effect (effect (add-counter card :agenda (quot (- (get-counters (:card context) :advancement) 3) 2))
(update-all-agenda-points)
(check-win-by-agenda))}})
(defcard "Project Kusanagi"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 2)))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :kusanagi])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :kusanagi])))}]
:abilities [{:label "Give a piece of ICE \"[Subroutine] Do 1 net damage\""
:prompt "Choose a piece of ICE"
:choices {:card #(and (ice? %)
(rezzed? %))}
:cost [:agenda 1]
:msg (str "make a piece of ICE gain \"[Subroutine] Do 1 net damage\" "
"after all its other subroutines for the remainder of the run")
:effect (effect (add-extra-sub! (get-card state target)
(do-net-damage 1)
(:cid card) {:back true})
(update! (update-in card [:special :kusanagi] #(conj % target))))}]})
(defcard "Project Vacheron"
(let [vacheron-ability
{:req (req (and (in-scored? card)
(not= (first (:previous-zone card)) :discard)
(same-card? card (or (:card context) target))))
:msg (msg "add 4 agenda counters on " (:title card))
:effect (effect (add-counter (get-card state card) :agenda 4)
(update! (assoc-in (get-card state card) [:special :vacheron] true)))}]
{:agendapoints-runner (req (if (or (= (first (:previous-zone card)) :discard)
(and (get-in card [:special :vacheron])
(zero? (get-counters card :agenda)))) 3 0))
:stolen vacheron-ability
:events [(assoc vacheron-ability :event :as-agenda)
{:event :runner-turn-begins
:req (req (pos? (get-counters card :agenda)))
:msg (msg "remove 1 agenda token from " (:title card))
:effect (req (when (pos? (get-counters card :agenda))
(add-counter state side card :agenda -1))
(update-all-agenda-points state side)
(when (zero? (get-counters (get-card state card) :agenda))
(let [points (get-agenda-points (get-card state card))]
(system-msg state :runner
(str "gains " (quantify points "agenda point")
" from " (:title card)))))
(check-win-by-agenda state side))}]
:flags {:has-events-when-stolen true}}))
(defcard "Project Vitruvius"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "Add 1 card from Archives to HQ"
:prompt "Choose a card in Archives to add to HQ"
:show-discard true
:choices {:card #(and (in-discard? %)
(corp? %))}
:req (req (pos? (get-counters card :agenda)))
:msg (msg "add "
(if (:seen target)
(:title target) "an unseen card ")
" to HQ from Archives")
:effect (effect (move target :hand))}]})
(defcard "Project Wotan"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :run-ends
:effect (req (let [cid (:cid card)
ices (get-in card [:special :wotan])]
(doseq [i ices]
(when-let [ice (get-card state i)]
(remove-sub! state side ice #(= cid (:from-cid %))))))
(update! state side (dissoc-in card [:special :wotan])))}]
:abilities [{:req (req (and current-ice
(rezzed? current-ice)
(has-subtype? current-ice "Bioroid")
(= :approach-ice (:phase run))))
:cost [:agenda 1]
:msg (str "make the approached piece of Bioroid ICE gain \"[Subroutine] End the run\""
"after all its other subroutines for the remainder of this run")
:effect (effect (add-extra-sub! (get-card state current-ice)
{:label "End the run"
:msg "end the run"
:async true
:effect (effect (end-run eid card))}
(:cid card) {:back true})
(update! (update-in card [:special :wotan] #(conj % current-ice))))}]})
(defcard "Project Yagi-Uda"
(letfn [(put-back-counter [state side card]
(update! state side (assoc-in card [:counter :agenda] (+ 1 (get-counters card :agenda)))))
(choose-swap [to-swap]
{:prompt (str "Select a card in HQ to swap with " (:title to-swap))
:choices {:not-self true
:card #(and (corp? %)
(in-hand? %)
(if (ice? to-swap)
(ice? %)
(or (agenda? %)
(asset? %)
(upgrade? %))))}
:msg (msg "swap " (card-str state to-swap) " with a card from HQ")
:effect (effect (swap-cards to-swap target))
:cancel-effect (effect (put-back-counter card))})
(choose-card [run-server]
{:waiting-prompt "Corp to use Project Yagi-Uda"
:prompt "Choose a card in or protecting the attacked server."
:choices {:card #(= (first run-server) (second (get-zone %)))}
:effect (effect (continue-ability (choose-swap target) card nil))
:cancel-effect (effect (put-back-counter card))})]
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda (- (get-counters (:card context) :advancement) 3)))}
:abilities [{:cost [:agenda 1]
:label "swap card in HQ with installed card"
:req (req run)
:effect (effect (continue-ability (choose-card (:server run)) card nil))}]}))
(defcard "Puppet Master"
{:events [{:event :successful-run
:player :corp
:interactive (req true)
:waiting-prompt "Corp to use Puppet Master"
:prompt "Select a card to place 1 advancement token on"
:choices {:card can-be-advanced?}
:msg (msg "place 1 advancement token on " (card-str state target))
:effect (effect (add-prop :corp target :advance-counter 1 {:placed true}))}]})
(defcard "Quantum Predictive Model"
{:flags {:rd-reveal (req true)}
:access {:req (req tagged)
:player :runner
:async true
:interactive (req true)
:prompt "Quantum Predictive Model was added to the corp's score area"
:choices ["OK"]
:msg "add it to their score area and gain 1 agenda point"
:effect (effect (as-agenda :corp eid card 1))}})
(defcard "Rebranding Team"
{:on-score {:msg "make all assets gain Advertisement"}
:swapped {:msg "make all assets gain Advertisement"}
:constant-effects [{:type :gain-subtype
:req (req (asset? target))
:value "Advertisement"}]})
(defcard "Reeducation"
(letfn [(corp-final [chosen original]
{:prompt (str "The bottom cards of R&D will be " (string/join ", " (map :title chosen)) ".")
:choices ["Done" "Start over"]
:async true
:msg (req (let [n (count chosen)]
(str "add " n " cards from HQ to the bottom of R&D and draw " n " cards."
" The Runner randomly adds " (if (<= n (count (:hand runner))) n 0)
" cards from their Grip to the bottom of the Stack")))
:effect (req (let [n (count chosen)]
(if (= target "Done")
(do (doseq [c (reverse chosen)] (move state :corp c :deck))
(draw state :corp n)
; if corp chooses more cards than runner's hand, don't shuffle runner hand back into Stack
(when (<= n (count (:hand runner)))
(doseq [r (take n (shuffle (:hand runner)))] (move state :runner r :deck)))
(effect-completed state side eid))
(continue-ability state side (corp-choice original '() original) card nil))))})
(corp-choice [remaining chosen original] ; Corp chooses cards until they press 'Done'
{:prompt "Choose a card to move to bottom of R&D"
:choices (conj (vec remaining) "Done")
:async true
:effect (req (let [chosen (cons target chosen)]
(if (not= target "Done")
(continue-ability
state side
(corp-choice (remove-once #(= target %) remaining) chosen original)
card nil)
(if (pos? (count (remove #(= % "Done") chosen)))
(continue-ability state side (corp-final (remove #(= % "Done") chosen) original) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid))))))})]
{:on-score {:async true
:waiting-prompt "Corp to add cards from HQ to bottom of R&D"
:effect (req (let [from (get-in @state [:corp :hand])]
(if (pos? (count from))
(continue-ability state :corp (corp-choice from '() from) card nil)
(do (system-msg state side "does not add any cards from HQ to bottom of R&D")
(effect-completed state side eid)))))}}))
(defcard "Remastered Edition"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:msg (msg "place 1 advancement token on " (card-str state target))
:label "place 1 advancement token"
:choices {:card installed?}
:effect (effect (add-prop target :advance-counter 1 {:placed true}))}]})
(defcard "Remote Data Farm"
{:on-score {:silent (req true)
:msg "increase their maximum hand size by 2"}
:constant-effects [(corp-hand-size+ 2)]})
(defcard "Remote Enforcement"
{:on-score
{:interactive (req true)
:optional
{:prompt "Search R&D for a piece of ice to install protecting a remote server?"
:yes-ability
{:async true
:effect (effect
(continue-ability
(if (not-empty (filter ice? (:deck corp)))
{: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 a server to install " (:title chosen-ice) " on")
:choices (filter #(not (#{"HQ" "Archives" "R&D"} %))
(corp-install-list state chosen-ice))
:effect (effect (shuffle! :deck)
(corp-install eid chosen-ice target
{:install-state :rezzed-no-rez-cost}))})
card nil))}
{:prompt "You have no ice in R&D"
:choices ["Carry on!"]
:prompt-type :bogus
:effect (effect (shuffle! :deck))})
card nil))}}}})
(defcard "Research Grant"
{:on-score {:interactive (req true)
:silent (req (empty? (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:async true
:effect (effect (continue-ability
{:prompt "Select another installed copy of Research Grant to score"
:choices {:card #(= (:title %) "Research Grant")}
:interactive (req true)
:async true
:req (req (seq (filter #(= (:title %) "Research Grant") (all-installed state :corp))))
:effect (effect (score eid (get-card state target) {:no-req true}))
:msg "score another installed copy of Research Grant"}
card nil))}})
(defcard "Restructured Datapool"
{:abilities [{:cost [:click 1]
:label "give runner 1 tag"
:trace {:base 2
:successful {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}}}]})
(defcard "SDS Drone Deployment"
{:steal-cost-bonus (req [:program 1])
:on-score {:req (req (seq (all-installed-runner-type state :program)))
:waiting-prompt "Corp to trash a card"
:prompt "Select a program to trash"
:choices {:card #(and (installed? %)
(program? %))
:all true}
:msg (msg "trash " (:title target))
:async true
:effect (effect (trash eid target))}})
(defcard "Self-Destruct Chips"
{:on-score {:silent (req true)
:msg "decrease the Runner's maximum hand size by 1"}
:constant-effects [(runner-hand-size+ -1)]})
(defcard "Sensor Net Activation"
{:on-score {:effect (effect (add-counter card :agenda 1))
:silent (req true)}
:abilities [{:cost [:agenda 1]
:req (req (some #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))
(all-installed state :corp)))
:label "Choose a bioroid to rez, ignoring all costs"
:prompt "Choose a bioroid to rez, ignoring all costs"
:choices {:card #(and (has-subtype? % "Bioroid")
(not (rezzed? %)))}
:msg (msg "rez " (card-str state target) ", ignoring all costs")
:async true
:effect (req (wait-for (rez state side target {:ignore-cost :all-costs})
(let [c (:card async-result)]
(register-events
state side card
[{:event (if (= side :corp) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:effect (effect (derez c))}])
(effect-completed state side eid))))}]})
(defcard "Sentinel Defense Program"
{:events [{:event :pre-resolve-damage
:req (req (and (= target :brain)
(pos? (last targets))))
:msg "do 1 net damage"
:effect (effect (damage eid :net 1 {:card card}))}]})
(defcard "Show of Force"
{:on-score {:async true
:msg "do 2 meat damage"
:effect (effect (damage eid :meat 2 {:card card}))}})
(defcard "SSL Endorsement"
(let [add-credits (effect (add-counter card :credit 9))]
{:flags {:has-events-when-stolen true}
:on-score {:effect add-credits
:interactive (req true)}
:abilities [(set-autoresolve :auto-fire "whether to take credits off SSL")]
:stolen {:effect add-credits}
:events [{:event :corp-turn-begins
:optional
{:req (req (pos? (get-counters card :credit)))
:once :per-turn
:prompt "Gain 3 [Credits] from SSL Endorsement?"
:autoresolve (get-autoresolve :auto-fire)
:yes-ability
{:async true
:msg (msg "gain " (min 3 (get-counters card :credit)) " [Credits]")
:effect (req (if (pos? (get-counters card :credit))
(do (add-counter state side card :credit -3)
(gain-credits state :corp eid 3))
(effect-completed state side eid)))}}}]}))
(defcard "Standoff"
(letfn [(stand [side]
{:async true
:prompt "Choose one of your installed cards to trash due to Standoff"
:choices {:card #(and (installed? %)
(same-side? side (:side %)))}
:cancel-effect (req (if (= side :runner)
(wait-for (draw state :corp 1 nil)
(clear-wait-prompt state :corp)
(system-msg state :runner "declines to trash a card due to Standoff")
(system-msg state :corp "draws a card and gains 5 [Credits] from Standoff")
(gain-credits state :corp eid 5))
(do (system-msg state :corp "declines to trash a card from Standoff")
(clear-wait-prompt state :runner)
(effect-completed state :corp eid))))
:effect (req (wait-for (trash state side target {:unpreventable true})
(system-msg state side (str "trashes " (card-str state target) " due to Standoff"))
(clear-wait-prompt state (other-side side))
(show-wait-prompt state side (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability state (other-side side) (stand (other-side side)) card nil)))})]
{:on-score
{:interactive (req true)
:async true
:effect (effect (show-wait-prompt (str (side-str (other-side side)) " to trash a card for Standoff"))
(continue-ability :runner (stand :runner) card nil))}}))
(defcard "Sting!"
(letfn [(count-opp-stings [state side]
(count (filter #(= (:title %) "Sting!") (get-in @state [(other-side side) :scored]))))]
{:on-score {:msg (msg "deal " (inc (count-opp-stings state :corp)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :corp)) {:card card}))}
:stolen {:msg (msg "deal " (inc (count-opp-stings state :runner)) " net damage")
:async true
:effect (effect (damage eid :net (inc (count-opp-stings state :runner)) {:card card}))}}))
(defcard "Successful Field Test"
(letfn [(sft [n max-ops]
{:prompt "Select a card in HQ to install with Successful Field Test"
:async true
:choices {:card #(and (corp? %)
(not (operation? %))
(in-hand? %))}
:effect (req (wait-for
(corp-install state side target nil {:ignore-all-cost true})
(continue-ability state side (when (< n max-ops) (sft (inc n) max-ops)) card nil)))})]
{:on-score {:async true
:msg "install cards from HQ, ignoring all costs"
:effect (req (let [max-ops (count (filter (complement operation?) (:hand corp)))]
(continue-ability state side (sft 1 max-ops) card nil)))}}))
(defcard "Superconducting Hub"
{:constant-effects [{:type :hand-size
:req (req (= :corp side))
:value 2}]
:on-score
{:optional
{:prompt "Draw 2 cards?"
:yes-ability {:msg "draw 2 cards"
:async true
:effect (effect (draw :corp eid 2 nil))}}}})
(defcard "Superior Cyberwalls"
(ice-boost-agenda "Barrier"))
(defcard "TGTBT"
{:flags {:rd-reveal (req true)}
:access {:msg "give the Runner 1 tag"
:async true
:effect (effect (gain-tags eid 1))}})
(defcard "The Cleaners"
{:events [{:event :pre-damage
:req (req (and (= target :meat)
(= side :corp)))
:msg "do 1 additional meat damage"
:effect (effect (damage-bonus :meat 1))}]})
(defcard "The Future is Now"
{:on-score {:interactive (req true)
:prompt "Choose a card to add to HQ"
:choices (req (:deck corp))
:msg (msg "add a card from R&D to HQ and shuffle R&D")
:req (req (pos? (count (:deck corp))))
:effect (effect (shuffle! :deck)
(move target :hand))}})
(defcard "The Future Perfect"
{:flags {:rd-reveal (req true)}
:access {:psi {:req (req (not installed))
:not-equal
{:msg "prevent it from being stolen"
:effect (effect (register-run-flag!
card :can-steal
(fn [_ _ c] (not (same-card? c card))))
(effect-completed eid))}}}})
(defcard "Timely Public Release"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 1))}
:abilities [{:cost [:agenda 1]
:label "Install a piece of ice in any position, ignoring all costs"
:prompt "Select a piece of ice to install"
:show-discard true
:choices {:card #(and (ice? %)
(or (in-hand? %)
(in-discard? %)))}
:msg (msg "install "
(if (and (in-discard? target)
(or (faceup? target)
(not (facedown? target))))
(:title target)
"ICE")
" from " (zone->name (get-zone target)))
:async true
:effect (effect
(continue-ability
(let [chosen-ice target]
{:prompt "Choose a server"
:choices (req servers)
:async true
:effect (effect
(continue-ability
(let [chosen-server target
num-ice (count (get-in (:corp @state)
(conj (server->zone state target) :ices)))]
{:prompt "Which position to install in? (0 is innermost)"
:choices (vec (reverse (map str (range (inc num-ice)))))
:async true
:effect (req (let [target (Integer/parseInt target)]
(wait-for (corp-install
state side chosen-ice chosen-server
{:ignore-all-cost true :index target})
(when (and run
(= (zone->name (first (:server run)))
chosen-server))
(let [curr-pos (get-in @state [:run :position])]
(when (< target curr-pos)
(swap! state update-in [:run :position] inc))))
(effect-completed state side eid))))})
card nil))})
card nil))}]})
(defcard "Tomorrow's Headline"
(let [ability
{:interactive (req true)
:msg "give Runner 1 tag"
:async true
:effect (req (gain-tags state :corp eid 1))}]
{:on-score ability
:stolen ability}))
(defcard "Transport Monopoly"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 2))}
:abilities [{:cost [:agenda 1]
:req (req run)
:msg "prevent this run from becoming successful"
:effect (effect (register-floating-effect
card
{:type :block-successful-run
:duration :end-of-run
:value true}))}]})
(defcard "Underway Renovation"
(letfn [(adv4? [s c] (if (>= (get-counters (get-card s c) :advancement) 4) 2 1))]
{:install-state :face-up
:events [{:event :advance
:async true
:req (req (same-card? card target))
:msg (msg (if (pos? (count (:deck runner)))
(str "trash "
(string/join ", " (map :title (take (adv4? state card) (:deck runner))))
" from the Runner's stack")
"trash from the Runner's stack but it is empty"))
:effect (effect (mill :corp eid :runner (adv4? state card)))}]}))
(defcard "Unorthodox Predictions"
{:implementation "Prevention of subroutine breaking is not enforced"
:on-score {:prompt "Choose an ICE type for Unorthodox Predictions"
:choices ["Barrier" "Code Gate" "Sentry"]
:msg (msg "prevent subroutines on " target " ICE from being broken until next turn.")}})
(defcard "Utopia Fragment"
{:events [{:event :pre-steal-cost
:req (req (pos? (get-counters target :advancement)))
:effect (req (let [counter (get-counters target :advancement)]
(steal-cost-bonus state side [:credit (* 2 counter)])))}]})
(defcard "Vanity Project"
;; No special implementation
{})
(defcard "Veterans Program"
{:on-score {:interactive (req true)
:msg "lose 2 bad publicity"
:effect (effect (lose-bad-publicity 2))}})
(defcard "Viral Weaponization"
{:on-score
{:effect
(effect
(register-events
card
[{:event (if (= :corp (:active-player @state)) :corp-turn-ends :runner-turn-ends)
:unregister-once-resolved true
:duration :end-of-turn
:msg (msg "do " (count (:hand runner)) " net damage")
:async true
:effect (effect (damage eid :net (count (:hand runner)) {:card card}))}]))}})
(defcard "Voting Machine Initiative"
{:on-score {:silent (req true)
:effect (effect (add-counter card :agenda 3))}
:events [{:event :runner-turn-begins
:optional
{:player :corp
:req (req (pos? (get-counters card :agenda)))
:waiting-prompt "Corp to use Voting Machine Initiative"
:prompt "Use Voting Machine Initiative to make the Runner lose 1 [Click]?"
:yes-ability
{:msg "make the Runner lose 1 [Click]"
:effect (effect (lose :runner :click 1)
(add-counter card :agenda -1))}}}]})
(defcard "Vulnerability Audit"
{:flags {:can-score (req (let [result (not= :this-turn (installed? card))]
(when-not result
(toast state :corp "Cannot score Vulnerability Audit the turn it was installed." "warning"))
result))}})
(defcard "Vulcan Coverup"
{:on-score {:interactive (req true)
:msg "do 2 meat damage"
:async true
:effect (effect (damage eid :meat 2 {:card card}))}
:stolen {:msg "force the Corp to take 1 bad publicity"
:async true
:effect (effect (gain-bad-publicity :corp eid 1))}})
(defcard "Water Monopoly"
{:constant-effects [{:type :install-cost
:req (req (and (resource? target)
(not (has-subtype? target "Virtual"))
(not (:facedown (second targets)))))
:value 1}]})
|
[
{
"context": "ays of looping and doing recursion.\"\n\n {:author \"Adam Helinski\"}\n\n (:require [clojure.test.check.generators :as",
"end": 111,
"score": 0.9991143345832825,
"start": 98,
"tag": "NAME",
"value": "Adam Helinski"
}
] |
project/break/src/clj/test/convex/test/break/loop.clj
|
rosejn/convex.cljc
| 30 |
(ns convex.test.break.loop
"Testing various ways of looping and doing recursion."
{:author "Adam Helinski"}
(:require [clojure.test.check.generators :as TC.gen]
[clojure.test.check.properties :as TC.prop]
[convex.break]
[convex.clj.eval :as $.clj.eval]
[convex.clj :as $.clj]
[convex.clj.gen :as $.clj.gen]
[helins.mprop :as mprop]))
;;;;;;;;;; Helpers
(defn- -recur
"Used by [[recur--]] for generating nested `loop` and `fn` forms which ensures that, in `recur`:
- A counter is properly incremented, looping does occur
- A fixed set of bindings do not mutate
- Possibly nested points of recurion are respected
Sometimes, loops are wrapped in a no-arg function just for messing with the recursion point.
Otherwise, execution stops by calling `fail`."
[[{:keys [fixed+
fn-wrap?
n
recur-point
sym]}
& looping+]]
(let [;; Symbols for binding that do not change during recursion
fixed-sym+ (mapv first
fixed+)
;; And associated values
fixed-x+ (mapv (comp $.clj/quoted
second)
fixed+)
;; Code that will be in the (loop [] ...) or ((fn [] ...)) form
body ($.clj/templ* (if (= ~sym
~n)
(if (= ~fixed-sym+
~fixed-x+)
~n
(fail :NOT-FIXED
"Fixed bindings were wrongfully modified"))
~(let [recur-form ($.clj/templ* (recur ~@fixed-sym+
(inc ~sym)))]
(if looping+
($.clj/templ* (if (= ~(-> looping+
first
:n)
~(-recur looping+))
~recur-form
(fail :BAD-ITER
"Iteration count of inner loop is wrong")))
recur-form))))
;; Wrapping body in a loop or a fn form
looping (case recur-point
:fn ($.clj/templ* ((fn ~(conj fixed-sym+
sym)
~body)
~@(conj fixed-x+
0)))
:loop ($.clj/templ* (loop ~(conj (reduce (fn [acc [sym x]]
(conj acc
sym
($.clj/quoted x)))
[]
fixed+)
sym
0)
~body)))]
;; Messing with point of recursion by wrapping in a fn that is immedialy called
(if fn-wrap?
($.clj/templ* ((fn [] ~looping)))
looping)))
;;;;;;;;;; Tests
(mprop/deftest dotimes--
{:ratio-num 20}
(TC.prop/for-all [n (TC.gen/double* {:infinite? false
:max 1e3
:min 0
:NaN? false})
[sym-bind
sym-counter] (TC.gen/vector-distinct $.clj.gen/symbol
{:num-elements 2})]
($.clj.eval/result* (do
(def ~sym-counter
0)
(dotimes [~sym-bind ~n]
(def ~sym-counter
(+ ~sym-counter
1)))
(== ~sym-counter
(floor ~n))))))
(mprop/deftest recur--
{:ratio-num 5}
(TC.prop/for-all [looping+ (TC.gen/vector (TC.gen/hash-map :fixed+ ($.clj.gen/binding+ 0
4)
:fn-wrap? $.clj.gen/boolean
:n (TC.gen/choose 0
5)
:recur-point (TC.gen/elements [:fn
:loop])
:sym (TC.gen/such-that #(not (#{;; TODO. Must also be different from syms in `:fixed+`
'+
'=
'fail
'inc
'recur}
%))
$.clj.gen/symbol))
1
5)]
(= (-> looping+
first
:n)
($.clj.eval/result (-recur looping+)))))
(mprop/deftest reduce--
{:ratio-num 10}
(TC.prop/for-all [x (TC.gen/such-that #(not-empty (cond->
;; `(list ...)` form or a vector
%
(seq? %)
rest))
$.clj.gen/collection)]
($.clj.eval/result* (let [x '~x
v (nth x
~(rand-int (count x)))]
(= v
(reduce (fn [acc item]
(if (= item
v)
(reduced item)
acc))
:convex-sentinel
x))))))
|
54011
|
(ns convex.test.break.loop
"Testing various ways of looping and doing recursion."
{:author "<NAME>"}
(:require [clojure.test.check.generators :as TC.gen]
[clojure.test.check.properties :as TC.prop]
[convex.break]
[convex.clj.eval :as $.clj.eval]
[convex.clj :as $.clj]
[convex.clj.gen :as $.clj.gen]
[helins.mprop :as mprop]))
;;;;;;;;;; Helpers
(defn- -recur
"Used by [[recur--]] for generating nested `loop` and `fn` forms which ensures that, in `recur`:
- A counter is properly incremented, looping does occur
- A fixed set of bindings do not mutate
- Possibly nested points of recurion are respected
Sometimes, loops are wrapped in a no-arg function just for messing with the recursion point.
Otherwise, execution stops by calling `fail`."
[[{:keys [fixed+
fn-wrap?
n
recur-point
sym]}
& looping+]]
(let [;; Symbols for binding that do not change during recursion
fixed-sym+ (mapv first
fixed+)
;; And associated values
fixed-x+ (mapv (comp $.clj/quoted
second)
fixed+)
;; Code that will be in the (loop [] ...) or ((fn [] ...)) form
body ($.clj/templ* (if (= ~sym
~n)
(if (= ~fixed-sym+
~fixed-x+)
~n
(fail :NOT-FIXED
"Fixed bindings were wrongfully modified"))
~(let [recur-form ($.clj/templ* (recur ~@fixed-sym+
(inc ~sym)))]
(if looping+
($.clj/templ* (if (= ~(-> looping+
first
:n)
~(-recur looping+))
~recur-form
(fail :BAD-ITER
"Iteration count of inner loop is wrong")))
recur-form))))
;; Wrapping body in a loop or a fn form
looping (case recur-point
:fn ($.clj/templ* ((fn ~(conj fixed-sym+
sym)
~body)
~@(conj fixed-x+
0)))
:loop ($.clj/templ* (loop ~(conj (reduce (fn [acc [sym x]]
(conj acc
sym
($.clj/quoted x)))
[]
fixed+)
sym
0)
~body)))]
;; Messing with point of recursion by wrapping in a fn that is immedialy called
(if fn-wrap?
($.clj/templ* ((fn [] ~looping)))
looping)))
;;;;;;;;;; Tests
(mprop/deftest dotimes--
{:ratio-num 20}
(TC.prop/for-all [n (TC.gen/double* {:infinite? false
:max 1e3
:min 0
:NaN? false})
[sym-bind
sym-counter] (TC.gen/vector-distinct $.clj.gen/symbol
{:num-elements 2})]
($.clj.eval/result* (do
(def ~sym-counter
0)
(dotimes [~sym-bind ~n]
(def ~sym-counter
(+ ~sym-counter
1)))
(== ~sym-counter
(floor ~n))))))
(mprop/deftest recur--
{:ratio-num 5}
(TC.prop/for-all [looping+ (TC.gen/vector (TC.gen/hash-map :fixed+ ($.clj.gen/binding+ 0
4)
:fn-wrap? $.clj.gen/boolean
:n (TC.gen/choose 0
5)
:recur-point (TC.gen/elements [:fn
:loop])
:sym (TC.gen/such-that #(not (#{;; TODO. Must also be different from syms in `:fixed+`
'+
'=
'fail
'inc
'recur}
%))
$.clj.gen/symbol))
1
5)]
(= (-> looping+
first
:n)
($.clj.eval/result (-recur looping+)))))
(mprop/deftest reduce--
{:ratio-num 10}
(TC.prop/for-all [x (TC.gen/such-that #(not-empty (cond->
;; `(list ...)` form or a vector
%
(seq? %)
rest))
$.clj.gen/collection)]
($.clj.eval/result* (let [x '~x
v (nth x
~(rand-int (count x)))]
(= v
(reduce (fn [acc item]
(if (= item
v)
(reduced item)
acc))
:convex-sentinel
x))))))
| true |
(ns convex.test.break.loop
"Testing various ways of looping and doing recursion."
{:author "PI:NAME:<NAME>END_PI"}
(:require [clojure.test.check.generators :as TC.gen]
[clojure.test.check.properties :as TC.prop]
[convex.break]
[convex.clj.eval :as $.clj.eval]
[convex.clj :as $.clj]
[convex.clj.gen :as $.clj.gen]
[helins.mprop :as mprop]))
;;;;;;;;;; Helpers
(defn- -recur
"Used by [[recur--]] for generating nested `loop` and `fn` forms which ensures that, in `recur`:
- A counter is properly incremented, looping does occur
- A fixed set of bindings do not mutate
- Possibly nested points of recurion are respected
Sometimes, loops are wrapped in a no-arg function just for messing with the recursion point.
Otherwise, execution stops by calling `fail`."
[[{:keys [fixed+
fn-wrap?
n
recur-point
sym]}
& looping+]]
(let [;; Symbols for binding that do not change during recursion
fixed-sym+ (mapv first
fixed+)
;; And associated values
fixed-x+ (mapv (comp $.clj/quoted
second)
fixed+)
;; Code that will be in the (loop [] ...) or ((fn [] ...)) form
body ($.clj/templ* (if (= ~sym
~n)
(if (= ~fixed-sym+
~fixed-x+)
~n
(fail :NOT-FIXED
"Fixed bindings were wrongfully modified"))
~(let [recur-form ($.clj/templ* (recur ~@fixed-sym+
(inc ~sym)))]
(if looping+
($.clj/templ* (if (= ~(-> looping+
first
:n)
~(-recur looping+))
~recur-form
(fail :BAD-ITER
"Iteration count of inner loop is wrong")))
recur-form))))
;; Wrapping body in a loop or a fn form
looping (case recur-point
:fn ($.clj/templ* ((fn ~(conj fixed-sym+
sym)
~body)
~@(conj fixed-x+
0)))
:loop ($.clj/templ* (loop ~(conj (reduce (fn [acc [sym x]]
(conj acc
sym
($.clj/quoted x)))
[]
fixed+)
sym
0)
~body)))]
;; Messing with point of recursion by wrapping in a fn that is immedialy called
(if fn-wrap?
($.clj/templ* ((fn [] ~looping)))
looping)))
;;;;;;;;;; Tests
(mprop/deftest dotimes--
{:ratio-num 20}
(TC.prop/for-all [n (TC.gen/double* {:infinite? false
:max 1e3
:min 0
:NaN? false})
[sym-bind
sym-counter] (TC.gen/vector-distinct $.clj.gen/symbol
{:num-elements 2})]
($.clj.eval/result* (do
(def ~sym-counter
0)
(dotimes [~sym-bind ~n]
(def ~sym-counter
(+ ~sym-counter
1)))
(== ~sym-counter
(floor ~n))))))
(mprop/deftest recur--
{:ratio-num 5}
(TC.prop/for-all [looping+ (TC.gen/vector (TC.gen/hash-map :fixed+ ($.clj.gen/binding+ 0
4)
:fn-wrap? $.clj.gen/boolean
:n (TC.gen/choose 0
5)
:recur-point (TC.gen/elements [:fn
:loop])
:sym (TC.gen/such-that #(not (#{;; TODO. Must also be different from syms in `:fixed+`
'+
'=
'fail
'inc
'recur}
%))
$.clj.gen/symbol))
1
5)]
(= (-> looping+
first
:n)
($.clj.eval/result (-recur looping+)))))
(mprop/deftest reduce--
{:ratio-num 10}
(TC.prop/for-all [x (TC.gen/such-that #(not-empty (cond->
;; `(list ...)` form or a vector
%
(seq? %)
rest))
$.clj.gen/collection)]
($.clj.eval/result* (let [x '~x
v (nth x
~(rand-int (count x)))]
(= v
(reduce (fn [acc item]
(if (= item
v)
(reduced item)
acc))
:convex-sentinel
x))))))
|
[
{
"context": "(ns ^{:doc \"TODO\"\n :author \"Jude Payne\"}\n loom-viz.graph\n (:require [rhizome.dot ",
"end": 43,
"score": 0.9998888373374939,
"start": 33,
"tag": "NAME",
"value": "Jude Payne"
}
] |
src/loom_viz/graph.cljc
|
judepayne/loom-viz
| 0 |
(ns ^{:doc "TODO"
:author "Jude Payne"}
loom-viz.graph
(:require [rhizome.dot :as rhidot]
[loom.graph :as loom.graph]
[extra-loom.multigraph :as extra-loom]
[loom.attr :as loom.attr]
[clojure.string :as str]
[loom-viz.clustered :as clstr]
[loom-viz.util :as util]
[tool-belt.core :as tb]
#?@(:cljs [[goog.string :as gstring]])
#?@(:cljs [[goog.string.format]])))
;; ---------------------
;; Utility graph functions
(defn- color-channels
"Returns a map of rgb values from a 24-bit number."
[rgb]
{:r (bit-shift-right (bit-and rgb 0xFF0000) 16)
:g (bit-shift-right (bit-and rgb 0x00FF00) 8)
:b (bit-and rgb 0x0000FF)})
(defn- hex
"Convert an unsigned integer to a hex string representation."
[n]
#?(:clj (format "%x" n)
:cljs (.toString n 16)))
(defn- str->rgb
"Converts a string to an rgb color value, blending with blend-with."
[s & {:keys [blend-with] :or {blend-with 0xBBFFBB}}]
(let [h (bit-shift-right (hash s) 8) ;;shift to 24-bit
rgb (color-channels h)
rgb-blend (color-channels blend-with)
red (bit-shift-right (+ (:r rgb) (:r rgb-blend)) 1)
green (bit-shift-right (+ (:g rgb) (:g rgb-blend)) 1)
blue (bit-shift-right (+ (:b rgb) (:b rgb-blend)) 1)]
(str "#" (hex red) (hex green) (hex blue))))
(defn edge-invisible?
[g n1 n2]
(let [style (:style (loom.attr/attrs g n1 n2))]
(and style (some #(= "invis" %) (str/split style #",")))))
(defn leaf? [g n]
(let [succs (loom.graph/successors* g n)
visible-succs (filter #(not (edge-invisible? g n %)) succs)]
(empty? visible-succs)))
(defn root? [g opts n]
(and
(-> opts :env :show-roots?)
(empty? (loom.graph/predecessors* g n))))
(defn successors
"Takes into account invisible edges"
[g n]
(let [succs (loom.graph/successors* g n)]
(filter #(not (edge-invisible? g n %)) succs)))
(defn- fff [nested] (first (ffirst nested)))
(defn- group-map
"Groups m by the first in each of grps, selects the rest keys into
the new submap and continues through the rest of the groups.
e.g. (group-map {:graph-a 1 :graph-b 2 :node-c 4 :edge-a 5}
[:graph :graph-a :graph-b] [:node :node-c])
=> {:graph {:graph-a 1, :graph-b 2}, :node {:edge-a 5}}"
[m & grps]
(reduce
(fn [acc cur]
(assoc acc (first cur) (select-keys m (rest cur))))
{}
grps))
;; ---------------------
;; Config for graph display, using Rhizome library
(def default-options
{:graph
{:dpi 72
:layout "dot"
:splines "lines"
:overlap "prism"
:pad 0.2
:rankdir "LR"}
:node
{:style "filled"
:fontsize 10
:fixedsize "true"
:shape "ellipse"
:margin "0.1"}
:env
{:show-roots? false}})
;; node functions
(defn shape
"Returns the shape of node n in g given options"
[g opts n]
(cond
(root? g opts n) "tripleoctagon"
:else (-> opts :node :shape)))
(defn fillcolor
"Return the fillcolor for node n in g given an options"
[g opts n]
;; if cluster-on, use that key to generate node colours
;; otherwise grab any node and use the first key in it
(let [color-key (if-let [ck (-> opts :env :color-on)]
ck
(if-let [cl (clstr/cluster-key g)]
cl
(fff (loom.graph/nodes g))))]
(str->rgb ((keyword color-key) n))))
(defn html-like-label?
"True is label is or starts with an html like label."
[s]
(when (and s (> (count s) 1))
(= "<<" (subs s 0 2))))
(defn first-label
"Gets the first valid label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"/")
lbl (some #(let [v ((keyword %) metadata)]
(if (= "" v) false v)) lbls)]
(if (nil? lbl) "" lbl)))
(defn composite-label
"Gets the composite label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"&")
flbl (get metadata (keyword (first lbls)))
lbl (if (html-like-label? flbl)
flbl
(apply str flbl "\n"
(interpose "\n"
(map
(fn [x]
(let [l (get metadata (keyword x))]
(if (html-like-label? l)
"" ;; filter out subsequent html-like labels
l)))
(rest lbls)))))]
(if (nil? lbl) "" lbl)))
(defn node-label
"Returns the label for the node n in g given options."
[g opts n]
(cond
(and (leaf? g n) (-> opts :env :hide-leaves?)) ""
:else (if-let [lbls (-> opts :node :label)]
(if (str/includes? lbls "/")
(first-label lbls n)
(composite-label lbls n))
"")))
(defn node-tooltip
"Returns the tooltip for the node n in g given options."
[g opts n]
(when-let [tt (-> opts :node :tooltip)]
(let [ks (map keyword (str/split tt #"&"))
tt (apply str (interpose
"\n"
(reduce
(fn [a c]
(conj a (str (name c) ": "(get n c))))
[]
ks)))]
tt)))
(defn node-url
"Returns the url for the node n in g given options."
[g opts n]
(when-let [url (-> opts :node :url)]
(get n (keyword url))))
;; cljs requires \n to be supplied as \\n otherwise will split line
;; whereas clj does not & will not. Use cljs fomrat but last minute
;; replace for when run from clojure
(defn doub-slash-n
[s]
(if (nil? s)
nil
(str/replace s #"\\\\n" "\n")))
(defn- node-descriptor
"Returns map of attributes for the node from *display-conf*."
[g opts n]
(merge
(:node opts) ;;static attrs
;; attrs result from functions..
(-> {}
(assoc :shape (shape g opts n))
(assoc :label (doub-slash-n (node-label g opts n)))
(assoc :fillcolor (fillcolor g opts n))
(assoc :tooltip (node-tooltip g opts n))
(assoc :URL (node-url g opts n) :target "_blank"))
;;per node attrs supplied by user
(if (and (root? g opts n) (map? (loom.attr/attrs g n)))
(dissoc (loom.attr/attrs g n) :shape)
(loom.attr/attrs g n))))
(defn- maybe-show-constraint [opts edge-attr-map]
(let [show (-> opts :env :show-constraints?)]
(when (and show (:constraint edge-attr-map))
{:style "" :color "deeppink3" :penwidth 4})))
(defn- edge-label
"Returns the label for the edge n1 n2 in g given options."
[opts metadata]
(when-let [lbls (-> opts :edge :edge-label)]
(if (str/includes? lbls "/")
(first-label lbls metadata)
(composite-label lbls metadata))))
(defn- constraints
[opts]
(if (-> opts :env :constraint)
{:constraint true}
{:constraint false}))
(defn- edge-descriptor
"Return map of attributes for the edge from *display-conf*"
[g opts n1 n2]
(let [description (fn [attr-map]
(let [metadata (:meta attr-map)]
(merge
(if (-> opts :edge :edge-label)
{:xlabel (doub-slash-n (edge-label opts metadata)) :forcelabels true}
nil)
(constraints opts)
;; per edge attrs supplied by user
(dissoc attr-map :meta)
(maybe-show-constraint opts attr-map))))
desc (if (extra-loom/extra-loom-graph? g)
(let [edges (extra-loom/edges-between g n1 n2)
attr-fn (fn [es]
(reduce (fn [acc cur]
(conj acc (description (loom.attr/attrs g cur))))
[]
es))]
(attr-fn edges))
(description (loom.attr/attrs g n1 n2)))]
desc))
;; NEEDS TO CHANGE WHEN NEW OPTS ADDED
(defn structure-opts
"structures the incoming opts map the same as default-options"
[opts]
(group-map opts
[:graph :dpi :layout :pad :splines :sep :ranksep
:scale :overlap :nodesep :rankdir :concentrate :ratio]
[:node :shape :label :fontsize :style :fixedsize :tooltip :url :area]
[:env :hide-leaves? :show-roots? :color-on :constraint :show-constraints?]
[:edge :edge-label]))
(defn- cluster-args
[g]
{:node->clusters
(fn [n] ((partial clstr/node->clusters g (clstr/cluster-key g)) n))
:cluster->descriptor
(fn [n]
(merge {:label n}
(let [x (clstr/merged-cluster-attr g n :style)]
(if (nil? x) {} x))))
:cluster->ranks
#(clstr/first-cluster-attr g % :fix-ranks)
:cluster->parent
(partial clstr/cluster-parent g)})
(defn- get-rhizome-args
"Returns the rhizome config (options) for a graph."
[g opts]
(let [opts* (tb/deep-merge default-options (structure-opts opts))]
(merge
{:options (:graph opts*)
:node->descriptor (partial node-descriptor g opts*)
:edge->descriptor (partial edge-descriptor g opts*)}
;; merge in cluster argument when g is clustered
(when (clstr/cluster-key g)
(cluster-args g)))))
;; -------------------------------------------------------------
;; ****** Functions to convert Loom graphs using Rhizome ******
(defn- graph->dot
"Returns an dot representation of a graph."
[ks succs-fn rhi-args]
(-> (apply
rhidot/graph->dot ks succs-fn
(apply concat rhi-args))))
(defn- loomgraph->dot
"converts loom graph to dot using rhizome"
[g rhi-args]
(let [ks (loom.graph/nodes g)
succs-fn #(loom.graph/successors* g %)]
(graph->dot ks succs-fn rhi-args)))
;;--------------------
;; public functions for producing dot
(defn process-graph
"Converts (Loom) graph to either a graph or an svg"
[g opts]
(loomgraph->dot g (get-rhizome-args g opts)))
|
93111
|
(ns ^{:doc "TODO"
:author "<NAME>"}
loom-viz.graph
(:require [rhizome.dot :as rhidot]
[loom.graph :as loom.graph]
[extra-loom.multigraph :as extra-loom]
[loom.attr :as loom.attr]
[clojure.string :as str]
[loom-viz.clustered :as clstr]
[loom-viz.util :as util]
[tool-belt.core :as tb]
#?@(:cljs [[goog.string :as gstring]])
#?@(:cljs [[goog.string.format]])))
;; ---------------------
;; Utility graph functions
(defn- color-channels
"Returns a map of rgb values from a 24-bit number."
[rgb]
{:r (bit-shift-right (bit-and rgb 0xFF0000) 16)
:g (bit-shift-right (bit-and rgb 0x00FF00) 8)
:b (bit-and rgb 0x0000FF)})
(defn- hex
"Convert an unsigned integer to a hex string representation."
[n]
#?(:clj (format "%x" n)
:cljs (.toString n 16)))
(defn- str->rgb
"Converts a string to an rgb color value, blending with blend-with."
[s & {:keys [blend-with] :or {blend-with 0xBBFFBB}}]
(let [h (bit-shift-right (hash s) 8) ;;shift to 24-bit
rgb (color-channels h)
rgb-blend (color-channels blend-with)
red (bit-shift-right (+ (:r rgb) (:r rgb-blend)) 1)
green (bit-shift-right (+ (:g rgb) (:g rgb-blend)) 1)
blue (bit-shift-right (+ (:b rgb) (:b rgb-blend)) 1)]
(str "#" (hex red) (hex green) (hex blue))))
(defn edge-invisible?
[g n1 n2]
(let [style (:style (loom.attr/attrs g n1 n2))]
(and style (some #(= "invis" %) (str/split style #",")))))
(defn leaf? [g n]
(let [succs (loom.graph/successors* g n)
visible-succs (filter #(not (edge-invisible? g n %)) succs)]
(empty? visible-succs)))
(defn root? [g opts n]
(and
(-> opts :env :show-roots?)
(empty? (loom.graph/predecessors* g n))))
(defn successors
"Takes into account invisible edges"
[g n]
(let [succs (loom.graph/successors* g n)]
(filter #(not (edge-invisible? g n %)) succs)))
(defn- fff [nested] (first (ffirst nested)))
(defn- group-map
"Groups m by the first in each of grps, selects the rest keys into
the new submap and continues through the rest of the groups.
e.g. (group-map {:graph-a 1 :graph-b 2 :node-c 4 :edge-a 5}
[:graph :graph-a :graph-b] [:node :node-c])
=> {:graph {:graph-a 1, :graph-b 2}, :node {:edge-a 5}}"
[m & grps]
(reduce
(fn [acc cur]
(assoc acc (first cur) (select-keys m (rest cur))))
{}
grps))
;; ---------------------
;; Config for graph display, using Rhizome library
(def default-options
{:graph
{:dpi 72
:layout "dot"
:splines "lines"
:overlap "prism"
:pad 0.2
:rankdir "LR"}
:node
{:style "filled"
:fontsize 10
:fixedsize "true"
:shape "ellipse"
:margin "0.1"}
:env
{:show-roots? false}})
;; node functions
(defn shape
"Returns the shape of node n in g given options"
[g opts n]
(cond
(root? g opts n) "tripleoctagon"
:else (-> opts :node :shape)))
(defn fillcolor
"Return the fillcolor for node n in g given an options"
[g opts n]
;; if cluster-on, use that key to generate node colours
;; otherwise grab any node and use the first key in it
(let [color-key (if-let [ck (-> opts :env :color-on)]
ck
(if-let [cl (clstr/cluster-key g)]
cl
(fff (loom.graph/nodes g))))]
(str->rgb ((keyword color-key) n))))
(defn html-like-label?
"True is label is or starts with an html like label."
[s]
(when (and s (> (count s) 1))
(= "<<" (subs s 0 2))))
(defn first-label
"Gets the first valid label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"/")
lbl (some #(let [v ((keyword %) metadata)]
(if (= "" v) false v)) lbls)]
(if (nil? lbl) "" lbl)))
(defn composite-label
"Gets the composite label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"&")
flbl (get metadata (keyword (first lbls)))
lbl (if (html-like-label? flbl)
flbl
(apply str flbl "\n"
(interpose "\n"
(map
(fn [x]
(let [l (get metadata (keyword x))]
(if (html-like-label? l)
"" ;; filter out subsequent html-like labels
l)))
(rest lbls)))))]
(if (nil? lbl) "" lbl)))
(defn node-label
"Returns the label for the node n in g given options."
[g opts n]
(cond
(and (leaf? g n) (-> opts :env :hide-leaves?)) ""
:else (if-let [lbls (-> opts :node :label)]
(if (str/includes? lbls "/")
(first-label lbls n)
(composite-label lbls n))
"")))
(defn node-tooltip
"Returns the tooltip for the node n in g given options."
[g opts n]
(when-let [tt (-> opts :node :tooltip)]
(let [ks (map keyword (str/split tt #"&"))
tt (apply str (interpose
"\n"
(reduce
(fn [a c]
(conj a (str (name c) ": "(get n c))))
[]
ks)))]
tt)))
(defn node-url
"Returns the url for the node n in g given options."
[g opts n]
(when-let [url (-> opts :node :url)]
(get n (keyword url))))
;; cljs requires \n to be supplied as \\n otherwise will split line
;; whereas clj does not & will not. Use cljs fomrat but last minute
;; replace for when run from clojure
(defn doub-slash-n
[s]
(if (nil? s)
nil
(str/replace s #"\\\\n" "\n")))
(defn- node-descriptor
"Returns map of attributes for the node from *display-conf*."
[g opts n]
(merge
(:node opts) ;;static attrs
;; attrs result from functions..
(-> {}
(assoc :shape (shape g opts n))
(assoc :label (doub-slash-n (node-label g opts n)))
(assoc :fillcolor (fillcolor g opts n))
(assoc :tooltip (node-tooltip g opts n))
(assoc :URL (node-url g opts n) :target "_blank"))
;;per node attrs supplied by user
(if (and (root? g opts n) (map? (loom.attr/attrs g n)))
(dissoc (loom.attr/attrs g n) :shape)
(loom.attr/attrs g n))))
(defn- maybe-show-constraint [opts edge-attr-map]
(let [show (-> opts :env :show-constraints?)]
(when (and show (:constraint edge-attr-map))
{:style "" :color "deeppink3" :penwidth 4})))
(defn- edge-label
"Returns the label for the edge n1 n2 in g given options."
[opts metadata]
(when-let [lbls (-> opts :edge :edge-label)]
(if (str/includes? lbls "/")
(first-label lbls metadata)
(composite-label lbls metadata))))
(defn- constraints
[opts]
(if (-> opts :env :constraint)
{:constraint true}
{:constraint false}))
(defn- edge-descriptor
"Return map of attributes for the edge from *display-conf*"
[g opts n1 n2]
(let [description (fn [attr-map]
(let [metadata (:meta attr-map)]
(merge
(if (-> opts :edge :edge-label)
{:xlabel (doub-slash-n (edge-label opts metadata)) :forcelabels true}
nil)
(constraints opts)
;; per edge attrs supplied by user
(dissoc attr-map :meta)
(maybe-show-constraint opts attr-map))))
desc (if (extra-loom/extra-loom-graph? g)
(let [edges (extra-loom/edges-between g n1 n2)
attr-fn (fn [es]
(reduce (fn [acc cur]
(conj acc (description (loom.attr/attrs g cur))))
[]
es))]
(attr-fn edges))
(description (loom.attr/attrs g n1 n2)))]
desc))
;; NEEDS TO CHANGE WHEN NEW OPTS ADDED
(defn structure-opts
"structures the incoming opts map the same as default-options"
[opts]
(group-map opts
[:graph :dpi :layout :pad :splines :sep :ranksep
:scale :overlap :nodesep :rankdir :concentrate :ratio]
[:node :shape :label :fontsize :style :fixedsize :tooltip :url :area]
[:env :hide-leaves? :show-roots? :color-on :constraint :show-constraints?]
[:edge :edge-label]))
(defn- cluster-args
[g]
{:node->clusters
(fn [n] ((partial clstr/node->clusters g (clstr/cluster-key g)) n))
:cluster->descriptor
(fn [n]
(merge {:label n}
(let [x (clstr/merged-cluster-attr g n :style)]
(if (nil? x) {} x))))
:cluster->ranks
#(clstr/first-cluster-attr g % :fix-ranks)
:cluster->parent
(partial clstr/cluster-parent g)})
(defn- get-rhizome-args
"Returns the rhizome config (options) for a graph."
[g opts]
(let [opts* (tb/deep-merge default-options (structure-opts opts))]
(merge
{:options (:graph opts*)
:node->descriptor (partial node-descriptor g opts*)
:edge->descriptor (partial edge-descriptor g opts*)}
;; merge in cluster argument when g is clustered
(when (clstr/cluster-key g)
(cluster-args g)))))
;; -------------------------------------------------------------
;; ****** Functions to convert Loom graphs using Rhizome ******
(defn- graph->dot
"Returns an dot representation of a graph."
[ks succs-fn rhi-args]
(-> (apply
rhidot/graph->dot ks succs-fn
(apply concat rhi-args))))
(defn- loomgraph->dot
"converts loom graph to dot using rhizome"
[g rhi-args]
(let [ks (loom.graph/nodes g)
succs-fn #(loom.graph/successors* g %)]
(graph->dot ks succs-fn rhi-args)))
;;--------------------
;; public functions for producing dot
(defn process-graph
"Converts (Loom) graph to either a graph or an svg"
[g opts]
(loomgraph->dot g (get-rhizome-args g opts)))
| true |
(ns ^{:doc "TODO"
:author "PI:NAME:<NAME>END_PI"}
loom-viz.graph
(:require [rhizome.dot :as rhidot]
[loom.graph :as loom.graph]
[extra-loom.multigraph :as extra-loom]
[loom.attr :as loom.attr]
[clojure.string :as str]
[loom-viz.clustered :as clstr]
[loom-viz.util :as util]
[tool-belt.core :as tb]
#?@(:cljs [[goog.string :as gstring]])
#?@(:cljs [[goog.string.format]])))
;; ---------------------
;; Utility graph functions
(defn- color-channels
"Returns a map of rgb values from a 24-bit number."
[rgb]
{:r (bit-shift-right (bit-and rgb 0xFF0000) 16)
:g (bit-shift-right (bit-and rgb 0x00FF00) 8)
:b (bit-and rgb 0x0000FF)})
(defn- hex
"Convert an unsigned integer to a hex string representation."
[n]
#?(:clj (format "%x" n)
:cljs (.toString n 16)))
(defn- str->rgb
"Converts a string to an rgb color value, blending with blend-with."
[s & {:keys [blend-with] :or {blend-with 0xBBFFBB}}]
(let [h (bit-shift-right (hash s) 8) ;;shift to 24-bit
rgb (color-channels h)
rgb-blend (color-channels blend-with)
red (bit-shift-right (+ (:r rgb) (:r rgb-blend)) 1)
green (bit-shift-right (+ (:g rgb) (:g rgb-blend)) 1)
blue (bit-shift-right (+ (:b rgb) (:b rgb-blend)) 1)]
(str "#" (hex red) (hex green) (hex blue))))
(defn edge-invisible?
[g n1 n2]
(let [style (:style (loom.attr/attrs g n1 n2))]
(and style (some #(= "invis" %) (str/split style #",")))))
(defn leaf? [g n]
(let [succs (loom.graph/successors* g n)
visible-succs (filter #(not (edge-invisible? g n %)) succs)]
(empty? visible-succs)))
(defn root? [g opts n]
(and
(-> opts :env :show-roots?)
(empty? (loom.graph/predecessors* g n))))
(defn successors
"Takes into account invisible edges"
[g n]
(let [succs (loom.graph/successors* g n)]
(filter #(not (edge-invisible? g n %)) succs)))
(defn- fff [nested] (first (ffirst nested)))
(defn- group-map
"Groups m by the first in each of grps, selects the rest keys into
the new submap and continues through the rest of the groups.
e.g. (group-map {:graph-a 1 :graph-b 2 :node-c 4 :edge-a 5}
[:graph :graph-a :graph-b] [:node :node-c])
=> {:graph {:graph-a 1, :graph-b 2}, :node {:edge-a 5}}"
[m & grps]
(reduce
(fn [acc cur]
(assoc acc (first cur) (select-keys m (rest cur))))
{}
grps))
;; ---------------------
;; Config for graph display, using Rhizome library
(def default-options
{:graph
{:dpi 72
:layout "dot"
:splines "lines"
:overlap "prism"
:pad 0.2
:rankdir "LR"}
:node
{:style "filled"
:fontsize 10
:fixedsize "true"
:shape "ellipse"
:margin "0.1"}
:env
{:show-roots? false}})
;; node functions
(defn shape
"Returns the shape of node n in g given options"
[g opts n]
(cond
(root? g opts n) "tripleoctagon"
:else (-> opts :node :shape)))
(defn fillcolor
"Return the fillcolor for node n in g given an options"
[g opts n]
;; if cluster-on, use that key to generate node colours
;; otherwise grab any node and use the first key in it
(let [color-key (if-let [ck (-> opts :env :color-on)]
ck
(if-let [cl (clstr/cluster-key g)]
cl
(fff (loom.graph/nodes g))))]
(str->rgb ((keyword color-key) n))))
(defn html-like-label?
"True is label is or starts with an html like label."
[s]
(when (and s (> (count s) 1))
(= "<<" (subs s 0 2))))
(defn first-label
"Gets the first valid label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"/")
lbl (some #(let [v ((keyword %) metadata)]
(if (= "" v) false v)) lbls)]
(if (nil? lbl) "" lbl)))
(defn composite-label
"Gets the composite label from the metadata, which can be a node or edge metadata."
[lbls metadata]
(let [lbls (str/split lbls #"&")
flbl (get metadata (keyword (first lbls)))
lbl (if (html-like-label? flbl)
flbl
(apply str flbl "\n"
(interpose "\n"
(map
(fn [x]
(let [l (get metadata (keyword x))]
(if (html-like-label? l)
"" ;; filter out subsequent html-like labels
l)))
(rest lbls)))))]
(if (nil? lbl) "" lbl)))
(defn node-label
"Returns the label for the node n in g given options."
[g opts n]
(cond
(and (leaf? g n) (-> opts :env :hide-leaves?)) ""
:else (if-let [lbls (-> opts :node :label)]
(if (str/includes? lbls "/")
(first-label lbls n)
(composite-label lbls n))
"")))
(defn node-tooltip
"Returns the tooltip for the node n in g given options."
[g opts n]
(when-let [tt (-> opts :node :tooltip)]
(let [ks (map keyword (str/split tt #"&"))
tt (apply str (interpose
"\n"
(reduce
(fn [a c]
(conj a (str (name c) ": "(get n c))))
[]
ks)))]
tt)))
(defn node-url
"Returns the url for the node n in g given options."
[g opts n]
(when-let [url (-> opts :node :url)]
(get n (keyword url))))
;; cljs requires \n to be supplied as \\n otherwise will split line
;; whereas clj does not & will not. Use cljs fomrat but last minute
;; replace for when run from clojure
(defn doub-slash-n
[s]
(if (nil? s)
nil
(str/replace s #"\\\\n" "\n")))
(defn- node-descriptor
"Returns map of attributes for the node from *display-conf*."
[g opts n]
(merge
(:node opts) ;;static attrs
;; attrs result from functions..
(-> {}
(assoc :shape (shape g opts n))
(assoc :label (doub-slash-n (node-label g opts n)))
(assoc :fillcolor (fillcolor g opts n))
(assoc :tooltip (node-tooltip g opts n))
(assoc :URL (node-url g opts n) :target "_blank"))
;;per node attrs supplied by user
(if (and (root? g opts n) (map? (loom.attr/attrs g n)))
(dissoc (loom.attr/attrs g n) :shape)
(loom.attr/attrs g n))))
(defn- maybe-show-constraint [opts edge-attr-map]
(let [show (-> opts :env :show-constraints?)]
(when (and show (:constraint edge-attr-map))
{:style "" :color "deeppink3" :penwidth 4})))
(defn- edge-label
"Returns the label for the edge n1 n2 in g given options."
[opts metadata]
(when-let [lbls (-> opts :edge :edge-label)]
(if (str/includes? lbls "/")
(first-label lbls metadata)
(composite-label lbls metadata))))
(defn- constraints
[opts]
(if (-> opts :env :constraint)
{:constraint true}
{:constraint false}))
(defn- edge-descriptor
"Return map of attributes for the edge from *display-conf*"
[g opts n1 n2]
(let [description (fn [attr-map]
(let [metadata (:meta attr-map)]
(merge
(if (-> opts :edge :edge-label)
{:xlabel (doub-slash-n (edge-label opts metadata)) :forcelabels true}
nil)
(constraints opts)
;; per edge attrs supplied by user
(dissoc attr-map :meta)
(maybe-show-constraint opts attr-map))))
desc (if (extra-loom/extra-loom-graph? g)
(let [edges (extra-loom/edges-between g n1 n2)
attr-fn (fn [es]
(reduce (fn [acc cur]
(conj acc (description (loom.attr/attrs g cur))))
[]
es))]
(attr-fn edges))
(description (loom.attr/attrs g n1 n2)))]
desc))
;; NEEDS TO CHANGE WHEN NEW OPTS ADDED
(defn structure-opts
"structures the incoming opts map the same as default-options"
[opts]
(group-map opts
[:graph :dpi :layout :pad :splines :sep :ranksep
:scale :overlap :nodesep :rankdir :concentrate :ratio]
[:node :shape :label :fontsize :style :fixedsize :tooltip :url :area]
[:env :hide-leaves? :show-roots? :color-on :constraint :show-constraints?]
[:edge :edge-label]))
(defn- cluster-args
[g]
{:node->clusters
(fn [n] ((partial clstr/node->clusters g (clstr/cluster-key g)) n))
:cluster->descriptor
(fn [n]
(merge {:label n}
(let [x (clstr/merged-cluster-attr g n :style)]
(if (nil? x) {} x))))
:cluster->ranks
#(clstr/first-cluster-attr g % :fix-ranks)
:cluster->parent
(partial clstr/cluster-parent g)})
(defn- get-rhizome-args
"Returns the rhizome config (options) for a graph."
[g opts]
(let [opts* (tb/deep-merge default-options (structure-opts opts))]
(merge
{:options (:graph opts*)
:node->descriptor (partial node-descriptor g opts*)
:edge->descriptor (partial edge-descriptor g opts*)}
;; merge in cluster argument when g is clustered
(when (clstr/cluster-key g)
(cluster-args g)))))
;; -------------------------------------------------------------
;; ****** Functions to convert Loom graphs using Rhizome ******
(defn- graph->dot
"Returns an dot representation of a graph."
[ks succs-fn rhi-args]
(-> (apply
rhidot/graph->dot ks succs-fn
(apply concat rhi-args))))
(defn- loomgraph->dot
"converts loom graph to dot using rhizome"
[g rhi-args]
(let [ks (loom.graph/nodes g)
succs-fn #(loom.graph/successors* g %)]
(graph->dot ks succs-fn rhi-args)))
;;--------------------
;; public functions for producing dot
(defn process-graph
"Converts (Loom) graph to either a graph or an svg"
[g opts]
(loomgraph->dot g (get-rhizome-args g opts)))
|
[
{
"context": "outes namespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed und",
"end": 93,
"score": 0.9989639520645142,
"start": 90,
"tag": "NAME",
"value": "F.M"
},
{
"context": "amespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed under the Apache L",
"end": 111,
"score": 0.9317696690559387,
"start": 96,
"tag": "NAME",
"value": "Filip) de Waard"
},
{
"context": "right 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 125,
"score": 0.9999327063560486,
"start": 113,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session\n {:username \"someone\"\n :permissions {:* [\"GET\" \"POST\"",
"end": 2598,
"score": 0.9995269179344177,
"start": 2591,
"tag": "USERNAME",
"value": "someone"
},
{
"context": " :session\n {:username \"nemo\"\n :permissions {:blog []}}))))\n\n",
"end": 2956,
"score": 0.9995952844619751,
"start": 2952,
"tag": "USERNAME",
"value": "nemo"
},
{
"context": " :title\n \"Tomasz Stańko Middelburg\"\n :slug\n ",
"end": 11001,
"score": 0.9998686909675598,
"start": 10977,
"tag": "NAME",
"value": "Tomasz Stańko Middelburg"
},
{
"context": " :content\n (str \"Gwilym Simcock, \"\n \"Mike Wal",
"end": 12323,
"score": 0.9998733401298523,
"start": 12309,
"tag": "NAME",
"value": "Gwilym Simcock"
},
{
"context": " Simcock, \"\n \"Mike Walker, \"\n \"Adam Nus",
"end": 12376,
"score": 0.9998606443405151,
"start": 12365,
"tag": "NAME",
"value": "Mike Walker"
},
{
"context": "e Walker, \"\n \"Adam Nussbaum, \"\n \"Steve Sw",
"end": 12431,
"score": 0.999881386756897,
"start": 12418,
"tag": "NAME",
"value": "Adam Nussbaum"
},
{
"context": "Nussbaum, \"\n \"Steve Swallow \"\n \"will be p",
"end": 12486,
"score": 0.9998559951782227,
"start": 12473,
"tag": "NAME",
"value": "Steve Swallow"
},
{
"context": " :title\n \"Yuri Honing\"\n :slug\n ",
"end": 13323,
"score": 0.999859094619751,
"start": 13312,
"tag": "NAME",
"value": "Yuri Honing"
},
{
"context": "ze winner \"\n \"Yuri Honing will be playing at \"\n ",
"end": 13587,
"score": 0.99964439868927,
"start": 13576,
"tag": "NAME",
"value": "Yuri Honing"
},
{
"context": " :title\n \"Yuri Honing\"\n :slug\n ",
"end": 14391,
"score": 0.9998701810836792,
"start": 14380,
"tag": "NAME",
"value": "Yuri Honing"
},
{
"context": "ze winner \"\n \"Yuri Honing at \"\n \"the Pa",
"end": 14661,
"score": 0.9994631409645081,
"start": 14650,
"tag": "NAME",
"value": "Yuri Honing"
},
{
"context": "(deftest test-logout\n (is (= (logout {:username \"johndoe\" :permissions {:* [:DELETE]}})\n {:session",
"end": 107833,
"score": 0.9996728897094727,
"start": 107826,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": "m-request :post \"/login\" main-routes {\"username\" \"fmw\"\n ",
"end": 108275,
"score": 0.9994966387748718,
"start": 108272,
"tag": "USERNAME",
"value": "fmw"
},
{
"context": " \"password\" \"foo\"})\n {:status 302\n :headers {",
"end": 108345,
"score": 0.9992315769195557,
"start": 108342,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "m-request :post \"/login\" main-routes {\"username\" \"fmw\"\n ",
"end": 108574,
"score": 0.9995001554489136,
"start": 108571,
"tag": "USERNAME",
"value": "fmw"
},
{
"context": " \"password\" \"oops\"})]\n (is (= ((:headers r) \"Location\") \"/admi",
"end": 108646,
"score": 0.9992732405662537,
"start": 108642,
"tag": "PASSWORD",
"value": "oops"
}
] |
test/clj/vix/test/routes.clj
|
fmw/vix
| 22 |
;; test/vix/test/routes.clj tests for routes namespace.
;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.
;;
;; 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 vix.test.routes
(:use [clojure.test]
[ring.middleware params
keyword-params
nested-params
multipart-params
cookies
flash]
[slingshot.slingshot :only [throw+]]
[slingshot.test]
[vix.routes] :reload
[clojure.data.json :only [json-str read-json]]
[vix.test.db :only [database-fixture +test-db+]]
[vix.test.test])
(:require [clj-time.format :as time-format]
[clj-time.core :as time-core]
[net.cgrand.enlive-html :as html]
[com.ashafa.clutch :as clutch]
[vix.db :as db]
[vix.auth :as auth]
[vix.config :as config]
[vix.util :as util]
[vix.lucene :as lucene])
(:import [org.apache.commons.codec.binary Base64]))
(def last-modified-pattern
#"[A-Z]{1}[a-z]{2}, \d{1,2} [A-Z]{1}[a-z]{2} \d{4} \d{2}:\d{2}:\d{2} \+0000")
(def mock-app
"Mock app without session middleware, so session is preserved."
(-> main-routes
wrap-keyword-params
wrap-nested-params
wrap-params
(wrap-multipart-params)
(wrap-flash)
(redirection-handler)
(wrap-caching-headers)
(handle-exceptions)))
(defn request-map [method resource body params]
{:request-method method
:uri resource
:body (when body (java.io.StringReader. body))
:params params
:server-name "localhost"})
; FIXME: refactor these four request functions to get rid of duplication
(defn request
([method resource my-routes]
(request method resource "" my-routes {}))
([method resource body my-routes]
(request method resource body my-routes {}))
([method resource body my-routes params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "someone"
:permissions {:* ["GET" "POST" "PUT" "DELETE"]}}))))
(defn unauthorized-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "nemo"
:permissions {:blog []}}))))
(defn unauthenticated-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (request-map method resource body params))))
(defn form-request [method resource my-routes form-params]
(app (dissoc (assoc (request-map method resource nil nil)
:form-params
form-params)
:body)))
(deftest test-reset-search-allowed-feeds!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(db/append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Vix Weblog!"
:name "images"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable false}))
(reset! search-allowed-feeds {})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["blog"]}))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["news" "blog"]})))
(deftest test-reset-available-languages!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true}))
(reset! available-languages {})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en"]))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"
:searchable true})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en" "nl"])))
(deftest test-reset-index-reader!
(let [ir @index-reader]
(do
(reset-index-reader!))
(is (not (= ir @index-reader))))
(do
(compare-and-set! index-reader @index-reader nil)
(is (= @index-reader nil))
(reset-index-reader!))
(is (= (class @index-reader)
org.apache.lucene.index.ReadOnlyDirectoryReader)))
(deftest test-data-response
(is (= (:status (data-response nil))
(:status (data-response nil :type :json))
(:status (data-response nil :type :clj)) 404))
(is (= (data-response {:foo "bar"} :type :json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"}))
(is (= (data-response {:foo "bar"})
(data-response {:foo "bar"} :type :clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "{:foo \"bar\"}"}))
(is (= (data-response {:foo "bar"} :status 201 :type :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"})))
(deftest test-response
(is (= (response "foo") {:status 200
:headers {"Content-Type"
"text/html; charset=UTF-8"}
:body "foo"}))
(is (= (:status (response nil) 404)))
(is (= (:status (response "foo" :status 201) 201)))
(is (= (get (:headers (response "foo" :content-type "image/png"))
"Content-Type")
"image/png")))
(deftest test-page-not-found-response
(is (= (page-not-found-response)
{:status 404
:headers {"Content-Type" "text/html; charset=UTF-8"}
:body "<h1>Page not found</h1>"})))
(deftest test-image-response
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false})
no-image-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:content ""
:draft false})
wp-response (image-response +test-db+ white-pixel-doc)]
(testing "test if a simple gif is returned correctly"
(is (= (get-in wp-response [:headers "Last-Modified"])
(time-format/unparse (time-format/formatters :rfc822)
(util/rfc3339-to-jodatime
(:published (first white-pixel-doc))
"UTC"))))
(is (re-matches last-modified-pattern
(get-in wp-response [:headers "Last-Modified"])))
(is (= (:status wp-response) 200))
(is (= (dissoc (:headers wp-response) "Last-Modified")
{"ETag" (:_rev (first white-pixel-doc))
"Content-Type" "image/gif"}))
(is (= (class (:body wp-response))
clj_http.core.proxy$java.io.FilterInputStream$0)))
(testing "test if a non-image document is handled correctly"
(is (= (image-response +test-db+ no-image-doc)
(page-not-found-response))))))
(deftest test-get-segment-and-get-segments
(let [slug-fn
(fn [language]
(str "/" language "/menu/menu"))
menu-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "menu"
:title "menu"
:slug "/en/menu/menu"
:content (str "<ul><li><a href=\""
"/\">home</a></li></ul>")
:draft false})
grote-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"grote-zaal"
:title
"Tomasz Stańko Middelburg"
:slug
"/en/grote-zaal/stanko-middelburg"
:content
(str "The legendary Polish "
"trumpet player Stańko "
"will be playing in "
"Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
kleine-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kleine-zaal"
:title
"The Impossible Gentlemen"
:slug
(str "/en/kleine-zaal/"
"impossible-gentlemen")
:content
(str "Gwilym Simcock, "
"Mike Walker, "
"Adam Nussbaum, "
"Steve Swallow "
"will be playing "
"at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
kabinet-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"Yuri Honing"
:slug
"/en/kabinet/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"Yuri Honing will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})
kabinet-doc-2 ;; dummy doc that should not be retrieved
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"Yuri Honing"
:slug
"/en/kabinet/yuri-honing-tilburg-dummy"
:content
(str "VPRO/Boy Edgar prize winner "
"Yuri Honing at "
"the Paradox venue in Tilburg.")
:start-time
"2012-02-01 20:30"
:end-time
"2012-02-01 23:59"
:draft false})
news-1
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"hey!"
:slug
"/en/news/hey"
:content
""
:draft false})
news-2
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"you!"
:slug
"/en/news/you"
:content
""
:draft false})
frontpage-segments
{:menu
{:type :document
:nodes :#menu
:slug slug-fn}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}}]
(testing "test (get-segment ...)"
(is (= (:content (:data (get-segment (:menu frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")))
"<ul><li><a href=\"/\">home</a></li></ul>"))
(is (= (get-segment (:primary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:primary-exposition frontpage-segments)
:data
(first grote-zaal-doc))))
(is (= (get-segment (:secondary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:secondary-exposition frontpage-segments)
:data
(first kleine-zaal-doc))))
(is (= (get-segment (:tertiary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:tertiary-exposition frontpage-segments)
:data
(first kabinet-doc))))
(is (= (get-segment (:news frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:news frontpage-segments)
:data
{:next nil
:documents [(first news-2) (first news-1)]})))
(is (= (get-segment {:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}
+test-db+
"en"
"Europe/Amsterdam")
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")})))
(testing "test (get-segments...)"
(is (= (get-segments frontpage-segments
+test-db+
"en"
"Europe/Amsterdam")
{:menu
{:type :document
:nodes :#menu
:slug slug-fn
:data (first menu-doc)}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1
:data (first grote-zaal-doc)}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1
:data (first kleine-zaal-doc)}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1
:data (first kabinet-doc)}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2
:data {:next nil
:documents [(first news-2) (first news-1)]}}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}})))))
(deftest test-get-frontpage-for-language!
;; this is tested in the tests for the view
;; if it returns a string the view is executed successfully
(is (string? (first (get-frontpage-for-language! +test-db+
"nl"
"Europe/Amsterdam")))))
(deftest test-get-cached-frontpage!
(is (= @frontpage-cache {}))
(let [empty-cache-fp (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")]
(is (= @frontpage-cache {"nl" empty-cache-fp}))
(do ; insert fake string to make sure pages are served from cache
(swap! frontpage-cache assoc "nl" "foo!"))
(is (= (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")
"foo!")))
(reset-frontpage-cache! "nl"))
(deftest test-reset-frontpage-cache!
(testing "test reset-frontpage-cache! on a single language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(is (= @frontpage-cache {"nl" "foo!"}))
(is (= (reset-frontpage-cache! "nl") {})))
(testing "test reset-frontpage-cache! on a multiple language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(swap! frontpage-cache assoc "en" "bar!")
(is (= @frontpage-cache {"nl" "foo!" "en" "bar!"}))
(is (= (reset-frontpage-cache! "nl") {"en" "bar!"}))))
(deftest test-reset-page-cache!
(is (= @page-cache {}))
(swap! page-cache assoc "/events/clojure-meetup.html" "hey!")
(is (not (= @page-cache {})))
(is (= (reset-page-cache!) {}))
(is (= @page-cache {})))
(deftest test-get-cached-page!
(is (= @page-cache {}))
(testing "make sure images skip the cache"
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/images/white-pixel.gif"
"Europe/Amsterdam"))
[:status :headers :body]))
;; the cache should still be empty:
(is (= @page-cache {}))))
(testing "test with a regular page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title "hic sunt dracones!"
:slug "/pages/hic-sunt-dracones.html"
:content "<h3>Here be dragons!</h3>"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/pages/hic-sunt-dracones.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/pages/hic-sunt-dracones.html" "hi!")
(is (= (get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam")
"hi!")))
;; TODO: make this test actually meaningful
(testing "test with event page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "calendar"
:title "Clojure Meetup!"
:slug "/events/clojure-meetup.html"
:content "<h3>Here be dragons!</h3>"
:start-time "2012-05-16 18:45"
:start-time-rfc3339 "2012-05-16T18:45:00.000Z"
:end-time "2012-05-16 23:00"
:end-time-rfc3339 "2012-05-16T23:00:00.000Z"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/events/clojure-meetup.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/events/clojure-meetup.html" "hello!")
(is (= (get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam")
"hello!")))
;; clean up
(reset-page-cache!)
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
404))
(is (= (:body (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
"<h1>Page not found</h1>"))
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
200))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/pixel.gif"
:content ""
:draft false})
image-response (get-cached-page! +test-db+
"/pixel.gif"
"Europe/Amsterdam")]
(is (= (get (:headers image-response) "Content-Type") "image/gif"))
(is (= (class (:body image-response))
clj_http.core.proxy$java.io.FilterInputStream$0))))
;; clean up
(reset-page-cache!))
(defn- remove-ids
"Removes internal database identifiers from the provided state map."
[{:keys [action] :as state}]
(assoc (dissoc state :_rev :_id :previous-id)
:action (keyword action)))
(defn- clean-body
"Returns a new version of the response map, with database internals
(i.e. :_id, :_rev and :previous-id) removed from the state sequence
in the response body. The body is read through read-json if :json
is passed as the value of the type argument and otherwise through
read-string. If the response type is json, the :action value is
turned into a keyword. If the response status is 400, the original
response is returned."
[type response]
(if (= (:status response) 400)
response
(update-in response
[:body]
(fn [body]
(map remove-ids
(if (= type :json)
(read-json body)
(read-string body)))))))
(deftest test-feed-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [blog-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "standard"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}")
:language "en"
:language-full "English"
:name "blog"
:searchable true
:subtitle ""
:title "Weblog"
:type "feed"}
image-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "image"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}.{ext}")
:language "en"
:language-full "English"
:name "images"
:searchable false
:subtitle ""
:title "Images"
:type "feed"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :POST :json blog-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :POST :clj image-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [image-feed]})))
(testing "test if feeds are updated correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+
:PUT
:json
(assoc blog-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"blog")))
:title "foo")
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+
:PUT
:clj
(assoc image-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"images")))
:title "foo")
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are loaded correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :GET :json nil "en" "blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :GET :clj nil "en" "images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are deleted correctly."
;; test json request
(let [current-blog-feed (db/get-feed +test-db+ "en" "blog")]
(is (= (clean-body
:json
(feed-request +test-db+
:DELETE
:json
(assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first current-blog-feed)))
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first
current-blog-feed)))
current-blog-feed))})))
;; test clojure request
(let [current-images-feed (db/get-feed +test-db+ "en" "images")]
(is (= (clean-body
:clj
(feed-request +test-db+
:DELETE
:clj
(assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
current-images-feed))})))))))
(defn- clean-req
"Parses the response :body and removes :_id and :_rev from states.
Also turns each state :action value into a keyword if it concerns a
JSON request. Accepts a response argument, as well as a type
(i.e. :json or :clj)."
[response type]
(update-in response
[:body]
(fn [states]
(map (fn [state]
(if (= type :clj)
(dissoc state :_rev :_id :previous-id)
(update-in (dissoc state :_rev :_id :previous-id)
[:action] keyword)))
(if (= type :clj)
(read-string states)
(read-json states))))))
(deftest test-document-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [json-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}
clj-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd-clj"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-req (document-request :POST :json json-doc) :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [json-doc]}))
;; test clojure request
(is (= (clean-req (document-request :POST :clj clj-doc) :clj)
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [clj-doc]})))
(testing "test if documents are updated correctly."
;; test json request
(let [json-doc-fresh (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (clean-req
(document-request :PUT
:json
(assoc (first json-doc-fresh)
:action
:update
:previous-id
(:_id (first json-doc-fresh))
:title
"foo"))
:json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first json-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd"))])})))
;; test clojure request
(let [clj-doc-fresh (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (clean-req
(document-request :PUT
:clj
(assoc (first clj-doc-fresh)
:action
:update
:previous-id
(:_id (first clj-doc-fresh))
:title
"foo"))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first clj-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd-clj"))])}))))
(testing "test if feeds are loaded correctly."
;; test json request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (document-request :GET :json existing-doc)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (json-str existing-doc)})))
;; test clojure request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (document-request :GET :clj existing-doc)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (pr-str existing-doc)}))))
(testing "test if feeds are deleted correctly."
;; test json request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd"))]
(is (= (clean-req
(document-request :DELETE
:json
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :delete,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :update,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil,
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :create,
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))
;; test clojure request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd-clj"))]
(is (= (clean-req
(document-request :DELETE
:clj
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :delete
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :update
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :create
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))))))
(deftest ^{:integration true} test-routes
(with-redefs [util/now-rfc3339 #(str "2012-09-22T04:07:05.756Z")]
(do
(db/append-to-feed +test-db+
{:action :create
:title "Pages"
:subtitle "Test Pages"
:name "pages"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "standard"
:language "en"
:searchable true})
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(let [directory (lucene/create-directory :RAM)]
(with-redefs [search-allowed-feeds (atom {"en" ["pages"]})
config/search-results-per-page 10
config/database +test-db+
lucene/directory directory]
(with-redefs [util/now-rfc3339
(fn []
(time-format/unparse
(time-format/formatters :date-time)
(time-core/now)))]
(dotimes [n 21]
(lucene/add-documents-to-index!
lucene/directory
[(first
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content "bar"
:draft false}))])))
(with-redefs [index-reader (atom
(lucene/create-index-reader directory))]
(testing "test document pagination"
;; test json request
(let [first-five (read-json
(:body
(request :get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-json
(:body
(request
:get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5))))
;; test clojure request
(let [first-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5)))))
(testing "test search page and search pagination"
(let [first-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"})))))]
(is (= (html/text
(first
(html/select
first-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select first-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-0"
1 "/pages/doc-1"
2 "/pages/doc-2"
3 "/pages/doc-3"
4 "/pages/doc-4"
5 "/pages/doc-5"
6 "/pages/doc-6"
7 "/pages/doc-7"
8 "/pages/doc-8"
9 "/pages/doc-9")
(is (= (html/select first-page
[:a#previous-search-results-page])
[]))
(is (= (first
(html/attr-values
(first
(html/select first-page
[:a#next-search-results-page]))
:href))
"/en/search?q=bar&after-doc-id=9&after-score=0.47674")))
(let [second-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request
:get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "9"
:after-score "0.47674"})))))]
(is (= (html/text
(first
(html/select
second-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select second-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-17"
1 "/pages/doc-18"
2 "/pages/doc-10"
3 "/pages/doc-11"
4 "/pages/doc-12"
5 "/pages/doc-13"
6 "/pages/doc-14"
7 "/pages/doc-15"
8 "/pages/doc-16"
9 "/pages/doc-19")
(is (= (html/attr-values
(first
(html/select second-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar"}))
(is (= (first
(html/attr-values
(first
(html/select second-page
[:a#next-search-results-page]))
:href))
(str "/en/search?q=bar&after-doc-id=19"
"&after-score=0.47674"
"&pp-aid[]=9&pp-as[]=0.47674"))))
(let [third-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "19"
:after-score "0.47674"
:pp-aid ["9"]
:pp-as ["0.47674"]})))))]
(is (= (html/text
(first
(html/select
third-page
[:span#search-stats])))
"21 results for query"))
(is (= (first
(html/attr-values
(first (html/select third-page
[[:ol#search-results]
[:li]
[:a]]))
:href))
"/pages/doc-20"))
(is
(= (html/attr-values
(first
(html/select third-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar&after-doc-id=9&after-score=0.47674"}))
(is (= (html/select third-page [:a#next-search-results-page])
[]))))
(is (= (:status (request :get "/" main-routes)) 200))
(is (= (:status (request :get "/login" main-routes)) 200))
(is (= (:status (request :get "/logout" main-routes)) 302))
(is (= (:status (request :get "/admin" main-routes)) 200))
(is (= (:status (request :get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (request :get
"/_api/clj/en/blog/_list-documents"
main-routes))
200))
;; test json request
(is (= (:status (request
:post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test clojure request
(is (= (:status (request
:post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test json POST request with HTTP method/action mismatch
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :delete
:title "test-create"
:slug "/blog/test-unique"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate clojure request with HTTP method/action mismatch
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :delete
:title "test-create"
:slug "/blog/test-unique-snowflake"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate json POST request
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test duplicate clojure POST request
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test json POST request with missing keys
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
;; test clojure POST request with missing keys
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
(testing "test if the document is added to the database"
;; test for json request
(let [document (db/get-document +test-db+ "/blog/test")]
(is (= (:title document)) "test-create"))
;; test for clojure request
(let [document (db/get-document +test-db+ "/blog/test-clj")]
(is (= (:title document)) "test-create")))
(testing "test if the document is added to the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 21) "title")
(.get (lucene/get-doc reader 22) "title")
"test-create"))))
(is (= (:status (request :get
"/_api/json/_document/blog/bar"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/bar"
main-routes))
200))
(is (= (:status (request :get
"/_api/json/_document/blog/t3"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/t3"
main-routes))
404))
(testing "test if documents are updated correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :put
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
(is (= (request
:put
"/_api/json/_document/blog/doesnt-exist"
(json-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request
:put
"/_api/clj/_document/blog/test-clj"
(pr-str (assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
(is (= (request
:put
"/_api/clj/_document/blog/doesnt-exist"
(pr-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")}))))
(testing "test if documents are also updated in the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 22) "title") "hi!"))))
(testing "test if document is deleted from the database correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/bar")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/test-clj")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."}))))
(testing "test if document is also deleted from the lucene index."
(let [reader (lucene/create-index-reader directory)
analyzer (lucene/create-analyzer)
filter (lucene/create-filter {:slug "/blog/bar"})
result (lucene/search "hi" filter 15 reader analyzer)
docs (lucene/get-docs reader (:docs result))]
(is (= (:total-hits result) 0)))))
(is (= (:status (request :get "/static/none" main-routes)) 404))
(is (= (:body (request :get "/static/none" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/bar" main-routes)) 404))
(is (= (:body (request :get "/blog/bar" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/test" main-routes)) 200))
(let [post-feed-request (request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Vix Weblog"
:language "en"
:subtitle "Vix Weblog..."
:default-slug-format
"/{document-title}"
:default-document-type "standard"
:searchable true})
main-routes)]
(is (= (:status post-feed-request) 201))
(is (= @search-allowed-feeds
(db/get-searchable-feeds (db/list-feeds +test-db+))
{"en" ["pages" "blog"]})
"Test if search-allowed-feeds is updated when feed is added")
(let [image-feed (map #(update-in % [:action] keyword)
(read-json
(:body
(request
:post
"/_api/json/_feed/en/image"
(json-str
{:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes))))
all-feeds (map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
main-routes))))
image-feed-nl (read-string
(:body
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)))]
(is (= (count all-feeds) 3))
;; test HTTP method/action mismatch
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :delete
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :delete
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; make sure it isn't possible to recreate existing feeds
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The provided feed already exists."}))
(testing "test language argument for /_api/x/_list-feeds"
(is (= (sort-by :name all-feeds)
(sort-by :name
(map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
nil
main-routes
{:language "en"})))))
(sort-by :name
(read-string
(:body
(request :get
"/_api/clj/_list-feeds"
nil
main-routes
{:language "en"}))))))
(is (= image-feed-nl
(read-string
(:body
(request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type "image"
:language "nl"}))))))
(is (= (count (read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
4))
(is (= (map #(update-in % [:action] keyword)
(read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
(read-string
(:body (request :get
"/_api/clj/_list-feeds"
main-routes)))))
(is (= (flatten [image-feed-nl image-feed])
(map #(update-in % [:action] keyword)
(read-json
(:body (request
:get
"/_api/json/_list-feeds"
nil
main-routes
{:default-document-type
"image"}))))
(read-string
(:body (request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type
"image"})))))))
(let [{:keys [status body] :as get-feed-json}
(update-in (request :get
"/_api/json/_feed/en/blog"
main-routes)
[:body]
read-json)
get-feed-clj
(update-in (request :get
"/_api/clj/_feed/en/blog"
main-routes)
[:body]
read-string)]
(is (= (update-in (dissoc get-feed-json :headers)
[:body]
(fn [states]
(map #(update-in % [:action] keyword) states)))
(dissoc get-feed-clj :headers)))
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix Weblog"))
;; make sure that update requests aren't allowed without
;; :previous-id
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the "
"most recent :previous-id.")})))
;; test json put request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-json}
(update-in (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Vix!"
:searchable false))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix!"))
(is (= @search-allowed-feeds {"nl" [] "en" ["pages"]})
"Make sure search-allowed-feeds is updated when feeds are")))
;; test clojure put request
(let [prev-body (first
(read-string
(:body
(request :get
"/_api/clj/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-clj}
(update-in (request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Fix!"
:searchable false))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Fix!")))
(testing "test delete requests"
;; make sure delete requests aren't allowed without :previous-id
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the most recent "
":previous-id.")}))
;; test json delete request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as delete-request-json}
(update-in (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (keyword (:action (first body)))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete)))
;; make sure the right error is returned when feed is already gone
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This feed has already been deleted."})))
;; test clojure delete request
(let [prev-body (first
(read-json
(:body
(request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Weblog"
:language "en"
:subtitle "Weblog..."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "standard"})
main-routes))))
{:keys [body status] :as delete-request-clj}
(update-in (request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:action (first body))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete))))))
(testing "test invalid api requests"
(are [uri]
(= (request :post
uri
"[}"
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})
"/_api/clj/_feed/nl/invalid-image"
"/_api/json/_feed/nl/invalid-image"
"/_api/clj/_document/blog/invalid-test"
"/_api/json/_document/blog/invalid-test"))))
(deftest test-read-body
(is (= (read-body "json" (java.io.StringReader. ""))
(read-body "clj" (java.io.StringReader. ""))
nil))
(is (= (read-body "json" (java.io.StringReader. "{\"foo\":\"bar\"}"))
{:foo "bar"}))
(is (= (read-body "clj" (java.io.StringReader. "{:foo :bar}"))
{:foo :bar}))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "json" (java.io.StringReader. "{]"))))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "clj" (java.io.StringReader. "{]")))))
(deftest ^{:integration true} test-routes-authorization
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false})
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{feed-name}/{document-title}"
:default-document-type "with-description"
:language "en"}))
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(testing "Test if authorization is enforced correctly."
(is (= (:status (unauthorized-request :get "/admin/" main-routes))
;; test json requests
(:status (unauthorized-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
;; test clojure requests
(:status (unauthorized-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
302)))))
(deftest ^{:integration true} test-routes-authentication
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false}))
(testing "Test if authentication is enforced correctly."
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(is (= (:status (unauthenticated-request :get "/admin" main-routes))
;; test json requests
(:status (unauthenticated-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/json/_document/blog/test"
main-routes))
;; test clojure requests
(:status (unauthenticated-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
302)))))
(deftest test-logout
(is (= (logout {:username "johndoe" :permissions {:* [:DELETE]}})
{:session {}
:status 302
:headers {"Location" "/"}})
"should empty the session and redirect to /"))
(deftest test-login
(do
(auth/add-user +test-db+
"fmw"
"oops"
{:* ["GET" "POST" "PUT" "DELETE"]}))
(with-redefs [config/database +test-db+]
(is (= (form-request :post "/login" main-routes {"username" "fmw"
"password" "foo"})
{:status 302
:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"
"Location" "/login"}
:body ""}))
(let [r (form-request :post "/login" main-routes {"username" "fmw"
"password" "oops"})]
(is (= ((:headers r) "Location") "/admin/"))
(is (= (:status r) 302)))))
(deftest test-wrap-caching-headers
(testing "test if regular pages are pre-expired"
(is (= ((wrap-caching-headers identity) {})
{:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}})))
(with-redefs [time-core/now
(fn []
(time-core/date-time 2012 4 22 16 04 57 525))]
(testing "test if files are expired correclty"
(are [content-type]
(= ((wrap-caching-headers identity)
{:headers {"Content-Type" content-type}})
{:headers {"Expires" "Wed, 22 Apr 2015 16:04:57 +0000"
"Cache-Control" "public"
"Content-Type" content-type}})
"image/png"
"image/jpeg"
"image/gif"
"text/css"
"text/javascript"))))
(deftest test-redirect-301
(is (= (redirect-301 "/foo")
{:status 301
:body "Moved Permanently"
:headers {"Location" "/foo"}})))
(deftest test-redirection-handler
(with-redefs [config/default-host "localhost"
config/base-uri "http://localhost:3000"
config/cdn-hostname "http://localhost:3000/"]
(is (= ((redirection-handler identity) {:server-name "localhost"})
{:server-name "localhost"}))
(testing "test if visitors are redirected to the default-host"
(with-redefs [config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "vixu.com"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com"}}))))
(testing "test if administrators are redirected to https://"
(with-redefs [config/server-name "www.vixu.com"
config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :http})
{:status 301
:body "Moved Permanently"
:headers {"Location" "https://www.vixu.com/admin/"}}))
;; don't redirect if the scheme is already https
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :https})
{:server-name "www.vixu.com" :uri "/admin/" :scheme :https}))))
(testing "on localhost, /admin shouldn't redirect to https://"
(with-redefs [config/default-host "localhost"]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/admin/"
:scheme :http})
{:server-name "localhost" :uri "/admin/" :scheme :http}))))
(testing "test if custom redirects are correctly executed"
(with-redefs [config/redirects {"/foo" "/bar"
"/vixu" "http://www.vixu.com/"}]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/foo"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "/bar"}}))
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/vixu"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com/"}}))
;; do nothing unless the uri is a listed redirect
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/test"})
{:server-name "localhost" :uri "/test"}))))))
(deftest test-handle-exceptions
(is (= ((handle-exceptions identity) :works) :works))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/insufficient-privileges-error)))
:should-not-work)
{:status 302
:headers {"Location" "/permission-denied"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/authentication-required-error)))
:should-not-work)
{:status 302
:headers {"Location" "/login"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ invalid-request-body-error)))
:should-not-work)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})))
(defn test-ns-hook []
(database-fixture test-reset-search-allowed-feeds!)
(database-fixture test-reset-available-languages!)
(test-reset-index-reader!)
(test-data-response)
(test-response)
(test-page-not-found-response)
(database-fixture test-image-response)
(database-fixture test-get-segment-and-get-segments)
(database-fixture test-get-frontpage-for-language!)
(database-fixture test-get-cached-frontpage!)
(database-fixture test-get-cached-page!)
(test-reset-frontpage-cache!)
(test-reset-page-cache!)
(database-fixture test-feed-request)
(database-fixture test-document-request)
(database-fixture test-routes)
(test-read-body)
(database-fixture test-routes-authorization)
(database-fixture test-routes-authentication)
(test-logout)
(database-fixture test-login)
(test-wrap-caching-headers)
(test-redirect-301)
(test-redirection-handler)
(test-handle-exceptions))
|
11926
|
;; test/vix/test/routes.clj tests for routes namespace.
;; Copyright 2011-2012, Vixu.com, <NAME>. (<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 vix.test.routes
(:use [clojure.test]
[ring.middleware params
keyword-params
nested-params
multipart-params
cookies
flash]
[slingshot.slingshot :only [throw+]]
[slingshot.test]
[vix.routes] :reload
[clojure.data.json :only [json-str read-json]]
[vix.test.db :only [database-fixture +test-db+]]
[vix.test.test])
(:require [clj-time.format :as time-format]
[clj-time.core :as time-core]
[net.cgrand.enlive-html :as html]
[com.ashafa.clutch :as clutch]
[vix.db :as db]
[vix.auth :as auth]
[vix.config :as config]
[vix.util :as util]
[vix.lucene :as lucene])
(:import [org.apache.commons.codec.binary Base64]))
(def last-modified-pattern
#"[A-Z]{1}[a-z]{2}, \d{1,2} [A-Z]{1}[a-z]{2} \d{4} \d{2}:\d{2}:\d{2} \+0000")
(def mock-app
"Mock app without session middleware, so session is preserved."
(-> main-routes
wrap-keyword-params
wrap-nested-params
wrap-params
(wrap-multipart-params)
(wrap-flash)
(redirection-handler)
(wrap-caching-headers)
(handle-exceptions)))
(defn request-map [method resource body params]
{:request-method method
:uri resource
:body (when body (java.io.StringReader. body))
:params params
:server-name "localhost"})
; FIXME: refactor these four request functions to get rid of duplication
(defn request
([method resource my-routes]
(request method resource "" my-routes {}))
([method resource body my-routes]
(request method resource body my-routes {}))
([method resource body my-routes params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "someone"
:permissions {:* ["GET" "POST" "PUT" "DELETE"]}}))))
(defn unauthorized-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "nemo"
:permissions {:blog []}}))))
(defn unauthenticated-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (request-map method resource body params))))
(defn form-request [method resource my-routes form-params]
(app (dissoc (assoc (request-map method resource nil nil)
:form-params
form-params)
:body)))
(deftest test-reset-search-allowed-feeds!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(db/append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Vix Weblog!"
:name "images"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable false}))
(reset! search-allowed-feeds {})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["blog"]}))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["news" "blog"]})))
(deftest test-reset-available-languages!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true}))
(reset! available-languages {})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en"]))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"
:searchable true})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en" "nl"])))
(deftest test-reset-index-reader!
(let [ir @index-reader]
(do
(reset-index-reader!))
(is (not (= ir @index-reader))))
(do
(compare-and-set! index-reader @index-reader nil)
(is (= @index-reader nil))
(reset-index-reader!))
(is (= (class @index-reader)
org.apache.lucene.index.ReadOnlyDirectoryReader)))
(deftest test-data-response
(is (= (:status (data-response nil))
(:status (data-response nil :type :json))
(:status (data-response nil :type :clj)) 404))
(is (= (data-response {:foo "bar"} :type :json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"}))
(is (= (data-response {:foo "bar"})
(data-response {:foo "bar"} :type :clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "{:foo \"bar\"}"}))
(is (= (data-response {:foo "bar"} :status 201 :type :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"})))
(deftest test-response
(is (= (response "foo") {:status 200
:headers {"Content-Type"
"text/html; charset=UTF-8"}
:body "foo"}))
(is (= (:status (response nil) 404)))
(is (= (:status (response "foo" :status 201) 201)))
(is (= (get (:headers (response "foo" :content-type "image/png"))
"Content-Type")
"image/png")))
(deftest test-page-not-found-response
(is (= (page-not-found-response)
{:status 404
:headers {"Content-Type" "text/html; charset=UTF-8"}
:body "<h1>Page not found</h1>"})))
(deftest test-image-response
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false})
no-image-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:content ""
:draft false})
wp-response (image-response +test-db+ white-pixel-doc)]
(testing "test if a simple gif is returned correctly"
(is (= (get-in wp-response [:headers "Last-Modified"])
(time-format/unparse (time-format/formatters :rfc822)
(util/rfc3339-to-jodatime
(:published (first white-pixel-doc))
"UTC"))))
(is (re-matches last-modified-pattern
(get-in wp-response [:headers "Last-Modified"])))
(is (= (:status wp-response) 200))
(is (= (dissoc (:headers wp-response) "Last-Modified")
{"ETag" (:_rev (first white-pixel-doc))
"Content-Type" "image/gif"}))
(is (= (class (:body wp-response))
clj_http.core.proxy$java.io.FilterInputStream$0)))
(testing "test if a non-image document is handled correctly"
(is (= (image-response +test-db+ no-image-doc)
(page-not-found-response))))))
(deftest test-get-segment-and-get-segments
(let [slug-fn
(fn [language]
(str "/" language "/menu/menu"))
menu-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "menu"
:title "menu"
:slug "/en/menu/menu"
:content (str "<ul><li><a href=\""
"/\">home</a></li></ul>")
:draft false})
grote-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"grote-zaal"
:title
"<NAME>"
:slug
"/en/grote-zaal/stanko-middelburg"
:content
(str "The legendary Polish "
"trumpet player Stańko "
"will be playing in "
"Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
kleine-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kleine-zaal"
:title
"The Impossible Gentlemen"
:slug
(str "/en/kleine-zaal/"
"impossible-gentlemen")
:content
(str "<NAME>, "
"<NAME>, "
"<NAME>, "
"<NAME> "
"will be playing "
"at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
kabinet-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"<NAME>"
:slug
"/en/kabinet/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"<NAME> will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})
kabinet-doc-2 ;; dummy doc that should not be retrieved
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"<NAME>"
:slug
"/en/kabinet/yuri-honing-tilburg-dummy"
:content
(str "VPRO/Boy Edgar prize winner "
"<NAME> at "
"the Paradox venue in Tilburg.")
:start-time
"2012-02-01 20:30"
:end-time
"2012-02-01 23:59"
:draft false})
news-1
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"hey!"
:slug
"/en/news/hey"
:content
""
:draft false})
news-2
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"you!"
:slug
"/en/news/you"
:content
""
:draft false})
frontpage-segments
{:menu
{:type :document
:nodes :#menu
:slug slug-fn}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}}]
(testing "test (get-segment ...)"
(is (= (:content (:data (get-segment (:menu frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")))
"<ul><li><a href=\"/\">home</a></li></ul>"))
(is (= (get-segment (:primary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:primary-exposition frontpage-segments)
:data
(first grote-zaal-doc))))
(is (= (get-segment (:secondary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:secondary-exposition frontpage-segments)
:data
(first kleine-zaal-doc))))
(is (= (get-segment (:tertiary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:tertiary-exposition frontpage-segments)
:data
(first kabinet-doc))))
(is (= (get-segment (:news frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:news frontpage-segments)
:data
{:next nil
:documents [(first news-2) (first news-1)]})))
(is (= (get-segment {:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}
+test-db+
"en"
"Europe/Amsterdam")
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")})))
(testing "test (get-segments...)"
(is (= (get-segments frontpage-segments
+test-db+
"en"
"Europe/Amsterdam")
{:menu
{:type :document
:nodes :#menu
:slug slug-fn
:data (first menu-doc)}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1
:data (first grote-zaal-doc)}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1
:data (first kleine-zaal-doc)}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1
:data (first kabinet-doc)}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2
:data {:next nil
:documents [(first news-2) (first news-1)]}}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}})))))
(deftest test-get-frontpage-for-language!
;; this is tested in the tests for the view
;; if it returns a string the view is executed successfully
(is (string? (first (get-frontpage-for-language! +test-db+
"nl"
"Europe/Amsterdam")))))
(deftest test-get-cached-frontpage!
(is (= @frontpage-cache {}))
(let [empty-cache-fp (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")]
(is (= @frontpage-cache {"nl" empty-cache-fp}))
(do ; insert fake string to make sure pages are served from cache
(swap! frontpage-cache assoc "nl" "foo!"))
(is (= (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")
"foo!")))
(reset-frontpage-cache! "nl"))
(deftest test-reset-frontpage-cache!
(testing "test reset-frontpage-cache! on a single language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(is (= @frontpage-cache {"nl" "foo!"}))
(is (= (reset-frontpage-cache! "nl") {})))
(testing "test reset-frontpage-cache! on a multiple language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(swap! frontpage-cache assoc "en" "bar!")
(is (= @frontpage-cache {"nl" "foo!" "en" "bar!"}))
(is (= (reset-frontpage-cache! "nl") {"en" "bar!"}))))
(deftest test-reset-page-cache!
(is (= @page-cache {}))
(swap! page-cache assoc "/events/clojure-meetup.html" "hey!")
(is (not (= @page-cache {})))
(is (= (reset-page-cache!) {}))
(is (= @page-cache {})))
(deftest test-get-cached-page!
(is (= @page-cache {}))
(testing "make sure images skip the cache"
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/images/white-pixel.gif"
"Europe/Amsterdam"))
[:status :headers :body]))
;; the cache should still be empty:
(is (= @page-cache {}))))
(testing "test with a regular page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title "hic sunt dracones!"
:slug "/pages/hic-sunt-dracones.html"
:content "<h3>Here be dragons!</h3>"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/pages/hic-sunt-dracones.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/pages/hic-sunt-dracones.html" "hi!")
(is (= (get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam")
"hi!")))
;; TODO: make this test actually meaningful
(testing "test with event page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "calendar"
:title "Clojure Meetup!"
:slug "/events/clojure-meetup.html"
:content "<h3>Here be dragons!</h3>"
:start-time "2012-05-16 18:45"
:start-time-rfc3339 "2012-05-16T18:45:00.000Z"
:end-time "2012-05-16 23:00"
:end-time-rfc3339 "2012-05-16T23:00:00.000Z"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/events/clojure-meetup.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/events/clojure-meetup.html" "hello!")
(is (= (get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam")
"hello!")))
;; clean up
(reset-page-cache!)
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
404))
(is (= (:body (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
"<h1>Page not found</h1>"))
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
200))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/pixel.gif"
:content ""
:draft false})
image-response (get-cached-page! +test-db+
"/pixel.gif"
"Europe/Amsterdam")]
(is (= (get (:headers image-response) "Content-Type") "image/gif"))
(is (= (class (:body image-response))
clj_http.core.proxy$java.io.FilterInputStream$0))))
;; clean up
(reset-page-cache!))
(defn- remove-ids
"Removes internal database identifiers from the provided state map."
[{:keys [action] :as state}]
(assoc (dissoc state :_rev :_id :previous-id)
:action (keyword action)))
(defn- clean-body
"Returns a new version of the response map, with database internals
(i.e. :_id, :_rev and :previous-id) removed from the state sequence
in the response body. The body is read through read-json if :json
is passed as the value of the type argument and otherwise through
read-string. If the response type is json, the :action value is
turned into a keyword. If the response status is 400, the original
response is returned."
[type response]
(if (= (:status response) 400)
response
(update-in response
[:body]
(fn [body]
(map remove-ids
(if (= type :json)
(read-json body)
(read-string body)))))))
(deftest test-feed-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [blog-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "standard"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}")
:language "en"
:language-full "English"
:name "blog"
:searchable true
:subtitle ""
:title "Weblog"
:type "feed"}
image-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "image"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}.{ext}")
:language "en"
:language-full "English"
:name "images"
:searchable false
:subtitle ""
:title "Images"
:type "feed"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :POST :json blog-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :POST :clj image-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [image-feed]})))
(testing "test if feeds are updated correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+
:PUT
:json
(assoc blog-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"blog")))
:title "foo")
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+
:PUT
:clj
(assoc image-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"images")))
:title "foo")
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are loaded correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :GET :json nil "en" "blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :GET :clj nil "en" "images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are deleted correctly."
;; test json request
(let [current-blog-feed (db/get-feed +test-db+ "en" "blog")]
(is (= (clean-body
:json
(feed-request +test-db+
:DELETE
:json
(assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first current-blog-feed)))
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first
current-blog-feed)))
current-blog-feed))})))
;; test clojure request
(let [current-images-feed (db/get-feed +test-db+ "en" "images")]
(is (= (clean-body
:clj
(feed-request +test-db+
:DELETE
:clj
(assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
current-images-feed))})))))))
(defn- clean-req
"Parses the response :body and removes :_id and :_rev from states.
Also turns each state :action value into a keyword if it concerns a
JSON request. Accepts a response argument, as well as a type
(i.e. :json or :clj)."
[response type]
(update-in response
[:body]
(fn [states]
(map (fn [state]
(if (= type :clj)
(dissoc state :_rev :_id :previous-id)
(update-in (dissoc state :_rev :_id :previous-id)
[:action] keyword)))
(if (= type :clj)
(read-string states)
(read-json states))))))
(deftest test-document-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [json-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}
clj-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd-clj"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-req (document-request :POST :json json-doc) :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [json-doc]}))
;; test clojure request
(is (= (clean-req (document-request :POST :clj clj-doc) :clj)
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [clj-doc]})))
(testing "test if documents are updated correctly."
;; test json request
(let [json-doc-fresh (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (clean-req
(document-request :PUT
:json
(assoc (first json-doc-fresh)
:action
:update
:previous-id
(:_id (first json-doc-fresh))
:title
"foo"))
:json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first json-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd"))])})))
;; test clojure request
(let [clj-doc-fresh (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (clean-req
(document-request :PUT
:clj
(assoc (first clj-doc-fresh)
:action
:update
:previous-id
(:_id (first clj-doc-fresh))
:title
"foo"))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first clj-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd-clj"))])}))))
(testing "test if feeds are loaded correctly."
;; test json request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (document-request :GET :json existing-doc)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (json-str existing-doc)})))
;; test clojure request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (document-request :GET :clj existing-doc)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (pr-str existing-doc)}))))
(testing "test if feeds are deleted correctly."
;; test json request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd"))]
(is (= (clean-req
(document-request :DELETE
:json
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :delete,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :update,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil,
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :create,
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))
;; test clojure request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd-clj"))]
(is (= (clean-req
(document-request :DELETE
:clj
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :delete
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :update
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :create
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))))))
(deftest ^{:integration true} test-routes
(with-redefs [util/now-rfc3339 #(str "2012-09-22T04:07:05.756Z")]
(do
(db/append-to-feed +test-db+
{:action :create
:title "Pages"
:subtitle "Test Pages"
:name "pages"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "standard"
:language "en"
:searchable true})
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(let [directory (lucene/create-directory :RAM)]
(with-redefs [search-allowed-feeds (atom {"en" ["pages"]})
config/search-results-per-page 10
config/database +test-db+
lucene/directory directory]
(with-redefs [util/now-rfc3339
(fn []
(time-format/unparse
(time-format/formatters :date-time)
(time-core/now)))]
(dotimes [n 21]
(lucene/add-documents-to-index!
lucene/directory
[(first
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content "bar"
:draft false}))])))
(with-redefs [index-reader (atom
(lucene/create-index-reader directory))]
(testing "test document pagination"
;; test json request
(let [first-five (read-json
(:body
(request :get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-json
(:body
(request
:get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5))))
;; test clojure request
(let [first-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5)))))
(testing "test search page and search pagination"
(let [first-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"})))))]
(is (= (html/text
(first
(html/select
first-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select first-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-0"
1 "/pages/doc-1"
2 "/pages/doc-2"
3 "/pages/doc-3"
4 "/pages/doc-4"
5 "/pages/doc-5"
6 "/pages/doc-6"
7 "/pages/doc-7"
8 "/pages/doc-8"
9 "/pages/doc-9")
(is (= (html/select first-page
[:a#previous-search-results-page])
[]))
(is (= (first
(html/attr-values
(first
(html/select first-page
[:a#next-search-results-page]))
:href))
"/en/search?q=bar&after-doc-id=9&after-score=0.47674")))
(let [second-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request
:get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "9"
:after-score "0.47674"})))))]
(is (= (html/text
(first
(html/select
second-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select second-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-17"
1 "/pages/doc-18"
2 "/pages/doc-10"
3 "/pages/doc-11"
4 "/pages/doc-12"
5 "/pages/doc-13"
6 "/pages/doc-14"
7 "/pages/doc-15"
8 "/pages/doc-16"
9 "/pages/doc-19")
(is (= (html/attr-values
(first
(html/select second-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar"}))
(is (= (first
(html/attr-values
(first
(html/select second-page
[:a#next-search-results-page]))
:href))
(str "/en/search?q=bar&after-doc-id=19"
"&after-score=0.47674"
"&pp-aid[]=9&pp-as[]=0.47674"))))
(let [third-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "19"
:after-score "0.47674"
:pp-aid ["9"]
:pp-as ["0.47674"]})))))]
(is (= (html/text
(first
(html/select
third-page
[:span#search-stats])))
"21 results for query"))
(is (= (first
(html/attr-values
(first (html/select third-page
[[:ol#search-results]
[:li]
[:a]]))
:href))
"/pages/doc-20"))
(is
(= (html/attr-values
(first
(html/select third-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar&after-doc-id=9&after-score=0.47674"}))
(is (= (html/select third-page [:a#next-search-results-page])
[]))))
(is (= (:status (request :get "/" main-routes)) 200))
(is (= (:status (request :get "/login" main-routes)) 200))
(is (= (:status (request :get "/logout" main-routes)) 302))
(is (= (:status (request :get "/admin" main-routes)) 200))
(is (= (:status (request :get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (request :get
"/_api/clj/en/blog/_list-documents"
main-routes))
200))
;; test json request
(is (= (:status (request
:post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test clojure request
(is (= (:status (request
:post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test json POST request with HTTP method/action mismatch
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :delete
:title "test-create"
:slug "/blog/test-unique"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate clojure request with HTTP method/action mismatch
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :delete
:title "test-create"
:slug "/blog/test-unique-snowflake"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate json POST request
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test duplicate clojure POST request
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test json POST request with missing keys
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
;; test clojure POST request with missing keys
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
(testing "test if the document is added to the database"
;; test for json request
(let [document (db/get-document +test-db+ "/blog/test")]
(is (= (:title document)) "test-create"))
;; test for clojure request
(let [document (db/get-document +test-db+ "/blog/test-clj")]
(is (= (:title document)) "test-create")))
(testing "test if the document is added to the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 21) "title")
(.get (lucene/get-doc reader 22) "title")
"test-create"))))
(is (= (:status (request :get
"/_api/json/_document/blog/bar"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/bar"
main-routes))
200))
(is (= (:status (request :get
"/_api/json/_document/blog/t3"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/t3"
main-routes))
404))
(testing "test if documents are updated correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :put
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
(is (= (request
:put
"/_api/json/_document/blog/doesnt-exist"
(json-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request
:put
"/_api/clj/_document/blog/test-clj"
(pr-str (assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
(is (= (request
:put
"/_api/clj/_document/blog/doesnt-exist"
(pr-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")}))))
(testing "test if documents are also updated in the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 22) "title") "hi!"))))
(testing "test if document is deleted from the database correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/bar")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/test-clj")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."}))))
(testing "test if document is also deleted from the lucene index."
(let [reader (lucene/create-index-reader directory)
analyzer (lucene/create-analyzer)
filter (lucene/create-filter {:slug "/blog/bar"})
result (lucene/search "hi" filter 15 reader analyzer)
docs (lucene/get-docs reader (:docs result))]
(is (= (:total-hits result) 0)))))
(is (= (:status (request :get "/static/none" main-routes)) 404))
(is (= (:body (request :get "/static/none" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/bar" main-routes)) 404))
(is (= (:body (request :get "/blog/bar" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/test" main-routes)) 200))
(let [post-feed-request (request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Vix Weblog"
:language "en"
:subtitle "Vix Weblog..."
:default-slug-format
"/{document-title}"
:default-document-type "standard"
:searchable true})
main-routes)]
(is (= (:status post-feed-request) 201))
(is (= @search-allowed-feeds
(db/get-searchable-feeds (db/list-feeds +test-db+))
{"en" ["pages" "blog"]})
"Test if search-allowed-feeds is updated when feed is added")
(let [image-feed (map #(update-in % [:action] keyword)
(read-json
(:body
(request
:post
"/_api/json/_feed/en/image"
(json-str
{:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes))))
all-feeds (map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
main-routes))))
image-feed-nl (read-string
(:body
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)))]
(is (= (count all-feeds) 3))
;; test HTTP method/action mismatch
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :delete
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :delete
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; make sure it isn't possible to recreate existing feeds
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The provided feed already exists."}))
(testing "test language argument for /_api/x/_list-feeds"
(is (= (sort-by :name all-feeds)
(sort-by :name
(map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
nil
main-routes
{:language "en"})))))
(sort-by :name
(read-string
(:body
(request :get
"/_api/clj/_list-feeds"
nil
main-routes
{:language "en"}))))))
(is (= image-feed-nl
(read-string
(:body
(request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type "image"
:language "nl"}))))))
(is (= (count (read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
4))
(is (= (map #(update-in % [:action] keyword)
(read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
(read-string
(:body (request :get
"/_api/clj/_list-feeds"
main-routes)))))
(is (= (flatten [image-feed-nl image-feed])
(map #(update-in % [:action] keyword)
(read-json
(:body (request
:get
"/_api/json/_list-feeds"
nil
main-routes
{:default-document-type
"image"}))))
(read-string
(:body (request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type
"image"})))))))
(let [{:keys [status body] :as get-feed-json}
(update-in (request :get
"/_api/json/_feed/en/blog"
main-routes)
[:body]
read-json)
get-feed-clj
(update-in (request :get
"/_api/clj/_feed/en/blog"
main-routes)
[:body]
read-string)]
(is (= (update-in (dissoc get-feed-json :headers)
[:body]
(fn [states]
(map #(update-in % [:action] keyword) states)))
(dissoc get-feed-clj :headers)))
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix Weblog"))
;; make sure that update requests aren't allowed without
;; :previous-id
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the "
"most recent :previous-id.")})))
;; test json put request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-json}
(update-in (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Vix!"
:searchable false))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix!"))
(is (= @search-allowed-feeds {"nl" [] "en" ["pages"]})
"Make sure search-allowed-feeds is updated when feeds are")))
;; test clojure put request
(let [prev-body (first
(read-string
(:body
(request :get
"/_api/clj/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-clj}
(update-in (request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Fix!"
:searchable false))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Fix!")))
(testing "test delete requests"
;; make sure delete requests aren't allowed without :previous-id
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the most recent "
":previous-id.")}))
;; test json delete request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as delete-request-json}
(update-in (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (keyword (:action (first body)))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete)))
;; make sure the right error is returned when feed is already gone
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This feed has already been deleted."})))
;; test clojure delete request
(let [prev-body (first
(read-json
(:body
(request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Weblog"
:language "en"
:subtitle "Weblog..."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "standard"})
main-routes))))
{:keys [body status] :as delete-request-clj}
(update-in (request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:action (first body))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete))))))
(testing "test invalid api requests"
(are [uri]
(= (request :post
uri
"[}"
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})
"/_api/clj/_feed/nl/invalid-image"
"/_api/json/_feed/nl/invalid-image"
"/_api/clj/_document/blog/invalid-test"
"/_api/json/_document/blog/invalid-test"))))
(deftest test-read-body
(is (= (read-body "json" (java.io.StringReader. ""))
(read-body "clj" (java.io.StringReader. ""))
nil))
(is (= (read-body "json" (java.io.StringReader. "{\"foo\":\"bar\"}"))
{:foo "bar"}))
(is (= (read-body "clj" (java.io.StringReader. "{:foo :bar}"))
{:foo :bar}))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "json" (java.io.StringReader. "{]"))))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "clj" (java.io.StringReader. "{]")))))
(deftest ^{:integration true} test-routes-authorization
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false})
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{feed-name}/{document-title}"
:default-document-type "with-description"
:language "en"}))
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(testing "Test if authorization is enforced correctly."
(is (= (:status (unauthorized-request :get "/admin/" main-routes))
;; test json requests
(:status (unauthorized-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
;; test clojure requests
(:status (unauthorized-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
302)))))
(deftest ^{:integration true} test-routes-authentication
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false}))
(testing "Test if authentication is enforced correctly."
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(is (= (:status (unauthenticated-request :get "/admin" main-routes))
;; test json requests
(:status (unauthenticated-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/json/_document/blog/test"
main-routes))
;; test clojure requests
(:status (unauthenticated-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
302)))))
(deftest test-logout
(is (= (logout {:username "johndoe" :permissions {:* [:DELETE]}})
{:session {}
:status 302
:headers {"Location" "/"}})
"should empty the session and redirect to /"))
(deftest test-login
(do
(auth/add-user +test-db+
"fmw"
"oops"
{:* ["GET" "POST" "PUT" "DELETE"]}))
(with-redefs [config/database +test-db+]
(is (= (form-request :post "/login" main-routes {"username" "fmw"
"password" "<PASSWORD>"})
{:status 302
:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"
"Location" "/login"}
:body ""}))
(let [r (form-request :post "/login" main-routes {"username" "fmw"
"password" "<PASSWORD>"})]
(is (= ((:headers r) "Location") "/admin/"))
(is (= (:status r) 302)))))
(deftest test-wrap-caching-headers
(testing "test if regular pages are pre-expired"
(is (= ((wrap-caching-headers identity) {})
{:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}})))
(with-redefs [time-core/now
(fn []
(time-core/date-time 2012 4 22 16 04 57 525))]
(testing "test if files are expired correclty"
(are [content-type]
(= ((wrap-caching-headers identity)
{:headers {"Content-Type" content-type}})
{:headers {"Expires" "Wed, 22 Apr 2015 16:04:57 +0000"
"Cache-Control" "public"
"Content-Type" content-type}})
"image/png"
"image/jpeg"
"image/gif"
"text/css"
"text/javascript"))))
(deftest test-redirect-301
(is (= (redirect-301 "/foo")
{:status 301
:body "Moved Permanently"
:headers {"Location" "/foo"}})))
(deftest test-redirection-handler
(with-redefs [config/default-host "localhost"
config/base-uri "http://localhost:3000"
config/cdn-hostname "http://localhost:3000/"]
(is (= ((redirection-handler identity) {:server-name "localhost"})
{:server-name "localhost"}))
(testing "test if visitors are redirected to the default-host"
(with-redefs [config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "vixu.com"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com"}}))))
(testing "test if administrators are redirected to https://"
(with-redefs [config/server-name "www.vixu.com"
config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :http})
{:status 301
:body "Moved Permanently"
:headers {"Location" "https://www.vixu.com/admin/"}}))
;; don't redirect if the scheme is already https
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :https})
{:server-name "www.vixu.com" :uri "/admin/" :scheme :https}))))
(testing "on localhost, /admin shouldn't redirect to https://"
(with-redefs [config/default-host "localhost"]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/admin/"
:scheme :http})
{:server-name "localhost" :uri "/admin/" :scheme :http}))))
(testing "test if custom redirects are correctly executed"
(with-redefs [config/redirects {"/foo" "/bar"
"/vixu" "http://www.vixu.com/"}]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/foo"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "/bar"}}))
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/vixu"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com/"}}))
;; do nothing unless the uri is a listed redirect
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/test"})
{:server-name "localhost" :uri "/test"}))))))
(deftest test-handle-exceptions
(is (= ((handle-exceptions identity) :works) :works))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/insufficient-privileges-error)))
:should-not-work)
{:status 302
:headers {"Location" "/permission-denied"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/authentication-required-error)))
:should-not-work)
{:status 302
:headers {"Location" "/login"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ invalid-request-body-error)))
:should-not-work)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})))
(defn test-ns-hook []
(database-fixture test-reset-search-allowed-feeds!)
(database-fixture test-reset-available-languages!)
(test-reset-index-reader!)
(test-data-response)
(test-response)
(test-page-not-found-response)
(database-fixture test-image-response)
(database-fixture test-get-segment-and-get-segments)
(database-fixture test-get-frontpage-for-language!)
(database-fixture test-get-cached-frontpage!)
(database-fixture test-get-cached-page!)
(test-reset-frontpage-cache!)
(test-reset-page-cache!)
(database-fixture test-feed-request)
(database-fixture test-document-request)
(database-fixture test-routes)
(test-read-body)
(database-fixture test-routes-authorization)
(database-fixture test-routes-authentication)
(test-logout)
(database-fixture test-login)
(test-wrap-caching-headers)
(test-redirect-301)
(test-redirection-handler)
(test-handle-exceptions))
| true |
;; test/vix/test/routes.clj tests for routes namespace.
;; Copyright 2011-2012, Vixu.com, PI:NAME:<NAME>END_PI. (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 vix.test.routes
(:use [clojure.test]
[ring.middleware params
keyword-params
nested-params
multipart-params
cookies
flash]
[slingshot.slingshot :only [throw+]]
[slingshot.test]
[vix.routes] :reload
[clojure.data.json :only [json-str read-json]]
[vix.test.db :only [database-fixture +test-db+]]
[vix.test.test])
(:require [clj-time.format :as time-format]
[clj-time.core :as time-core]
[net.cgrand.enlive-html :as html]
[com.ashafa.clutch :as clutch]
[vix.db :as db]
[vix.auth :as auth]
[vix.config :as config]
[vix.util :as util]
[vix.lucene :as lucene])
(:import [org.apache.commons.codec.binary Base64]))
(def last-modified-pattern
#"[A-Z]{1}[a-z]{2}, \d{1,2} [A-Z]{1}[a-z]{2} \d{4} \d{2}:\d{2}:\d{2} \+0000")
(def mock-app
"Mock app without session middleware, so session is preserved."
(-> main-routes
wrap-keyword-params
wrap-nested-params
wrap-params
(wrap-multipart-params)
(wrap-flash)
(redirection-handler)
(wrap-caching-headers)
(handle-exceptions)))
(defn request-map [method resource body params]
{:request-method method
:uri resource
:body (when body (java.io.StringReader. body))
:params params
:server-name "localhost"})
; FIXME: refactor these four request functions to get rid of duplication
(defn request
([method resource my-routes]
(request method resource "" my-routes {}))
([method resource body my-routes]
(request method resource body my-routes {}))
([method resource body my-routes params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "someone"
:permissions {:* ["GET" "POST" "PUT" "DELETE"]}}))))
(defn unauthorized-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (assoc (request-map method resource body params)
:session
{:username "nemo"
:permissions {:blog []}}))))
(defn unauthenticated-request
([method resource my-routes]
(unauthorized-request method resource "" my-routes))
([method resource body my-routes & params]
(mock-app (request-map method resource body params))))
(defn form-request [method resource my-routes form-params]
(app (dissoc (assoc (request-map method resource nil nil)
:form-params
form-params)
:body)))
(deftest test-reset-search-allowed-feeds!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(db/append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Vix Weblog!"
:name "images"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable false}))
(reset! search-allowed-feeds {})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["blog"]}))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true})
(reset-search-allowed-feeds! +test-db+)
(is (= @search-allowed-feeds {"en" ["news" "blog"]})))
(deftest test-reset-available-languages!
(do
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"
:searchable true}))
(reset! available-languages {})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en"]))
(db/append-to-feed +test-db+
{:action :create
:title "News"
:subtitle "Vix News!"
:name "news"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"
:searchable true})
(reset-available-languages! +test-db+)
(is (= @available-languages ["en" "nl"])))
(deftest test-reset-index-reader!
(let [ir @index-reader]
(do
(reset-index-reader!))
(is (not (= ir @index-reader))))
(do
(compare-and-set! index-reader @index-reader nil)
(is (= @index-reader nil))
(reset-index-reader!))
(is (= (class @index-reader)
org.apache.lucene.index.ReadOnlyDirectoryReader)))
(deftest test-data-response
(is (= (:status (data-response nil))
(:status (data-response nil :type :json))
(:status (data-response nil :type :clj)) 404))
(is (= (data-response {:foo "bar"} :type :json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"}))
(is (= (data-response {:foo "bar"})
(data-response {:foo "bar"} :type :clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "{:foo \"bar\"}"}))
(is (= (data-response {:foo "bar"} :status 201 :type :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body "{\"foo\":\"bar\"}"})))
(deftest test-response
(is (= (response "foo") {:status 200
:headers {"Content-Type"
"text/html; charset=UTF-8"}
:body "foo"}))
(is (= (:status (response nil) 404)))
(is (= (:status (response "foo" :status 201) 201)))
(is (= (get (:headers (response "foo" :content-type "image/png"))
"Content-Type")
"image/png")))
(deftest test-page-not-found-response
(is (= (page-not-found-response)
{:status 404
:headers {"Content-Type" "text/html; charset=UTF-8"}
:body "<h1>Page not found</h1>"})))
(deftest test-image-response
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false})
no-image-doc (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:content ""
:draft false})
wp-response (image-response +test-db+ white-pixel-doc)]
(testing "test if a simple gif is returned correctly"
(is (= (get-in wp-response [:headers "Last-Modified"])
(time-format/unparse (time-format/formatters :rfc822)
(util/rfc3339-to-jodatime
(:published (first white-pixel-doc))
"UTC"))))
(is (re-matches last-modified-pattern
(get-in wp-response [:headers "Last-Modified"])))
(is (= (:status wp-response) 200))
(is (= (dissoc (:headers wp-response) "Last-Modified")
{"ETag" (:_rev (first white-pixel-doc))
"Content-Type" "image/gif"}))
(is (= (class (:body wp-response))
clj_http.core.proxy$java.io.FilterInputStream$0)))
(testing "test if a non-image document is handled correctly"
(is (= (image-response +test-db+ no-image-doc)
(page-not-found-response))))))
(deftest test-get-segment-and-get-segments
(let [slug-fn
(fn [language]
(str "/" language "/menu/menu"))
menu-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "menu"
:title "menu"
:slug "/en/menu/menu"
:content (str "<ul><li><a href=\""
"/\">home</a></li></ul>")
:draft false})
grote-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"grote-zaal"
:title
"PI:NAME:<NAME>END_PI"
:slug
"/en/grote-zaal/stanko-middelburg"
:content
(str "The legendary Polish "
"trumpet player Stańko "
"will be playing in "
"Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
kleine-zaal-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kleine-zaal"
:title
"The Impossible Gentlemen"
:slug
(str "/en/kleine-zaal/"
"impossible-gentlemen")
:content
(str "PI:NAME:<NAME>END_PI, "
"PI:NAME:<NAME>END_PI, "
"PI:NAME:<NAME>END_PI, "
"PI:NAME:<NAME>END_PI "
"will be playing "
"at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
kabinet-doc
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"PI:NAME:<NAME>END_PI"
:slug
"/en/kabinet/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"PI:NAME:<NAME>END_PI will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})
kabinet-doc-2 ;; dummy doc that should not be retrieved
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"kabinet"
:title
"PI:NAME:<NAME>END_PI"
:slug
"/en/kabinet/yuri-honing-tilburg-dummy"
:content
(str "VPRO/Boy Edgar prize winner "
"PI:NAME:<NAME>END_PI at "
"the Paradox venue in Tilburg.")
:start-time
"2012-02-01 20:30"
:end-time
"2012-02-01 23:59"
:draft false})
news-1
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"hey!"
:slug
"/en/news/hey"
:content
""
:draft false})
news-2
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"news"
:title
"you!"
:slug
"/en/news/you"
:content
""
:draft false})
frontpage-segments
{:menu
{:type :document
:nodes :#menu
:slug slug-fn}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}}]
(testing "test (get-segment ...)"
(is (= (:content (:data (get-segment (:menu frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")))
"<ul><li><a href=\"/\">home</a></li></ul>"))
(is (= (get-segment (:primary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:primary-exposition frontpage-segments)
:data
(first grote-zaal-doc))))
(is (= (get-segment (:secondary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:secondary-exposition frontpage-segments)
:data
(first kleine-zaal-doc))))
(is (= (get-segment (:tertiary-exposition frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:tertiary-exposition frontpage-segments)
:data
(first kabinet-doc))))
(is (= (get-segment (:news frontpage-segments)
+test-db+
"en"
"Europe/Amsterdam")
(assoc (:news frontpage-segments)
:data
{:next nil
:documents [(first news-2) (first news-1)]})))
(is (= (get-segment {:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}
+test-db+
"en"
"Europe/Amsterdam")
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")})))
(testing "test (get-segments...)"
(is (= (get-segments frontpage-segments
+test-db+
"en"
"Europe/Amsterdam")
{:menu
{:type :document
:nodes :#menu
:slug slug-fn
:data (first menu-doc)}
:primary-exposition
{:type :most-recent-events
:nodes :div#primary-exposition-block
:feed "grote-zaal"
:limit 1
:data (first grote-zaal-doc)}
:secondary-exposition
{:type :most-recent-events
:nodes :div#secondary-exposition-block
:feed "kleine-zaal"
:limit 1
:data (first kleine-zaal-doc)}
:tertiary-exposition
{:type :most-recent-events
:nodes :div#tertiary-exposition-block
:feed "kabinet"
:limit 1
:data (first kabinet-doc)}
:news
{:type :feed
:nodes [:div#news-block-first :div#news-block-second]
:feed "news"
:limit 2
:data {:next nil
:documents [(first news-2) (first news-1)]}}
:background-image
{:type :string
:data (str "http://cdn0.baz.vixu.com/"
"/static/images/baz-content-bg.jpg")}})))))
(deftest test-get-frontpage-for-language!
;; this is tested in the tests for the view
;; if it returns a string the view is executed successfully
(is (string? (first (get-frontpage-for-language! +test-db+
"nl"
"Europe/Amsterdam")))))
(deftest test-get-cached-frontpage!
(is (= @frontpage-cache {}))
(let [empty-cache-fp (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")]
(is (= @frontpage-cache {"nl" empty-cache-fp}))
(do ; insert fake string to make sure pages are served from cache
(swap! frontpage-cache assoc "nl" "foo!"))
(is (= (get-cached-frontpage! +test-db+
"nl"
"Europe/Amsterdam")
"foo!")))
(reset-frontpage-cache! "nl"))
(deftest test-reset-frontpage-cache!
(testing "test reset-frontpage-cache! on a single language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(is (= @frontpage-cache {"nl" "foo!"}))
(is (= (reset-frontpage-cache! "nl") {})))
(testing "test reset-frontpage-cache! on a multiple language cache"
(swap! frontpage-cache assoc "nl" "foo!")
(swap! frontpage-cache assoc "en" "bar!")
(is (= @frontpage-cache {"nl" "foo!" "en" "bar!"}))
(is (= (reset-frontpage-cache! "nl") {"en" "bar!"}))))
(deftest test-reset-page-cache!
(is (= @page-cache {}))
(swap! page-cache assoc "/events/clojure-meetup.html" "hey!")
(is (not (= @page-cache {})))
(is (= (reset-page-cache!) {}))
(is (= @page-cache {})))
(deftest test-get-cached-page!
(is (= @page-cache {}))
(testing "make sure images skip the cache"
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:content ""
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/images/white-pixel.gif"
"Europe/Amsterdam"))
[:status :headers :body]))
;; the cache should still be empty:
(is (= @page-cache {}))))
(testing "test with a regular page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title "hic sunt dracones!"
:slug "/pages/hic-sunt-dracones.html"
:content "<h3>Here be dragons!</h3>"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/pages/hic-sunt-dracones.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/pages/hic-sunt-dracones.html" "hi!")
(is (= (get-cached-page! +test-db+
"/pages/hic-sunt-dracones.html"
"Europe/Amsterdam")
"hi!")))
;; TODO: make this test actually meaningful
(testing "test with event page"
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "calendar"
:title "Clojure Meetup!"
:slug "/events/clojure-meetup.html"
:content "<h3>Here be dragons!</h3>"
:start-time "2012-05-16 18:45"
:start-time-rfc3339 "2012-05-16T18:45:00.000Z"
:end-time "2012-05-16 23:00"
:end-time-rfc3339 "2012-05-16T23:00:00.000Z"
:draft false}))
(is (= (keys
(get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam"))
[:status :headers :body]))
(is (= (keys (get @page-cache "/events/clojure-meetup.html"))
[:status :headers :body]))
;; make sure the page is really served from the cache
(swap! page-cache assoc "/events/clojure-meetup.html" "hello!")
(is (= (get-cached-page! +test-db+
"/events/clojure-meetup.html"
"Europe/Amsterdam")
"hello!")))
;; clean up
(reset-page-cache!)
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
404))
(is (= (:body (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
"<h1>Page not found</h1>"))
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(is (= (:status (get-cached-page! +test-db+
"/blog/bar"
"Europe/Amsterdam"))
200))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (db/append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "images"
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/pixel.gif"
:content ""
:draft false})
image-response (get-cached-page! +test-db+
"/pixel.gif"
"Europe/Amsterdam")]
(is (= (get (:headers image-response) "Content-Type") "image/gif"))
(is (= (class (:body image-response))
clj_http.core.proxy$java.io.FilterInputStream$0))))
;; clean up
(reset-page-cache!))
(defn- remove-ids
"Removes internal database identifiers from the provided state map."
[{:keys [action] :as state}]
(assoc (dissoc state :_rev :_id :previous-id)
:action (keyword action)))
(defn- clean-body
"Returns a new version of the response map, with database internals
(i.e. :_id, :_rev and :previous-id) removed from the state sequence
in the response body. The body is read through read-json if :json
is passed as the value of the type argument and otherwise through
read-string. If the response type is json, the :action value is
turned into a keyword. If the response status is 400, the original
response is returned."
[type response]
(if (= (:status response) 400)
response
(update-in response
[:body]
(fn [body]
(map remove-ids
(if (= type :json)
(read-json body)
(read-string body)))))))
(deftest test-feed-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [blog-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "standard"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}")
:language "en"
:language-full "English"
:name "blog"
:searchable true
:subtitle ""
:title "Weblog"
:type "feed"}
image-feed {:action :create
:created "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:default-document-type "image"
:default-slug-format (str "/{language}/{feed-name}"
"/{document-title}.{ext}")
:language "en"
:language-full "English"
:name "images"
:searchable false
:subtitle ""
:title "Images"
:type "feed"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :POST :json blog-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :POST :clj image-feed "en" "blog"))
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [image-feed]})))
(testing "test if feeds are updated correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+
:PUT
:json
(assoc blog-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"blog")))
:title "foo")
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+
:PUT
:clj
(assoc image-feed
:action :update
:previous-id (:_id
(first
(db/get-feed +test-db+
"en"
"images")))
:title "foo")
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are loaded correctly."
;; test json request
(is (= (clean-body
:json
(feed-request +test-db+ :GET :json nil "en" "blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [(assoc blog-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
blog-feed]}))
;; test clojure request
(is (= (clean-body
:clj
(feed-request +test-db+ :GET :clj nil "en" "images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [(assoc image-feed
:action :update
:title "foo"
:datestamp "2012-07-19T15:09:16.253Z")
image-feed]})))
(testing "test if feeds are deleted correctly."
;; test json request
(let [current-blog-feed (db/get-feed +test-db+ "en" "blog")]
(is (= (clean-body
:json
(feed-request +test-db+
:DELETE
:json
(assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first current-blog-feed)))
"en"
"blog"))
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-blog-feed)
:action :delete
:previous-id (:_id
(first
current-blog-feed)))
current-blog-feed))})))
;; test clojure request
(let [current-images-feed (db/get-feed +test-db+ "en" "images")]
(is (= (clean-body
:clj
(feed-request +test-db+
:DELETE
:clj
(assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
"en"
"images"))
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map remove-ids
(cons (assoc (first current-images-feed)
:action :delete
:previous-id (:_id
(first
current-images-feed)))
current-images-feed))})))))))
(defn- clean-req
"Parses the response :body and removes :_id and :_rev from states.
Also turns each state :action value into a keyword if it concerns a
JSON request. Accepts a response argument, as well as a type
(i.e. :json or :clj)."
[response type]
(update-in response
[:body]
(fn [states]
(map (fn [state]
(if (= type :clj)
(dissoc state :_rev :_id :previous-id)
(update-in (dissoc state :_rev :_id :previous-id)
[:action] keyword)))
(if (= type :clj)
(read-string states)
(read-json states))))))
(deftest test-document-request
(with-redefs [util/now-rfc3339 #(str "2012-07-19T15:09:16.253Z")
config/database +test-db+]
(let [json-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}
clj-doc {:action :create
:content "Hic sunt dracones."
:description "A nice map."
:draft false
:start-time ""
:start-time-rfc3339 nil
:end-time ""
:end-time-rfc3339 nil
:feed "blog"
:icon ""
:language "en"
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:related-pages []
:related-images []
:slug "/en/blog/hsd-clj"
:subtitle "Here be dragons"
:title "Hello, world!"
:type "document"}]
(testing "test if feeds are created correctly."
;; test json request
(is (= (clean-req (document-request :POST :json json-doc) :json)
{:status 201
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body [json-doc]}))
;; test clojure request
(is (= (clean-req (document-request :POST :clj clj-doc) :clj)
{:status 201
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body [clj-doc]})))
(testing "test if documents are updated correctly."
;; test json request
(let [json-doc-fresh (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (clean-req
(document-request :PUT
:json
(assoc (first json-doc-fresh)
:action
:update
:previous-id
(:_id (first json-doc-fresh))
:title
"foo"))
:json)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first json-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd"))])})))
;; test clojure request
(let [clj-doc-fresh (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (clean-req
(document-request :PUT
:clj
(assoc (first clj-doc-fresh)
:action
:update
:previous-id
(:_id (first clj-doc-fresh))
:title
"foo"))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (map #(dissoc % :_rev :_id)
[(assoc (first clj-doc-fresh)
:action :update
:title "foo")
(second
(db/get-document +test-db+
"/en/blog/hsd-clj"))])}))))
(testing "test if feeds are loaded correctly."
;; test json request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd")]
(is (= (document-request :GET :json existing-doc)
{:status 200
:headers {"Content-Type" "application/json; charset=UTF-8"}
:body (json-str existing-doc)})))
;; test clojure request
(let [existing-doc (db/get-document +test-db+ "/en/blog/hsd-clj")]
(is (= (document-request :GET :clj existing-doc)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (pr-str existing-doc)}))))
(testing "test if feeds are deleted correctly."
;; test json request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd"))]
(is (= (clean-req
(document-request :DELETE
:json
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :delete,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :update,
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil,
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false,
:related-pages [],
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd"
:icon ""
:content "Hic sunt dracones."
:action :create,
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))
;; test clojure request
(let [existing-doc
(first (db/get-document +test-db+ "/en/blog/hsd-clj"))]
(is (= (clean-req
(document-request :DELETE
:clj
(assoc existing-doc
:action :delete
:previous-id (:_id existing-doc)))
:clj)
{:status 200
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
[{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :delete
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :update
:related-images []
:language "en"
:title "foo"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}
{:subtitle "Here be dragons"
:slug "/en/blog/hsd-clj"
:icon ""
:content "Hic sunt dracones."
:action :create
:related-images []
:language "en"
:title "Hello, world!"
:start-time-rfc3339 nil
:published "2012-07-19T15:09:16.253Z"
:datestamp "2012-07-19T15:09:16.253Z"
:created "2012-07-19T15:09:16.253Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description "A nice map."
:end-time-rfc3339 nil
:start-time ""
:end-time ""}]})))))))
(deftest ^{:integration true} test-routes
(with-redefs [util/now-rfc3339 #(str "2012-09-22T04:07:05.756Z")]
(do
(db/append-to-feed +test-db+
{:action :create
:title "Pages"
:subtitle "Test Pages"
:name "pages"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "standard"
:language "en"
:searchable true})
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/bar"
:content "bar"
:draft false}))
(let [directory (lucene/create-directory :RAM)]
(with-redefs [search-allowed-feeds (atom {"en" ["pages"]})
config/search-results-per-page 10
config/database +test-db+
lucene/directory directory]
(with-redefs [util/now-rfc3339
(fn []
(time-format/unparse
(time-format/formatters :date-time)
(time-core/now)))]
(dotimes [n 21]
(lucene/add-documents-to-index!
lucene/directory
[(first
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "pages"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content "bar"
:draft false}))])))
(with-redefs [index-reader (atom
(lucene/create-index-reader directory))]
(testing "test document pagination"
;; test json request
(let [first-five (read-json
(:body
(request :get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-json
(:body
(request
:get
"/_api/json/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5))))
;; test clojure request
(let [first-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"})))]
(is (= (count (:documents first-five)) 5))
(let [next-five (read-string
(:body
(request :get
"/_api/clj/en/pages/_list-documents"
nil
main-routes
{:limit "5"
:startkey-published
(:published
(:next first-five))})))]
(is (= (count (:documents next-five)) 5)))))
(testing "test search page and search pagination"
(let [first-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"})))))]
(is (= (html/text
(first
(html/select
first-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select first-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-0"
1 "/pages/doc-1"
2 "/pages/doc-2"
3 "/pages/doc-3"
4 "/pages/doc-4"
5 "/pages/doc-5"
6 "/pages/doc-6"
7 "/pages/doc-7"
8 "/pages/doc-8"
9 "/pages/doc-9")
(is (= (html/select first-page
[:a#previous-search-results-page])
[]))
(is (= (first
(html/attr-values
(first
(html/select first-page
[:a#next-search-results-page]))
:href))
"/en/search?q=bar&after-doc-id=9&after-score=0.47674")))
(let [second-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request
:get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "9"
:after-score "0.47674"})))))]
(is (= (html/text
(first
(html/select
second-page
[:span#search-stats])))
"21 results for query"))
(are [n expected-href]
(= (first
(html/attr-values
(nth (html/select second-page
[[:ol#search-results] [:li] [:a]])
n)
:href))
expected-href)
0 "/pages/doc-17"
1 "/pages/doc-18"
2 "/pages/doc-10"
3 "/pages/doc-11"
4 "/pages/doc-12"
5 "/pages/doc-13"
6 "/pages/doc-14"
7 "/pages/doc-15"
8 "/pages/doc-16"
9 "/pages/doc-19")
(is (= (html/attr-values
(first
(html/select second-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar"}))
(is (= (first
(html/attr-values
(first
(html/select second-page
[:a#next-search-results-page]))
:href))
(str "/en/search?q=bar&after-doc-id=19"
"&after-score=0.47674"
"&pp-aid[]=9&pp-as[]=0.47674"))))
(let [third-page (html/html-resource
(java.io.StringReader.
(apply str
(:body
(request :get
"/en/search"
""
main-routes
{:q "bar"
:after-doc-id "19"
:after-score "0.47674"
:pp-aid ["9"]
:pp-as ["0.47674"]})))))]
(is (= (html/text
(first
(html/select
third-page
[:span#search-stats])))
"21 results for query"))
(is (= (first
(html/attr-values
(first (html/select third-page
[[:ol#search-results]
[:li]
[:a]]))
:href))
"/pages/doc-20"))
(is
(= (html/attr-values
(first
(html/select third-page
[:a#previous-search-results-page]))
:href)
#{"/en/search?q=bar&after-doc-id=9&after-score=0.47674"}))
(is (= (html/select third-page [:a#next-search-results-page])
[]))))
(is (= (:status (request :get "/" main-routes)) 200))
(is (= (:status (request :get "/login" main-routes)) 200))
(is (= (:status (request :get "/logout" main-routes)) 302))
(is (= (:status (request :get "/admin" main-routes)) 200))
(is (= (:status (request :get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (request :get
"/_api/clj/en/blog/_list-documents"
main-routes))
200))
;; test json request
(is (= (:status (request
:post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test clojure request
(is (= (:status (request
:post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes))
201))
;; test json POST request with HTTP method/action mismatch
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :delete
:title "test-create"
:slug "/blog/test-unique"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate clojure request with HTTP method/action mismatch
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :delete
:title "test-create"
:slug "/blog/test-unique-snowflake"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; test duplicate json POST request
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test duplicate clojure POST request
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-clj"
:language "en"
:feed "blog"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
"There is an existing document with the provided slug."}))
;; test json POST request with missing keys
(is (= (request :post
"/_api/json/_document/blog/test"
(json-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
;; test clojure POST request with missing keys
(is (= (request :post
"/_api/clj/_document/blog/test-clj"
(pr-str {:action :create
:title "test-create"
:slug "/blog/test-missing-keys"
:language "en"
:content "hic sunt dracones"})
main-routes)
{:status 400
:headers
{"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "This document is missing required keys. "
"The keys :slug, :language, :feed, :title "
"are required.")}))
(testing "test if the document is added to the database"
;; test for json request
(let [document (db/get-document +test-db+ "/blog/test")]
(is (= (:title document)) "test-create"))
;; test for clojure request
(let [document (db/get-document +test-db+ "/blog/test-clj")]
(is (= (:title document)) "test-create")))
(testing "test if the document is added to the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 21) "title")
(.get (lucene/get-doc reader 22) "title")
"test-create"))))
(is (= (:status (request :get
"/_api/json/_document/blog/bar"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/bar"
main-routes))
200))
(is (= (:status (request :get
"/_api/json/_document/blog/t3"
main-routes))
(:status (request :get
"/_api/clj/_document/blog/t3"
main-routes))
404))
(testing "test if documents are updated correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :put
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
(is (= (request
:put
"/_api/json/_document/blog/doesnt-exist"
(json-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request
:put
"/_api/clj/_document/blog/test-clj"
(pr-str (assoc document
:action :update
:previous-id (:_id document)
:title "hi!"))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
(is (= (request
:put
"/_api/clj/_document/blog/doesnt-exist"
(pr-str (assoc document
:action :update
:title "hi!"))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This document map doesn't contain "
"the most recent :previous-id.")}))))
(testing "test if documents are also updated in the lucene index"
(let [reader (lucene/create-index-reader directory)]
(is (= (.get (lucene/get-doc reader 22) "title") "hi!"))))
(testing "test if document is deleted from the database correctly"
;; test json request
(let [document (first (db/get-document +test-db+ "/blog/bar"))]
(is (= (clean-req (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:json)
{:status 200
:headers
{"Content-Type" "application/json; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"
:draft false}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/json/_document/blog/bar"
(json-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/bar")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."})))
;; test clojure request
(let [document
(first (db/get-document +test-db+ "/blog/test-clj"))]
(is (= (clean-req (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action :delete
:previous-id (:_id document)))
main-routes)
:clj)
{:status 200
:headers
{"Content-Type" "text/plain; charset=UTF-8"
"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}
:body
[{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :delete
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :update
:language "en"
:title "hi!"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}
{:slug "/blog/test-clj"
:content "hic sunt dracones"
:action :create
:language "en"
:title "test-create"
:published "2012-09-22T04:07:05.756Z"
:datestamp "2012-09-22T04:07:05.756Z"
:created "2012-09-22T04:07:05.756Z"
:type "document"
:feed "blog"}]}))
;; test error message for double deletion
(is (= (request :delete
"/_api/clj/_document/blog/test-clj"
(pr-str
(assoc document
:action
:delete
:previous-id
(:_id
(first
(db/get-document +test-db+
"/blog/test-clj")))))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This document has already been deleted."}))))
(testing "test if document is also deleted from the lucene index."
(let [reader (lucene/create-index-reader directory)
analyzer (lucene/create-analyzer)
filter (lucene/create-filter {:slug "/blog/bar"})
result (lucene/search "hi" filter 15 reader analyzer)
docs (lucene/get-docs reader (:docs result))]
(is (= (:total-hits result) 0)))))
(is (= (:status (request :get "/static/none" main-routes)) 404))
(is (= (:body (request :get "/static/none" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/bar" main-routes)) 404))
(is (= (:body (request :get "/blog/bar" main-routes))
"<h1>Page not found</h1>"))
(is (= (:status (request :get "/blog/test" main-routes)) 200))
(let [post-feed-request (request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Vix Weblog"
:language "en"
:subtitle "Vix Weblog..."
:default-slug-format
"/{document-title}"
:default-document-type "standard"
:searchable true})
main-routes)]
(is (= (:status post-feed-request) 201))
(is (= @search-allowed-feeds
(db/get-searchable-feeds (db/list-feeds +test-db+))
{"en" ["pages" "blog"]})
"Test if search-allowed-feeds is updated when feed is added")
(let [image-feed (map #(update-in % [:action] keyword)
(read-json
(:body
(request
:post
"/_api/json/_feed/en/image"
(json-str
{:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes))))
all-feeds (map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
main-routes))))
image-feed-nl (read-string
(:body
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)))]
(is (= (count all-feeds) 3))
;; test HTTP method/action mismatch
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :delete
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :delete
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body
(str "The :action value in the provided map must "
"correspond to the right HTTP method "
"(i.e. POST & :create, PUT & :update "
"and DELETE and :delete).")}))
;; make sure it isn't possible to recreate existing feeds
(is (= (request
:post
"/_api/json/_feed/en/image"
(json-str {:action :create
:name "image"
:title "Images"
:language "en"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
(request
:post
"/_api/clj/_feed/nl/image"
(pr-str {:action :create
:name "image"
:title "Images"
:language "nl"
:subtitle "Pictures."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "image"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The provided feed already exists."}))
(testing "test language argument for /_api/x/_list-feeds"
(is (= (sort-by :name all-feeds)
(sort-by :name
(map #(update-in % [:action] keyword)
(read-json
(:body
(request :get
"/_api/json/_list-feeds"
nil
main-routes
{:language "en"})))))
(sort-by :name
(read-string
(:body
(request :get
"/_api/clj/_list-feeds"
nil
main-routes
{:language "en"}))))))
(is (= image-feed-nl
(read-string
(:body
(request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type "image"
:language "nl"}))))))
(is (= (count (read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
4))
(is (= (map #(update-in % [:action] keyword)
(read-json
(:body (request :get
"/_api/json/_list-feeds"
main-routes))))
(read-string
(:body (request :get
"/_api/clj/_list-feeds"
main-routes)))))
(is (= (flatten [image-feed-nl image-feed])
(map #(update-in % [:action] keyword)
(read-json
(:body (request
:get
"/_api/json/_list-feeds"
nil
main-routes
{:default-document-type
"image"}))))
(read-string
(:body (request
:get
"/_api/clj/_list-feeds"
nil
main-routes
{:default-document-type
"image"})))))))
(let [{:keys [status body] :as get-feed-json}
(update-in (request :get
"/_api/json/_feed/en/blog"
main-routes)
[:body]
read-json)
get-feed-clj
(update-in (request :get
"/_api/clj/_feed/en/blog"
main-routes)
[:body]
read-string)]
(is (= (update-in (dissoc get-feed-json :headers)
[:body]
(fn [states]
(map #(update-in % [:action] keyword) states)))
(dissoc get-feed-clj :headers)))
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix Weblog"))
;; make sure that update requests aren't allowed without
;; :previous-id
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id :foo
:title "Vix!"
:searchable false))
main-routes)
(request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:title "Vix!"
:searchable false))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the "
"most recent :previous-id.")})))
;; test json put request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-json}
(update-in (request :put
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Vix!"
:searchable false))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Vix!"))
(is (= @search-allowed-feeds {"nl" [] "en" ["pages"]})
"Make sure search-allowed-feeds is updated when feeds are")))
;; test clojure put request
(let [prev-body (first
(read-string
(:body
(request :get
"/_api/clj/_feed/en/blog"
main-routes))))
{:keys [body status] :as put-request-clj}
(update-in (request :put
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :update
:previous-id (:_id prev-body)
:title "Fix!"
:searchable false))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:name (first body)) "blog"))
(is (= (:title (first body)) "Fix!")))
(testing "test delete requests"
;; make sure delete requests aren't allowed without :previous-id
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/json/_feed/en/blog"
(json-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:previous-id :foo
:name "blog"
:language "en"})
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
{:action :delete
:name "blog"
:language "en"})
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body (str "This feed map doesn't contain the most recent "
":previous-id.")}))
;; test json delete request
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))
{:keys [body status] :as delete-request-json}
(update-in (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-json)]
(is (= status 200))
(is (= (keyword (:action (first body)))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete)))
;; make sure the right error is returned when feed is already gone
(let [prev-body (first
(read-json
(:body
(request :get
"/_api/json/_feed/en/blog"
main-routes))))]
(is (= (request :delete
"/_api/json/_feed/en/blog"
(json-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
(request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "This feed has already been deleted."})))
;; test clojure delete request
(let [prev-body (first
(read-json
(:body
(request
:post
"/_api/json/_feed/en/blog"
(json-str {:action :create
:name "blog"
:title "Weblog"
:language "en"
:subtitle "Weblog..."
:default-slug-format
"/static/{document-title}.{ext}"
:default-document-type "standard"})
main-routes))))
{:keys [body status] :as delete-request-clj}
(update-in (request :delete
"/_api/clj/_feed/en/blog"
(pr-str
(assoc prev-body
:action :delete
:previous-id (:_id prev-body)))
main-routes)
[:body]
read-string)]
(is (= status 200))
(is (= (:action (first body))
(:action (first (db/get-feed +test-db+ "en" "blog")))
:delete))))))
(testing "test invalid api requests"
(are [uri]
(= (request :post
uri
"[}"
main-routes)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})
"/_api/clj/_feed/nl/invalid-image"
"/_api/json/_feed/nl/invalid-image"
"/_api/clj/_document/blog/invalid-test"
"/_api/json/_document/blog/invalid-test"))))
(deftest test-read-body
(is (= (read-body "json" (java.io.StringReader. ""))
(read-body "clj" (java.io.StringReader. ""))
nil))
(is (= (read-body "json" (java.io.StringReader. "{\"foo\":\"bar\"}"))
{:foo "bar"}))
(is (= (read-body "clj" (java.io.StringReader. "{:foo :bar}"))
{:foo :bar}))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "json" (java.io.StringReader. "{]"))))
(is (thrown+? (partial check-exc :vix.routes/invalid-request-body)
(read-body "clj" (java.io.StringReader. "{]")))))
(deftest ^{:integration true} test-routes-authorization
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false})
(db/append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{feed-name}/{document-title}"
:default-document-type "with-description"
:language "en"}))
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(testing "Test if authorization is enforced correctly."
(is (= (:status (unauthorized-request :get "/admin/" main-routes))
;; test json requests
(:status (unauthorized-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
;; test clojure requests
(:status (unauthorized-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthorized-request
:post
"/_api/clj/_feed/foo/bar"
main-routes))
(:status (unauthorized-request
:get
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:put
"/_api/clj/_feed/en/blog"
main-routes))
(:status (unauthorized-request
:delete
"/_api/clj/_feed/en/blog"
main-routes))
302)))))
(deftest ^{:integration true} test-routes-authentication
(do
(db/append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/test"
:content "bar"
:draft false}))
(testing "Test if authentication is enforced correctly."
(with-redefs [config/database +test-db+
lucene/directory (lucene/create-directory :RAM)]
(is (= (:status (unauthenticated-request :get "/admin" main-routes))
;; test json requests
(:status (unauthenticated-request
:get
"/_api/json/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/json/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/json/_document/blog/test"
(json-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/json/_document/blog/test"
main-routes))
;; test clojure requests
(:status (unauthenticated-request
:get
"/_api/clj/en/blog/_list-documents"
main-routes))
(:status (unauthenticated-request
:post
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:get
"/_api/clj/_document/blog/test"
main-routes))
(:status (unauthenticated-request
:put
"/_api/clj/_document/blog/test"
(pr-str {:title "test-create"
:slug "/blog/test"
:content "hic sunt dracones"})
main-routes))
(:status (unauthenticated-request
:delete
"/_api/clj/_document/blog/test"
main-routes))
302)))))
(deftest test-logout
(is (= (logout {:username "johndoe" :permissions {:* [:DELETE]}})
{:session {}
:status 302
:headers {"Location" "/"}})
"should empty the session and redirect to /"))
(deftest test-login
(do
(auth/add-user +test-db+
"fmw"
"oops"
{:* ["GET" "POST" "PUT" "DELETE"]}))
(with-redefs [config/database +test-db+]
(is (= (form-request :post "/login" main-routes {"username" "fmw"
"password" "PI:PASSWORD:<PASSWORD>END_PI"})
{:status 302
:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"
"Location" "/login"}
:body ""}))
(let [r (form-request :post "/login" main-routes {"username" "fmw"
"password" "PI:PASSWORD:<PASSWORD>END_PI"})]
(is (= ((:headers r) "Location") "/admin/"))
(is (= (:status r) 302)))))
(deftest test-wrap-caching-headers
(testing "test if regular pages are pre-expired"
(is (= ((wrap-caching-headers identity) {})
{:headers {"Expires" "Mon, 26 Mar 2012 09:00:00 GMT"}})))
(with-redefs [time-core/now
(fn []
(time-core/date-time 2012 4 22 16 04 57 525))]
(testing "test if files are expired correclty"
(are [content-type]
(= ((wrap-caching-headers identity)
{:headers {"Content-Type" content-type}})
{:headers {"Expires" "Wed, 22 Apr 2015 16:04:57 +0000"
"Cache-Control" "public"
"Content-Type" content-type}})
"image/png"
"image/jpeg"
"image/gif"
"text/css"
"text/javascript"))))
(deftest test-redirect-301
(is (= (redirect-301 "/foo")
{:status 301
:body "Moved Permanently"
:headers {"Location" "/foo"}})))
(deftest test-redirection-handler
(with-redefs [config/default-host "localhost"
config/base-uri "http://localhost:3000"
config/cdn-hostname "http://localhost:3000/"]
(is (= ((redirection-handler identity) {:server-name "localhost"})
{:server-name "localhost"}))
(testing "test if visitors are redirected to the default-host"
(with-redefs [config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "vixu.com"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com"}}))))
(testing "test if administrators are redirected to https://"
(with-redefs [config/server-name "www.vixu.com"
config/default-host "www.vixu.com"]
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :http})
{:status 301
:body "Moved Permanently"
:headers {"Location" "https://www.vixu.com/admin/"}}))
;; don't redirect if the scheme is already https
(is (= ((redirection-handler identity) {:server-name "www.vixu.com"
:uri "/admin/"
:scheme :https})
{:server-name "www.vixu.com" :uri "/admin/" :scheme :https}))))
(testing "on localhost, /admin shouldn't redirect to https://"
(with-redefs [config/default-host "localhost"]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/admin/"
:scheme :http})
{:server-name "localhost" :uri "/admin/" :scheme :http}))))
(testing "test if custom redirects are correctly executed"
(with-redefs [config/redirects {"/foo" "/bar"
"/vixu" "http://www.vixu.com/"}]
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/foo"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "/bar"}}))
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/vixu"})
{:status 301
:body "Moved Permanently"
:headers {"Location" "http://www.vixu.com/"}}))
;; do nothing unless the uri is a listed redirect
(is (= ((redirection-handler identity)
{:server-name "localhost"
:uri "/test"})
{:server-name "localhost" :uri "/test"}))))))
(deftest test-handle-exceptions
(is (= ((handle-exceptions identity) :works) :works))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/insufficient-privileges-error)))
:should-not-work)
{:status 302
:headers {"Location" "/permission-denied"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ auth/authentication-required-error)))
:should-not-work)
{:status 302
:headers {"Location" "/login"}
:body ""}))
(is (= ((handle-exceptions
(fn [handler]
(throw+ invalid-request-body-error)))
:should-not-work)
{:status 400
:headers {"Content-Type" "text/plain; charset=UTF-8"}
:body "The JSON or Clojure request body is invalid."})))
(defn test-ns-hook []
(database-fixture test-reset-search-allowed-feeds!)
(database-fixture test-reset-available-languages!)
(test-reset-index-reader!)
(test-data-response)
(test-response)
(test-page-not-found-response)
(database-fixture test-image-response)
(database-fixture test-get-segment-and-get-segments)
(database-fixture test-get-frontpage-for-language!)
(database-fixture test-get-cached-frontpage!)
(database-fixture test-get-cached-page!)
(test-reset-frontpage-cache!)
(test-reset-page-cache!)
(database-fixture test-feed-request)
(database-fixture test-document-request)
(database-fixture test-routes)
(test-read-body)
(database-fixture test-routes-authorization)
(database-fixture test-routes-authentication)
(test-logout)
(database-fixture test-login)
(test-wrap-caching-headers)
(test-redirect-301)
(test-redirection-handler)
(test-handle-exceptions))
|
[
{
"context": "(ns com.github.hindol.fire-tools\n (:require [rum.core :as rum]\n ",
"end": 21,
"score": 0.8181939721107483,
"start": 15,
"tag": "USERNAME",
"value": "hindol"
},
{
"context": "tainer-fluid\n [:a.navbar-brand {:href \"#\"} \"F.I.R.E. Tools\"]\n (NavbarToggler toggle-target)\n ",
"end": 2027,
"score": 0.6099254488945007,
"start": 2022,
"tag": "NAME",
"value": "I.R.E"
}
] |
src/com/github/hindol/fire_tools.cljs
|
hindol/fire-tools
| 0 |
(ns com.github.hindol.fire-tools
(:require [rum.core :as rum]
[citrus.core :as citrus]))
(def initial-state 0)
(defmulti control (fn [event] event))
(defmethod control :init
[]
{:local-storage
{:method :get
:key :counter
:on-read :init-ready}})
(defmethod control :init-ready
[_ [counter]]
(if-not (nil? counter)
{:state (js/parseInt counter)}
{:state initial-state}))
(defmethod control :inc
[_ _ counter]
(let [next-counter (inc counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defmethod control :dec
[_ _ counter]
(let [next-counter (dec counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defn local-storage
[reconciler controller-name effect]
(let [{:keys [method data key on-read]} effect]
(case method
:set (js/localStorage.setItem (name key) data)
:get (->> (js/localStorage.getItem (name key))
(citrus/dispatch! reconciler controller-name on-read))
nil)))
(rum/defc Counter < rum/reactive
[r]
[:div
[:button {:on-click #(citrus/dispatch! r :counter :dec)} "-"]
[:span (rum/react (citrus/subscription r [:counter]))]
[:button {:on-click #(citrus/dispatch! r :counter :inc)} "+"]])
(rum/defc NavbarToggler
[label]
[:button.navbar-toggler {:type "button"
:data-bs-toggle "collapse"
:data-bs-target (str "#" label)
:aria-controls label
:aria-expanded "false"
:aria-label "Toggle navigation"}
[:span.navbar-toggler-icon]])
(rum/defc NavLink
[label]
[:a.nav-link {:href "#"} label])
(rum/defc Navbar
[& contents]
(let [toggle-target "navbarNavAltMarkup"]
[:nav.navbar.navbar-expand-lg.navbar-light.bg-light
[:div.container-fluid
[:a.navbar-brand {:href "#"} "F.I.R.E. Tools"]
(NavbarToggler toggle-target)
[:div.collapse.navbar-collapse {:id toggle-target}
(into
[:div.navbar-nav]
contents)]]]))
(rum/defc Breadcrumb
[items]
[:nav {:aria-label "breadcrumb"}
(into
[:ol.breadcrumb]
(for [{:keys [href label active?]} items]
[:li.breadcrumb-item
{:class (when active? "active")
:aria-current (when active? "page")}
(if active?
label
[:a {:href href} label])]))])
(rum/defc Main
[& contents]
[:div.container-lg
(into
[:main]
contents)])
(rum/defc App
[& contents]
(into
[:div]
contents))
(defonce reconciler
(citrus/reconciler
{:state
(atom {})
:controllers
{:counter control}
:effect-handlers
{:local-storage local-storage}}))
(defonce init-ctrl (citrus/broadcast-sync! reconciler :init))
(rum/mount (App (Navbar (NavLink "Home")
(NavLink "About"))
(Main (Breadcrumb [{:href "#" :label "Home"}
{:href "#" :label "F.I.R.E. Tools" :active? true}])
(Counter reconciler)))
(.getElementById js/document "app"))
|
39201
|
(ns com.github.hindol.fire-tools
(:require [rum.core :as rum]
[citrus.core :as citrus]))
(def initial-state 0)
(defmulti control (fn [event] event))
(defmethod control :init
[]
{:local-storage
{:method :get
:key :counter
:on-read :init-ready}})
(defmethod control :init-ready
[_ [counter]]
(if-not (nil? counter)
{:state (js/parseInt counter)}
{:state initial-state}))
(defmethod control :inc
[_ _ counter]
(let [next-counter (inc counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defmethod control :dec
[_ _ counter]
(let [next-counter (dec counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defn local-storage
[reconciler controller-name effect]
(let [{:keys [method data key on-read]} effect]
(case method
:set (js/localStorage.setItem (name key) data)
:get (->> (js/localStorage.getItem (name key))
(citrus/dispatch! reconciler controller-name on-read))
nil)))
(rum/defc Counter < rum/reactive
[r]
[:div
[:button {:on-click #(citrus/dispatch! r :counter :dec)} "-"]
[:span (rum/react (citrus/subscription r [:counter]))]
[:button {:on-click #(citrus/dispatch! r :counter :inc)} "+"]])
(rum/defc NavbarToggler
[label]
[:button.navbar-toggler {:type "button"
:data-bs-toggle "collapse"
:data-bs-target (str "#" label)
:aria-controls label
:aria-expanded "false"
:aria-label "Toggle navigation"}
[:span.navbar-toggler-icon]])
(rum/defc NavLink
[label]
[:a.nav-link {:href "#"} label])
(rum/defc Navbar
[& contents]
(let [toggle-target "navbarNavAltMarkup"]
[:nav.navbar.navbar-expand-lg.navbar-light.bg-light
[:div.container-fluid
[:a.navbar-brand {:href "#"} "F.<NAME>. Tools"]
(NavbarToggler toggle-target)
[:div.collapse.navbar-collapse {:id toggle-target}
(into
[:div.navbar-nav]
contents)]]]))
(rum/defc Breadcrumb
[items]
[:nav {:aria-label "breadcrumb"}
(into
[:ol.breadcrumb]
(for [{:keys [href label active?]} items]
[:li.breadcrumb-item
{:class (when active? "active")
:aria-current (when active? "page")}
(if active?
label
[:a {:href href} label])]))])
(rum/defc Main
[& contents]
[:div.container-lg
(into
[:main]
contents)])
(rum/defc App
[& contents]
(into
[:div]
contents))
(defonce reconciler
(citrus/reconciler
{:state
(atom {})
:controllers
{:counter control}
:effect-handlers
{:local-storage local-storage}}))
(defonce init-ctrl (citrus/broadcast-sync! reconciler :init))
(rum/mount (App (Navbar (NavLink "Home")
(NavLink "About"))
(Main (Breadcrumb [{:href "#" :label "Home"}
{:href "#" :label "F.I.R.E. Tools" :active? true}])
(Counter reconciler)))
(.getElementById js/document "app"))
| true |
(ns com.github.hindol.fire-tools
(:require [rum.core :as rum]
[citrus.core :as citrus]))
(def initial-state 0)
(defmulti control (fn [event] event))
(defmethod control :init
[]
{:local-storage
{:method :get
:key :counter
:on-read :init-ready}})
(defmethod control :init-ready
[_ [counter]]
(if-not (nil? counter)
{:state (js/parseInt counter)}
{:state initial-state}))
(defmethod control :inc
[_ _ counter]
(let [next-counter (inc counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defmethod control :dec
[_ _ counter]
(let [next-counter (dec counter)]
{:state next-counter
:local-storage
{:method :set
:data next-counter
:key :counter}}))
(defn local-storage
[reconciler controller-name effect]
(let [{:keys [method data key on-read]} effect]
(case method
:set (js/localStorage.setItem (name key) data)
:get (->> (js/localStorage.getItem (name key))
(citrus/dispatch! reconciler controller-name on-read))
nil)))
(rum/defc Counter < rum/reactive
[r]
[:div
[:button {:on-click #(citrus/dispatch! r :counter :dec)} "-"]
[:span (rum/react (citrus/subscription r [:counter]))]
[:button {:on-click #(citrus/dispatch! r :counter :inc)} "+"]])
(rum/defc NavbarToggler
[label]
[:button.navbar-toggler {:type "button"
:data-bs-toggle "collapse"
:data-bs-target (str "#" label)
:aria-controls label
:aria-expanded "false"
:aria-label "Toggle navigation"}
[:span.navbar-toggler-icon]])
(rum/defc NavLink
[label]
[:a.nav-link {:href "#"} label])
(rum/defc Navbar
[& contents]
(let [toggle-target "navbarNavAltMarkup"]
[:nav.navbar.navbar-expand-lg.navbar-light.bg-light
[:div.container-fluid
[:a.navbar-brand {:href "#"} "F.PI:NAME:<NAME>END_PI. Tools"]
(NavbarToggler toggle-target)
[:div.collapse.navbar-collapse {:id toggle-target}
(into
[:div.navbar-nav]
contents)]]]))
(rum/defc Breadcrumb
[items]
[:nav {:aria-label "breadcrumb"}
(into
[:ol.breadcrumb]
(for [{:keys [href label active?]} items]
[:li.breadcrumb-item
{:class (when active? "active")
:aria-current (when active? "page")}
(if active?
label
[:a {:href href} label])]))])
(rum/defc Main
[& contents]
[:div.container-lg
(into
[:main]
contents)])
(rum/defc App
[& contents]
(into
[:div]
contents))
(defonce reconciler
(citrus/reconciler
{:state
(atom {})
:controllers
{:counter control}
:effect-handlers
{:local-storage local-storage}}))
(defonce init-ctrl (citrus/broadcast-sync! reconciler :init))
(rum/mount (App (Navbar (NavLink "Home")
(NavLink "About"))
(Main (Breadcrumb [{:href "#" :label "Home"}
{:href "#" :label "F.I.R.E. Tools" :active? true}])
(Counter reconciler)))
(.getElementById js/document "app"))
|
[
{
"context": " :type \"test_type\"\n :id \"HaShMe\"\n :source {:first-name \"Kelis\"\n ",
"end": 2791,
"score": 0.5371279716491699,
"start": 2789,
"tag": "USERNAME",
"value": "Me"
},
{
"context": " :id \"HaShMe\"\n :source {:first-name \"Kelis\"\n :surname \"WaterDancer\"}})",
"end": 2834,
"score": 0.9996523857116699,
"start": 2829,
"tag": "NAME",
"value": "Kelis"
},
{
"context": "e \"test_type\"\n :source {:first-name \"Luke\"\n :surname \"Skywalker\"}})\n\n",
"end": 2992,
"score": 0.9994601011276245,
"start": 2988,
"tag": "NAME",
"value": "Luke"
},
{
"context": "e \"test_type\"\n :source {:first-name \"Obiwan\"\n :surname \"Kenobi\"}})\n\n (",
"end": 3150,
"score": 0.9995158314704895,
"start": 3144,
"tag": "NAME",
"value": "Obiwan"
}
] |
qanal/src/qanal/elasticsearch.clj
|
samsara/samsara
| 146 |
;; 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 qanal.elasticsearch
(:require [clojurewerkz.elastisch.rest :as esr]
[clojurewerkz.elastisch.rest.bulk :as esb]
[taoensso.timbre :as log]
[samsara.trackit :refer [track-time track-rate]]))
(defn make-bulk-request
"Turns a kafka message into a two-lines bulk operation item.
see http://www.elastic.co/guide/en/elasticsearch/reference/1.3/docs-bulk.html
for more information."
[{:keys [index type id source]}]
[ {:index
(merge {:_index index,
:_type type }
(when id {:_id id})) }
source ])
(defn log-failed-requests
"This function checks http response code of the response and
if not in 2XX range logs the request and response"
[request-item response-item]
(let [[action els-resp] (first response-item)] ;;ELS response items are maps made of only one key-value pair
(when (>= (:status els-resp) 300) ;;Http response code not in 2XX range means failure of some sort
(let [document (:source request-item)
status (:status els-resp)
error-msg (:error els-resp)]
(log/warn "FAILED Bulk request action ->" action "for document ->" document ". Response status ->" status
"and error ->" error-msg)))))
(defn bulk-index [{:keys [end-point]} messages]
;; TODO: connection should be cached
(let [conn (esr/connect end-point)
;; track interesting metrics
_ (track-rate "qanal.els.bulk-index.docs" (count messages))
resp (track-time "qanal.els.bulk-index.time"
(esb/bulk conn (mapcat make-bulk-request messages)))]
(when (:errors resp)
(let [resp-items (:items resp)] ;;ELS returns response-items in the SAME order as the bulk requests
(dorun (map log-failed-requests messages resp-items))))))
(comment
(def test-endpoint (esr/connect "http://localhost:9200"))
(def test1 {:index "test_index"
:type "test_type"
:id "HaShMe"
:source {:first-name "Kelis"
:surname "WaterDancer"}})
(def test2 {:index "test_index"
:type "test_type"
:source {:first-name "Luke"
:surname "Skywalker"}})
(def test3 {:index "test_index"
:type "test_type"
:source {:first-name "Obiwan"
:surname "Kenobi"}})
(mapcat make-bulk-request [test1 test2 test3])
(bulk-index test-endpoint [test1 test2 test3]))
|
92029
|
;; 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 qanal.elasticsearch
(:require [clojurewerkz.elastisch.rest :as esr]
[clojurewerkz.elastisch.rest.bulk :as esb]
[taoensso.timbre :as log]
[samsara.trackit :refer [track-time track-rate]]))
(defn make-bulk-request
"Turns a kafka message into a two-lines bulk operation item.
see http://www.elastic.co/guide/en/elasticsearch/reference/1.3/docs-bulk.html
for more information."
[{:keys [index type id source]}]
[ {:index
(merge {:_index index,
:_type type }
(when id {:_id id})) }
source ])
(defn log-failed-requests
"This function checks http response code of the response and
if not in 2XX range logs the request and response"
[request-item response-item]
(let [[action els-resp] (first response-item)] ;;ELS response items are maps made of only one key-value pair
(when (>= (:status els-resp) 300) ;;Http response code not in 2XX range means failure of some sort
(let [document (:source request-item)
status (:status els-resp)
error-msg (:error els-resp)]
(log/warn "FAILED Bulk request action ->" action "for document ->" document ". Response status ->" status
"and error ->" error-msg)))))
(defn bulk-index [{:keys [end-point]} messages]
;; TODO: connection should be cached
(let [conn (esr/connect end-point)
;; track interesting metrics
_ (track-rate "qanal.els.bulk-index.docs" (count messages))
resp (track-time "qanal.els.bulk-index.time"
(esb/bulk conn (mapcat make-bulk-request messages)))]
(when (:errors resp)
(let [resp-items (:items resp)] ;;ELS returns response-items in the SAME order as the bulk requests
(dorun (map log-failed-requests messages resp-items))))))
(comment
(def test-endpoint (esr/connect "http://localhost:9200"))
(def test1 {:index "test_index"
:type "test_type"
:id "HaShMe"
:source {:first-name "<NAME>"
:surname "WaterDancer"}})
(def test2 {:index "test_index"
:type "test_type"
:source {:first-name "<NAME>"
:surname "Skywalker"}})
(def test3 {:index "test_index"
:type "test_type"
:source {:first-name "<NAME>"
:surname "Kenobi"}})
(mapcat make-bulk-request [test1 test2 test3])
(bulk-index test-endpoint [test1 test2 test3]))
| 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 qanal.elasticsearch
(:require [clojurewerkz.elastisch.rest :as esr]
[clojurewerkz.elastisch.rest.bulk :as esb]
[taoensso.timbre :as log]
[samsara.trackit :refer [track-time track-rate]]))
(defn make-bulk-request
"Turns a kafka message into a two-lines bulk operation item.
see http://www.elastic.co/guide/en/elasticsearch/reference/1.3/docs-bulk.html
for more information."
[{:keys [index type id source]}]
[ {:index
(merge {:_index index,
:_type type }
(when id {:_id id})) }
source ])
(defn log-failed-requests
"This function checks http response code of the response and
if not in 2XX range logs the request and response"
[request-item response-item]
(let [[action els-resp] (first response-item)] ;;ELS response items are maps made of only one key-value pair
(when (>= (:status els-resp) 300) ;;Http response code not in 2XX range means failure of some sort
(let [document (:source request-item)
status (:status els-resp)
error-msg (:error els-resp)]
(log/warn "FAILED Bulk request action ->" action "for document ->" document ". Response status ->" status
"and error ->" error-msg)))))
(defn bulk-index [{:keys [end-point]} messages]
;; TODO: connection should be cached
(let [conn (esr/connect end-point)
;; track interesting metrics
_ (track-rate "qanal.els.bulk-index.docs" (count messages))
resp (track-time "qanal.els.bulk-index.time"
(esb/bulk conn (mapcat make-bulk-request messages)))]
(when (:errors resp)
(let [resp-items (:items resp)] ;;ELS returns response-items in the SAME order as the bulk requests
(dorun (map log-failed-requests messages resp-items))))))
(comment
(def test-endpoint (esr/connect "http://localhost:9200"))
(def test1 {:index "test_index"
:type "test_type"
:id "HaShMe"
:source {:first-name "PI:NAME:<NAME>END_PI"
:surname "WaterDancer"}})
(def test2 {:index "test_index"
:type "test_type"
:source {:first-name "PI:NAME:<NAME>END_PI"
:surname "Skywalker"}})
(def test3 {:index "test_index"
:type "test_type"
:source {:first-name "PI:NAME:<NAME>END_PI"
:surname "Kenobi"}})
(mapcat make-bulk-request [test1 test2 test3])
(bulk-index test-endpoint [test1 test2 test3]))
|
[
{
"context": "their description of\n the SME algorithm.\n\n [1] Falkenhainer, Forbus & Gentner (1989). The structure-mapping e",
"end": 374,
"score": 0.9998536109924316,
"start": 362,
"tag": "NAME",
"value": "Falkenhainer"
},
{
"context": "ion of\n the SME algorithm.\n\n [1] Falkenhainer, Forbus & Gentner (1989). The structure-mapping engine:\n ",
"end": 382,
"score": 0.9917489290237427,
"start": 376,
"tag": "NAME",
"value": "Forbus"
},
{
"context": "the SME algorithm.\n\n [1] Falkenhainer, Forbus & Gentner (1989). The structure-mapping engine:\n a",
"end": 392,
"score": 0.9963159561157227,
"start": 385,
"tag": "NAME",
"value": "Gentner"
}
] |
src/sme_clj/example/simple_heat_water.clj
|
svdm/SME-clj
| 6 |
(ns sme-clj.example.simple-heat-water
"Example adapted from SME literature [1], of an analogy between the flow of
water from a large beaker through a pipe to a small vial, and the flow of
heat from a cup of coffee through a bar into an ice cube.
This is the running example Falkenhainer et al. use in their description of
the SME algorithm.
[1] Falkenhainer, Forbus & Gentner (1989). The structure-mapping engine:
algorithm and examples. Artificial Intelligence, 41, 1-62.
"
(:use sme-clj.typedef)
(:require [sme-clj.core :as sme]
[clojure.pprint :as pp]))
;; Predicate definitions
(defpredicate flow
:type :relation
:arity 4)
(defpredicate greater
:type :relation
:arity 2)
(defpredicate cause
:type :relation
:arity 2)
(defpredicate temperature
:type :function)
(defpredicate flat-top
:type :function)
(defpredicate pressure
:type :function)
(defpredicate diameter
:type :function)
(defpredicate liquid
:type :attribute)
(defpredicate clear
:type :attribute)
;; Entities
(defentity Coffee []) ; [] -> no value slots in entity
(defentity Icecube [])
(defentity Bar [])
(defentity Heat [])
(defentity Water [])
(defentity Beaker [])
(defentity Vial [])
(defentity Pipe [])
;; Concept graph definitions
(def simple-heat-flow
(make-concept-graph "simple heat flow" e
(e flow Coffee Icecube Heat Bar)
(e greater (e temperature Coffee) (e temperature Icecube))
(e flat-top Coffee)
(e liquid Coffee)))
(def simple-water-flow
(make-concept-graph "simple water flow" e
(e cause
(e greater (e pressure Beaker) (e pressure Vial))
(e flow Beaker Vial Water Pipe))
(e greater (e diameter Beaker) (e diameter Vial))
(e clear Beaker)
(e flat-top Water)
(e liquid Water)))
;; Commented out example
#_(do
;; Water flow is the base, heat flow the target
(def result (sme/match simple-water-flow simple-heat-flow))
(def gmaps (:gmaps result))
;; Should show the cause relation between the greater temperature
;; relation and the heat flow relation. This relation has been inferred
;; based on the analogical cause relation in the water flow graph.
(pp/write (:transferred (first gmaps)) :suppress-namespaces true)
;; For other keys like :transferred that are stored in a gmap and might be
;; interesting to examine, see the docstring for 'sme-clj.core/match
)
|
8516
|
(ns sme-clj.example.simple-heat-water
"Example adapted from SME literature [1], of an analogy between the flow of
water from a large beaker through a pipe to a small vial, and the flow of
heat from a cup of coffee through a bar into an ice cube.
This is the running example Falkenhainer et al. use in their description of
the SME algorithm.
[1] <NAME>, <NAME> & <NAME> (1989). The structure-mapping engine:
algorithm and examples. Artificial Intelligence, 41, 1-62.
"
(:use sme-clj.typedef)
(:require [sme-clj.core :as sme]
[clojure.pprint :as pp]))
;; Predicate definitions
(defpredicate flow
:type :relation
:arity 4)
(defpredicate greater
:type :relation
:arity 2)
(defpredicate cause
:type :relation
:arity 2)
(defpredicate temperature
:type :function)
(defpredicate flat-top
:type :function)
(defpredicate pressure
:type :function)
(defpredicate diameter
:type :function)
(defpredicate liquid
:type :attribute)
(defpredicate clear
:type :attribute)
;; Entities
(defentity Coffee []) ; [] -> no value slots in entity
(defentity Icecube [])
(defentity Bar [])
(defentity Heat [])
(defentity Water [])
(defentity Beaker [])
(defentity Vial [])
(defentity Pipe [])
;; Concept graph definitions
(def simple-heat-flow
(make-concept-graph "simple heat flow" e
(e flow Coffee Icecube Heat Bar)
(e greater (e temperature Coffee) (e temperature Icecube))
(e flat-top Coffee)
(e liquid Coffee)))
(def simple-water-flow
(make-concept-graph "simple water flow" e
(e cause
(e greater (e pressure Beaker) (e pressure Vial))
(e flow Beaker Vial Water Pipe))
(e greater (e diameter Beaker) (e diameter Vial))
(e clear Beaker)
(e flat-top Water)
(e liquid Water)))
;; Commented out example
#_(do
;; Water flow is the base, heat flow the target
(def result (sme/match simple-water-flow simple-heat-flow))
(def gmaps (:gmaps result))
;; Should show the cause relation between the greater temperature
;; relation and the heat flow relation. This relation has been inferred
;; based on the analogical cause relation in the water flow graph.
(pp/write (:transferred (first gmaps)) :suppress-namespaces true)
;; For other keys like :transferred that are stored in a gmap and might be
;; interesting to examine, see the docstring for 'sme-clj.core/match
)
| true |
(ns sme-clj.example.simple-heat-water
"Example adapted from SME literature [1], of an analogy between the flow of
water from a large beaker through a pipe to a small vial, and the flow of
heat from a cup of coffee through a bar into an ice cube.
This is the running example Falkenhainer et al. use in their description of
the SME algorithm.
[1] PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI (1989). The structure-mapping engine:
algorithm and examples. Artificial Intelligence, 41, 1-62.
"
(:use sme-clj.typedef)
(:require [sme-clj.core :as sme]
[clojure.pprint :as pp]))
;; Predicate definitions
(defpredicate flow
:type :relation
:arity 4)
(defpredicate greater
:type :relation
:arity 2)
(defpredicate cause
:type :relation
:arity 2)
(defpredicate temperature
:type :function)
(defpredicate flat-top
:type :function)
(defpredicate pressure
:type :function)
(defpredicate diameter
:type :function)
(defpredicate liquid
:type :attribute)
(defpredicate clear
:type :attribute)
;; Entities
(defentity Coffee []) ; [] -> no value slots in entity
(defentity Icecube [])
(defentity Bar [])
(defentity Heat [])
(defentity Water [])
(defentity Beaker [])
(defentity Vial [])
(defentity Pipe [])
;; Concept graph definitions
(def simple-heat-flow
(make-concept-graph "simple heat flow" e
(e flow Coffee Icecube Heat Bar)
(e greater (e temperature Coffee) (e temperature Icecube))
(e flat-top Coffee)
(e liquid Coffee)))
(def simple-water-flow
(make-concept-graph "simple water flow" e
(e cause
(e greater (e pressure Beaker) (e pressure Vial))
(e flow Beaker Vial Water Pipe))
(e greater (e diameter Beaker) (e diameter Vial))
(e clear Beaker)
(e flat-top Water)
(e liquid Water)))
;; Commented out example
#_(do
;; Water flow is the base, heat flow the target
(def result (sme/match simple-water-flow simple-heat-flow))
(def gmaps (:gmaps result))
;; Should show the cause relation between the greater temperature
;; relation and the heat flow relation. This relation has been inferred
;; based on the analogical cause relation in the water flow graph.
(pp/write (:transferred (first gmaps)) :suppress-namespaces true)
;; For other keys like :transferred that are stored in a gmap and might be
;; interesting to examine, see the docstring for 'sme-clj.core/match
)
|
[
{
"context": "or IPersistentMap IPersistentList ISeq)))\n\n; Thx @ Alex Miller! http://www.ibm.com/developerworks/library/j-tree",
"end": 207,
"score": 0.999462902545929,
"start": 196,
"tag": "NAME",
"value": "Alex Miller"
}
] |
src/main/rksm/cloxp_trace/transform.clj
|
rksm/cloxp-trace
| 2 |
(ns rksm.cloxp-trace.transform
(:require [clojure.zip :as z]
[clojure.pprint :refer :all])
(:import (clojure.lang IPersistentVector IPersistentMap IPersistentList ISeq)))
; Thx @ Alex Miller! http://www.ibm.com/developerworks/library/j-treevisit/
(defmulti tree-branch? class)
(defmethod tree-branch? :default [_] false)
(defmethod tree-branch? IPersistentVector [v] (not-empty v))
(defmethod tree-branch? IPersistentMap [m] (not-empty m))
(defmethod tree-branch? IPersistentList [l] true)
(defmethod tree-branch? ISeq [s] true)
(prefer-method tree-branch? IPersistentList ISeq)
(defmulti tree-children class)
(defmethod tree-children IPersistentVector [v] v)
(defmethod tree-children IPersistentMap [m] (->> m seq (apply concat)))
(defmethod tree-children IPersistentList [l] l)
(defmethod tree-children ISeq [s] s)
(prefer-method tree-children IPersistentList ISeq)
(defmulti tree-make-node (fn [node children] (class node)))
(defmethod tree-make-node IPersistentVector [v children]
(vec children))
(defmethod tree-make-node IPersistentMap [m children]
(apply hash-map children))
(defmethod tree-make-node IPersistentList [_ children]
children)
(defmethod tree-make-node ISeq [node children]
(apply list children))
(prefer-method tree-make-node IPersistentList ISeq)
(defn tree-zipper [node]
(z/zipper tree-branch? tree-children tree-make-node node))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(defn print-tree
"for debugging"
[node]
(let [all (take-while (complement z/end?) (iterate z/next (tree-zipper node)))]
(binding [*print-right-margin* 20]
(pprint
(->> all
(map z/node) (zipmap (range))
sort)))))
(defn tfm-visit
[zippd i ids-and-idxs]
(if-let [[id _] (first (filter (fn [[_ idx]] (= i idx)) ids-and-idxs))]
(z/edit zippd (fn [n] `(rksm.cloxp-trace.capturing/capture ~id ~n)))
zippd))
(defn insert-captures-into-expr
"Takes a clojure expression and for each idx inserts a (capture _)
expression, wrapping the original node. Idx is a pointer into the expression
tree, in the order of iterative left-to-right traversal.
Example, given '(+ 2 (- 3 4)):
0: (+ 2 (- 3 4))
1: +
2: 2
3: (- 3 4)
4: -
5: 3
6: 4"
[expr ids-and-idxs]
(let [root (tree-zipper expr)
all (-> (take-while (complement z/end?) (iterate z/next root)))
last-with-counting-ctx {:i (count all), :z (last all)}
visit-and-prev (fn [{:keys [i z]}]
{:i (dec i),
:z (z/prev (tfm-visit z (dec i) ids-and-idxs))})
it (iterate visit-and-prev last-with-counting-ctx)
tfmed (take-while (comp not nil? :z) it)]
(-> tfmed last :z z/node)))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(comment
(insert-captures-into-expr '(+ 2 (- 3 4)) [["test" 3]])
(insert-captures-into-expr '(foo 2 {:x (+ 3 4)}) [["a" 3] ["b" 5]])
(insert-captures-into-expr '((if x y) 23) [["a" 4]])
(print-tree '({} {:x 3}))
(print-tree '(defn install-capture!
[form & {ns :ns, name :name, :as spec}]
(let [spec-with-id (add-capture-record! form spec)
records-for-form (capture-records-for ns name)
ids-and-idxs (map (fn [{:keys [id ast-idx]}] [id ast-idx]) records-for-form)
traced-form (tfm-for-capture form ids-and-idxs)
existing (find-existing-def spec-with-id)]
[ns name]
(remove-watch (find-var (symbol (str ns) (str name))) :cloxp-capture-reinstall)
(eval-form traced-form ns existing {::capturing {:hash (hash form)}})
(re-install-on-redef spec-with-id)
spec-with-id
)))
(seq {})
)
|
88137
|
(ns rksm.cloxp-trace.transform
(:require [clojure.zip :as z]
[clojure.pprint :refer :all])
(:import (clojure.lang IPersistentVector IPersistentMap IPersistentList ISeq)))
; Thx @ <NAME>! http://www.ibm.com/developerworks/library/j-treevisit/
(defmulti tree-branch? class)
(defmethod tree-branch? :default [_] false)
(defmethod tree-branch? IPersistentVector [v] (not-empty v))
(defmethod tree-branch? IPersistentMap [m] (not-empty m))
(defmethod tree-branch? IPersistentList [l] true)
(defmethod tree-branch? ISeq [s] true)
(prefer-method tree-branch? IPersistentList ISeq)
(defmulti tree-children class)
(defmethod tree-children IPersistentVector [v] v)
(defmethod tree-children IPersistentMap [m] (->> m seq (apply concat)))
(defmethod tree-children IPersistentList [l] l)
(defmethod tree-children ISeq [s] s)
(prefer-method tree-children IPersistentList ISeq)
(defmulti tree-make-node (fn [node children] (class node)))
(defmethod tree-make-node IPersistentVector [v children]
(vec children))
(defmethod tree-make-node IPersistentMap [m children]
(apply hash-map children))
(defmethod tree-make-node IPersistentList [_ children]
children)
(defmethod tree-make-node ISeq [node children]
(apply list children))
(prefer-method tree-make-node IPersistentList ISeq)
(defn tree-zipper [node]
(z/zipper tree-branch? tree-children tree-make-node node))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(defn print-tree
"for debugging"
[node]
(let [all (take-while (complement z/end?) (iterate z/next (tree-zipper node)))]
(binding [*print-right-margin* 20]
(pprint
(->> all
(map z/node) (zipmap (range))
sort)))))
(defn tfm-visit
[zippd i ids-and-idxs]
(if-let [[id _] (first (filter (fn [[_ idx]] (= i idx)) ids-and-idxs))]
(z/edit zippd (fn [n] `(rksm.cloxp-trace.capturing/capture ~id ~n)))
zippd))
(defn insert-captures-into-expr
"Takes a clojure expression and for each idx inserts a (capture _)
expression, wrapping the original node. Idx is a pointer into the expression
tree, in the order of iterative left-to-right traversal.
Example, given '(+ 2 (- 3 4)):
0: (+ 2 (- 3 4))
1: +
2: 2
3: (- 3 4)
4: -
5: 3
6: 4"
[expr ids-and-idxs]
(let [root (tree-zipper expr)
all (-> (take-while (complement z/end?) (iterate z/next root)))
last-with-counting-ctx {:i (count all), :z (last all)}
visit-and-prev (fn [{:keys [i z]}]
{:i (dec i),
:z (z/prev (tfm-visit z (dec i) ids-and-idxs))})
it (iterate visit-and-prev last-with-counting-ctx)
tfmed (take-while (comp not nil? :z) it)]
(-> tfmed last :z z/node)))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(comment
(insert-captures-into-expr '(+ 2 (- 3 4)) [["test" 3]])
(insert-captures-into-expr '(foo 2 {:x (+ 3 4)}) [["a" 3] ["b" 5]])
(insert-captures-into-expr '((if x y) 23) [["a" 4]])
(print-tree '({} {:x 3}))
(print-tree '(defn install-capture!
[form & {ns :ns, name :name, :as spec}]
(let [spec-with-id (add-capture-record! form spec)
records-for-form (capture-records-for ns name)
ids-and-idxs (map (fn [{:keys [id ast-idx]}] [id ast-idx]) records-for-form)
traced-form (tfm-for-capture form ids-and-idxs)
existing (find-existing-def spec-with-id)]
[ns name]
(remove-watch (find-var (symbol (str ns) (str name))) :cloxp-capture-reinstall)
(eval-form traced-form ns existing {::capturing {:hash (hash form)}})
(re-install-on-redef spec-with-id)
spec-with-id
)))
(seq {})
)
| true |
(ns rksm.cloxp-trace.transform
(:require [clojure.zip :as z]
[clojure.pprint :refer :all])
(:import (clojure.lang IPersistentVector IPersistentMap IPersistentList ISeq)))
; Thx @ PI:NAME:<NAME>END_PI! http://www.ibm.com/developerworks/library/j-treevisit/
(defmulti tree-branch? class)
(defmethod tree-branch? :default [_] false)
(defmethod tree-branch? IPersistentVector [v] (not-empty v))
(defmethod tree-branch? IPersistentMap [m] (not-empty m))
(defmethod tree-branch? IPersistentList [l] true)
(defmethod tree-branch? ISeq [s] true)
(prefer-method tree-branch? IPersistentList ISeq)
(defmulti tree-children class)
(defmethod tree-children IPersistentVector [v] v)
(defmethod tree-children IPersistentMap [m] (->> m seq (apply concat)))
(defmethod tree-children IPersistentList [l] l)
(defmethod tree-children ISeq [s] s)
(prefer-method tree-children IPersistentList ISeq)
(defmulti tree-make-node (fn [node children] (class node)))
(defmethod tree-make-node IPersistentVector [v children]
(vec children))
(defmethod tree-make-node IPersistentMap [m children]
(apply hash-map children))
(defmethod tree-make-node IPersistentList [_ children]
children)
(defmethod tree-make-node ISeq [node children]
(apply list children))
(prefer-method tree-make-node IPersistentList ISeq)
(defn tree-zipper [node]
(z/zipper tree-branch? tree-children tree-make-node node))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(defn print-tree
"for debugging"
[node]
(let [all (take-while (complement z/end?) (iterate z/next (tree-zipper node)))]
(binding [*print-right-margin* 20]
(pprint
(->> all
(map z/node) (zipmap (range))
sort)))))
(defn tfm-visit
[zippd i ids-and-idxs]
(if-let [[id _] (first (filter (fn [[_ idx]] (= i idx)) ids-and-idxs))]
(z/edit zippd (fn [n] `(rksm.cloxp-trace.capturing/capture ~id ~n)))
zippd))
(defn insert-captures-into-expr
"Takes a clojure expression and for each idx inserts a (capture _)
expression, wrapping the original node. Idx is a pointer into the expression
tree, in the order of iterative left-to-right traversal.
Example, given '(+ 2 (- 3 4)):
0: (+ 2 (- 3 4))
1: +
2: 2
3: (- 3 4)
4: -
5: 3
6: 4"
[expr ids-and-idxs]
(let [root (tree-zipper expr)
all (-> (take-while (complement z/end?) (iterate z/next root)))
last-with-counting-ctx {:i (count all), :z (last all)}
visit-and-prev (fn [{:keys [i z]}]
{:i (dec i),
:z (z/prev (tfm-visit z (dec i) ids-and-idxs))})
it (iterate visit-and-prev last-with-counting-ctx)
tfmed (take-while (comp not nil? :z) it)]
(-> tfmed last :z z/node)))
; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(comment
(insert-captures-into-expr '(+ 2 (- 3 4)) [["test" 3]])
(insert-captures-into-expr '(foo 2 {:x (+ 3 4)}) [["a" 3] ["b" 5]])
(insert-captures-into-expr '((if x y) 23) [["a" 4]])
(print-tree '({} {:x 3}))
(print-tree '(defn install-capture!
[form & {ns :ns, name :name, :as spec}]
(let [spec-with-id (add-capture-record! form spec)
records-for-form (capture-records-for ns name)
ids-and-idxs (map (fn [{:keys [id ast-idx]}] [id ast-idx]) records-for-form)
traced-form (tfm-for-capture form ids-and-idxs)
existing (find-existing-def spec-with-id)]
[ns name]
(remove-watch (find-var (symbol (str ns) (str name))) :cloxp-capture-reinstall)
(eval-form traced-form ns existing {::capturing {:hash (hash form)}})
(re-install-on-redef spec-with-id)
spec-with-id
)))
(seq {})
)
|
[
{
"context": "all]))\n\n\n(defn setup\n []\n (h/create-test-user! \"[email protected]\")\n (h/create-test-user! \"[email protected]",
"end": 319,
"score": 0.9999262094497681,
"start": 286,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "simulator.amazonses.com\")\n (h/create-test-user! \"[email protected]\" \"Test\" #{:customer :admin})\n (h/create-test-aut",
"end": 379,
"score": 0.999926745891571,
"start": 346,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "admin})\n (h/create-test-authorisation! (user/id \"[email protected]\") \"some-phrase\")\n (h/create-test-authorisation! ",
"end": 484,
"score": 0.9999250769615173,
"start": 451,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "hrase\")\n (h/create-test-authorisation! (user/id \"[email protected]\") \"some-other-phrase\")\n (h/create-test-authorisa",
"end": 577,
"score": 0.999921441078186,
"start": 544,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "hrase\")\n (h/create-test-authorisation! (user/id \"[email protected]\") \"some-phrase\"))\n\n(defn fixture [test]\n (h/ensu",
"end": 676,
"score": 0.9999226927757263,
"start": 643,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[request (h/request\n {:session \"[email protected]\"\n :query {:authorisations {}}}",
"end": 2004,
"score": 0.9999240636825562,
"start": 1971,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session {:current-user-id (user/id \"[email protected]\")}}\n (h/decode :transit body)))))\n\n ",
"end": 2322,
"score": 0.9999226927757263,
"start": 2289,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[request (h/request\n {:session \"[email protected]\"\n :query {:authorisations {}}}",
"end": 2622,
"score": 0.9999268054962158,
"start": 2589,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :authorisations {(authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n (",
"end": 2888,
"score": 0.9999255537986755,
"start": 2855,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 2984,
"score": 0.9999258518218994,
"start": 2951,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (authorisation/id (user/id \"[email protected]\") \"some-other-phrase\")\n ",
"end": 3318,
"score": 0.9999247193336487,
"start": 3285,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 3420,
"score": 0.9999244213104248,
"start": 3387,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n (",
"end": 3760,
"score": 0.9999229311943054,
"start": 3727,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 3856,
"score": 0.9999184012413025,
"start": 3823,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " {:next-offset (authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n :exhau",
"end": 4247,
"score": 0.999928891658783,
"start": 4214,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session {:current-user-id (user/id \"[email protected]\")}}\n (h/decode :transit body)))))\n\n ",
"end": 4394,
"score": 0.9999291896820068,
"start": 4361,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[request (h/request\n {:session \"[email protected]\"\n :metadata {:authorisations {",
"end": 4620,
"score": 0.9999293684959412,
"start": 4587,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :authorisations {(authorisation/id (user/id \"[email protected]\") \"some-other-phrase\")\n ",
"end": 4957,
"score": 0.9999252557754517,
"start": 4924,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 5059,
"score": 0.9999274611473083,
"start": 5026,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n (",
"end": 5399,
"score": 0.9999252557754517,
"start": 5366,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 5495,
"score": 0.9999251961708069,
"start": 5462,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " {:next-offset (authorisation/id (user/id \"[email protected]\") \"some-other-phrase\")\n :exhausted",
"end": 5890,
"score": 0.9999284148216248,
"start": 5857,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session {:current-user-id (user/id \"[email protected]\")}}\n (h/decode :transit body)))))\n\n ",
"end": 6034,
"score": 0.9999285340309143,
"start": 6001,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[request (h/request\n {:session \"[email protected]\"\n :metadata {:authorisations\n ",
"end": 6262,
"score": 0.9999294877052307,
"start": 6229,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (authorisation/id (user/id \"[email protected]\") \"some-other-phrase\")}}\n :que",
"end": 6485,
"score": 0.9999284744262695,
"start": 6452,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :authorisations {(authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n (",
"end": 6775,
"score": 0.9999269843101501,
"start": 6742,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "se\")\n (-> (user/id \"[email protected]\")\n (authorisati",
"end": 6871,
"score": 0.9999185800552368,
"start": 6838,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ffset\n (authorisation/id (user/id \"[email protected]\") \"some-phrase\")\n :exhausted? fals",
"end": 7275,
"score": 0.9999231696128845,
"start": 7242,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session {:current-user-id (user/id \"[email protected]\")}}\n (h/decode :transit body)))))\n\n ",
"end": 7413,
"score": 0.9998830556869507,
"start": 7380,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[request (h/request\n {:session \"[email protected]\"\n :metadata {:authorisations\n ",
"end": 7642,
"score": 0.9999244213104248,
"start": 7609,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (authorisation/id (user/id \"[email protected]\") \"some-phrase\")}}\n :query {:a",
"end": 7865,
"score": 0.9999157190322876,
"start": 7832,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :session {:current-user-id (user/id \"[email protected]\")}}\n (h/decode :transit body))))))\n",
"end": 8298,
"score": 0.9999204277992249,
"start": 8265,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
api/test/feature/flow/query/authorisations_test.clj
|
kgxsz/flow
| 0 |
(ns flow.query.authorisations-test
(:require [flow.core :refer :all]
[flow.entity.authorisation :as authorisation]
[flow.entity.user :as user]
[flow.helpers :as h]
[clojure.test :refer :all]))
(defn setup
[]
(h/create-test-user! "[email protected]")
(h/create-test-user! "[email protected]" "Test" #{:customer :admin})
(h/create-test-authorisation! (user/id "[email protected]") "some-phrase")
(h/create-test-authorisation! (user/id "[email protected]") "some-other-phrase")
(h/create-test-authorisation! (user/id "[email protected]") "some-phrase"))
(defn fixture [test]
(h/ensure-empty-table)
(setup)
(test)
(h/ensure-empty-table))
(use-fixtures :each fixture)
(deftest test-authorisations
(testing "The handler negotiates the authorisations query when no session is provided."
(let [request (h/request {:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an unauthorised session is provided."
(let [request (h/request
{:session :unauthorised
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session is provided
for a user with a customer role."
(let [request (h/request
{:session "[email protected]"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id (user/id "[email protected]")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session for a user
with both a customer and admin role is provided."
(let [request (h/request
{:session "[email protected]"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "[email protected]") "some-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "[email protected]") "some-other-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "[email protected]") "some-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata {:authorisations
{:next-offset (authorisation/id (user/id "[email protected]") "some-phrase")
:exhausted? true}}
:session {:current-user-id (user/id "[email protected]")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when a limit is provided"
(let [request (h/request
{:session "[email protected]"
:metadata {:authorisations {:limit 2 :offset nil}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "[email protected]") "some-other-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "[email protected]") "some-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata
{:authorisations
{:next-offset (authorisation/id (user/id "[email protected]") "some-other-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "[email protected]")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an offset is provided"
(let [request (h/request
{:session "[email protected]"
:metadata {:authorisations
{:limit 1
:offset
(authorisation/id (user/id "[email protected]") "some-other-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "[email protected]") "some-phrase")
(-> (user/id "[email protected]")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))}
:metadata
{:authorisations
{:next-offset
(authorisation/id (user/id "[email protected]") "some-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "[email protected]")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when there's no items left."
(let [request (h/request
{:session "[email protected]"
:metadata {:authorisations
{:limit 2
:offset
(authorisation/id (user/id "[email protected]") "some-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata
{:authorisations {:next-offset nil
:exhausted? true}}
:session {:current-user-id (user/id "[email protected]")}}
(h/decode :transit body))))))
|
5334
|
(ns flow.query.authorisations-test
(:require [flow.core :refer :all]
[flow.entity.authorisation :as authorisation]
[flow.entity.user :as user]
[flow.helpers :as h]
[clojure.test :refer :all]))
(defn setup
[]
(h/create-test-user! "<EMAIL>")
(h/create-test-user! "<EMAIL>" "Test" #{:customer :admin})
(h/create-test-authorisation! (user/id "<EMAIL>") "some-phrase")
(h/create-test-authorisation! (user/id "<EMAIL>") "some-other-phrase")
(h/create-test-authorisation! (user/id "<EMAIL>") "some-phrase"))
(defn fixture [test]
(h/ensure-empty-table)
(setup)
(test)
(h/ensure-empty-table))
(use-fixtures :each fixture)
(deftest test-authorisations
(testing "The handler negotiates the authorisations query when no session is provided."
(let [request (h/request {:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an unauthorised session is provided."
(let [request (h/request
{:session :unauthorised
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session is provided
for a user with a customer role."
(let [request (h/request
{:session "<EMAIL>"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id (user/id "<EMAIL>")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session for a user
with both a customer and admin role is provided."
(let [request (h/request
{:session "<EMAIL>"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "<EMAIL>") "some-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "<EMAIL>") "some-other-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "<EMAIL>") "some-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata {:authorisations
{:next-offset (authorisation/id (user/id "<EMAIL>") "some-phrase")
:exhausted? true}}
:session {:current-user-id (user/id "<EMAIL>")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when a limit is provided"
(let [request (h/request
{:session "<EMAIL>"
:metadata {:authorisations {:limit 2 :offset nil}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "<EMAIL>") "some-other-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "<EMAIL>") "some-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata
{:authorisations
{:next-offset (authorisation/id (user/id "<EMAIL>") "some-other-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "<EMAIL>")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an offset is provided"
(let [request (h/request
{:session "<EMAIL>"
:metadata {:authorisations
{:limit 1
:offset
(authorisation/id (user/id "<EMAIL>") "some-other-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "<EMAIL>") "some-phrase")
(-> (user/id "<EMAIL>")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))}
:metadata
{:authorisations
{:next-offset
(authorisation/id (user/id "<EMAIL>") "some-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "<EMAIL>")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when there's no items left."
(let [request (h/request
{:session "<EMAIL>"
:metadata {:authorisations
{:limit 2
:offset
(authorisation/id (user/id "<EMAIL>") "some-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata
{:authorisations {:next-offset nil
:exhausted? true}}
:session {:current-user-id (user/id "<EMAIL>")}}
(h/decode :transit body))))))
| true |
(ns flow.query.authorisations-test
(:require [flow.core :refer :all]
[flow.entity.authorisation :as authorisation]
[flow.entity.user :as user]
[flow.helpers :as h]
[clojure.test :refer :all]))
(defn setup
[]
(h/create-test-user! "PI:EMAIL:<EMAIL>END_PI")
(h/create-test-user! "PI:EMAIL:<EMAIL>END_PI" "Test" #{:customer :admin})
(h/create-test-authorisation! (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
(h/create-test-authorisation! (user/id "PI:EMAIL:<EMAIL>END_PI") "some-other-phrase")
(h/create-test-authorisation! (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase"))
(defn fixture [test]
(h/ensure-empty-table)
(setup)
(test)
(h/ensure-empty-table))
(use-fixtures :each fixture)
(deftest test-authorisations
(testing "The handler negotiates the authorisations query when no session is provided."
(let [request (h/request {:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an unauthorised session is provided."
(let [request (h/request
{:session :unauthorised
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id nil}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session is provided
for a user with a customer role."
(let [request (h/request
{:session "PI:EMAIL:<EMAIL>END_PI"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata {}
:session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an authorised session for a user
with both a customer and admin role is provided."
(let [request (h/request
{:session "PI:EMAIL:<EMAIL>END_PI"
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-other-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata {:authorisations
{:next-offset (authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
:exhausted? true}}
:session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when a limit is provided"
(let [request (h/request
{:session "PI:EMAIL:<EMAIL>END_PI"
:metadata {:authorisations {:limit 2 :offset nil}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-other-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-other-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:owner :customer :admin}])))}
:metadata
{:authorisations
{:next-offset (authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-other-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when an offset is provided"
(let [request (h/request
{:session "PI:EMAIL:<EMAIL>END_PI"
:metadata {:authorisations
{:limit 1
:offset
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-other-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
(-> (user/id "PI:EMAIL:<EMAIL>END_PI")
(authorisation/id "some-phrase")
(authorisation/fetch)
(select-keys (get-in h/accessible-keys [:authorisation #{:customer :admin}])))}
:metadata
{:authorisations
{:next-offset
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")
:exhausted? false}}
:session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}}
(h/decode :transit body)))))
(testing "The handler negotiates the authorisations query when there's no items left."
(let [request (h/request
{:session "PI:EMAIL:<EMAIL>END_PI"
:metadata {:authorisations
{:limit 2
:offset
(authorisation/id (user/id "PI:EMAIL:<EMAIL>END_PI") "some-phrase")}}
:query {:authorisations {}}})
{:keys [status headers body] :as response} (handler request)]
(is (= 200 status))
(is (= {:users {}
:authorisations {}
:metadata
{:authorisations {:next-offset nil
:exhausted? true}}
:session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}}
(h/decode :transit body))))))
|
[
{
"context": "s \"Hello\" from client, replies with \"World\"\n;;\n;; Isaiah Peng <[email protected]>\n;;\n\n(ns hwserver\n (:refer-cl",
"end": 146,
"score": 0.9998601078987122,
"start": 135,
"tag": "NAME",
"value": "Isaiah Peng"
},
{
"context": " client, replies with \"World\"\n;;\n;; Isaiah Peng <[email protected]>\n;;\n\n(ns hwserver\n (:refer-clojure :exclude [sen",
"end": 165,
"score": 0.9999201893806458,
"start": 148,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
docs/zeroMQ-guide2/examples/Clojure/hwserver.clj
|
krattai/noo-ebs
| 2 |
;;
;; Hello World server in Clojure
;; Binds REP socket to tcp://*:5555
;; Expects "Hello" from client, replies with "World"
;;
;; Isaiah Peng <[email protected]>
;;
(ns hwserver
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq]))
(defn -main []
(let [sock (-> 1 mq/context (mq/socket mq/rep))]
(mq/bind sock "tcp://*:5555")
(while true
(let [req (mq/recv-str sock)
reply "World\u0000"]
(println (str "Received request: [ " req " ]"))
;; Do some 'work'
(Thread/sleep 1000)
;; Send reply back to client
;; We will send a 0-terminated string (C string) back to the client,
;; so that this server also works with The Guide's C and C++ "Hello World" clients
(mq/send sock reply))
)))
|
55002
|
;;
;; Hello World server in Clojure
;; Binds REP socket to tcp://*:5555
;; Expects "Hello" from client, replies with "World"
;;
;; <NAME> <<EMAIL>>
;;
(ns hwserver
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq]))
(defn -main []
(let [sock (-> 1 mq/context (mq/socket mq/rep))]
(mq/bind sock "tcp://*:5555")
(while true
(let [req (mq/recv-str sock)
reply "World\u0000"]
(println (str "Received request: [ " req " ]"))
;; Do some 'work'
(Thread/sleep 1000)
;; Send reply back to client
;; We will send a 0-terminated string (C string) back to the client,
;; so that this server also works with The Guide's C and C++ "Hello World" clients
(mq/send sock reply))
)))
| true |
;;
;; Hello World server in Clojure
;; Binds REP socket to tcp://*:5555
;; Expects "Hello" from client, replies with "World"
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
(ns hwserver
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq]))
(defn -main []
(let [sock (-> 1 mq/context (mq/socket mq/rep))]
(mq/bind sock "tcp://*:5555")
(while true
(let [req (mq/recv-str sock)
reply "World\u0000"]
(println (str "Received request: [ " req " ]"))
;; Do some 'work'
(Thread/sleep 1000)
;; Send reply back to client
;; We will send a 0-terminated string (C string) back to the client,
;; so that this server also works with The Guide's C and C++ "Hello World" clients
(mq/send sock reply))
)))
|
[
{
"context": "t [ msg ]\n (.get xhr (str \"http://admin:[email protected]:5984/\" msg)\n (fn [err res body]\n ",
"end": 513,
"score": 0.9997073411941528,
"start": 504,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "t [ msg ]\n (.put xhr (str \"http://admin:[email protected]:5984/\" msg)\n (fn [err res body]\n ",
"end": 663,
"score": 0.9997267127037048,
"start": 654,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " \"url\" (str \"http://admin:[email protected]:5984/\"\n database\n ",
"end": 860,
"score": 0.9997448921203613,
"start": 846,
"tag": "IP_ADDRESS",
"value": "35.212.206.166"
}
] |
src/server/util.cljs
|
tecumsehcommunications/Website
| 0 |
(ns server.util
(:require [cljs.nodejs :as node])
(:import goog.dom))
(def root "/usr/local/lib/node_modules/")
; (def fs (node/require "fs"))
; (def gm (node/require (str root "gm")))
; (def parser (node/require (str root "node-html-parser")))
(def mongodb (node/require (str root "mongodb")))
(def wss (node/require (str root "ws")))
(def uidgen (node/require (str root "uuid")))
(def xhr (node/require (str root "request")))
(defn couchGet [ msg ]
(.get xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn couchPut [ msg ]
(.put xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn createDoc [ database docObj ]
(.put xhr (js-obj
"url" (str "http://admin:[email protected]:5984/"
database
"/"
(.replace clojure.string (.v4 uidgen) "-" ""))
"body" (.stringify js/JSON docObj))))
(defn getCards []
(.get xhr "http://127.0.0.1:5984/flashcards/_design/dDoc1/_view/v1"
(fn [ err res body ] (.log js/console body))))
(getCards)
(do
(def c1 (js-obj "seqno" 1 "english" "person" "pinyin" "rén" "chinese" "人"))
(def c2 (js-obj "seqno" 2 "english" "knife" "pinyin" "dāo" "chinese" "刀"))
(def c3 (js-obj "seqno" 3 "english" "power" "pinyin" "lì" "chinese" "力"))
(def c4 (js-obj "seqno" 4 "english" "right hand; again" "pinyin" "yòu" "chinese" "又"))
(def c5 (js-obj "seqno" 5 "english" "mouth" "pinyin" "kǒu" "chinese" "口"))
(def c6 (js-obj "seqno" 6 "english" "enclose" "pinyin" "wéi" "chinese" "囗"))
(def c7 (js-obj "seqno" 7 "english" "earth" "pinyin" "tǔ" "chinese" "土"))
(def c8 (js-obj "seqno" 8 "english" "sunset" "pinyin" "xī" "chinese" "夕"))
(def c9 (js-obj "seqno" 9 "english" "big" "pinyin" "dà" "chinese" "大"))
(def c10 (js-obj "seqno" 10 "english" "woman" "pinyin" "nǚ" "chinese" "女"))
(def c11 (js-obj "seqno" 11 "english" "son" "pinyin" "zǐ" "chinese" "子"))
(def c12 (js-obj "seqno" 12 "english" "inch" "pinyin" "cùn" "chinese" "寸"))
(def c13 (js-obj "seqno" 13 "english" "small" "pinyin" "xiǎo" "chinese" "小"))
(def c14 (js-obj "seqno" 14 "english" "labor; work" "gōng" "tǔ" "chinese" "工"))
(def c15 (js-obj "seqno" 15 "english" "tiny; small" "pinyin" "yāo" "chinese" "幺"))
(def c16 (js-obj "seqno" 16 "english" "bow" "pinyin" "gōng" "chinese" "弓"))
(def c17 (js-obj "seqno" 17 "english" "heart" "pinyin" "xīn" "chinese" "心"))
(def c18 (js-obj "seqno" 18 "english" "dagger-axe" "pinyin" "gē" "chinese" "戈"))
(def c19 (js-obj "seqno" 19 "english" "hand" "pinyin" "shǒu" "chinese" "手"))
(def c20 (js-obj "seqno" 20 "english" "sun" "pinyin" "rì" "chinese" "日"))
(def c21 (js-obj "seqno" 21 "english" "moon" "pinyin" "yuè" "chinese" "月"))
(def c22 (js-obj "seqno" 22 "english" "wood" "pinyin" "mù" "chinese" "木"))
(def c23 (js-obj "seqno" 23 "english" "water" "pinyin" "shuǐ" "chinese" "水"))
(def c24 (js-obj "seqno" 24 "english" "fire" "pinyin" "huǒ" "chinese" "火"))
(def c25 (js-obj "seqno" 25 "english" "field" "pinyin" "tián" "chinese" "田"))
(def c26 (js-obj "seqno" 26 "english" "eye" "pinyin" "mù" "chinese" "目"))
(def c27 (js-obj "seqno" 27 "english" "show" "pinyin" "shì" "chinese" "示"))
(def c28 (js-obj "seqno" 28 "english" "fine silk" "pinyin" "mì" "chinese" "纟"))
)
(createDoc "cards" c28)
(couchGet "_all_dbs")
(def livereload (node/require (str root "livereload")))
(defn livereload-on [ directory ]
(let [ lrServer (.createServer livereload
(js-obj "exts"
(array "html" "svg" "css" "png" "jpg" "gif")))
fileWatcher (.watch lrServer directory) ]))
(def lrHandle (livereload-on "/var/www/html/"))
;;;;
(def mongoClient (. mongodb -MongoClient))
(def mongoURL "mongodb://localhost:27017")
(def dbClient (new mongoClient mongoURL))
(.then (.connect dbClient) (.log js/console "successful db connection"))
(def db (.db dbClient "flashcards"))(d
(def collection (.collection db "documents"))
(.insertOne collection (def mike #js {:_id "4EBA" :pinyin "ren" :english "person" } )
(def mike (.find collection #js {:_id "4EBA"}))
(.each mike (fn [ err item] (.log js/console item)))
(.close db)
(js-obj
(defn newWss [ port ]
(new wss.Server (js-obj "port" port)))
(deftype noradImageFetcher [ tempDir archive ] Object
(init [ this time ]
(set! this.time (str time))
(set! this.wrkTime (str nil))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.baseUrl "https://radar.weather.gov/RadarImg/N0R/BHX/")
(set! this.reqObject (js-obj
"headers" (js-obj
"Host" "radar.weather.gov"
"User-Agent" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"
"Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"Accept-Language" "en-US,en;q=0.5"
"Connection" "keep-alive"
"Upgrade-Insecure-Requests" 1)))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pic in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs
(str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.baseUrl
this.reqObject
(fn [err res body]
(if err
(do
(js.console.log "norad page request error")
(set! this.sleepTime 60000) ; wait a minute and try again)
(.queue this))
(let [ tableRows (.reverse ; reversing table to start at bottom
(goog.dom.getChildren
(.querySelector (parser.parse body) "table")))
goodTable (.slice tableRows 0 (- (. tableRows -length) 3 )) ]
(loop [ cnt 1 ]
(if (and (< cnt 20 ) (aget goodTable cnt))
(let [ name (.-innerHTML (goog.dom.getFirstElementChild
(aget (goog.dom.getChildren
(aget goodTable cnt)) 1)))
year (.substring name 4 8)
month (.substring name 8 10)
day (.substring name 10 12)
time (.substring name 13 17)
url (str this.baseUrl name)
tempfile (str this.tempDir "norad-" cnt ".gif")
fname (str this.archive year month day time ".png") ]
(if (= 1 cnt) (set! this.wrkTime time))
(if (= this.wrkTime this.time)
(set! this.sleepTime 300000)
(do
(.pipe
(request.get
(str this.baseUrl name)
this.reqObject)
(.on
(fs.createWriteStream tempfile)
"finish"
(fn []
(js.console.log "tempfile name: " tempfile)
(.write
(.resize
(.rotate
; (.resize
(gm tempfile)
; 1600 1100)
"transparent" -12.5)
1024 1024 "!")
fname
(fn [err]
(if err
(do (js.console.log "norad image write error")
(js.console.log err)))
(.unlink fs tempfile this.stdErr))))))
(recur (inc cnt)))))))
(set! this.sleepTime 300000)
(set! this.time this.wrkTime)
(.scrubDir this)
(.queue this )))))))
(deftype geosImageFetcher [ tempDir archive ] Object
; require node filesystem (as fs) and node request as rs in scope
(init [this time ]
(set! this.time (str time))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.reqString "https://weather.msfc.nasa.gov/cgi-bin/get-abi?satellite=GOESWestconusband02&lat=40.4&lon=-124.0&zoom=1&width=558&height=992&quality=100&mapcolor=yellow")
(set! this.urlPrefix "https://weather.msfc.nasa.gov")
(set! this.tempFile (str tempDir "nasageo.jpg"))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pics in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs (str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.reqString
(fn [err res body]
(if err
(do
(js.console.log "geos satellite picture request error")
(set! this.sleepTime 60000)
(.queue this))
(let [ start (+ 1 (.indexOf body "\"" (.indexOf body "<IMG")))
end (.indexOf body "\"" start)
srcStr (.substring body start end)
fnStart (+ (.indexOf srcStr "/GOES") 5)
time (.substring srcStr fnStart (+ fnStart 4))
year (.substring srcStr (+ fnStart 4) (+ 8 fnStart))
day (.substring srcStr (+ fnStart 8) (+ 11 fnStart))
url (str "https://weather.msfc.nasa.gov" srcStr )
fname (str this.archive year day time ".jpg") ]
(if (= time this.time)
(do
(set! this.sleepTime 60000) ; try again in one minute
(.queue this))
(do
(set! this.sleepTime 300000) ; five minute wait
(set! this.time time)
(.pipe
(request url)
(.on
(fs.createWriteStream this.tempFile)
"finish"
(fn []
(.write
(.resize
(.crop
(gm this.tempFile)
558
932
0
60)
512 512 "!")
fname
(fn [err]
(if err
(do
(js.console.log "nasa image write error")
(js.console.log err))
(do
(.scrubDir this)
(.queue this))))))))))))))))
|
100083
|
(ns server.util
(:require [cljs.nodejs :as node])
(:import goog.dom))
(def root "/usr/local/lib/node_modules/")
; (def fs (node/require "fs"))
; (def gm (node/require (str root "gm")))
; (def parser (node/require (str root "node-html-parser")))
(def mongodb (node/require (str root "mongodb")))
(def wss (node/require (str root "ws")))
(def uidgen (node/require (str root "uuid")))
(def xhr (node/require (str root "request")))
(defn couchGet [ msg ]
(.get xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn couchPut [ msg ]
(.put xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn createDoc [ database docObj ]
(.put xhr (js-obj
"url" (str "http://admin:[email protected]:5984/"
database
"/"
(.replace clojure.string (.v4 uidgen) "-" ""))
"body" (.stringify js/JSON docObj))))
(defn getCards []
(.get xhr "http://127.0.0.1:5984/flashcards/_design/dDoc1/_view/v1"
(fn [ err res body ] (.log js/console body))))
(getCards)
(do
(def c1 (js-obj "seqno" 1 "english" "person" "pinyin" "rén" "chinese" "人"))
(def c2 (js-obj "seqno" 2 "english" "knife" "pinyin" "dāo" "chinese" "刀"))
(def c3 (js-obj "seqno" 3 "english" "power" "pinyin" "lì" "chinese" "力"))
(def c4 (js-obj "seqno" 4 "english" "right hand; again" "pinyin" "yòu" "chinese" "又"))
(def c5 (js-obj "seqno" 5 "english" "mouth" "pinyin" "kǒu" "chinese" "口"))
(def c6 (js-obj "seqno" 6 "english" "enclose" "pinyin" "wéi" "chinese" "囗"))
(def c7 (js-obj "seqno" 7 "english" "earth" "pinyin" "tǔ" "chinese" "土"))
(def c8 (js-obj "seqno" 8 "english" "sunset" "pinyin" "xī" "chinese" "夕"))
(def c9 (js-obj "seqno" 9 "english" "big" "pinyin" "dà" "chinese" "大"))
(def c10 (js-obj "seqno" 10 "english" "woman" "pinyin" "nǚ" "chinese" "女"))
(def c11 (js-obj "seqno" 11 "english" "son" "pinyin" "zǐ" "chinese" "子"))
(def c12 (js-obj "seqno" 12 "english" "inch" "pinyin" "cùn" "chinese" "寸"))
(def c13 (js-obj "seqno" 13 "english" "small" "pinyin" "xiǎo" "chinese" "小"))
(def c14 (js-obj "seqno" 14 "english" "labor; work" "gōng" "tǔ" "chinese" "工"))
(def c15 (js-obj "seqno" 15 "english" "tiny; small" "pinyin" "yāo" "chinese" "幺"))
(def c16 (js-obj "seqno" 16 "english" "bow" "pinyin" "gōng" "chinese" "弓"))
(def c17 (js-obj "seqno" 17 "english" "heart" "pinyin" "xīn" "chinese" "心"))
(def c18 (js-obj "seqno" 18 "english" "dagger-axe" "pinyin" "gē" "chinese" "戈"))
(def c19 (js-obj "seqno" 19 "english" "hand" "pinyin" "shǒu" "chinese" "手"))
(def c20 (js-obj "seqno" 20 "english" "sun" "pinyin" "rì" "chinese" "日"))
(def c21 (js-obj "seqno" 21 "english" "moon" "pinyin" "yuè" "chinese" "月"))
(def c22 (js-obj "seqno" 22 "english" "wood" "pinyin" "mù" "chinese" "木"))
(def c23 (js-obj "seqno" 23 "english" "water" "pinyin" "shuǐ" "chinese" "水"))
(def c24 (js-obj "seqno" 24 "english" "fire" "pinyin" "huǒ" "chinese" "火"))
(def c25 (js-obj "seqno" 25 "english" "field" "pinyin" "tián" "chinese" "田"))
(def c26 (js-obj "seqno" 26 "english" "eye" "pinyin" "mù" "chinese" "目"))
(def c27 (js-obj "seqno" 27 "english" "show" "pinyin" "shì" "chinese" "示"))
(def c28 (js-obj "seqno" 28 "english" "fine silk" "pinyin" "mì" "chinese" "纟"))
)
(createDoc "cards" c28)
(couchGet "_all_dbs")
(def livereload (node/require (str root "livereload")))
(defn livereload-on [ directory ]
(let [ lrServer (.createServer livereload
(js-obj "exts"
(array "html" "svg" "css" "png" "jpg" "gif")))
fileWatcher (.watch lrServer directory) ]))
(def lrHandle (livereload-on "/var/www/html/"))
;;;;
(def mongoClient (. mongodb -MongoClient))
(def mongoURL "mongodb://localhost:27017")
(def dbClient (new mongoClient mongoURL))
(.then (.connect dbClient) (.log js/console "successful db connection"))
(def db (.db dbClient "flashcards"))(d
(def collection (.collection db "documents"))
(.insertOne collection (def mike #js {:_id "4EBA" :pinyin "ren" :english "person" } )
(def mike (.find collection #js {:_id "4EBA"}))
(.each mike (fn [ err item] (.log js/console item)))
(.close db)
(js-obj
(defn newWss [ port ]
(new wss.Server (js-obj "port" port)))
(deftype noradImageFetcher [ tempDir archive ] Object
(init [ this time ]
(set! this.time (str time))
(set! this.wrkTime (str nil))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.baseUrl "https://radar.weather.gov/RadarImg/N0R/BHX/")
(set! this.reqObject (js-obj
"headers" (js-obj
"Host" "radar.weather.gov"
"User-Agent" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"
"Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"Accept-Language" "en-US,en;q=0.5"
"Connection" "keep-alive"
"Upgrade-Insecure-Requests" 1)))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pic in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs
(str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.baseUrl
this.reqObject
(fn [err res body]
(if err
(do
(js.console.log "norad page request error")
(set! this.sleepTime 60000) ; wait a minute and try again)
(.queue this))
(let [ tableRows (.reverse ; reversing table to start at bottom
(goog.dom.getChildren
(.querySelector (parser.parse body) "table")))
goodTable (.slice tableRows 0 (- (. tableRows -length) 3 )) ]
(loop [ cnt 1 ]
(if (and (< cnt 20 ) (aget goodTable cnt))
(let [ name (.-innerHTML (goog.dom.getFirstElementChild
(aget (goog.dom.getChildren
(aget goodTable cnt)) 1)))
year (.substring name 4 8)
month (.substring name 8 10)
day (.substring name 10 12)
time (.substring name 13 17)
url (str this.baseUrl name)
tempfile (str this.tempDir "norad-" cnt ".gif")
fname (str this.archive year month day time ".png") ]
(if (= 1 cnt) (set! this.wrkTime time))
(if (= this.wrkTime this.time)
(set! this.sleepTime 300000)
(do
(.pipe
(request.get
(str this.baseUrl name)
this.reqObject)
(.on
(fs.createWriteStream tempfile)
"finish"
(fn []
(js.console.log "tempfile name: " tempfile)
(.write
(.resize
(.rotate
; (.resize
(gm tempfile)
; 1600 1100)
"transparent" -12.5)
1024 1024 "!")
fname
(fn [err]
(if err
(do (js.console.log "norad image write error")
(js.console.log err)))
(.unlink fs tempfile this.stdErr))))))
(recur (inc cnt)))))))
(set! this.sleepTime 300000)
(set! this.time this.wrkTime)
(.scrubDir this)
(.queue this )))))))
(deftype geosImageFetcher [ tempDir archive ] Object
; require node filesystem (as fs) and node request as rs in scope
(init [this time ]
(set! this.time (str time))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.reqString "https://weather.msfc.nasa.gov/cgi-bin/get-abi?satellite=GOESWestconusband02&lat=40.4&lon=-124.0&zoom=1&width=558&height=992&quality=100&mapcolor=yellow")
(set! this.urlPrefix "https://weather.msfc.nasa.gov")
(set! this.tempFile (str tempDir "nasageo.jpg"))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pics in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs (str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.reqString
(fn [err res body]
(if err
(do
(js.console.log "geos satellite picture request error")
(set! this.sleepTime 60000)
(.queue this))
(let [ start (+ 1 (.indexOf body "\"" (.indexOf body "<IMG")))
end (.indexOf body "\"" start)
srcStr (.substring body start end)
fnStart (+ (.indexOf srcStr "/GOES") 5)
time (.substring srcStr fnStart (+ fnStart 4))
year (.substring srcStr (+ fnStart 4) (+ 8 fnStart))
day (.substring srcStr (+ fnStart 8) (+ 11 fnStart))
url (str "https://weather.msfc.nasa.gov" srcStr )
fname (str this.archive year day time ".jpg") ]
(if (= time this.time)
(do
(set! this.sleepTime 60000) ; try again in one minute
(.queue this))
(do
(set! this.sleepTime 300000) ; five minute wait
(set! this.time time)
(.pipe
(request url)
(.on
(fs.createWriteStream this.tempFile)
"finish"
(fn []
(.write
(.resize
(.crop
(gm this.tempFile)
558
932
0
60)
512 512 "!")
fname
(fn [err]
(if err
(do
(js.console.log "nasa image write error")
(js.console.log err))
(do
(.scrubDir this)
(.queue this))))))))))))))))
| true |
(ns server.util
(:require [cljs.nodejs :as node])
(:import goog.dom))
(def root "/usr/local/lib/node_modules/")
; (def fs (node/require "fs"))
; (def gm (node/require (str root "gm")))
; (def parser (node/require (str root "node-html-parser")))
(def mongodb (node/require (str root "mongodb")))
(def wss (node/require (str root "ws")))
(def uidgen (node/require (str root "uuid")))
(def xhr (node/require (str root "request")))
(defn couchGet [ msg ]
(.get xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn couchPut [ msg ]
(.put xhr (str "http://admin:[email protected]:5984/" msg)
(fn [err res body]
(.log js/console body))))
(defn createDoc [ database docObj ]
(.put xhr (js-obj
"url" (str "http://admin:Pa$$w0rd@PI:IP_ADDRESS:172.16.31.10END_PI:5984/"
database
"/"
(.replace clojure.string (.v4 uidgen) "-" ""))
"body" (.stringify js/JSON docObj))))
(defn getCards []
(.get xhr "http://127.0.0.1:5984/flashcards/_design/dDoc1/_view/v1"
(fn [ err res body ] (.log js/console body))))
(getCards)
(do
(def c1 (js-obj "seqno" 1 "english" "person" "pinyin" "rén" "chinese" "人"))
(def c2 (js-obj "seqno" 2 "english" "knife" "pinyin" "dāo" "chinese" "刀"))
(def c3 (js-obj "seqno" 3 "english" "power" "pinyin" "lì" "chinese" "力"))
(def c4 (js-obj "seqno" 4 "english" "right hand; again" "pinyin" "yòu" "chinese" "又"))
(def c5 (js-obj "seqno" 5 "english" "mouth" "pinyin" "kǒu" "chinese" "口"))
(def c6 (js-obj "seqno" 6 "english" "enclose" "pinyin" "wéi" "chinese" "囗"))
(def c7 (js-obj "seqno" 7 "english" "earth" "pinyin" "tǔ" "chinese" "土"))
(def c8 (js-obj "seqno" 8 "english" "sunset" "pinyin" "xī" "chinese" "夕"))
(def c9 (js-obj "seqno" 9 "english" "big" "pinyin" "dà" "chinese" "大"))
(def c10 (js-obj "seqno" 10 "english" "woman" "pinyin" "nǚ" "chinese" "女"))
(def c11 (js-obj "seqno" 11 "english" "son" "pinyin" "zǐ" "chinese" "子"))
(def c12 (js-obj "seqno" 12 "english" "inch" "pinyin" "cùn" "chinese" "寸"))
(def c13 (js-obj "seqno" 13 "english" "small" "pinyin" "xiǎo" "chinese" "小"))
(def c14 (js-obj "seqno" 14 "english" "labor; work" "gōng" "tǔ" "chinese" "工"))
(def c15 (js-obj "seqno" 15 "english" "tiny; small" "pinyin" "yāo" "chinese" "幺"))
(def c16 (js-obj "seqno" 16 "english" "bow" "pinyin" "gōng" "chinese" "弓"))
(def c17 (js-obj "seqno" 17 "english" "heart" "pinyin" "xīn" "chinese" "心"))
(def c18 (js-obj "seqno" 18 "english" "dagger-axe" "pinyin" "gē" "chinese" "戈"))
(def c19 (js-obj "seqno" 19 "english" "hand" "pinyin" "shǒu" "chinese" "手"))
(def c20 (js-obj "seqno" 20 "english" "sun" "pinyin" "rì" "chinese" "日"))
(def c21 (js-obj "seqno" 21 "english" "moon" "pinyin" "yuè" "chinese" "月"))
(def c22 (js-obj "seqno" 22 "english" "wood" "pinyin" "mù" "chinese" "木"))
(def c23 (js-obj "seqno" 23 "english" "water" "pinyin" "shuǐ" "chinese" "水"))
(def c24 (js-obj "seqno" 24 "english" "fire" "pinyin" "huǒ" "chinese" "火"))
(def c25 (js-obj "seqno" 25 "english" "field" "pinyin" "tián" "chinese" "田"))
(def c26 (js-obj "seqno" 26 "english" "eye" "pinyin" "mù" "chinese" "目"))
(def c27 (js-obj "seqno" 27 "english" "show" "pinyin" "shì" "chinese" "示"))
(def c28 (js-obj "seqno" 28 "english" "fine silk" "pinyin" "mì" "chinese" "纟"))
)
(createDoc "cards" c28)
(couchGet "_all_dbs")
(def livereload (node/require (str root "livereload")))
(defn livereload-on [ directory ]
(let [ lrServer (.createServer livereload
(js-obj "exts"
(array "html" "svg" "css" "png" "jpg" "gif")))
fileWatcher (.watch lrServer directory) ]))
(def lrHandle (livereload-on "/var/www/html/"))
;;;;
(def mongoClient (. mongodb -MongoClient))
(def mongoURL "mongodb://localhost:27017")
(def dbClient (new mongoClient mongoURL))
(.then (.connect dbClient) (.log js/console "successful db connection"))
(def db (.db dbClient "flashcards"))(d
(def collection (.collection db "documents"))
(.insertOne collection (def mike #js {:_id "4EBA" :pinyin "ren" :english "person" } )
(def mike (.find collection #js {:_id "4EBA"}))
(.each mike (fn [ err item] (.log js/console item)))
(.close db)
(js-obj
(defn newWss [ port ]
(new wss.Server (js-obj "port" port)))
(deftype noradImageFetcher [ tempDir archive ] Object
(init [ this time ]
(set! this.time (str time))
(set! this.wrkTime (str nil))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.baseUrl "https://radar.weather.gov/RadarImg/N0R/BHX/")
(set! this.reqObject (js-obj
"headers" (js-obj
"Host" "radar.weather.gov"
"User-Agent" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"
"Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"Accept-Language" "en-US,en;q=0.5"
"Connection" "keep-alive"
"Upgrade-Insecure-Requests" 1)))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pic in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs
(str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.baseUrl
this.reqObject
(fn [err res body]
(if err
(do
(js.console.log "norad page request error")
(set! this.sleepTime 60000) ; wait a minute and try again)
(.queue this))
(let [ tableRows (.reverse ; reversing table to start at bottom
(goog.dom.getChildren
(.querySelector (parser.parse body) "table")))
goodTable (.slice tableRows 0 (- (. tableRows -length) 3 )) ]
(loop [ cnt 1 ]
(if (and (< cnt 20 ) (aget goodTable cnt))
(let [ name (.-innerHTML (goog.dom.getFirstElementChild
(aget (goog.dom.getChildren
(aget goodTable cnt)) 1)))
year (.substring name 4 8)
month (.substring name 8 10)
day (.substring name 10 12)
time (.substring name 13 17)
url (str this.baseUrl name)
tempfile (str this.tempDir "norad-" cnt ".gif")
fname (str this.archive year month day time ".png") ]
(if (= 1 cnt) (set! this.wrkTime time))
(if (= this.wrkTime this.time)
(set! this.sleepTime 300000)
(do
(.pipe
(request.get
(str this.baseUrl name)
this.reqObject)
(.on
(fs.createWriteStream tempfile)
"finish"
(fn []
(js.console.log "tempfile name: " tempfile)
(.write
(.resize
(.rotate
; (.resize
(gm tempfile)
; 1600 1100)
"transparent" -12.5)
1024 1024 "!")
fname
(fn [err]
(if err
(do (js.console.log "norad image write error")
(js.console.log err)))
(.unlink fs tempfile this.stdErr))))))
(recur (inc cnt)))))))
(set! this.sleepTime 300000)
(set! this.time this.wrkTime)
(.scrubDir this)
(.queue this )))))))
(deftype geosImageFetcher [ tempDir archive ] Object
; require node filesystem (as fs) and node request as rs in scope
(init [this time ]
(set! this.time (str time))
(set! this.files "none")
(set! this.lastFile "none")
(set! this.timerHandle nil)
(set! this.reqString "https://weather.msfc.nasa.gov/cgi-bin/get-abi?satellite=GOESWestconusband02&lat=40.4&lon=-124.0&zoom=1&width=558&height=992&quality=100&mapcolor=yellow")
(set! this.urlPrefix "https://weather.msfc.nasa.gov")
(set! this.tempFile (str tempDir "nasageo.jpg"))
(set! this.sleepTime 300000) ; 5 mins in ms
(set! this.stdErr (fn [err] (if err (js.console.log err))))
this)
(queue [this]
(set! this.timerHandle (js.setTimeout (fn [] (.getPic this)) this.sleepTime)))
(dequeue [this]
(if this.timerHandle
(do
(js.clearTimeout this.timerHandle)
(set! this.timerHandle nil))))
(scrubDir [ this ]
(.readdir fs this.archive
(fn [err files] ; files is a js array
(let [ numFiles (- (.-length files) 1)
excess (- numFiles 61) ] ; no more than 61 pics in directory
(if (> excess 0)
(do
(set! this.files (.slice files (- excess 1) files.length))
(doseq [x (range excess) ]
(.unlink fs (str this.archive (aget files x)) this.stdErr)))
(set! this.files files))
(set! this.lastFile
(aget files
(- files.length 1)))))))
(getPic [this]
(request.get
this.reqString
(fn [err res body]
(if err
(do
(js.console.log "geos satellite picture request error")
(set! this.sleepTime 60000)
(.queue this))
(let [ start (+ 1 (.indexOf body "\"" (.indexOf body "<IMG")))
end (.indexOf body "\"" start)
srcStr (.substring body start end)
fnStart (+ (.indexOf srcStr "/GOES") 5)
time (.substring srcStr fnStart (+ fnStart 4))
year (.substring srcStr (+ fnStart 4) (+ 8 fnStart))
day (.substring srcStr (+ fnStart 8) (+ 11 fnStart))
url (str "https://weather.msfc.nasa.gov" srcStr )
fname (str this.archive year day time ".jpg") ]
(if (= time this.time)
(do
(set! this.sleepTime 60000) ; try again in one minute
(.queue this))
(do
(set! this.sleepTime 300000) ; five minute wait
(set! this.time time)
(.pipe
(request url)
(.on
(fs.createWriteStream this.tempFile)
"finish"
(fn []
(.write
(.resize
(.crop
(gm this.tempFile)
558
932
0
60)
512 512 "!")
fname
(fn [err]
(if err
(do
(js.console.log "nasa image write error")
(js.console.log err))
(do
(.scrubDir this)
(.queue this))))))))))))))))
|
[
{
"context": ";; Copyright (c) 2019, 2020 Will Cohen\n;;\n;; Licensed under the Apache License, Version ",
"end": 38,
"score": 0.9997742772102356,
"start": 28,
"tag": "NAME",
"value": "Will Cohen"
}
] |
src/aurelius/census.clj
|
willcohen/aurelius
| 10 |
;; Copyright (c) 2019, 2020 Will Cohen
;;
;; 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 aurelius.census
(:require [aurelius.db :as aurelius.db]
[aurelius.util :as u]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[hugsql.core :as hugsql]
[geo.io :as geo.io]
[geo.jts :as geo.jts]
[ovid.feature :as feature :refer [Featurelike]]))
(set! *warn-on-reflection* true)
(defn add-qcew-monthly-data
[r month]
(assoc r
:month (u/quarter->month (:year r) (:qtr r) month)
:emplvl ((keyword
(clojure.string/join ["month" month "_emplvl"])) r)
:lq_emplvl ((keyword
(clojure.string/join
["lq_month" month "_emplvl"])) r)
:oty_emplvl_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_chg"])) r)
:oty_emplvl_pct_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_pct_chg"])) r)))
(defn remove-qcew-monthly-data
[r]
(dissoc r :year :qtr
:month1_emplvl :month2_emplvl :month3_emplvl
:lq_month1_emplvl :lq_month2_emplvl :lq_month3_emplvl
:oty_month1_emplvl_chg
:oty_month2_emplvl_chg
:oty_month3_emplvl_chg
:oty_month1_emplvl_pct_chg
:oty_month2_emplvl_pct_chg
:oty_month3_emplvl_pct_chg))
(defn qcew-monthly-data
[r month]
(-> r
(add-qcew-monthly-data month)
remove-qcew-monthly-data))
(defn qcew-qtr->month
[r]
(map #(qcew-monthly-data r (inc %)) (range 3)))
|
25455
|
;; Copyright (c) 2019, 2020 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns aurelius.census
(:require [aurelius.db :as aurelius.db]
[aurelius.util :as u]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[hugsql.core :as hugsql]
[geo.io :as geo.io]
[geo.jts :as geo.jts]
[ovid.feature :as feature :refer [Featurelike]]))
(set! *warn-on-reflection* true)
(defn add-qcew-monthly-data
[r month]
(assoc r
:month (u/quarter->month (:year r) (:qtr r) month)
:emplvl ((keyword
(clojure.string/join ["month" month "_emplvl"])) r)
:lq_emplvl ((keyword
(clojure.string/join
["lq_month" month "_emplvl"])) r)
:oty_emplvl_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_chg"])) r)
:oty_emplvl_pct_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_pct_chg"])) r)))
(defn remove-qcew-monthly-data
[r]
(dissoc r :year :qtr
:month1_emplvl :month2_emplvl :month3_emplvl
:lq_month1_emplvl :lq_month2_emplvl :lq_month3_emplvl
:oty_month1_emplvl_chg
:oty_month2_emplvl_chg
:oty_month3_emplvl_chg
:oty_month1_emplvl_pct_chg
:oty_month2_emplvl_pct_chg
:oty_month3_emplvl_pct_chg))
(defn qcew-monthly-data
[r month]
(-> r
(add-qcew-monthly-data month)
remove-qcew-monthly-data))
(defn qcew-qtr->month
[r]
(map #(qcew-monthly-data r (inc %)) (range 3)))
| true |
;; Copyright (c) 2019, 2020 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns aurelius.census
(:require [aurelius.db :as aurelius.db]
[aurelius.util :as u]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[hugsql.core :as hugsql]
[geo.io :as geo.io]
[geo.jts :as geo.jts]
[ovid.feature :as feature :refer [Featurelike]]))
(set! *warn-on-reflection* true)
(defn add-qcew-monthly-data
[r month]
(assoc r
:month (u/quarter->month (:year r) (:qtr r) month)
:emplvl ((keyword
(clojure.string/join ["month" month "_emplvl"])) r)
:lq_emplvl ((keyword
(clojure.string/join
["lq_month" month "_emplvl"])) r)
:oty_emplvl_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_chg"])) r)
:oty_emplvl_pct_chg ((keyword
(clojure.string/join
["oty_month" month "_emplvl_pct_chg"])) r)))
(defn remove-qcew-monthly-data
[r]
(dissoc r :year :qtr
:month1_emplvl :month2_emplvl :month3_emplvl
:lq_month1_emplvl :lq_month2_emplvl :lq_month3_emplvl
:oty_month1_emplvl_chg
:oty_month2_emplvl_chg
:oty_month3_emplvl_chg
:oty_month1_emplvl_pct_chg
:oty_month2_emplvl_pct_chg
:oty_month3_emplvl_pct_chg))
(defn qcew-monthly-data
[r month]
(-> r
(add-qcew-monthly-data month)
remove-qcew-monthly-data))
(defn qcew-qtr->month
[r]
(map #(qcew-monthly-data r (inc %)) (range 3)))
|
[
{
"context": "ks like and feels like. Design is how it works. -- Steve Jobs\"))\n\n\n;; general card view om componnet\n(defn card",
"end": 3475,
"score": 0.9956686496734619,
"start": 3465,
"tag": "NAME",
"value": "Steve Jobs"
}
] |
src/assistant/core.cljs
|
29decibel/assistant
| 306 |
(ns assistant.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs-http.client :as http]
[cljs.reader :as reader]
[garden.core :refer [css]]
[cognitect.transit :as t]
[cljs.core.async :refer [<! >! chan]]
[hickory.core :as hk]
[assistant.utils :as utils]
[hickory.select :as s]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
;; a list of plugins installed by default
;; user can alwasy disalbe them in the ~/.assistant-plugins
(defn log [m]
(.log js/console m))
(defn printcol [col]
(doall (map print col)))
(enable-console-print!)
(def gui (js/require "nw.gui"))
(def fs (js/require "fs"))
(def config-file (str (utils/user-home) "/.assistant"))
(utils/create-if-not-exist config-file)
(def config-data (reader/read-string (.readFileSync fs config-file "utf-8")))
;; return config data
(defn config []
config-data)
;; enable default menu
(defn create-built-in-menu! []
(let [win (.get (.-Window gui)) ;; current window
Menu (.-Menu gui) ;; create menu
mb (Menu. #js {:type "menubar" })]
(.createMacBuiltin mb "Assistant")
(set! (.-menu win) mb)))
(create-built-in-menu!)
(defn read-app-state []
"read app state from ~/.assistant-store"
(try
(let [file-name (str (utils/user-home) "/.assistant-store")
file-exists (utils/create-if-not-exist file-name)
file-content (.readFileSync fs file-name "utf-8")
r (t/reader :json)
state (t/read r file-content)]
(print "Restore state now....")
state) (catch js/Error e {:cards []})))
;; app state might contains entire application's configuration info
(def app-state (atom {:cards []}))
(def cards (atom {}))
(def dispatchers (atom {}))
(def styles (atom []))
(def dispatcher-chan (chan))
(defn put-result [result]
"Put a result into channel"
(go (>! dispatcher-chan result)))
(let [win (.get (.-Window gui))
w (t/writer :json)]
(.on win "close" #(this-as me (do
(print "Start writing....")
(utils/write-to-file (str (utils/user-home) "/.assistant-store" ) (t/write w @app-state))
(.close me true)))))
(defn handle-change [e owner {:keys [text]}]
(om/set-state! owner :text (.. e -target -value)))
;; application component will be a something like:
;; a text box which accept the commands or words from people
;; a List of components area/playgroud to show the response of any given commands
;; push card data into app data stack
(defn push-card [app card]
(om/transact! app :cards (fn [xs] (cons card xs))))
(defn dispatch-input [result-chan text]
(let [parts (.split text " ")
command-name (keyword (first parts))
query (clojure.string/join " "(rest parts))
dispatcher (get-in @dispatchers [command-name :exec])]
(if dispatcher
;; using correspond dispatcher/processor to process the text
(dispatcher result-chan query)
;; not found dispatcher, show a warn card
(put-result {:type :info-card :info-type "warn" :title (str "Unknown Command - " text) :content "You can run command 'help' to get all available commands."}))))
(defn empty-card []
(dom/div #js {:className "empty-card"} "Design is not just what it looks like and feels like. Design is how it works. -- Steve Jobs"))
;; general card view om componnet
(defn card-view-om [data owner]
(reify
om/IRender
(render [this]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))))
(defn card-view [data owner]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))
(defn app-view [app owner]
(reify
om/IInitState
(init-state [_]
{:count 1 :text ""})
om/IWillMount
(will-mount [_]
(go (loop []
(let [result (<! dispatcher-chan)]
(push-card app result)
(recur)))))
om/IRenderState
(render-state [this state]
(let [all-cards (:cards app)]
(dom/div nil
(dom/div #js {:className "prompt"} ">")
(dom/input #js {:type "text" :placeholder "Type your commands here..." :autoFocus "autofocus"
:value (:text state)
:onChange #(handle-change % owner state)
:onKeyDown #(when (== (.-keyCode %) 13)
(dispatch-input dispatcher-chan (:text state))
(om/set-state! owner :text ""))} "")
(dom/div #js {:className "conversation"}
(if (= (count all-cards) 0)
(empty-card)
(apply dom/ul #js {:className "list"}
(om/build-all card-view-om all-cards))))
(dom/a #js {:className "clear-btn" :href "#" :onClick #(reset! app-state {:cards []})} "Clear"))))))
(defn register-dispatcher [respond-name dispatcher desc]
(swap! dispatchers assoc respond-name {:exec dispatcher :desc desc}))
(defn register-card [card-name card]
(swap! cards assoc card-name card))
(defn update-styles []
(set! (.-innerHTML (. js/document (getElementById "plugin-styles")))
(css @styles)))
(defn register-css
"Register plugin css for card"
[css-content]
(swap! styles conj css-content)
(update-styles))
(defn valid-config [names msg & info-type]
"check if the config exist
example arguments: :jira :key"
(let [c (config)]
(if-not (get-in c names)
(not (go (>! dispatcher-chan {:type :info-card :content msg :info-type "error" :title "Configuration value[s] missing in ~/.assistant"}))) ;; this case should return true
true)))
;; built in help dispatcher and card
(defn help-dispatcher [result-chan text]
(go
(>! result-chan {:type :help :content (map #(:desc %) (vals @dispatchers)) })))
(defn help-card [app owner]
(reify
om/IRender
(render [this]
(let [commands (-> app :content )
commands-text (filter #(not= nil %) commands)
commands-map (map #(hash-map :name (nth (.split % "--") 0) :desc (nth (.split % "--") 1)) commands-text)]
(dom/div nil
(dom/h2 nil "Available Commands")
(apply dom/ul nil (map #(dom/li nil
(dom/span #js {:className "label"} (:name %))
(dom/span #js {:className "desc"} (:desc %))) commands-map)))))))
(register-dispatcher :help help-dispatcher "help -- show the list of available commands")
(register-card :help help-card)
(defn clear-dispatcher [result-chan text]
"Built in dispatcher to clear all cards"
(reset! app-state {:cards []}))
(register-dispatcher :clear clear-dispatcher "clear -- clear all cards.")
(defn refresh-app-state! []
(reset! app-state (read-app-state)))
(om/root
app-view ;; om component
app-state ;; app state
{:target (. js/document (getElementById "app"))})
|
86073
|
(ns assistant.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs-http.client :as http]
[cljs.reader :as reader]
[garden.core :refer [css]]
[cognitect.transit :as t]
[cljs.core.async :refer [<! >! chan]]
[hickory.core :as hk]
[assistant.utils :as utils]
[hickory.select :as s]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
;; a list of plugins installed by default
;; user can alwasy disalbe them in the ~/.assistant-plugins
(defn log [m]
(.log js/console m))
(defn printcol [col]
(doall (map print col)))
(enable-console-print!)
(def gui (js/require "nw.gui"))
(def fs (js/require "fs"))
(def config-file (str (utils/user-home) "/.assistant"))
(utils/create-if-not-exist config-file)
(def config-data (reader/read-string (.readFileSync fs config-file "utf-8")))
;; return config data
(defn config []
config-data)
;; enable default menu
(defn create-built-in-menu! []
(let [win (.get (.-Window gui)) ;; current window
Menu (.-Menu gui) ;; create menu
mb (Menu. #js {:type "menubar" })]
(.createMacBuiltin mb "Assistant")
(set! (.-menu win) mb)))
(create-built-in-menu!)
(defn read-app-state []
"read app state from ~/.assistant-store"
(try
(let [file-name (str (utils/user-home) "/.assistant-store")
file-exists (utils/create-if-not-exist file-name)
file-content (.readFileSync fs file-name "utf-8")
r (t/reader :json)
state (t/read r file-content)]
(print "Restore state now....")
state) (catch js/Error e {:cards []})))
;; app state might contains entire application's configuration info
(def app-state (atom {:cards []}))
(def cards (atom {}))
(def dispatchers (atom {}))
(def styles (atom []))
(def dispatcher-chan (chan))
(defn put-result [result]
"Put a result into channel"
(go (>! dispatcher-chan result)))
(let [win (.get (.-Window gui))
w (t/writer :json)]
(.on win "close" #(this-as me (do
(print "Start writing....")
(utils/write-to-file (str (utils/user-home) "/.assistant-store" ) (t/write w @app-state))
(.close me true)))))
(defn handle-change [e owner {:keys [text]}]
(om/set-state! owner :text (.. e -target -value)))
;; application component will be a something like:
;; a text box which accept the commands or words from people
;; a List of components area/playgroud to show the response of any given commands
;; push card data into app data stack
(defn push-card [app card]
(om/transact! app :cards (fn [xs] (cons card xs))))
(defn dispatch-input [result-chan text]
(let [parts (.split text " ")
command-name (keyword (first parts))
query (clojure.string/join " "(rest parts))
dispatcher (get-in @dispatchers [command-name :exec])]
(if dispatcher
;; using correspond dispatcher/processor to process the text
(dispatcher result-chan query)
;; not found dispatcher, show a warn card
(put-result {:type :info-card :info-type "warn" :title (str "Unknown Command - " text) :content "You can run command 'help' to get all available commands."}))))
(defn empty-card []
(dom/div #js {:className "empty-card"} "Design is not just what it looks like and feels like. Design is how it works. -- <NAME>"))
;; general card view om componnet
(defn card-view-om [data owner]
(reify
om/IRender
(render [this]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))))
(defn card-view [data owner]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))
(defn app-view [app owner]
(reify
om/IInitState
(init-state [_]
{:count 1 :text ""})
om/IWillMount
(will-mount [_]
(go (loop []
(let [result (<! dispatcher-chan)]
(push-card app result)
(recur)))))
om/IRenderState
(render-state [this state]
(let [all-cards (:cards app)]
(dom/div nil
(dom/div #js {:className "prompt"} ">")
(dom/input #js {:type "text" :placeholder "Type your commands here..." :autoFocus "autofocus"
:value (:text state)
:onChange #(handle-change % owner state)
:onKeyDown #(when (== (.-keyCode %) 13)
(dispatch-input dispatcher-chan (:text state))
(om/set-state! owner :text ""))} "")
(dom/div #js {:className "conversation"}
(if (= (count all-cards) 0)
(empty-card)
(apply dom/ul #js {:className "list"}
(om/build-all card-view-om all-cards))))
(dom/a #js {:className "clear-btn" :href "#" :onClick #(reset! app-state {:cards []})} "Clear"))))))
(defn register-dispatcher [respond-name dispatcher desc]
(swap! dispatchers assoc respond-name {:exec dispatcher :desc desc}))
(defn register-card [card-name card]
(swap! cards assoc card-name card))
(defn update-styles []
(set! (.-innerHTML (. js/document (getElementById "plugin-styles")))
(css @styles)))
(defn register-css
"Register plugin css for card"
[css-content]
(swap! styles conj css-content)
(update-styles))
(defn valid-config [names msg & info-type]
"check if the config exist
example arguments: :jira :key"
(let [c (config)]
(if-not (get-in c names)
(not (go (>! dispatcher-chan {:type :info-card :content msg :info-type "error" :title "Configuration value[s] missing in ~/.assistant"}))) ;; this case should return true
true)))
;; built in help dispatcher and card
(defn help-dispatcher [result-chan text]
(go
(>! result-chan {:type :help :content (map #(:desc %) (vals @dispatchers)) })))
(defn help-card [app owner]
(reify
om/IRender
(render [this]
(let [commands (-> app :content )
commands-text (filter #(not= nil %) commands)
commands-map (map #(hash-map :name (nth (.split % "--") 0) :desc (nth (.split % "--") 1)) commands-text)]
(dom/div nil
(dom/h2 nil "Available Commands")
(apply dom/ul nil (map #(dom/li nil
(dom/span #js {:className "label"} (:name %))
(dom/span #js {:className "desc"} (:desc %))) commands-map)))))))
(register-dispatcher :help help-dispatcher "help -- show the list of available commands")
(register-card :help help-card)
(defn clear-dispatcher [result-chan text]
"Built in dispatcher to clear all cards"
(reset! app-state {:cards []}))
(register-dispatcher :clear clear-dispatcher "clear -- clear all cards.")
(defn refresh-app-state! []
(reset! app-state (read-app-state)))
(om/root
app-view ;; om component
app-state ;; app state
{:target (. js/document (getElementById "app"))})
| true |
(ns assistant.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [cljs-http.client :as http]
[cljs.reader :as reader]
[garden.core :refer [css]]
[cognitect.transit :as t]
[cljs.core.async :refer [<! >! chan]]
[hickory.core :as hk]
[assistant.utils :as utils]
[hickory.select :as s]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
;; a list of plugins installed by default
;; user can alwasy disalbe them in the ~/.assistant-plugins
(defn log [m]
(.log js/console m))
(defn printcol [col]
(doall (map print col)))
(enable-console-print!)
(def gui (js/require "nw.gui"))
(def fs (js/require "fs"))
(def config-file (str (utils/user-home) "/.assistant"))
(utils/create-if-not-exist config-file)
(def config-data (reader/read-string (.readFileSync fs config-file "utf-8")))
;; return config data
(defn config []
config-data)
;; enable default menu
(defn create-built-in-menu! []
(let [win (.get (.-Window gui)) ;; current window
Menu (.-Menu gui) ;; create menu
mb (Menu. #js {:type "menubar" })]
(.createMacBuiltin mb "Assistant")
(set! (.-menu win) mb)))
(create-built-in-menu!)
(defn read-app-state []
"read app state from ~/.assistant-store"
(try
(let [file-name (str (utils/user-home) "/.assistant-store")
file-exists (utils/create-if-not-exist file-name)
file-content (.readFileSync fs file-name "utf-8")
r (t/reader :json)
state (t/read r file-content)]
(print "Restore state now....")
state) (catch js/Error e {:cards []})))
;; app state might contains entire application's configuration info
(def app-state (atom {:cards []}))
(def cards (atom {}))
(def dispatchers (atom {}))
(def styles (atom []))
(def dispatcher-chan (chan))
(defn put-result [result]
"Put a result into channel"
(go (>! dispatcher-chan result)))
(let [win (.get (.-Window gui))
w (t/writer :json)]
(.on win "close" #(this-as me (do
(print "Start writing....")
(utils/write-to-file (str (utils/user-home) "/.assistant-store" ) (t/write w @app-state))
(.close me true)))))
(defn handle-change [e owner {:keys [text]}]
(om/set-state! owner :text (.. e -target -value)))
;; application component will be a something like:
;; a text box which accept the commands or words from people
;; a List of components area/playgroud to show the response of any given commands
;; push card data into app data stack
(defn push-card [app card]
(om/transact! app :cards (fn [xs] (cons card xs))))
(defn dispatch-input [result-chan text]
(let [parts (.split text " ")
command-name (keyword (first parts))
query (clojure.string/join " "(rest parts))
dispatcher (get-in @dispatchers [command-name :exec])]
(if dispatcher
;; using correspond dispatcher/processor to process the text
(dispatcher result-chan query)
;; not found dispatcher, show a warn card
(put-result {:type :info-card :info-type "warn" :title (str "Unknown Command - " text) :content "You can run command 'help' to get all available commands."}))))
(defn empty-card []
(dom/div #js {:className "empty-card"} "Design is not just what it looks like and feels like. Design is how it works. -- PI:NAME:<NAME>END_PI"))
;; general card view om componnet
(defn card-view-om [data owner]
(reify
om/IRender
(render [this]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))))
(defn card-view [data owner]
(let [card-type (:type data)
card-fn (get @cards card-type)]
(when card-fn
(dom/li #js {:className (str "card " (name card-type))} (om/build card-fn data)))))
(defn app-view [app owner]
(reify
om/IInitState
(init-state [_]
{:count 1 :text ""})
om/IWillMount
(will-mount [_]
(go (loop []
(let [result (<! dispatcher-chan)]
(push-card app result)
(recur)))))
om/IRenderState
(render-state [this state]
(let [all-cards (:cards app)]
(dom/div nil
(dom/div #js {:className "prompt"} ">")
(dom/input #js {:type "text" :placeholder "Type your commands here..." :autoFocus "autofocus"
:value (:text state)
:onChange #(handle-change % owner state)
:onKeyDown #(when (== (.-keyCode %) 13)
(dispatch-input dispatcher-chan (:text state))
(om/set-state! owner :text ""))} "")
(dom/div #js {:className "conversation"}
(if (= (count all-cards) 0)
(empty-card)
(apply dom/ul #js {:className "list"}
(om/build-all card-view-om all-cards))))
(dom/a #js {:className "clear-btn" :href "#" :onClick #(reset! app-state {:cards []})} "Clear"))))))
(defn register-dispatcher [respond-name dispatcher desc]
(swap! dispatchers assoc respond-name {:exec dispatcher :desc desc}))
(defn register-card [card-name card]
(swap! cards assoc card-name card))
(defn update-styles []
(set! (.-innerHTML (. js/document (getElementById "plugin-styles")))
(css @styles)))
(defn register-css
"Register plugin css for card"
[css-content]
(swap! styles conj css-content)
(update-styles))
(defn valid-config [names msg & info-type]
"check if the config exist
example arguments: :jira :key"
(let [c (config)]
(if-not (get-in c names)
(not (go (>! dispatcher-chan {:type :info-card :content msg :info-type "error" :title "Configuration value[s] missing in ~/.assistant"}))) ;; this case should return true
true)))
;; built in help dispatcher and card
(defn help-dispatcher [result-chan text]
(go
(>! result-chan {:type :help :content (map #(:desc %) (vals @dispatchers)) })))
(defn help-card [app owner]
(reify
om/IRender
(render [this]
(let [commands (-> app :content )
commands-text (filter #(not= nil %) commands)
commands-map (map #(hash-map :name (nth (.split % "--") 0) :desc (nth (.split % "--") 1)) commands-text)]
(dom/div nil
(dom/h2 nil "Available Commands")
(apply dom/ul nil (map #(dom/li nil
(dom/span #js {:className "label"} (:name %))
(dom/span #js {:className "desc"} (:desc %))) commands-map)))))))
(register-dispatcher :help help-dispatcher "help -- show the list of available commands")
(register-card :help help-card)
(defn clear-dispatcher [result-chan text]
"Built in dispatcher to clear all cards"
(reset! app-state {:cards []}))
(register-dispatcher :clear clear-dispatcher "clear -- clear all cards.")
(defn refresh-app-state! []
(reset! app-state (read-app-state)))
(om/root
app-view ;; om component
app-state ;; app state
{:target (. js/document (getElementById "app"))})
|
[
{
"context": "1em482svs0uojb8u7kmooulmmj\"}\n {:username \"[email protected]\"\n :password \"Test1234\"})\n <?\n ",
"end": 916,
"score": 0.9997372627258301,
"start": 896,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "rname \"[email protected]\"\n :password \"Test1234\"})\n <?\n :rx.aws/data\n :Authenti",
"end": 947,
"score": 0.9992300271987915,
"start": 939,
"tag": "PASSWORD",
"value": "Test1234"
},
{
"context": " :aws.cog/jwks-str\n \"{\\\"keys\\\":[{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"Uc55PuoXTb1+",
"end": 2315,
"score": 0.52885901927948,
"start": 2312,
"tag": "KEY",
"value": "alg"
},
{
"context": "ws.cog/jwks-str\n \"{\\\"keys\\\":[{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"Uc55PuoXTb1+Yxr8cC++RWqrDr3K0NPimJ0p5VG26uE=\\\",\\\"k",
"end": 2353,
"score": 0.928538978099823,
"start": 2320,
"tag": "KEY",
"value": "RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\""
},
{
"context": "ys\\\":[{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"Uc55PuoXTb1+Yxr8cC++RWqrDr3K0NPimJ0p5VG26uE=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\"9aW80tw1sCwxGStjzVOoofljyPFa_Fk",
"end": 2405,
"score": 0.9861153960227966,
"start": 2353,
"tag": "KEY",
"value": "Uc55PuoXTb1+Yxr8cC++RWqrDr3K0NPimJ0p5VG26uE=\\\",\\\"kty"
},
{
"context": "XTb1+Yxr8cC++RWqrDr3K0NPimJ0p5VG26uE=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\"9aW80tw1sCwxGStjzVOoofljyPFa_FkLUzSXaFu_Qjf2pRnuxn",
"end": 2424,
"score": 0.7815828323364258,
"start": 2410,
"tag": "KEY",
"value": "RSA\\\",\\\"n\\\":\\\""
},
{
"context": "WqrDr3K0NPimJ0p5VG26uE=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\"9aW80tw1sCwxGStjzVOoofljyPFa_FkLUzSXaFu_Qjf2pRnuxn6QSxXkI_C_aj1z-clP0sOlss6nIcJIGeP4u9E2gz7_Df2uCkU4AfGxio9RzznY3MsQVp8kfKEdK_5Go3zXX8x526Ky5sGMjFWR8RO-JEOl6NvnmgY_rv8uMS6GMUQx0wDAU4rAYHGKTzphgqJAt1I-9xTB0v4MyrI8qg7xcs21A6AVpRj3svAZn1sVsF9IphSrZeSFJmw1WfJe5NKnekOJm7qG2CUjKcTTY7jdf_L6MGQk",
"end": 2662,
"score": 0.9920016527175903,
"start": 2424,
"tag": "KEY",
"value": "9aW80tw1sCwxGStjzVOoofljyPFa_FkLUzSXaFu_Qjf2pRnuxn6QSxXkI_C_aj1z-clP0sOlss6nIcJIGeP4u9E2gz7_Df2uCkU4AfGxio9RzznY3MsQVp8kfKEdK_5Go3zXX8x526Ky5sGMjFWR8RO-JEOl6NvnmgY_rv8uMS6GMUQx0wDAU4rAYHGKTzphgqJAt1I-9xTB0v4MyrI8qg7xcs21A6AVpRj3svAZn1sVsF"
},
{
"context": "zphgqJAt1I-9xTB0v4MyrI8qg7xcs21A6AVpRj3svAZn1sVsF9IphSrZeSFJmw1WfJe5NKnekOJm7qG2CUjKcTTY7jdf_L6MGQky2wlTUstxHUeiFDBehbD1nRDaps9D6mzpDObb8MMmx1Cjv_SUBFJkQ\\\",\\\"use\\\":\\\"sig\\\"},{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQA",
"end": 2766,
"score": 0.9912348985671997,
"start": 2663,
"tag": "KEY",
"value": "IphSrZeSFJmw1WfJe5NKnekOJm7qG2CUjKcTTY7jdf_L6MGQky2wlTUstxHUeiFDBehbD1nRDaps9D6mzpDObb8MMmx1Cjv_SUBFJkQ"
},
{
"context": "bb8MMmx1Cjv_SUBFJkQ\\\",\\\"use\\\":\\\"sig\\\"},{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"kA8o8ZKo39RBS26uCab1Fj",
"end": 2802,
"score": 0.6087172031402588,
"start": 2797,
"tag": "KEY",
"value": "RS256"
},
{
"context": "JkQ\\\",\\\"use\\\":\\\"sig\\\"},{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"kA8o8ZKo39RBS26uCab1FjPWl0o8B03DxlFzgomdVTg=\\\",\\\"k",
"end": 2830,
"score": 0.7533067464828491,
"start": 2813,
"tag": "KEY",
"value": "AQAB\\\",\\\"kid\\\":\\\""
},
{
"context": "ig\\\"},{\\\"alg\\\":\\\"RS256\\\",\\\"e\\\":\\\"AQAB\\\",\\\"kid\\\":\\\"kA8o8ZKo39RBS26uCab1FjPWl0o8B03DxlFzgomdVTg=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\"jpa17hbfmap73UQinjq7HuICMYo7YaJRD_c5X73TPzCaSJ2w76",
"end": 2901,
"score": 0.9589714407920837,
"start": 2830,
"tag": "KEY",
"value": "kA8o8ZKo39RBS26uCab1FjPWl0o8B03DxlFzgomdVTg=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\""
},
{
"context": "jPWl0o8B03DxlFzgomdVTg=\\\",\\\"kty\\\":\\\"RSA\\\",\\\"n\\\":\\\"jpa17hbfmap73UQinjq7HuICMYo7YaJRD_c5X73TPzCaSJ2w760UrvNgfOgGeIvlZleg5lqEokH4kyI2IBUJJ_qNXZWym6_s_mwJTXtrlF8l11j30oeP7DmNfE_j6RGDT5_mHOLXcN1DFdQaEu9P3IzINMHHQh5tJk7s2Zb8V0cSLQjVgdoHE4S5HXPzhKe243j8kpMIPRUeuEm1IN17EklMsE0Mxvv69Aksnt219EYQL12DcjswbuIaVGAi0VnQ3YzYinyzDNJ7keD34Wn9KFvfMUQh5s1VO_opQ2h0V50aKmENqYnImrTss0lVuklEC0u0_sSI1eBwfI-Ww_iupw\\\",\\\"use\\\":\\\"sig\\\"}]}\"}\n id-token)]\n [[(= \"",
"end": 3248,
"score": 0.9925625920295715,
"start": 2901,
"tag": "KEY",
"value": "jpa17hbfmap73UQinjq7HuICMYo7YaJRD_c5X73TPzCaSJ2w760UrvNgfOgGeIvlZleg5lqEokH4kyI2IBUJJ_qNXZWym6_s_mwJTXtrlF8l11j30oeP7DmNfE_j6RGDT5_mHOLXcN1DFdQaEu9P3IzINMHHQh5tJk7s2Zb8V0cSLQjVgdoHE4S5HXPzhKe243j8kpMIPRUeuEm1IN17EklMsE0Mxvv69Aksnt219EYQL12DcjswbuIaVGAi0VnQ3YzYinyzDNJ7keD34Wn9KFvfMUQh5s1VO_opQ2h0V50aKmENqYnImrTss0lVuklEC0u0_sSI1eBwfI-Ww_iupw\\\",\\\""
},
{
"context": "use\\\":\\\"sig\\\"}]}\"}\n id-token)]\n [[(= \"[email protected]\"\n (-> verify-res\n res/data\n ",
"end": 3318,
"score": 0.9998904466629028,
"start": 3298,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/cljs-node/rx/node/box/sync_server_test.cljs
|
zk/rx-lib
| 0 |
(ns rx.node.box.sync-server-test
(:require [rx.kitchen-sink :as ks]
[rx.node.box.sync-server :as r]
[rx.res :as res]
[rx.node.aws :as aws]
[rx.test :as test
:refer-macros [deftest <deftest]]
[rx.anom :as anom :refer-macros [<defn <?]]
[rx.test :as rt]
[cljs.core.async :as async
:refer [<! chan put!] :refer-macros [go]]))
(def schema
{:box/ddb-data-table-name "rx-test-pk-string"
:box/ddb-creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs
"~/.rx-secrets.edn")))
:box/attrs
{:foo/id {:box.attr/ident? true}}})
(<defn <id-token []
(->> (aws/<cogisp-user-password-auth
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.rx-secrets.edn")))
{:cog-client-id "1em482svs0uojb8u7kmooulmmj"}
{:username "[email protected]"
:password "Test1234"})
<?
:rx.aws/data
:AuthenticationResult
:IdToken))
(deftest all-ops-owned [_]
[[(r/all-ops-owned?
schema
[{:box.sync/op-key :box.op/update
:box.sync/entity {:foo/id "foo"
:box.sync/owner-id "zk"}}]
{:sub "zk"})]])
(deftest verify-and-decode-cog-auth [_]
[[(try
(r/verify-and-decode-cog-auth nil nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
"foo bar")
false
(catch js/Error e true))]])
(<deftest verify-and-decode-cog-auth-async [_]
(let [id-token (<? (<id-token))
verify-res
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj"
:aws.cog/user-pool-id "us-west-2_W1OuUCkYR"
:aws.cog/allowed-use-claims ["id" "access"]
:aws.cog/jwks-str
"{\"keys\":[{\"alg\":\"RS256\",\"e\":\"AQAB\",\"kid\":\"Uc55PuoXTb1+Yxr8cC++RWqrDr3K0NPimJ0p5VG26uE=\",\"kty\":\"RSA\",\"n\":\"9aW80tw1sCwxGStjzVOoofljyPFa_FkLUzSXaFu_Qjf2pRnuxn6QSxXkI_C_aj1z-clP0sOlss6nIcJIGeP4u9E2gz7_Df2uCkU4AfGxio9RzznY3MsQVp8kfKEdK_5Go3zXX8x526Ky5sGMjFWR8RO-JEOl6NvnmgY_rv8uMS6GMUQx0wDAU4rAYHGKTzphgqJAt1I-9xTB0v4MyrI8qg7xcs21A6AVpRj3svAZn1sVsF9IphSrZeSFJmw1WfJe5NKnekOJm7qG2CUjKcTTY7jdf_L6MGQky2wlTUstxHUeiFDBehbD1nRDaps9D6mzpDObb8MMmx1Cjv_SUBFJkQ\",\"use\":\"sig\"},{\"alg\":\"RS256\",\"e\":\"AQAB\",\"kid\":\"kA8o8ZKo39RBS26uCab1FjPWl0o8B03DxlFzgomdVTg=\",\"kty\":\"RSA\",\"n\":\"jpa17hbfmap73UQinjq7HuICMYo7YaJRD_c5X73TPzCaSJ2w760UrvNgfOgGeIvlZleg5lqEokH4kyI2IBUJJ_qNXZWym6_s_mwJTXtrlF8l11j30oeP7DmNfE_j6RGDT5_mHOLXcN1DFdQaEu9P3IzINMHHQh5tJk7s2Zb8V0cSLQjVgdoHE4S5HXPzhKe243j8kpMIPRUeuEm1IN17EklMsE0Mxvv69Aksnt219EYQL12DcjswbuIaVGAi0VnQ3YzYinyzDNJ7keD34Wn9KFvfMUQh5s1VO_opQ2h0V50aKmENqYnImrTss0lVuklEC0u0_sSI1eBwfI-Ww_iupw\",\"use\":\"sig\"}]}"}
id-token)]
[[(= "[email protected]"
(-> verify-res
res/data
:payload
:email))]]))
#_(test/reg ::to-ddb-item
(fn []
[[(try
(r/default-to-ddb-item nil nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} {})
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"})
false
(catch js/Error e true))]
[(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"
:baz/bap "asdf"
:box.sync/owner-id "zk"})]]))
(comment
(test/<run-ns-repl
'rx.node.box.sync-server-test
{})
(test/<run-ns
'rx.node.box.sync-server-test
{})
(test-to-ddb-item)
(test-verify-and-decode-cog-auth)
(test-verify-and-decode-cog-auth-async)
(test/run-tests 'rx.node.box.sync-server-test)
(r/default-to-ddb-item
schema
{:foo/id "foo"})
(r/lambda-println "foo")
;; not owner
(ks/<pp
(r/<sync-objs
schema
[{:gpt/id "foo"
:box.pers/owner-id "zk"}
{:gpt/id "bar"}
{:gpt/id "baz"
:box.pers/delete-marked-ts 1}]
{:sub "zk"}))
;; ok
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world"
:box.pers/owner-id "zk"}
{:foo/id "bar"
:box.pers/owner-id "zk"}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world2"
:box.pers/owner-id "zk"
:box.pers/force-update? true}
{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? false}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(go
(let [start (system-time)]
(ks/pp
(<! (r/<sync-objs
{:box/schema schema}
(->> (range 1)
(map
(fn [i]
{:box.sync/op-key :box.op/update
:box.sync/ignore-match-version? true
:box.sync/entity
{:foo/id (str "foo" i)
:test/one "one"
:test/two "two"
:box.sync/owner-id "zk"}})))
{:sub "zk"})))
(ks/pn (- (system-time) start))))
(require '[clojure.browser.repl :as cbr])
(ks/<pp (<id-token))
)
|
46075
|
(ns rx.node.box.sync-server-test
(:require [rx.kitchen-sink :as ks]
[rx.node.box.sync-server :as r]
[rx.res :as res]
[rx.node.aws :as aws]
[rx.test :as test
:refer-macros [deftest <deftest]]
[rx.anom :as anom :refer-macros [<defn <?]]
[rx.test :as rt]
[cljs.core.async :as async
:refer [<! chan put!] :refer-macros [go]]))
(def schema
{:box/ddb-data-table-name "rx-test-pk-string"
:box/ddb-creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs
"~/.rx-secrets.edn")))
:box/attrs
{:foo/id {:box.attr/ident? true}}})
(<defn <id-token []
(->> (aws/<cogisp-user-password-auth
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.rx-secrets.edn")))
{:cog-client-id "1em482svs0uojb8u7kmooulmmj"}
{:username "<EMAIL>"
:password "<PASSWORD>"})
<?
:rx.aws/data
:AuthenticationResult
:IdToken))
(deftest all-ops-owned [_]
[[(r/all-ops-owned?
schema
[{:box.sync/op-key :box.op/update
:box.sync/entity {:foo/id "foo"
:box.sync/owner-id "zk"}}]
{:sub "zk"})]])
(deftest verify-and-decode-cog-auth [_]
[[(try
(r/verify-and-decode-cog-auth nil nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
"foo bar")
false
(catch js/Error e true))]])
(<deftest verify-and-decode-cog-auth-async [_]
(let [id-token (<? (<id-token))
verify-res
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj"
:aws.cog/user-pool-id "us-west-2_W1OuUCkYR"
:aws.cog/allowed-use-claims ["id" "access"]
:aws.cog/jwks-str
"{\"keys\":[{\"<KEY>\":\"<KEY> <KEY>\":\"<KEY> <KEY>9<KEY>\",\"use\":\"sig\"},{\"alg\":\"<KEY>\",\"e\":\"<KEY> <KEY> <KEY>use\":\"sig\"}]}"}
id-token)]
[[(= "<EMAIL>"
(-> verify-res
res/data
:payload
:email))]]))
#_(test/reg ::to-ddb-item
(fn []
[[(try
(r/default-to-ddb-item nil nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} {})
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"})
false
(catch js/Error e true))]
[(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"
:baz/bap "asdf"
:box.sync/owner-id "zk"})]]))
(comment
(test/<run-ns-repl
'rx.node.box.sync-server-test
{})
(test/<run-ns
'rx.node.box.sync-server-test
{})
(test-to-ddb-item)
(test-verify-and-decode-cog-auth)
(test-verify-and-decode-cog-auth-async)
(test/run-tests 'rx.node.box.sync-server-test)
(r/default-to-ddb-item
schema
{:foo/id "foo"})
(r/lambda-println "foo")
;; not owner
(ks/<pp
(r/<sync-objs
schema
[{:gpt/id "foo"
:box.pers/owner-id "zk"}
{:gpt/id "bar"}
{:gpt/id "baz"
:box.pers/delete-marked-ts 1}]
{:sub "zk"}))
;; ok
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world"
:box.pers/owner-id "zk"}
{:foo/id "bar"
:box.pers/owner-id "zk"}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world2"
:box.pers/owner-id "zk"
:box.pers/force-update? true}
{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? false}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(go
(let [start (system-time)]
(ks/pp
(<! (r/<sync-objs
{:box/schema schema}
(->> (range 1)
(map
(fn [i]
{:box.sync/op-key :box.op/update
:box.sync/ignore-match-version? true
:box.sync/entity
{:foo/id (str "foo" i)
:test/one "one"
:test/two "two"
:box.sync/owner-id "zk"}})))
{:sub "zk"})))
(ks/pn (- (system-time) start))))
(require '[clojure.browser.repl :as cbr])
(ks/<pp (<id-token))
)
| true |
(ns rx.node.box.sync-server-test
(:require [rx.kitchen-sink :as ks]
[rx.node.box.sync-server :as r]
[rx.res :as res]
[rx.node.aws :as aws]
[rx.test :as test
:refer-macros [deftest <deftest]]
[rx.anom :as anom :refer-macros [<defn <?]]
[rx.test :as rt]
[cljs.core.async :as async
:refer [<! chan put!] :refer-macros [go]]))
(def schema
{:box/ddb-data-table-name "rx-test-pk-string"
:box/ddb-creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs
"~/.rx-secrets.edn")))
:box/attrs
{:foo/id {:box.attr/ident? true}}})
(<defn <id-token []
(->> (aws/<cogisp-user-password-auth
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.rx-secrets.edn")))
{:cog-client-id "1em482svs0uojb8u7kmooulmmj"}
{:username "PI:EMAIL:<EMAIL>END_PI"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
<?
:rx.aws/data
:AuthenticationResult
:IdToken))
(deftest all-ops-owned [_]
[[(r/all-ops-owned?
schema
[{:box.sync/op-key :box.op/update
:box.sync/entity {:foo/id "foo"
:box.sync/owner-id "zk"}}]
{:sub "zk"})]])
(deftest verify-and-decode-cog-auth [_]
[[(try
(r/verify-and-decode-cog-auth nil nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
nil)
false
(catch js/Error e true))]
[(try
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "client-id"
:aws.cog/user-pool-id "user-pool-id"
:aws.cog/allowed-use-claims ["foo" "bar"]
:aws.cog/jwks-str "jwks-str"}
"foo bar")
false
(catch js/Error e true))]])
(<deftest verify-and-decode-cog-auth-async [_]
(let [id-token (<? (<id-token))
verify-res
(r/verify-and-decode-cog-auth
{:aws.cog/client-id "1em482svs0uojb8u7kmooulmmj"
:aws.cog/user-pool-id "us-west-2_W1OuUCkYR"
:aws.cog/allowed-use-claims ["id" "access"]
:aws.cog/jwks-str
"{\"keys\":[{\"PI:KEY:<KEY>END_PI\":\"PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI\":\"PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI\",\"use\":\"sig\"},{\"alg\":\"PI:KEY:<KEY>END_PI\",\"e\":\"PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PIuse\":\"sig\"}]}"}
id-token)]
[[(= "PI:EMAIL:<EMAIL>END_PI"
(-> verify-res
res/data
:payload
:email))]]))
#_(test/reg ::to-ddb-item
(fn []
[[(try
(r/default-to-ddb-item nil nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} nil)
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item {} {})
false
(catch js/Error e true))]
[(try
(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"})
false
(catch js/Error e true))]
[(r/default-to-ddb-item
{:box/attrs
{:foo/id {:box.attr/ident? true}}}
{:foo/id "foo1"
:baz/bap "asdf"
:box.sync/owner-id "zk"})]]))
(comment
(test/<run-ns-repl
'rx.node.box.sync-server-test
{})
(test/<run-ns
'rx.node.box.sync-server-test
{})
(test-to-ddb-item)
(test-verify-and-decode-cog-auth)
(test-verify-and-decode-cog-auth-async)
(test/run-tests 'rx.node.box.sync-server-test)
(r/default-to-ddb-item
schema
{:foo/id "foo"})
(r/lambda-println "foo")
;; not owner
(ks/<pp
(r/<sync-objs
schema
[{:gpt/id "foo"
:box.pers/owner-id "zk"}
{:gpt/id "bar"}
{:gpt/id "baz"
:box.pers/delete-marked-ts 1}]
{:sub "zk"}))
;; ok
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world"
:box.pers/owner-id "zk"}
{:foo/id "bar"
:box.pers/owner-id "zk"}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "foo"
:hello "world2"
:box.pers/owner-id "zk"
:box.pers/force-update? true}
{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? false}
{:foo/id "baz"
:box.pers/delete-marked-ts 1
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(ks/<pp
(r/<sync-objs
{:box/schema schema}
[{:foo/id "bar"
:box.pers/owner-id "zk"
:box.pers/force-update? true}]
{:sub "zk"}))
(go
(let [start (system-time)]
(ks/pp
(<! (r/<sync-objs
{:box/schema schema}
(->> (range 1)
(map
(fn [i]
{:box.sync/op-key :box.op/update
:box.sync/ignore-match-version? true
:box.sync/entity
{:foo/id (str "foo" i)
:test/one "one"
:test/two "two"
:box.sync/owner-id "zk"}})))
{:sub "zk"})))
(ks/pn (- (system-time) start))))
(require '[clojure.browser.repl :as cbr])
(ks/<pp (<id-token))
)
|
[
{
"context": " Map is a form, see map/Maps.clj\n(println {:name \"Cesar\" :age 50})\n\n;A Set is a form, sett set/Sets.clj\n(",
"end": 802,
"score": 0.9998660087585449,
"start": 797,
"tag": "NAME",
"value": "Cesar"
},
{
"context": "\n\n;A Set is a form, sett set/Sets.clj\n(println #{\"Abe\", \"Ray\", \"Ann\", \"Lisa\"})\n",
"end": 866,
"score": 0.9998324513435364,
"start": 863,
"tag": "NAME",
"value": "Abe"
},
{
"context": "t is a form, sett set/Sets.clj\n(println #{\"Abe\", \"Ray\", \"Ann\", \"Lisa\"})\n",
"end": 873,
"score": 0.999869167804718,
"start": 870,
"tag": "NAME",
"value": "Ray"
},
{
"context": "form, sett set/Sets.clj\n(println #{\"Abe\", \"Ray\", \"Ann\", \"Lisa\"})\n",
"end": 880,
"score": 0.9998732209205627,
"start": 877,
"tag": "NAME",
"value": "Ann"
},
{
"context": "ett set/Sets.clj\n(println #{\"Abe\", \"Ray\", \"Ann\", \"Lisa\"})\n",
"end": 888,
"score": 0.9998235702514648,
"start": 884,
"tag": "NAME",
"value": "Lisa"
}
] |
clojure/forms/forms.clj
|
miroadamy/language-matrix
| 15 |
; Chunks of data read by the clojure reader.
; A number is a form, see number/Numbers.clj
(println 22)
(println 44.3)
; A Vector is a form, see vector/Vector.clj
(println [1 2 3])
; A List is a form see list/Lists.clj
(println 1 2 3)
; A List with a function is also a form, see function/Functions.clj
; Having the + in the beginning is prefix notation
(println (+ 1 2 4))
;A boolean is a form, see boolean/Booleans.clj
(println true)
(println false)
;A character is a form, see character/Characters.clj
(println \b)
;A symbol is a form, see symbol/symbols.clj
(println java.lang.String)
; TODO: (println user/foo) fix this
;A Nil is a form, see nil/Nils.clj
(println nil)
;A Keyword is a form, see keyword/Keywords.clj
(println :bob)
;A Map is a form, see map/Maps.clj
(println {:name "Cesar" :age 50})
;A Set is a form, sett set/Sets.clj
(println #{"Abe", "Ray", "Ann", "Lisa"})
|
18793
|
; Chunks of data read by the clojure reader.
; A number is a form, see number/Numbers.clj
(println 22)
(println 44.3)
; A Vector is a form, see vector/Vector.clj
(println [1 2 3])
; A List is a form see list/Lists.clj
(println 1 2 3)
; A List with a function is also a form, see function/Functions.clj
; Having the + in the beginning is prefix notation
(println (+ 1 2 4))
;A boolean is a form, see boolean/Booleans.clj
(println true)
(println false)
;A character is a form, see character/Characters.clj
(println \b)
;A symbol is a form, see symbol/symbols.clj
(println java.lang.String)
; TODO: (println user/foo) fix this
;A Nil is a form, see nil/Nils.clj
(println nil)
;A Keyword is a form, see keyword/Keywords.clj
(println :bob)
;A Map is a form, see map/Maps.clj
(println {:name "<NAME>" :age 50})
;A Set is a form, sett set/Sets.clj
(println #{"<NAME>", "<NAME>", "<NAME>", "<NAME>"})
| true |
; Chunks of data read by the clojure reader.
; A number is a form, see number/Numbers.clj
(println 22)
(println 44.3)
; A Vector is a form, see vector/Vector.clj
(println [1 2 3])
; A List is a form see list/Lists.clj
(println 1 2 3)
; A List with a function is also a form, see function/Functions.clj
; Having the + in the beginning is prefix notation
(println (+ 1 2 4))
;A boolean is a form, see boolean/Booleans.clj
(println true)
(println false)
;A character is a form, see character/Characters.clj
(println \b)
;A symbol is a form, see symbol/symbols.clj
(println java.lang.String)
; TODO: (println user/foo) fix this
;A Nil is a form, see nil/Nils.clj
(println nil)
;A Keyword is a form, see keyword/Keywords.clj
(println :bob)
;A Map is a form, see map/Maps.clj
(println {:name "PI:NAME:<NAME>END_PI" :age 50})
;A Set is a form, sett set/Sets.clj
(println #{"PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"})
|
[
{
"context": "tart as opposed to waiting for it to finish\n(force jackson-5-delay)\n;; => \"First deref: Just call my name and I'll b",
"end": 2099,
"score": 0.8903940320014954,
"start": 2084,
"tag": "USERNAME",
"value": "jackson-5-delay"
},
{
"context": "re\"\n;; => \"Just call my name and I'll be there\"\n\n@jackson-5-delay\n;; => \"Just call my name and I'll be there\"\n;; On",
"end": 2219,
"score": 0.9563339352607727,
"start": 2204,
"tag": "USERNAME",
"value": "jackson-5-delay"
},
{
"context": "eadshot]\n true)\n(let [notify (delay (email-user \"[email protected]\"))]\n (doseq [headshot gimli-headshots]\n (futu",
"end": 2675,
"score": 0.9998733997344971,
"start": 2655,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
code/clojure-noob/src/clojure_noob/ch9.clj
|
itsrainingmani/learn-clojure-in-public
| 7 |
(ns clojure-noob.ch9
(:require [clojure.string :as str]
[clojure.repl :as repl])
(:import (java.net URLEncoder))
(:gen-class))
;; Concurrency - managing more than one task at the same time
;; Parallelism - executing more than one task at the same time
(let [result (future (println "this prints once")
(+ 1 1))]
(println "deref: " (deref result))
(println "@: " @result))
;; Once a future's body has been executed once, the result is cached
;; on next deref, the println won't execute
;; derefing a future blocks if the future hasn't finished running
;; place a time limit on how long to wait for a future
(deref (future (Thread/sleep 1000) 0) 10 5) ;; returns 10 if future doesn't return a value within 10 milliseconds
;; ([ref] [ref timeout-ms timeout-val])
(realized? (future (Thread/sleep 1000)))
(let [f (future)]
@f
(realized? f))
;; => true
;; future - chuck tasks onto other threads
;; Clojure allows you to treat task defn and requiring the result independently with delays and promises
;; First Concurrency Goblin
;; reference cell problem - occurs when two threads can read and write to the same location and the value of the location depends on the order of the reads and writes
;; Second Concurrency Goblin
;; Mutual Exclusion - each thread is trying to write something to file but doesn't have exclusive write access. the output ends up being garbled because the writes are interleaved
;; Third Concurrency Goblin
;; deadlock - each thread blocks indefinitely for a resource to become available
;; 3 events - Task Defn, Task Execution and Requiring a Task's result
;; Delays - define a task without having to execute it or require the result indefinitely
(def jackson-5-delay
(delay (let [message "Just call my name and I'll be there"]
(println "First deref: " message)
message)))
;; evaluate the delay and get result by deref or force
;; force is identical to deref but communicates the intent more clearly
;; causing a task to start as opposed to waiting for it to finish
(force jackson-5-delay)
;; => "First deref: Just call my name and I'll be there"
;; => "Just call my name and I'll be there"
@jackson-5-delay
;; => "Just call my name and I'll be there"
;; One way you can use a delay is to fire off a statement the first time one future out of a group of related futures finishes
(def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"])
(defn email-user
[email-address]
(println "Sending headshot notification to" email-address))
(defn upload-document
"Needs to be implemented"
[headshot]
true)
(let [notify (delay (email-user "[email protected]"))]
(doseq [headshot gimli-headshots]
(future (upload-document headshot)
(force notify))))
;; Promises allow you to express that you expect a result without having to define the task that should produce it or when that task should run
(def my-promise (promise))
(deliver my-promise (+ 1 2))
@my-promise
;; create a promise and deliver a value to it
;; Can only deliver a value to a promise once
(def yak-butter-international
{:store "Yak Butter International"
:price 90
:smoothness 90})
(def butter-than-nothing
{:store "Butter Than Nothing"
:price 150
:smoothness 83})
;; This is the butter that meets our requirements
(def baby-got-yak
{:store "Baby Got Yak"
:price 94
:smoothness 99})
(defn mock-api-call
[result]
(Thread/sleep 1000)
result)
(defn satisfactory?
"if the butter meets our criteria, return it, else return false"
[butter]
(and (<= (:price butter) 100)
(>= (:smoothness butter) 97)
butter))
;; Happens synchronously. Takes about 3 seconds
(time (some (comp satisfactory? mock-api-call)
[yak-butter-international butter-than-nothing baby-got-yak]))
(time
(let [butter-promise (promise)]
(doseq [butter [yak-butter-international butter-than-nothing baby-got-yak]]
(future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))]
(deliver butter-promise satisfactory-butter))))
(println "And the winner is: " @butter-promise)))
;; And the winner is: {:store Baby Got Yak, :price 94, :smoothness 99}
;; "Elapsed time: 1003.752965 msecs"
;; Decouples the requirement for a result from how the result from how the result is actually computed. Can perform multiple computations in parallel.
(let [p (promise)]
(deref p 100 "timed out"))
;; => "timed out"
(let [ferengi-wisdom-promise (promise)]
(future (println "here's some ferengi wisdom: " @ferengi-wisdom-promise))
(Thread/sleep 100)
(deliver ferengi-wisdom-promise "WHisper your way to success."))
;; => #<Promise@3edac563: "WHisper your way to success.">
;; here's some ferengi wisdom: WHisper your way to success.
;; Rolling your own Q
(defmacro wait
"Sleep `timeout` seconds before evaluating the body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
(wait 200 (println "Bippity Boppity Boo"))
(let [saying3 (promise)]
(future (deliver saying3 (wait 100 "Cheerio")))
@(let [saying2 (promise)]
(future (deliver saying2 (wait 400 "Pip pip!")))
@(let [saying1 (promise)]
(future (deliver saying1 (wait 200 "Ello, gov'na!")))
(println @saying1)
saying1)
(println @saying2)
saying2)
(println @saying3)
saying3)
(defmacro enqueue
([q concurrent-promise-name concurrent serialized]
`(let [~concurrent-promise-name (promise)]
(future (deliver ~concurrent-promise-name ~concurrent))
(deref ~q)
~serialized
~concurrent-promise-name))
([concurrent-promise-name concurrent serialized]
~(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized)))
;; Chapter Exercises
;; 1. Write a function that takes a string as an argument and searches for it on Bing and Google using the slurp function. Your function should return the HTML of the first page returned by the search.
(defmacro ustr
"URL Encodes the string"
[& s]
`(URLEncoder/encode (str ~@s)))
(defn construct-search-url
"Given the name of a search engine, Constructs a valid search URL"
[engine]
(str "https://" engine ".com/search?q%3D")) ;; Have to url encode the space
(defn search-on-web
[search-string]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x ["bing" "google"]]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "athens"))
;; 2. Update your function so it takes a second argument consisting of the search engines to use.
(defn search-on-web
[search-string engines]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "I am a doo doo head" ["bing" "google"]))
(:engine srch)
;; => "google"
;; 3. Create a new function that takes a search term and search engines as arguments, and returns a vector of the URLs from the first page of search results from each search engine.
(def url-regex #"(?i)\b((?:([a-z][\w-]+:(?:/{1,3}|[a-z0-9%]))|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
(defn first-page-urls
"Takes a search term, search engines and returns a vector of URLS from first page from each search engine"
[search-string engines]
(let [encoded-search (ustr search-string)
first-page-urls (atom {})]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (swap! first-page-urls assoc (keyword x)
(map first (re-seq url-regex (slurp search-url)))))))
first-page-urls))
(def srch (first-page-urls "Athens Research" ["bing" "google"]))
|
73348
|
(ns clojure-noob.ch9
(:require [clojure.string :as str]
[clojure.repl :as repl])
(:import (java.net URLEncoder))
(:gen-class))
;; Concurrency - managing more than one task at the same time
;; Parallelism - executing more than one task at the same time
(let [result (future (println "this prints once")
(+ 1 1))]
(println "deref: " (deref result))
(println "@: " @result))
;; Once a future's body has been executed once, the result is cached
;; on next deref, the println won't execute
;; derefing a future blocks if the future hasn't finished running
;; place a time limit on how long to wait for a future
(deref (future (Thread/sleep 1000) 0) 10 5) ;; returns 10 if future doesn't return a value within 10 milliseconds
;; ([ref] [ref timeout-ms timeout-val])
(realized? (future (Thread/sleep 1000)))
(let [f (future)]
@f
(realized? f))
;; => true
;; future - chuck tasks onto other threads
;; Clojure allows you to treat task defn and requiring the result independently with delays and promises
;; First Concurrency Goblin
;; reference cell problem - occurs when two threads can read and write to the same location and the value of the location depends on the order of the reads and writes
;; Second Concurrency Goblin
;; Mutual Exclusion - each thread is trying to write something to file but doesn't have exclusive write access. the output ends up being garbled because the writes are interleaved
;; Third Concurrency Goblin
;; deadlock - each thread blocks indefinitely for a resource to become available
;; 3 events - Task Defn, Task Execution and Requiring a Task's result
;; Delays - define a task without having to execute it or require the result indefinitely
(def jackson-5-delay
(delay (let [message "Just call my name and I'll be there"]
(println "First deref: " message)
message)))
;; evaluate the delay and get result by deref or force
;; force is identical to deref but communicates the intent more clearly
;; causing a task to start as opposed to waiting for it to finish
(force jackson-5-delay)
;; => "First deref: Just call my name and I'll be there"
;; => "Just call my name and I'll be there"
@jackson-5-delay
;; => "Just call my name and I'll be there"
;; One way you can use a delay is to fire off a statement the first time one future out of a group of related futures finishes
(def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"])
(defn email-user
[email-address]
(println "Sending headshot notification to" email-address))
(defn upload-document
"Needs to be implemented"
[headshot]
true)
(let [notify (delay (email-user "<EMAIL>"))]
(doseq [headshot gimli-headshots]
(future (upload-document headshot)
(force notify))))
;; Promises allow you to express that you expect a result without having to define the task that should produce it or when that task should run
(def my-promise (promise))
(deliver my-promise (+ 1 2))
@my-promise
;; create a promise and deliver a value to it
;; Can only deliver a value to a promise once
(def yak-butter-international
{:store "Yak Butter International"
:price 90
:smoothness 90})
(def butter-than-nothing
{:store "Butter Than Nothing"
:price 150
:smoothness 83})
;; This is the butter that meets our requirements
(def baby-got-yak
{:store "Baby Got Yak"
:price 94
:smoothness 99})
(defn mock-api-call
[result]
(Thread/sleep 1000)
result)
(defn satisfactory?
"if the butter meets our criteria, return it, else return false"
[butter]
(and (<= (:price butter) 100)
(>= (:smoothness butter) 97)
butter))
;; Happens synchronously. Takes about 3 seconds
(time (some (comp satisfactory? mock-api-call)
[yak-butter-international butter-than-nothing baby-got-yak]))
(time
(let [butter-promise (promise)]
(doseq [butter [yak-butter-international butter-than-nothing baby-got-yak]]
(future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))]
(deliver butter-promise satisfactory-butter))))
(println "And the winner is: " @butter-promise)))
;; And the winner is: {:store Baby Got Yak, :price 94, :smoothness 99}
;; "Elapsed time: 1003.752965 msecs"
;; Decouples the requirement for a result from how the result from how the result is actually computed. Can perform multiple computations in parallel.
(let [p (promise)]
(deref p 100 "timed out"))
;; => "timed out"
(let [ferengi-wisdom-promise (promise)]
(future (println "here's some ferengi wisdom: " @ferengi-wisdom-promise))
(Thread/sleep 100)
(deliver ferengi-wisdom-promise "WHisper your way to success."))
;; => #<Promise@3edac563: "WHisper your way to success.">
;; here's some ferengi wisdom: WHisper your way to success.
;; Rolling your own Q
(defmacro wait
"Sleep `timeout` seconds before evaluating the body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
(wait 200 (println "Bippity Boppity Boo"))
(let [saying3 (promise)]
(future (deliver saying3 (wait 100 "Cheerio")))
@(let [saying2 (promise)]
(future (deliver saying2 (wait 400 "Pip pip!")))
@(let [saying1 (promise)]
(future (deliver saying1 (wait 200 "Ello, gov'na!")))
(println @saying1)
saying1)
(println @saying2)
saying2)
(println @saying3)
saying3)
(defmacro enqueue
([q concurrent-promise-name concurrent serialized]
`(let [~concurrent-promise-name (promise)]
(future (deliver ~concurrent-promise-name ~concurrent))
(deref ~q)
~serialized
~concurrent-promise-name))
([concurrent-promise-name concurrent serialized]
~(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized)))
;; Chapter Exercises
;; 1. Write a function that takes a string as an argument and searches for it on Bing and Google using the slurp function. Your function should return the HTML of the first page returned by the search.
(defmacro ustr
"URL Encodes the string"
[& s]
`(URLEncoder/encode (str ~@s)))
(defn construct-search-url
"Given the name of a search engine, Constructs a valid search URL"
[engine]
(str "https://" engine ".com/search?q%3D")) ;; Have to url encode the space
(defn search-on-web
[search-string]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x ["bing" "google"]]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "athens"))
;; 2. Update your function so it takes a second argument consisting of the search engines to use.
(defn search-on-web
[search-string engines]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "I am a doo doo head" ["bing" "google"]))
(:engine srch)
;; => "google"
;; 3. Create a new function that takes a search term and search engines as arguments, and returns a vector of the URLs from the first page of search results from each search engine.
(def url-regex #"(?i)\b((?:([a-z][\w-]+:(?:/{1,3}|[a-z0-9%]))|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
(defn first-page-urls
"Takes a search term, search engines and returns a vector of URLS from first page from each search engine"
[search-string engines]
(let [encoded-search (ustr search-string)
first-page-urls (atom {})]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (swap! first-page-urls assoc (keyword x)
(map first (re-seq url-regex (slurp search-url)))))))
first-page-urls))
(def srch (first-page-urls "Athens Research" ["bing" "google"]))
| true |
(ns clojure-noob.ch9
(:require [clojure.string :as str]
[clojure.repl :as repl])
(:import (java.net URLEncoder))
(:gen-class))
;; Concurrency - managing more than one task at the same time
;; Parallelism - executing more than one task at the same time
(let [result (future (println "this prints once")
(+ 1 1))]
(println "deref: " (deref result))
(println "@: " @result))
;; Once a future's body has been executed once, the result is cached
;; on next deref, the println won't execute
;; derefing a future blocks if the future hasn't finished running
;; place a time limit on how long to wait for a future
(deref (future (Thread/sleep 1000) 0) 10 5) ;; returns 10 if future doesn't return a value within 10 milliseconds
;; ([ref] [ref timeout-ms timeout-val])
(realized? (future (Thread/sleep 1000)))
(let [f (future)]
@f
(realized? f))
;; => true
;; future - chuck tasks onto other threads
;; Clojure allows you to treat task defn and requiring the result independently with delays and promises
;; First Concurrency Goblin
;; reference cell problem - occurs when two threads can read and write to the same location and the value of the location depends on the order of the reads and writes
;; Second Concurrency Goblin
;; Mutual Exclusion - each thread is trying to write something to file but doesn't have exclusive write access. the output ends up being garbled because the writes are interleaved
;; Third Concurrency Goblin
;; deadlock - each thread blocks indefinitely for a resource to become available
;; 3 events - Task Defn, Task Execution and Requiring a Task's result
;; Delays - define a task without having to execute it or require the result indefinitely
(def jackson-5-delay
(delay (let [message "Just call my name and I'll be there"]
(println "First deref: " message)
message)))
;; evaluate the delay and get result by deref or force
;; force is identical to deref but communicates the intent more clearly
;; causing a task to start as opposed to waiting for it to finish
(force jackson-5-delay)
;; => "First deref: Just call my name and I'll be there"
;; => "Just call my name and I'll be there"
@jackson-5-delay
;; => "Just call my name and I'll be there"
;; One way you can use a delay is to fire off a statement the first time one future out of a group of related futures finishes
(def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"])
(defn email-user
[email-address]
(println "Sending headshot notification to" email-address))
(defn upload-document
"Needs to be implemented"
[headshot]
true)
(let [notify (delay (email-user "PI:EMAIL:<EMAIL>END_PI"))]
(doseq [headshot gimli-headshots]
(future (upload-document headshot)
(force notify))))
;; Promises allow you to express that you expect a result without having to define the task that should produce it or when that task should run
(def my-promise (promise))
(deliver my-promise (+ 1 2))
@my-promise
;; create a promise and deliver a value to it
;; Can only deliver a value to a promise once
(def yak-butter-international
{:store "Yak Butter International"
:price 90
:smoothness 90})
(def butter-than-nothing
{:store "Butter Than Nothing"
:price 150
:smoothness 83})
;; This is the butter that meets our requirements
(def baby-got-yak
{:store "Baby Got Yak"
:price 94
:smoothness 99})
(defn mock-api-call
[result]
(Thread/sleep 1000)
result)
(defn satisfactory?
"if the butter meets our criteria, return it, else return false"
[butter]
(and (<= (:price butter) 100)
(>= (:smoothness butter) 97)
butter))
;; Happens synchronously. Takes about 3 seconds
(time (some (comp satisfactory? mock-api-call)
[yak-butter-international butter-than-nothing baby-got-yak]))
(time
(let [butter-promise (promise)]
(doseq [butter [yak-butter-international butter-than-nothing baby-got-yak]]
(future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))]
(deliver butter-promise satisfactory-butter))))
(println "And the winner is: " @butter-promise)))
;; And the winner is: {:store Baby Got Yak, :price 94, :smoothness 99}
;; "Elapsed time: 1003.752965 msecs"
;; Decouples the requirement for a result from how the result from how the result is actually computed. Can perform multiple computations in parallel.
(let [p (promise)]
(deref p 100 "timed out"))
;; => "timed out"
(let [ferengi-wisdom-promise (promise)]
(future (println "here's some ferengi wisdom: " @ferengi-wisdom-promise))
(Thread/sleep 100)
(deliver ferengi-wisdom-promise "WHisper your way to success."))
;; => #<Promise@3edac563: "WHisper your way to success.">
;; here's some ferengi wisdom: WHisper your way to success.
;; Rolling your own Q
(defmacro wait
"Sleep `timeout` seconds before evaluating the body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
(wait 200 (println "Bippity Boppity Boo"))
(let [saying3 (promise)]
(future (deliver saying3 (wait 100 "Cheerio")))
@(let [saying2 (promise)]
(future (deliver saying2 (wait 400 "Pip pip!")))
@(let [saying1 (promise)]
(future (deliver saying1 (wait 200 "Ello, gov'na!")))
(println @saying1)
saying1)
(println @saying2)
saying2)
(println @saying3)
saying3)
(defmacro enqueue
([q concurrent-promise-name concurrent serialized]
`(let [~concurrent-promise-name (promise)]
(future (deliver ~concurrent-promise-name ~concurrent))
(deref ~q)
~serialized
~concurrent-promise-name))
([concurrent-promise-name concurrent serialized]
~(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized)))
;; Chapter Exercises
;; 1. Write a function that takes a string as an argument and searches for it on Bing and Google using the slurp function. Your function should return the HTML of the first page returned by the search.
(defmacro ustr
"URL Encodes the string"
[& s]
`(URLEncoder/encode (str ~@s)))
(defn construct-search-url
"Given the name of a search engine, Constructs a valid search URL"
[engine]
(str "https://" engine ".com/search?q%3D")) ;; Have to url encode the space
(defn search-on-web
[search-string]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x ["bing" "google"]]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "athens"))
;; 2. Update your function so it takes a second argument consisting of the search engines to use.
(defn search-on-web
[search-string engines]
(let [encoded-search (ustr search-string)
first-page (promise)]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (deliver first-page {:page (slurp search-url) :engine x}))))
(deref first-page)))
(def srch (search-on-web "I am a doo doo head" ["bing" "google"]))
(:engine srch)
;; => "google"
;; 3. Create a new function that takes a search term and search engines as arguments, and returns a vector of the URLs from the first page of search results from each search engine.
(def url-regex #"(?i)\b((?:([a-z][\w-]+:(?:/{1,3}|[a-z0-9%]))|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
(defn first-page-urls
"Takes a search term, search engines and returns a vector of URLS from first page from each search engine"
[search-string engines]
(let [encoded-search (ustr search-string)
first-page-urls (atom {})]
(doseq [x engines]
(let [search-url (str (construct-search-url x) encoded-search)]
(future (swap! first-page-urls assoc (keyword x)
(map first (re-seq url-regex (slurp search-url)))))))
first-page-urls))
(def srch (first-page-urls "Athens Research" ["bing" "google"]))
|
[
{
"context": ";; copyright (c) 2021 Michaël Salihi, all rights reserved\n\n(ns usermanager.system\n (:",
"end": 36,
"score": 0.9998747110366821,
"start": 22,
"tag": "NAME",
"value": "Michaël Salihi"
}
] |
src/usermanager/system.clj
|
prestancedesign/usermanager-inertia-example
| 3 |
;; copyright (c) 2021 Michaël Salihi, all rights reserved
(ns usermanager.system
(:require [integrant.core :as ig]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[ring.adapter.jetty :refer [run-jetty]]
[usermanager.handler :as handler]
[usermanager.model.user-manager :refer [populate]]))
(def config
{:adapter/jetty {:handler (ig/ref :handler/run-app) :port 3000}
:handler/run-app {:db (ig/ref :database.sql/connection)}
:database.sql/connection {:dbtype "sqlite" :dbname "usermanager_db"}})
(defmethod ig/init-key :adapter/jetty [_ {:keys [handler] :as opts}]
(run-jetty handler (-> opts (dissoc handler) (assoc :join? false))))
(defmethod ig/init-key :handler/run-app [_ {:keys [db]}]
(handler/app db))
(defmethod ig/init-key :database.sql/connection [_ db-spec]
(let [conn (jdbc/get-datasource db-spec)]
(populate conn (:dbtype db-spec))
(jdbc/with-options conn {:builder-fn rs/as-unqualified-maps})))
(defmethod ig/halt-key! :adapter/jetty [_ server]
(.stop server))
(defn -main []
(ig/init config))
|
107833
|
;; copyright (c) 2021 <NAME>, all rights reserved
(ns usermanager.system
(:require [integrant.core :as ig]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[ring.adapter.jetty :refer [run-jetty]]
[usermanager.handler :as handler]
[usermanager.model.user-manager :refer [populate]]))
(def config
{:adapter/jetty {:handler (ig/ref :handler/run-app) :port 3000}
:handler/run-app {:db (ig/ref :database.sql/connection)}
:database.sql/connection {:dbtype "sqlite" :dbname "usermanager_db"}})
(defmethod ig/init-key :adapter/jetty [_ {:keys [handler] :as opts}]
(run-jetty handler (-> opts (dissoc handler) (assoc :join? false))))
(defmethod ig/init-key :handler/run-app [_ {:keys [db]}]
(handler/app db))
(defmethod ig/init-key :database.sql/connection [_ db-spec]
(let [conn (jdbc/get-datasource db-spec)]
(populate conn (:dbtype db-spec))
(jdbc/with-options conn {:builder-fn rs/as-unqualified-maps})))
(defmethod ig/halt-key! :adapter/jetty [_ server]
(.stop server))
(defn -main []
(ig/init config))
| true |
;; copyright (c) 2021 PI:NAME:<NAME>END_PI, all rights reserved
(ns usermanager.system
(:require [integrant.core :as ig]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[ring.adapter.jetty :refer [run-jetty]]
[usermanager.handler :as handler]
[usermanager.model.user-manager :refer [populate]]))
(def config
{:adapter/jetty {:handler (ig/ref :handler/run-app) :port 3000}
:handler/run-app {:db (ig/ref :database.sql/connection)}
:database.sql/connection {:dbtype "sqlite" :dbname "usermanager_db"}})
(defmethod ig/init-key :adapter/jetty [_ {:keys [handler] :as opts}]
(run-jetty handler (-> opts (dissoc handler) (assoc :join? false))))
(defmethod ig/init-key :handler/run-app [_ {:keys [db]}]
(handler/app db))
(defmethod ig/init-key :database.sql/connection [_ db-spec]
(let [conn (jdbc/get-datasource db-spec)]
(populate conn (:dbtype db-spec))
(jdbc/with-options conn {:builder-fn rs/as-unqualified-maps})))
(defmethod ig/halt-key! :adapter/jetty [_ server]
(.stop server))
(defn -main []
(ig/init config))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2015-11-18\"\n :doc \"Unit tests for za",
"end": 105,
"score": 0.9998773336410522,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] |
src/test/clojure/zana/test/math/prng.clj
|
wahpenayo/zana
| 2 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2015-11-18"
:doc "Unit tests for zana.stats.prng." }
zana.test.math.prng
(:require [clojure.test :as test]
[zana.stats.prng :as prng])
(:import [org.uncommons.maths.binary BinaryUtils]
[org.uncommons.maths.random MersenneTwisterRNG]))
;;------------------------------------------------------------------------------
(test/deftest mersenne-twister-seed
(let [seed0 (prng/mersenne-twister-seed)
seed1 (prng/mersenne-twister-seed)]
(test/is (not (nil? seed0)))
(test/is (not (nil? seed1)))
(test/is (not= seed0 seed1))))
(test/deftest mersenne-twister-generator
(let [seed0 "21CEE048585DD1821A40D3556E1FD10E"
b (into [] (BinaryUtils/convertHexStringToBytes seed0))
^MersenneTwisterRNG prng0 (prng/mersenne-twister-generator seed0)
b0 (into [] (.getSeed prng0))
^MersenneTwisterRNG prng1 (prng/mersenne-twister-generator)
b1 (into [] (.getSeed prng1))]
(test/is (not (nil? prng0)))
(test/is (not (nil? prng1)))
(test/is (not= prng0 prng1))
(test/is (not= (.nextLong prng0) (.nextLong prng0)))
(test/is (not= (.nextLong prng0) (.nextLong prng1)))
(test/is (= b b0))
(test/is (not= b0 b1))))
;;------------------------------------------------------------------------------
|
71384
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2015-11-18"
:doc "Unit tests for zana.stats.prng." }
zana.test.math.prng
(:require [clojure.test :as test]
[zana.stats.prng :as prng])
(:import [org.uncommons.maths.binary BinaryUtils]
[org.uncommons.maths.random MersenneTwisterRNG]))
;;------------------------------------------------------------------------------
(test/deftest mersenne-twister-seed
(let [seed0 (prng/mersenne-twister-seed)
seed1 (prng/mersenne-twister-seed)]
(test/is (not (nil? seed0)))
(test/is (not (nil? seed1)))
(test/is (not= seed0 seed1))))
(test/deftest mersenne-twister-generator
(let [seed0 "21CEE048585DD1821A40D3556E1FD10E"
b (into [] (BinaryUtils/convertHexStringToBytes seed0))
^MersenneTwisterRNG prng0 (prng/mersenne-twister-generator seed0)
b0 (into [] (.getSeed prng0))
^MersenneTwisterRNG prng1 (prng/mersenne-twister-generator)
b1 (into [] (.getSeed prng1))]
(test/is (not (nil? prng0)))
(test/is (not (nil? prng1)))
(test/is (not= prng0 prng1))
(test/is (not= (.nextLong prng0) (.nextLong prng0)))
(test/is (not= (.nextLong prng0) (.nextLong prng1)))
(test/is (= b b0))
(test/is (not= b0 b1))))
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2015-11-18"
:doc "Unit tests for zana.stats.prng." }
zana.test.math.prng
(:require [clojure.test :as test]
[zana.stats.prng :as prng])
(:import [org.uncommons.maths.binary BinaryUtils]
[org.uncommons.maths.random MersenneTwisterRNG]))
;;------------------------------------------------------------------------------
(test/deftest mersenne-twister-seed
(let [seed0 (prng/mersenne-twister-seed)
seed1 (prng/mersenne-twister-seed)]
(test/is (not (nil? seed0)))
(test/is (not (nil? seed1)))
(test/is (not= seed0 seed1))))
(test/deftest mersenne-twister-generator
(let [seed0 "21CEE048585DD1821A40D3556E1FD10E"
b (into [] (BinaryUtils/convertHexStringToBytes seed0))
^MersenneTwisterRNG prng0 (prng/mersenne-twister-generator seed0)
b0 (into [] (.getSeed prng0))
^MersenneTwisterRNG prng1 (prng/mersenne-twister-generator)
b1 (into [] (.getSeed prng1))]
(test/is (not (nil? prng0)))
(test/is (not (nil? prng1)))
(test/is (not= prng0 prng1))
(test/is (not= (.nextLong prng0) (.nextLong prng0)))
(test/is (not= (.nextLong prng0) (.nextLong prng1)))
(test/is (= b b0))
(test/is (not= b0 b1))))
;;------------------------------------------------------------------------------
|
[
{
"context": " (str v)] {:key (str \"gae-s-\" v)}))\n v-schema)",
"end": 4336,
"score": 0.6351317763328552,
"start": 4329,
"tag": "KEY",
"value": "gae-s-\""
}
] |
src/cljs/cocdan/modals/general_attr_editor.cljs
|
chaomi1998/cocdan
| 3 |
(ns cocdan.modals.general-attr-editor
(:require
[reagent.core :as r]
[cocdan.auxiliary :as aux]
[re-frame.core :as rf]))
(defonce active? (r/atom false))
(defonce attrs (r/atom nil))
(defonce col-keys (r/atom nil))
(defonce base-key (r/atom nil))
(defonce schema (r/atom {}))
(sort (:substage @schema))
(aux/init-page
{}
{:event/modal-general-attr-editor-active
(fn [_ _ base-key' col-keys' attrs' schema']
(if (and
(not (nil? (:id attrs')))
(contains? #{:avatar :stage} base-key'))
(do (reset! active? true)
(reset! attrs attrs')
(reset! base-key base-key')
(reset! col-keys col-keys')
(if (nil? schema')
(reset! schema (reduce (fn [a f]
(f a)) attrs' col-keys'))
(reset! schema schema')))
(do
(js/console.log "no id")
(js/console.log attrs')))
{})})
(defn- edit-cancel
[]
(reset! active? false))
(defn- check-list-candidate
[path default-value v-schema]
(cond
(set? v-schema) (let [filtered-default-value (set (filter #(contains? v-schema %) default-value))]
(when (not= (set default-value) (set filtered-default-value))
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) filtered-default-value)))
filtered-default-value))
(or
(vector? v-schema)
(seq? v-schema)) (if (contains? (set v-schema) default-value)
(.indexOf v-schema default-value)
(do
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) (first v-schema))))
(first v-schema)))
:else default-value))
(defn- edit-item
[path default-value' v-schema]
(let [default-value (check-list-candidate path default-value' v-schema)
key-path (conj @col-keys (keyword path))]
[:div {:class "field is-horizontal"}
[:div {:class "field-label is-normal"}
[:label (str path)]]
[:div.field-body>div.field>div.control
(cond
(string? v-schema) [:input.input
{:placeholder "string"
:defaultValue default-value
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (-> % .-target .-value))))}]
(int? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseInt (-> % .-target .-value)))))}]
(float? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseFloat (-> % .-target .-value)))))}]
(set? v-schema) [:div.select {:class "is-multiple"}
[:select {:multiple true
:size 8
:style {:max-height "10em"}
:value (let [val (reduce (fn [a f] (f a)) @attrs key-path)
seqval (seq val)]
(if (nil? seqval)
[]
seqval))
:on-change #()
:on-click (fn [e]
(let [value (-> e .-target .-value)
ori-value (set (reduce (fn [a f] (f a)) @attrs key-path))]
(if (contains? ori-value value)
(swap! attrs (fn [a] (assoc-in a key-path (disj ori-value value))))
(swap! attrs (fn [a] (assoc-in a key-path (conj ori-value value)))))))}
(doall (map
(fn [v] (with-meta [:option
(str v)] {:key (str "gae-s-" v)}))
v-schema))]]
(seq v-schema) [:div.select
[:select
{:default-value default-value
:on-change #(swap! attrs (fn [a]
(assoc-in a key-path
(nth v-schema (js/parseInt (-> % .-target .-value))))))}
(doall (map-indexed
(fn [i v] (with-meta [:option
{:value i}
(str v)] {:key (str "gae-s-" i)}))
v-schema))
(when (< (count v-schema) default-value)
(swap! attrs (fn [a] (assoc-in a key-path (first v-schema)))))]])]]))
(defn general-attr-editor
[]
(when (and @active? (not (nil? @attrs)))
[:div.modal {:class "is-active"}
[:div.modal-background {:on-click edit-cancel}]
[:div.modal-card
[:header.modal-card-head
[:p "general attribute editor for " (str @col-keys)]]
[:section.modal-card-body
(let [value (reduce (fn [a f] (f a)) @attrs @col-keys)]
(doall (for [[k v-schema] @schema]
(with-meta (edit-item k (k value) v-schema) {:key (str "gae-" k)}))))]
[:footer.modal-card-foot
[:button.button {:class "is-primary"
:on-click #(do
(rf/dispatch [:event/patch-to-server @base-key (assoc-in
{:id (:id @attrs)}
@col-keys
(reduce (fn [a f] (f a)) @attrs @col-keys))])
(edit-cancel))} "Submit"]
[:button.button {:on-click edit-cancel} "Cancel"]]]]))
|
40497
|
(ns cocdan.modals.general-attr-editor
(:require
[reagent.core :as r]
[cocdan.auxiliary :as aux]
[re-frame.core :as rf]))
(defonce active? (r/atom false))
(defonce attrs (r/atom nil))
(defonce col-keys (r/atom nil))
(defonce base-key (r/atom nil))
(defonce schema (r/atom {}))
(sort (:substage @schema))
(aux/init-page
{}
{:event/modal-general-attr-editor-active
(fn [_ _ base-key' col-keys' attrs' schema']
(if (and
(not (nil? (:id attrs')))
(contains? #{:avatar :stage} base-key'))
(do (reset! active? true)
(reset! attrs attrs')
(reset! base-key base-key')
(reset! col-keys col-keys')
(if (nil? schema')
(reset! schema (reduce (fn [a f]
(f a)) attrs' col-keys'))
(reset! schema schema')))
(do
(js/console.log "no id")
(js/console.log attrs')))
{})})
(defn- edit-cancel
[]
(reset! active? false))
(defn- check-list-candidate
[path default-value v-schema]
(cond
(set? v-schema) (let [filtered-default-value (set (filter #(contains? v-schema %) default-value))]
(when (not= (set default-value) (set filtered-default-value))
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) filtered-default-value)))
filtered-default-value))
(or
(vector? v-schema)
(seq? v-schema)) (if (contains? (set v-schema) default-value)
(.indexOf v-schema default-value)
(do
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) (first v-schema))))
(first v-schema)))
:else default-value))
(defn- edit-item
[path default-value' v-schema]
(let [default-value (check-list-candidate path default-value' v-schema)
key-path (conj @col-keys (keyword path))]
[:div {:class "field is-horizontal"}
[:div {:class "field-label is-normal"}
[:label (str path)]]
[:div.field-body>div.field>div.control
(cond
(string? v-schema) [:input.input
{:placeholder "string"
:defaultValue default-value
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (-> % .-target .-value))))}]
(int? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseInt (-> % .-target .-value)))))}]
(float? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseFloat (-> % .-target .-value)))))}]
(set? v-schema) [:div.select {:class "is-multiple"}
[:select {:multiple true
:size 8
:style {:max-height "10em"}
:value (let [val (reduce (fn [a f] (f a)) @attrs key-path)
seqval (seq val)]
(if (nil? seqval)
[]
seqval))
:on-change #()
:on-click (fn [e]
(let [value (-> e .-target .-value)
ori-value (set (reduce (fn [a f] (f a)) @attrs key-path))]
(if (contains? ori-value value)
(swap! attrs (fn [a] (assoc-in a key-path (disj ori-value value))))
(swap! attrs (fn [a] (assoc-in a key-path (conj ori-value value)))))))}
(doall (map
(fn [v] (with-meta [:option
(str v)] {:key (str "<KEY> v)}))
v-schema))]]
(seq v-schema) [:div.select
[:select
{:default-value default-value
:on-change #(swap! attrs (fn [a]
(assoc-in a key-path
(nth v-schema (js/parseInt (-> % .-target .-value))))))}
(doall (map-indexed
(fn [i v] (with-meta [:option
{:value i}
(str v)] {:key (str "gae-s-" i)}))
v-schema))
(when (< (count v-schema) default-value)
(swap! attrs (fn [a] (assoc-in a key-path (first v-schema)))))]])]]))
(defn general-attr-editor
[]
(when (and @active? (not (nil? @attrs)))
[:div.modal {:class "is-active"}
[:div.modal-background {:on-click edit-cancel}]
[:div.modal-card
[:header.modal-card-head
[:p "general attribute editor for " (str @col-keys)]]
[:section.modal-card-body
(let [value (reduce (fn [a f] (f a)) @attrs @col-keys)]
(doall (for [[k v-schema] @schema]
(with-meta (edit-item k (k value) v-schema) {:key (str "gae-" k)}))))]
[:footer.modal-card-foot
[:button.button {:class "is-primary"
:on-click #(do
(rf/dispatch [:event/patch-to-server @base-key (assoc-in
{:id (:id @attrs)}
@col-keys
(reduce (fn [a f] (f a)) @attrs @col-keys))])
(edit-cancel))} "Submit"]
[:button.button {:on-click edit-cancel} "Cancel"]]]]))
| true |
(ns cocdan.modals.general-attr-editor
(:require
[reagent.core :as r]
[cocdan.auxiliary :as aux]
[re-frame.core :as rf]))
(defonce active? (r/atom false))
(defonce attrs (r/atom nil))
(defonce col-keys (r/atom nil))
(defonce base-key (r/atom nil))
(defonce schema (r/atom {}))
(sort (:substage @schema))
(aux/init-page
{}
{:event/modal-general-attr-editor-active
(fn [_ _ base-key' col-keys' attrs' schema']
(if (and
(not (nil? (:id attrs')))
(contains? #{:avatar :stage} base-key'))
(do (reset! active? true)
(reset! attrs attrs')
(reset! base-key base-key')
(reset! col-keys col-keys')
(if (nil? schema')
(reset! schema (reduce (fn [a f]
(f a)) attrs' col-keys'))
(reset! schema schema')))
(do
(js/console.log "no id")
(js/console.log attrs')))
{})})
(defn- edit-cancel
[]
(reset! active? false))
(defn- check-list-candidate
[path default-value v-schema]
(cond
(set? v-schema) (let [filtered-default-value (set (filter #(contains? v-schema %) default-value))]
(when (not= (set default-value) (set filtered-default-value))
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) filtered-default-value)))
filtered-default-value))
(or
(vector? v-schema)
(seq? v-schema)) (if (contains? (set v-schema) default-value)
(.indexOf v-schema default-value)
(do
(swap! attrs (fn [a] (assoc-in a (conj @col-keys (keyword path)) (first v-schema))))
(first v-schema)))
:else default-value))
(defn- edit-item
[path default-value' v-schema]
(let [default-value (check-list-candidate path default-value' v-schema)
key-path (conj @col-keys (keyword path))]
[:div {:class "field is-horizontal"}
[:div {:class "field-label is-normal"}
[:label (str path)]]
[:div.field-body>div.field>div.control
(cond
(string? v-schema) [:input.input
{:placeholder "string"
:defaultValue default-value
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (-> % .-target .-value))))}]
(int? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseInt (-> % .-target .-value)))))}]
(float? v-schema) [:input.input
{:placeholder v-schema
:defaultValue default-value
:type "number"
:on-change #(swap! attrs (fn [a] (assoc-in a key-path (js/parseFloat (-> % .-target .-value)))))}]
(set? v-schema) [:div.select {:class "is-multiple"}
[:select {:multiple true
:size 8
:style {:max-height "10em"}
:value (let [val (reduce (fn [a f] (f a)) @attrs key-path)
seqval (seq val)]
(if (nil? seqval)
[]
seqval))
:on-change #()
:on-click (fn [e]
(let [value (-> e .-target .-value)
ori-value (set (reduce (fn [a f] (f a)) @attrs key-path))]
(if (contains? ori-value value)
(swap! attrs (fn [a] (assoc-in a key-path (disj ori-value value))))
(swap! attrs (fn [a] (assoc-in a key-path (conj ori-value value)))))))}
(doall (map
(fn [v] (with-meta [:option
(str v)] {:key (str "PI:KEY:<KEY>END_PI v)}))
v-schema))]]
(seq v-schema) [:div.select
[:select
{:default-value default-value
:on-change #(swap! attrs (fn [a]
(assoc-in a key-path
(nth v-schema (js/parseInt (-> % .-target .-value))))))}
(doall (map-indexed
(fn [i v] (with-meta [:option
{:value i}
(str v)] {:key (str "gae-s-" i)}))
v-schema))
(when (< (count v-schema) default-value)
(swap! attrs (fn [a] (assoc-in a key-path (first v-schema)))))]])]]))
(defn general-attr-editor
[]
(when (and @active? (not (nil? @attrs)))
[:div.modal {:class "is-active"}
[:div.modal-background {:on-click edit-cancel}]
[:div.modal-card
[:header.modal-card-head
[:p "general attribute editor for " (str @col-keys)]]
[:section.modal-card-body
(let [value (reduce (fn [a f] (f a)) @attrs @col-keys)]
(doall (for [[k v-schema] @schema]
(with-meta (edit-item k (k value) v-schema) {:key (str "gae-" k)}))))]
[:footer.modal-card-foot
[:button.button {:class "is-primary"
:on-click #(do
(rf/dispatch [:event/patch-to-server @base-key (assoc-in
{:id (:id @attrs)}
@col-keys
(reduce (fn [a f] (f a)) @attrs @col-keys))])
(edit-cancel))} "Submit"]
[:button.button {:on-click edit-cancel} "Cancel"]]]]))
|
[
{
"context": ";; Copyright © 2015-2021 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.999875545501709,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
},
{
"context": "ong/parseLong port)\n :user user\n :password password\n :schema schema\n :table table}))\n\n(deftes",
"end": 8037,
"score": 0.9903337359428406,
"start": 8029,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "7f34234ec4_5dce9e39cf744126\"\n :password \"pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8\"\n :schema \"test_territorybro_49a5ab7f342",
"end": 8330,
"score": 0.9954123497009277,
"start": 8280,
"tag": "PASSWORD",
"value": "pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8"
},
{
"context": "user_49a5ab7f34234ec4_5dce9e39cf744126' password='pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8' sslmode=prefer key='id' srid=4326 type=MultiPoly",
"end": 8623,
"score": 0.9951820373535156,
"start": 8573,
"tag": "PASSWORD",
"value": "pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8"
},
{
"context": "Polygon table=\\\"test_territorybro_49a5ab7f34234ec481b7f45bf9c4d3c2\\\".\\\"territory\\\" (location) sql=\"))))\n\n(defn get-",
"end": 8734,
"score": 0.8148618936538696,
"start": 8719,
"tag": "PASSWORD",
"value": "81b7f45bf9c4d3c"
},
{
"context": "e)\n :user (:user datasource)\n :password (:password datasource)\n :currentSchema (str (:schema dat",
"end": 9609,
"score": 0.5761728286743164,
"start": 9601,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ochSecond 42)]\n (binding [auth/*user* {:user/id test-user}\n config/env (assoc config/env :now ",
"end": 10259,
"score": 0.8214196562767029,
"start": 10250,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "ken config/env))))]\n (is user)\n (is (= \"Esko Luontola\" (get-in user [:user/attributes :name])))))\n\n (t",
"end": 13228,
"score": 0.9995030760765076,
"start": 13215,
"tag": "NAME",
"value": "Esko Luontola"
},
{
"context": "oper\"\n :name \"Developer\"\n :email \"dev",
"end": 13902,
"score": 0.9855632781982422,
"start": 13893,
"tag": "NAME",
"value": "Developer"
},
{
"context": "per\"\n :email \"[email protected]\"})\n app)]\n (is (ok",
"end": 13970,
"score": 0.9999154806137085,
"start": 13949,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "eloper\"\n :name \"Developer\"\n :email \"devel",
"end": 14566,
"score": 0.9697628617286682,
"start": 14557,
"tag": "NAME",
"value": "Developer"
},
{
"context": "loper\"\n :email \"[email protected]\"})\n app)]\n (is (forbid",
"end": 14632,
"score": 0.9999161958694458,
"start": 14611,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sub\"\n :name \"name\"\n :email \"em",
"end": 15406,
"score": 0.5866143703460693,
"start": 15402,
"tag": "NAME",
"value": "name"
},
{
"context": " {}]\n (user/save-user! conn \"user1\" {:name \"User 1\"}))]\n\n (testing \"add user\"\n ",
"end": 23415,
"score": 0.7368847727775574,
"start": 23410,
"tag": "USERNAME",
"value": "user1"
}
] |
test/territory_bro/api_test.clj
|
luontola/territory-bro
| 2 |
;; Copyright © 2015-2021 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 ^:slow territory-bro.api-test
(:require [clj-xpath.core :as xpath]
[clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[ring.mock.request :refer :all]
[ring.util.http-predicates :refer :all]
[territory-bro.api :as api]
[territory-bro.dispatcher :as dispatcher]
[territory-bro.domain.card-minimap-viewport :as card-minimap-viewport]
[territory-bro.domain.congregation :as congregation]
[territory-bro.domain.congregation-boundary :as congregation-boundary]
[territory-bro.domain.region :as region]
[territory-bro.domain.share :as share]
[territory-bro.domain.territory :as territory]
[territory-bro.domain.testdata :as testdata]
[territory-bro.gis.gis-db :as gis-db]
[territory-bro.gis.gis-sync :as gis-sync]
[territory-bro.gis.gis-user :as gis-user]
[territory-bro.infra.authentication :as auth]
[territory-bro.infra.config :as config]
[territory-bro.infra.db :as db]
[territory-bro.infra.json :as json]
[territory-bro.infra.jwt :as jwt]
[territory-bro.infra.jwt-test :as jwt-test]
[territory-bro.infra.router :as router]
[territory-bro.infra.user :as user]
[territory-bro.projections :as projections]
[territory-bro.test.fixtures :refer [db-fixture api-fixture]])
(:import (java.time Instant Duration)
(java.util UUID)
(territory_bro ValidationException NoPermitException WriteConflictException)))
(use-fixtures :once (join-fixtures [db-fixture api-fixture]))
(defn- get-cookies [response]
(->> (get-in response [:headers "Set-Cookie"])
(map (fn [header]
(let [[name value] (-> (first (str/split header #";" 2))
(str/split #"=" 2))]
[name {:value value}])))
(into {})))
(deftest get-cookies-test
(is (= {} (get-cookies {})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123"]}})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123;Path=/;HttpOnly;SameSite=Strict"]}})))
(is (= {"foo" {:value "123"}
"bar" {:value "456"}}
(get-cookies {:headers {"Set-Cookie" ["foo=123" "bar=456"]}}))))
(defn parse-json [body]
(cond
(nil? body) body
(string? body) (json/read-value body)
:else (json/read-value (slurp (io/reader body)))))
(defn read-body [response]
(let [content-type (get-in response [:headers "Content-Type"])]
(if (str/starts-with? content-type "application/json")
(update response :body parse-json)
response)))
(defn app [request]
(-> request router/app read-body))
(defn assert-response [response predicate]
(assert (predicate response)
(str "Unexpected response " response))
response)
(defn refresh-projections! []
;; TODO: do synchronously, or propagate errors from the async thread?
;; - GIS changes cannot be synced in test thread, because
;; it will produce transaction conflicts with the worker
;; thread which is triggered by DB notifications
;; TODO: propagating errors might be useful also in production
(projections/refresh-async!)
(projections/await-refreshed (Duration/ofSeconds 10)))
(defn sync-gis-changes! []
(gis-sync/refresh-async!)
(gis-sync/await-refreshed (Duration/ofSeconds 10))
(projections/await-refreshed (Duration/ofSeconds 10)))
;;;; API Helpers
(defn get-session [response]
{:cookies (get-cookies response)})
(defn login! [app]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app
(assert-response ok?))]
(get-session response)))
(defn logout! [app session]
(-> (request :post "/api/logout")
(merge session)
app
(assert-response ok?)))
(defn get-user-id [session]
(let [response (-> (request :get "/api/settings")
(merge session)
app
(assert-response ok?))
user-id (UUID/fromString (:id (:user (:body response))))]
user-id))
(defn try-create-congregation! [session name]
(-> (request :post "/api/congregations")
(json-body {:name name})
(merge session)
app))
(defn create-congregation! [session name]
(let [response (-> (try-create-congregation! session name)
(assert-response ok?))
cong-id (UUID/fromString (:id (:body response)))]
cong-id))
(defn try-rename-congregation! [session cong-id name]
(-> (request :post (str "/api/congregation/" cong-id "/rename"))
(json-body {:name name})
(merge session)
app))
(defn try-add-user! [session cong-id user-id]
(-> (request :post (str "/api/congregation/" cong-id "/add-user"))
(json-body {:userId (str user-id)})
(merge session)
app))
(defn create-congregation-without-user! [name]
(let [cong-id (UUID/randomUUID)
state (projections/cached-state)]
(db/with-db [conn {}]
(dispatcher/command! conn state
{:command/type :congregation.command/create-congregation
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:congregation/name name}))
(refresh-projections!)
cong-id))
(defn revoke-access-from-all! [cong-id]
(let [state (projections/cached-state)
user-ids (congregation/get-users state cong-id)]
(db/with-db [conn {}]
(doseq [user-id user-ids]
(dispatcher/command! conn state
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
:permission/ids []})))
(refresh-projections!)))
(defn- create-territory! [cong-id]
(let [territory-id (UUID/randomUUID)]
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :territory.command/create-territory
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}))
(refresh-projections!)
territory-id))
(defn- parse-qgis-datasource [datasource]
(let [required (fn [v]
(if (nil? v)
(throw (AssertionError. (str "Failed to parse: " datasource)))
v))
[_ dbname] (required (re-find #"dbname='(.*?)'" datasource))
[_ host] (required (re-find #"host=(\S*)" datasource))
[_ port] (required (re-find #"port=(\S*)" datasource))
[_ user] (required (re-find #"user='(.*?)'" datasource))
[_ password] (required (re-find #"password='(.*?)'" datasource))
[_ schema table] (required (re-find #"table=\"(.*?)\".\"(.*?)\"" datasource))]
{:dbname dbname
:host host
:port (Long/parseLong port)
:user user
:password password
:schema schema
:table table}))
(deftest parse-qgis-datasource-test
(is (= {:dbname "territorybro"
:host "localhost"
:port 5432
:user "gis_user_49a5ab7f34234ec4_5dce9e39cf744126"
:password "pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8"
:schema "test_territorybro_49a5ab7f34234ec481b7f45bf9c4d3c2"
:table "territory"}
(parse-qgis-datasource "dbname='territorybro' host=localhost port=5432 user='gis_user_49a5ab7f34234ec4_5dce9e39cf744126' password='pfClEgNVadYRAt-ytE9x4iakLNjwsNGIfLIS6Mc_hfASiYajB8' sslmode=prefer key='id' srid=4326 type=MultiPolygon table=\"test_territorybro_49a5ab7f34234ec481b7f45bf9c4d3c2\".\"territory\" (location) sql="))))
(defn get-gis-db-spec [session cong-id]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app
(assert-response ok?))
;; XXX: the XML parser doesn't support DOCTYPE
qgis-project (str/replace-first (:body response) "<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>" "")
datasource (->> (xpath/$x "//datasource" qgis-project)
(map :text)
(filter #(str/starts-with? % "dbname="))
(map parse-qgis-datasource)
(first))]
{:dbtype "postgresql"
:dbname (:dbname datasource)
:host (:host datasource)
:port (:port datasource)
:user (:user datasource)
:password (:password datasource)
:currentSchema (str (:schema datasource) ",public")}))
;;;; Tests
(deftest format-for-api-test
(is (= {} (api/format-for-api {})))
(is (= {:foo 1} (api/format-for-api {:foo 1})))
(is (= {:fooBar 1} (api/format-for-api {:foo-bar 1})))
(is (= {:bar 1} (api/format-for-api {:foo/bar 1})))
(is (= [{:fooBar 1} {:bar 2}] (api/format-for-api [{:foo-bar 1} {:foo/bar 2}]))))
(deftest api-command-test
(let [conn :dummy-conn
state :dummy-state
command {:command/type :dummy-command}
test-user (UUID. 0 0x123)
test-time (Instant/ofEpochSecond 42)]
(binding [auth/*user* {:user/id test-user}
config/env (assoc config/env :now (constantly test-time))]
(testing "successful command"
(with-redefs [dispatcher/command! (fn [& args]
(is (= [conn state (assoc command
:command/time test-time
:command/user test-user)]
args)))]
(is (= {:body {:message "OK"}
:status 200
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: validation"
(with-redefs [dispatcher/command! (fn [& _]
(throw (ValidationException. [[:dummy-error 123]])))]
(is (= {:body {:errors [[:dummy-error 123]]}
:status 400
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: permission check"
(with-redefs [dispatcher/command! (fn [& _]
(throw (NoPermitException. test-user [:dummy-permission 123])))]
(is (= {:body {:message "Forbidden"}
:status 403
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: write conflict"
(with-redefs [dispatcher/command! (fn [& _]
(throw (WriteConflictException. "dummy error")))]
(is (= {:body {:message "Conflict"}
:status 409
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: internal error"
(with-redefs [dispatcher/command! (fn [& _]
(throw (RuntimeException. "dummy error")))]
(is (= {:body {:message "Internal Server Error"}
:status 500
:headers {}}
(api/api-command! conn state command))))))))
(deftest basic-routes-test
(testing "index"
(let [response (-> (request :get "/")
app)]
(is (ok? response))))
(testing "page not found"
(let [response (-> (request :get "/invalid")
app)]
(is (not-found? response)))))
(deftest login-test
(testing "login with valid token"
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response))))))
(testing "user is saved on login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn (:sub (jwt/validate jwt-test/token config/env))))]
(is user)
(is (= "Esko Luontola" (get-in user [:user/attributes :name])))))
(testing "login with expired token"
(binding [config/env (assoc config/env :now #(Instant/now))]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (forbidden? response))
(is (= "Invalid token" (:body response)))
(is (empty? (get-cookies response))))))
(testing "dev login"
(binding [config/env (assoc config/env :dev true)]
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "Developer"
:email "[email protected]"})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response)))))))
(testing "user is saved on dev login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn "developer"))]
(is user)
(is (= "Developer" (get-in user [:user/attributes :name])))))
(testing "dev login outside dev mode"
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "Developer"
:email "[email protected]"})
app)]
(is (forbidden? response))
(is (= "Dev mode disabled" (:body response)))
(is (empty? (get-cookies response))))))
(deftest dev-login-test
(testing "authenticates as anybody in dev mode"
(binding [config/env {:dev true}
api/save-user-from-jwt! (fn [_]
(UUID. 0 1))]
(is (= {:status 200,
:headers {},
:body "Logged in",
:session {::auth/user {:user/id (UUID. 0 1)
:sub "sub",
:name "name",
:email "email"}}}
(api/dev-login {:params {:sub "sub"
:name "name"
:email "email"}})))))
(testing "is disabled when not in dev mode"
(binding [config/env {:dev false}]
(is (= {:status 403
:headers {}
:body "Dev mode disabled"}
(api/dev-login {:params {:sub "sub"
:name "name"
:email "email"}}))))))
(deftest authorization-test
(testing "before login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response))))
(let [session (login! app)]
(testing "after login"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))))
(testing "after logout"
(logout! app session)
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (unauthorized? response))))))
(deftest super-user-test
(let [cong-id (create-congregation-without-user! "sudo test")
session (login! app)
user-id (get-user-id session)]
(testing "normal users cannot use sudo"
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (forbidden? response))
(is (= "Not super user" (:body response)))))
(testing "super users can use sudo"
(binding [config/env (update config/env :super-users conj user-id)]
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (see-other? response))
(is (= "http://localhost/" (get-in response [:headers "Location"]))))))
(testing "super user can view all congregations"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (contains? (->> (:body response)
(map :id)
(set))
(str cong-id)))))
(testing "super user can configure all congregations"
(let [response (try-add-user! session cong-id user-id)]
(is (ok? response))))))
(deftest create-congregation-test
(let [session (login! app)
user-id (get-user-id session)
response (try-create-congregation! session "foo")]
(is (ok? response))
(is (:id (:body response)))
(let [cong-id (UUID/fromString (:id (:body response)))
state (projections/cached-state)]
(testing "grants access to the current user"
(is (= 1 (count (congregation/get-users state cong-id)))))
(testing "creates a GIS user for the current user"
(let [gis-user (gis-user/get-gis-user state cong-id user-id)]
(is gis-user)
(is (true? (db/with-db [conn {:read-only? true}]
(gis-db/user-exists? conn (:gis-user/username gis-user)))))))))
(testing "requires login"
(let [response (try-create-congregation! nil "foo")]
(is (unauthorized? response)))))
(deftest list-congregations-test
(let [session (login! app)
response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (sequential? (:body response))))
(testing "requires login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response)))))
(deftest get-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "foo")]
(testing "get congregation"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
app)]
(is (unauthorized? response))))
(testing "wrong ID"
(let [response (-> (request :get (str "/api/congregation/" (UUID/randomUUID)))
(merge session)
app)]
;; same as when ID exists but user has no access
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))))
(deftest get-demo-congregation-test
(let [session (login! app)
cong-id (create-congregation-without-user! "foo")]
(binding [config/env (assoc config/env :demo-congregation cong-id)]
(testing "get demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (ok? response))
(is (= {:id "demo"
:name "Demo Congregation"
:users []
:permissions {:viewCongregation true}}
(select-keys (:body response) [:id :name :users :permissions]))
"returns an anonymized read-only congregation")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/demo"))
app)]
(is (unauthorized? response)))))
(binding [config/env (assoc config/env :demo-congregation nil)]
(testing "no demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (forbidden? response))
(is (= "No demo congregation" (:body response))))))))
(deftest download-qgis-project-test
(let [session (login! app)
user-id (get-user-id session)
cong-id (create-congregation! session "Example Congregation")]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (ok? response))
(is (str/includes? (:body response) "<qgis"))
(is (str/includes? (get-in response [:headers "Content-Disposition"])
"Example Congregation.qgs")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
app)]
(is (unauthorized? response))))
(testing "requires GIS access"
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
;; TODO: create a command for removing a single permission? or produce the event directly from tests?
;; removed :gis-access
:permission/ids [:view-congregation :configure-congregation]}))
(refresh-projections!)
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (forbidden? response))
(is (str/includes? (:body response) "No GIS access"))))))
(deftest add-user-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
new-user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(testing "add user"
(let [response (try-add-user! session cong-id new-user-id)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (contains? (set users) new-user-id)))))
(testing "invalid user"
(let [response (try-add-user! session cong-id (UUID. 0 1))]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-add-user! session cong-id new-user-id)]
(is (forbidden? response))))))
(deftest set-user-permissions-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(is (ok? (try-add-user! session cong-id user-id)))
;; TODO: test changing permissions (after new users no more get full admin access)?
(testing "remove user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (not (contains? (set users) user-id))))))
(testing "invalid user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str (UUID. 0 1))
:permissions []})
(merge session)
app)]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (forbidden? response))))))
(deftest rename-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")]
(testing "rename congregation"
(let [response (try-rename-congregation! session cong-id "New Name")]
(is (ok? response)))
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= "New Name" (:name (:body response))))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-rename-congregation! session cong-id "should not be allowed")]
(is (forbidden? response))))))
(deftest share-territory-link-test
(let [*session (atom (login! app))
cong-id (create-congregation! @*session "Congregation")
territory-id (create-territory! cong-id)
territory-id2 (create-territory! cong-id)
*share-key (atom nil)]
(testing "create a share link"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/territory/" territory-id "/share"))
(json-body {})
(merge @*session)
app)
share-key (:key (:body response))
share-url (:url (:body response))]
(is (ok? response))
(is (not (str/blank? share-key)))
(is (= (str "http://localhost:8080/share/" share-key)
share-url))
(reset! *share-key share-key)))
;; The rest of this test is ran as an anonymous user
(reset! *session nil)
(testing "open share link"
(let [response (-> (request :get (str "/api/share/" @*share-key))
(merge @*session)
app)]
(reset! *session (get-session response)) ; TODO: stateful HTTP client which remembers the cookies automatically
(is (ok? response))
(is (= {:congregation (str cong-id)
:territory (str territory-id)}
(:body response)))))
(testing "records that the share was opened"
(is (some? (:share/last-opened (share/find-share-by-key (projections/cached-state) @*share-key)))))
(testing "can view the shared territory"
;; TODO: API to get one territory by ID
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge @*session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))
(is (contains? (->> (:territories (:body response))
(map :id)
(set))
(str territory-id)))
(testing "- but cannot view other territories"
(is (= 1 (count (:territories (:body response))))))
(testing "- cannot view other congregation details"
(is (= [] (:regions (:body response)))
"regions")
(is (= [] (:congregationBoundaries (:body response)))
"congregation boundaries")
(is (= [] (:cardMinimapViewports (:body response)))
"card minimap viewports")
(is (= [] (:users (:body response)))
"users"))))
(testing "non-existing share link"
(let [response (-> (request :get "/api/share/foo")
(merge @*session)
app)]
(is (not-found? response))
(is (= {:message "Share not found"}
(:body response)))))))
(deftest gis-changes-sync-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")
db-spec (get-gis-db-spec session cong-id)
territory-id (UUID/randomUUID)
region-id (UUID/randomUUID)
congregation-boundary-id (UUID/randomUUID)
card-minimap-viewport-id (UUID/randomUUID)
conflicting-stream-id (create-congregation-without-user! "foo")]
(testing "write to GIS database"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["insert into territory (id, number, addresses, subregion, meta, location) values (?, ?, ?, ?, ?::jsonb, ?::public.geography)"
territory-id "123" "the addresses" "the region" {:foo "bar"} testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update territory set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon territory-id])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
region-id "Somewhere" testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update subregion set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon region-id])
(jdbc/execute! conn ["insert into congregation_boundary (id, location) values (?, ?::public.geography)"
congregation-boundary-id testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update congregation_boundary set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon congregation-boundary-id])
(jdbc/execute! conn ["insert into card_minimap_viewport (id, location) values (?, ?::public.geography)"
card-minimap-viewport-id testdata/wkt-polygon2])
(jdbc/execute! conn ["update card_minimap_viewport set location = ?::public.geography where id = ?"
testdata/wkt-polygon card-minimap-viewport-id]))
(sync-gis-changes!))
(testing "changes to GIS database are synced to event store"
(let [state (projections/cached-state)]
(is (= {:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id territory-id])))
(is (= {:region/id region-id
:region/name "Somewhere"
:region/location testdata/wkt-multi-polygon}
(get-in state [::region/regions cong-id region-id])))
(is (= {:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}
(get-in state [::congregation-boundary/congregation-boundaries cong-id congregation-boundary-id])))
(is (= {:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}
(get-in state [::card-minimap-viewport/card-minimap-viewports cong-id card-minimap-viewport-id])))))
(testing "syncing changes is idempotent"
(let [state-before (projections/cached-state)]
(sync-gis-changes!) ;; should not process the already processed changes
(is (identical? state-before (projections/cached-state)))))
(testing "syncing changes is triggered automatically"
(let [new-id (jdbc/with-db-transaction [conn db-spec]
(gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon))
deadline (-> (Instant/now) (.plus (Duration/ofSeconds 5)))]
(loop []
(cond
(= new-id (get-in (projections/cached-state) [::congregation-boundary/congregation-boundaries cong-id new-id :congregation-boundary/id]))
(is true "was synced")
(-> (Instant/now) (.isAfter deadline))
(is false "deadline reached, was not synced")
:else
(do (Thread/sleep 10)
(recur))))))
(testing "changing the ID will delete the old territory and create a new one"
(let [new-territory-id (UUID/randomUUID)]
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update territory set id = ? where id = ?"
new-territory-id territory-id]))
(sync-gis-changes!)
(let [state (projections/cached-state)]
(is (nil? (get-in state [::territory/territories cong-id territory-id]))
"old ID")
(is (= {:territory/id new-territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id new-territory-id]))
"new ID"))))
(testing "stream ID conflict on insert -> generates a new replacement ID"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["delete from subregion"])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
conflicting-stream-id "Conflicting insert" testdata/wkt-multi-polygon]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting insert"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))
(testing "stream ID conflict on ID update -> generates a new replacement ID"
;; combination of the previous two tests, to ensure that the features to not conflict
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update subregion set id = ?, name = ?"
conflicting-stream-id "Conflicting update"]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting update"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))))
;; TODO: delete territory and then restore it to same congregation
|
80511
|
;; Copyright © 2015-2021 <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 ^:slow territory-bro.api-test
(:require [clj-xpath.core :as xpath]
[clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[ring.mock.request :refer :all]
[ring.util.http-predicates :refer :all]
[territory-bro.api :as api]
[territory-bro.dispatcher :as dispatcher]
[territory-bro.domain.card-minimap-viewport :as card-minimap-viewport]
[territory-bro.domain.congregation :as congregation]
[territory-bro.domain.congregation-boundary :as congregation-boundary]
[territory-bro.domain.region :as region]
[territory-bro.domain.share :as share]
[territory-bro.domain.territory :as territory]
[territory-bro.domain.testdata :as testdata]
[territory-bro.gis.gis-db :as gis-db]
[territory-bro.gis.gis-sync :as gis-sync]
[territory-bro.gis.gis-user :as gis-user]
[territory-bro.infra.authentication :as auth]
[territory-bro.infra.config :as config]
[territory-bro.infra.db :as db]
[territory-bro.infra.json :as json]
[territory-bro.infra.jwt :as jwt]
[territory-bro.infra.jwt-test :as jwt-test]
[territory-bro.infra.router :as router]
[territory-bro.infra.user :as user]
[territory-bro.projections :as projections]
[territory-bro.test.fixtures :refer [db-fixture api-fixture]])
(:import (java.time Instant Duration)
(java.util UUID)
(territory_bro ValidationException NoPermitException WriteConflictException)))
(use-fixtures :once (join-fixtures [db-fixture api-fixture]))
(defn- get-cookies [response]
(->> (get-in response [:headers "Set-Cookie"])
(map (fn [header]
(let [[name value] (-> (first (str/split header #";" 2))
(str/split #"=" 2))]
[name {:value value}])))
(into {})))
(deftest get-cookies-test
(is (= {} (get-cookies {})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123"]}})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123;Path=/;HttpOnly;SameSite=Strict"]}})))
(is (= {"foo" {:value "123"}
"bar" {:value "456"}}
(get-cookies {:headers {"Set-Cookie" ["foo=123" "bar=456"]}}))))
(defn parse-json [body]
(cond
(nil? body) body
(string? body) (json/read-value body)
:else (json/read-value (slurp (io/reader body)))))
(defn read-body [response]
(let [content-type (get-in response [:headers "Content-Type"])]
(if (str/starts-with? content-type "application/json")
(update response :body parse-json)
response)))
(defn app [request]
(-> request router/app read-body))
(defn assert-response [response predicate]
(assert (predicate response)
(str "Unexpected response " response))
response)
(defn refresh-projections! []
;; TODO: do synchronously, or propagate errors from the async thread?
;; - GIS changes cannot be synced in test thread, because
;; it will produce transaction conflicts with the worker
;; thread which is triggered by DB notifications
;; TODO: propagating errors might be useful also in production
(projections/refresh-async!)
(projections/await-refreshed (Duration/ofSeconds 10)))
(defn sync-gis-changes! []
(gis-sync/refresh-async!)
(gis-sync/await-refreshed (Duration/ofSeconds 10))
(projections/await-refreshed (Duration/ofSeconds 10)))
;;;; API Helpers
(defn get-session [response]
{:cookies (get-cookies response)})
(defn login! [app]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app
(assert-response ok?))]
(get-session response)))
(defn logout! [app session]
(-> (request :post "/api/logout")
(merge session)
app
(assert-response ok?)))
(defn get-user-id [session]
(let [response (-> (request :get "/api/settings")
(merge session)
app
(assert-response ok?))
user-id (UUID/fromString (:id (:user (:body response))))]
user-id))
(defn try-create-congregation! [session name]
(-> (request :post "/api/congregations")
(json-body {:name name})
(merge session)
app))
(defn create-congregation! [session name]
(let [response (-> (try-create-congregation! session name)
(assert-response ok?))
cong-id (UUID/fromString (:id (:body response)))]
cong-id))
(defn try-rename-congregation! [session cong-id name]
(-> (request :post (str "/api/congregation/" cong-id "/rename"))
(json-body {:name name})
(merge session)
app))
(defn try-add-user! [session cong-id user-id]
(-> (request :post (str "/api/congregation/" cong-id "/add-user"))
(json-body {:userId (str user-id)})
(merge session)
app))
(defn create-congregation-without-user! [name]
(let [cong-id (UUID/randomUUID)
state (projections/cached-state)]
(db/with-db [conn {}]
(dispatcher/command! conn state
{:command/type :congregation.command/create-congregation
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:congregation/name name}))
(refresh-projections!)
cong-id))
(defn revoke-access-from-all! [cong-id]
(let [state (projections/cached-state)
user-ids (congregation/get-users state cong-id)]
(db/with-db [conn {}]
(doseq [user-id user-ids]
(dispatcher/command! conn state
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
:permission/ids []})))
(refresh-projections!)))
(defn- create-territory! [cong-id]
(let [territory-id (UUID/randomUUID)]
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :territory.command/create-territory
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}))
(refresh-projections!)
territory-id))
(defn- parse-qgis-datasource [datasource]
(let [required (fn [v]
(if (nil? v)
(throw (AssertionError. (str "Failed to parse: " datasource)))
v))
[_ dbname] (required (re-find #"dbname='(.*?)'" datasource))
[_ host] (required (re-find #"host=(\S*)" datasource))
[_ port] (required (re-find #"port=(\S*)" datasource))
[_ user] (required (re-find #"user='(.*?)'" datasource))
[_ password] (required (re-find #"password='(.*?)'" datasource))
[_ schema table] (required (re-find #"table=\"(.*?)\".\"(.*?)\"" datasource))]
{:dbname dbname
:host host
:port (Long/parseLong port)
:user user
:password <PASSWORD>
:schema schema
:table table}))
(deftest parse-qgis-datasource-test
(is (= {:dbname "territorybro"
:host "localhost"
:port 5432
:user "gis_user_49a5ab7f34234ec4_5dce9e39cf744126"
:password "<PASSWORD>"
:schema "test_territorybro_49a5ab7f34234ec481b7f45bf9c4d3c2"
:table "territory"}
(parse-qgis-datasource "dbname='territorybro' host=localhost port=5432 user='gis_user_49a5ab7f34234ec4_5dce9e39cf744126' password='<PASSWORD>' sslmode=prefer key='id' srid=4326 type=MultiPolygon table=\"test_territorybro_49a5ab7f34234ec4<PASSWORD>2\".\"territory\" (location) sql="))))
(defn get-gis-db-spec [session cong-id]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app
(assert-response ok?))
;; XXX: the XML parser doesn't support DOCTYPE
qgis-project (str/replace-first (:body response) "<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>" "")
datasource (->> (xpath/$x "//datasource" qgis-project)
(map :text)
(filter #(str/starts-with? % "dbname="))
(map parse-qgis-datasource)
(first))]
{:dbtype "postgresql"
:dbname (:dbname datasource)
:host (:host datasource)
:port (:port datasource)
:user (:user datasource)
:password (:<PASSWORD> datasource)
:currentSchema (str (:schema datasource) ",public")}))
;;;; Tests
(deftest format-for-api-test
(is (= {} (api/format-for-api {})))
(is (= {:foo 1} (api/format-for-api {:foo 1})))
(is (= {:fooBar 1} (api/format-for-api {:foo-bar 1})))
(is (= {:bar 1} (api/format-for-api {:foo/bar 1})))
(is (= [{:fooBar 1} {:bar 2}] (api/format-for-api [{:foo-bar 1} {:foo/bar 2}]))))
(deftest api-command-test
(let [conn :dummy-conn
state :dummy-state
command {:command/type :dummy-command}
test-user (UUID. 0 0x123)
test-time (Instant/ofEpochSecond 42)]
(binding [auth/*user* {:user/id test-user}
config/env (assoc config/env :now (constantly test-time))]
(testing "successful command"
(with-redefs [dispatcher/command! (fn [& args]
(is (= [conn state (assoc command
:command/time test-time
:command/user test-user)]
args)))]
(is (= {:body {:message "OK"}
:status 200
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: validation"
(with-redefs [dispatcher/command! (fn [& _]
(throw (ValidationException. [[:dummy-error 123]])))]
(is (= {:body {:errors [[:dummy-error 123]]}
:status 400
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: permission check"
(with-redefs [dispatcher/command! (fn [& _]
(throw (NoPermitException. test-user [:dummy-permission 123])))]
(is (= {:body {:message "Forbidden"}
:status 403
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: write conflict"
(with-redefs [dispatcher/command! (fn [& _]
(throw (WriteConflictException. "dummy error")))]
(is (= {:body {:message "Conflict"}
:status 409
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: internal error"
(with-redefs [dispatcher/command! (fn [& _]
(throw (RuntimeException. "dummy error")))]
(is (= {:body {:message "Internal Server Error"}
:status 500
:headers {}}
(api/api-command! conn state command))))))))
(deftest basic-routes-test
(testing "index"
(let [response (-> (request :get "/")
app)]
(is (ok? response))))
(testing "page not found"
(let [response (-> (request :get "/invalid")
app)]
(is (not-found? response)))))
(deftest login-test
(testing "login with valid token"
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response))))))
(testing "user is saved on login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn (:sub (jwt/validate jwt-test/token config/env))))]
(is user)
(is (= "<NAME>" (get-in user [:user/attributes :name])))))
(testing "login with expired token"
(binding [config/env (assoc config/env :now #(Instant/now))]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (forbidden? response))
(is (= "Invalid token" (:body response)))
(is (empty? (get-cookies response))))))
(testing "dev login"
(binding [config/env (assoc config/env :dev true)]
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "<NAME>"
:email "<EMAIL>"})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response)))))))
(testing "user is saved on dev login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn "developer"))]
(is user)
(is (= "Developer" (get-in user [:user/attributes :name])))))
(testing "dev login outside dev mode"
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "<NAME>"
:email "<EMAIL>"})
app)]
(is (forbidden? response))
(is (= "Dev mode disabled" (:body response)))
(is (empty? (get-cookies response))))))
(deftest dev-login-test
(testing "authenticates as anybody in dev mode"
(binding [config/env {:dev true}
api/save-user-from-jwt! (fn [_]
(UUID. 0 1))]
(is (= {:status 200,
:headers {},
:body "Logged in",
:session {::auth/user {:user/id (UUID. 0 1)
:sub "sub",
:name "name",
:email "email"}}}
(api/dev-login {:params {:sub "sub"
:name "<NAME>"
:email "email"}})))))
(testing "is disabled when not in dev mode"
(binding [config/env {:dev false}]
(is (= {:status 403
:headers {}
:body "Dev mode disabled"}
(api/dev-login {:params {:sub "sub"
:name "name"
:email "email"}}))))))
(deftest authorization-test
(testing "before login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response))))
(let [session (login! app)]
(testing "after login"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))))
(testing "after logout"
(logout! app session)
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (unauthorized? response))))))
(deftest super-user-test
(let [cong-id (create-congregation-without-user! "sudo test")
session (login! app)
user-id (get-user-id session)]
(testing "normal users cannot use sudo"
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (forbidden? response))
(is (= "Not super user" (:body response)))))
(testing "super users can use sudo"
(binding [config/env (update config/env :super-users conj user-id)]
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (see-other? response))
(is (= "http://localhost/" (get-in response [:headers "Location"]))))))
(testing "super user can view all congregations"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (contains? (->> (:body response)
(map :id)
(set))
(str cong-id)))))
(testing "super user can configure all congregations"
(let [response (try-add-user! session cong-id user-id)]
(is (ok? response))))))
(deftest create-congregation-test
(let [session (login! app)
user-id (get-user-id session)
response (try-create-congregation! session "foo")]
(is (ok? response))
(is (:id (:body response)))
(let [cong-id (UUID/fromString (:id (:body response)))
state (projections/cached-state)]
(testing "grants access to the current user"
(is (= 1 (count (congregation/get-users state cong-id)))))
(testing "creates a GIS user for the current user"
(let [gis-user (gis-user/get-gis-user state cong-id user-id)]
(is gis-user)
(is (true? (db/with-db [conn {:read-only? true}]
(gis-db/user-exists? conn (:gis-user/username gis-user)))))))))
(testing "requires login"
(let [response (try-create-congregation! nil "foo")]
(is (unauthorized? response)))))
(deftest list-congregations-test
(let [session (login! app)
response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (sequential? (:body response))))
(testing "requires login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response)))))
(deftest get-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "foo")]
(testing "get congregation"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
app)]
(is (unauthorized? response))))
(testing "wrong ID"
(let [response (-> (request :get (str "/api/congregation/" (UUID/randomUUID)))
(merge session)
app)]
;; same as when ID exists but user has no access
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))))
(deftest get-demo-congregation-test
(let [session (login! app)
cong-id (create-congregation-without-user! "foo")]
(binding [config/env (assoc config/env :demo-congregation cong-id)]
(testing "get demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (ok? response))
(is (= {:id "demo"
:name "Demo Congregation"
:users []
:permissions {:viewCongregation true}}
(select-keys (:body response) [:id :name :users :permissions]))
"returns an anonymized read-only congregation")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/demo"))
app)]
(is (unauthorized? response)))))
(binding [config/env (assoc config/env :demo-congregation nil)]
(testing "no demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (forbidden? response))
(is (= "No demo congregation" (:body response))))))))
(deftest download-qgis-project-test
(let [session (login! app)
user-id (get-user-id session)
cong-id (create-congregation! session "Example Congregation")]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (ok? response))
(is (str/includes? (:body response) "<qgis"))
(is (str/includes? (get-in response [:headers "Content-Disposition"])
"Example Congregation.qgs")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
app)]
(is (unauthorized? response))))
(testing "requires GIS access"
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
;; TODO: create a command for removing a single permission? or produce the event directly from tests?
;; removed :gis-access
:permission/ids [:view-congregation :configure-congregation]}))
(refresh-projections!)
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (forbidden? response))
(is (str/includes? (:body response) "No GIS access"))))))
(deftest add-user-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
new-user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(testing "add user"
(let [response (try-add-user! session cong-id new-user-id)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (contains? (set users) new-user-id)))))
(testing "invalid user"
(let [response (try-add-user! session cong-id (UUID. 0 1))]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-add-user! session cong-id new-user-id)]
(is (forbidden? response))))))
(deftest set-user-permissions-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(is (ok? (try-add-user! session cong-id user-id)))
;; TODO: test changing permissions (after new users no more get full admin access)?
(testing "remove user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (not (contains? (set users) user-id))))))
(testing "invalid user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str (UUID. 0 1))
:permissions []})
(merge session)
app)]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (forbidden? response))))))
(deftest rename-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")]
(testing "rename congregation"
(let [response (try-rename-congregation! session cong-id "New Name")]
(is (ok? response)))
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= "New Name" (:name (:body response))))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-rename-congregation! session cong-id "should not be allowed")]
(is (forbidden? response))))))
(deftest share-territory-link-test
(let [*session (atom (login! app))
cong-id (create-congregation! @*session "Congregation")
territory-id (create-territory! cong-id)
territory-id2 (create-territory! cong-id)
*share-key (atom nil)]
(testing "create a share link"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/territory/" territory-id "/share"))
(json-body {})
(merge @*session)
app)
share-key (:key (:body response))
share-url (:url (:body response))]
(is (ok? response))
(is (not (str/blank? share-key)))
(is (= (str "http://localhost:8080/share/" share-key)
share-url))
(reset! *share-key share-key)))
;; The rest of this test is ran as an anonymous user
(reset! *session nil)
(testing "open share link"
(let [response (-> (request :get (str "/api/share/" @*share-key))
(merge @*session)
app)]
(reset! *session (get-session response)) ; TODO: stateful HTTP client which remembers the cookies automatically
(is (ok? response))
(is (= {:congregation (str cong-id)
:territory (str territory-id)}
(:body response)))))
(testing "records that the share was opened"
(is (some? (:share/last-opened (share/find-share-by-key (projections/cached-state) @*share-key)))))
(testing "can view the shared territory"
;; TODO: API to get one territory by ID
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge @*session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))
(is (contains? (->> (:territories (:body response))
(map :id)
(set))
(str territory-id)))
(testing "- but cannot view other territories"
(is (= 1 (count (:territories (:body response))))))
(testing "- cannot view other congregation details"
(is (= [] (:regions (:body response)))
"regions")
(is (= [] (:congregationBoundaries (:body response)))
"congregation boundaries")
(is (= [] (:cardMinimapViewports (:body response)))
"card minimap viewports")
(is (= [] (:users (:body response)))
"users"))))
(testing "non-existing share link"
(let [response (-> (request :get "/api/share/foo")
(merge @*session)
app)]
(is (not-found? response))
(is (= {:message "Share not found"}
(:body response)))))))
(deftest gis-changes-sync-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")
db-spec (get-gis-db-spec session cong-id)
territory-id (UUID/randomUUID)
region-id (UUID/randomUUID)
congregation-boundary-id (UUID/randomUUID)
card-minimap-viewport-id (UUID/randomUUID)
conflicting-stream-id (create-congregation-without-user! "foo")]
(testing "write to GIS database"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["insert into territory (id, number, addresses, subregion, meta, location) values (?, ?, ?, ?, ?::jsonb, ?::public.geography)"
territory-id "123" "the addresses" "the region" {:foo "bar"} testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update territory set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon territory-id])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
region-id "Somewhere" testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update subregion set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon region-id])
(jdbc/execute! conn ["insert into congregation_boundary (id, location) values (?, ?::public.geography)"
congregation-boundary-id testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update congregation_boundary set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon congregation-boundary-id])
(jdbc/execute! conn ["insert into card_minimap_viewport (id, location) values (?, ?::public.geography)"
card-minimap-viewport-id testdata/wkt-polygon2])
(jdbc/execute! conn ["update card_minimap_viewport set location = ?::public.geography where id = ?"
testdata/wkt-polygon card-minimap-viewport-id]))
(sync-gis-changes!))
(testing "changes to GIS database are synced to event store"
(let [state (projections/cached-state)]
(is (= {:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id territory-id])))
(is (= {:region/id region-id
:region/name "Somewhere"
:region/location testdata/wkt-multi-polygon}
(get-in state [::region/regions cong-id region-id])))
(is (= {:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}
(get-in state [::congregation-boundary/congregation-boundaries cong-id congregation-boundary-id])))
(is (= {:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}
(get-in state [::card-minimap-viewport/card-minimap-viewports cong-id card-minimap-viewport-id])))))
(testing "syncing changes is idempotent"
(let [state-before (projections/cached-state)]
(sync-gis-changes!) ;; should not process the already processed changes
(is (identical? state-before (projections/cached-state)))))
(testing "syncing changes is triggered automatically"
(let [new-id (jdbc/with-db-transaction [conn db-spec]
(gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon))
deadline (-> (Instant/now) (.plus (Duration/ofSeconds 5)))]
(loop []
(cond
(= new-id (get-in (projections/cached-state) [::congregation-boundary/congregation-boundaries cong-id new-id :congregation-boundary/id]))
(is true "was synced")
(-> (Instant/now) (.isAfter deadline))
(is false "deadline reached, was not synced")
:else
(do (Thread/sleep 10)
(recur))))))
(testing "changing the ID will delete the old territory and create a new one"
(let [new-territory-id (UUID/randomUUID)]
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update territory set id = ? where id = ?"
new-territory-id territory-id]))
(sync-gis-changes!)
(let [state (projections/cached-state)]
(is (nil? (get-in state [::territory/territories cong-id territory-id]))
"old ID")
(is (= {:territory/id new-territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id new-territory-id]))
"new ID"))))
(testing "stream ID conflict on insert -> generates a new replacement ID"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["delete from subregion"])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
conflicting-stream-id "Conflicting insert" testdata/wkt-multi-polygon]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting insert"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))
(testing "stream ID conflict on ID update -> generates a new replacement ID"
;; combination of the previous two tests, to ensure that the features to not conflict
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update subregion set id = ?, name = ?"
conflicting-stream-id "Conflicting update"]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting update"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))))
;; TODO: delete territory and then restore it to same congregation
| true |
;; Copyright © 2015-2021 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 ^:slow territory-bro.api-test
(:require [clj-xpath.core :as xpath]
[clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[ring.mock.request :refer :all]
[ring.util.http-predicates :refer :all]
[territory-bro.api :as api]
[territory-bro.dispatcher :as dispatcher]
[territory-bro.domain.card-minimap-viewport :as card-minimap-viewport]
[territory-bro.domain.congregation :as congregation]
[territory-bro.domain.congregation-boundary :as congregation-boundary]
[territory-bro.domain.region :as region]
[territory-bro.domain.share :as share]
[territory-bro.domain.territory :as territory]
[territory-bro.domain.testdata :as testdata]
[territory-bro.gis.gis-db :as gis-db]
[territory-bro.gis.gis-sync :as gis-sync]
[territory-bro.gis.gis-user :as gis-user]
[territory-bro.infra.authentication :as auth]
[territory-bro.infra.config :as config]
[territory-bro.infra.db :as db]
[territory-bro.infra.json :as json]
[territory-bro.infra.jwt :as jwt]
[territory-bro.infra.jwt-test :as jwt-test]
[territory-bro.infra.router :as router]
[territory-bro.infra.user :as user]
[territory-bro.projections :as projections]
[territory-bro.test.fixtures :refer [db-fixture api-fixture]])
(:import (java.time Instant Duration)
(java.util UUID)
(territory_bro ValidationException NoPermitException WriteConflictException)))
(use-fixtures :once (join-fixtures [db-fixture api-fixture]))
(defn- get-cookies [response]
(->> (get-in response [:headers "Set-Cookie"])
(map (fn [header]
(let [[name value] (-> (first (str/split header #";" 2))
(str/split #"=" 2))]
[name {:value value}])))
(into {})))
(deftest get-cookies-test
(is (= {} (get-cookies {})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123"]}})))
(is (= {"ring-session" {:value "123"}}
(get-cookies {:headers {"Set-Cookie" ["ring-session=123;Path=/;HttpOnly;SameSite=Strict"]}})))
(is (= {"foo" {:value "123"}
"bar" {:value "456"}}
(get-cookies {:headers {"Set-Cookie" ["foo=123" "bar=456"]}}))))
(defn parse-json [body]
(cond
(nil? body) body
(string? body) (json/read-value body)
:else (json/read-value (slurp (io/reader body)))))
(defn read-body [response]
(let [content-type (get-in response [:headers "Content-Type"])]
(if (str/starts-with? content-type "application/json")
(update response :body parse-json)
response)))
(defn app [request]
(-> request router/app read-body))
(defn assert-response [response predicate]
(assert (predicate response)
(str "Unexpected response " response))
response)
(defn refresh-projections! []
;; TODO: do synchronously, or propagate errors from the async thread?
;; - GIS changes cannot be synced in test thread, because
;; it will produce transaction conflicts with the worker
;; thread which is triggered by DB notifications
;; TODO: propagating errors might be useful also in production
(projections/refresh-async!)
(projections/await-refreshed (Duration/ofSeconds 10)))
(defn sync-gis-changes! []
(gis-sync/refresh-async!)
(gis-sync/await-refreshed (Duration/ofSeconds 10))
(projections/await-refreshed (Duration/ofSeconds 10)))
;;;; API Helpers
(defn get-session [response]
{:cookies (get-cookies response)})
(defn login! [app]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app
(assert-response ok?))]
(get-session response)))
(defn logout! [app session]
(-> (request :post "/api/logout")
(merge session)
app
(assert-response ok?)))
(defn get-user-id [session]
(let [response (-> (request :get "/api/settings")
(merge session)
app
(assert-response ok?))
user-id (UUID/fromString (:id (:user (:body response))))]
user-id))
(defn try-create-congregation! [session name]
(-> (request :post "/api/congregations")
(json-body {:name name})
(merge session)
app))
(defn create-congregation! [session name]
(let [response (-> (try-create-congregation! session name)
(assert-response ok?))
cong-id (UUID/fromString (:id (:body response)))]
cong-id))
(defn try-rename-congregation! [session cong-id name]
(-> (request :post (str "/api/congregation/" cong-id "/rename"))
(json-body {:name name})
(merge session)
app))
(defn try-add-user! [session cong-id user-id]
(-> (request :post (str "/api/congregation/" cong-id "/add-user"))
(json-body {:userId (str user-id)})
(merge session)
app))
(defn create-congregation-without-user! [name]
(let [cong-id (UUID/randomUUID)
state (projections/cached-state)]
(db/with-db [conn {}]
(dispatcher/command! conn state
{:command/type :congregation.command/create-congregation
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:congregation/name name}))
(refresh-projections!)
cong-id))
(defn revoke-access-from-all! [cong-id]
(let [state (projections/cached-state)
user-ids (congregation/get-users state cong-id)]
(db/with-db [conn {}]
(doseq [user-id user-ids]
(dispatcher/command! conn state
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
:permission/ids []})))
(refresh-projections!)))
(defn- create-territory! [cong-id]
(let [territory-id (UUID/randomUUID)]
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :territory.command/create-territory
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}))
(refresh-projections!)
territory-id))
(defn- parse-qgis-datasource [datasource]
(let [required (fn [v]
(if (nil? v)
(throw (AssertionError. (str "Failed to parse: " datasource)))
v))
[_ dbname] (required (re-find #"dbname='(.*?)'" datasource))
[_ host] (required (re-find #"host=(\S*)" datasource))
[_ port] (required (re-find #"port=(\S*)" datasource))
[_ user] (required (re-find #"user='(.*?)'" datasource))
[_ password] (required (re-find #"password='(.*?)'" datasource))
[_ schema table] (required (re-find #"table=\"(.*?)\".\"(.*?)\"" datasource))]
{:dbname dbname
:host host
:port (Long/parseLong port)
:user user
:password PI:PASSWORD:<PASSWORD>END_PI
:schema schema
:table table}))
(deftest parse-qgis-datasource-test
(is (= {:dbname "territorybro"
:host "localhost"
:port 5432
:user "gis_user_49a5ab7f34234ec4_5dce9e39cf744126"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:schema "test_territorybro_49a5ab7f34234ec481b7f45bf9c4d3c2"
:table "territory"}
(parse-qgis-datasource "dbname='territorybro' host=localhost port=5432 user='gis_user_49a5ab7f34234ec4_5dce9e39cf744126' password='PI:PASSWORD:<PASSWORD>END_PI' sslmode=prefer key='id' srid=4326 type=MultiPolygon table=\"test_territorybro_49a5ab7f34234ec4PI:PASSWORD:<PASSWORD>END_PI2\".\"territory\" (location) sql="))))
(defn get-gis-db-spec [session cong-id]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app
(assert-response ok?))
;; XXX: the XML parser doesn't support DOCTYPE
qgis-project (str/replace-first (:body response) "<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>" "")
datasource (->> (xpath/$x "//datasource" qgis-project)
(map :text)
(filter #(str/starts-with? % "dbname="))
(map parse-qgis-datasource)
(first))]
{:dbtype "postgresql"
:dbname (:dbname datasource)
:host (:host datasource)
:port (:port datasource)
:user (:user datasource)
:password (:PI:PASSWORD:<PASSWORD>END_PI datasource)
:currentSchema (str (:schema datasource) ",public")}))
;;;; Tests
(deftest format-for-api-test
(is (= {} (api/format-for-api {})))
(is (= {:foo 1} (api/format-for-api {:foo 1})))
(is (= {:fooBar 1} (api/format-for-api {:foo-bar 1})))
(is (= {:bar 1} (api/format-for-api {:foo/bar 1})))
(is (= [{:fooBar 1} {:bar 2}] (api/format-for-api [{:foo-bar 1} {:foo/bar 2}]))))
(deftest api-command-test
(let [conn :dummy-conn
state :dummy-state
command {:command/type :dummy-command}
test-user (UUID. 0 0x123)
test-time (Instant/ofEpochSecond 42)]
(binding [auth/*user* {:user/id test-user}
config/env (assoc config/env :now (constantly test-time))]
(testing "successful command"
(with-redefs [dispatcher/command! (fn [& args]
(is (= [conn state (assoc command
:command/time test-time
:command/user test-user)]
args)))]
(is (= {:body {:message "OK"}
:status 200
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: validation"
(with-redefs [dispatcher/command! (fn [& _]
(throw (ValidationException. [[:dummy-error 123]])))]
(is (= {:body {:errors [[:dummy-error 123]]}
:status 400
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: permission check"
(with-redefs [dispatcher/command! (fn [& _]
(throw (NoPermitException. test-user [:dummy-permission 123])))]
(is (= {:body {:message "Forbidden"}
:status 403
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: write conflict"
(with-redefs [dispatcher/command! (fn [& _]
(throw (WriteConflictException. "dummy error")))]
(is (= {:body {:message "Conflict"}
:status 409
:headers {}}
(api/api-command! conn state command)))))
(testing "failed command: internal error"
(with-redefs [dispatcher/command! (fn [& _]
(throw (RuntimeException. "dummy error")))]
(is (= {:body {:message "Internal Server Error"}
:status 500
:headers {}}
(api/api-command! conn state command))))))))
(deftest basic-routes-test
(testing "index"
(let [response (-> (request :get "/")
app)]
(is (ok? response))))
(testing "page not found"
(let [response (-> (request :get "/invalid")
app)]
(is (not-found? response)))))
(deftest login-test
(testing "login with valid token"
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response))))))
(testing "user is saved on login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn (:sub (jwt/validate jwt-test/token config/env))))]
(is user)
(is (= "PI:NAME:<NAME>END_PI" (get-in user [:user/attributes :name])))))
(testing "login with expired token"
(binding [config/env (assoc config/env :now #(Instant/now))]
(let [response (-> (request :post "/api/login")
(json-body {:idToken jwt-test/token})
app)]
(is (forbidden? response))
(is (= "Invalid token" (:body response)))
(is (empty? (get-cookies response))))))
(testing "dev login"
(binding [config/env (assoc config/env :dev true)]
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"})
app)]
(is (ok? response))
(is (= "Logged in" (:body response)))
(is (= ["ring-session"] (keys (get-cookies response)))))))
(testing "user is saved on dev login"
(let [user (db/with-db [conn {}]
(user/get-by-subject conn "developer"))]
(is user)
(is (= "Developer" (get-in user [:user/attributes :name])))))
(testing "dev login outside dev mode"
(let [response (-> (request :post "/api/dev-login")
(json-body {:sub "developer"
:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"})
app)]
(is (forbidden? response))
(is (= "Dev mode disabled" (:body response)))
(is (empty? (get-cookies response))))))
(deftest dev-login-test
(testing "authenticates as anybody in dev mode"
(binding [config/env {:dev true}
api/save-user-from-jwt! (fn [_]
(UUID. 0 1))]
(is (= {:status 200,
:headers {},
:body "Logged in",
:session {::auth/user {:user/id (UUID. 0 1)
:sub "sub",
:name "name",
:email "email"}}}
(api/dev-login {:params {:sub "sub"
:name "PI:NAME:<NAME>END_PI"
:email "email"}})))))
(testing "is disabled when not in dev mode"
(binding [config/env {:dev false}]
(is (= {:status 403
:headers {}
:body "Dev mode disabled"}
(api/dev-login {:params {:sub "sub"
:name "name"
:email "email"}}))))))
(deftest authorization-test
(testing "before login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response))))
(let [session (login! app)]
(testing "after login"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))))
(testing "after logout"
(logout! app session)
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (unauthorized? response))))))
(deftest super-user-test
(let [cong-id (create-congregation-without-user! "sudo test")
session (login! app)
user-id (get-user-id session)]
(testing "normal users cannot use sudo"
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (forbidden? response))
(is (= "Not super user" (:body response)))))
(testing "super users can use sudo"
(binding [config/env (update config/env :super-users conj user-id)]
(let [response (-> (request :get "/api/sudo")
(merge session)
app)]
(is (see-other? response))
(is (= "http://localhost/" (get-in response [:headers "Location"]))))))
(testing "super user can view all congregations"
(let [response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (contains? (->> (:body response)
(map :id)
(set))
(str cong-id)))))
(testing "super user can configure all congregations"
(let [response (try-add-user! session cong-id user-id)]
(is (ok? response))))))
(deftest create-congregation-test
(let [session (login! app)
user-id (get-user-id session)
response (try-create-congregation! session "foo")]
(is (ok? response))
(is (:id (:body response)))
(let [cong-id (UUID/fromString (:id (:body response)))
state (projections/cached-state)]
(testing "grants access to the current user"
(is (= 1 (count (congregation/get-users state cong-id)))))
(testing "creates a GIS user for the current user"
(let [gis-user (gis-user/get-gis-user state cong-id user-id)]
(is gis-user)
(is (true? (db/with-db [conn {:read-only? true}]
(gis-db/user-exists? conn (:gis-user/username gis-user)))))))))
(testing "requires login"
(let [response (try-create-congregation! nil "foo")]
(is (unauthorized? response)))))
(deftest list-congregations-test
(let [session (login! app)
response (-> (request :get "/api/congregations")
(merge session)
app)]
(is (ok? response))
(is (sequential? (:body response))))
(testing "requires login"
(let [response (-> (request :get "/api/congregations")
app)]
(is (unauthorized? response)))))
(deftest get-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "foo")]
(testing "get congregation"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id))
app)]
(is (unauthorized? response))))
(testing "wrong ID"
(let [response (-> (request :get (str "/api/congregation/" (UUID/randomUUID)))
(merge session)
app)]
;; same as when ID exists but user has no access
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (forbidden? response))
(is (= "No congregation access" (:body response)))))))
(deftest get-demo-congregation-test
(let [session (login! app)
cong-id (create-congregation-without-user! "foo")]
(binding [config/env (assoc config/env :demo-congregation cong-id)]
(testing "get demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (ok? response))
(is (= {:id "demo"
:name "Demo Congregation"
:users []
:permissions {:viewCongregation true}}
(select-keys (:body response) [:id :name :users :permissions]))
"returns an anonymized read-only congregation")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/demo"))
app)]
(is (unauthorized? response)))))
(binding [config/env (assoc config/env :demo-congregation nil)]
(testing "no demo congregation"
(let [response (-> (request :get (str "/api/congregation/demo"))
(merge session)
app)]
(is (forbidden? response))
(is (= "No demo congregation" (:body response))))))))
(deftest download-qgis-project-test
(let [session (login! app)
user-id (get-user-id session)
cong-id (create-congregation! session "Example Congregation")]
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (ok? response))
(is (str/includes? (:body response) "<qgis"))
(is (str/includes? (get-in response [:headers "Content-Disposition"])
"Example Congregation.qgs")))
(testing "requires login"
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
app)]
(is (unauthorized? response))))
(testing "requires GIS access"
(db/with-db [conn {}]
(dispatcher/command! conn (projections/cached-state)
{:command/type :congregation.command/set-user-permissions
:command/time (Instant/now)
:command/system "test"
:congregation/id cong-id
:user/id user-id
;; TODO: create a command for removing a single permission? or produce the event directly from tests?
;; removed :gis-access
:permission/ids [:view-congregation :configure-congregation]}))
(refresh-projections!)
(let [response (-> (request :get (str "/api/congregation/" cong-id "/qgis-project"))
(merge session)
app)]
(is (forbidden? response))
(is (str/includes? (:body response) "No GIS access"))))))
(deftest add-user-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
new-user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(testing "add user"
(let [response (try-add-user! session cong-id new-user-id)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (contains? (set users) new-user-id)))))
(testing "invalid user"
(let [response (try-add-user! session cong-id (UUID. 0 1))]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-add-user! session cong-id new-user-id)]
(is (forbidden? response))))))
(deftest set-user-permissions-test
(let [session (login! app)
cong-id (create-congregation! session "Congregation")
user-id (db/with-db [conn {}]
(user/save-user! conn "user1" {:name "User 1"}))]
(is (ok? (try-add-user! session cong-id user-id)))
;; TODO: test changing permissions (after new users no more get full admin access)?
(testing "remove user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (ok? response))
;; TODO: check the result through the API
(let [users (congregation/get-users (projections/cached-state) cong-id)]
(is (not (contains? (set users) user-id))))))
(testing "invalid user"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str (UUID. 0 1))
:permissions []})
(merge session)
app)]
(is (bad-request? response))
(is (= {:errors [["no-such-user" "00000000-0000-0000-0000-000000000001"]]}
(:body response)))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (-> (request :post (str "/api/congregation/" cong-id "/set-user-permissions"))
(json-body {:userId (str user-id)
:permissions []})
(merge session)
app)]
(is (forbidden? response))))))
(deftest rename-congregation-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")]
(testing "rename congregation"
(let [response (try-rename-congregation! session cong-id "New Name")]
(is (ok? response)))
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge session)
app)]
(is (ok? response))
(is (= "New Name" (:name (:body response))))))
(testing "no access"
(revoke-access-from-all! cong-id)
(let [response (try-rename-congregation! session cong-id "should not be allowed")]
(is (forbidden? response))))))
(deftest share-territory-link-test
(let [*session (atom (login! app))
cong-id (create-congregation! @*session "Congregation")
territory-id (create-territory! cong-id)
territory-id2 (create-territory! cong-id)
*share-key (atom nil)]
(testing "create a share link"
(let [response (-> (request :post (str "/api/congregation/" cong-id "/territory/" territory-id "/share"))
(json-body {})
(merge @*session)
app)
share-key (:key (:body response))
share-url (:url (:body response))]
(is (ok? response))
(is (not (str/blank? share-key)))
(is (= (str "http://localhost:8080/share/" share-key)
share-url))
(reset! *share-key share-key)))
;; The rest of this test is ran as an anonymous user
(reset! *session nil)
(testing "open share link"
(let [response (-> (request :get (str "/api/share/" @*share-key))
(merge @*session)
app)]
(reset! *session (get-session response)) ; TODO: stateful HTTP client which remembers the cookies automatically
(is (ok? response))
(is (= {:congregation (str cong-id)
:territory (str territory-id)}
(:body response)))))
(testing "records that the share was opened"
(is (some? (:share/last-opened (share/find-share-by-key (projections/cached-state) @*share-key)))))
(testing "can view the shared territory"
;; TODO: API to get one territory by ID
(let [response (-> (request :get (str "/api/congregation/" cong-id))
(merge @*session)
app)]
(is (ok? response))
(is (= (str cong-id) (:id (:body response))))
(is (contains? (->> (:territories (:body response))
(map :id)
(set))
(str territory-id)))
(testing "- but cannot view other territories"
(is (= 1 (count (:territories (:body response))))))
(testing "- cannot view other congregation details"
(is (= [] (:regions (:body response)))
"regions")
(is (= [] (:congregationBoundaries (:body response)))
"congregation boundaries")
(is (= [] (:cardMinimapViewports (:body response)))
"card minimap viewports")
(is (= [] (:users (:body response)))
"users"))))
(testing "non-existing share link"
(let [response (-> (request :get "/api/share/foo")
(merge @*session)
app)]
(is (not-found? response))
(is (= {:message "Share not found"}
(:body response)))))))
(deftest gis-changes-sync-test
(let [session (login! app)
cong-id (create-congregation! session "Old Name")
db-spec (get-gis-db-spec session cong-id)
territory-id (UUID/randomUUID)
region-id (UUID/randomUUID)
congregation-boundary-id (UUID/randomUUID)
card-minimap-viewport-id (UUID/randomUUID)
conflicting-stream-id (create-congregation-without-user! "foo")]
(testing "write to GIS database"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["insert into territory (id, number, addresses, subregion, meta, location) values (?, ?, ?, ?, ?::jsonb, ?::public.geography)"
territory-id "123" "the addresses" "the region" {:foo "bar"} testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update territory set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon territory-id])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
region-id "Somewhere" testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update subregion set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon region-id])
(jdbc/execute! conn ["insert into congregation_boundary (id, location) values (?, ?::public.geography)"
congregation-boundary-id testdata/wkt-multi-polygon2])
(jdbc/execute! conn ["update congregation_boundary set location = ?::public.geography where id = ?"
testdata/wkt-multi-polygon congregation-boundary-id])
(jdbc/execute! conn ["insert into card_minimap_viewport (id, location) values (?, ?::public.geography)"
card-minimap-viewport-id testdata/wkt-polygon2])
(jdbc/execute! conn ["update card_minimap_viewport set location = ?::public.geography where id = ?"
testdata/wkt-polygon card-minimap-viewport-id]))
(sync-gis-changes!))
(testing "changes to GIS database are synced to event store"
(let [state (projections/cached-state)]
(is (= {:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id territory-id])))
(is (= {:region/id region-id
:region/name "Somewhere"
:region/location testdata/wkt-multi-polygon}
(get-in state [::region/regions cong-id region-id])))
(is (= {:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}
(get-in state [::congregation-boundary/congregation-boundaries cong-id congregation-boundary-id])))
(is (= {:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}
(get-in state [::card-minimap-viewport/card-minimap-viewports cong-id card-minimap-viewport-id])))))
(testing "syncing changes is idempotent"
(let [state-before (projections/cached-state)]
(sync-gis-changes!) ;; should not process the already processed changes
(is (identical? state-before (projections/cached-state)))))
(testing "syncing changes is triggered automatically"
(let [new-id (jdbc/with-db-transaction [conn db-spec]
(gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon))
deadline (-> (Instant/now) (.plus (Duration/ofSeconds 5)))]
(loop []
(cond
(= new-id (get-in (projections/cached-state) [::congregation-boundary/congregation-boundaries cong-id new-id :congregation-boundary/id]))
(is true "was synced")
(-> (Instant/now) (.isAfter deadline))
(is false "deadline reached, was not synced")
:else
(do (Thread/sleep 10)
(recur))))))
(testing "changing the ID will delete the old territory and create a new one"
(let [new-territory-id (UUID/randomUUID)]
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update territory set id = ? where id = ?"
new-territory-id territory-id]))
(sync-gis-changes!)
(let [state (projections/cached-state)]
(is (nil? (get-in state [::territory/territories cong-id territory-id]))
"old ID")
(is (= {:territory/id new-territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
(get-in state [::territory/territories cong-id new-territory-id]))
"new ID"))))
(testing "stream ID conflict on insert -> generates a new replacement ID"
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["delete from subregion"])
(jdbc/execute! conn ["insert into subregion (id, name, location) values (?, ?, ?::public.geography)"
conflicting-stream-id "Conflicting insert" testdata/wkt-multi-polygon]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting insert"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))
(testing "stream ID conflict on ID update -> generates a new replacement ID"
;; combination of the previous two tests, to ensure that the features to not conflict
(jdbc/with-db-transaction [conn db-spec]
(jdbc/execute! conn ["update subregion set id = ?, name = ?"
conflicting-stream-id "Conflicting update"]))
(sync-gis-changes!)
(let [state (projections/cached-state)
replacement-id (first (keys (get-in state [::region/regions cong-id])))]
(is (some? replacement-id))
(is (not= conflicting-stream-id replacement-id))
(is (= [{:region/id replacement-id
:region/name "Conflicting update"
:region/location testdata/wkt-multi-polygon}]
(vals (get-in state [::region/regions cong-id]))))))))
;; TODO: delete territory and then restore it to same congregation
|
[
{
"context": " (map :itemLabel)\n;; (into #{}))\n;;=> #{\"Marcus Furius Camillus\" \"Avianus\" \"Porcia Catonis\" \"Faustina the Elder\" ",
"end": 2647,
"score": 0.9998204708099365,
"start": 2625,
"tag": "NAME",
"value": "Marcus Furius Camillus"
},
{
"context": " (into #{}))\n;;=> #{\"Marcus Furius Camillus\" \"Avianus\" \"Porcia Catonis\" \"Faustina the Elder\" \"Hippolytu",
"end": 2657,
"score": 0.9256599545478821,
"start": 2650,
"tag": "NAME",
"value": "Avianus"
},
{
"context": " #{}))\n;;=> #{\"Marcus Furius Camillus\" \"Avianus\" \"Porcia Catonis\" \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" ",
"end": 2674,
"score": 0.9990273714065552,
"start": 2660,
"tag": "NAME",
"value": "Porcia Catonis"
},
{
"context": "rcus Furius Camillus\" \"Avianus\" \"Porcia Catonis\" \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" \"Lucius Caecilius Met",
"end": 2695,
"score": 0.90848308801651,
"start": 2677,
"tag": "NAME",
"value": "Faustina the Elder"
},
{
"context": " \"Avianus\" \"Porcia Catonis\" \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" \"Lucius Caecilius Metellu",
"end": 2699,
"score": 0.5527511239051819,
"start": 2698,
"tag": "NAME",
"value": "H"
},
{
"context": "ianus\" \"Porcia Catonis\" \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" \"Lucius Caecilius Metellus Dente",
"end": 2706,
"score": 0.6533613801002502,
"start": 2702,
"tag": "NAME",
"value": "olyt"
},
{
"context": "orcia Catonis\" \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" \"Lucius Caecilius Metellus Denter\" \"Lucius Jun",
"end": 2720,
"score": 0.6673067212104797,
"start": 2711,
"tag": "NAME",
"value": "Sylvester"
},
{
"context": " \"Faustina the Elder\" \"Hippolytus\" \"Sylvester I\" \"Lucius Caecilius Metellus Denter\" \"Lucius Junius Brutus\" \"Gaius Valarius Sabinus\" ",
"end": 2757,
"score": 0.9995743036270142,
"start": 2725,
"tag": "NAME",
"value": "Lucius Caecilius Metellus Denter"
},
{
"context": "\"Sylvester I\" \"Lucius Caecilius Metellus Denter\" \"Lucius Junius Brutus\" \"Gaius Valarius Sabinus\" \"Publius Petronius Turp",
"end": 2780,
"score": 0.9996321797370911,
"start": 2760,
"tag": "NAME",
"value": "Lucius Junius Brutus"
},
{
"context": "aecilius Metellus Denter\" \"Lucius Junius Brutus\" \"Gaius Valarius Sabinus\" \"Publius Petronius Turpilianus\"}\n\n;; What places",
"end": 2805,
"score": 0.9994280934333801,
"start": 2783,
"tag": "NAME",
"value": "Gaius Valarius Sabinus"
},
{
"context": " \"Lucius Junius Brutus\" \"Gaius Valarius Sabinus\" \"Publius Petronius Turpilianus\"}\n\n;; What places in Germany have names that end ",
"end": 2837,
"score": 0.9903760552406311,
"start": 2808,
"tag": "NAME",
"value": "Publius Petronius Turpilianus"
},
{
"context": "\", :wo \"Point(13.716666666 50.993055555)\", :name \"Bannewitz\"}\n;; {:ort \"Q93223\", :wo \"Point(14.233333333 51.",
"end": 3465,
"score": 0.9997261166572571,
"start": 3456,
"tag": "NAME",
"value": "Bannewitz"
},
{
"context": "\", :wo \"Point(14.233333333 51.233333333)\", :name \"Crostwitz\"}\n;; {:ort \"Q160693\", :wo \"Point(14.2275 51.2475",
"end": 3544,
"score": 0.9997529983520508,
"start": 3535,
"tag": "NAME",
"value": "Crostwitz"
},
{
"context": "t \"Q160693\", :wo \"Point(14.2275 51.2475)\", :name \"Caseritz\"}\n;; {:ort \"Q160779\", :wo \"Point(14.2628 51.2339",
"end": 3613,
"score": 0.999720573425293,
"start": 3605,
"tag": "NAME",
"value": "Caseritz"
},
{
"context": "t \"Q160779\", :wo \"Point(14.2628 51.2339)\", :name \"Prautitz\"}\n;; {:ort \"Q162721\", :wo \"Point(14.265 51.2247)",
"end": 3682,
"score": 0.9997649192810059,
"start": 3674,
"tag": "NAME",
"value": "Prautitz"
},
{
"context": "rt \"Q162721\", :wo \"Point(14.265 51.2247)\", :name \"Nucknitz\"}\n;; {:ort \"Q2795\", :wo \"Point(12.9222 50.8351)\"",
"end": 3750,
"score": 0.9997024536132812,
"start": 3742,
"tag": "NAME",
"value": "Nucknitz"
},
{
"context": "ort \"Q2795\", :wo \"Point(12.9222 50.8351)\", :name \"Chemnitz\"}\n;; {:ort \"Q115077\", :wo \"Point(13.5589 54.5586",
"end": 3817,
"score": 0.9996936321258545,
"start": 3809,
"tag": "NAME",
"value": "Chemnitz"
},
{
"context": "t \"Q115077\", :wo \"Point(13.5589 54.5586)\", :name \"Quoltitz\"}\n;; {:ort \"Q160799\", :wo \"Point(14.43713889 51.",
"end": 3886,
"score": 0.9996446967124939,
"start": 3878,
"tag": "NAME",
"value": "Quoltitz"
},
{
"context": "99\", :wo \"Point(14.43713889 51.79291667)\", :name \"Groß Lieskow\"}\n;; {:ort \"Q318609\", :wo \"Point(7.28119 53.4654",
"end": 3967,
"score": 0.9997984766960144,
"start": 3955,
"tag": "NAME",
"value": "Groß Lieskow"
},
{
"context": "t \"Q318609\", :wo \"Point(7.28119 53.4654)\", :name \"Abelitz\"}\n;; {:ort \"Q1124721\", :wo \"Point(13.3096 53.751",
"end": 4035,
"score": 0.9997358918190002,
"start": 4028,
"tag": "NAME",
"value": "Abelitz"
},
{
"context": " \"Q1124721\", :wo \"Point(13.3096 53.7516)\", :name \"Conerow\"}]\n\n;; WikiData is multilingual! Here's a query t",
"end": 4104,
"score": 0.999612033367157,
"start": 4097,
"tag": "NAME",
"value": "Conerow"
},
{
"context": "nglishName \"Apodidae\"}\n;; {:germanName \"Höhlenschwalme\", :englishName \"Aegothelidae\"}\n;; {:germanName",
"end": 4845,
"score": 0.5534866452217102,
"start": 4842,
"tag": "NAME",
"value": "wal"
},
{
"context": "alogy (map entity [\"The Beatles\" \"rock and roll\" \"Miles Davis\"]))\n;;=> (\"The Beatles is <genre> to rock and rol",
"end": 6427,
"score": 0.9205087423324585,
"start": 6416,
"tag": "NAME",
"value": "Miles Davis"
},
{
"context": "\n;;=> (\"The Beatles is <genre> to rock and roll as Miles Davis is <genre> to jazz\")\n\n;; airports within 100km of",
"end": 6493,
"score": 0.8477201461791992,
"start": 6482,
"tag": "NAME",
"value": "Miles Davis"
},
{
"context": "ce 2019 1 ; year and month\n [\"Kelly Link\" \"Stromae\" \"Guillermo del Toro\" \"Hayao Miyazaki\" ",
"end": 7746,
"score": 0.999878466129303,
"start": 7736,
"tag": "NAME",
"value": "Kelly Link"
},
{
"context": "ear and month\n [\"Kelly Link\" \"Stromae\" \"Guillermo del Toro\" \"Hayao Miyazaki\" \"Lydia Dav",
"end": 7756,
"score": 0.9998111724853516,
"start": 7749,
"tag": "NAME",
"value": "Stromae"
},
{
"context": "nth\n [\"Kelly Link\" \"Stromae\" \"Guillermo del Toro\" \"Hayao Miyazaki\" \"Lydia Davis\"\n ",
"end": 7777,
"score": 0.9998694062232971,
"start": 7759,
"tag": "NAME",
"value": "Guillermo del Toro"
},
{
"context": " [\"Kelly Link\" \"Stromae\" \"Guillermo del Toro\" \"Hayao Miyazaki\" \"Lydia Davis\"\n \"Werner Herz",
"end": 7794,
"score": 0.999896228313446,
"start": 7780,
"tag": "NAME",
"value": "Hayao Miyazaki"
},
{
"context": " \"Stromae\" \"Guillermo del Toro\" \"Hayao Miyazaki\" \"Lydia Davis\"\n \"Werner Herzog\" \"Björk\" \"G",
"end": 7808,
"score": 0.9998764991760254,
"start": 7797,
"tag": "NAME",
"value": "Lydia Davis"
},
{
"context": "ao Miyazaki\" \"Lydia Davis\"\n \"Werner Herzog\" \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" ",
"end": 7846,
"score": 0.9998857378959656,
"start": 7833,
"tag": "NAME",
"value": "Werner Herzog"
},
{
"context": "dia Davis\"\n \"Werner Herzog\" \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" \"Sofia C",
"end": 7854,
"score": 0.9998835921287537,
"start": 7849,
"tag": "NAME",
"value": "Björk"
},
{
"context": "s\"\n \"Werner Herzog\" \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" \"Sofia Coppola\"])\n (ma",
"end": 7872,
"score": 0.999873161315918,
"start": 7857,
"tag": "NAME",
"value": "George Saunders"
},
{
"context": " \"Werner Herzog\" \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" \"Sofia Coppola\"])\n (map #(sele",
"end": 7880,
"score": 0.9998583793640137,
"start": 7875,
"tag": "NAME",
"value": "Feist"
},
{
"context": "Werner Herzog\" \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" \"Sofia Coppola\"])\n (map #(select-keys % [:wo",
"end": 7894,
"score": 0.9998717308044434,
"start": 7883,
"tag": "NAME",
"value": "Andrew Bird"
},
{
"context": " \"Björk\" \"George Saunders\" \"Feist\" \"Andrew Bird\" \"Sofia Coppola\"])\n (map #(select-keys % [:workLabel :creator",
"end": 7910,
"score": 0.9998815655708313,
"start": 7897,
"tag": "NAME",
"value": "Sofia Coppola"
}
] |
src/mundaneum/examples.clj
|
ngrunwald/mundaneum
| 0 |
(ns mundaneum.examples
(:require [mundaneum.query :refer [describe entity label property query stringify-query *default-language*]]
[backtick :refer [template]]
[clj-time.format :as tf]))
;; To understand what's happening here, it would be a good idea to
;; read through this document:
;; https://m.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries
;; The first challenge when using Wikidata is finding the right IDs
;; for the properties and entities you must use to phrase your
;; question properly. We have functions to help:
(entity "U2")
;; Now we know the ID for U2... or do we? Which U2 is it, really?
(describe (entity "U2"))
(entity "U2" :part-of (entity "Berlin U-Bahn"))
(describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
;; We also have functions that turn keywords into property values:
(property :instance-of)
;;=> "P31"
;; ... but we use it indirectly through a set of helper functions
;; named for Wikidata namespaces, like wdt, p, ps and pq. The link
;; above will help you understand which one of these you might want
;; for a given query, but it's most often wdt.
;; we can ask which things contain an administrative territory and get
;; a list of the pairs filtered to the situation where the container
;; is Ireland
(query
'[:select ?areaLabel
:where [[(entity "Ireland") (wdt :contains-administrative-territorial-entity) ?area]]
:limit 50])
;; Discoveries/inventions grouped by person on the clojure side,
(->> (query
'[:select ?thingLabel ?whomLabel
:where [[?thing (wdt :discoverer-or-inventor) ?whom]]
:limit 100])
(group-by :whomLabel)
(reduce #(assoc %1 (first %2) (mapv :thingLabel (second %2))) {}))
;; eye color popularity, grouping and counting as part of the query
(query
'[:select ?eyeColorLabel (count ?person :as ?count)
:where [[?person (wdt :eye-color) ?eyeColor] ]
:group-by ?eyeColorLabel
:order-by (desc ?count)])
;; U7 stations in Berlin w/ geo coords
(query (template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (entity "U7" :part-of ~(entity "Berlin U-Bahn"))
_ (wdt :coordinate-location) ?coord]]]))
;; born in ancient Rome or territories thereof
;; WARN: Strange Clojure compiler bug inside
;; (->> (query
;; '[:select ?itemLabel
;; :where [:union [[[?item (wdt :place-of-birth) ?pob]
;; [?pob (wdt :located-in-the-administrative-territorial-entity) * (entity "ancient rome")]]]]
;; :limit 10])
;; (map :itemLabel)
;; (into #{}))
;;=> #{"Marcus Furius Camillus" "Avianus" "Porcia Catonis" "Faustina the Elder" "Hippolytus" "Sylvester I" "Lucius Caecilius Metellus Denter" "Lucius Junius Brutus" "Gaius Valarius Sabinus" "Publius Petronius Turpilianus"}
;; What places in Germany have names that end in -ow/-itz (indicating
;; that they were historically Slavic)
;;
;; (note the _, which translates to SPARQL's ; which means "use the
;; same subject as before")
(query
'[:select *
:where [[?ort (wdt :instance-of) / (wdt :subclass-of) * (entity "human settlement")
_ (wdt :country) (entity "Germany")
_ rdfs:label ?name
_ (wdt :coordinate-location) ?wo]
:filter ((lang ?name) = "de")
:filter ((regex ?name "(ow|itz)$"))]
:limit 10])
;;=>
;; [{:ort "Q6448", :wo "Point(13.716666666 50.993055555)", :name "Bannewitz"}
;; {:ort "Q93223", :wo "Point(14.233333333 51.233333333)", :name "Crostwitz"}
;; {:ort "Q160693", :wo "Point(14.2275 51.2475)", :name "Caseritz"}
;; {:ort "Q160779", :wo "Point(14.2628 51.2339)", :name "Prautitz"}
;; {:ort "Q162721", :wo "Point(14.265 51.2247)", :name "Nucknitz"}
;; {:ort "Q2795", :wo "Point(12.9222 50.8351)", :name "Chemnitz"}
;; {:ort "Q115077", :wo "Point(13.5589 54.5586)", :name "Quoltitz"}
;; {:ort "Q160799", :wo "Point(14.43713889 51.79291667)", :name "Groß Lieskow"}
;; {:ort "Q318609", :wo "Point(7.28119 53.4654)", :name "Abelitz"}
;; {:ort "Q1124721", :wo "Point(13.3096 53.7516)", :name "Conerow"}]
;; WikiData is multilingual! Here's a query to list species of Swift
;; (the bird) with their English and German (and often Latin) names
(query '[:select ?englishName ?germanName
:where [[?item (wdt :parent-taxon) (entity "Apodiformes")
_ rdfs:label ?germanName
_ rdfs:label ?englishName]
:filter ((lang ?germanName) = "de")
:filter ((lang ?englishName) = "en")]
:limit 10])
;;=>
;; [{:germanName "Jungornithidae", :englishName "Jungornithidae"}
;; {:germanName "Eocypselus", :englishName "Eocypselus"}
;; {:germanName "Eocypselidae", :englishName "Eocypselidae"}
;; {:germanName "Segler", :englishName "Apodidae"}
;; {:germanName "Höhlenschwalme", :englishName "Aegothelidae"}
;; {:germanName "Aegialornithidae", :englishName "Aegialornithidae"}
;; {:germanName "Apodi", :englishName "Apodi"}
;; {:germanName "Baumsegler", :englishName "treeswift"}
;; {:germanName "Kolibris", :englishName "Trochilidae"}]
;; We can also use triples to find out about analogies in the dataset
(defn make-analogy
"Return known analogies for the form `a1` is to `a2` as `b1` is to ???"
[a1 a2 b1]
(->> (query
(template [:select ?isto ?analogyLabel
:where [[~(symbol (str "wd:" a1)) ?isto ~(symbol (str "wd:" a2))]
[~(symbol (str "wd:" b1)) ?isto ?analogy]
;; tightens analogies by requiring that a2/b2 be of the same kind,
;; but loses some interesting loose analogies:
;; [~(symbol (str "wd:" a2)) (wdt :instance-of) ?kind]
;; [?analogy (wdt :instance-of) ?kind]
]]))
(map #(let [arc (label (:isto %))]
(str (label a1)
" is <" arc "> to "
(label a2)
" as "
(label b1)
" is <" arc "> to " (:analogyLabel %))))
distinct))
(make-analogy (entity "Paris") (entity "France") (entity "Berlin"))
;;=> ("Paris is <country> to France as Berlin is <country> to Germany"
;; "Paris is <capital of> to France as Berlin is <capital of> to Germany")
(apply make-analogy (map entity ["The Beatles" "rock and roll" "Miles Davis"]))
;;=> ("The Beatles is <genre> to rock and roll as Miles Davis is <genre> to jazz")
;; airports within 100km of Paris, use "around" service
(->>
(query
'[:select :distinct ?placeLabel
:where [[(entity "Paris") (wdt :coordinate-location) ?parisLoc]
[?place (wdt :instance-of) (entity "airport")]
:service wikibase:around [[?place (wdt :coordinate-location) ?location]
[bd:serviceParam wikibase:center ?parisLoc]
[bd:serviceParam wikibase:radius "100"]]]])
(map :placeLabel)
(into #{}))
(defn releases-since
"Returns any creative works published since `year`/`month` by any `entities` known to Wikidata."
[since-year since-month entities]
(let [ents (map #(if (re-find #"^Q[\d]+" %) % (entity %)) entities)]
(query
(template [:select ?workLabel ?creatorLabel ?role ?date
:where [[?work ?role ?creator _ (wdt :publication-date) ?date]
:union ~(mapv #(vector '?work '?role (symbol (str "wd:" %))) ents)
:filter ((year ?date) >= ~since-year)
:filter ((month ?date) >= ~since-month)]
:order-by (asc ?date)]))))
(->> (releases-since 2019 1 ; year and month
["Kelly Link" "Stromae" "Guillermo del Toro" "Hayao Miyazaki" "Lydia Davis"
"Werner Herzog" "Björk" "George Saunders" "Feist" "Andrew Bird" "Sofia Coppola"])
(map #(select-keys % [:workLabel :creatorLabel]))
distinct)
;; How about something a bit more serious? Here we find drug-gene
;; product interactions and diseases for which these might be
;; candidates.
(->> (query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 100])
(group-by :diseaseLabel)
(mapv (fn [[k vs]] [k (mapv #(dissoc % :diseaseLabel) vs)]))
(into {}))
;;=>
;; {"Parkinson disease"
;; [{:drugLabel "SB-203580", :geneLabel "GAK"}],
;; "obesity"
;; [{:drugLabel "allopurinol", :geneLabel "XDH"}
;; {:drugLabel "estriol", :geneLabel "ESR1"}
;; {:drugLabel "tamoxifen", :geneLabel "ESR1"}
;; {:drugLabel "17β-estradiol", :geneLabel "ESR1"}
;; "malaria" [{:drugLabel "benserazide", :geneLabel "DDC"}],
;; "systemic lupus erythematosus"
;; [{:drugLabel "Hypothetical protein CT_814", :geneLabel "DDA1"}
;; {:drugLabel "ibrutinib", :geneLabel "BLK"}],
;; "Crohn's disease"
;; [{:drugLabel "momelotinib", :geneLabel "JAK2"}
;; {:drugLabel "pacritinib", :geneLabel "JAK2"}],
;; "multiple sclerosis"
;; [{:drugLabel "cabozantinib", :geneLabel "MET"}
;; {:drugLabel "crizotinib", :geneLabel "MET"}
;; {:drugLabel "tivantinib", :geneLabel "MET"}],
;; "ulcerative colitis"
;; [{:drugLabel "bumetanide", :geneLabel "GPR35"}
;; {:drugLabel "furosemide", :geneLabel "GPR35"}],
;; "hepatitis B"
;; [{:drugLabel "L-aspartic Acid", :geneLabel "GRIN2A"}
;; {:drugLabel "ketamine", :geneLabel "GRIN2A"}]},
(query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 10])
;;=>
;; [{:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "everolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "ridaforolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "dactolisib", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "temsirolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "AIDA", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}
;; {:drugLabel "CPCCOEt", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Recently added lexical queries
;; A recursive query using property paths
;; https://en.wikibooks.org/wiki/SPARQL/Property_paths
(query
'[:select :distinct ?ancestorLemma ?ancestorLangLabel
:where [[?lexeme (literal "wikibase:lemma") "Quark"@de] ; lexeme for DE word "Quark"
[?lexeme (literal "wdt:P5191") + ?ancestor] ; P5191 = derived-from, too new to be in properties list?!
[?ancestor (literal "wikibase:lemma") ?ancestorLemma ; get each ancestor lemma and language
_ (literal "dct:language") ?ancestorLang]]
:limit 20])
;;=>
;; [{:xLangLabel "Polish", :xLemma "twaróg"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvarogъ"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvoriti"}]
;; Note the use of (literal ...) for cases were we do not yet support
;; the namespace/syntax required for the query. This allows for
;; greater access to the SPARQL endpoint's power while progressively
;; improving our DSL.
;; German-language media representation in Wikidata
(mapv
(fn [zeitung]
(assoc (first (query
(template
[:select (count ?ref :as ?mentions)
:where [[?statement (literal "prov:wasDerivedFrom") ?ref]
[?ref (literal pr:P248) (entity ~zeitung)]]])))
:zeitung zeitung))
["Bild" "Süddeutsche Zeitung" "Frankfurter Allgemeine Zeitung" "Die Zeit" "Die Welt" "Die Tageszeitung"])
;;=>
;; [{:mentions "57", :zeitung "Süddeutsche Zeitung"}
;; {:mentions "19", :zeitung "Frankfurter Allgemeine Zeitung"}
;; {:mentions "15", :zeitung "Die Zeit"}
;; {:mentions "8", :zeitung "Die Welt"}
;; {:mentions "3", :zeitung "Die Tageszeitung"}
;; {:mentions "1", :zeitung "Bild"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; multiple language support (work ongoing)
;; lookup an entity using Thai as the default language
(binding [mundaneum.query/*default-language* "th"]
(entity "ระยอง"))
;; => "Q395325"
;; also works for describe
(binding [mundaneum.query/*default-language* "th"]
(describe (entity "ระยอง")))
;;=> "หน้าแก้ความกำกวมวิกิมีเดีย"
|
30640
|
(ns mundaneum.examples
(:require [mundaneum.query :refer [describe entity label property query stringify-query *default-language*]]
[backtick :refer [template]]
[clj-time.format :as tf]))
;; To understand what's happening here, it would be a good idea to
;; read through this document:
;; https://m.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries
;; The first challenge when using Wikidata is finding the right IDs
;; for the properties and entities you must use to phrase your
;; question properly. We have functions to help:
(entity "U2")
;; Now we know the ID for U2... or do we? Which U2 is it, really?
(describe (entity "U2"))
(entity "U2" :part-of (entity "Berlin U-Bahn"))
(describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
;; We also have functions that turn keywords into property values:
(property :instance-of)
;;=> "P31"
;; ... but we use it indirectly through a set of helper functions
;; named for Wikidata namespaces, like wdt, p, ps and pq. The link
;; above will help you understand which one of these you might want
;; for a given query, but it's most often wdt.
;; we can ask which things contain an administrative territory and get
;; a list of the pairs filtered to the situation where the container
;; is Ireland
(query
'[:select ?areaLabel
:where [[(entity "Ireland") (wdt :contains-administrative-territorial-entity) ?area]]
:limit 50])
;; Discoveries/inventions grouped by person on the clojure side,
(->> (query
'[:select ?thingLabel ?whomLabel
:where [[?thing (wdt :discoverer-or-inventor) ?whom]]
:limit 100])
(group-by :whomLabel)
(reduce #(assoc %1 (first %2) (mapv :thingLabel (second %2))) {}))
;; eye color popularity, grouping and counting as part of the query
(query
'[:select ?eyeColorLabel (count ?person :as ?count)
:where [[?person (wdt :eye-color) ?eyeColor] ]
:group-by ?eyeColorLabel
:order-by (desc ?count)])
;; U7 stations in Berlin w/ geo coords
(query (template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (entity "U7" :part-of ~(entity "Berlin U-Bahn"))
_ (wdt :coordinate-location) ?coord]]]))
;; born in ancient Rome or territories thereof
;; WARN: Strange Clojure compiler bug inside
;; (->> (query
;; '[:select ?itemLabel
;; :where [:union [[[?item (wdt :place-of-birth) ?pob]
;; [?pob (wdt :located-in-the-administrative-territorial-entity) * (entity "ancient rome")]]]]
;; :limit 10])
;; (map :itemLabel)
;; (into #{}))
;;=> #{"<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>ipp<NAME>us" "<NAME> I" "<NAME>" "<NAME>" "<NAME>" "<NAME>"}
;; What places in Germany have names that end in -ow/-itz (indicating
;; that they were historically Slavic)
;;
;; (note the _, which translates to SPARQL's ; which means "use the
;; same subject as before")
(query
'[:select *
:where [[?ort (wdt :instance-of) / (wdt :subclass-of) * (entity "human settlement")
_ (wdt :country) (entity "Germany")
_ rdfs:label ?name
_ (wdt :coordinate-location) ?wo]
:filter ((lang ?name) = "de")
:filter ((regex ?name "(ow|itz)$"))]
:limit 10])
;;=>
;; [{:ort "Q6448", :wo "Point(13.716666666 50.993055555)", :name "<NAME>"}
;; {:ort "Q93223", :wo "Point(14.233333333 51.233333333)", :name "<NAME>"}
;; {:ort "Q160693", :wo "Point(14.2275 51.2475)", :name "<NAME>"}
;; {:ort "Q160779", :wo "Point(14.2628 51.2339)", :name "<NAME>"}
;; {:ort "Q162721", :wo "Point(14.265 51.2247)", :name "<NAME>"}
;; {:ort "Q2795", :wo "Point(12.9222 50.8351)", :name "<NAME>"}
;; {:ort "Q115077", :wo "Point(13.5589 54.5586)", :name "<NAME>"}
;; {:ort "Q160799", :wo "Point(14.43713889 51.79291667)", :name "<NAME>"}
;; {:ort "Q318609", :wo "Point(7.28119 53.4654)", :name "<NAME>"}
;; {:ort "Q1124721", :wo "Point(13.3096 53.7516)", :name "<NAME>"}]
;; WikiData is multilingual! Here's a query to list species of Swift
;; (the bird) with their English and German (and often Latin) names
(query '[:select ?englishName ?germanName
:where [[?item (wdt :parent-taxon) (entity "Apodiformes")
_ rdfs:label ?germanName
_ rdfs:label ?englishName]
:filter ((lang ?germanName) = "de")
:filter ((lang ?englishName) = "en")]
:limit 10])
;;=>
;; [{:germanName "Jungornithidae", :englishName "Jungornithidae"}
;; {:germanName "Eocypselus", :englishName "Eocypselus"}
;; {:germanName "Eocypselidae", :englishName "Eocypselidae"}
;; {:germanName "Segler", :englishName "Apodidae"}
;; {:germanName "Höhlensch<NAME>me", :englishName "Aegothelidae"}
;; {:germanName "Aegialornithidae", :englishName "Aegialornithidae"}
;; {:germanName "Apodi", :englishName "Apodi"}
;; {:germanName "Baumsegler", :englishName "treeswift"}
;; {:germanName "Kolibris", :englishName "Trochilidae"}]
;; We can also use triples to find out about analogies in the dataset
(defn make-analogy
"Return known analogies for the form `a1` is to `a2` as `b1` is to ???"
[a1 a2 b1]
(->> (query
(template [:select ?isto ?analogyLabel
:where [[~(symbol (str "wd:" a1)) ?isto ~(symbol (str "wd:" a2))]
[~(symbol (str "wd:" b1)) ?isto ?analogy]
;; tightens analogies by requiring that a2/b2 be of the same kind,
;; but loses some interesting loose analogies:
;; [~(symbol (str "wd:" a2)) (wdt :instance-of) ?kind]
;; [?analogy (wdt :instance-of) ?kind]
]]))
(map #(let [arc (label (:isto %))]
(str (label a1)
" is <" arc "> to "
(label a2)
" as "
(label b1)
" is <" arc "> to " (:analogyLabel %))))
distinct))
(make-analogy (entity "Paris") (entity "France") (entity "Berlin"))
;;=> ("Paris is <country> to France as Berlin is <country> to Germany"
;; "Paris is <capital of> to France as Berlin is <capital of> to Germany")
(apply make-analogy (map entity ["The Beatles" "rock and roll" "<NAME>"]))
;;=> ("The Beatles is <genre> to rock and roll as <NAME> is <genre> to jazz")
;; airports within 100km of Paris, use "around" service
(->>
(query
'[:select :distinct ?placeLabel
:where [[(entity "Paris") (wdt :coordinate-location) ?parisLoc]
[?place (wdt :instance-of) (entity "airport")]
:service wikibase:around [[?place (wdt :coordinate-location) ?location]
[bd:serviceParam wikibase:center ?parisLoc]
[bd:serviceParam wikibase:radius "100"]]]])
(map :placeLabel)
(into #{}))
(defn releases-since
"Returns any creative works published since `year`/`month` by any `entities` known to Wikidata."
[since-year since-month entities]
(let [ents (map #(if (re-find #"^Q[\d]+" %) % (entity %)) entities)]
(query
(template [:select ?workLabel ?creatorLabel ?role ?date
:where [[?work ?role ?creator _ (wdt :publication-date) ?date]
:union ~(mapv #(vector '?work '?role (symbol (str "wd:" %))) ents)
:filter ((year ?date) >= ~since-year)
:filter ((month ?date) >= ~since-month)]
:order-by (asc ?date)]))))
(->> (releases-since 2019 1 ; year and month
["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"
"<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"])
(map #(select-keys % [:workLabel :creatorLabel]))
distinct)
;; How about something a bit more serious? Here we find drug-gene
;; product interactions and diseases for which these might be
;; candidates.
(->> (query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 100])
(group-by :diseaseLabel)
(mapv (fn [[k vs]] [k (mapv #(dissoc % :diseaseLabel) vs)]))
(into {}))
;;=>
;; {"Parkinson disease"
;; [{:drugLabel "SB-203580", :geneLabel "GAK"}],
;; "obesity"
;; [{:drugLabel "allopurinol", :geneLabel "XDH"}
;; {:drugLabel "estriol", :geneLabel "ESR1"}
;; {:drugLabel "tamoxifen", :geneLabel "ESR1"}
;; {:drugLabel "17β-estradiol", :geneLabel "ESR1"}
;; "malaria" [{:drugLabel "benserazide", :geneLabel "DDC"}],
;; "systemic lupus erythematosus"
;; [{:drugLabel "Hypothetical protein CT_814", :geneLabel "DDA1"}
;; {:drugLabel "ibrutinib", :geneLabel "BLK"}],
;; "Crohn's disease"
;; [{:drugLabel "momelotinib", :geneLabel "JAK2"}
;; {:drugLabel "pacritinib", :geneLabel "JAK2"}],
;; "multiple sclerosis"
;; [{:drugLabel "cabozantinib", :geneLabel "MET"}
;; {:drugLabel "crizotinib", :geneLabel "MET"}
;; {:drugLabel "tivantinib", :geneLabel "MET"}],
;; "ulcerative colitis"
;; [{:drugLabel "bumetanide", :geneLabel "GPR35"}
;; {:drugLabel "furosemide", :geneLabel "GPR35"}],
;; "hepatitis B"
;; [{:drugLabel "L-aspartic Acid", :geneLabel "GRIN2A"}
;; {:drugLabel "ketamine", :geneLabel "GRIN2A"}]},
(query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 10])
;;=>
;; [{:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "everolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "ridaforolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "dactolisib", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "temsirolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "AIDA", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}
;; {:drugLabel "CPCCOEt", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Recently added lexical queries
;; A recursive query using property paths
;; https://en.wikibooks.org/wiki/SPARQL/Property_paths
(query
'[:select :distinct ?ancestorLemma ?ancestorLangLabel
:where [[?lexeme (literal "wikibase:lemma") "Quark"@de] ; lexeme for DE word "Quark"
[?lexeme (literal "wdt:P5191") + ?ancestor] ; P5191 = derived-from, too new to be in properties list?!
[?ancestor (literal "wikibase:lemma") ?ancestorLemma ; get each ancestor lemma and language
_ (literal "dct:language") ?ancestorLang]]
:limit 20])
;;=>
;; [{:xLangLabel "Polish", :xLemma "twaróg"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvarogъ"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvoriti"}]
;; Note the use of (literal ...) for cases were we do not yet support
;; the namespace/syntax required for the query. This allows for
;; greater access to the SPARQL endpoint's power while progressively
;; improving our DSL.
;; German-language media representation in Wikidata
(mapv
(fn [zeitung]
(assoc (first (query
(template
[:select (count ?ref :as ?mentions)
:where [[?statement (literal "prov:wasDerivedFrom") ?ref]
[?ref (literal pr:P248) (entity ~zeitung)]]])))
:zeitung zeitung))
["Bild" "Süddeutsche Zeitung" "Frankfurter Allgemeine Zeitung" "Die Zeit" "Die Welt" "Die Tageszeitung"])
;;=>
;; [{:mentions "57", :zeitung "Süddeutsche Zeitung"}
;; {:mentions "19", :zeitung "Frankfurter Allgemeine Zeitung"}
;; {:mentions "15", :zeitung "Die Zeit"}
;; {:mentions "8", :zeitung "Die Welt"}
;; {:mentions "3", :zeitung "Die Tageszeitung"}
;; {:mentions "1", :zeitung "Bild"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; multiple language support (work ongoing)
;; lookup an entity using Thai as the default language
(binding [mundaneum.query/*default-language* "th"]
(entity "ระยอง"))
;; => "Q395325"
;; also works for describe
(binding [mundaneum.query/*default-language* "th"]
(describe (entity "ระยอง")))
;;=> "หน้าแก้ความกำกวมวิกิมีเดีย"
| true |
(ns mundaneum.examples
(:require [mundaneum.query :refer [describe entity label property query stringify-query *default-language*]]
[backtick :refer [template]]
[clj-time.format :as tf]))
;; To understand what's happening here, it would be a good idea to
;; read through this document:
;; https://m.wikidata.org/wiki/Wikidata:SPARQL_query_service/queries
;; The first challenge when using Wikidata is finding the right IDs
;; for the properties and entities you must use to phrase your
;; question properly. We have functions to help:
(entity "U2")
;; Now we know the ID for U2... or do we? Which U2 is it, really?
(describe (entity "U2"))
(entity "U2" :part-of (entity "Berlin U-Bahn"))
(describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
;; We also have functions that turn keywords into property values:
(property :instance-of)
;;=> "P31"
;; ... but we use it indirectly through a set of helper functions
;; named for Wikidata namespaces, like wdt, p, ps and pq. The link
;; above will help you understand which one of these you might want
;; for a given query, but it's most often wdt.
;; we can ask which things contain an administrative territory and get
;; a list of the pairs filtered to the situation where the container
;; is Ireland
(query
'[:select ?areaLabel
:where [[(entity "Ireland") (wdt :contains-administrative-territorial-entity) ?area]]
:limit 50])
;; Discoveries/inventions grouped by person on the clojure side,
(->> (query
'[:select ?thingLabel ?whomLabel
:where [[?thing (wdt :discoverer-or-inventor) ?whom]]
:limit 100])
(group-by :whomLabel)
(reduce #(assoc %1 (first %2) (mapv :thingLabel (second %2))) {}))
;; eye color popularity, grouping and counting as part of the query
(query
'[:select ?eyeColorLabel (count ?person :as ?count)
:where [[?person (wdt :eye-color) ?eyeColor] ]
:group-by ?eyeColorLabel
:order-by (desc ?count)])
;; U7 stations in Berlin w/ geo coords
(query (template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (entity "U7" :part-of ~(entity "Berlin U-Bahn"))
_ (wdt :coordinate-location) ?coord]]]))
;; born in ancient Rome or territories thereof
;; WARN: Strange Clojure compiler bug inside
;; (->> (query
;; '[:select ?itemLabel
;; :where [:union [[[?item (wdt :place-of-birth) ?pob]
;; [?pob (wdt :located-in-the-administrative-territorial-entity) * (entity "ancient rome")]]]]
;; :limit 10])
;; (map :itemLabel)
;; (into #{}))
;;=> #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PIippPI:NAME:<NAME>END_PIus" "PI:NAME:<NAME>END_PI I" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}
;; What places in Germany have names that end in -ow/-itz (indicating
;; that they were historically Slavic)
;;
;; (note the _, which translates to SPARQL's ; which means "use the
;; same subject as before")
(query
'[:select *
:where [[?ort (wdt :instance-of) / (wdt :subclass-of) * (entity "human settlement")
_ (wdt :country) (entity "Germany")
_ rdfs:label ?name
_ (wdt :coordinate-location) ?wo]
:filter ((lang ?name) = "de")
:filter ((regex ?name "(ow|itz)$"))]
:limit 10])
;;=>
;; [{:ort "Q6448", :wo "Point(13.716666666 50.993055555)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q93223", :wo "Point(14.233333333 51.233333333)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q160693", :wo "Point(14.2275 51.2475)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q160779", :wo "Point(14.2628 51.2339)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q162721", :wo "Point(14.265 51.2247)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q2795", :wo "Point(12.9222 50.8351)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q115077", :wo "Point(13.5589 54.5586)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q160799", :wo "Point(14.43713889 51.79291667)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q318609", :wo "Point(7.28119 53.4654)", :name "PI:NAME:<NAME>END_PI"}
;; {:ort "Q1124721", :wo "Point(13.3096 53.7516)", :name "PI:NAME:<NAME>END_PI"}]
;; WikiData is multilingual! Here's a query to list species of Swift
;; (the bird) with their English and German (and often Latin) names
(query '[:select ?englishName ?germanName
:where [[?item (wdt :parent-taxon) (entity "Apodiformes")
_ rdfs:label ?germanName
_ rdfs:label ?englishName]
:filter ((lang ?germanName) = "de")
:filter ((lang ?englishName) = "en")]
:limit 10])
;;=>
;; [{:germanName "Jungornithidae", :englishName "Jungornithidae"}
;; {:germanName "Eocypselus", :englishName "Eocypselus"}
;; {:germanName "Eocypselidae", :englishName "Eocypselidae"}
;; {:germanName "Segler", :englishName "Apodidae"}
;; {:germanName "HöhlenschPI:NAME:<NAME>END_PIme", :englishName "Aegothelidae"}
;; {:germanName "Aegialornithidae", :englishName "Aegialornithidae"}
;; {:germanName "Apodi", :englishName "Apodi"}
;; {:germanName "Baumsegler", :englishName "treeswift"}
;; {:germanName "Kolibris", :englishName "Trochilidae"}]
;; We can also use triples to find out about analogies in the dataset
(defn make-analogy
"Return known analogies for the form `a1` is to `a2` as `b1` is to ???"
[a1 a2 b1]
(->> (query
(template [:select ?isto ?analogyLabel
:where [[~(symbol (str "wd:" a1)) ?isto ~(symbol (str "wd:" a2))]
[~(symbol (str "wd:" b1)) ?isto ?analogy]
;; tightens analogies by requiring that a2/b2 be of the same kind,
;; but loses some interesting loose analogies:
;; [~(symbol (str "wd:" a2)) (wdt :instance-of) ?kind]
;; [?analogy (wdt :instance-of) ?kind]
]]))
(map #(let [arc (label (:isto %))]
(str (label a1)
" is <" arc "> to "
(label a2)
" as "
(label b1)
" is <" arc "> to " (:analogyLabel %))))
distinct))
(make-analogy (entity "Paris") (entity "France") (entity "Berlin"))
;;=> ("Paris is <country> to France as Berlin is <country> to Germany"
;; "Paris is <capital of> to France as Berlin is <capital of> to Germany")
(apply make-analogy (map entity ["The Beatles" "rock and roll" "PI:NAME:<NAME>END_PI"]))
;;=> ("The Beatles is <genre> to rock and roll as PI:NAME:<NAME>END_PI is <genre> to jazz")
;; airports within 100km of Paris, use "around" service
(->>
(query
'[:select :distinct ?placeLabel
:where [[(entity "Paris") (wdt :coordinate-location) ?parisLoc]
[?place (wdt :instance-of) (entity "airport")]
:service wikibase:around [[?place (wdt :coordinate-location) ?location]
[bd:serviceParam wikibase:center ?parisLoc]
[bd:serviceParam wikibase:radius "100"]]]])
(map :placeLabel)
(into #{}))
(defn releases-since
"Returns any creative works published since `year`/`month` by any `entities` known to Wikidata."
[since-year since-month entities]
(let [ents (map #(if (re-find #"^Q[\d]+" %) % (entity %)) entities)]
(query
(template [:select ?workLabel ?creatorLabel ?role ?date
:where [[?work ?role ?creator _ (wdt :publication-date) ?date]
:union ~(mapv #(vector '?work '?role (symbol (str "wd:" %))) ents)
:filter ((year ?date) >= ~since-year)
:filter ((month ?date) >= ~since-month)]
:order-by (asc ?date)]))))
(->> (releases-since 2019 1 ; year and month
["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])
(map #(select-keys % [:workLabel :creatorLabel]))
distinct)
;; How about something a bit more serious? Here we find drug-gene
;; product interactions and diseases for which these might be
;; candidates.
(->> (query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 100])
(group-by :diseaseLabel)
(mapv (fn [[k vs]] [k (mapv #(dissoc % :diseaseLabel) vs)]))
(into {}))
;;=>
;; {"Parkinson disease"
;; [{:drugLabel "SB-203580", :geneLabel "GAK"}],
;; "obesity"
;; [{:drugLabel "allopurinol", :geneLabel "XDH"}
;; {:drugLabel "estriol", :geneLabel "ESR1"}
;; {:drugLabel "tamoxifen", :geneLabel "ESR1"}
;; {:drugLabel "17β-estradiol", :geneLabel "ESR1"}
;; "malaria" [{:drugLabel "benserazide", :geneLabel "DDC"}],
;; "systemic lupus erythematosus"
;; [{:drugLabel "Hypothetical protein CT_814", :geneLabel "DDA1"}
;; {:drugLabel "ibrutinib", :geneLabel "BLK"}],
;; "Crohn's disease"
;; [{:drugLabel "momelotinib", :geneLabel "JAK2"}
;; {:drugLabel "pacritinib", :geneLabel "JAK2"}],
;; "multiple sclerosis"
;; [{:drugLabel "cabozantinib", :geneLabel "MET"}
;; {:drugLabel "crizotinib", :geneLabel "MET"}
;; {:drugLabel "tivantinib", :geneLabel "MET"}],
;; "ulcerative colitis"
;; [{:drugLabel "bumetanide", :geneLabel "GPR35"}
;; {:drugLabel "furosemide", :geneLabel "GPR35"}],
;; "hepatitis B"
;; [{:drugLabel "L-aspartic Acid", :geneLabel "GRIN2A"}
;; {:drugLabel "ketamine", :geneLabel "GRIN2A"}]},
(query
'[:select ?drugLabel ?geneLabel ?diseaseLabel
:where [[?drug (wdt :physically-interacts-with) ?gene_product]
[?gene_product (wdt :encoded-by) ?gene]
[?gene (wdt :genetic-association) ?disease]]
:limit 10])
;;=>
;; [{:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "basal-cell carcinoma"}
;; {:drugLabel "Hypothetical protein CTL0156", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "Hypothetical protein CT_788", :geneLabel "TP53", :diseaseLabel "head and neck squamous cell carcinoma"}
;; {:drugLabel "everolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "ridaforolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "dactolisib", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "temsirolimus", :geneLabel "MTOR", :diseaseLabel "macrocephaly-intellectual disability-neurodevelopmental disorder-small thorax syndrome"}
;; {:drugLabel "AIDA", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}
;; {:drugLabel "CPCCOEt", :geneLabel "GRM1", :diseaseLabel "autosomal recessive spinocerebellar ataxia 13"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Recently added lexical queries
;; A recursive query using property paths
;; https://en.wikibooks.org/wiki/SPARQL/Property_paths
(query
'[:select :distinct ?ancestorLemma ?ancestorLangLabel
:where [[?lexeme (literal "wikibase:lemma") "Quark"@de] ; lexeme for DE word "Quark"
[?lexeme (literal "wdt:P5191") + ?ancestor] ; P5191 = derived-from, too new to be in properties list?!
[?ancestor (literal "wikibase:lemma") ?ancestorLemma ; get each ancestor lemma and language
_ (literal "dct:language") ?ancestorLang]]
:limit 20])
;;=>
;; [{:xLangLabel "Polish", :xLemma "twaróg"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvarogъ"}
;; {:xLangLabel "Proto-Slavic", :xLemma "*tvoriti"}]
;; Note the use of (literal ...) for cases were we do not yet support
;; the namespace/syntax required for the query. This allows for
;; greater access to the SPARQL endpoint's power while progressively
;; improving our DSL.
;; German-language media representation in Wikidata
(mapv
(fn [zeitung]
(assoc (first (query
(template
[:select (count ?ref :as ?mentions)
:where [[?statement (literal "prov:wasDerivedFrom") ?ref]
[?ref (literal pr:P248) (entity ~zeitung)]]])))
:zeitung zeitung))
["Bild" "Süddeutsche Zeitung" "Frankfurter Allgemeine Zeitung" "Die Zeit" "Die Welt" "Die Tageszeitung"])
;;=>
;; [{:mentions "57", :zeitung "Süddeutsche Zeitung"}
;; {:mentions "19", :zeitung "Frankfurter Allgemeine Zeitung"}
;; {:mentions "15", :zeitung "Die Zeit"}
;; {:mentions "8", :zeitung "Die Welt"}
;; {:mentions "3", :zeitung "Die Tageszeitung"}
;; {:mentions "1", :zeitung "Bild"}]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; multiple language support (work ongoing)
;; lookup an entity using Thai as the default language
(binding [mundaneum.query/*default-language* "th"]
(entity "ระยอง"))
;; => "Q395325"
;; also works for describe
(binding [mundaneum.query/*default-language* "th"]
(describe (entity "ระยอง")))
;;=> "หน้าแก้ความกำกวมวิกิมีเดีย"
|
[
{
"context": "(ns ^{:author \"Leeor Engel\"}\n chapter-3.chapter-3-q1\n (:import (clojure.la",
"end": 26,
"score": 0.9998949766159058,
"start": 15,
"tag": "NAME",
"value": "Leeor Engel"
}
] |
Clojure/src/chapter_3/chapter_3_q1.clj
|
Kiandr/crackingcodinginterview
| 0 |
(ns ^{:author "Leeor Engel"}
chapter-3.chapter-3-q1
(:import (clojure.lang Atom)))
(defprotocol Stacks
(stack-pop [this stack-num])
(stack-peek [this stack-num])
(stack-push [this stack-num x])
(stack-empty? [this stack-num]))
(defn- peek-with-fn [n stack-num stacks post-peek-fn]
{:pre [(<= 1 stack-num 3)]}
(let [tops (:tops stacks)
arr (:arr stacks)
tops-vec @tops
to-pop-idx (get tops-vec (dec stack-num))]
(if (>= to-pop-idx (* n (dec stack-num)))
(let [popped (aget arr to-pop-idx)]
(when (some? post-peek-fn)
(post-peek-fn tops to-pop-idx))
popped)
nil)))
(defrecord ThreeStacks [n arr ^Atom tops]
Stacks
(stack-pop [this stack-num]
(peek-with-fn n stack-num this (fn [^Atom tops to-pop-idx]
(let [new-top (dec to-pop-idx)]
(swap! tops assoc (dec stack-num) new-top)))))
(stack-peek [this stack-num]
(peek-with-fn n stack-num this nil))
(stack-push [this stack-num x]
(if (let [max-idx (dec (* n stack-num))]
(= max-idx (get @tops (dec stack-num))))
(throw (IllegalStateException. "Stack full!"))
(let [tops-vec @tops
cur-top-idx (get tops-vec (dec stack-num))
to-push-idx (inc cur-top-idx)]
(aset arr to-push-idx x)
(swap! tops assoc (dec stack-num) to-push-idx))))
(stack-empty? [this stack-num]
(if (<= 1 stack-num 3)
(let [tops-vec @tops]
(< (get tops-vec (dec stack-num)) (* n (dec stack-num))))
(throw (IllegalArgumentException. "Invalid stack number!")))))
(defn create-three-stacks [n]
(->ThreeStacks n (make-array Object (* n 3)) (atom [(dec (* n 0)) (dec (* n 1)) (dec (* n 2))])))
|
33820
|
(ns ^{:author "<NAME>"}
chapter-3.chapter-3-q1
(:import (clojure.lang Atom)))
(defprotocol Stacks
(stack-pop [this stack-num])
(stack-peek [this stack-num])
(stack-push [this stack-num x])
(stack-empty? [this stack-num]))
(defn- peek-with-fn [n stack-num stacks post-peek-fn]
{:pre [(<= 1 stack-num 3)]}
(let [tops (:tops stacks)
arr (:arr stacks)
tops-vec @tops
to-pop-idx (get tops-vec (dec stack-num))]
(if (>= to-pop-idx (* n (dec stack-num)))
(let [popped (aget arr to-pop-idx)]
(when (some? post-peek-fn)
(post-peek-fn tops to-pop-idx))
popped)
nil)))
(defrecord ThreeStacks [n arr ^Atom tops]
Stacks
(stack-pop [this stack-num]
(peek-with-fn n stack-num this (fn [^Atom tops to-pop-idx]
(let [new-top (dec to-pop-idx)]
(swap! tops assoc (dec stack-num) new-top)))))
(stack-peek [this stack-num]
(peek-with-fn n stack-num this nil))
(stack-push [this stack-num x]
(if (let [max-idx (dec (* n stack-num))]
(= max-idx (get @tops (dec stack-num))))
(throw (IllegalStateException. "Stack full!"))
(let [tops-vec @tops
cur-top-idx (get tops-vec (dec stack-num))
to-push-idx (inc cur-top-idx)]
(aset arr to-push-idx x)
(swap! tops assoc (dec stack-num) to-push-idx))))
(stack-empty? [this stack-num]
(if (<= 1 stack-num 3)
(let [tops-vec @tops]
(< (get tops-vec (dec stack-num)) (* n (dec stack-num))))
(throw (IllegalArgumentException. "Invalid stack number!")))))
(defn create-three-stacks [n]
(->ThreeStacks n (make-array Object (* n 3)) (atom [(dec (* n 0)) (dec (* n 1)) (dec (* n 2))])))
| true |
(ns ^{:author "PI:NAME:<NAME>END_PI"}
chapter-3.chapter-3-q1
(:import (clojure.lang Atom)))
(defprotocol Stacks
(stack-pop [this stack-num])
(stack-peek [this stack-num])
(stack-push [this stack-num x])
(stack-empty? [this stack-num]))
(defn- peek-with-fn [n stack-num stacks post-peek-fn]
{:pre [(<= 1 stack-num 3)]}
(let [tops (:tops stacks)
arr (:arr stacks)
tops-vec @tops
to-pop-idx (get tops-vec (dec stack-num))]
(if (>= to-pop-idx (* n (dec stack-num)))
(let [popped (aget arr to-pop-idx)]
(when (some? post-peek-fn)
(post-peek-fn tops to-pop-idx))
popped)
nil)))
(defrecord ThreeStacks [n arr ^Atom tops]
Stacks
(stack-pop [this stack-num]
(peek-with-fn n stack-num this (fn [^Atom tops to-pop-idx]
(let [new-top (dec to-pop-idx)]
(swap! tops assoc (dec stack-num) new-top)))))
(stack-peek [this stack-num]
(peek-with-fn n stack-num this nil))
(stack-push [this stack-num x]
(if (let [max-idx (dec (* n stack-num))]
(= max-idx (get @tops (dec stack-num))))
(throw (IllegalStateException. "Stack full!"))
(let [tops-vec @tops
cur-top-idx (get tops-vec (dec stack-num))
to-push-idx (inc cur-top-idx)]
(aset arr to-push-idx x)
(swap! tops assoc (dec stack-num) to-push-idx))))
(stack-empty? [this stack-num]
(if (<= 1 stack-num 3)
(let [tops-vec @tops]
(< (get tops-vec (dec stack-num)) (* n (dec stack-num))))
(throw (IllegalArgumentException. "Invalid stack number!")))))
(defn create-three-stacks [n]
(->ThreeStacks n (make-array Object (* n 3)) (atom [(dec (* n 0)) (dec (* n 1)) (dec (* n 2))])))
|
[
{
"context": ":latitude \"6457.934248,N\"})\n\n(def valid-password \"joujou\")\n(def valid-password-params {:X-foobar \"bar\",\n ",
"end": 488,
"score": 0.9995114803314209,
"start": 482,
"tag": "PASSWORD",
"value": "joujou"
},
{
"context": "6.100084,E\",\n :password valid-password\n :version \"1\",",
"end": 688,
"score": 0.8692781925201416,
"start": 683,
"tag": "PASSWORD",
"value": "valid"
},
{
"context": "ed-secret})\n(def valid-password-tracker {:password valid-password})\n \n(fact \"when tracker is not available, authen",
"end": 1008,
"score": 0.9937958717346191,
"start": 994,
"tag": "PASSWORD",
"value": "valid-password"
},
{
"context": "tication-status valid-password-params {:password \"wrong-password\"} :mac)\n => {:authentication-failed true})\n\n",
"end": 1726,
"score": 0.9988572597503662,
"start": 1712,
"tag": "PASSWORD",
"value": "wrong-password"
}
] |
test/ruuvi_server/tracker_security_test.clj
|
RuuviTracker/ruuvitracker_server
| 1 |
(ns ruuvi-server.tracker-security-test
(:use midje.sweet
ruuvi-server.tracker-security)
)
(def valid-mac "17e4ccf60f766710d0695348d7fda63cee0a3d46")
(def valid-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:mac valid-mac
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-password "joujou")
(def valid-password-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:password valid-password
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-shared-secret "foobar")
(def valid-tracker {:shared_secret valid-shared-secret})
(def valid-password-tracker {:password valid-password})
(fact "when tracker is not available, authentication is not attempted"
(authentication-status valid-params nil :mac )
=> {:unknown-tracker true})
(fact "when mac or password field is not in message, authentication is not used"
(authentication-status {:some "fields"} valid-tracker :mac)
=> {:not-authenticated true})
(fact "when computed mac does not match mac in message, authentication fails"
(authentication-status valid-params {:shared_secret "wrong-shared-secret"} :mac)
=> {:authentication-failed true})
(fact "when request password does not match tracker's password, authentication fails"
(authentication-status valid-password-params {:password "wrong-password"} :mac)
=> {:authentication-failed true})
(fact "when computed mac matches mac in message, authentication succeeds"
(authentication-status valid-params valid-tracker :mac)
=> {:authenticated-tracker true}
(provided (compute-hmac valid-params valid-shared-secret :mac) => valid-mac))
(fact "when request password matches trackers password, authentication succeeds"
(authentication-status valid-password-params valid-password-tracker :mac)
=> {:authenticated-tracker true})
(fact
(generate-mac-message valid-params :mac) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact
(generate-mac-message valid-params :not-exists) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|mac:17e4ccf60f766710d0695348d7fda63cee0a3d46|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact "compute-hmac appends secret to end of (generate-mac-message ...) and computes HMAC-SHA1 from that"
(compute-hmac valid-params "secret" :mac) => "fd264415979bb17f68a3e4fd3b645b7e763e3b56"
(provided
(generate-mac-message valid-params :mac) => "base"))
|
87914
|
(ns ruuvi-server.tracker-security-test
(:use midje.sweet
ruuvi-server.tracker-security)
)
(def valid-mac "17e4ccf60f766710d0695348d7fda63cee0a3d46")
(def valid-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:mac valid-mac
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-password "<PASSWORD>")
(def valid-password-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:password <PASSWORD>-password
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-shared-secret "foobar")
(def valid-tracker {:shared_secret valid-shared-secret})
(def valid-password-tracker {:password <PASSWORD>})
(fact "when tracker is not available, authentication is not attempted"
(authentication-status valid-params nil :mac )
=> {:unknown-tracker true})
(fact "when mac or password field is not in message, authentication is not used"
(authentication-status {:some "fields"} valid-tracker :mac)
=> {:not-authenticated true})
(fact "when computed mac does not match mac in message, authentication fails"
(authentication-status valid-params {:shared_secret "wrong-shared-secret"} :mac)
=> {:authentication-failed true})
(fact "when request password does not match tracker's password, authentication fails"
(authentication-status valid-password-params {:password "<PASSWORD>"} :mac)
=> {:authentication-failed true})
(fact "when computed mac matches mac in message, authentication succeeds"
(authentication-status valid-params valid-tracker :mac)
=> {:authenticated-tracker true}
(provided (compute-hmac valid-params valid-shared-secret :mac) => valid-mac))
(fact "when request password matches trackers password, authentication succeeds"
(authentication-status valid-password-params valid-password-tracker :mac)
=> {:authenticated-tracker true})
(fact
(generate-mac-message valid-params :mac) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact
(generate-mac-message valid-params :not-exists) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|mac:17e4ccf60f766710d0695348d7fda63cee0a3d46|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact "compute-hmac appends secret to end of (generate-mac-message ...) and computes HMAC-SHA1 from that"
(compute-hmac valid-params "secret" :mac) => "fd264415979bb17f68a3e4fd3b645b7e763e3b56"
(provided
(generate-mac-message valid-params :mac) => "base"))
| true |
(ns ruuvi-server.tracker-security-test
(:use midje.sweet
ruuvi-server.tracker-security)
)
(def valid-mac "17e4ccf60f766710d0695348d7fda63cee0a3d46")
(def valid-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:mac valid-mac
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-password "PI:PASSWORD:<PASSWORD>END_PI")
(def valid-password-params {:X-foobar "bar",
:tracker_code "foobar",
:longitude "02536.100084,E",
:password PI:PASSWORD:<PASSWORD>END_PI-password
:version "1",
:time "2012-04-02T18:35:11.000+0200",
:latitude "6457.934248,N"})
(def valid-shared-secret "foobar")
(def valid-tracker {:shared_secret valid-shared-secret})
(def valid-password-tracker {:password PI:PASSWORD:<PASSWORD>END_PI})
(fact "when tracker is not available, authentication is not attempted"
(authentication-status valid-params nil :mac )
=> {:unknown-tracker true})
(fact "when mac or password field is not in message, authentication is not used"
(authentication-status {:some "fields"} valid-tracker :mac)
=> {:not-authenticated true})
(fact "when computed mac does not match mac in message, authentication fails"
(authentication-status valid-params {:shared_secret "wrong-shared-secret"} :mac)
=> {:authentication-failed true})
(fact "when request password does not match tracker's password, authentication fails"
(authentication-status valid-password-params {:password "PI:PASSWORD:<PASSWORD>END_PI"} :mac)
=> {:authentication-failed true})
(fact "when computed mac matches mac in message, authentication succeeds"
(authentication-status valid-params valid-tracker :mac)
=> {:authenticated-tracker true}
(provided (compute-hmac valid-params valid-shared-secret :mac) => valid-mac))
(fact "when request password matches trackers password, authentication succeeds"
(authentication-status valid-password-params valid-password-tracker :mac)
=> {:authenticated-tracker true})
(fact
(generate-mac-message valid-params :mac) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact
(generate-mac-message valid-params :not-exists) => "X-foobar:bar|latitude:6457.934248,N|longitude:02536.100084,E|mac:17e4ccf60f766710d0695348d7fda63cee0a3d46|time:2012-04-02T18:35:11.000+0200|tracker_code:foobar|version:1|")
(fact "compute-hmac appends secret to end of (generate-mac-message ...) and computes HMAC-SHA1 from that"
(compute-hmac valid-params "secret" :mac) => "fd264415979bb17f68a3e4fd3b645b7e763e3b56"
(provided
(generate-mac-message valid-params :mac) => "base"))
|
[
{
"context": "j -- simple call-tracing macros for Clojure\n\n;; by Stuart Sierra, http://stuartsierra.com/\n;; December 3, 2008\n\n;;",
"end": 76,
"score": 0.9998924136161804,
"start": 63,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "tsierra.com/\n;; December 3, 2008\n\n;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use\n;; and distr",
"end": 154,
"score": 0.9998829960823059,
"start": 141,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "nction instead of a macro \n;; (suggestion from Stuart Halloway)\n;;\n;; * added trace-fn-call\n;;\n;; Jun",
"end": 847,
"score": 0.6740127801895142,
"start": 841,
"tag": "NAME",
"value": "Stuart"
},
{
"context": "June 9, 2008: first version\n\n\n\n(ns \n #^{:author \"Stuart Sierra, Michel Salim\",\n :doc \"This file defines simp",
"end": 957,
"score": 0.9998952150344849,
"start": 944,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "first version\n\n\n\n(ns \n #^{:author \"Stuart Sierra, Michel Salim\",\n :doc \"This file defines simple \\\"tracing\\\"",
"end": 971,
"score": 0.9998664855957031,
"start": 959,
"tag": "NAME",
"value": "Michel Salim"
}
] |
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/trace.clj
|
allertonm/Couverjure
| 3 |
;;; trace.clj -- simple call-tracing macros for Clojure
;; by Stuart Sierra, http://stuartsierra.com/
;; December 3, 2008
;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; This file defines simple "tracing" macros to help you see what your
;; code is doing.
;; CHANGE LOG
;;
;; December 3, 2008:
;;
;; * replaced *trace-out* with tracer
;;
;; * made trace a function instead of a macro
;; (suggestion from Stuart Halloway)
;;
;; * added trace-fn-call
;;
;; June 9, 2008: first version
(ns
#^{:author "Stuart Sierra, Michel Salim",
:doc "This file defines simple \"tracing\" macros to help you see what your
code is doing."}
clojure.contrib.trace)
(def
#^{:doc "Current stack depth of traced function calls."}
*trace-depth* 0)
(defn tracer
"This function is called by trace. Prints to standard output, but
may be rebound to do anything you like. 'name' is optional."
[name value]
(println (str "TRACE" (when name (str " " name)) ": " value)))
(defn trace
"Sends name (optional) and value to the tracer function, then
returns value. May be wrapped around any expression without
affecting the result."
([value] (trace nil value))
([name value]
(tracer name (pr-str value))
value))
(defn trace-indent
"Returns an indentation string based on *trace-depth*"
[]
(apply str (take *trace-depth* (repeat "| "))))
(defn trace-fn-call
"Traces a single call to a function f with args. 'name' is the
symbol name of the function."
[name f args]
(let [id (gensym "t")]
(tracer id (str (trace-indent) (pr-str (cons name args))))
(let [value (binding [*trace-depth* (inc *trace-depth*)]
(apply f args))]
(tracer id (str (trace-indent) "=> " (pr-str value)))
value)))
(defmacro deftrace
"Use in place of defn; traces each call/return of this fn, including
arguments. Nested calls to deftrace'd functions will print a
tree-like structure."
[name & definition]
`(do
(def ~name)
(let [f# (fn ~@definition)]
(defn ~name [& args#]
(trace-fn-call '~name f# args#)))))
(defmacro dotrace
"Given a sequence of function identifiers, evaluate the body
expressions in an environment in which the identifiers are bound to
the traced functions. Does not work on inlined functions,
such as clojure.core/+"
[fns & exprs]
(if (empty? fns)
`(do ~@exprs)
(let [func (first fns)
fns (next fns)]
`(let [f# ~func]
(binding [~func (fn [& args#] (trace-fn-call '~func f# args#))]
(dotrace ~fns ~@exprs))))))
|
107182
|
;;; trace.clj -- simple call-tracing macros for Clojure
;; by <NAME>, http://stuartsierra.com/
;; December 3, 2008
;; Copyright (c) <NAME>, 2008. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; This file defines simple "tracing" macros to help you see what your
;; code is doing.
;; CHANGE LOG
;;
;; December 3, 2008:
;;
;; * replaced *trace-out* with tracer
;;
;; * made trace a function instead of a macro
;; (suggestion from <NAME> Halloway)
;;
;; * added trace-fn-call
;;
;; June 9, 2008: first version
(ns
#^{:author "<NAME>, <NAME>",
:doc "This file defines simple \"tracing\" macros to help you see what your
code is doing."}
clojure.contrib.trace)
(def
#^{:doc "Current stack depth of traced function calls."}
*trace-depth* 0)
(defn tracer
"This function is called by trace. Prints to standard output, but
may be rebound to do anything you like. 'name' is optional."
[name value]
(println (str "TRACE" (when name (str " " name)) ": " value)))
(defn trace
"Sends name (optional) and value to the tracer function, then
returns value. May be wrapped around any expression without
affecting the result."
([value] (trace nil value))
([name value]
(tracer name (pr-str value))
value))
(defn trace-indent
"Returns an indentation string based on *trace-depth*"
[]
(apply str (take *trace-depth* (repeat "| "))))
(defn trace-fn-call
"Traces a single call to a function f with args. 'name' is the
symbol name of the function."
[name f args]
(let [id (gensym "t")]
(tracer id (str (trace-indent) (pr-str (cons name args))))
(let [value (binding [*trace-depth* (inc *trace-depth*)]
(apply f args))]
(tracer id (str (trace-indent) "=> " (pr-str value)))
value)))
(defmacro deftrace
"Use in place of defn; traces each call/return of this fn, including
arguments. Nested calls to deftrace'd functions will print a
tree-like structure."
[name & definition]
`(do
(def ~name)
(let [f# (fn ~@definition)]
(defn ~name [& args#]
(trace-fn-call '~name f# args#)))))
(defmacro dotrace
"Given a sequence of function identifiers, evaluate the body
expressions in an environment in which the identifiers are bound to
the traced functions. Does not work on inlined functions,
such as clojure.core/+"
[fns & exprs]
(if (empty? fns)
`(do ~@exprs)
(let [func (first fns)
fns (next fns)]
`(let [f# ~func]
(binding [~func (fn [& args#] (trace-fn-call '~func f# args#))]
(dotrace ~fns ~@exprs))))))
| true |
;;; trace.clj -- simple call-tracing macros for Clojure
;; by PI:NAME:<NAME>END_PI, http://stuartsierra.com/
;; December 3, 2008
;; Copyright (c) PI:NAME:<NAME>END_PI, 2008. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; This file defines simple "tracing" macros to help you see what your
;; code is doing.
;; CHANGE LOG
;;
;; December 3, 2008:
;;
;; * replaced *trace-out* with tracer
;;
;; * made trace a function instead of a macro
;; (suggestion from PI:NAME:<NAME>END_PI Halloway)
;;
;; * added trace-fn-call
;;
;; June 9, 2008: first version
(ns
#^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:doc "This file defines simple \"tracing\" macros to help you see what your
code is doing."}
clojure.contrib.trace)
(def
#^{:doc "Current stack depth of traced function calls."}
*trace-depth* 0)
(defn tracer
"This function is called by trace. Prints to standard output, but
may be rebound to do anything you like. 'name' is optional."
[name value]
(println (str "TRACE" (when name (str " " name)) ": " value)))
(defn trace
"Sends name (optional) and value to the tracer function, then
returns value. May be wrapped around any expression without
affecting the result."
([value] (trace nil value))
([name value]
(tracer name (pr-str value))
value))
(defn trace-indent
"Returns an indentation string based on *trace-depth*"
[]
(apply str (take *trace-depth* (repeat "| "))))
(defn trace-fn-call
"Traces a single call to a function f with args. 'name' is the
symbol name of the function."
[name f args]
(let [id (gensym "t")]
(tracer id (str (trace-indent) (pr-str (cons name args))))
(let [value (binding [*trace-depth* (inc *trace-depth*)]
(apply f args))]
(tracer id (str (trace-indent) "=> " (pr-str value)))
value)))
(defmacro deftrace
"Use in place of defn; traces each call/return of this fn, including
arguments. Nested calls to deftrace'd functions will print a
tree-like structure."
[name & definition]
`(do
(def ~name)
(let [f# (fn ~@definition)]
(defn ~name [& args#]
(trace-fn-call '~name f# args#)))))
(defmacro dotrace
"Given a sequence of function identifiers, evaluate the body
expressions in an environment in which the identifiers are bound to
the traced functions. Does not work on inlined functions,
such as clojure.core/+"
[fns & exprs]
(if (empty? fns)
`(do ~@exprs)
(let [func (first fns)
fns (next fns)]
`(let [f# ~func]
(binding [~func (fn [& args#] (trace-fn-call '~func f# args#))]
(dotrace ~fns ~@exprs))))))
|
[
{
"context": " load-file from ~/.clojure/deps.edn\n\n Stolen from Sean Corfield's configurations https://github.com/seancorfield/",
"end": 86,
"score": 0.9998881816864014,
"start": 73,
"tag": "NAME",
"value": "Sean Corfield"
},
{
"context": "Sean Corfield's configurations https://github.com/seancorfield/dot-clojure\"\n (:require [clojure.string :as str]",
"end": 135,
"score": 0.9997166395187378,
"start": 123,
"tag": "USERNAME",
"value": "seancorfield"
}
] |
clojure/dev.clj
|
wandersoncferreira/dotfiles
| 37 |
(ns dev
"Invoked via load-file from ~/.clojure/deps.edn
Stolen from Sean Corfield's configurations https://github.com/seancorfield/dot-clojure"
(:require [clojure.string :as str]
[clojure.repl :refer [demunge]]))
(defn- ellipsis [s n] (if (< n (count s)) (str "..." (subs s (- (count s) n))) s))
(defn- clean-trace
"Given a stack trace frame, trim class and file to the rightmost 24
chars so they make a nice, neat table."
[[c f file line]]
[(symbol (ellipsis (-> (name c)
(demunge)
(str/replace #"--[0-9]{1,}" ""))
24))
f
(ellipsis file 24)
line])
(defn- install-reveal-extras
"Returns a Reveal view object that tracks each tap>'d value and
displays its metadata and class type, and its value in a table.
In order for this to take effect, this function needs to be
called and its result sent to Reveal, after Reveal is up and
running. This dev.clj file achieves this by executing the
following code when starting Reveal:
(future (Thread/sleep 6000)
(tap> (install-reveal-extras)))
The six second delay should be enough for Reveal to initialize
and display its initial view."
[]
(try
(let [last-tap (atom nil)
rx-stream-as-is (requiring-resolve 'vlaaad.reveal.ext/stream-as-is)
rx-obs-view @(requiring-resolve 'vlaaad.reveal.ext/observable-view)
rx-value-view @(requiring-resolve 'vlaaad.reveal.ext/value-view)
rx-table-view @(requiring-resolve 'vlaaad.reveal.ext/table-view)
rx-as (requiring-resolve 'vlaaad.reveal.ext/as)
rx-raw-string (requiring-resolve 'vlaaad.reveal.ext/raw-string)]
(add-tap #(reset! last-tap %))
(rx-stream-as-is
(rx-as
{:fx/type rx-obs-view
:ref last-tap
:fn (fn [x]
(let [x' (if (var? x) (deref x) x) ; get Var's value
c (class x') ; class of underlying value
m (meta x) ; original metadata
m' (when (var? x) (meta x')) ; underlying Var metadata (if any)
[ex-m ex-d ex-t]
(when (instance? Throwable x')
[(ex-message x') (ex-data x') (-> x' (Throwable->map) :trace)])
;; if the underlying value is a function
;; and it has a docstring, use that; if
;; the underlying value is a namespace,
;; run ns-publics and display that map:
x' (cond
(and (fn? x') (or (:doc m) (:doc m')))
(or (:doc m) (:doc m'))
(= clojure.lang.Namespace c)
(ns-publics x')
ex-t ; show stack trace if present
(mapv clean-trace ex-t)
:else
x')]
{:fx/type :v-box
:children
;; in the top box, display metadata
[{:fx/type rx-value-view
:v-box/vgrow :always
:value (cond-> (assoc m :_class c)
m'
(assoc :_meta m')
ex-m
(assoc :_message ex-m)
ex-d
(assoc :_data ex-d))}
(cond
;; display a string in raw form for easier reading:
(string? x')
{:fx/type rx-value-view
:v-box/vgrow :always
:value (rx-stream-as-is (rx-as x' (rx-raw-string x' {:fill :string})))}
;; automatically display URLs using the internal browser:
(instance? java.net.URL x')
{:fx/type :web-view
:url (str x')}
;; else display simple values as a single item in a table:
(or (nil? x') (not (seqable? x')))
{:fx/type rx-table-view
:items [x']
:v-box/vgrow :always
:columns [{:fn identity :header 'value}
{:fn str :header 'string}]}
:else ; display the value in a reasonable table form:
(let [head (first x')]
{:fx/type rx-table-view
:items x'
:v-box/vgrow :always
:columns (cond
(map? head) (for [k (keys head)] {:header k :fn #(get % k)})
(map-entry? head) [{:header 'key :fn key} {:header 'val :fn val}]
(indexed? head) (for [i (range (bounded-count 1024 head))] {:header i :fn #(nth % i)})
:else [{:header 'item :fn identity}])}))]}))}
(rx-raw-string "right-click > view" {:fill :object}))))
(catch Throwable t
(println "Unable to install Reveal extras!")
(println (ex-message t)))))
;; start
(try
(future
(do
(Thread/sleep 5000)
(tap> (install-reveal-extras))))
(catch Exception _exc))
|
22208
|
(ns dev
"Invoked via load-file from ~/.clojure/deps.edn
Stolen from <NAME>'s configurations https://github.com/seancorfield/dot-clojure"
(:require [clojure.string :as str]
[clojure.repl :refer [demunge]]))
(defn- ellipsis [s n] (if (< n (count s)) (str "..." (subs s (- (count s) n))) s))
(defn- clean-trace
"Given a stack trace frame, trim class and file to the rightmost 24
chars so they make a nice, neat table."
[[c f file line]]
[(symbol (ellipsis (-> (name c)
(demunge)
(str/replace #"--[0-9]{1,}" ""))
24))
f
(ellipsis file 24)
line])
(defn- install-reveal-extras
"Returns a Reveal view object that tracks each tap>'d value and
displays its metadata and class type, and its value in a table.
In order for this to take effect, this function needs to be
called and its result sent to Reveal, after Reveal is up and
running. This dev.clj file achieves this by executing the
following code when starting Reveal:
(future (Thread/sleep 6000)
(tap> (install-reveal-extras)))
The six second delay should be enough for Reveal to initialize
and display its initial view."
[]
(try
(let [last-tap (atom nil)
rx-stream-as-is (requiring-resolve 'vlaaad.reveal.ext/stream-as-is)
rx-obs-view @(requiring-resolve 'vlaaad.reveal.ext/observable-view)
rx-value-view @(requiring-resolve 'vlaaad.reveal.ext/value-view)
rx-table-view @(requiring-resolve 'vlaaad.reveal.ext/table-view)
rx-as (requiring-resolve 'vlaaad.reveal.ext/as)
rx-raw-string (requiring-resolve 'vlaaad.reveal.ext/raw-string)]
(add-tap #(reset! last-tap %))
(rx-stream-as-is
(rx-as
{:fx/type rx-obs-view
:ref last-tap
:fn (fn [x]
(let [x' (if (var? x) (deref x) x) ; get Var's value
c (class x') ; class of underlying value
m (meta x) ; original metadata
m' (when (var? x) (meta x')) ; underlying Var metadata (if any)
[ex-m ex-d ex-t]
(when (instance? Throwable x')
[(ex-message x') (ex-data x') (-> x' (Throwable->map) :trace)])
;; if the underlying value is a function
;; and it has a docstring, use that; if
;; the underlying value is a namespace,
;; run ns-publics and display that map:
x' (cond
(and (fn? x') (or (:doc m) (:doc m')))
(or (:doc m) (:doc m'))
(= clojure.lang.Namespace c)
(ns-publics x')
ex-t ; show stack trace if present
(mapv clean-trace ex-t)
:else
x')]
{:fx/type :v-box
:children
;; in the top box, display metadata
[{:fx/type rx-value-view
:v-box/vgrow :always
:value (cond-> (assoc m :_class c)
m'
(assoc :_meta m')
ex-m
(assoc :_message ex-m)
ex-d
(assoc :_data ex-d))}
(cond
;; display a string in raw form for easier reading:
(string? x')
{:fx/type rx-value-view
:v-box/vgrow :always
:value (rx-stream-as-is (rx-as x' (rx-raw-string x' {:fill :string})))}
;; automatically display URLs using the internal browser:
(instance? java.net.URL x')
{:fx/type :web-view
:url (str x')}
;; else display simple values as a single item in a table:
(or (nil? x') (not (seqable? x')))
{:fx/type rx-table-view
:items [x']
:v-box/vgrow :always
:columns [{:fn identity :header 'value}
{:fn str :header 'string}]}
:else ; display the value in a reasonable table form:
(let [head (first x')]
{:fx/type rx-table-view
:items x'
:v-box/vgrow :always
:columns (cond
(map? head) (for [k (keys head)] {:header k :fn #(get % k)})
(map-entry? head) [{:header 'key :fn key} {:header 'val :fn val}]
(indexed? head) (for [i (range (bounded-count 1024 head))] {:header i :fn #(nth % i)})
:else [{:header 'item :fn identity}])}))]}))}
(rx-raw-string "right-click > view" {:fill :object}))))
(catch Throwable t
(println "Unable to install Reveal extras!")
(println (ex-message t)))))
;; start
(try
(future
(do
(Thread/sleep 5000)
(tap> (install-reveal-extras))))
(catch Exception _exc))
| true |
(ns dev
"Invoked via load-file from ~/.clojure/deps.edn
Stolen from PI:NAME:<NAME>END_PI's configurations https://github.com/seancorfield/dot-clojure"
(:require [clojure.string :as str]
[clojure.repl :refer [demunge]]))
(defn- ellipsis [s n] (if (< n (count s)) (str "..." (subs s (- (count s) n))) s))
(defn- clean-trace
"Given a stack trace frame, trim class and file to the rightmost 24
chars so they make a nice, neat table."
[[c f file line]]
[(symbol (ellipsis (-> (name c)
(demunge)
(str/replace #"--[0-9]{1,}" ""))
24))
f
(ellipsis file 24)
line])
(defn- install-reveal-extras
"Returns a Reveal view object that tracks each tap>'d value and
displays its metadata and class type, and its value in a table.
In order for this to take effect, this function needs to be
called and its result sent to Reveal, after Reveal is up and
running. This dev.clj file achieves this by executing the
following code when starting Reveal:
(future (Thread/sleep 6000)
(tap> (install-reveal-extras)))
The six second delay should be enough for Reveal to initialize
and display its initial view."
[]
(try
(let [last-tap (atom nil)
rx-stream-as-is (requiring-resolve 'vlaaad.reveal.ext/stream-as-is)
rx-obs-view @(requiring-resolve 'vlaaad.reveal.ext/observable-view)
rx-value-view @(requiring-resolve 'vlaaad.reveal.ext/value-view)
rx-table-view @(requiring-resolve 'vlaaad.reveal.ext/table-view)
rx-as (requiring-resolve 'vlaaad.reveal.ext/as)
rx-raw-string (requiring-resolve 'vlaaad.reveal.ext/raw-string)]
(add-tap #(reset! last-tap %))
(rx-stream-as-is
(rx-as
{:fx/type rx-obs-view
:ref last-tap
:fn (fn [x]
(let [x' (if (var? x) (deref x) x) ; get Var's value
c (class x') ; class of underlying value
m (meta x) ; original metadata
m' (when (var? x) (meta x')) ; underlying Var metadata (if any)
[ex-m ex-d ex-t]
(when (instance? Throwable x')
[(ex-message x') (ex-data x') (-> x' (Throwable->map) :trace)])
;; if the underlying value is a function
;; and it has a docstring, use that; if
;; the underlying value is a namespace,
;; run ns-publics and display that map:
x' (cond
(and (fn? x') (or (:doc m) (:doc m')))
(or (:doc m) (:doc m'))
(= clojure.lang.Namespace c)
(ns-publics x')
ex-t ; show stack trace if present
(mapv clean-trace ex-t)
:else
x')]
{:fx/type :v-box
:children
;; in the top box, display metadata
[{:fx/type rx-value-view
:v-box/vgrow :always
:value (cond-> (assoc m :_class c)
m'
(assoc :_meta m')
ex-m
(assoc :_message ex-m)
ex-d
(assoc :_data ex-d))}
(cond
;; display a string in raw form for easier reading:
(string? x')
{:fx/type rx-value-view
:v-box/vgrow :always
:value (rx-stream-as-is (rx-as x' (rx-raw-string x' {:fill :string})))}
;; automatically display URLs using the internal browser:
(instance? java.net.URL x')
{:fx/type :web-view
:url (str x')}
;; else display simple values as a single item in a table:
(or (nil? x') (not (seqable? x')))
{:fx/type rx-table-view
:items [x']
:v-box/vgrow :always
:columns [{:fn identity :header 'value}
{:fn str :header 'string}]}
:else ; display the value in a reasonable table form:
(let [head (first x')]
{:fx/type rx-table-view
:items x'
:v-box/vgrow :always
:columns (cond
(map? head) (for [k (keys head)] {:header k :fn #(get % k)})
(map-entry? head) [{:header 'key :fn key} {:header 'val :fn val}]
(indexed? head) (for [i (range (bounded-count 1024 head))] {:header i :fn #(nth % i)})
:else [{:header 'item :fn identity}])}))]}))}
(rx-raw-string "right-click > view" {:fill :object}))))
(catch Throwable t
(println "Unable to install Reveal extras!")
(println (ex-message t)))))
;; start
(try
(future
(do
(Thread/sleep 5000)
(tap> (install-reveal-extras))))
(catch Exception _exc))
|
[
{
"context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 33,
"score": 0.9106675982475281,
"start": 30,
"tag": "NAME",
"value": "Net"
},
{
"context": "roup-by, and pig/cogroup.\n\nSee https://github.com/Netflix/PigPen/wiki/Folding-Data\n\"\n (:refer-clojure :exc",
"end": 765,
"score": 0.9498234987258911,
"start": 758,
"tag": "USERNAME",
"value": "Netflix"
}
] |
pigpen-core/src/main/clojure/pigpen/fold.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.fold
"Fold operations for use with pig/fold, pig/group-by, and pig/cogroup.
See https://github.com/Netflix/PigPen/wiki/Folding-Data
"
(:refer-clojure :exclude [vec map mapcat filter remove distinct keep take first last sort sort-by juxt count min min-key max max-key])
(:require [clojure.set]
[pigpen.join :refer [fold-fn*]]
[pigpen.extensions.core :refer [zipv]]))
(defn fold-fn
"Creates a pre-defined fold operation. Can be used with cogroup and group-by
to aggregate large groupings in parallel. See pigpen.core/fold for usage of
reducef and combinef.
Example:
(def count
(pig/fold-fn + (fn [acc _] (inc acc))))
(def sum
(pig/fold-fn +))
(defn sum-by [f]
(pig/fold-fn + (fn [acc value] (+ acc (f value)))))
"
{:added "0.2.0"}
;; TODO investigate support for threading folds into this
([reducef] (fold-fn identity reducef reducef identity))
([combinef reducef] (fold-fn identity combinef reducef identity))
([combinef reducef post] (fold-fn identity combinef reducef post))
([pre combinef reducef post]
(fold-fn* pre combinef reducef post)))
;; TODO interop
;; TODO add assertions that folds are folds
(defn ^:private seq-fold? [fold]
(and
(-> fold :combinef meta :seq)
(-> fold :reducef meta :seq)))
(defn ^:private comp-pre
[f {:keys [pre combinef reducef post] :as fold}]
(assert (seq-fold? fold) (str "Operator must be used before aggregation."))
(fold-fn (comp f pre)
combinef
reducef
post))
(defn ^:private comp-fold
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
(comp f combinef)
(comp f reducef)
post))
(defn ^:private comp-fold-new
[{:keys [pre] :as fold} {:keys [combinef reducef post]}]
(fold-fn pre
combinef
reducef
post))
(defn ^:private comp-post
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
combinef
reducef
(comp f post)))
(defn vec
"Returns all values as a vector. This is the default fold operation if none
other is specified.
Example:
(fold/vec)
(->> (fold/vec)
(fold/take 5))
"
{:added "0.2.0"}
[]
(fold-fn ^:seq (fn
([] [])
([l r] (clojure.core/vec (concat l r))))
^:seq (fn [acc val] (conj acc val))))
(defn preprocess
"Takes a a clojure seq function, like map or filter, and returns a fold
preprocess function. The function must take two params: a function and a seq.
Example:
(def map (preprocess clojure.core/map))
(pig/fold (map :foo))
"
{:added "0.2.0"}
[f']
(fn
([f]
(comp-pre (partial f' f) (vec)))
([f fold]
(comp-pre (partial f' f) fold))))
(defmacro ^:private def-preprocess
""
[name fn]
`(def ~(with-meta name {:arglists ''([f] [f fold])
:added "0.2.0"})
~(str "Pre-processes data for a fold operation. Same as " fn ".")
(preprocess ~fn)))
(def-preprocess map clojure.core/map)
(def-preprocess mapcat clojure.core/mapcat)
(def-preprocess filter clojure.core/filter)
(def-preprocess remove clojure.core/remove)
(def-preprocess keep clojure.core/keep)
(defn distinct
"Returns the distinct set of values.
Example:
(fold/distinct)
(->> (fold/map :foo)
(fold/keep identity)
(fold/distinct))
"
{:added "0.2.0"}
([]
(fold-fn clojure.set/union conj))
([fold]
(comp-fold-new fold (distinct))))
(defn take
"Returns a sequence of the first n items in coll. This is a post-reduce
operation, meaning that it can only be applied after a fold operation that
produces a sequence.
Example:
(->>
(fold/sort)
(fold/take 40))
"
{:added "0.2.0"}
([n] (take n (vec)))
([n fold]
(comp-fold (partial clojure.core/take n) fold)))
(defn first
"Returns the first output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/first)
(->> (fold/map :foo)
(fold/sort)
(fold/first))
See also: pigpen.fold/last, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (first (vec)))
([fold]
(->> fold
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/first))))
(defn last
"Returns the last output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/last)
(->> (fold/map :foo)
(fold/sort)
(fold/last))
See also: pigpen.fold/first, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (last (vec)))
([fold]
(->> fold
(comp-fold reverse)
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/last))))
(defn sort
"Sorts the data. This sorts the data after every element, so it's best to use
with take, which also limits the data after every value. If a comparator is not
specified, clojure.core/compare is used.
Example:
(fold/sort)
(->>
(fold/sort)
(fold/take 40))
(->>
(fold/sort >)
(fold/take 40))
See also: pigpen.fold/sort-by, pigpen.fold/top
"
{:added "0.2.0"}
([] (sort compare (vec)))
([fold] (sort compare fold))
([c fold]
(comp-fold (partial clojure.core/sort c) fold)))
(defn sort-by
"Sorts the data by (keyfn value). This sorts the data after every element, so
it's best to use with take, which also limits the data after every value. If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/sort-by :foo)
(->> (vec)
(fold/sort-by :foo)
(fold/take 40))
(->> (vec)
(fold/sort-by :foo >)
(fold/take 40))
See also: pigpen.fold/sort, pigpen.fold/top-by
"
{:added "0.2.0"}
([keyfn] (sort-by keyfn compare (vec)))
([keyfn fold] (sort-by keyfn compare fold))
([keyfn c fold]
(comp-fold (partial clojure.core/sort-by keyfn c) fold)))
(defn juxt
"Applies multiple fold fns to the same data. Produces a vector of results.
Example:
(fold/juxt (fold/count) (fold/sum) (fold/avg))
"
{:added "0.2.0"}
[& folds]
(fold-fn
; pre
(fn [vals]
(for [v vals]
(zipv [{:keys [pre]} folds]
(pre [v]))))
; combine
(fn
([]
(zipv [{:keys [combinef]} folds]
(combinef)))
([l r]
(zipv [{:keys [combinef]} folds
l' l
r' r]
(combinef l' r'))))
; reduce
(fn [acc val]
(zipv [{:keys [reducef]} folds
a' acc
v' val]
(reduce reducef a' v')))
; post
(fn [vals]
(zipv [{:keys [post]} folds
v' vals]
(post v')))))
(defn count
"Counts the values, including nils. Optionally takes another fold operation
to compose.
Example:
(fold/count)
(->> (fold/keep identity) (fold/count)) ; count non-nils
(->> (fold/filter #(< 0 %)) (fold/count)) ; count positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/count))
See also: pigpen.fold/sum, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn + (fn [acc _] (inc acc))))
([fold]
(comp-fold-new fold (count))))
(defn sum
"Sums the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/sum)
(->> (fold/map :foo) (fold/sum)) ; sum the foo's
(->> (fold/keep identity) (fold/sum)) ; sum non-nils
(->> (fold/filter #(< 0 %)) (fold/sum)) ; sum positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/sum))
See also: pigpen.fold/count, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn +))
([fold]
(comp-fold-new fold (sum))))
(defn avg
"Average the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/avg)
(->> (fold/map :foo) (fold/avg)) ; average the foo's
(->> (fold/keep identity) (fold/avg)) ; avg non-nils
(->> (fold/filter #(< 0 %)) (fold/avg)) ; avg positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/avg))
See also: pigpen.fold/count, pigpen.fold/sum
"
{:added "0.2.0"}
([]
(fold-fn (fn
([] [0 0])
([l r]
(mapv + l r)))
(fn [[s c] val]
[(+ s val) (inc c)])
(fn [[s c]]
(when (pos? c)
(/ s c)))))
([fold]
(comp-fold-new fold (avg))))
(defn top
"Returns the top n items in the collection. If a comparator is not specified,
clojure.core/compare is used.
Example:
(fold/top 40)
(fold/top > 40)
See also: pigpen.fold/top-by
"
{:added "0.2.0"}
([n] (top compare n))
([comp n]
(->> (vec)
(sort comp)
(take n))))
(defn top-by
"Returns the top n items in the collection based on (keyfn value). If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/top-by :foo 40)
(fold/top-by :foo > 40)
See also: pigpen.fold/top
"
{:added "0.2.0"}
([keyfn n] (top-by keyfn compare n))
([keyfn comp n]
(->> (vec)
(sort-by keyfn comp)
(take n))))
(defn ^:private min*
"Returns the best item from the collection. Optionally specify a comparator."
[comp fold]
{:pre [(instance? java.util.Comparator comp)]}
(comp-fold-new fold
(fold-fn (fn
([] ::nil)
([l r]
(cond
(= ::nil l) r
(= ::nil r) l
(< (comp l r) 0) l
:else r))))))
(defn ^:private compare-by
([keyfn] (compare-by keyfn compare))
([keyfn comp] #(comp (keyfn %1) (keyfn %2))))
(defn min
"Return the minimum (first) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/min)
(fold/min >)
(->>
(fold/map :foo)
(fold/min >))
See also: pigpen.fold/min-key, pigpen.fold/max, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* compare (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* fold (vec))
(min* compare fold)))
([comp fold] (min* comp fold)))
(defn min-key
"Return the minimum (first) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/min-key :foo)
(fold/min-key :foo >)
See also: pigpen.fold/min, pigpen.fold/max-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (min-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(min-key keyfn fold (vec))
(min-key keyfn compare fold)))
([keyfn comp fold] (min* (compare-by keyfn comp) fold)))
(defn max
"Return the maximum (last) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/max)
(fold/max >)
(->>
(fold/map :foo)
(fold/max >))
See also: pigpen.fold/max-key, pigpen.fold/min, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* (clojure.core/comp - compare) (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* (clojure.core/comp - fold) (vec))
(min* (clojure.core/comp - compare) fold)))
([comp fold] (min* (clojure.core/comp - comp) fold)))
(defn max-key
"Return the maximum (last) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/max-key :foo)
(fold/max-key :foo >)
See also: pigpen.fold/max, pigpen.fold/min-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (max-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(max-key keyfn fold (vec))
(max-key keyfn compare fold)))
([keyfn comp fold] (min* (clojure.core/comp - (compare-by keyfn comp)) fold)))
|
22218
|
;;
;;
;; 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.fold
"Fold operations for use with pig/fold, pig/group-by, and pig/cogroup.
See https://github.com/Netflix/PigPen/wiki/Folding-Data
"
(:refer-clojure :exclude [vec map mapcat filter remove distinct keep take first last sort sort-by juxt count min min-key max max-key])
(:require [clojure.set]
[pigpen.join :refer [fold-fn*]]
[pigpen.extensions.core :refer [zipv]]))
(defn fold-fn
"Creates a pre-defined fold operation. Can be used with cogroup and group-by
to aggregate large groupings in parallel. See pigpen.core/fold for usage of
reducef and combinef.
Example:
(def count
(pig/fold-fn + (fn [acc _] (inc acc))))
(def sum
(pig/fold-fn +))
(defn sum-by [f]
(pig/fold-fn + (fn [acc value] (+ acc (f value)))))
"
{:added "0.2.0"}
;; TODO investigate support for threading folds into this
([reducef] (fold-fn identity reducef reducef identity))
([combinef reducef] (fold-fn identity combinef reducef identity))
([combinef reducef post] (fold-fn identity combinef reducef post))
([pre combinef reducef post]
(fold-fn* pre combinef reducef post)))
;; TODO interop
;; TODO add assertions that folds are folds
(defn ^:private seq-fold? [fold]
(and
(-> fold :combinef meta :seq)
(-> fold :reducef meta :seq)))
(defn ^:private comp-pre
[f {:keys [pre combinef reducef post] :as fold}]
(assert (seq-fold? fold) (str "Operator must be used before aggregation."))
(fold-fn (comp f pre)
combinef
reducef
post))
(defn ^:private comp-fold
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
(comp f combinef)
(comp f reducef)
post))
(defn ^:private comp-fold-new
[{:keys [pre] :as fold} {:keys [combinef reducef post]}]
(fold-fn pre
combinef
reducef
post))
(defn ^:private comp-post
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
combinef
reducef
(comp f post)))
(defn vec
"Returns all values as a vector. This is the default fold operation if none
other is specified.
Example:
(fold/vec)
(->> (fold/vec)
(fold/take 5))
"
{:added "0.2.0"}
[]
(fold-fn ^:seq (fn
([] [])
([l r] (clojure.core/vec (concat l r))))
^:seq (fn [acc val] (conj acc val))))
(defn preprocess
"Takes a a clojure seq function, like map or filter, and returns a fold
preprocess function. The function must take two params: a function and a seq.
Example:
(def map (preprocess clojure.core/map))
(pig/fold (map :foo))
"
{:added "0.2.0"}
[f']
(fn
([f]
(comp-pre (partial f' f) (vec)))
([f fold]
(comp-pre (partial f' f) fold))))
(defmacro ^:private def-preprocess
""
[name fn]
`(def ~(with-meta name {:arglists ''([f] [f fold])
:added "0.2.0"})
~(str "Pre-processes data for a fold operation. Same as " fn ".")
(preprocess ~fn)))
(def-preprocess map clojure.core/map)
(def-preprocess mapcat clojure.core/mapcat)
(def-preprocess filter clojure.core/filter)
(def-preprocess remove clojure.core/remove)
(def-preprocess keep clojure.core/keep)
(defn distinct
"Returns the distinct set of values.
Example:
(fold/distinct)
(->> (fold/map :foo)
(fold/keep identity)
(fold/distinct))
"
{:added "0.2.0"}
([]
(fold-fn clojure.set/union conj))
([fold]
(comp-fold-new fold (distinct))))
(defn take
"Returns a sequence of the first n items in coll. This is a post-reduce
operation, meaning that it can only be applied after a fold operation that
produces a sequence.
Example:
(->>
(fold/sort)
(fold/take 40))
"
{:added "0.2.0"}
([n] (take n (vec)))
([n fold]
(comp-fold (partial clojure.core/take n) fold)))
(defn first
"Returns the first output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/first)
(->> (fold/map :foo)
(fold/sort)
(fold/first))
See also: pigpen.fold/last, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (first (vec)))
([fold]
(->> fold
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/first))))
(defn last
"Returns the last output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/last)
(->> (fold/map :foo)
(fold/sort)
(fold/last))
See also: pigpen.fold/first, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (last (vec)))
([fold]
(->> fold
(comp-fold reverse)
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/last))))
(defn sort
"Sorts the data. This sorts the data after every element, so it's best to use
with take, which also limits the data after every value. If a comparator is not
specified, clojure.core/compare is used.
Example:
(fold/sort)
(->>
(fold/sort)
(fold/take 40))
(->>
(fold/sort >)
(fold/take 40))
See also: pigpen.fold/sort-by, pigpen.fold/top
"
{:added "0.2.0"}
([] (sort compare (vec)))
([fold] (sort compare fold))
([c fold]
(comp-fold (partial clojure.core/sort c) fold)))
(defn sort-by
"Sorts the data by (keyfn value). This sorts the data after every element, so
it's best to use with take, which also limits the data after every value. If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/sort-by :foo)
(->> (vec)
(fold/sort-by :foo)
(fold/take 40))
(->> (vec)
(fold/sort-by :foo >)
(fold/take 40))
See also: pigpen.fold/sort, pigpen.fold/top-by
"
{:added "0.2.0"}
([keyfn] (sort-by keyfn compare (vec)))
([keyfn fold] (sort-by keyfn compare fold))
([keyfn c fold]
(comp-fold (partial clojure.core/sort-by keyfn c) fold)))
(defn juxt
"Applies multiple fold fns to the same data. Produces a vector of results.
Example:
(fold/juxt (fold/count) (fold/sum) (fold/avg))
"
{:added "0.2.0"}
[& folds]
(fold-fn
; pre
(fn [vals]
(for [v vals]
(zipv [{:keys [pre]} folds]
(pre [v]))))
; combine
(fn
([]
(zipv [{:keys [combinef]} folds]
(combinef)))
([l r]
(zipv [{:keys [combinef]} folds
l' l
r' r]
(combinef l' r'))))
; reduce
(fn [acc val]
(zipv [{:keys [reducef]} folds
a' acc
v' val]
(reduce reducef a' v')))
; post
(fn [vals]
(zipv [{:keys [post]} folds
v' vals]
(post v')))))
(defn count
"Counts the values, including nils. Optionally takes another fold operation
to compose.
Example:
(fold/count)
(->> (fold/keep identity) (fold/count)) ; count non-nils
(->> (fold/filter #(< 0 %)) (fold/count)) ; count positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/count))
See also: pigpen.fold/sum, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn + (fn [acc _] (inc acc))))
([fold]
(comp-fold-new fold (count))))
(defn sum
"Sums the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/sum)
(->> (fold/map :foo) (fold/sum)) ; sum the foo's
(->> (fold/keep identity) (fold/sum)) ; sum non-nils
(->> (fold/filter #(< 0 %)) (fold/sum)) ; sum positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/sum))
See also: pigpen.fold/count, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn +))
([fold]
(comp-fold-new fold (sum))))
(defn avg
"Average the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/avg)
(->> (fold/map :foo) (fold/avg)) ; average the foo's
(->> (fold/keep identity) (fold/avg)) ; avg non-nils
(->> (fold/filter #(< 0 %)) (fold/avg)) ; avg positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/avg))
See also: pigpen.fold/count, pigpen.fold/sum
"
{:added "0.2.0"}
([]
(fold-fn (fn
([] [0 0])
([l r]
(mapv + l r)))
(fn [[s c] val]
[(+ s val) (inc c)])
(fn [[s c]]
(when (pos? c)
(/ s c)))))
([fold]
(comp-fold-new fold (avg))))
(defn top
"Returns the top n items in the collection. If a comparator is not specified,
clojure.core/compare is used.
Example:
(fold/top 40)
(fold/top > 40)
See also: pigpen.fold/top-by
"
{:added "0.2.0"}
([n] (top compare n))
([comp n]
(->> (vec)
(sort comp)
(take n))))
(defn top-by
"Returns the top n items in the collection based on (keyfn value). If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/top-by :foo 40)
(fold/top-by :foo > 40)
See also: pigpen.fold/top
"
{:added "0.2.0"}
([keyfn n] (top-by keyfn compare n))
([keyfn comp n]
(->> (vec)
(sort-by keyfn comp)
(take n))))
(defn ^:private min*
"Returns the best item from the collection. Optionally specify a comparator."
[comp fold]
{:pre [(instance? java.util.Comparator comp)]}
(comp-fold-new fold
(fold-fn (fn
([] ::nil)
([l r]
(cond
(= ::nil l) r
(= ::nil r) l
(< (comp l r) 0) l
:else r))))))
(defn ^:private compare-by
([keyfn] (compare-by keyfn compare))
([keyfn comp] #(comp (keyfn %1) (keyfn %2))))
(defn min
"Return the minimum (first) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/min)
(fold/min >)
(->>
(fold/map :foo)
(fold/min >))
See also: pigpen.fold/min-key, pigpen.fold/max, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* compare (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* fold (vec))
(min* compare fold)))
([comp fold] (min* comp fold)))
(defn min-key
"Return the minimum (first) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/min-key :foo)
(fold/min-key :foo >)
See also: pigpen.fold/min, pigpen.fold/max-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (min-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(min-key keyfn fold (vec))
(min-key keyfn compare fold)))
([keyfn comp fold] (min* (compare-by keyfn comp) fold)))
(defn max
"Return the maximum (last) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/max)
(fold/max >)
(->>
(fold/map :foo)
(fold/max >))
See also: pigpen.fold/max-key, pigpen.fold/min, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* (clojure.core/comp - compare) (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* (clojure.core/comp - fold) (vec))
(min* (clojure.core/comp - compare) fold)))
([comp fold] (min* (clojure.core/comp - comp) fold)))
(defn max-key
"Return the maximum (last) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/max-key :foo)
(fold/max-key :foo >)
See also: pigpen.fold/max, pigpen.fold/min-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (max-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(max-key keyfn fold (vec))
(max-key keyfn compare fold)))
([keyfn comp fold] (min* (clojure.core/comp - (compare-by keyfn comp)) fold)))
| 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.fold
"Fold operations for use with pig/fold, pig/group-by, and pig/cogroup.
See https://github.com/Netflix/PigPen/wiki/Folding-Data
"
(:refer-clojure :exclude [vec map mapcat filter remove distinct keep take first last sort sort-by juxt count min min-key max max-key])
(:require [clojure.set]
[pigpen.join :refer [fold-fn*]]
[pigpen.extensions.core :refer [zipv]]))
(defn fold-fn
"Creates a pre-defined fold operation. Can be used with cogroup and group-by
to aggregate large groupings in parallel. See pigpen.core/fold for usage of
reducef and combinef.
Example:
(def count
(pig/fold-fn + (fn [acc _] (inc acc))))
(def sum
(pig/fold-fn +))
(defn sum-by [f]
(pig/fold-fn + (fn [acc value] (+ acc (f value)))))
"
{:added "0.2.0"}
;; TODO investigate support for threading folds into this
([reducef] (fold-fn identity reducef reducef identity))
([combinef reducef] (fold-fn identity combinef reducef identity))
([combinef reducef post] (fold-fn identity combinef reducef post))
([pre combinef reducef post]
(fold-fn* pre combinef reducef post)))
;; TODO interop
;; TODO add assertions that folds are folds
(defn ^:private seq-fold? [fold]
(and
(-> fold :combinef meta :seq)
(-> fold :reducef meta :seq)))
(defn ^:private comp-pre
[f {:keys [pre combinef reducef post] :as fold}]
(assert (seq-fold? fold) (str "Operator must be used before aggregation."))
(fold-fn (comp f pre)
combinef
reducef
post))
(defn ^:private comp-fold
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
(comp f combinef)
(comp f reducef)
post))
(defn ^:private comp-fold-new
[{:keys [pre] :as fold} {:keys [combinef reducef post]}]
(fold-fn pre
combinef
reducef
post))
(defn ^:private comp-post
[f {:keys [pre combinef reducef post]}]
(fold-fn pre
combinef
reducef
(comp f post)))
(defn vec
"Returns all values as a vector. This is the default fold operation if none
other is specified.
Example:
(fold/vec)
(->> (fold/vec)
(fold/take 5))
"
{:added "0.2.0"}
[]
(fold-fn ^:seq (fn
([] [])
([l r] (clojure.core/vec (concat l r))))
^:seq (fn [acc val] (conj acc val))))
(defn preprocess
"Takes a a clojure seq function, like map or filter, and returns a fold
preprocess function. The function must take two params: a function and a seq.
Example:
(def map (preprocess clojure.core/map))
(pig/fold (map :foo))
"
{:added "0.2.0"}
[f']
(fn
([f]
(comp-pre (partial f' f) (vec)))
([f fold]
(comp-pre (partial f' f) fold))))
(defmacro ^:private def-preprocess
""
[name fn]
`(def ~(with-meta name {:arglists ''([f] [f fold])
:added "0.2.0"})
~(str "Pre-processes data for a fold operation. Same as " fn ".")
(preprocess ~fn)))
(def-preprocess map clojure.core/map)
(def-preprocess mapcat clojure.core/mapcat)
(def-preprocess filter clojure.core/filter)
(def-preprocess remove clojure.core/remove)
(def-preprocess keep clojure.core/keep)
(defn distinct
"Returns the distinct set of values.
Example:
(fold/distinct)
(->> (fold/map :foo)
(fold/keep identity)
(fold/distinct))
"
{:added "0.2.0"}
([]
(fold-fn clojure.set/union conj))
([fold]
(comp-fold-new fold (distinct))))
(defn take
"Returns a sequence of the first n items in coll. This is a post-reduce
operation, meaning that it can only be applied after a fold operation that
produces a sequence.
Example:
(->>
(fold/sort)
(fold/take 40))
"
{:added "0.2.0"}
([n] (take n (vec)))
([n fold]
(comp-fold (partial clojure.core/take n) fold)))
(defn first
"Returns the first output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/first)
(->> (fold/map :foo)
(fold/sort)
(fold/first))
See also: pigpen.fold/last, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (first (vec)))
([fold]
(->> fold
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/first))))
(defn last
"Returns the last output value. This is a post-reduce operation, meaning that
it can only be applied after a fold operation that produces a sequence.
Example:
(fold/last)
(->> (fold/map :foo)
(fold/sort)
(fold/last))
See also: pigpen.fold/first, pigpen.fold/min, pigpen.fold/max
"
{:added "0.2.0"}
([] (last (vec)))
([fold]
(->> fold
(comp-fold reverse)
(comp-fold (partial clojure.core/take 1))
(comp-post clojure.core/last))))
(defn sort
"Sorts the data. This sorts the data after every element, so it's best to use
with take, which also limits the data after every value. If a comparator is not
specified, clojure.core/compare is used.
Example:
(fold/sort)
(->>
(fold/sort)
(fold/take 40))
(->>
(fold/sort >)
(fold/take 40))
See also: pigpen.fold/sort-by, pigpen.fold/top
"
{:added "0.2.0"}
([] (sort compare (vec)))
([fold] (sort compare fold))
([c fold]
(comp-fold (partial clojure.core/sort c) fold)))
(defn sort-by
"Sorts the data by (keyfn value). This sorts the data after every element, so
it's best to use with take, which also limits the data after every value. If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/sort-by :foo)
(->> (vec)
(fold/sort-by :foo)
(fold/take 40))
(->> (vec)
(fold/sort-by :foo >)
(fold/take 40))
See also: pigpen.fold/sort, pigpen.fold/top-by
"
{:added "0.2.0"}
([keyfn] (sort-by keyfn compare (vec)))
([keyfn fold] (sort-by keyfn compare fold))
([keyfn c fold]
(comp-fold (partial clojure.core/sort-by keyfn c) fold)))
(defn juxt
"Applies multiple fold fns to the same data. Produces a vector of results.
Example:
(fold/juxt (fold/count) (fold/sum) (fold/avg))
"
{:added "0.2.0"}
[& folds]
(fold-fn
; pre
(fn [vals]
(for [v vals]
(zipv [{:keys [pre]} folds]
(pre [v]))))
; combine
(fn
([]
(zipv [{:keys [combinef]} folds]
(combinef)))
([l r]
(zipv [{:keys [combinef]} folds
l' l
r' r]
(combinef l' r'))))
; reduce
(fn [acc val]
(zipv [{:keys [reducef]} folds
a' acc
v' val]
(reduce reducef a' v')))
; post
(fn [vals]
(zipv [{:keys [post]} folds
v' vals]
(post v')))))
(defn count
"Counts the values, including nils. Optionally takes another fold operation
to compose.
Example:
(fold/count)
(->> (fold/keep identity) (fold/count)) ; count non-nils
(->> (fold/filter #(< 0 %)) (fold/count)) ; count positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/count))
See also: pigpen.fold/sum, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn + (fn [acc _] (inc acc))))
([fold]
(comp-fold-new fold (count))))
(defn sum
"Sums the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/sum)
(->> (fold/map :foo) (fold/sum)) ; sum the foo's
(->> (fold/keep identity) (fold/sum)) ; sum non-nils
(->> (fold/filter #(< 0 %)) (fold/sum)) ; sum positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/sum))
See also: pigpen.fold/count, pigpen.fold/avg
"
{:added "0.2.0"}
([]
(fold-fn +))
([fold]
(comp-fold-new fold (sum))))
(defn avg
"Average the values. All values must be numeric. Optionally takes another
fold operation to compose.
Example:
(fold/avg)
(->> (fold/map :foo) (fold/avg)) ; average the foo's
(->> (fold/keep identity) (fold/avg)) ; avg non-nils
(->> (fold/filter #(< 0 %)) (fold/avg)) ; avg positive numbers
(->>
(fold/map :foo)
(fold/keep identity)
(fold/avg))
See also: pigpen.fold/count, pigpen.fold/sum
"
{:added "0.2.0"}
([]
(fold-fn (fn
([] [0 0])
([l r]
(mapv + l r)))
(fn [[s c] val]
[(+ s val) (inc c)])
(fn [[s c]]
(when (pos? c)
(/ s c)))))
([fold]
(comp-fold-new fold (avg))))
(defn top
"Returns the top n items in the collection. If a comparator is not specified,
clojure.core/compare is used.
Example:
(fold/top 40)
(fold/top > 40)
See also: pigpen.fold/top-by
"
{:added "0.2.0"}
([n] (top compare n))
([comp n]
(->> (vec)
(sort comp)
(take n))))
(defn top-by
"Returns the top n items in the collection based on (keyfn value). If a
comparator is not specified, clojure.core/compare is used.
Example:
(fold/top-by :foo 40)
(fold/top-by :foo > 40)
See also: pigpen.fold/top
"
{:added "0.2.0"}
([keyfn n] (top-by keyfn compare n))
([keyfn comp n]
(->> (vec)
(sort-by keyfn comp)
(take n))))
(defn ^:private min*
"Returns the best item from the collection. Optionally specify a comparator."
[comp fold]
{:pre [(instance? java.util.Comparator comp)]}
(comp-fold-new fold
(fold-fn (fn
([] ::nil)
([l r]
(cond
(= ::nil l) r
(= ::nil r) l
(< (comp l r) 0) l
:else r))))))
(defn ^:private compare-by
([keyfn] (compare-by keyfn compare))
([keyfn comp] #(comp (keyfn %1) (keyfn %2))))
(defn min
"Return the minimum (first) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/min)
(fold/min >)
(->>
(fold/map :foo)
(fold/min >))
See also: pigpen.fold/min-key, pigpen.fold/max, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* compare (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* fold (vec))
(min* compare fold)))
([comp fold] (min* comp fold)))
(defn min-key
"Return the minimum (first) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/min-key :foo)
(fold/min-key :foo >)
See also: pigpen.fold/min, pigpen.fold/max-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (min-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(min-key keyfn fold (vec))
(min-key keyfn compare fold)))
([keyfn comp fold] (min* (compare-by keyfn comp) fold)))
(defn max
"Return the maximum (last) value of the collection. If a comparator is not
specified, clojure.core/compare is used. Optionally takes another fold
operation to compose.
Example:
(fold/max)
(fold/max >)
(->>
(fold/map :foo)
(fold/max >))
See also: pigpen.fold/max-key, pigpen.fold/min, pigpen.fold/top
"
{:arglists '([] [fold] [comp] [comp fold])
:added "0.2.0"}
([] (min* (clojure.core/comp - compare) (vec)))
([fold]
(if (instance? java.util.Comparator fold)
(min* (clojure.core/comp - fold) (vec))
(min* (clojure.core/comp - compare) fold)))
([comp fold] (min* (clojure.core/comp - comp) fold)))
(defn max-key
"Return the maximum (last) value of the collection based on (keyfn value).
If a comparator is not specified, clojure.core/compare is used. Optionally takes
another fold operation to compose.
Example:
(fold/max-key :foo)
(fold/max-key :foo >)
See also: pigpen.fold/max, pigpen.fold/min-key, pigpen.fold/top-by
"
{:arglists '([keyfn] [keyfn fold] [keyfn comp] [keyfn comp fold])
:added "0.2.0"}
([keyfn] (max-key keyfn compare (vec)))
([keyfn fold]
(if (instance? java.util.Comparator fold)
(max-key keyfn fold (vec))
(max-key keyfn compare fold)))
([keyfn comp fold] (min* (clojure.core/comp - (compare-by keyfn comp)) fold)))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-03\"\n ",
"end": 97,
"score": 0.6720846891403198,
"start": 88,
"tag": "EMAIL",
"value": "wahpenayo"
},
{
"context": "ath* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-03\"\n :date \"",
"end": 106,
"score": 0.6985073089599609,
"start": 102,
"tag": "EMAIL",
"value": "mail"
},
{
"context": "rn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-03\"\n :date \"2017-11-",
"end": 114,
"score": 0.7114116549491882,
"start": 111,
"tag": "EMAIL",
"value": "com"
}
] |
src/scripts/clojure/taigabench/scripts/ontime/distinct.clj
|
wahpenayo/taigabench
| 0 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:since "2016-11-03"
:date "2017-11-21"
:doc "Determine possible values for enums in
public airline ontime data benchmark:
https://www.r-bloggers.com/benchmarking-random-forest-implementations/
http://stat-computing.org/dataexpo/2009/" }
taigabench.scripts.ontime.distinct
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.api :as z]
[taiga.api :as taiga]
[taigabench.ontime.data :as data]))
;; clj48g src\scripts\clojure\taigabench\scripts\ontime\distinct.clj > distinct.txt
;;----------------------------------------------------------------
(defn- split [^String s] (s/split s #"\,"))
(defn- record [header tokens]
(let [r (zipmap header tokens)]
{:origin (:origin r)
:dest (:dest r)
:uniquecarrier (:uniquecarrier r)}))
(defn- read-csv [year]
(z/seconds
(print-str year)
(with-open [r (z/reader (data/raw-data-file year))]
(let [lines (line-seq r)
header (mapv #(keyword (s/lower-case %))
(split (first lines)))
_(pp/pprint header)
records (mapv #(record header (split %)) (rest lines))]
(println (count records))
(pp/pprint (first records))
records))))
;;----------------------------------------------------------------
(let [data (z/seconds
"read train"
(z/mapcat
read-csv
["2003" "2004" "2005" "2006" "2007" "2007" "2008"]))
_(pp/pprint (first data))
carriers (z/sort (z/distinct :uniquecarrier data))
airports (z/sort (z/union (z/distinct :origin data)
(z/distinct :dest data)))]
(pp/pprint {:records (z/count data)
:carriers (z/count carriers)
:airports (z/count airports)})
(pp/pprint carriers)
(pp/pprint airports))
;;----------------------------------------------------------------
|
106064
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL> at g<EMAIL> dot <EMAIL>"
:since "2016-11-03"
:date "2017-11-21"
:doc "Determine possible values for enums in
public airline ontime data benchmark:
https://www.r-bloggers.com/benchmarking-random-forest-implementations/
http://stat-computing.org/dataexpo/2009/" }
taigabench.scripts.ontime.distinct
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.api :as z]
[taiga.api :as taiga]
[taigabench.ontime.data :as data]))
;; clj48g src\scripts\clojure\taigabench\scripts\ontime\distinct.clj > distinct.txt
;;----------------------------------------------------------------
(defn- split [^String s] (s/split s #"\,"))
(defn- record [header tokens]
(let [r (zipmap header tokens)]
{:origin (:origin r)
:dest (:dest r)
:uniquecarrier (:uniquecarrier r)}))
(defn- read-csv [year]
(z/seconds
(print-str year)
(with-open [r (z/reader (data/raw-data-file year))]
(let [lines (line-seq r)
header (mapv #(keyword (s/lower-case %))
(split (first lines)))
_(pp/pprint header)
records (mapv #(record header (split %)) (rest lines))]
(println (count records))
(pp/pprint (first records))
records))))
;;----------------------------------------------------------------
(let [data (z/seconds
"read train"
(z/mapcat
read-csv
["2003" "2004" "2005" "2006" "2007" "2007" "2008"]))
_(pp/pprint (first data))
carriers (z/sort (z/distinct :uniquecarrier data))
airports (z/sort (z/union (z/distinct :origin data)
(z/distinct :dest data)))]
(pp/pprint {:records (z/count data)
:carriers (z/count carriers)
:airports (z/count airports)})
(pp/pprint carriers)
(pp/pprint airports))
;;----------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI at gPI:EMAIL:<EMAIL>END_PI dot PI:EMAIL:<EMAIL>END_PI"
:since "2016-11-03"
:date "2017-11-21"
:doc "Determine possible values for enums in
public airline ontime data benchmark:
https://www.r-bloggers.com/benchmarking-random-forest-implementations/
http://stat-computing.org/dataexpo/2009/" }
taigabench.scripts.ontime.distinct
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.api :as z]
[taiga.api :as taiga]
[taigabench.ontime.data :as data]))
;; clj48g src\scripts\clojure\taigabench\scripts\ontime\distinct.clj > distinct.txt
;;----------------------------------------------------------------
(defn- split [^String s] (s/split s #"\,"))
(defn- record [header tokens]
(let [r (zipmap header tokens)]
{:origin (:origin r)
:dest (:dest r)
:uniquecarrier (:uniquecarrier r)}))
(defn- read-csv [year]
(z/seconds
(print-str year)
(with-open [r (z/reader (data/raw-data-file year))]
(let [lines (line-seq r)
header (mapv #(keyword (s/lower-case %))
(split (first lines)))
_(pp/pprint header)
records (mapv #(record header (split %)) (rest lines))]
(println (count records))
(pp/pprint (first records))
records))))
;;----------------------------------------------------------------
(let [data (z/seconds
"read train"
(z/mapcat
read-csv
["2003" "2004" "2005" "2006" "2007" "2007" "2008"]))
_(pp/pprint (first data))
carriers (z/sort (z/distinct :uniquecarrier data))
airports (z/sort (z/union (z/distinct :origin data)
(z/distinct :dest data)))]
(pp/pprint {:records (z/count data)
:carriers (z/count carriers)
:airports (z/count airports)})
(pp/pprint carriers)
(pp/pprint airports))
;;----------------------------------------------------------------
|
[
{
"context": "ta structure with ease\"\n :url \"http://github.com/rm-hull/table\"\n :license {\n :name \"The MIT License\"\n ",
"end": 145,
"score": 0.9996429085731506,
"start": 138,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "-ns table.core}\n :dependencies [ ]\n :scm {:url \"[email protected]:rm-hull/table.git\"}\n :source-paths [\"src\"]\n :ja",
"end": 333,
"score": 0.9993239641189575,
"start": 319,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "\n :dependencies [ ]\n :scm {:url \"[email protected]:rm-hull/table.git\"}\n :source-paths [\"src\"]\n :jar-exclus",
"end": 341,
"score": 0.9995333552360535,
"start": 334,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "path \"doc/api\"\n :source-uri \"http://github.com/rm-hull/table/blob/master/{filepath}#L{line}\" }\n :min-l",
"end": 519,
"score": 0.9996039271354675,
"start": 512,
"tag": "USERNAME",
"value": "rm-hull"
}
] |
project.clj
|
bbqbaron/table
| 0 |
(defproject rm-hull/table "0.7.0"
:description "Display ascii tables for almost any data structure with ease"
:url "http://github.com/rm-hull/table"
:license {
:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:repl-options {
:init-ns table.core}
:dependencies [ ]
:scm {:url "[email protected]:rm-hull/table.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/table/blob/master/{filepath}#L{line}" }
:min-lein-version "2.7.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.5.7"]
[lein-codox "0.10.3"]
[lein-cloverage "1.0.10"]]
:dependencies [
[org.clojure/clojure "1.9.0"]]}})
|
86339
|
(defproject rm-hull/table "0.7.0"
:description "Display ascii tables for almost any data structure with ease"
:url "http://github.com/rm-hull/table"
:license {
:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:repl-options {
:init-ns table.core}
:dependencies [ ]
:scm {:url "<EMAIL>:rm-hull/table.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/table/blob/master/{filepath}#L{line}" }
:min-lein-version "2.7.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.5.7"]
[lein-codox "0.10.3"]
[lein-cloverage "1.0.10"]]
:dependencies [
[org.clojure/clojure "1.9.0"]]}})
| true |
(defproject rm-hull/table "0.7.0"
:description "Display ascii tables for almost any data structure with ease"
:url "http://github.com/rm-hull/table"
:license {
:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:repl-options {
:init-ns table.core}
:dependencies [ ]
:scm {:url "PI:EMAIL:<EMAIL>END_PI:rm-hull/table.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/table/blob/master/{filepath}#L{line}" }
:min-lein-version "2.7.1"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.5.7"]
[lein-codox "0.10.3"]
[lein-cloverage "1.0.10"]]
:dependencies [
[org.clojure/clojure "1.9.0"]]}})
|
[
{
"context": "\n(ns #^{:author \"al3xandr3 <[email protected]>\"\n :doc \"Cov3, a custo",
"end": 26,
"score": 0.999708354473114,
"start": 17,
"tag": "USERNAME",
"value": "al3xandr3"
},
{
"context": "\n(ns #^{:author \"al3xandr3 <[email protected]>\"\n :doc \"Cov3, a custom crawler\" }\n cov3)\n",
"end": 47,
"score": 0.999923050403595,
"start": 28,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "new instance, borrowed from:\n;; http://github.com/mikitebeka/webdriver-clj/blob/master/webdriver.clj\n(def *dri",
"end": 1193,
"score": 0.9994937777519226,
"start": 1183,
"tag": "USERNAME",
"value": "mikitebeka"
},
{
"context": "(println \"DONE\")))))\n;; (cov3/crawl :ff \"http://al3xandr3.github.com/\" '(\"document.title\" \"(typeof jQ",
"end": 8669,
"score": 0.530510425567627,
"start": 8668,
"tag": "USERNAME",
"value": "3"
}
] |
data/train/clojure/a681fb8487a85a3b55b7433570d5d890573a9ff6cov3.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
(ns #^{:author "al3xandr3 <[email protected]>"
:doc "Cov3, a custom crawler" }
cov3)
(require '[clojure.zip :as zip])
(require '[clojure.xml :as xml])
(require '[clojure.contrib.string :as string])
(require '[clojure.contrib.duck-streams :as stream])
(use 'clojure.set)
(use 'clojure.contrib.zip-filter.xml)
(import '(java.io File))
(import 'java.io.FileWriter)
(import 'java.text.SimpleDateFormat)
(import 'java.util.Date)
(import 'java.util.Calendar)
(import 'java.net.URLDecoder)
(import 'org.openqa.selenium.By)
(import 'org.openqa.selenium.Cookie)
(import 'org.openqa.selenium.Speed)
(import 'org.openqa.selenium.WebDriver)
(import 'org.openqa.selenium.WebElement)
(import 'org.openqa.selenium.htmlunit.HtmlUnitDriver)
(import 'org.openqa.selenium.firefox.FirefoxDriver)
(import 'org.openqa.selenium.ie.InternetExplorerDriver)
(import 'org.openqa.selenium.chrome.ChromeDriver)
(import 'org.openqa.selenium.JavascriptExecutor)
(import 'java.io.FileReader 'au.com.bytecode.opencsv.CSVReader)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; WEBDRIVER API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; *drivers* list and way to create a new instance, borrowed from:
;; http://github.com/mikitebeka/webdriver-clj/blob/master/webdriver.clj
(def *drivers* {
:ff FirefoxDriver
:ie InternetExplorerDriver
:ch ChromeDriver
:hu HtmlUnitDriver})
(defmacro with-browser
"given a variable to place the browser intance and a type of browser
(ff, ie, ch or hu), it creates a webdriver browser instance than
is then available in the body. Closes browser instance at the end"
[browser type & body]
`(let [~browser (.newInstance (*drivers* ~type))]
;; htmlUnit requires to be explicitly enabled for javascript
(if (= ~type :hu)
(.setJavascriptEnabled ~browser true))
~@body
;; htmlUnit does not needs to be closed
(if (not (= ~type :hu))
(.close ~browser))))
;; (macroexpand '(cov3/with-browser b :ff))
;; (cov3/with-browser b :ff)
(defn go
"given a browser instance with some page open, it
browses to a page"
[browser url]
(try
(.get browser url)
(catch Exception e
(println (str url "," e)))))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/"))
(defn js-eval
"given a browser instance with some page open, it
executes javascript code"
[browser code]
(try
(.executeScript browser (str "return " code) (into-array ""))
(catch Exception e
(println (str code "," e))
(str code "," e))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(typeof jQuery !== 'undefined')")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(new Date().getHours())+':'+(new Date().getMinutes())+':'+(new Date().getSeconds())")))
;; note that chrome has bugs, reported here:
;; http://code.google.com/p/selenium/issues/detail?id=430
;; so following does not work yet...
;; (cov3/with-browser b :ch (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
(defn get-protocol
"given a browser instance with some page open, it
returns the url protocol, like 'http'"
[b]
(js-eval b "location.protocol"))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-protocol b)))
(defn get-domain
"given a browser instance with some page open, it
returns the url domain, like al3xandr3.github.com"
[b]
(js-eval b "location.hostname"))
;;(cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-domain b)))
(defn- get-attr
"given a webdrivers html element, it returns
the value of the attr specified"
[elem attr]
"gets an attribute from a webdriver web element"
(.getAttribute elem attr))
(defn get-links-in-domain
"given a browser instance with some page open, it
retuns all of the page's links to the same domain"
[b]
(try
(let [lnks (js-eval b "document.links")]
(if (empty? lnks)
'()
(let [href (map #(get-attr % "href") lnks)
host (str (get-protocol b) "//" (get-domain b))
flnks (map #(if (string/substring? host %) % (str host %)) href)
pound (map #(first (string/split #"\#" %)) flnks)]
pound)))
(catch Exception e
(println (str "get-links-in-domain: " e)))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (first (cov3/get-links-in-domain b))))
(defn read-cookie
[driver name]
(let [coo (.getCookieNamed (.manage driver) name)]
(if (= coo nil)
""
(.getValue coo))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/read-cookie b "_github_ses")))
(defn write-cookie
([b n v] (write-cookie b n v nil "/"))
([b n v d] (write-cookie b n v d "/"))
([b name value date path] (.addCookie (.manage b) (new Cookie name value path date))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/new-cookie b "al" "123" "")))
(defn remove-cookie
"given en executing browser and a cookie name,
it removes that cookie"
[b name]
(.deleteCookieNamed (.manage b) name))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/remove-cookie b "_github_ses")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PAGE VALIDATOR ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate-page
"given a browser and a page, returns a comma separated string
result of the execution of the javascript validation given"
([b u v] (validate-page b u v (fn[b]()) ))
([browser a-url validations post-fn]
(try
(go browser a-url)
(Thread/sleep 2000) ;; make a little timeout, to avoid overloading server
(post-fn browser)
(let [vals (map #(js-eval browser %) validations)
vals-str (apply str (interpose "," vals))]
(str a-url "," vals-str))
(catch Exception e
(str a-url "," e)))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title") (fn[b](cov3/remove-cookie b "_github_ses")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; REGULAR CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- domain-of [a-url]
"given a url it returns its domain"
(last (re-find #"http(s?)://([^/]*)" a-url)))
;; (cov3/domain-of "http://al3xandr3.github.com/")
(defn- save-q [a-url to-see seen]
"saves a queue to file"
(do
(stream/spit
(str (domain-of a-url) "_to_see.txt")
to-see))
(stream/spit
(str (domain-of a-url) "_seen.txt")
seen))
(defn- load-q [a-url name]
"loads a queue(for the crawler) from file, for a given url,
for a given domain name.
Note that when loads an non-existing file, then also returns back as the
first on the queue the url given as this func argument,
this is usefull for bootstraping the crawler"
(let [fil (new File (str (domain-of a-url) name))]
(if (.exists fil)
(with-in-str (slurp (str (domain-of a-url) name)) (read))
#{(str a-url)})))
(defn- process-to-see
"calculates the list of the next links to see in the crawler crawl"
[to-see seen saw-lnk new-lnks]
(let [nto-see (disj to-see saw-lnk)] ;remove the last seen link
(if (not (empty? new-lnks))
(let [asset (set new-lnks)
;; only allow the ones with correct domain
rightdomain (set (filter #(= (domain-of saw-lnk) (domain-of %)) asset))
;; removes the already seen links
without-seen (difference rightdomain seen)]
(union nto-see without-seen))
nto-see)))
(defn crawl
"crawls a site, and a aplies the javavascript validations given to each page"
([b u v] (crawl b u v (fn[b]()) ))
([b a-site validations post-fn]
(cov3/with-browser browser b
(binding [*out* (FileWriter.
(str "result_crawl_"
(domain-of a-site)
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
;; returns the root url, when empty for bootstrap
(loop [to-see (load-q a-site "_to_see.txt")
seen (load-q a-site "_seen.txt")]
(if (not (empty? to-see))
(let [a-url (first to-see)]
(save-q a-url to-see seen)
(println (validate-page browser a-url validations post-fn))
(let [new-lnks (get-links-in-domain browser)]
(recur (process-to-see to-see seen a-url new-lnks) (conj seen a-url))))))
(println "DONE")))))
;; (cov3/crawl :ff "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SITEMAP.XML CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pick-sample [a-percentage a-list]
"picks a subset (a)percentage of the total"
(filter #(if (> (rand) (- 1 (/ a-percentage 100))) %) a-list))
;; (cov3.sitemap/pick-sample 50 '(1 2 3 4 5 6 7 8 9 0))
(defn- get-sitemap
"given a sitemap url it returns a list of the sample size of the links
also aplies replacement to the links if desired, usefull for development
enviroments that go check live enviroment, or vice-versa."
[sitemap-url sub-from sub-to sample-size]
(let [raw (xml-> (zip/xml-zip (xml/parse sitemap-url)) :url :loc text)
piked (pick-sample sample-size raw)
trans (map #(.replace % sub-from sub-to) piked)]
trans))
;; (cov3/get-sitemap "http://al3xandr3.github.com/sitemap.xml" "" "" 100)
(defn sitemap-crawl
"given a browser a sitemap url and validations it runs those validations
on each page of the sample sixed sitemap, also with the transformation given"
([b s f t ss v] (sitemap-crawl b s f t ss v (fn[b]())))
([b sitemap-url replace-from replace-to sample-size validations post-fn]
(cov3/with-browser a-browser b
(let [url-list (get-sitemap sitemap-url replace-from replace-to sample-size)]
;; outputs the result to file
(binding [*out* (FileWriter.
(str "result_sitemap-crawl_"
(domain-of sitemap-url) "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(doseq [a-url url-list]
(println (validate-page a-browser a-url validations post-fn))))))))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; STEP CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- read-csv [filename]
"given a filename it returns a list(seq) of lines, where each line is a 4 element list(seq)"
(let [reader (CSVReader. (FileReader. filename))]
(map vec (take-while identity (repeatedly #(.readNext reader))))))
(defn step-crawl
"given a browser and a file with the steps to take, goes step-by-step
outputing the validations results. In the file besides the url on each step
there are also the validations to execute. File format, a csv file with 4 columns:
url-to-go,javascript-validation-to-run1,javascript-validation-to-run2,javascript-validation-to-run3
example: http://al3xandr3.github.com/,\"document.title\",\"'jQuery?:'+(typeof jQuery !== 'undefined')\",2+2"
([b f] (step-crawl b f (fn[b]())))
([b file post-fn]
(let [stripname (last (string/split #"\/" file))]
(binding [*out* (FileWriter.
(str "result_step-crawl_"
stripname "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(cov3/with-browser browser b
(let [lst (read-csv file)]
(doseq [[url check1 check2 check3] lst]
(println (validate-page browser url (list check1 check2 check3) post-fn)))))))))
;; (cov3/step-crawl :ff "data/steps.csv")
;; (cov3/step-crawl :ff "data/steps.csv" #(cov3/remove-cookie % "_github_ses"))
|
54034
|
(ns #^{:author "al3xandr3 <<EMAIL>>"
:doc "Cov3, a custom crawler" }
cov3)
(require '[clojure.zip :as zip])
(require '[clojure.xml :as xml])
(require '[clojure.contrib.string :as string])
(require '[clojure.contrib.duck-streams :as stream])
(use 'clojure.set)
(use 'clojure.contrib.zip-filter.xml)
(import '(java.io File))
(import 'java.io.FileWriter)
(import 'java.text.SimpleDateFormat)
(import 'java.util.Date)
(import 'java.util.Calendar)
(import 'java.net.URLDecoder)
(import 'org.openqa.selenium.By)
(import 'org.openqa.selenium.Cookie)
(import 'org.openqa.selenium.Speed)
(import 'org.openqa.selenium.WebDriver)
(import 'org.openqa.selenium.WebElement)
(import 'org.openqa.selenium.htmlunit.HtmlUnitDriver)
(import 'org.openqa.selenium.firefox.FirefoxDriver)
(import 'org.openqa.selenium.ie.InternetExplorerDriver)
(import 'org.openqa.selenium.chrome.ChromeDriver)
(import 'org.openqa.selenium.JavascriptExecutor)
(import 'java.io.FileReader 'au.com.bytecode.opencsv.CSVReader)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; WEBDRIVER API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; *drivers* list and way to create a new instance, borrowed from:
;; http://github.com/mikitebeka/webdriver-clj/blob/master/webdriver.clj
(def *drivers* {
:ff FirefoxDriver
:ie InternetExplorerDriver
:ch ChromeDriver
:hu HtmlUnitDriver})
(defmacro with-browser
"given a variable to place the browser intance and a type of browser
(ff, ie, ch or hu), it creates a webdriver browser instance than
is then available in the body. Closes browser instance at the end"
[browser type & body]
`(let [~browser (.newInstance (*drivers* ~type))]
;; htmlUnit requires to be explicitly enabled for javascript
(if (= ~type :hu)
(.setJavascriptEnabled ~browser true))
~@body
;; htmlUnit does not needs to be closed
(if (not (= ~type :hu))
(.close ~browser))))
;; (macroexpand '(cov3/with-browser b :ff))
;; (cov3/with-browser b :ff)
(defn go
"given a browser instance with some page open, it
browses to a page"
[browser url]
(try
(.get browser url)
(catch Exception e
(println (str url "," e)))))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/"))
(defn js-eval
"given a browser instance with some page open, it
executes javascript code"
[browser code]
(try
(.executeScript browser (str "return " code) (into-array ""))
(catch Exception e
(println (str code "," e))
(str code "," e))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(typeof jQuery !== 'undefined')")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(new Date().getHours())+':'+(new Date().getMinutes())+':'+(new Date().getSeconds())")))
;; note that chrome has bugs, reported here:
;; http://code.google.com/p/selenium/issues/detail?id=430
;; so following does not work yet...
;; (cov3/with-browser b :ch (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
(defn get-protocol
"given a browser instance with some page open, it
returns the url protocol, like 'http'"
[b]
(js-eval b "location.protocol"))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-protocol b)))
(defn get-domain
"given a browser instance with some page open, it
returns the url domain, like al3xandr3.github.com"
[b]
(js-eval b "location.hostname"))
;;(cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-domain b)))
(defn- get-attr
"given a webdrivers html element, it returns
the value of the attr specified"
[elem attr]
"gets an attribute from a webdriver web element"
(.getAttribute elem attr))
(defn get-links-in-domain
"given a browser instance with some page open, it
retuns all of the page's links to the same domain"
[b]
(try
(let [lnks (js-eval b "document.links")]
(if (empty? lnks)
'()
(let [href (map #(get-attr % "href") lnks)
host (str (get-protocol b) "//" (get-domain b))
flnks (map #(if (string/substring? host %) % (str host %)) href)
pound (map #(first (string/split #"\#" %)) flnks)]
pound)))
(catch Exception e
(println (str "get-links-in-domain: " e)))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (first (cov3/get-links-in-domain b))))
(defn read-cookie
[driver name]
(let [coo (.getCookieNamed (.manage driver) name)]
(if (= coo nil)
""
(.getValue coo))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/read-cookie b "_github_ses")))
(defn write-cookie
([b n v] (write-cookie b n v nil "/"))
([b n v d] (write-cookie b n v d "/"))
([b name value date path] (.addCookie (.manage b) (new Cookie name value path date))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/new-cookie b "al" "123" "")))
(defn remove-cookie
"given en executing browser and a cookie name,
it removes that cookie"
[b name]
(.deleteCookieNamed (.manage b) name))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/remove-cookie b "_github_ses")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PAGE VALIDATOR ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate-page
"given a browser and a page, returns a comma separated string
result of the execution of the javascript validation given"
([b u v] (validate-page b u v (fn[b]()) ))
([browser a-url validations post-fn]
(try
(go browser a-url)
(Thread/sleep 2000) ;; make a little timeout, to avoid overloading server
(post-fn browser)
(let [vals (map #(js-eval browser %) validations)
vals-str (apply str (interpose "," vals))]
(str a-url "," vals-str))
(catch Exception e
(str a-url "," e)))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title") (fn[b](cov3/remove-cookie b "_github_ses")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; REGULAR CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- domain-of [a-url]
"given a url it returns its domain"
(last (re-find #"http(s?)://([^/]*)" a-url)))
;; (cov3/domain-of "http://al3xandr3.github.com/")
(defn- save-q [a-url to-see seen]
"saves a queue to file"
(do
(stream/spit
(str (domain-of a-url) "_to_see.txt")
to-see))
(stream/spit
(str (domain-of a-url) "_seen.txt")
seen))
(defn- load-q [a-url name]
"loads a queue(for the crawler) from file, for a given url,
for a given domain name.
Note that when loads an non-existing file, then also returns back as the
first on the queue the url given as this func argument,
this is usefull for bootstraping the crawler"
(let [fil (new File (str (domain-of a-url) name))]
(if (.exists fil)
(with-in-str (slurp (str (domain-of a-url) name)) (read))
#{(str a-url)})))
(defn- process-to-see
"calculates the list of the next links to see in the crawler crawl"
[to-see seen saw-lnk new-lnks]
(let [nto-see (disj to-see saw-lnk)] ;remove the last seen link
(if (not (empty? new-lnks))
(let [asset (set new-lnks)
;; only allow the ones with correct domain
rightdomain (set (filter #(= (domain-of saw-lnk) (domain-of %)) asset))
;; removes the already seen links
without-seen (difference rightdomain seen)]
(union nto-see without-seen))
nto-see)))
(defn crawl
"crawls a site, and a aplies the javavascript validations given to each page"
([b u v] (crawl b u v (fn[b]()) ))
([b a-site validations post-fn]
(cov3/with-browser browser b
(binding [*out* (FileWriter.
(str "result_crawl_"
(domain-of a-site)
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
;; returns the root url, when empty for bootstrap
(loop [to-see (load-q a-site "_to_see.txt")
seen (load-q a-site "_seen.txt")]
(if (not (empty? to-see))
(let [a-url (first to-see)]
(save-q a-url to-see seen)
(println (validate-page browser a-url validations post-fn))
(let [new-lnks (get-links-in-domain browser)]
(recur (process-to-see to-see seen a-url new-lnks) (conj seen a-url))))))
(println "DONE")))))
;; (cov3/crawl :ff "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SITEMAP.XML CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pick-sample [a-percentage a-list]
"picks a subset (a)percentage of the total"
(filter #(if (> (rand) (- 1 (/ a-percentage 100))) %) a-list))
;; (cov3.sitemap/pick-sample 50 '(1 2 3 4 5 6 7 8 9 0))
(defn- get-sitemap
"given a sitemap url it returns a list of the sample size of the links
also aplies replacement to the links if desired, usefull for development
enviroments that go check live enviroment, or vice-versa."
[sitemap-url sub-from sub-to sample-size]
(let [raw (xml-> (zip/xml-zip (xml/parse sitemap-url)) :url :loc text)
piked (pick-sample sample-size raw)
trans (map #(.replace % sub-from sub-to) piked)]
trans))
;; (cov3/get-sitemap "http://al3xandr3.github.com/sitemap.xml" "" "" 100)
(defn sitemap-crawl
"given a browser a sitemap url and validations it runs those validations
on each page of the sample sixed sitemap, also with the transformation given"
([b s f t ss v] (sitemap-crawl b s f t ss v (fn[b]())))
([b sitemap-url replace-from replace-to sample-size validations post-fn]
(cov3/with-browser a-browser b
(let [url-list (get-sitemap sitemap-url replace-from replace-to sample-size)]
;; outputs the result to file
(binding [*out* (FileWriter.
(str "result_sitemap-crawl_"
(domain-of sitemap-url) "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(doseq [a-url url-list]
(println (validate-page a-browser a-url validations post-fn))))))))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; STEP CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- read-csv [filename]
"given a filename it returns a list(seq) of lines, where each line is a 4 element list(seq)"
(let [reader (CSVReader. (FileReader. filename))]
(map vec (take-while identity (repeatedly #(.readNext reader))))))
(defn step-crawl
"given a browser and a file with the steps to take, goes step-by-step
outputing the validations results. In the file besides the url on each step
there are also the validations to execute. File format, a csv file with 4 columns:
url-to-go,javascript-validation-to-run1,javascript-validation-to-run2,javascript-validation-to-run3
example: http://al3xandr3.github.com/,\"document.title\",\"'jQuery?:'+(typeof jQuery !== 'undefined')\",2+2"
([b f] (step-crawl b f (fn[b]())))
([b file post-fn]
(let [stripname (last (string/split #"\/" file))]
(binding [*out* (FileWriter.
(str "result_step-crawl_"
stripname "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(cov3/with-browser browser b
(let [lst (read-csv file)]
(doseq [[url check1 check2 check3] lst]
(println (validate-page browser url (list check1 check2 check3) post-fn)))))))))
;; (cov3/step-crawl :ff "data/steps.csv")
;; (cov3/step-crawl :ff "data/steps.csv" #(cov3/remove-cookie % "_github_ses"))
| true |
(ns #^{:author "al3xandr3 <PI:EMAIL:<EMAIL>END_PI>"
:doc "Cov3, a custom crawler" }
cov3)
(require '[clojure.zip :as zip])
(require '[clojure.xml :as xml])
(require '[clojure.contrib.string :as string])
(require '[clojure.contrib.duck-streams :as stream])
(use 'clojure.set)
(use 'clojure.contrib.zip-filter.xml)
(import '(java.io File))
(import 'java.io.FileWriter)
(import 'java.text.SimpleDateFormat)
(import 'java.util.Date)
(import 'java.util.Calendar)
(import 'java.net.URLDecoder)
(import 'org.openqa.selenium.By)
(import 'org.openqa.selenium.Cookie)
(import 'org.openqa.selenium.Speed)
(import 'org.openqa.selenium.WebDriver)
(import 'org.openqa.selenium.WebElement)
(import 'org.openqa.selenium.htmlunit.HtmlUnitDriver)
(import 'org.openqa.selenium.firefox.FirefoxDriver)
(import 'org.openqa.selenium.ie.InternetExplorerDriver)
(import 'org.openqa.selenium.chrome.ChromeDriver)
(import 'org.openqa.selenium.JavascriptExecutor)
(import 'java.io.FileReader 'au.com.bytecode.opencsv.CSVReader)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; WEBDRIVER API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; *drivers* list and way to create a new instance, borrowed from:
;; http://github.com/mikitebeka/webdriver-clj/blob/master/webdriver.clj
(def *drivers* {
:ff FirefoxDriver
:ie InternetExplorerDriver
:ch ChromeDriver
:hu HtmlUnitDriver})
(defmacro with-browser
"given a variable to place the browser intance and a type of browser
(ff, ie, ch or hu), it creates a webdriver browser instance than
is then available in the body. Closes browser instance at the end"
[browser type & body]
`(let [~browser (.newInstance (*drivers* ~type))]
;; htmlUnit requires to be explicitly enabled for javascript
(if (= ~type :hu)
(.setJavascriptEnabled ~browser true))
~@body
;; htmlUnit does not needs to be closed
(if (not (= ~type :hu))
(.close ~browser))))
;; (macroexpand '(cov3/with-browser b :ff))
;; (cov3/with-browser b :ff)
(defn go
"given a browser instance with some page open, it
browses to a page"
[browser url]
(try
(.get browser url)
(catch Exception e
(println (str url "," e)))))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/"))
(defn js-eval
"given a browser instance with some page open, it
executes javascript code"
[browser code]
(try
(.executeScript browser (str "return " code) (into-array ""))
(catch Exception e
(println (str code "," e))
(str code "," e))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(typeof jQuery !== 'undefined')")))
;; (cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/")
;; (println (cov3/js-eval b "(new Date().getHours())+':'+(new Date().getMinutes())+':'+(new Date().getSeconds())")))
;; note that chrome has bugs, reported here:
;; http://code.google.com/p/selenium/issues/detail?id=430
;; so following does not work yet...
;; (cov3/with-browser b :ch (cov3/go b "http://al3xandr3.github.com/") (println (cov3/js-eval b "document.title")))
(defn get-protocol
"given a browser instance with some page open, it
returns the url protocol, like 'http'"
[b]
(js-eval b "location.protocol"))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-protocol b)))
(defn get-domain
"given a browser instance with some page open, it
returns the url domain, like al3xandr3.github.com"
[b]
(js-eval b "location.hostname"))
;;(cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/get-domain b)))
(defn- get-attr
"given a webdrivers html element, it returns
the value of the attr specified"
[elem attr]
"gets an attribute from a webdriver web element"
(.getAttribute elem attr))
(defn get-links-in-domain
"given a browser instance with some page open, it
retuns all of the page's links to the same domain"
[b]
(try
(let [lnks (js-eval b "document.links")]
(if (empty? lnks)
'()
(let [href (map #(get-attr % "href") lnks)
host (str (get-protocol b) "//" (get-domain b))
flnks (map #(if (string/substring? host %) % (str host %)) href)
pound (map #(first (string/split #"\#" %)) flnks)]
pound)))
(catch Exception e
(println (str "get-links-in-domain: " e)))))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (first (cov3/get-links-in-domain b))))
(defn read-cookie
[driver name]
(let [coo (.getCookieNamed (.manage driver) name)]
(if (= coo nil)
""
(.getValue coo))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/read-cookie b "_github_ses")))
(defn write-cookie
([b n v] (write-cookie b n v nil "/"))
([b n v d] (write-cookie b n v d "/"))
([b name value date path] (.addCookie (.manage b) (new Cookie name value path date))))
;;(cov3/with-browser b :ff (cov3/go b "http://al3xandr3.github.com/") (println (cov3/new-cookie b "al" "123" "")))
(defn remove-cookie
"given en executing browser and a cookie name,
it removes that cookie"
[b name]
(.deleteCookieNamed (.manage b) name))
;; (cov3/with-browser b :hu (cov3/go b "http://al3xandr3.github.com/") (println (cov3/remove-cookie b "_github_ses")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PAGE VALIDATOR ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate-page
"given a browser and a page, returns a comma separated string
result of the execution of the javascript validation given"
([b u v] (validate-page b u v (fn[b]()) ))
([browser a-url validations post-fn]
(try
(go browser a-url)
(Thread/sleep 2000) ;; make a little timeout, to avoid overloading server
(post-fn browser)
(let [vals (map #(js-eval browser %) validations)
vals-str (apply str (interpose "," vals))]
(str a-url "," vals-str))
(catch Exception e
(str a-url "," e)))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))))
;; (cov3/with-browser b :ff (println (cov3/validate-page b "http://al3xandr3.github.com/" '("document.title") (fn[b](cov3/remove-cookie b "_github_ses")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; REGULAR CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- domain-of [a-url]
"given a url it returns its domain"
(last (re-find #"http(s?)://([^/]*)" a-url)))
;; (cov3/domain-of "http://al3xandr3.github.com/")
(defn- save-q [a-url to-see seen]
"saves a queue to file"
(do
(stream/spit
(str (domain-of a-url) "_to_see.txt")
to-see))
(stream/spit
(str (domain-of a-url) "_seen.txt")
seen))
(defn- load-q [a-url name]
"loads a queue(for the crawler) from file, for a given url,
for a given domain name.
Note that when loads an non-existing file, then also returns back as the
first on the queue the url given as this func argument,
this is usefull for bootstraping the crawler"
(let [fil (new File (str (domain-of a-url) name))]
(if (.exists fil)
(with-in-str (slurp (str (domain-of a-url) name)) (read))
#{(str a-url)})))
(defn- process-to-see
"calculates the list of the next links to see in the crawler crawl"
[to-see seen saw-lnk new-lnks]
(let [nto-see (disj to-see saw-lnk)] ;remove the last seen link
(if (not (empty? new-lnks))
(let [asset (set new-lnks)
;; only allow the ones with correct domain
rightdomain (set (filter #(= (domain-of saw-lnk) (domain-of %)) asset))
;; removes the already seen links
without-seen (difference rightdomain seen)]
(union nto-see without-seen))
nto-see)))
(defn crawl
"crawls a site, and a aplies the javavascript validations given to each page"
([b u v] (crawl b u v (fn[b]()) ))
([b a-site validations post-fn]
(cov3/with-browser browser b
(binding [*out* (FileWriter.
(str "result_crawl_"
(domain-of a-site)
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
;; returns the root url, when empty for bootstrap
(loop [to-see (load-q a-site "_to_see.txt")
seen (load-q a-site "_seen.txt")]
(if (not (empty? to-see))
(let [a-url (first to-see)]
(save-q a-url to-see seen)
(println (validate-page browser a-url validations post-fn))
(let [new-lnks (get-links-in-domain browser)]
(recur (process-to-see to-see seen a-url new-lnks) (conj seen a-url))))))
(println "DONE")))))
;; (cov3/crawl :ff "http://al3xandr3.github.com/" '("document.title" "(typeof jQuery !== 'undefined')"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SITEMAP.XML CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pick-sample [a-percentage a-list]
"picks a subset (a)percentage of the total"
(filter #(if (> (rand) (- 1 (/ a-percentage 100))) %) a-list))
;; (cov3.sitemap/pick-sample 50 '(1 2 3 4 5 6 7 8 9 0))
(defn- get-sitemap
"given a sitemap url it returns a list of the sample size of the links
also aplies replacement to the links if desired, usefull for development
enviroments that go check live enviroment, or vice-versa."
[sitemap-url sub-from sub-to sample-size]
(let [raw (xml-> (zip/xml-zip (xml/parse sitemap-url)) :url :loc text)
piked (pick-sample sample-size raw)
trans (map #(.replace % sub-from sub-to) piked)]
trans))
;; (cov3/get-sitemap "http://al3xandr3.github.com/sitemap.xml" "" "" 100)
(defn sitemap-crawl
"given a browser a sitemap url and validations it runs those validations
on each page of the sample sixed sitemap, also with the transformation given"
([b s f t ss v] (sitemap-crawl b s f t ss v (fn[b]())))
([b sitemap-url replace-from replace-to sample-size validations post-fn]
(cov3/with-browser a-browser b
(let [url-list (get-sitemap sitemap-url replace-from replace-to sample-size)]
;; outputs the result to file
(binding [*out* (FileWriter.
(str "result_sitemap-crawl_"
(domain-of sitemap-url) "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(doseq [a-url url-list]
(println (validate-page a-browser a-url validations post-fn))))))))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;; (cov3/sitemap-crawl :ff "http://al3xandr3.github.com/sitemap.xml" "" "" 90 '("document.title"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; STEP CRAWLER ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- read-csv [filename]
"given a filename it returns a list(seq) of lines, where each line is a 4 element list(seq)"
(let [reader (CSVReader. (FileReader. filename))]
(map vec (take-while identity (repeatedly #(.readNext reader))))))
(defn step-crawl
"given a browser and a file with the steps to take, goes step-by-step
outputing the validations results. In the file besides the url on each step
there are also the validations to execute. File format, a csv file with 4 columns:
url-to-go,javascript-validation-to-run1,javascript-validation-to-run2,javascript-validation-to-run3
example: http://al3xandr3.github.com/,\"document.title\",\"'jQuery?:'+(typeof jQuery !== 'undefined')\",2+2"
([b f] (step-crawl b f (fn[b]())))
([b file post-fn]
(let [stripname (last (string/split #"\/" file))]
(binding [*out* (FileWriter.
(str "result_step-crawl_"
stripname "_"
(.format (SimpleDateFormat. "yyyy-MM-dd") (Date.)) ".csv"))]
(cov3/with-browser browser b
(let [lst (read-csv file)]
(doseq [[url check1 check2 check3] lst]
(println (validate-page browser url (list check1 check2 check3) post-fn)))))))))
;; (cov3/step-crawl :ff "data/steps.csv")
;; (cov3/step-crawl :ff "data/steps.csv" #(cov3/remove-cookie % "_github_ses"))
|
[
{
"context": ";; autodub.clj\n;; (c) 2017 by Milan Gruner\n;; Part of project \"AlgorithMuss\"\n\n(ns algorithmu",
"end": 42,
"score": 0.9998547434806824,
"start": 30,
"tag": "NAME",
"value": "Milan Gruner"
}
] |
overtone/src/algorithmuss/autodub.clj
|
lemilonkh/algorithmuss
| 13 |
;; autodub.clj
;; (c) 2017 by Milan Gruner
;; Part of project "AlgorithMuss"
(ns algorithmuss.autodub)
(use 'overtone.live)
(let [
bpm 120
;; create pool of notes as seed for random base line sequence
notes [40 41 28 28 28 27 25 35 78]
;; create an impulse trigger firing once per bar
trig (impulse:kr (/ bpm 120))
;; create frequency generator for a randomly picked note
freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25))
;; switch note durations
swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF))
;; create a sweep curve for filter below
sweep (lin-exp (lf-tri swr) -1 1 40 3000)
;; create a slightly detuned stereo sawtooth oscillator
wob (mix (saw (* freq [0.99 1.01])))
;; apply low pass filter using sweep curve to control cutoff freq
wob (lpf wob sweep)
;; normalize to 80% volume
wob (* 0.8 (normalizer wob))
;; apply band pass filter with resonance at 5kHz
wob (+ wob (bpf wob 1500 2))
;; mix in 20% reverb
wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7)))
;; create impulse generator from given drum pattern
kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7)
;; use modulated sine wave oscillator
kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200))))
;; clip at max volume to create distortion
kick (clip2 kick 1)
;; snare is just using gated & over-amplified pink noise
snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05])))
;; send through band pass filter with peak @ 2kHz
snare (+ snare (bpf (* 4 snare) 2000))
;; also clip at max vol to distort
snare (clip2 snare 1)]
;; mixdown & clip
(clip2 (+ wob kick snare) 1))
|
26640
|
;; autodub.clj
;; (c) 2017 by <NAME>
;; Part of project "AlgorithMuss"
(ns algorithmuss.autodub)
(use 'overtone.live)
(let [
bpm 120
;; create pool of notes as seed for random base line sequence
notes [40 41 28 28 28 27 25 35 78]
;; create an impulse trigger firing once per bar
trig (impulse:kr (/ bpm 120))
;; create frequency generator for a randomly picked note
freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25))
;; switch note durations
swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF))
;; create a sweep curve for filter below
sweep (lin-exp (lf-tri swr) -1 1 40 3000)
;; create a slightly detuned stereo sawtooth oscillator
wob (mix (saw (* freq [0.99 1.01])))
;; apply low pass filter using sweep curve to control cutoff freq
wob (lpf wob sweep)
;; normalize to 80% volume
wob (* 0.8 (normalizer wob))
;; apply band pass filter with resonance at 5kHz
wob (+ wob (bpf wob 1500 2))
;; mix in 20% reverb
wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7)))
;; create impulse generator from given drum pattern
kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7)
;; use modulated sine wave oscillator
kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200))))
;; clip at max volume to create distortion
kick (clip2 kick 1)
;; snare is just using gated & over-amplified pink noise
snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05])))
;; send through band pass filter with peak @ 2kHz
snare (+ snare (bpf (* 4 snare) 2000))
;; also clip at max vol to distort
snare (clip2 snare 1)]
;; mixdown & clip
(clip2 (+ wob kick snare) 1))
| true |
;; autodub.clj
;; (c) 2017 by PI:NAME:<NAME>END_PI
;; Part of project "AlgorithMuss"
(ns algorithmuss.autodub)
(use 'overtone.live)
(let [
bpm 120
;; create pool of notes as seed for random base line sequence
notes [40 41 28 28 28 27 25 35 78]
;; create an impulse trigger firing once per bar
trig (impulse:kr (/ bpm 120))
;; create frequency generator for a randomly picked note
freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25))
;; switch note durations
swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF))
;; create a sweep curve for filter below
sweep (lin-exp (lf-tri swr) -1 1 40 3000)
;; create a slightly detuned stereo sawtooth oscillator
wob (mix (saw (* freq [0.99 1.01])))
;; apply low pass filter using sweep curve to control cutoff freq
wob (lpf wob sweep)
;; normalize to 80% volume
wob (* 0.8 (normalizer wob))
;; apply band pass filter with resonance at 5kHz
wob (+ wob (bpf wob 1500 2))
;; mix in 20% reverb
wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7)))
;; create impulse generator from given drum pattern
kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7)
;; use modulated sine wave oscillator
kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200))))
;; clip at max volume to create distortion
kick (clip2 kick 1)
;; snare is just using gated & over-amplified pink noise
snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05])))
;; send through band pass filter with peak @ 2kHz
snare (+ snare (bpf (* 4 snare) 2000))
;; also clip at max vol to distort
snare (clip2 snare 1)]
;; mixdown & clip
(clip2 (+ wob kick snare) 1))
|
[
{
"context": ":instance \"Malcolm\"\n :annotations {\"default\" \"Bob\"}\n :type \"string\"\n :valid? true}\n (v/v",
"end": 436,
"score": 0.9985981583595276,
"start": 433,
"tag": "NAME",
"value": "Bob"
},
{
"context": "v/validate\n {\"type\" \"string\"\n \"default\" \"Bob\"}\n \"Malcolm\" )))\n (is\n (=\n {:instance {",
"end": 536,
"score": 0.9996391534805298,
"start": 533,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {\"type\" \"string\"\n \"default\" \"Bob\"}\n \"Malcolm\" )))\n (is\n (=\n {:instance {\"surname\" \"Spark",
"end": 552,
"score": 0.9991500973701477,
"start": 545,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": " {\"surname\" \"Sparks\"\n \"firstname\" \"Bob\"}\n :annotations\n {\"title\" \"person\"\n ",
"end": 637,
"score": 0.9956604242324829,
"start": 634,
"tag": "NAME",
"value": "Bob"
},
{
"context": "on\" \"Family name\"}\n \"firstname\" {\"default\" \"Bob\"}}}\n :type \"object\"\n :valid? true}\n\n (",
"end": 865,
"score": 0.9986572265625,
"start": 862,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ame\"\n {\"type\" \"string\"\n \"default\" \"Bob\"}\n \"surname\"\n {\"type\" \"string\"\n ",
"end": 1124,
"score": 0.9996939897537231,
"start": 1121,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\"description\" \"Family name\"\n \"examples\" [\"Smith\" \"Johnson\" \"Jones\" \"Williams\"]\n }}\n ",
"end": 1261,
"score": 0.999768078327179,
"start": 1256,
"tag": "NAME",
"value": "Smith"
},
{
"context": "tion\" \"Family name\"\n \"examples\" [\"Smith\" \"Johnson\" \"Jones\" \"Williams\"]\n }}\n \"required",
"end": 1271,
"score": 0.9996978640556335,
"start": 1264,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "ily name\"\n \"examples\" [\"Smith\" \"Johnson\" \"Jones\" \"Williams\"]\n }}\n \"required\" [\"firs",
"end": 1279,
"score": 0.999716579914093,
"start": 1274,
"tag": "NAME",
"value": "Jones"
},
{
"context": "\"\n \"examples\" [\"Smith\" \"Johnson\" \"Jones\" \"Williams\"]\n }}\n \"required\" [\"firstname\" \"sur",
"end": 1290,
"score": 0.9993891716003418,
"start": 1282,
"tag": "NAME",
"value": "Williams"
},
{
"context": "perties\" {\"firstname\" {\"type\" \"string\" \"default\" \"Dominic\"}\n \"surname\"\n {\"a",
"end": 1540,
"score": 0.8246433138847351,
"start": 1533,
"tag": "NAME",
"value": "Dominic"
},
{
"context": "perties\" {\"firstname\" {\"type\" \"string\" \"default\" \"Dominic\"}\n \"surname\"\n {\"a",
"end": 2051,
"score": 0.6571057438850403,
"start": 2044,
"tag": "NAME",
"value": "Dominic"
}
] |
test/juxt/jinx/annotation_test.cljc
|
The-Alchemist/jinx
| 73 |
;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.annotation-test
(:require
[juxt.jinx.alpha.validate :as v]
[juxt.jinx.alpha.schema :refer [schema]]
#?(:clj
[clojure.test :refer [deftest is testing]]
:cljs
[cljs.test :refer-macros [deftest is testing run-tests]]
[cljs.core :refer [ExceptionInfo]])))
(deftest simple-annotation-test
(is
(=
{:instance "Malcolm"
:annotations {"default" "Bob"}
:type "string"
:valid? true}
(v/validate
{"type" "string"
"default" "Bob"}
"Malcolm" )))
(is
(=
{:instance {"surname" "Sparks"
"firstname" "Bob"}
:annotations
{"title" "person"
"description" "A person, user or employee"
:properties
{"surname" {"title" "Surname"
"description" "Family name"}
"firstname" {"default" "Bob"}}}
:type "object"
:valid? true}
(v/validate
(schema
{"type" "object"
"title" "person"
"description" "A person, user or employee"
"properties"
{"firstname"
{"type" "string"
"default" "Bob"}
"surname"
{"type" "string"
"title" "Surname"
"description" "Family name"
"examples" ["Smith" "Johnson" "Jones" "Williams"]
}}
"required" ["firstname" "surname"]})
{"surname" "Sparks"}
{:journal? false}))))
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "Dominic"}
"surname"
{"anyOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "number"
"default" "foo"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "Dominic"}
"surname"
{"allOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "string"
"default" "food"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
|
102863
|
;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.annotation-test
(:require
[juxt.jinx.alpha.validate :as v]
[juxt.jinx.alpha.schema :refer [schema]]
#?(:clj
[clojure.test :refer [deftest is testing]]
:cljs
[cljs.test :refer-macros [deftest is testing run-tests]]
[cljs.core :refer [ExceptionInfo]])))
(deftest simple-annotation-test
(is
(=
{:instance "Malcolm"
:annotations {"default" "<NAME>"}
:type "string"
:valid? true}
(v/validate
{"type" "string"
"default" "<NAME>"}
"<NAME>" )))
(is
(=
{:instance {"surname" "Sparks"
"firstname" "<NAME>"}
:annotations
{"title" "person"
"description" "A person, user or employee"
:properties
{"surname" {"title" "Surname"
"description" "Family name"}
"firstname" {"default" "<NAME>"}}}
:type "object"
:valid? true}
(v/validate
(schema
{"type" "object"
"title" "person"
"description" "A person, user or employee"
"properties"
{"firstname"
{"type" "string"
"default" "<NAME>"}
"surname"
{"type" "string"
"title" "Surname"
"description" "Family name"
"examples" ["<NAME>" "<NAME>" "<NAME>" "<NAME>"]
}}
"required" ["firstname" "surname"]})
{"surname" "Sparks"}
{:journal? false}))))
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "<NAME>"}
"surname"
{"anyOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "number"
"default" "foo"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "<NAME>"}
"surname"
{"allOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "string"
"default" "food"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
| true |
;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.annotation-test
(:require
[juxt.jinx.alpha.validate :as v]
[juxt.jinx.alpha.schema :refer [schema]]
#?(:clj
[clojure.test :refer [deftest is testing]]
:cljs
[cljs.test :refer-macros [deftest is testing run-tests]]
[cljs.core :refer [ExceptionInfo]])))
(deftest simple-annotation-test
(is
(=
{:instance "Malcolm"
:annotations {"default" "PI:NAME:<NAME>END_PI"}
:type "string"
:valid? true}
(v/validate
{"type" "string"
"default" "PI:NAME:<NAME>END_PI"}
"PI:NAME:<NAME>END_PI" )))
(is
(=
{:instance {"surname" "Sparks"
"firstname" "PI:NAME:<NAME>END_PI"}
:annotations
{"title" "person"
"description" "A person, user or employee"
:properties
{"surname" {"title" "Surname"
"description" "Family name"}
"firstname" {"default" "PI:NAME:<NAME>END_PI"}}}
:type "object"
:valid? true}
(v/validate
(schema
{"type" "object"
"title" "person"
"description" "A person, user or employee"
"properties"
{"firstname"
{"type" "string"
"default" "PI:NAME:<NAME>END_PI"}
"surname"
{"type" "string"
"title" "Surname"
"description" "Family name"
"examples" ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
}}
"required" ["firstname" "surname"]})
{"surname" "Sparks"}
{:journal? false}))))
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "PI:NAME:<NAME>END_PI"}
"surname"
{"anyOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "number"
"default" "foo"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
#_(v/validate
(schema
{"type" "object"
"required" ["firstname"]
"properties" {"firstname" {"type" "string" "default" "PI:NAME:<NAME>END_PI"}
"surname"
{"allOf"
[{"type" "string"
"default" "foo"
"title" "Surname"
}
{"type" "string"
"default" "food"
"title" "Family name"
}]}}})
{"surname" "Sparks"}
{:journal? false})
|
[
{
"context": " :username \"[email protected]\"\n; :passw",
"end": 5546,
"score": 0.999909520149231,
"start": 5525,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :password \"CB5BB29D51A198961E1A1C68509D410458A29E10\"}]]\n;\n\n\n\n;Datomic is ready for development stage\n",
"end": 5641,
"score": 0.9992765188217163,
"start": 5601,
"tag": "PASSWORD",
"value": "CB5BB29D51A198961E1A1C68509D410458A29E10"
}
] |
workspace/datomic-dev-client/src/datomic_dev_client/core.clj
|
muthuishere/clojure-web-fundamentals
| 0 |
(ns datomic-dev-client.core
(:require
[datomic.client.api :as d]
[datomic-dev-client.data :refer [movie-schema default-movie-data]]
)
)
(def cfg {:server-type :dev-local
:system "dev"
}
)
(def movie-db-name "movies")
(def client (d/client cfg))
(defn create-database [db-name]
(d/create-database client {:db-name db-name})
)
(defn delete-database [db-name]
(d/delete-database client {:db-name db-name})
)
(defn connect-db [db-name]
(d/connect client {:db-name db-name})
)
(defn database-exists? [db-name]
(try
(connect-db db-name)
true
(catch Exception e
false
)
)
)
(defn database-does-not-exists? [db-name]
(not (database-exists? db-name))
)
(defn query-engine []
(d/db (connect-db movie-db-name))
)
(defn connect-movie-db []
(connect-db movie-db-name)
)
(defn create-movie-schema []
(d/transact (connect-movie-db) {:tx-data movie-schema
})
)
(defn insert-default-movies []
(d/transact (connect-movie-db) {:tx-data default-movie-data
})
)
;insert data
;update data
;delete & update
;graphql
;queries
; all
; by id
; by genre
;mutation
;insert
;delete
(defn setup-database []
; (println "does not exists" (database-does-not-exists? movie-db-name))
(when (database-does-not-exists? movie-db-name)
(println "Creating Database")
(create-database movie-db-name)
(println "Creating Schema")
(create-movie-schema)
(println "inserting movies")
(println (insert-default-movies))
)
)
(defn get-all-movies-array []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-actors-by-id [movie-id]
(d/q '[:find ?actors
:in $ ?id
:where
[?movie :movie/actors ?actors]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn find-genres-by-id [movie-id]
(d/q '[:find ?genres
:in $ ?id
:where
[?movie :movie/genres ?genres]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn all-movies-other [request]
(map #(d/pull (query-engine) '[*] %) (get-all-entity-ids))
)
(defn get-all-movies []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-movie-by-id [movie-id]
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:in $ ?id
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine) movie-id)
)
(defn parse-entity-id [[[entity-id]]]
entity-id
)
(defn find-entity-id-by-movie-id [movie-id]
(parse-entity-id ( d/q '[:find ?entityid
:in $ ?id
:where
[?entityid :movie/id ?id]
]
(query-engine)
movie-id
))
)
(defn delete-by-id [ connection entity-id]
(println "deleting " entity-id)
(d/transact
connection
{:tx-data
[[:db/retractEntity entity-id]]
})
)
(defn delete-by-movie-id [movie-id]
(delete-by-id (connect-movie-db) (find-entity-id-by-movie-id movie-id ))
)
(comment
(delete-by-movie-id 2)
;(find-all-movie-ids)
(find-entity-id-by-movie-id 2)
(get-all-movies)
(find-movie-by-id 1)
(find-genres-by-id 2)
(delete-database movie-db-name)
;(database-exists? movie-db-name)
;(database-does-not-exists? movie-db-name)
;(create-database movie-db-name)
(setup-database)
(get-all-movies)
(count (get-all-movies))
)
;Download cognitect tools and run install
;https://cognitect.com/dev-tools
; Update your leiningen project.clj
;Add dependency
; [com.datomic/dev-local "1.0.238"]
; Add repository
;:repositories [
; ["cognitect-dev-tools" {:url "https://dev-tools.cognitect.com/maven/releases/"
; :username "[email protected]"
; :password "CB5BB29D51A198961E1A1C68509D410458A29E10"}]]
;
;Datomic is ready for development stage
;For prod
;(require '[datomic.dev-local :as dl])
;(dl/divert-system {:system "production"})
;
;;; existing requests for Cloud system will be served locally!
;(def client (d/client {:system "production"
; :server-type :ion
; :region "us-east-1"
; :endpoint "https://ljfrt3pr18.execute-api.us-east-1.amazonaws.com"}))
; This is db client
; Create a Database
;(d/delete-database client {:db-name "movies"})
(comment
; plot VARCHAR(781) NOT NULL
; ,director VARCHAR(120) NOT NULL
; ,genres VARCHAR(117) NOT NULL
; ,title VARCHAR(124) NOT NULL
; ,year INTEGER NOT NULL
; ,actors VARCHAR(157) NOT NULL
; ,id INTEGER NOT NULL PRIMARY KEY
; ,runtime INTEGER NOT NULL
; ,posterUrl VARCHAR(781) NOT NULL
)
(comment
;Queries should be exceuted against database
(def db (d/db (connect-movie-db)))
; Find All
(d/q '[:find ?title ?plot ?director ?genres ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/plot ?genres]
[?movie :movie/plot ?year]
[?movie :movie/plot ?id]
[?movie :movie/plot ?runtime]
[?movie :movie/plot ?posterUrl]
]
db)
;FInd Determine which data to return , you will be using only dump variable there
;Where you will do the mapping against the variavle
;Query Data
(def all-titles-q '[:find ?title ?plot
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
])
(d/q all-titles-q db)
(d/pull db '[*])
)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
|
23557
|
(ns datomic-dev-client.core
(:require
[datomic.client.api :as d]
[datomic-dev-client.data :refer [movie-schema default-movie-data]]
)
)
(def cfg {:server-type :dev-local
:system "dev"
}
)
(def movie-db-name "movies")
(def client (d/client cfg))
(defn create-database [db-name]
(d/create-database client {:db-name db-name})
)
(defn delete-database [db-name]
(d/delete-database client {:db-name db-name})
)
(defn connect-db [db-name]
(d/connect client {:db-name db-name})
)
(defn database-exists? [db-name]
(try
(connect-db db-name)
true
(catch Exception e
false
)
)
)
(defn database-does-not-exists? [db-name]
(not (database-exists? db-name))
)
(defn query-engine []
(d/db (connect-db movie-db-name))
)
(defn connect-movie-db []
(connect-db movie-db-name)
)
(defn create-movie-schema []
(d/transact (connect-movie-db) {:tx-data movie-schema
})
)
(defn insert-default-movies []
(d/transact (connect-movie-db) {:tx-data default-movie-data
})
)
;insert data
;update data
;delete & update
;graphql
;queries
; all
; by id
; by genre
;mutation
;insert
;delete
(defn setup-database []
; (println "does not exists" (database-does-not-exists? movie-db-name))
(when (database-does-not-exists? movie-db-name)
(println "Creating Database")
(create-database movie-db-name)
(println "Creating Schema")
(create-movie-schema)
(println "inserting movies")
(println (insert-default-movies))
)
)
(defn get-all-movies-array []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-actors-by-id [movie-id]
(d/q '[:find ?actors
:in $ ?id
:where
[?movie :movie/actors ?actors]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn find-genres-by-id [movie-id]
(d/q '[:find ?genres
:in $ ?id
:where
[?movie :movie/genres ?genres]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn all-movies-other [request]
(map #(d/pull (query-engine) '[*] %) (get-all-entity-ids))
)
(defn get-all-movies []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-movie-by-id [movie-id]
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:in $ ?id
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine) movie-id)
)
(defn parse-entity-id [[[entity-id]]]
entity-id
)
(defn find-entity-id-by-movie-id [movie-id]
(parse-entity-id ( d/q '[:find ?entityid
:in $ ?id
:where
[?entityid :movie/id ?id]
]
(query-engine)
movie-id
))
)
(defn delete-by-id [ connection entity-id]
(println "deleting " entity-id)
(d/transact
connection
{:tx-data
[[:db/retractEntity entity-id]]
})
)
(defn delete-by-movie-id [movie-id]
(delete-by-id (connect-movie-db) (find-entity-id-by-movie-id movie-id ))
)
(comment
(delete-by-movie-id 2)
;(find-all-movie-ids)
(find-entity-id-by-movie-id 2)
(get-all-movies)
(find-movie-by-id 1)
(find-genres-by-id 2)
(delete-database movie-db-name)
;(database-exists? movie-db-name)
;(database-does-not-exists? movie-db-name)
;(create-database movie-db-name)
(setup-database)
(get-all-movies)
(count (get-all-movies))
)
;Download cognitect tools and run install
;https://cognitect.com/dev-tools
; Update your leiningen project.clj
;Add dependency
; [com.datomic/dev-local "1.0.238"]
; Add repository
;:repositories [
; ["cognitect-dev-tools" {:url "https://dev-tools.cognitect.com/maven/releases/"
; :username "<EMAIL>"
; :password "<PASSWORD>"}]]
;
;Datomic is ready for development stage
;For prod
;(require '[datomic.dev-local :as dl])
;(dl/divert-system {:system "production"})
;
;;; existing requests for Cloud system will be served locally!
;(def client (d/client {:system "production"
; :server-type :ion
; :region "us-east-1"
; :endpoint "https://ljfrt3pr18.execute-api.us-east-1.amazonaws.com"}))
; This is db client
; Create a Database
;(d/delete-database client {:db-name "movies"})
(comment
; plot VARCHAR(781) NOT NULL
; ,director VARCHAR(120) NOT NULL
; ,genres VARCHAR(117) NOT NULL
; ,title VARCHAR(124) NOT NULL
; ,year INTEGER NOT NULL
; ,actors VARCHAR(157) NOT NULL
; ,id INTEGER NOT NULL PRIMARY KEY
; ,runtime INTEGER NOT NULL
; ,posterUrl VARCHAR(781) NOT NULL
)
(comment
;Queries should be exceuted against database
(def db (d/db (connect-movie-db)))
; Find All
(d/q '[:find ?title ?plot ?director ?genres ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/plot ?genres]
[?movie :movie/plot ?year]
[?movie :movie/plot ?id]
[?movie :movie/plot ?runtime]
[?movie :movie/plot ?posterUrl]
]
db)
;FInd Determine which data to return , you will be using only dump variable there
;Where you will do the mapping against the variavle
;Query Data
(def all-titles-q '[:find ?title ?plot
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
])
(d/q all-titles-q db)
(d/pull db '[*])
)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
| true |
(ns datomic-dev-client.core
(:require
[datomic.client.api :as d]
[datomic-dev-client.data :refer [movie-schema default-movie-data]]
)
)
(def cfg {:server-type :dev-local
:system "dev"
}
)
(def movie-db-name "movies")
(def client (d/client cfg))
(defn create-database [db-name]
(d/create-database client {:db-name db-name})
)
(defn delete-database [db-name]
(d/delete-database client {:db-name db-name})
)
(defn connect-db [db-name]
(d/connect client {:db-name db-name})
)
(defn database-exists? [db-name]
(try
(connect-db db-name)
true
(catch Exception e
false
)
)
)
(defn database-does-not-exists? [db-name]
(not (database-exists? db-name))
)
(defn query-engine []
(d/db (connect-db movie-db-name))
)
(defn connect-movie-db []
(connect-db movie-db-name)
)
(defn create-movie-schema []
(d/transact (connect-movie-db) {:tx-data movie-schema
})
)
(defn insert-default-movies []
(d/transact (connect-movie-db) {:tx-data default-movie-data
})
)
;insert data
;update data
;delete & update
;graphql
;queries
; all
; by id
; by genre
;mutation
;insert
;delete
(defn setup-database []
; (println "does not exists" (database-does-not-exists? movie-db-name))
(when (database-does-not-exists? movie-db-name)
(println "Creating Database")
(create-database movie-db-name)
(println "Creating Schema")
(create-movie-schema)
(println "inserting movies")
(println (insert-default-movies))
)
)
(defn get-all-movies-array []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-actors-by-id [movie-id]
(d/q '[:find ?actors
:in $ ?id
:where
[?movie :movie/actors ?actors]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn find-genres-by-id [movie-id]
(d/q '[:find ?genres
:in $ ?id
:where
[?movie :movie/genres ?genres]
[?movie :movie/id ?id]
]
(query-engine)
movie-id
)
)
(defn all-movies-other [request]
(map #(d/pull (query-engine) '[*] %) (get-all-entity-ids))
)
(defn get-all-movies []
; Find All
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine))
)
(defn find-movie-by-id [movie-id]
(d/q '[:find ?title ?plot ?director (distinct ?actors) (distinct ?genres) ?year ?id ?runtime ?posterUrl
:in $ ?id
:keys title plot director actors genres year id runtime posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/genres ?genres]
[?movie :movie/year ?year]
[?movie :movie/id ?id]
[?movie :movie/actors ?actors]
[?movie :movie/runtime ?runtime]
[?movie :movie/posterUrl ?posterUrl]
]
(query-engine) movie-id)
)
(defn parse-entity-id [[[entity-id]]]
entity-id
)
(defn find-entity-id-by-movie-id [movie-id]
(parse-entity-id ( d/q '[:find ?entityid
:in $ ?id
:where
[?entityid :movie/id ?id]
]
(query-engine)
movie-id
))
)
(defn delete-by-id [ connection entity-id]
(println "deleting " entity-id)
(d/transact
connection
{:tx-data
[[:db/retractEntity entity-id]]
})
)
(defn delete-by-movie-id [movie-id]
(delete-by-id (connect-movie-db) (find-entity-id-by-movie-id movie-id ))
)
(comment
(delete-by-movie-id 2)
;(find-all-movie-ids)
(find-entity-id-by-movie-id 2)
(get-all-movies)
(find-movie-by-id 1)
(find-genres-by-id 2)
(delete-database movie-db-name)
;(database-exists? movie-db-name)
;(database-does-not-exists? movie-db-name)
;(create-database movie-db-name)
(setup-database)
(get-all-movies)
(count (get-all-movies))
)
;Download cognitect tools and run install
;https://cognitect.com/dev-tools
; Update your leiningen project.clj
;Add dependency
; [com.datomic/dev-local "1.0.238"]
; Add repository
;:repositories [
; ["cognitect-dev-tools" {:url "https://dev-tools.cognitect.com/maven/releases/"
; :username "PI:EMAIL:<EMAIL>END_PI"
; :password "PI:PASSWORD:<PASSWORD>END_PI"}]]
;
;Datomic is ready for development stage
;For prod
;(require '[datomic.dev-local :as dl])
;(dl/divert-system {:system "production"})
;
;;; existing requests for Cloud system will be served locally!
;(def client (d/client {:system "production"
; :server-type :ion
; :region "us-east-1"
; :endpoint "https://ljfrt3pr18.execute-api.us-east-1.amazonaws.com"}))
; This is db client
; Create a Database
;(d/delete-database client {:db-name "movies"})
(comment
; plot VARCHAR(781) NOT NULL
; ,director VARCHAR(120) NOT NULL
; ,genres VARCHAR(117) NOT NULL
; ,title VARCHAR(124) NOT NULL
; ,year INTEGER NOT NULL
; ,actors VARCHAR(157) NOT NULL
; ,id INTEGER NOT NULL PRIMARY KEY
; ,runtime INTEGER NOT NULL
; ,posterUrl VARCHAR(781) NOT NULL
)
(comment
;Queries should be exceuted against database
(def db (d/db (connect-movie-db)))
; Find All
(d/q '[:find ?title ?plot ?director ?genres ?year ?id ?runtime ?posterUrl
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
[?movie :movie/director ?director]
[?movie :movie/plot ?genres]
[?movie :movie/plot ?year]
[?movie :movie/plot ?id]
[?movie :movie/plot ?runtime]
[?movie :movie/plot ?posterUrl]
]
db)
;FInd Determine which data to return , you will be using only dump variable there
;Where you will do the mapping against the variavle
;Query Data
(def all-titles-q '[:find ?title ?plot
:where
[?movie :movie/title ?title]
[?movie :movie/plot ?plot]
])
(d/q all-titles-q db)
(d/pull db '[*])
)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
|
[
{
"context": "---------------------\nCopyright (c) 2007-2013 Basho Technologies, Inc. All Rights Reserved.\n\nThis fi",
"end": 109,
"score": 0.6258668899536133,
"start": 108,
"tag": "NAME",
"value": "o"
}
] |
client_tests/clojure/clj-s3/test/java_s3_tests/test/client.clj
|
sharp/riak_cs
| 1 |
(comment
---------------------------------------------------------------------
Copyright (c) 2007-2013 Basho Technologies, Inc. All Rights Reserved.
This file is provided to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---------------------------------------------------------------------
)
(ns java-s3-tests.test.client
(:import java.security.MessageDigest
org.apache.commons.codec.binary.Hex
com.amazonaws.services.s3.model.AmazonS3Exception
com.amazonaws.services.s3.model.ObjectMetadata)
(:require [aws.sdk.s3 :as s3])
(:require [java-s3-tests.user-creation :as user-creation])
(:use midje.sweet))
(def ^:internal riak-cs-host-with-protocol "http://localhost")
(def ^:internal riak-cs-host "localhost")
(defn get-riak-cs-port-str
"Try to get a TCP port number from the OS environment"
[]
(let [port-str (get (System/getenv) "CS_HTTP_PORT")]
(cond (nil? port-str) "8080"
:else port-str)))
(defn get-riak-cs-port []
(Integer/parseInt (get-riak-cs-port-str) 10))
(defn md5-byte-array [input-byte-array]
(let [instance (MessageDigest/getInstance "MD5")]
(.digest instance input-byte-array)))
(defn md5-string
[input-byte-array]
(let [b (md5-byte-array input-byte-array)]
(String. (Hex/encodeHex b))))
(defn random-client
[]
(let [new-creds (user-creation/create-random-user
riak-cs-host-with-protocol
(get-riak-cs-port))]
(s3/client (:key_id new-creds)
(:key_secret new-creds)
{:proxy-host riak-cs-host
:proxy-port (get-riak-cs-port)
:protocol :http})))
(defmacro with-random-client
"Execute `form` with a random-client
bound to `var-name`"
[var-name form]
`(let [~var-name (random-client)]
~form))
(defn random-string []
(str (java.util.UUID/randomUUID)))
(fact "bogus creds raises an exception"
(let [bogus-client
(s3/client "foo"
"bar"
{:endpoint (str "http://localhost:"
(get-riak-cs-port-str))})]
(s3/list-buckets bogus-client))
=> (throws AmazonS3Exception))
(fact "new users have no buckets"
(with-random-client c
(s3/list-buckets c))
=> [])
(let [bucket-name (random-string)]
(fact "creating a bucket should list
one bucket in list buckets"
(with-random-client c
(do (s3/create-bucket c bucket-name)
((comp :name first) (s3/list-buckets c))))
=> bucket-name))
(let [bucket-name (random-string)
object-name (random-string)]
(fact "simple put works"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
"contents")))
=> truthy))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"]
(fact "the value received during GET is the same
as the object that was PUT"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp slurp :content) (s3/get-object c bucket-name object-name))))
=> value))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"
as-bytes (.getBytes value "UTF-8")
md5-sum (md5-string as-bytes)]
(fact "check that the etag of the response
is the same as the md5 of the original
object"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp :etag :metadata)
(s3/get-object
c bucket-name object-name))))
=> md5-sum))
|
56885
|
(comment
---------------------------------------------------------------------
Copyright (c) 2007-2013 Bash<NAME> Technologies, Inc. All Rights Reserved.
This file is provided to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---------------------------------------------------------------------
)
(ns java-s3-tests.test.client
(:import java.security.MessageDigest
org.apache.commons.codec.binary.Hex
com.amazonaws.services.s3.model.AmazonS3Exception
com.amazonaws.services.s3.model.ObjectMetadata)
(:require [aws.sdk.s3 :as s3])
(:require [java-s3-tests.user-creation :as user-creation])
(:use midje.sweet))
(def ^:internal riak-cs-host-with-protocol "http://localhost")
(def ^:internal riak-cs-host "localhost")
(defn get-riak-cs-port-str
"Try to get a TCP port number from the OS environment"
[]
(let [port-str (get (System/getenv) "CS_HTTP_PORT")]
(cond (nil? port-str) "8080"
:else port-str)))
(defn get-riak-cs-port []
(Integer/parseInt (get-riak-cs-port-str) 10))
(defn md5-byte-array [input-byte-array]
(let [instance (MessageDigest/getInstance "MD5")]
(.digest instance input-byte-array)))
(defn md5-string
[input-byte-array]
(let [b (md5-byte-array input-byte-array)]
(String. (Hex/encodeHex b))))
(defn random-client
[]
(let [new-creds (user-creation/create-random-user
riak-cs-host-with-protocol
(get-riak-cs-port))]
(s3/client (:key_id new-creds)
(:key_secret new-creds)
{:proxy-host riak-cs-host
:proxy-port (get-riak-cs-port)
:protocol :http})))
(defmacro with-random-client
"Execute `form` with a random-client
bound to `var-name`"
[var-name form]
`(let [~var-name (random-client)]
~form))
(defn random-string []
(str (java.util.UUID/randomUUID)))
(fact "bogus creds raises an exception"
(let [bogus-client
(s3/client "foo"
"bar"
{:endpoint (str "http://localhost:"
(get-riak-cs-port-str))})]
(s3/list-buckets bogus-client))
=> (throws AmazonS3Exception))
(fact "new users have no buckets"
(with-random-client c
(s3/list-buckets c))
=> [])
(let [bucket-name (random-string)]
(fact "creating a bucket should list
one bucket in list buckets"
(with-random-client c
(do (s3/create-bucket c bucket-name)
((comp :name first) (s3/list-buckets c))))
=> bucket-name))
(let [bucket-name (random-string)
object-name (random-string)]
(fact "simple put works"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
"contents")))
=> truthy))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"]
(fact "the value received during GET is the same
as the object that was PUT"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp slurp :content) (s3/get-object c bucket-name object-name))))
=> value))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"
as-bytes (.getBytes value "UTF-8")
md5-sum (md5-string as-bytes)]
(fact "check that the etag of the response
is the same as the md5 of the original
object"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp :etag :metadata)
(s3/get-object
c bucket-name object-name))))
=> md5-sum))
| true |
(comment
---------------------------------------------------------------------
Copyright (c) 2007-2013 BashPI:NAME:<NAME>END_PI Technologies, Inc. All Rights Reserved.
This file is provided to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---------------------------------------------------------------------
)
(ns java-s3-tests.test.client
(:import java.security.MessageDigest
org.apache.commons.codec.binary.Hex
com.amazonaws.services.s3.model.AmazonS3Exception
com.amazonaws.services.s3.model.ObjectMetadata)
(:require [aws.sdk.s3 :as s3])
(:require [java-s3-tests.user-creation :as user-creation])
(:use midje.sweet))
(def ^:internal riak-cs-host-with-protocol "http://localhost")
(def ^:internal riak-cs-host "localhost")
(defn get-riak-cs-port-str
"Try to get a TCP port number from the OS environment"
[]
(let [port-str (get (System/getenv) "CS_HTTP_PORT")]
(cond (nil? port-str) "8080"
:else port-str)))
(defn get-riak-cs-port []
(Integer/parseInt (get-riak-cs-port-str) 10))
(defn md5-byte-array [input-byte-array]
(let [instance (MessageDigest/getInstance "MD5")]
(.digest instance input-byte-array)))
(defn md5-string
[input-byte-array]
(let [b (md5-byte-array input-byte-array)]
(String. (Hex/encodeHex b))))
(defn random-client
[]
(let [new-creds (user-creation/create-random-user
riak-cs-host-with-protocol
(get-riak-cs-port))]
(s3/client (:key_id new-creds)
(:key_secret new-creds)
{:proxy-host riak-cs-host
:proxy-port (get-riak-cs-port)
:protocol :http})))
(defmacro with-random-client
"Execute `form` with a random-client
bound to `var-name`"
[var-name form]
`(let [~var-name (random-client)]
~form))
(defn random-string []
(str (java.util.UUID/randomUUID)))
(fact "bogus creds raises an exception"
(let [bogus-client
(s3/client "foo"
"bar"
{:endpoint (str "http://localhost:"
(get-riak-cs-port-str))})]
(s3/list-buckets bogus-client))
=> (throws AmazonS3Exception))
(fact "new users have no buckets"
(with-random-client c
(s3/list-buckets c))
=> [])
(let [bucket-name (random-string)]
(fact "creating a bucket should list
one bucket in list buckets"
(with-random-client c
(do (s3/create-bucket c bucket-name)
((comp :name first) (s3/list-buckets c))))
=> bucket-name))
(let [bucket-name (random-string)
object-name (random-string)]
(fact "simple put works"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
"contents")))
=> truthy))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"]
(fact "the value received during GET is the same
as the object that was PUT"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp slurp :content) (s3/get-object c bucket-name object-name))))
=> value))
(let [bucket-name (random-string)
object-name (random-string)
value "this is the value!"
as-bytes (.getBytes value "UTF-8")
md5-sum (md5-string as-bytes)]
(fact "check that the etag of the response
is the same as the md5 of the original
object"
(with-random-client c
(do (s3/create-bucket c bucket-name)
(s3/put-object c bucket-name object-name
value)
((comp :etag :metadata)
(s3/get-object
c bucket-name object-name))))
=> md5-sum))
|
[
{
"context": "\"https://unpkg.com/[email protected]\")\n [:title \"Lagosta\"]\n [:meta\n {:charset \"utf-8\",\n :na",
"end": 3403,
"score": 0.7551254034042358,
"start": 3396,
"tag": "NAME",
"value": "Lagosta"
}
] |
src/jcpsantiago/ui.clj
|
jcpsantiago/htmx-clj-dashboard
| 3 |
(ns jcpsantiago.ui
(:require
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.page :refer [html5 include-css include-js]]))
(defn spinner
"SVG spinner used as htmx-indicator
originally from https://samherbert.net/svg-loaders/"
[id size]
[:img {:id id
:src "/img/tail-spin.svg"
:class (str "w-" size " "
"h-" size " "
"mx-2 htmx-indicator")}])
(defn btn
"Active button"
[extra-attrs & elements]
(let [base-attrs {:class "items-center px-4 py-2 border border-transparent
rounded-md shadow text-sm font-medium text-white
bg-indigo-600 hover:bg-indigo-700 focus:outline-none
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(defn btn-disabled
"Disabled, greyed-out button with default non-interactive cursor"
[extra-attrs & elements]
(let [base-attrs {:disabled true
; FIXME use keywords too
:class "items-center px-4 py-2 border-2
rounded-md text-sm font-medium text-gray-500
border-gray-500 focus:outline-none cursor-default
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(def sm-container-css
"CSS to produce a content container with a slight drop shadow"
"px-4 py-3 rounded-md shadow bg-white")
(def main-container-css
"CSS for the container holding the main content"
"flex flex-col min-h-screen justify-between mx-20")
(def textinput-css
"CSS for a textarea input component"
"font-mono text-xs md:text-sm text-gray-50
w-full px-4 py-3 mt-2 rounded-md shadow bg-gray-700
border-gray-50
focus:outline-none focus:ring focus:border-indigo-300")
(defn compfn
"Skeleton for a component"
[html-tag-k css-classes extra-attrs & elements]
[html-tag-k
(conj {:class (->> (:class extra-attrs)
(str css-classes " "))}
extra-attrs)
elements])
(def sm-container (partial compfn :div sm-container-css))
(def main-container (partial compfn :div main-container-css))
(def textinput (partial compfn :input textinput-css))
(defn ex-form
"Example of a form using HTMX AJAX requests and server-side validation"
[]
[:form {:id "ex-form" :name "ex-form" :hx-post "/postit"
:hx-indicator "#indicator"}
(anti-forgery-field)
[:label {:class "text-md text-gray-500 mb-2"
:for "ex-text"}
"Type something👇 (only `this is not a test` will work)"]
(textinput {:id "ex-text" :name "ex-text" :hx-get "/validate" :hx-target "this"
:type "text"
:hx-swap "outerHTML" :hx-indicator "#indicator"})])
(defn common-header
"Creates the header seen in every page"
[& elements]
[:header {:class "my-5 mx-20"}
[:nav {:hx-boost "true"}
[:div {:class "flex-1 flex items-center justify-left"}
[:h1 {:class "font-mono 2xl text-indigo-500 mr-8"}
[:a {:href "/"} "Mighty dashboard 🦢"]]
elements]]])
(defn base-page
"Skeleton used for every page"
[header & elements]
(html5
{:class "" :lang "en"}
[:head
(include-css "https://unpkg.com/[email protected]/dist/tailwind.min.css")
(include-js "https://unpkg.com/[email protected]")
[:title "Lagosta"]
[:meta
{:charset "utf-8",
:name "viewport",
:content "width=device-width, initial-scale=1.0"}]]
[:body {:class "bg-gray-800"} ; FIXME should use actual dark mode from tailwind
header
[:main {:class "mb-auto"}
[:section
elements]]
[:footer {:class "mt-5"}
[:p {:class "text-gray-300 text-xs"} ""]]]))
|
69008
|
(ns jcpsantiago.ui
(:require
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.page :refer [html5 include-css include-js]]))
(defn spinner
"SVG spinner used as htmx-indicator
originally from https://samherbert.net/svg-loaders/"
[id size]
[:img {:id id
:src "/img/tail-spin.svg"
:class (str "w-" size " "
"h-" size " "
"mx-2 htmx-indicator")}])
(defn btn
"Active button"
[extra-attrs & elements]
(let [base-attrs {:class "items-center px-4 py-2 border border-transparent
rounded-md shadow text-sm font-medium text-white
bg-indigo-600 hover:bg-indigo-700 focus:outline-none
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(defn btn-disabled
"Disabled, greyed-out button with default non-interactive cursor"
[extra-attrs & elements]
(let [base-attrs {:disabled true
; FIXME use keywords too
:class "items-center px-4 py-2 border-2
rounded-md text-sm font-medium text-gray-500
border-gray-500 focus:outline-none cursor-default
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(def sm-container-css
"CSS to produce a content container with a slight drop shadow"
"px-4 py-3 rounded-md shadow bg-white")
(def main-container-css
"CSS for the container holding the main content"
"flex flex-col min-h-screen justify-between mx-20")
(def textinput-css
"CSS for a textarea input component"
"font-mono text-xs md:text-sm text-gray-50
w-full px-4 py-3 mt-2 rounded-md shadow bg-gray-700
border-gray-50
focus:outline-none focus:ring focus:border-indigo-300")
(defn compfn
"Skeleton for a component"
[html-tag-k css-classes extra-attrs & elements]
[html-tag-k
(conj {:class (->> (:class extra-attrs)
(str css-classes " "))}
extra-attrs)
elements])
(def sm-container (partial compfn :div sm-container-css))
(def main-container (partial compfn :div main-container-css))
(def textinput (partial compfn :input textinput-css))
(defn ex-form
"Example of a form using HTMX AJAX requests and server-side validation"
[]
[:form {:id "ex-form" :name "ex-form" :hx-post "/postit"
:hx-indicator "#indicator"}
(anti-forgery-field)
[:label {:class "text-md text-gray-500 mb-2"
:for "ex-text"}
"Type something👇 (only `this is not a test` will work)"]
(textinput {:id "ex-text" :name "ex-text" :hx-get "/validate" :hx-target "this"
:type "text"
:hx-swap "outerHTML" :hx-indicator "#indicator"})])
(defn common-header
"Creates the header seen in every page"
[& elements]
[:header {:class "my-5 mx-20"}
[:nav {:hx-boost "true"}
[:div {:class "flex-1 flex items-center justify-left"}
[:h1 {:class "font-mono 2xl text-indigo-500 mr-8"}
[:a {:href "/"} "Mighty dashboard 🦢"]]
elements]]])
(defn base-page
"Skeleton used for every page"
[header & elements]
(html5
{:class "" :lang "en"}
[:head
(include-css "https://unpkg.com/[email protected]/dist/tailwind.min.css")
(include-js "https://unpkg.com/[email protected]")
[:title "<NAME>"]
[:meta
{:charset "utf-8",
:name "viewport",
:content "width=device-width, initial-scale=1.0"}]]
[:body {:class "bg-gray-800"} ; FIXME should use actual dark mode from tailwind
header
[:main {:class "mb-auto"}
[:section
elements]]
[:footer {:class "mt-5"}
[:p {:class "text-gray-300 text-xs"} ""]]]))
| true |
(ns jcpsantiago.ui
(:require
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.page :refer [html5 include-css include-js]]))
(defn spinner
"SVG spinner used as htmx-indicator
originally from https://samherbert.net/svg-loaders/"
[id size]
[:img {:id id
:src "/img/tail-spin.svg"
:class (str "w-" size " "
"h-" size " "
"mx-2 htmx-indicator")}])
(defn btn
"Active button"
[extra-attrs & elements]
(let [base-attrs {:class "items-center px-4 py-2 border border-transparent
rounded-md shadow text-sm font-medium text-white
bg-indigo-600 hover:bg-indigo-700 focus:outline-none
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(defn btn-disabled
"Disabled, greyed-out button with default non-interactive cursor"
[extra-attrs & elements]
(let [base-attrs {:disabled true
; FIXME use keywords too
:class "items-center px-4 py-2 border-2
rounded-md text-sm font-medium text-gray-500
border-gray-500 focus:outline-none cursor-default
focus:ring-2 focus:ring-offset-2"}]
[:button (conj base-attrs extra-attrs) elements]))
(def sm-container-css
"CSS to produce a content container with a slight drop shadow"
"px-4 py-3 rounded-md shadow bg-white")
(def main-container-css
"CSS for the container holding the main content"
"flex flex-col min-h-screen justify-between mx-20")
(def textinput-css
"CSS for a textarea input component"
"font-mono text-xs md:text-sm text-gray-50
w-full px-4 py-3 mt-2 rounded-md shadow bg-gray-700
border-gray-50
focus:outline-none focus:ring focus:border-indigo-300")
(defn compfn
"Skeleton for a component"
[html-tag-k css-classes extra-attrs & elements]
[html-tag-k
(conj {:class (->> (:class extra-attrs)
(str css-classes " "))}
extra-attrs)
elements])
(def sm-container (partial compfn :div sm-container-css))
(def main-container (partial compfn :div main-container-css))
(def textinput (partial compfn :input textinput-css))
(defn ex-form
"Example of a form using HTMX AJAX requests and server-side validation"
[]
[:form {:id "ex-form" :name "ex-form" :hx-post "/postit"
:hx-indicator "#indicator"}
(anti-forgery-field)
[:label {:class "text-md text-gray-500 mb-2"
:for "ex-text"}
"Type something👇 (only `this is not a test` will work)"]
(textinput {:id "ex-text" :name "ex-text" :hx-get "/validate" :hx-target "this"
:type "text"
:hx-swap "outerHTML" :hx-indicator "#indicator"})])
(defn common-header
"Creates the header seen in every page"
[& elements]
[:header {:class "my-5 mx-20"}
[:nav {:hx-boost "true"}
[:div {:class "flex-1 flex items-center justify-left"}
[:h1 {:class "font-mono 2xl text-indigo-500 mr-8"}
[:a {:href "/"} "Mighty dashboard 🦢"]]
elements]]])
(defn base-page
"Skeleton used for every page"
[header & elements]
(html5
{:class "" :lang "en"}
[:head
(include-css "https://unpkg.com/[email protected]/dist/tailwind.min.css")
(include-js "https://unpkg.com/[email protected]")
[:title "PI:NAME:<NAME>END_PI"]
[:meta
{:charset "utf-8",
:name "viewport",
:content "width=device-width, initial-scale=1.0"}]]
[:body {:class "bg-gray-800"} ; FIXME should use actual dark mode from tailwind
header
[:main {:class "mb-auto"}
[:section
elements]]
[:footer {:class "mt-5"}
[:p {:class "text-gray-300 text-xs"} ""]]]))
|
[
{
"context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde",
"end": 31,
"score": 0.9997178316116333,
"start": 19,
"tag": "NAME",
"value": "Hirokuni Kim"
},
{
"context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses",
"end": 64,
"score": 0.9998739361763,
"start": 52,
"tag": "NAME",
"value": "Kevin Kredit"
}
] |
clojure/p09-if/src/p09_if/core.clj
|
kkredit/pl-study
| 0 |
;; Original author Hirokuni Kim
;; Modifications by Kevin Kredit
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#if
(ns p09-if.core)
(defn positive-number [numbers]
(if-let [pos-nums (not-empty (filter pos? numbers))]
pos-nums
"no positive numbers"))
(defn -main
"Main"
[]
(if true
(println "This branch is take if predicate evaluates to 'true'")
(println "This branch is take if predicate evaluates to 'false'"))
(if true
(do
(println "one")
(println "two")))
(println (positive-number [-1 -2 1 2]))
(println (positive-number [-1 -2]))
(println (boolean (filter pos? [-1])))
(println (not-empty [1 2]))
(println (not-empty []))
(when-let [pos-nums (filter pos? [ -1 -2 1 2])]
pos-nums
(println "one")
(println "two"))
)
|
98581
|
;; Original author <NAME>
;; Modifications by <NAME>
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#if
(ns p09-if.core)
(defn positive-number [numbers]
(if-let [pos-nums (not-empty (filter pos? numbers))]
pos-nums
"no positive numbers"))
(defn -main
"Main"
[]
(if true
(println "This branch is take if predicate evaluates to 'true'")
(println "This branch is take if predicate evaluates to 'false'"))
(if true
(do
(println "one")
(println "two")))
(println (positive-number [-1 -2 1 2]))
(println (positive-number [-1 -2]))
(println (boolean (filter pos? [-1])))
(println (not-empty [1 2]))
(println (not-empty []))
(when-let [pos-nums (filter pos? [ -1 -2 1 2])]
pos-nums
(println "one")
(println "two"))
)
| true |
;; Original author PI:NAME:<NAME>END_PI
;; Modifications by PI:NAME:<NAME>END_PI
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#if
(ns p09-if.core)
(defn positive-number [numbers]
(if-let [pos-nums (not-empty (filter pos? numbers))]
pos-nums
"no positive numbers"))
(defn -main
"Main"
[]
(if true
(println "This branch is take if predicate evaluates to 'true'")
(println "This branch is take if predicate evaluates to 'false'"))
(if true
(do
(println "one")
(println "two")))
(println (positive-number [-1 -2 1 2]))
(println (positive-number [-1 -2]))
(println (boolean (filter pos? [-1])))
(println (not-empty [1 2]))
(println (not-empty []))
(when-let [pos-nums (filter pos? [ -1 -2 1 2])]
pos-nums
(println "one")
(println "two"))
)
|
[
{
"context": "as q]\n [quil.middleware :as m]))\n\n; x = Asin(at + phi)\n; y = Bsin(bt)\n\n(def size 300)\n(def t-s",
"end": 98,
"score": 0.906277060508728,
"start": 94,
"tag": "NAME",
"value": "Asin"
},
{
"context": "il.middleware :as m]))\n\n; x = Asin(at + phi)\n; y = Bsin(bt)\n\n(def size 300)\n(def t-scale 100)\n(def lissaj",
"end": 119,
"score": 0.9198683500289917,
"start": 115,
"tag": "NAME",
"value": "Bsin"
}
] |
src/lissajous/core.clj
|
nathandao/lissajous
| 0 |
(ns lissajous.core
(:require [quil.core :as q]
[quil.middleware :as m]))
; x = Asin(at + phi)
; y = Bsin(bt)
(def size 300)
(def t-scale 100)
(def lissajous-box-size (/ size 2))
(def ds 0.1)
(def amp (/ size 4))
(def ch1 {:amp amp :freq 2.5})
(def ch2 {:amp amp :freq 3})
(def phi (q/radians 0))
(defn update-image []
(q/set-state! :image (create-image)))
(defn f-ch1 [t s]
(let [freq (:freq ch1)]
[(* s (/ size t-scale) 2)
(* (:amp ch1)
(q/sin (+ phi
(* (/ freq (* 2 Math/PI))
(+ s t)))))]))
(defn f-ch2 [t s]
(let [freq (:freq ch2)]
[(* (:amp ch2)
(q/sin (* (/ freq (* 2 Math/PI))
(+ (+ s t)))))
(* s (/ size t-scale) 2)]))
(defn f-lissajous [t]
[(* (:amp ch2)
(q/sin (* (/ (:freq ch2) (* 2 Math/PI)) t)))
(* (:amp ch1)
(q/sin (+ (* (/ (:freq ch1) (* 2 Math/PI)) t)
phi)))])
(defn draw-channel [f-ch t]
(doseq [s (range 0 t-scale ds)]
(q/line (f-ch t s)
(f-ch t (+ s ds)))))
(defn draw-lissajous-box [x]
(q/image (q/state :image) (- 0 (/ size 4)) (- 0 (/ size 4))))
(defn draw-lissajous [t]
(let [t0 (if (> (- t 10) 0) (- t 10) 0)
ly (second (f-lissajous (- t ds)))
lx (first (f-lissajous (- t ds)))
offset (- 0 (/ size 2))]
(draw-lissajous-box lissajous-box-size)
(q/stroke 255 220)
(q/stroke-weight 1)
(q/line [lx ly] [offset ly])
(q/line [lx ly] [lx offset])
(q/stroke 68 242 91)
(q/stroke-weight 12)
(q/point lx ly)
(doseq [s (range t0 t ds)]
(q/stroke-weight 2)
(q/stroke 68 242 91 (* 255 (/ (- s t0) 10)))
(q/line (f-lissajous s)
(f-lissajous (- s ds))))))
(defn draw []
(let [t (/ (q/frame-count) 5)]
(q/background 26 80 118)
(q/stroke 175 195 193)
(q/stroke-weight 2)
(q/with-translation [0 (/ (q/height) 2)]
(draw-channel f-ch1 t))
(q/with-translation [(/ (q/width) 2) 0]
(draw-channel f-ch2 t))
(q/with-translation [(/ (q/width) 2) (/ (q/height) 2)]
(draw-lissajous t))))
(defn create-image []
(let [width (* 2 amp)
im (q/create-image width width :rgb)]
(dotimes [x width]
(dotimes [y width]
(q/set-pixel im x y (q/color 26 80 118 230))))
(doseq [s (range 0 2000 0.1)]
(let [xy (f-lissajous s)]
(q/set-pixel im
(+ (first xy) (/ width 2))
(+ (second xy) (/ width 2))
(q/color 242 90 67))))
im))
(defn setup []
(q/set-state! :image (create-image))
(q/frame-rate 60))
(q/defsketch lissajous
:size [size size]
:setup setup
:draw draw)
|
87006
|
(ns lissajous.core
(:require [quil.core :as q]
[quil.middleware :as m]))
; x = <NAME>(at + phi)
; y = <NAME>(bt)
(def size 300)
(def t-scale 100)
(def lissajous-box-size (/ size 2))
(def ds 0.1)
(def amp (/ size 4))
(def ch1 {:amp amp :freq 2.5})
(def ch2 {:amp amp :freq 3})
(def phi (q/radians 0))
(defn update-image []
(q/set-state! :image (create-image)))
(defn f-ch1 [t s]
(let [freq (:freq ch1)]
[(* s (/ size t-scale) 2)
(* (:amp ch1)
(q/sin (+ phi
(* (/ freq (* 2 Math/PI))
(+ s t)))))]))
(defn f-ch2 [t s]
(let [freq (:freq ch2)]
[(* (:amp ch2)
(q/sin (* (/ freq (* 2 Math/PI))
(+ (+ s t)))))
(* s (/ size t-scale) 2)]))
(defn f-lissajous [t]
[(* (:amp ch2)
(q/sin (* (/ (:freq ch2) (* 2 Math/PI)) t)))
(* (:amp ch1)
(q/sin (+ (* (/ (:freq ch1) (* 2 Math/PI)) t)
phi)))])
(defn draw-channel [f-ch t]
(doseq [s (range 0 t-scale ds)]
(q/line (f-ch t s)
(f-ch t (+ s ds)))))
(defn draw-lissajous-box [x]
(q/image (q/state :image) (- 0 (/ size 4)) (- 0 (/ size 4))))
(defn draw-lissajous [t]
(let [t0 (if (> (- t 10) 0) (- t 10) 0)
ly (second (f-lissajous (- t ds)))
lx (first (f-lissajous (- t ds)))
offset (- 0 (/ size 2))]
(draw-lissajous-box lissajous-box-size)
(q/stroke 255 220)
(q/stroke-weight 1)
(q/line [lx ly] [offset ly])
(q/line [lx ly] [lx offset])
(q/stroke 68 242 91)
(q/stroke-weight 12)
(q/point lx ly)
(doseq [s (range t0 t ds)]
(q/stroke-weight 2)
(q/stroke 68 242 91 (* 255 (/ (- s t0) 10)))
(q/line (f-lissajous s)
(f-lissajous (- s ds))))))
(defn draw []
(let [t (/ (q/frame-count) 5)]
(q/background 26 80 118)
(q/stroke 175 195 193)
(q/stroke-weight 2)
(q/with-translation [0 (/ (q/height) 2)]
(draw-channel f-ch1 t))
(q/with-translation [(/ (q/width) 2) 0]
(draw-channel f-ch2 t))
(q/with-translation [(/ (q/width) 2) (/ (q/height) 2)]
(draw-lissajous t))))
(defn create-image []
(let [width (* 2 amp)
im (q/create-image width width :rgb)]
(dotimes [x width]
(dotimes [y width]
(q/set-pixel im x y (q/color 26 80 118 230))))
(doseq [s (range 0 2000 0.1)]
(let [xy (f-lissajous s)]
(q/set-pixel im
(+ (first xy) (/ width 2))
(+ (second xy) (/ width 2))
(q/color 242 90 67))))
im))
(defn setup []
(q/set-state! :image (create-image))
(q/frame-rate 60))
(q/defsketch lissajous
:size [size size]
:setup setup
:draw draw)
| true |
(ns lissajous.core
(:require [quil.core :as q]
[quil.middleware :as m]))
; x = PI:NAME:<NAME>END_PI(at + phi)
; y = PI:NAME:<NAME>END_PI(bt)
(def size 300)
(def t-scale 100)
(def lissajous-box-size (/ size 2))
(def ds 0.1)
(def amp (/ size 4))
(def ch1 {:amp amp :freq 2.5})
(def ch2 {:amp amp :freq 3})
(def phi (q/radians 0))
(defn update-image []
(q/set-state! :image (create-image)))
(defn f-ch1 [t s]
(let [freq (:freq ch1)]
[(* s (/ size t-scale) 2)
(* (:amp ch1)
(q/sin (+ phi
(* (/ freq (* 2 Math/PI))
(+ s t)))))]))
(defn f-ch2 [t s]
(let [freq (:freq ch2)]
[(* (:amp ch2)
(q/sin (* (/ freq (* 2 Math/PI))
(+ (+ s t)))))
(* s (/ size t-scale) 2)]))
(defn f-lissajous [t]
[(* (:amp ch2)
(q/sin (* (/ (:freq ch2) (* 2 Math/PI)) t)))
(* (:amp ch1)
(q/sin (+ (* (/ (:freq ch1) (* 2 Math/PI)) t)
phi)))])
(defn draw-channel [f-ch t]
(doseq [s (range 0 t-scale ds)]
(q/line (f-ch t s)
(f-ch t (+ s ds)))))
(defn draw-lissajous-box [x]
(q/image (q/state :image) (- 0 (/ size 4)) (- 0 (/ size 4))))
(defn draw-lissajous [t]
(let [t0 (if (> (- t 10) 0) (- t 10) 0)
ly (second (f-lissajous (- t ds)))
lx (first (f-lissajous (- t ds)))
offset (- 0 (/ size 2))]
(draw-lissajous-box lissajous-box-size)
(q/stroke 255 220)
(q/stroke-weight 1)
(q/line [lx ly] [offset ly])
(q/line [lx ly] [lx offset])
(q/stroke 68 242 91)
(q/stroke-weight 12)
(q/point lx ly)
(doseq [s (range t0 t ds)]
(q/stroke-weight 2)
(q/stroke 68 242 91 (* 255 (/ (- s t0) 10)))
(q/line (f-lissajous s)
(f-lissajous (- s ds))))))
(defn draw []
(let [t (/ (q/frame-count) 5)]
(q/background 26 80 118)
(q/stroke 175 195 193)
(q/stroke-weight 2)
(q/with-translation [0 (/ (q/height) 2)]
(draw-channel f-ch1 t))
(q/with-translation [(/ (q/width) 2) 0]
(draw-channel f-ch2 t))
(q/with-translation [(/ (q/width) 2) (/ (q/height) 2)]
(draw-lissajous t))))
(defn create-image []
(let [width (* 2 amp)
im (q/create-image width width :rgb)]
(dotimes [x width]
(dotimes [y width]
(q/set-pixel im x y (q/color 26 80 118 230))))
(doseq [s (range 0 2000 0.1)]
(let [xy (f-lissajous s)]
(q/set-pixel im
(+ (first xy) (/ width 2))
(+ (second xy) (/ width 2))
(q/color 242 90 67))))
im))
(defn setup []
(q/set-state! :image (create-image))
(q/frame-rate 60))
(q/defsketch lissajous
:size [size size]
:setup setup
:draw draw)
|
[
{
"context": "file\"\n (c/gen-config! {:var-a \"blah\" :var-b \"dave\"} [:var-a \"Var a description\" :var-b \"Var b de",
"end": 1105,
"score": 0.5985892415046692,
"start": 1104,
"tag": "NAME",
"value": "d"
}
] |
test/stonecutter/test/config.clj
|
d-cent/stonecutter
| 39 |
(ns stonecutter.test.config
(:require [midje.sweet :refer :all]
[stonecutter.config :as c]
[clojure.java.io :as io]))
(fact "get-env throws an exception when the requested key isn't in the env-vars set"
(c/get-env {:env-key "env-var"} :some-key-that-isnt-in-env-vars) => (throws Exception))
(tabular
(fact "secure? is true by default"
(c/secure? {:secure ?secure-env-value}) => ?return-value)
?secure-env-value ?return-value
"true" true
"asdf" true
"" true
nil true
"false" false)
(fact "about to-env"
(c/to-env :some-config) => "SOME_CONFIG")
(fact "can generate config line in file"
(c/gen-config-line {:some-config 1} [:some-config "This is a piece of config"])
=> "# This is a piece of config\nSOME_CONFIG=1"
(c/gen-config-line {:some-config 1} [:some-other-config "Some other description"])
=> "# Some other description\n# SOME_OTHER_CONFIG=")
(fact "can generate config file"
(c/gen-config! {:var-a "blah" :var-b "dave"} [:var-a "Var a description" :var-b "Var b description"] "test-resources/config.env")
(slurp "test-resources/config.env") => "# Var a description\nVAR_A=blah\n\n# Var b description\nVAR_B=dave"
(io/delete-file "test-resources/config.env"))
|
106806
|
(ns stonecutter.test.config
(:require [midje.sweet :refer :all]
[stonecutter.config :as c]
[clojure.java.io :as io]))
(fact "get-env throws an exception when the requested key isn't in the env-vars set"
(c/get-env {:env-key "env-var"} :some-key-that-isnt-in-env-vars) => (throws Exception))
(tabular
(fact "secure? is true by default"
(c/secure? {:secure ?secure-env-value}) => ?return-value)
?secure-env-value ?return-value
"true" true
"asdf" true
"" true
nil true
"false" false)
(fact "about to-env"
(c/to-env :some-config) => "SOME_CONFIG")
(fact "can generate config line in file"
(c/gen-config-line {:some-config 1} [:some-config "This is a piece of config"])
=> "# This is a piece of config\nSOME_CONFIG=1"
(c/gen-config-line {:some-config 1} [:some-other-config "Some other description"])
=> "# Some other description\n# SOME_OTHER_CONFIG=")
(fact "can generate config file"
(c/gen-config! {:var-a "blah" :var-b "<NAME>ave"} [:var-a "Var a description" :var-b "Var b description"] "test-resources/config.env")
(slurp "test-resources/config.env") => "# Var a description\nVAR_A=blah\n\n# Var b description\nVAR_B=dave"
(io/delete-file "test-resources/config.env"))
| true |
(ns stonecutter.test.config
(:require [midje.sweet :refer :all]
[stonecutter.config :as c]
[clojure.java.io :as io]))
(fact "get-env throws an exception when the requested key isn't in the env-vars set"
(c/get-env {:env-key "env-var"} :some-key-that-isnt-in-env-vars) => (throws Exception))
(tabular
(fact "secure? is true by default"
(c/secure? {:secure ?secure-env-value}) => ?return-value)
?secure-env-value ?return-value
"true" true
"asdf" true
"" true
nil true
"false" false)
(fact "about to-env"
(c/to-env :some-config) => "SOME_CONFIG")
(fact "can generate config line in file"
(c/gen-config-line {:some-config 1} [:some-config "This is a piece of config"])
=> "# This is a piece of config\nSOME_CONFIG=1"
(c/gen-config-line {:some-config 1} [:some-other-config "Some other description"])
=> "# Some other description\n# SOME_OTHER_CONFIG=")
(fact "can generate config file"
(c/gen-config! {:var-a "blah" :var-b "PI:NAME:<NAME>END_PIave"} [:var-a "Var a description" :var-b "Var b description"] "test-resources/config.env")
(slurp "test-resources/config.env") => "# Var a description\nVAR_A=blah\n\n# Var b description\nVAR_B=dave"
(io/delete-file "test-resources/config.env"))
|
[
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License",
"end": 49,
"score": 0.9998820424079895,
"start": 37,
"tag": "NAME",
"value": "Ronen Narkis"
},
{
"context": "omment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ",
"end": 62,
"score": 0.8712013363838196,
"start": 52,
"tag": "EMAIL",
"value": "arkisr.com"
}
] |
src/remote/ruby.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 remote.ruby
"A remoter that launches ruby script against an instance"
(:require
[clojure.core.strint :refer (<<)]
[slingshot.slingshot :refer [throw+]]
[clojure.java.shell :refer (with-sh-dir)]
[supernal.sshj :refer (copy sh- dest-path)]
[re-core.common :refer (import-logging gen-uuid interpulate)]
[me.raynes.fs :refer (delete-dir exists? mkdirs tmpdir)]
[re-core.core :refer (Remoter)]
[re-core.model :refer (rconstruct)])
)
(import-logging)
(defrecord Ruby [src args dst timeout]
Remoter
(setup [this]
(when (exists? (dest-path src dst))
(throw+ {:type ::old-code} "Old code found in place, cleanup first"))
(mkdirs dst)
(try
(sh- "ruby" "-v" {:dir dst})
(catch Throwable e
(throw+ {:type ::ruby-sanity-fail} "Failed to run ruby sanity step")))
(copy src dst {}))
(run [this]
(info (dest-path src dst))
(apply sh- "ruby" (conj args {:dir (dest-path src dst) :timeout timeout})))
(cleanup [this]
(delete-dir dst)))
(defmethod rconstruct :ruby [{:keys [src ruby name]:as action}
{:keys [env] :as run-info}]
(let [{:keys [args timeout]} (ruby env)]
(->Ruby src (mapv #(interpulate % run-info) args) (<< "~(tmpdir)/~(gen-uuid)/~{name}") timeout)))
|
103813
|
(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 remote.ruby
"A remoter that launches ruby script against an instance"
(:require
[clojure.core.strint :refer (<<)]
[slingshot.slingshot :refer [throw+]]
[clojure.java.shell :refer (with-sh-dir)]
[supernal.sshj :refer (copy sh- dest-path)]
[re-core.common :refer (import-logging gen-uuid interpulate)]
[me.raynes.fs :refer (delete-dir exists? mkdirs tmpdir)]
[re-core.core :refer (Remoter)]
[re-core.model :refer (rconstruct)])
)
(import-logging)
(defrecord Ruby [src args dst timeout]
Remoter
(setup [this]
(when (exists? (dest-path src dst))
(throw+ {:type ::old-code} "Old code found in place, cleanup first"))
(mkdirs dst)
(try
(sh- "ruby" "-v" {:dir dst})
(catch Throwable e
(throw+ {:type ::ruby-sanity-fail} "Failed to run ruby sanity step")))
(copy src dst {}))
(run [this]
(info (dest-path src dst))
(apply sh- "ruby" (conj args {:dir (dest-path src dst) :timeout timeout})))
(cleanup [this]
(delete-dir dst)))
(defmethod rconstruct :ruby [{:keys [src ruby name]:as action}
{:keys [env] :as run-info}]
(let [{:keys [args timeout]} (ruby env)]
(->Ruby src (mapv #(interpulate % run-info) args) (<< "~(tmpdir)/~(gen-uuid)/~{name}") timeout)))
| 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 remote.ruby
"A remoter that launches ruby script against an instance"
(:require
[clojure.core.strint :refer (<<)]
[slingshot.slingshot :refer [throw+]]
[clojure.java.shell :refer (with-sh-dir)]
[supernal.sshj :refer (copy sh- dest-path)]
[re-core.common :refer (import-logging gen-uuid interpulate)]
[me.raynes.fs :refer (delete-dir exists? mkdirs tmpdir)]
[re-core.core :refer (Remoter)]
[re-core.model :refer (rconstruct)])
)
(import-logging)
(defrecord Ruby [src args dst timeout]
Remoter
(setup [this]
(when (exists? (dest-path src dst))
(throw+ {:type ::old-code} "Old code found in place, cleanup first"))
(mkdirs dst)
(try
(sh- "ruby" "-v" {:dir dst})
(catch Throwable e
(throw+ {:type ::ruby-sanity-fail} "Failed to run ruby sanity step")))
(copy src dst {}))
(run [this]
(info (dest-path src dst))
(apply sh- "ruby" (conj args {:dir (dest-path src dst) :timeout timeout})))
(cleanup [this]
(delete-dir dst)))
(defmethod rconstruct :ruby [{:keys [src ruby name]:as action}
{:keys [env] :as run-info}]
(let [{:keys [args timeout]} (ruby env)]
(->Ruby src (mapv #(interpulate % run-info) args) (<< "~(tmpdir)/~(gen-uuid)/~{name}") timeout)))
|
[
{
"context": "ied from buddy\n\n(deftest pal-hashers\n (let [pwd \"my-test-password\"]\n (are [alg]\n (let [result (hashers/en",
"end": 292,
"score": 0.997409999370575,
"start": 276,
"tag": "PASSWORD",
"value": "my-test-password"
},
{
"context": "\n(deftest confirm-check-failure\n (let [pwd-good \"my-test-password\"\n pwd-bad \"my-text-password\"]\n (are [al",
"end": 533,
"score": 0.9965901374816895,
"start": 517,
"tag": "PASSWORD",
"value": "my-test-password"
},
{
"context": "let [pwd-good \"my-test-password\"\n pwd-bad \"my-text-password\"]\n (are [alg]\n (let [result (hashers/en",
"end": 568,
"score": 0.9958738088607788,
"start": 552,
"tag": "PASSWORD",
"value": "my-text-password"
},
{
"context": "ha384)))\n\n(deftest buddy-hashers-nil\n (let [pwd \"my-test-password\"\n result (hashers/encrypt pwd {:alg :bcryp",
"end": 815,
"score": 0.9973489046096802,
"start": 799,
"tag": "PASSWORD",
"value": "my-test-password"
},
{
"context": "\n(deftest algorithm-embedded-in-hash\n (let [pwd \"my-test-password\"]\n (are [alg]\n (-> (hashers/encrypt pwd",
"end": 1068,
"score": 0.9963719248771667,
"start": 1052,
"tag": "PASSWORD",
"value": "my-test-password"
},
{
"context": "ftest received-salt-embedded-in-hash\n (let [pwd \"my-test-password\"\n salt (nonce/random-bytes 16)]\n (are [",
"end": 1470,
"score": 0.998663604259491,
"start": 1454,
"tag": "PASSWORD",
"value": "my-test-password"
},
{
"context": "mit})))))\n\n(deftest debug-time-bench\n (let [pwd \"my-test-password\"]\n (are [alg]\n (do\n (println a",
"end": 2002,
"score": 0.9990200996398926,
"start": 1986,
"tag": "PASSWORD",
"value": "my-test-password"
}
] |
test/pal/hashers_test.cljs
|
leppert/pal-hashers
| 1 |
(ns pal.hashers-test
(:require [cljs.test :refer-macros [deftest testing is are]]
[pal.hashers :as hashers]
[pal.core.nonce :as nonce]
[pal.core.codecs :refer [bytes->hex]]))
;; tests copied from buddy
(deftest pal-hashers
(let [pwd "my-test-password"]
(are [alg]
(let [result (hashers/encrypt pwd {:alg alg})]
(hashers/check pwd result))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest confirm-check-failure
(let [pwd-good "my-test-password"
pwd-bad "my-text-password"]
(are [alg]
(let [result (hashers/encrypt pwd-good {:alg alg})]
(not (hashers/check pwd-bad result)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest buddy-hashers-nil
(let [pwd "my-test-password"
result (hashers/encrypt pwd {:alg :bcrypt+sha512})]
(is (nil? (hashers/check nil result)))
(is (nil? (hashers/check pwd nil)))
(is (nil? (hashers/check nil nil)))))
(deftest algorithm-embedded-in-hash
(let [pwd "my-test-password"]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg})
(.startsWith (name alg)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; Confirm that the algorithm used is always embedded at the
;; start of the hash, and that the salt is also appended (after
;; being converted to their byte values)
(deftest received-salt-embedded-in-hash
(let [pwd "my-test-password"
salt (nonce/random-bytes 16)]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg :salt salt})
(.startsWith (str (name alg) "$" (bytes->hex salt))))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest limit-available-algorithms
(let [pwd (hashers/encrypt "hello" {:alg :bcrypt+sha512})
limit #{:pbkdf2+sha256 :scrypt}]
(is (hashers/check "hello" pwd))
(is (not (hashers/check "hello" pwd {:limit limit})))))
(deftest debug-time-bench
(let [pwd "my-test-password"]
(are [alg]
(do
(println alg)
(time (hashers/encrypt pwd {:alg alg}))
true)
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; pal specific tests
(deftest pal-check-validates-buddy-hash
(are [hash] (= true (hashers/check "foobar" hash))
"pbkdf2+sha1$0102030405060708090a0b0c$100000$359a9b2a752425dd1042ab7a36f261f380ffb542"
"bcrypt+sha384$0102030405060708090a0b0c0d0e0f10$12$f56ffb6d2204d38ead28baedc7980ae0d86382713c14b68b"
"bcrypt+sha512$0102030405060708090a0b0c0d0e0f10$12$e74c3d09fadf982b6a3d5d7a704134339ed6aac45f640500"))
|
29853
|
(ns pal.hashers-test
(:require [cljs.test :refer-macros [deftest testing is are]]
[pal.hashers :as hashers]
[pal.core.nonce :as nonce]
[pal.core.codecs :refer [bytes->hex]]))
;; tests copied from buddy
(deftest pal-hashers
(let [pwd "<PASSWORD>"]
(are [alg]
(let [result (hashers/encrypt pwd {:alg alg})]
(hashers/check pwd result))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest confirm-check-failure
(let [pwd-good "<PASSWORD>"
pwd-bad "<PASSWORD>"]
(are [alg]
(let [result (hashers/encrypt pwd-good {:alg alg})]
(not (hashers/check pwd-bad result)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest buddy-hashers-nil
(let [pwd "<PASSWORD>"
result (hashers/encrypt pwd {:alg :bcrypt+sha512})]
(is (nil? (hashers/check nil result)))
(is (nil? (hashers/check pwd nil)))
(is (nil? (hashers/check nil nil)))))
(deftest algorithm-embedded-in-hash
(let [pwd "<PASSWORD>"]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg})
(.startsWith (name alg)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; Confirm that the algorithm used is always embedded at the
;; start of the hash, and that the salt is also appended (after
;; being converted to their byte values)
(deftest received-salt-embedded-in-hash
(let [pwd "<PASSWORD>"
salt (nonce/random-bytes 16)]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg :salt salt})
(.startsWith (str (name alg) "$" (bytes->hex salt))))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest limit-available-algorithms
(let [pwd (hashers/encrypt "hello" {:alg :bcrypt+sha512})
limit #{:pbkdf2+sha256 :scrypt}]
(is (hashers/check "hello" pwd))
(is (not (hashers/check "hello" pwd {:limit limit})))))
(deftest debug-time-bench
(let [pwd "<PASSWORD>"]
(are [alg]
(do
(println alg)
(time (hashers/encrypt pwd {:alg alg}))
true)
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; pal specific tests
(deftest pal-check-validates-buddy-hash
(are [hash] (= true (hashers/check "foobar" hash))
"pbkdf2+sha1$0102030405060708090a0b0c$100000$359a9b2a752425dd1042ab7a36f261f380ffb542"
"bcrypt+sha384$0102030405060708090a0b0c0d0e0f10$12$f56ffb6d2204d38ead28baedc7980ae0d86382713c14b68b"
"bcrypt+sha512$0102030405060708090a0b0c0d0e0f10$12$e74c3d09fadf982b6a3d5d7a704134339ed6aac45f640500"))
| true |
(ns pal.hashers-test
(:require [cljs.test :refer-macros [deftest testing is are]]
[pal.hashers :as hashers]
[pal.core.nonce :as nonce]
[pal.core.codecs :refer [bytes->hex]]))
;; tests copied from buddy
(deftest pal-hashers
(let [pwd "PI:PASSWORD:<PASSWORD>END_PI"]
(are [alg]
(let [result (hashers/encrypt pwd {:alg alg})]
(hashers/check pwd result))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest confirm-check-failure
(let [pwd-good "PI:PASSWORD:<PASSWORD>END_PI"
pwd-bad "PI:PASSWORD:<PASSWORD>END_PI"]
(are [alg]
(let [result (hashers/encrypt pwd-good {:alg alg})]
(not (hashers/check pwd-bad result)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest buddy-hashers-nil
(let [pwd "PI:PASSWORD:<PASSWORD>END_PI"
result (hashers/encrypt pwd {:alg :bcrypt+sha512})]
(is (nil? (hashers/check nil result)))
(is (nil? (hashers/check pwd nil)))
(is (nil? (hashers/check nil nil)))))
(deftest algorithm-embedded-in-hash
(let [pwd "PI:PASSWORD:<PASSWORD>END_PI"]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg})
(.startsWith (name alg)))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; Confirm that the algorithm used is always embedded at the
;; start of the hash, and that the salt is also appended (after
;; being converted to their byte values)
(deftest received-salt-embedded-in-hash
(let [pwd "PI:PASSWORD:<PASSWORD>END_PI"
salt (nonce/random-bytes 16)]
(are [alg]
(-> (hashers/encrypt pwd {:alg alg :salt salt})
(.startsWith (str (name alg) "$" (bytes->hex salt))))
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
(deftest limit-available-algorithms
(let [pwd (hashers/encrypt "hello" {:alg :bcrypt+sha512})
limit #{:pbkdf2+sha256 :scrypt}]
(is (hashers/check "hello" pwd))
(is (not (hashers/check "hello" pwd {:limit limit})))))
(deftest debug-time-bench
(let [pwd "PI:PASSWORD:<PASSWORD>END_PI"]
(are [alg]
(do
(println alg)
(time (hashers/encrypt pwd {:alg alg}))
true)
:pbkdf2+sha1
:bcrypt+sha512
:bcrypt+sha384)))
;; pal specific tests
(deftest pal-check-validates-buddy-hash
(are [hash] (= true (hashers/check "foobar" hash))
"pbkdf2+sha1$0102030405060708090a0b0c$100000$359a9b2a752425dd1042ab7a36f261f380ffb542"
"bcrypt+sha384$0102030405060708090a0b0c0d0e0f10$12$f56ffb6d2204d38ead28baedc7980ae0d86382713c14b68b"
"bcrypt+sha512$0102030405060708090a0b0c0d0e0f10$12$e74c3d09fadf982b6a3d5d7a704134339ed6aac45f640500"))
|
[
{
"context": " for building recurrent error maps.\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.core.data ACell\n ",
"end": 323,
"score": 0.9993088245391846,
"start": 310,
"tag": "NAME",
"value": "Adam Helinski"
}
] |
project/run/src/clj/main/convex/run/err.clj
|
rosejn/convex.cljc
| 30 |
(ns convex.run.err
"Errors are CVX maps, either mappified CVM exceptions or built from scratch.
Using [[convex.run.exec/fail]], they are reported back to the CVX executing environment
and can be handled from CVX.
This namespace provides functions for building recurrent error maps."
{:author "Adam Helinski"}
(:import (convex.core.data ACell
AMap)
(convex.core.lang.impl ErrorValue)
; (java.nio.file Files)
; (java.nio.file.attribute FileAttribute)
)
(:require [clojure.java.io]
[clojure.pprint]
[convex.cell :as $.cell]
[convex.run.kw :as $.run.kw]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Altering error maps
(defn assoc-phase
"Associates a `phase` to the given `err`.
A `phase` is a CVM keyword which provides an idea of what stage the error occured in."
^AMap
[^AMap err ^ACell phase]
(.assoc err
$.run.kw/phase
phase))
(defn assoc-trx
"Associates a transaction to the given `err` map. under `:trx`."
[^AMap err ^ACell trx]
(.assoc err
$.run.kw/trx
trx))
;;;;;;;;;; Creating error maps
(defn fatal
"Creates a `:FATAL` error map."
[message]
($.cell/error ($.cell/code-std* :FATAL)
message))
(defn mappify
"Transforms the given CVM exception into a map.
If prodived, associates to the resulting error map a [[phase]] and the current transaction that caused this error."
(^AMap [^ErrorValue ex]
($.cell/error (.getCode ex)
(.getMessage ex)
($.cell/vector (.getTrace ex))))
(^AMap [ex phase ^ACell trx]
(-> ex
mappify
(.assoc $.run.kw/trx
trx)
(assoc-phase phase))))
(defn reader
"Creates a `:READER` error map, for when the CVX reader fails."
^AMap
[]
($.cell/error $.run.kw/err-reader
($.cell/string "String cannot be read as Convex Lisp")))
(defn sreq
"Error map describing an error that occured when performing an operation for a request."
^AMap
[code message trx]
(-> ($.cell/error code
message)
(assoc-phase $.run.kw/sreq)
(assoc-trx trx)))
;;;;;;;;;; Fatal
; (defn report
;
; "Uses [[fail]] with `err` but associates to it a `:report` key pointing to a temp file
; where an EDN file has been written.
;
; This EDN file pretty-prints the given `env` with `ex` under `:convex.run/exception` (the Java exception
; that caused the failure).
;
; The error in Convex data under `:convex.run/error` is stringified for better readibility."
;
; [env ^AMap err ex]
;
; (let [path (str (Files/createTempFile "cvx_report_"
; ".edn"
; (make-array FileAttribute
; 0)))
; env-2 (fail env
; (.assoc err
; $.run.kw/report
; ($.cell/string path)))]
; (clojure.pprint/pprint (-> env-2
; (update :convex.run/error
; str)
; (assoc :convex.run/exception
; ex))
; (clojure.java.io/writer path))
; env-2))
|
112942
|
(ns convex.run.err
"Errors are CVX maps, either mappified CVM exceptions or built from scratch.
Using [[convex.run.exec/fail]], they are reported back to the CVX executing environment
and can be handled from CVX.
This namespace provides functions for building recurrent error maps."
{:author "<NAME>"}
(:import (convex.core.data ACell
AMap)
(convex.core.lang.impl ErrorValue)
; (java.nio.file Files)
; (java.nio.file.attribute FileAttribute)
)
(:require [clojure.java.io]
[clojure.pprint]
[convex.cell :as $.cell]
[convex.run.kw :as $.run.kw]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Altering error maps
(defn assoc-phase
"Associates a `phase` to the given `err`.
A `phase` is a CVM keyword which provides an idea of what stage the error occured in."
^AMap
[^AMap err ^ACell phase]
(.assoc err
$.run.kw/phase
phase))
(defn assoc-trx
"Associates a transaction to the given `err` map. under `:trx`."
[^AMap err ^ACell trx]
(.assoc err
$.run.kw/trx
trx))
;;;;;;;;;; Creating error maps
(defn fatal
"Creates a `:FATAL` error map."
[message]
($.cell/error ($.cell/code-std* :FATAL)
message))
(defn mappify
"Transforms the given CVM exception into a map.
If prodived, associates to the resulting error map a [[phase]] and the current transaction that caused this error."
(^AMap [^ErrorValue ex]
($.cell/error (.getCode ex)
(.getMessage ex)
($.cell/vector (.getTrace ex))))
(^AMap [ex phase ^ACell trx]
(-> ex
mappify
(.assoc $.run.kw/trx
trx)
(assoc-phase phase))))
(defn reader
"Creates a `:READER` error map, for when the CVX reader fails."
^AMap
[]
($.cell/error $.run.kw/err-reader
($.cell/string "String cannot be read as Convex Lisp")))
(defn sreq
"Error map describing an error that occured when performing an operation for a request."
^AMap
[code message trx]
(-> ($.cell/error code
message)
(assoc-phase $.run.kw/sreq)
(assoc-trx trx)))
;;;;;;;;;; Fatal
; (defn report
;
; "Uses [[fail]] with `err` but associates to it a `:report` key pointing to a temp file
; where an EDN file has been written.
;
; This EDN file pretty-prints the given `env` with `ex` under `:convex.run/exception` (the Java exception
; that caused the failure).
;
; The error in Convex data under `:convex.run/error` is stringified for better readibility."
;
; [env ^AMap err ex]
;
; (let [path (str (Files/createTempFile "cvx_report_"
; ".edn"
; (make-array FileAttribute
; 0)))
; env-2 (fail env
; (.assoc err
; $.run.kw/report
; ($.cell/string path)))]
; (clojure.pprint/pprint (-> env-2
; (update :convex.run/error
; str)
; (assoc :convex.run/exception
; ex))
; (clojure.java.io/writer path))
; env-2))
| true |
(ns convex.run.err
"Errors are CVX maps, either mappified CVM exceptions or built from scratch.
Using [[convex.run.exec/fail]], they are reported back to the CVX executing environment
and can be handled from CVX.
This namespace provides functions for building recurrent error maps."
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.core.data ACell
AMap)
(convex.core.lang.impl ErrorValue)
; (java.nio.file Files)
; (java.nio.file.attribute FileAttribute)
)
(:require [clojure.java.io]
[clojure.pprint]
[convex.cell :as $.cell]
[convex.run.kw :as $.run.kw]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Altering error maps
(defn assoc-phase
"Associates a `phase` to the given `err`.
A `phase` is a CVM keyword which provides an idea of what stage the error occured in."
^AMap
[^AMap err ^ACell phase]
(.assoc err
$.run.kw/phase
phase))
(defn assoc-trx
"Associates a transaction to the given `err` map. under `:trx`."
[^AMap err ^ACell trx]
(.assoc err
$.run.kw/trx
trx))
;;;;;;;;;; Creating error maps
(defn fatal
"Creates a `:FATAL` error map."
[message]
($.cell/error ($.cell/code-std* :FATAL)
message))
(defn mappify
"Transforms the given CVM exception into a map.
If prodived, associates to the resulting error map a [[phase]] and the current transaction that caused this error."
(^AMap [^ErrorValue ex]
($.cell/error (.getCode ex)
(.getMessage ex)
($.cell/vector (.getTrace ex))))
(^AMap [ex phase ^ACell trx]
(-> ex
mappify
(.assoc $.run.kw/trx
trx)
(assoc-phase phase))))
(defn reader
"Creates a `:READER` error map, for when the CVX reader fails."
^AMap
[]
($.cell/error $.run.kw/err-reader
($.cell/string "String cannot be read as Convex Lisp")))
(defn sreq
"Error map describing an error that occured when performing an operation for a request."
^AMap
[code message trx]
(-> ($.cell/error code
message)
(assoc-phase $.run.kw/sreq)
(assoc-trx trx)))
;;;;;;;;;; Fatal
; (defn report
;
; "Uses [[fail]] with `err` but associates to it a `:report` key pointing to a temp file
; where an EDN file has been written.
;
; This EDN file pretty-prints the given `env` with `ex` under `:convex.run/exception` (the Java exception
; that caused the failure).
;
; The error in Convex data under `:convex.run/error` is stringified for better readibility."
;
; [env ^AMap err ex]
;
; (let [path (str (Files/createTempFile "cvx_report_"
; ".edn"
; (make-array FileAttribute
; 0)))
; env-2 (fail env
; (.assoc err
; $.run.kw/report
; ($.cell/string path)))]
; (clojure.pprint/pprint (-> env-2
; (update :convex.run/error
; str)
; (assoc :convex.run/exception
; ex))
; (clojure.java.io/writer path))
; env-2))
|
[
{
"context": "quire [clojure.test :refer :all]))\n\n(def api-key \"sk_test_7GJV4OR48SPEoZgndbJjpU8s\")\n\n(def tokens\n {:valid-token \"",
"end": 116,
"score": 0.9986547827720642,
"start": 84,
"tag": "KEY",
"value": "sk_test_7GJV4OR48SPEoZgndbJjpU8s"
},
{
"context": "\n(def tokens\n {:valid-token \"tok_visa\"\n :three-d-secure-required \"tok_threeDSecu",
"end": 174,
"score": 0.7558928728103638,
"start": 170,
"tag": "PASSWORD",
"value": "visa"
}
] |
test/zebra/helpers/constants.clj
|
Global-Online-Health/zebra
| 5 |
(ns zebra.helpers.constants
(:require [clojure.test :refer :all]))
(def api-key "sk_test_7GJV4OR48SPEoZgndbJjpU8s")
(def tokens
{:valid-token "tok_visa"
:three-d-secure-required "tok_threeDSecureRequired"
:three-d-secure-not-supported "tok_amex_threeDSecureNotSupported"})
|
112297
|
(ns zebra.helpers.constants
(:require [clojure.test :refer :all]))
(def api-key "<KEY>")
(def tokens
{:valid-token "tok_<PASSWORD>"
:three-d-secure-required "tok_threeDSecureRequired"
:three-d-secure-not-supported "tok_amex_threeDSecureNotSupported"})
| true |
(ns zebra.helpers.constants
(:require [clojure.test :refer :all]))
(def api-key "PI:KEY:<KEY>END_PI")
(def tokens
{:valid-token "tok_PI:PASSWORD:<PASSWORD>END_PI"
:three-d-secure-required "tok_threeDSecureRequired"
:three-d-secure-not-supported "tok_amex_threeDSecureNotSupported"})
|
[
{
"context": "; Copyright (c) Rich Hickey, Reid Draper, and contributors.\n; All rights re",
"end": 29,
"score": 0.9998601675033569,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "; Copyright (c) Rich Hickey, Reid Draper, and contributors.\n; All rights reserved.\n; T",
"end": 42,
"score": 0.999868631362915,
"start": 31,
"tag": "NAME",
"value": "Reid Draper"
},
{
"context": "or any other, from this software.\n\n(ns ^{:author \"Gary Fredericks\"}\n clojure.test.check.random.doubles\n (:require",
"end": 529,
"score": 0.9998642802238464,
"start": 514,
"tag": "NAME",
"value": "Gary Fredericks"
}
] |
gh-pages/index.html.out/clojure/test/check/random/doubles.cljs
|
thedavidmeister/cljs-ntp
| 4 |
; Copyright (c) Rich Hickey, Reid Draper, and contributors.
; 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 "Gary Fredericks"}
clojure.test.check.random.doubles
(:require [clojure.test.check.random.longs :as longs]))
(def ^:private double-unit
(loop [i 53 x 1]
(if (zero? i)
x
(recur (dec i) (/ x 2)))))
(def ^:private big-double-unit
;; (* double-unit 0x100000000)
(* double-unit 4294967296))
(defn rand-long->rand-double
"Given a uniformly distributed random long, returns a uniformly
distributed double between 0.0 (inclusive) and 1.0 (exclusive)."
[long]
(let [x (longs/unsigned-bit-shift-right long 11)
low-bits (.getLowBitsUnsigned x)
high-bits (.getHighBits x)]
(+ (* double-unit low-bits)
(* big-double-unit high-bits))))
|
78499
|
; Copyright (c) <NAME>, <NAME>, and contributors.
; 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>"}
clojure.test.check.random.doubles
(:require [clojure.test.check.random.longs :as longs]))
(def ^:private double-unit
(loop [i 53 x 1]
(if (zero? i)
x
(recur (dec i) (/ x 2)))))
(def ^:private big-double-unit
;; (* double-unit 0x100000000)
(* double-unit 4294967296))
(defn rand-long->rand-double
"Given a uniformly distributed random long, returns a uniformly
distributed double between 0.0 (inclusive) and 1.0 (exclusive)."
[long]
(let [x (longs/unsigned-bit-shift-right long 11)
low-bits (.getLowBitsUnsigned x)
high-bits (.getHighBits x)]
(+ (* double-unit low-bits)
(* big-double-unit high-bits))))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and contributors.
; 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"}
clojure.test.check.random.doubles
(:require [clojure.test.check.random.longs :as longs]))
(def ^:private double-unit
(loop [i 53 x 1]
(if (zero? i)
x
(recur (dec i) (/ x 2)))))
(def ^:private big-double-unit
;; (* double-unit 0x100000000)
(* double-unit 4294967296))
(defn rand-long->rand-double
"Given a uniformly distributed random long, returns a uniformly
distributed double between 0.0 (inclusive) and 1.0 (exclusive)."
[long]
(let [x (longs/unsigned-bit-shift-right long 11)
low-bits (.getLowBitsUnsigned x)
high-bits (.getHighBits x)]
(+ (* double-unit low-bits)
(* big-double-unit high-bits))))
|
[
{
"context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998807311058044,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] |
src/territory_bro/json.clj
|
JessRoberts/territory_assistant
| 0 |
;; Copyright © 2015-2019 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.json
(:require [jsonista.core :as j])
(:import (com.fasterxml.jackson.databind ObjectMapper)))
(def ^ObjectMapper mapper
(j/object-mapper {:decode-key-fn true}))
(defn ^String generate-string [obj]
(j/write-value-as-string obj mapper))
(defn parse-string [^String json]
(j/read-value json mapper))
|
35311
|
;; Copyright © 2015-2019 <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.json
(:require [jsonista.core :as j])
(:import (com.fasterxml.jackson.databind ObjectMapper)))
(def ^ObjectMapper mapper
(j/object-mapper {:decode-key-fn true}))
(defn ^String generate-string [obj]
(j/write-value-as-string obj mapper))
(defn parse-string [^String json]
(j/read-value json mapper))
| true |
;; Copyright © 2015-2019 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.json
(:require [jsonista.core :as j])
(:import (com.fasterxml.jackson.databind ObjectMapper)))
(def ^ObjectMapper mapper
(j/object-mapper {:decode-key-fn true}))
(defn ^String generate-string [obj]
(j/write-value-as-string obj mapper))
(defn parse-string [^String json]
(j/read-value json mapper))
|
[
{
"context": "anipulating and testing sequences\"\n :author \"Sam Aaron\"}\n overtone.helpers.seq\n (:require [clojure.zip",
"end": 97,
"score": 0.9998886585235596,
"start": 88,
"tag": "NAME",
"value": "Sam Aaron"
}
] |
src/overtone/helpers/seq.clj
|
ABaldwinHunter/overtone
| 3,870 |
(ns
^{:doc "Helper functions for manipulating and testing sequences"
:author "Sam Aaron"}
overtone.helpers.seq
(:require [clojure.zip :as zip]))
(defn consecutive-ints?
"Checks whether seq s consists of consecutive integers
(consecutive-ints? [1 2 3 4 5]) ;=> true
(consecutive-ints? [1 2 3 5 4]) ;=> false"
[s]
(and
(sequential? s)
(every? integer? (seq s))
(apply = (map - (rest s) (seq s)))))
(defn indexed
"Takes a seq and returns a list of index val pairs for each successive val in
col. O(n) complexity. Prefer map-indexed or filter-indexed where possible."
[s]
(map-indexed (fn [i v] [i v]) s))
(defn index-of
"Return the index of item in seq."
[s item]
(first (first (filter (fn [[i v]]
(= v item))
(indexed s)))))
(defn mapply
"Takes a fn and a seq of seqs and returns a seq representing the application
of the fn on each sub-seq.
(mapply + [[1 2 3] [4 5 6] [7 8 9]]) ;=> [6 15 24]"
[f coll-coll]
(map #(apply f %) coll-coll))
(defn parallel-seqs
"takes n seqs and returns a seq of vectors of length n, lazily
(take 4 (parallel-seqs (repeat 5)
(cycle [1 2 3]))) => ([5 1] [5 2] [5 3] [5 1])"
[seqs]
(apply map vector seqs))
(defn find-first
"Finds first element of seq s for which pred returns true"
[pred s]
(first (filter pred s)))
(defn zipper-seq
"Returns a lazy sequence of a depth-first traversal of zipper z"
[z]
(lazy-seq
(when-not (zip/end? z)
(cons (zip/node z) (zipper-seq (zip/next z))))))
|
109150
|
(ns
^{:doc "Helper functions for manipulating and testing sequences"
:author "<NAME>"}
overtone.helpers.seq
(:require [clojure.zip :as zip]))
(defn consecutive-ints?
"Checks whether seq s consists of consecutive integers
(consecutive-ints? [1 2 3 4 5]) ;=> true
(consecutive-ints? [1 2 3 5 4]) ;=> false"
[s]
(and
(sequential? s)
(every? integer? (seq s))
(apply = (map - (rest s) (seq s)))))
(defn indexed
"Takes a seq and returns a list of index val pairs for each successive val in
col. O(n) complexity. Prefer map-indexed or filter-indexed where possible."
[s]
(map-indexed (fn [i v] [i v]) s))
(defn index-of
"Return the index of item in seq."
[s item]
(first (first (filter (fn [[i v]]
(= v item))
(indexed s)))))
(defn mapply
"Takes a fn and a seq of seqs and returns a seq representing the application
of the fn on each sub-seq.
(mapply + [[1 2 3] [4 5 6] [7 8 9]]) ;=> [6 15 24]"
[f coll-coll]
(map #(apply f %) coll-coll))
(defn parallel-seqs
"takes n seqs and returns a seq of vectors of length n, lazily
(take 4 (parallel-seqs (repeat 5)
(cycle [1 2 3]))) => ([5 1] [5 2] [5 3] [5 1])"
[seqs]
(apply map vector seqs))
(defn find-first
"Finds first element of seq s for which pred returns true"
[pred s]
(first (filter pred s)))
(defn zipper-seq
"Returns a lazy sequence of a depth-first traversal of zipper z"
[z]
(lazy-seq
(when-not (zip/end? z)
(cons (zip/node z) (zipper-seq (zip/next z))))))
| true |
(ns
^{:doc "Helper functions for manipulating and testing sequences"
:author "PI:NAME:<NAME>END_PI"}
overtone.helpers.seq
(:require [clojure.zip :as zip]))
(defn consecutive-ints?
"Checks whether seq s consists of consecutive integers
(consecutive-ints? [1 2 3 4 5]) ;=> true
(consecutive-ints? [1 2 3 5 4]) ;=> false"
[s]
(and
(sequential? s)
(every? integer? (seq s))
(apply = (map - (rest s) (seq s)))))
(defn indexed
"Takes a seq and returns a list of index val pairs for each successive val in
col. O(n) complexity. Prefer map-indexed or filter-indexed where possible."
[s]
(map-indexed (fn [i v] [i v]) s))
(defn index-of
"Return the index of item in seq."
[s item]
(first (first (filter (fn [[i v]]
(= v item))
(indexed s)))))
(defn mapply
"Takes a fn and a seq of seqs and returns a seq representing the application
of the fn on each sub-seq.
(mapply + [[1 2 3] [4 5 6] [7 8 9]]) ;=> [6 15 24]"
[f coll-coll]
(map #(apply f %) coll-coll))
(defn parallel-seqs
"takes n seqs and returns a seq of vectors of length n, lazily
(take 4 (parallel-seqs (repeat 5)
(cycle [1 2 3]))) => ([5 1] [5 2] [5 3] [5 1])"
[seqs]
(apply map vector seqs))
(defn find-first
"Finds first element of seq s for which pred returns true"
[pred s]
(first (filter pred s)))
(defn zipper-seq
"Returns a lazy sequence of a depth-first traversal of zipper z"
[z]
(lazy-seq
(when-not (zip/end? z)
(cons (zip/node z) (zipper-seq (zip/next z))))))
|
[
{
"context": " (is (nil? (<? (h/get-item! creds table {:name \"rofl\"}))))))))\n\n(deftest put+get\n (with-local-dynamo!",
"end": 1852,
"score": 0.8660544157028198,
"start": 1848,
"tag": "USERNAME",
"value": "rofl"
},
{
"context": "leeping}\n :bad \"good\"}\n {:nick [:set \"Rodrigo\"]\n :hobbies [:add #{\"dreaming\"}]\n :bad ",
"end": 5120,
"score": 0.9996710419654846,
"start": 5113,
"tag": "NAME",
"value": "Rodrigo"
},
{
"context": "dreaming\"}]\n :bad [:remove]}\n {:nick \"Rodrigo\"\n :hobbies #{:eating :sleeping :dreaming}}))\n\n",
"end": 5202,
"score": 0.999565064907074,
"start": 5195,
"tag": "NAME",
"value": "Rodrigo"
}
] |
test/hildebrand/test/core.cljc
|
nervous-systems/hildebrand
| 74 |
(ns hildebrand.test.core
(:require [clojure.walk :as walk]
[hildebrand.core :as h]
[glossop.util]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]
[hildebrand.test.common :as test.common
:refer [table create-table-default creds
namespaced-table create-table-namespaced
with-local-dynamo! with-remote-dynamo!]]
[#? (:clj clojure.core.async :cljs cljs.core.async) :as async]
[hildebrand.test.util
#? (:clj :refer :cljs :refer-macros) [deftest is]])
#? (:clj
(:import (clojure.lang ExceptionInfo))
:cljs
(:require-macros [hildebrand.test.core :refer [update-test]])))
(defn ba->seq [x]
#? (:clj
(seq x)
:cljs
(for [i (range (aget x "length"))]
(.readInt8 x i))))
(deftest binary-roundtrip
(with-local-dynamo!
(fn [creds]
(let [in #? (:clj
(.getBytes "\u00a5123Hello" "utf8")
:cljs
(js/Buffer. "\u00a5123Hello" "utf8"))]
(go-catching
(<? (h/put-item! creds table {:name "binary-roundtrip" :attr in}))
(is (= (ba->seq in)
(-> (h/get-item! creds table {:name "binary-roundtrip"})
<?
:attr
ba->seq))))))))
(def item {:name "Mephistopheles"})
(def namespaced-item {:namespaced/name "Mephistopheles"})
(deftest list-tables
(with-local-dynamo!
(fn [creds]
(go-catching
(let [tables (<? (h/list-tables! creds {:limit 1}))]
(is (= 1 (count tables)))
(is (-> tables meta :start-table)))))))
(deftest get+nonexistent
(with-local-dynamo!
(fn [creds]
(go-catching
(is (nil? (<? (h/get-item! creds table {:name "rofl"}))))))))
(deftest put+get
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/put-item! creds table (assoc item :age 33)))))
(is (= 33 (<? (h/get-item!
creds table item
{:consistent true}
{:chan (async/chan 1 (map :age))}))))))))
(deftest namespaced-put+get
(let [val (assoc namespaced-item :namespaced/age 33)]
(with-local-dynamo! {create-table-namespaced [val]}
(fn [creds]
(go-catching
(is (= val (<? (h/get-item! creds namespaced-table namespaced-item {:consistent true})))))))))
(deftest put+conditional
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= :conditional-failed
(try
(<? (h/put-item! creds table item {:when [:not-exists [:name]]}))
(catch #? (:clj ExceptionInfo :cljs js/Error) e
(-> e ex-data :type)))))))))
(deftest put+returning
(with-local-dynamo!
(fn [creds]
(go-catching
(let [item' (assoc item :old "put-returning")]
(is (empty? (<? (h/put-item! creds table item'))))
(is (= item' (<? (h/put-item! creds table item {:return :all-old})))))))))
(deftest put+meta
(with-remote-dynamo! [create-table-default]
(fn [creds]
(go-catching
(<? (h/put-item! creds table item {:capacity :total}))
(let [item (<? (h/put-item! creds table item
{:capacity :total :return :all-old}))]
(is (= table (-> item meta :capacity :table))))))))
(deftest delete
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (empty? (<? (h/delete-item! creds table item))))))))
(deftest delete+cc
(with-remote-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= table
(->
(h/delete-item! creds table item
{:capacity :total :return :all-old})
<?
meta
:capacity
:table)))))))
(deftest delete+expected-expr
(with-local-dynamo! {create-table-default
[(assoc item :age 33 :hobby "Strolling")]}
(fn [creds]
(go-catching
(is (empty?
(<? (h/delete-item!
creds table item
{:when
[:and
[:<= 30 ^:hildebrand/path [:age]]
[:<= [:age] 34]
[:in [:age] [30 33 34]]
[:not [:in [:age] #{30 34}]]
[:or
[:begins-with [:hobby] "St"]
[:begins-with [:hobby] "Tro"]]]}))))))))
(defn update-test [attrs-in updates attrs-out]
(let [keyed-item (merge item attrs-in)
exp (merge item attrs-out)]
(with-local-dynamo! {create-table-default [keyed-item]}
(fn [creds]
(go-catching
(is (= exp
(<? (h/update-item!
creds table item updates {:return :all-new})))))))))
(deftest update-item
(update-test
{:hobbies #{:eating :sleeping}
:bad "good"}
{:nick [:set "Rodrigo"]
:hobbies [:add #{"dreaming"}]
:bad [:remove]}
{:nick "Rodrigo"
:hobbies #{:eating :sleeping :dreaming}}))
(deftest update-item+list
(update-test
{:x [1 2 3]}
{:x [:append ["4"]]}
{:x [1 2 3 "4"]}))
(deftest update-item+concat
(update-test
{:x [1] :y #{1}}
{:x [:concat [2]] :y [:concat #{2}]}
{:x [1 2] :y #{1 2}}))
(deftest update-item+init
(update-test
{:y 5}
{:x [:init 6] :y [:init 1]}
{:y 5 :x 6}))
(deftest update-item+remove
(update-test
{:y 5 :z 5}
{:y [:remove] :z [:remove]}
{}))
(deftest update-item+nested-set
(update-test
{:a [:b]}
{:a {0 [:set "c"]}}
{:a ["c"]}))
(deftest update-item+deeply-nested-set
(update-test
{:a ["b" "c" {:d ["e"]}]}
{:a {2 {:d {0 [:set "f"]}}}}
{:a ["b" "c" {:d ["f"]}]}))
(deftest update-item+nested-init
(update-test
{:a {:b "c"}}
{:a {:b [:init "d"] :B [:init "D"]}}
{:a {:b "c" :B "D"}}))
(deftest update-item+nested-append
(update-test
{:a {:b [["c"]]}}
{:a {:b {0 [:concat ["d"]]}}}
{:a {:b [["c" "d"]]}}))
(deftest update-item+nested-remove
(update-test
{:a {:b [{:c :d}]}}
{:a {:b {0 [:remove]}}}
{:a {:b []}}))
(deftest update-item+inc+dec
(update-test
{:a 5 :b 4}
{:a [:inc 4]
:b [:dec 4]}
{:a 9 :b 0}))
(deftest update-item+nested-reserved-names
(update-test
{:deterministic {:except {:for "deterministic,"}}}
{:deterministic {:except {:for [:set "deterministic!"]}}}
{:deterministic {:except {:for "deterministic!"}}}))
(deftest update-item+refer
(update-test
{:please {:init "ialize"} :me ", boss!"}
{:please
{:init [:set (with-meta [:me] {:hildebrand/path true})]}
:and [:init (with-meta [:me] {:hildebrand/path true})]}
{:please {:init ", boss!"} :and ", boss!" :me ", boss!"}))
(deftest update-item+nested-refer
(update-test
{:irish {:set ["ter, "]} :norfolk "terrier"}
{:norfolk [:set (with-meta [:irish :set 0] {:hildebrand/path true})]}
{:irish {:set ["ter, "]} :norfolk "ter, "}))
(def items
(for [i (range 5)]
(assoc item :name (str "batch-write-" i))))
(deftest batch-write
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/batch-write-item! creds {:put {table items}}))))))))
(deftest batch-write+get
(with-local-dynamo!
(fn [creds]
(go-catching
(<? (h/batch-write-item! creds {:put {table items}}))
(let [responses
(<? (h/batch-get-item!
creds {table {:consistent true :keys items}}))]
(is (= (into #{} items)
(into #{} (responses table)))))))))
(deftest query
(with-local-dynamo! {create-table-default [{:name "Mephistopheles"}]}
(fn [creds]
(go-catching
(is (= [{:name "Mephistopheles"}]
(map #(select-keys % #{:name})
(<? (h/query! creds table
{:name [:= "Mephistopheles"]})))))))))
(def ->game-item (partial zipmap [:user-id :game-title :timestamp :data]))
(def indexed-items
(map ->game-item
[["moe" "Super Metroid" 1 "great"]
["moe" "Wii Fit" 2]]))
(deftest query+local-index
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"] :timestamp [:< 2]}
{:index test.common/local-index}))))))))
(deftest query+filter
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"]}
{:filter [:< [:timestamp] 2]}))))))))
(deftest scan
(let [items (for [i (range 5)]
{:name (str "scan-test-" i)
:religion "scan-test"})]
(with-local-dynamo! {create-table-default items}
(fn [creds]
(go-catching
(is (= (into #{} items)
(into #{} (<? (h/scan! creds table
{:filter [:= [:religion] "scan-test"]}))))))))))
|
70353
|
(ns hildebrand.test.core
(:require [clojure.walk :as walk]
[hildebrand.core :as h]
[glossop.util]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]
[hildebrand.test.common :as test.common
:refer [table create-table-default creds
namespaced-table create-table-namespaced
with-local-dynamo! with-remote-dynamo!]]
[#? (:clj clojure.core.async :cljs cljs.core.async) :as async]
[hildebrand.test.util
#? (:clj :refer :cljs :refer-macros) [deftest is]])
#? (:clj
(:import (clojure.lang ExceptionInfo))
:cljs
(:require-macros [hildebrand.test.core :refer [update-test]])))
(defn ba->seq [x]
#? (:clj
(seq x)
:cljs
(for [i (range (aget x "length"))]
(.readInt8 x i))))
(deftest binary-roundtrip
(with-local-dynamo!
(fn [creds]
(let [in #? (:clj
(.getBytes "\u00a5123Hello" "utf8")
:cljs
(js/Buffer. "\u00a5123Hello" "utf8"))]
(go-catching
(<? (h/put-item! creds table {:name "binary-roundtrip" :attr in}))
(is (= (ba->seq in)
(-> (h/get-item! creds table {:name "binary-roundtrip"})
<?
:attr
ba->seq))))))))
(def item {:name "Mephistopheles"})
(def namespaced-item {:namespaced/name "Mephistopheles"})
(deftest list-tables
(with-local-dynamo!
(fn [creds]
(go-catching
(let [tables (<? (h/list-tables! creds {:limit 1}))]
(is (= 1 (count tables)))
(is (-> tables meta :start-table)))))))
(deftest get+nonexistent
(with-local-dynamo!
(fn [creds]
(go-catching
(is (nil? (<? (h/get-item! creds table {:name "rofl"}))))))))
(deftest put+get
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/put-item! creds table (assoc item :age 33)))))
(is (= 33 (<? (h/get-item!
creds table item
{:consistent true}
{:chan (async/chan 1 (map :age))}))))))))
(deftest namespaced-put+get
(let [val (assoc namespaced-item :namespaced/age 33)]
(with-local-dynamo! {create-table-namespaced [val]}
(fn [creds]
(go-catching
(is (= val (<? (h/get-item! creds namespaced-table namespaced-item {:consistent true})))))))))
(deftest put+conditional
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= :conditional-failed
(try
(<? (h/put-item! creds table item {:when [:not-exists [:name]]}))
(catch #? (:clj ExceptionInfo :cljs js/Error) e
(-> e ex-data :type)))))))))
(deftest put+returning
(with-local-dynamo!
(fn [creds]
(go-catching
(let [item' (assoc item :old "put-returning")]
(is (empty? (<? (h/put-item! creds table item'))))
(is (= item' (<? (h/put-item! creds table item {:return :all-old})))))))))
(deftest put+meta
(with-remote-dynamo! [create-table-default]
(fn [creds]
(go-catching
(<? (h/put-item! creds table item {:capacity :total}))
(let [item (<? (h/put-item! creds table item
{:capacity :total :return :all-old}))]
(is (= table (-> item meta :capacity :table))))))))
(deftest delete
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (empty? (<? (h/delete-item! creds table item))))))))
(deftest delete+cc
(with-remote-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= table
(->
(h/delete-item! creds table item
{:capacity :total :return :all-old})
<?
meta
:capacity
:table)))))))
(deftest delete+expected-expr
(with-local-dynamo! {create-table-default
[(assoc item :age 33 :hobby "Strolling")]}
(fn [creds]
(go-catching
(is (empty?
(<? (h/delete-item!
creds table item
{:when
[:and
[:<= 30 ^:hildebrand/path [:age]]
[:<= [:age] 34]
[:in [:age] [30 33 34]]
[:not [:in [:age] #{30 34}]]
[:or
[:begins-with [:hobby] "St"]
[:begins-with [:hobby] "Tro"]]]}))))))))
(defn update-test [attrs-in updates attrs-out]
(let [keyed-item (merge item attrs-in)
exp (merge item attrs-out)]
(with-local-dynamo! {create-table-default [keyed-item]}
(fn [creds]
(go-catching
(is (= exp
(<? (h/update-item!
creds table item updates {:return :all-new})))))))))
(deftest update-item
(update-test
{:hobbies #{:eating :sleeping}
:bad "good"}
{:nick [:set "<NAME>"]
:hobbies [:add #{"dreaming"}]
:bad [:remove]}
{:nick "<NAME>"
:hobbies #{:eating :sleeping :dreaming}}))
(deftest update-item+list
(update-test
{:x [1 2 3]}
{:x [:append ["4"]]}
{:x [1 2 3 "4"]}))
(deftest update-item+concat
(update-test
{:x [1] :y #{1}}
{:x [:concat [2]] :y [:concat #{2}]}
{:x [1 2] :y #{1 2}}))
(deftest update-item+init
(update-test
{:y 5}
{:x [:init 6] :y [:init 1]}
{:y 5 :x 6}))
(deftest update-item+remove
(update-test
{:y 5 :z 5}
{:y [:remove] :z [:remove]}
{}))
(deftest update-item+nested-set
(update-test
{:a [:b]}
{:a {0 [:set "c"]}}
{:a ["c"]}))
(deftest update-item+deeply-nested-set
(update-test
{:a ["b" "c" {:d ["e"]}]}
{:a {2 {:d {0 [:set "f"]}}}}
{:a ["b" "c" {:d ["f"]}]}))
(deftest update-item+nested-init
(update-test
{:a {:b "c"}}
{:a {:b [:init "d"] :B [:init "D"]}}
{:a {:b "c" :B "D"}}))
(deftest update-item+nested-append
(update-test
{:a {:b [["c"]]}}
{:a {:b {0 [:concat ["d"]]}}}
{:a {:b [["c" "d"]]}}))
(deftest update-item+nested-remove
(update-test
{:a {:b [{:c :d}]}}
{:a {:b {0 [:remove]}}}
{:a {:b []}}))
(deftest update-item+inc+dec
(update-test
{:a 5 :b 4}
{:a [:inc 4]
:b [:dec 4]}
{:a 9 :b 0}))
(deftest update-item+nested-reserved-names
(update-test
{:deterministic {:except {:for "deterministic,"}}}
{:deterministic {:except {:for [:set "deterministic!"]}}}
{:deterministic {:except {:for "deterministic!"}}}))
(deftest update-item+refer
(update-test
{:please {:init "ialize"} :me ", boss!"}
{:please
{:init [:set (with-meta [:me] {:hildebrand/path true})]}
:and [:init (with-meta [:me] {:hildebrand/path true})]}
{:please {:init ", boss!"} :and ", boss!" :me ", boss!"}))
(deftest update-item+nested-refer
(update-test
{:irish {:set ["ter, "]} :norfolk "terrier"}
{:norfolk [:set (with-meta [:irish :set 0] {:hildebrand/path true})]}
{:irish {:set ["ter, "]} :norfolk "ter, "}))
(def items
(for [i (range 5)]
(assoc item :name (str "batch-write-" i))))
(deftest batch-write
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/batch-write-item! creds {:put {table items}}))))))))
(deftest batch-write+get
(with-local-dynamo!
(fn [creds]
(go-catching
(<? (h/batch-write-item! creds {:put {table items}}))
(let [responses
(<? (h/batch-get-item!
creds {table {:consistent true :keys items}}))]
(is (= (into #{} items)
(into #{} (responses table)))))))))
(deftest query
(with-local-dynamo! {create-table-default [{:name "Mephistopheles"}]}
(fn [creds]
(go-catching
(is (= [{:name "Mephistopheles"}]
(map #(select-keys % #{:name})
(<? (h/query! creds table
{:name [:= "Mephistopheles"]})))))))))
(def ->game-item (partial zipmap [:user-id :game-title :timestamp :data]))
(def indexed-items
(map ->game-item
[["moe" "Super Metroid" 1 "great"]
["moe" "Wii Fit" 2]]))
(deftest query+local-index
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"] :timestamp [:< 2]}
{:index test.common/local-index}))))))))
(deftest query+filter
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"]}
{:filter [:< [:timestamp] 2]}))))))))
(deftest scan
(let [items (for [i (range 5)]
{:name (str "scan-test-" i)
:religion "scan-test"})]
(with-local-dynamo! {create-table-default items}
(fn [creds]
(go-catching
(is (= (into #{} items)
(into #{} (<? (h/scan! creds table
{:filter [:= [:religion] "scan-test"]}))))))))))
| true |
(ns hildebrand.test.core
(:require [clojure.walk :as walk]
[hildebrand.core :as h]
[glossop.util]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]
[hildebrand.test.common :as test.common
:refer [table create-table-default creds
namespaced-table create-table-namespaced
with-local-dynamo! with-remote-dynamo!]]
[#? (:clj clojure.core.async :cljs cljs.core.async) :as async]
[hildebrand.test.util
#? (:clj :refer :cljs :refer-macros) [deftest is]])
#? (:clj
(:import (clojure.lang ExceptionInfo))
:cljs
(:require-macros [hildebrand.test.core :refer [update-test]])))
(defn ba->seq [x]
#? (:clj
(seq x)
:cljs
(for [i (range (aget x "length"))]
(.readInt8 x i))))
(deftest binary-roundtrip
(with-local-dynamo!
(fn [creds]
(let [in #? (:clj
(.getBytes "\u00a5123Hello" "utf8")
:cljs
(js/Buffer. "\u00a5123Hello" "utf8"))]
(go-catching
(<? (h/put-item! creds table {:name "binary-roundtrip" :attr in}))
(is (= (ba->seq in)
(-> (h/get-item! creds table {:name "binary-roundtrip"})
<?
:attr
ba->seq))))))))
(def item {:name "Mephistopheles"})
(def namespaced-item {:namespaced/name "Mephistopheles"})
(deftest list-tables
(with-local-dynamo!
(fn [creds]
(go-catching
(let [tables (<? (h/list-tables! creds {:limit 1}))]
(is (= 1 (count tables)))
(is (-> tables meta :start-table)))))))
(deftest get+nonexistent
(with-local-dynamo!
(fn [creds]
(go-catching
(is (nil? (<? (h/get-item! creds table {:name "rofl"}))))))))
(deftest put+get
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/put-item! creds table (assoc item :age 33)))))
(is (= 33 (<? (h/get-item!
creds table item
{:consistent true}
{:chan (async/chan 1 (map :age))}))))))))
(deftest namespaced-put+get
(let [val (assoc namespaced-item :namespaced/age 33)]
(with-local-dynamo! {create-table-namespaced [val]}
(fn [creds]
(go-catching
(is (= val (<? (h/get-item! creds namespaced-table namespaced-item {:consistent true})))))))))
(deftest put+conditional
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= :conditional-failed
(try
(<? (h/put-item! creds table item {:when [:not-exists [:name]]}))
(catch #? (:clj ExceptionInfo :cljs js/Error) e
(-> e ex-data :type)))))))))
(deftest put+returning
(with-local-dynamo!
(fn [creds]
(go-catching
(let [item' (assoc item :old "put-returning")]
(is (empty? (<? (h/put-item! creds table item'))))
(is (= item' (<? (h/put-item! creds table item {:return :all-old})))))))))
(deftest put+meta
(with-remote-dynamo! [create-table-default]
(fn [creds]
(go-catching
(<? (h/put-item! creds table item {:capacity :total}))
(let [item (<? (h/put-item! creds table item
{:capacity :total :return :all-old}))]
(is (= table (-> item meta :capacity :table))))))))
(deftest delete
(with-local-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (empty? (<? (h/delete-item! creds table item))))))))
(deftest delete+cc
(with-remote-dynamo! {create-table-default [item]}
(fn [creds]
(go-catching
(is (= table
(->
(h/delete-item! creds table item
{:capacity :total :return :all-old})
<?
meta
:capacity
:table)))))))
(deftest delete+expected-expr
(with-local-dynamo! {create-table-default
[(assoc item :age 33 :hobby "Strolling")]}
(fn [creds]
(go-catching
(is (empty?
(<? (h/delete-item!
creds table item
{:when
[:and
[:<= 30 ^:hildebrand/path [:age]]
[:<= [:age] 34]
[:in [:age] [30 33 34]]
[:not [:in [:age] #{30 34}]]
[:or
[:begins-with [:hobby] "St"]
[:begins-with [:hobby] "Tro"]]]}))))))))
(defn update-test [attrs-in updates attrs-out]
(let [keyed-item (merge item attrs-in)
exp (merge item attrs-out)]
(with-local-dynamo! {create-table-default [keyed-item]}
(fn [creds]
(go-catching
(is (= exp
(<? (h/update-item!
creds table item updates {:return :all-new})))))))))
(deftest update-item
(update-test
{:hobbies #{:eating :sleeping}
:bad "good"}
{:nick [:set "PI:NAME:<NAME>END_PI"]
:hobbies [:add #{"dreaming"}]
:bad [:remove]}
{:nick "PI:NAME:<NAME>END_PI"
:hobbies #{:eating :sleeping :dreaming}}))
(deftest update-item+list
(update-test
{:x [1 2 3]}
{:x [:append ["4"]]}
{:x [1 2 3 "4"]}))
(deftest update-item+concat
(update-test
{:x [1] :y #{1}}
{:x [:concat [2]] :y [:concat #{2}]}
{:x [1 2] :y #{1 2}}))
(deftest update-item+init
(update-test
{:y 5}
{:x [:init 6] :y [:init 1]}
{:y 5 :x 6}))
(deftest update-item+remove
(update-test
{:y 5 :z 5}
{:y [:remove] :z [:remove]}
{}))
(deftest update-item+nested-set
(update-test
{:a [:b]}
{:a {0 [:set "c"]}}
{:a ["c"]}))
(deftest update-item+deeply-nested-set
(update-test
{:a ["b" "c" {:d ["e"]}]}
{:a {2 {:d {0 [:set "f"]}}}}
{:a ["b" "c" {:d ["f"]}]}))
(deftest update-item+nested-init
(update-test
{:a {:b "c"}}
{:a {:b [:init "d"] :B [:init "D"]}}
{:a {:b "c" :B "D"}}))
(deftest update-item+nested-append
(update-test
{:a {:b [["c"]]}}
{:a {:b {0 [:concat ["d"]]}}}
{:a {:b [["c" "d"]]}}))
(deftest update-item+nested-remove
(update-test
{:a {:b [{:c :d}]}}
{:a {:b {0 [:remove]}}}
{:a {:b []}}))
(deftest update-item+inc+dec
(update-test
{:a 5 :b 4}
{:a [:inc 4]
:b [:dec 4]}
{:a 9 :b 0}))
(deftest update-item+nested-reserved-names
(update-test
{:deterministic {:except {:for "deterministic,"}}}
{:deterministic {:except {:for [:set "deterministic!"]}}}
{:deterministic {:except {:for "deterministic!"}}}))
(deftest update-item+refer
(update-test
{:please {:init "ialize"} :me ", boss!"}
{:please
{:init [:set (with-meta [:me] {:hildebrand/path true})]}
:and [:init (with-meta [:me] {:hildebrand/path true})]}
{:please {:init ", boss!"} :and ", boss!" :me ", boss!"}))
(deftest update-item+nested-refer
(update-test
{:irish {:set ["ter, "]} :norfolk "terrier"}
{:norfolk [:set (with-meta [:irish :set 0] {:hildebrand/path true})]}
{:irish {:set ["ter, "]} :norfolk "ter, "}))
(def items
(for [i (range 5)]
(assoc item :name (str "batch-write-" i))))
(deftest batch-write
(with-local-dynamo!
(fn [creds]
(go-catching
(is (empty? (<? (h/batch-write-item! creds {:put {table items}}))))))))
(deftest batch-write+get
(with-local-dynamo!
(fn [creds]
(go-catching
(<? (h/batch-write-item! creds {:put {table items}}))
(let [responses
(<? (h/batch-get-item!
creds {table {:consistent true :keys items}}))]
(is (= (into #{} items)
(into #{} (responses table)))))))))
(deftest query
(with-local-dynamo! {create-table-default [{:name "Mephistopheles"}]}
(fn [creds]
(go-catching
(is (= [{:name "Mephistopheles"}]
(map #(select-keys % #{:name})
(<? (h/query! creds table
{:name [:= "Mephistopheles"]})))))))))
(def ->game-item (partial zipmap [:user-id :game-title :timestamp :data]))
(def indexed-items
(map ->game-item
[["moe" "Super Metroid" 1 "great"]
["moe" "Wii Fit" 2]]))
(deftest query+local-index
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"] :timestamp [:< 2]}
{:index test.common/local-index}))))))))
(deftest query+filter
(with-local-dynamo! {test.common/create-table-indexed indexed-items}
(fn [creds]
(go-catching
(is (= [(first indexed-items)]
(<? (h/query!
creds
test.common/indexed-table
{:user-id [:= "moe"]}
{:filter [:< [:timestamp] 2]}))))))))
(deftest scan
(let [items (for [i (range 5)]
{:name (str "scan-test-" i)
:religion "scan-test"})]
(with-local-dynamo! {create-table-default items}
(fn [creds]
(go-catching
(is (= (into #{} items)
(into #{} (<? (h/scan! creds table
{:filter [:= [:religion] "scan-test"]}))))))))))
|
[
{
"context": "ue})\n\n(def flat-app-state (atom {:a 1 :user/name \"Sam\" :c 99}))\n\n(defn flat-state-read [{:keys [state p",
"end": 16770,
"score": 0.9331925511360168,
"start": 16767,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (my-parser {:state flat-app-state} '[:a {:user [:user/name]} :c])\n \"\n\n The first (possibly surprising",
"end": 18556,
"score": 0.9829080104827881,
"start": 18552,
"tag": "USERNAME",
"value": "user"
},
{
"context": "parser {:state flat-app-state} '[:a {:user [:user/name]} :c])\n \"\n\n The first (possibly surprising thin",
"end": 18561,
"score": 0.7590663433074951,
"start": 18557,
"tag": "USERNAME",
"value": "name"
}
] |
src/devguide/untangled_devguide/I_Building_A_Server.cljs
|
pholas/untangled-devguide
| 43 |
(ns untangled-devguide.I-Building-A-Server
(:require-macros [cljs.test :refer [is]])
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[untangled-devguide.state-reads.parser-1 :as parser1]
[untangled-devguide.state-reads.parser-2 :as parser2]
[untangled-devguide.state-reads.parser-3 :as parser3]
[devcards.util.edn-renderer :refer [html-edn]]
[devcards.core :as dc :refer-macros [defcard defcard-doc deftest]]
[cljs.reader :as r]
[om.next.impl.parser :as p]
[devcards.core :as dc :refer-macros [defcard defcard-doc]]))
; TODO: make external refs (e.g. to ss component) links
(defcard-doc
"
# Building the server
The pre-built server components for Untangled use Stuart Seirra's Component library. The server has no
global state except for a debugging atom that holds the entire system. The project has already
been set up with a basic server, and we'll cover what's in there, and what you need to write.
You should have a firm understanding of Stuart's component library, since we won't be covering that
in detail here.
## Constructing a base server
The base server is trivial to create:
```
(ns app.system
(:require
[untangled.server.core :as core]
[app.api :as api]
[om.next.server :as om]))
(defn make-system []
(core/make-untangled-server
; where you want to store your override config file
:config-path \"/usr/local/etc/app.edn\"
; Standard Om parser
:parser (om/parser {:read api/api-read :mutate api/mutate})
; The keyword names of any components you want auto-injected into the parser env (e.g. databases)
:parser-injections #{}
; Additional components you want added to the server
:components {}))
```
### Configuring the server
Server configuration requires two EDN files:
- `resources/config/defaults.edn`: This file should contain a single EDN map that contains
defaults for everything that the application wants to configure.
- `/abs/path/of/choice`: This file can be named what you want (you supply the name when
making the server). It can also contain an empty map, but is meant to be machine-local
overrides of the configuration in the defaults. This file is required. We chose to do this because
it keeps people from starting the app in an unconfigured production environment.
```
(defn make-system []
(core/make-untangled-server
:config-path \"/usr/local/etc/app.edn\"
...
```
The only parameter that the default server looks for is the network port to listen on:
```
{ :port 3000 }
```
### Pre-installed components
When you start an Untangled server it comes pre-supplied with injectable components that your
own component can depend on, as well as inject into the server-side Om parsing environment.
The most important of these, of course, is the configuration itself. The available components
are known by the following keys:
- `:config`: The configuration component. The actual EDN value is in the `:value` field
of the component.
- `:handler`: The component that handles web traffic. You can inject your own Ring handlers into
two different places in the request/response processing. Early or Late (to intercept or supply a default).
- `:server`: The actual web server.
The component library, of course, figures out the dependency order and ensures things are initialized
and available where necessary.
### Making components available in the processing environment
Any components in the server can be injected into the processing pipeline so they are
available when writing your mutations and query procesing. Making them available is as simple
as putting their component keyword into the `:parser-injections` set when building the server:
```
(defn make-system []
(core/make-untangled-server
:parser-injections #{:config}
...))
```
### Provisioning a request parser
All incoming client communication will be in the form of Om Queries/Mutations. Om supplies
a parser to do the low-level parsing, but you must supply the bits that do the real logic.
Learning how to build these parts is relatively simple, and is the only thing you need
to know to process all possible communications from a client.
Om parsers require two things: A function to process reads, and a function to process mutations.
These are completely open to your choice of implementation. They simply need to be functions
with the signature:
```
(fn [env key params] ...)
```
- The `env` is the environment. On the *server* this will contain:
- Anything components you've asked to be injected during construction. Usually some kind
of database connection and configuration.
- `ast`: An AST representation of the item being parsed.
- `parser`: The Om parser itself (to allow you to do recursive calls)
- `request`: The actual incoming request (with headers)
- ... TODO: finish this
- The `key` is the dispatch key for the item being parsed. We'll cover that shortly.
- The `params` are any params being passed to the item being parsed.
")
(defcard-doc
"
## Processing reads
The Om parser is exactly what it sounds like: a parser for the query grammar. Now, formally
a parser is something that takes apart input data and figures out what the parts mean (e.g.
that's a join, that's a mutation call, etc.). In an interpreter, each time the parser finds
a bit of meaning, it invokes a function to interpret that meaning and emit a result.
In this case, the meaning is a bit of result data; thus, for Om to be able to generate a
result from the parser, you must supply the \"read\" emitter.
First, let's see what an Om parser in action.
")
(defcard om-parser
"This card will run an Om parser on an arbitrary query, record the calls to the read emitter,
and show the trace of those calls in order. Feel free to look at the source of this card.
Essentially, it creates an Om parser:
```
(om/parser {:read read-tracking})
```
where the `read-tracking` simply stores details of each call in an atom and shows those calls
when parse is complete.
The signature of a read function is:
`(read [env dispatch-key params])`
where the env contains the state of your application, a reference to your parser (so you can
call it recursively, if you wish), a query root marker, an AST node describing the exact
details of the element's meaning, a path, and *anything else* you want to put in there if
you call the parser recursively.
Try some queries like these:
- `[:a :b]`
- `[:a {:b [:c]}]` (note that the AST is recursively built, but only the top keys are actually parsed to trigger reads)
- `[(:a { :x 1 })]` (note the value of params)
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:env (assoc env :parser :function-elided)
:dispatch-key k
:params params}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
### Injecting some kind of database
In order to play with this on a server, you'll want to have some kind of state
available. The most trivial thing you can do is just create a global top-level atom
that holds data. This is sufficient for testing, and we'll assume we've done something
like this on our server:
```
(defonce state (atom {}))
```
One could also wrap that in a Stuart Sierra component and inject it (as state) into the
parser.
Much of the remainder of this section assumes this.
## Implementing read
When building your server you must build a read function such that it can
pull data to fufill what the parser needs to fill in the result of a query parse.
The Om Next parser understands the grammar, and is written in such a way that the process
is very simple:
- The parser calls your `read` with the key that it parsed, along with some other helpful information.
- Your read function returns a value for that key (possibly calling the parser recursively if it is a join).
- The parser generates the result map by putting that key/value pair into
the result at the correct position (relative to the query).
Note that the parser only processes the query one level deep. Recursion (if you need it)
is controlled by *your* read.
")
(defcard parser-read-trace
"This card is similar to the prior card, but it has a read function that just records what keys it was
triggered for. Give it an arbitrary legal query, and see what happens.
Some interesting queries:
- `[:a :b :c]`
- `[:a {:b [:x :y]} :c]`
- `[{:a {:b {:c [:x :y]}}}]`
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:read-called-with-key k}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
In the card above you should have seen that only the top-level keys trigger reads.
So, the query:
```clj
[:kw {:j [:v]}]
```
would result in a call to your read function on `:kw` and `:j`. Two calls. No
automatic recursion. Done. The output value of the *parser* will be a map (that
parse creates) which contains the keys (from the query, copied over by the
parser) and values (obtained from your read):
```clj
{ :kw value-from-read-for-kw :j value-from-read-for-j }
```
Note that if your read accidentally returns a scalar for `:j` then you've not
done the right thing...a join like `{ :j [:k] }` expects a result that is a
vector of (zero or more) things *or* a singleton *map* that contains key
`:k`.
```clj
{ :kw 21 :j { :k 42 } }
; OR
{ :kw 21 :j [{ :k 42 } {:k 43}] }
```
Dealing with recursive queries is a natural fit for a recusive algorithm, and it
is perfectly fine to invoke the `parser` function to descend the query. In fact,
the `parser` is passed as part of your environment.
So, the read function you write will receive three arguments, as described below:
1. An environment containing:
+ `:ast`: An abstract syntax *tree* for the element, which contains:
+ `:type`: The type of node (e.g. :prop, :join, etc.)
+ `:dispatch-key`: The keyword portion of the triggering query element (e.g. :people/by-id)
+ `:key`: The full key of the triggering query element (e.g. [:people/by-id 1])
+ `:query`: (same as the query in `env`)
+ `:children`: If this node has sub-queries, will be AST nodes for those
+ others...see documentation
+ `:parser`: The query parser
+ `:query`: **if** the element had one E.g. `{:people [:user/name]}` has `:query` `[:user/name]`
+ Components you requested be injected
2. A dispatch key for the item that triggered the read (same as dispatch key in the AST)
3. Parameters (which are nil if not supplied in the query)
It must return a value that has the shape implied the grammar element being read.
So, lets try it out.
")
(defn read-42 [env key params] {:value 42})
(def parser-42 (om/parser {:read read-42}))
(defcard-doc
"
### Reading a keyword
If the parser encounters a keyword `:kw`, your function will be called with:
```clj
(your-read
{ :dispatch-key :kw :parser (fn ...) } ;; the environment: parser, etc.
:kw ;; the keyword
nil) ;; no parameters
```
your read function should return some value that makes sense for
that spot in the grammar. There are no real restrictions on what that data
value has to be in this case. You are reading a simple property.
There is no further shape implied by the grammar.
It could be a string, number, Entity Object, JS Date, nil, etc.
Due to additional features of the parser, *your return value must be wrapped in a
map with the key `:value`*. If you fail to do this, you will get nothing
in the result.
Thus, a very simple read for props (keywords) could be:
```clj
(defn read [env key params] { :value 42 })
```
below is a devcard that implements exactly this `read` and plugs it into a
parser like this:"
(dc/mkdn-pprint-source read-42)
(dc/mkdn-pprint-source parser-42))
(defn parser-tester [parser]
(fn [state _]
(let [{:keys [v error]} @state]
(dom/div nil
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(swap! state assoc :error "" :result (parser {:state (atom (:db @state))} (r/read-string v)))
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(when error
(dom/div nil (str error)))
(dom/h4 nil "Query Result")
(html-edn (:result @state))
(dom/h4 nil "Database")
(html-edn (:db @state))))))
(defcard property-read-for-the-meaning-of-life-the-universe-and-everything
"This card is using the parser/read pairing shown above (the read returns
the value 42 no matter what it is asked for). Run any query you
want in it, and check out the answer.
This card just runs `(parser-42 {} your-query)` and reports the result.
Some examples to try:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester parser-42)
{:db {}})
(defn property-read [{:keys [state]} key params] {:value (get @state key :not-found)})
(def property-parser (om/parser {:read property-read}))
(defcard-doc
"
So now you have a read function that returns the meaning of life the universe and
everything in a single line of code! But now it is obvious that we need to build
an even bigger machine to understand the question.
If your server state is just a flat set of scalar values with unique keyword
identities, then a better read is similarly trivial.
The read function:
"
(dc/mkdn-pprint-source property-read)
"
Just assumes the property will be in the top-level of some injected state atom.
")
(defcard trivial-property-reader
"This card is using the `property-read` function above in a parser.
The database we're emulating is shown at the bottom of the card, after the
result.
Run some queries and see what you get. Some suggestions:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester property-parser)
{:db {:a 1 :b 2 :c 99}}
{:inspect-data true})
(def flat-app-state (atom {:a 1 :user/name "Sam" :c 99}))
(defn flat-state-read [{:keys [state parser query] :as env} key params]
(if (= :user key)
{:value (parser env query)} ; recursive call. query is now [:user/name]
{:value (get @state key)})) ; gets called for :user/name :a and :c
(def my-parser (om/parser {:read flat-state-read}))
(defcard-doc
"
The result of those nested queries is supposed to be a nested map. So, obviously we
have more work to do.
### Reading a join
Your state probably has some more structure to it than just a flat
bag of properties. Joins are naturally recursive in syntax, and
those that are accustomed to writing parsers probably already see the solution.
First, let's clarify what the read function will receive for a join. When
parsing:
```clj
{ :j [:a :b :c] }
```
your read function will be called with:
```clj
(your-read { :state state :parser (fn ...) :query [:a :b :c] } ; the environment
:j ; keyword of the join
nil) ; no parameters
```
But just to prove a point about the separation of database format and
query structure we'll implement this next example
with a basic recursive parse, *but use more flat data* (the following is live code):
"
(dc/mkdn-pprint-source flat-app-state)
(dc/mkdn-pprint-source flat-state-read)
(dc/mkdn-pprint-source my-parser)
"
The important bit is the `then` part of the `if`. Return a value that is
the recursive parse of the sub-query. Otherwise, we just look up the keyword
in the state (which as you can see is a very flat map).
The result of running this parser on the query shown is:
"
(my-parser {:state flat-app-state} '[:a {:user [:user/name]} :c])
"
The first (possibly surprising thing) is that your result includes a nested
object. The parser creates the result, and the recusion natually nested the
result correctly.
Next you should remember that join implies a there could be one OR many results.
The singleton case is fine (e.g. putting a single map there). If there are
multiple results it should be a vector.
In this case, we're just showing that you can use the parser recursively
and it in turn will call your read function again.
In a real application, your data will not be this flat, so you
will almost certainly not do things in quite this
way.
So, let's put a little better state in our application, and write a
more realistic parser.
### A Non-trivial, recursive example
Let's start with the following hand-normalized application state:
"
(dc/mkdn-pprint-source parser1/app-state)
"
Our friend `db->tree` could handle queries against this database,
but let's implement it by hand.
Say we want to run this query:
"
(dc/mkdn-pprint-source parser1/query)
"
From the earlier discussion you see that we'll have to handle the
top level keys one at a time.
For this query there are only two keys to handle: `:friends`
and `:window-size`. So, let's write a case for each:
"
(dc/mkdn-pprint-source parser1/read)
"
The default case is `nil`, which means if we supply an errant key in the query no
exception will happen.
when we run the query, we get:
"
(parser1/parser {:state parser1/app-state} parser1/query)
"
Those of you paying close attention will notice that we have yet to need
recursion. We've also done something a bit naive: select-keys assumes
that query contains only keys! What if app state and query were instead:
"
(dc/mkdn-pprint-source parser2/app-state)
(dc/mkdn-pprint-source parser2/query)
"
Now things get interesting, and I'm sure more than one reader will have an
opinion on how to proceed. My aim is to show that the parser can be called
recursively to handle these things, not to find the perfect structure for the
parser in general, so I'm going to do something simple.
The primary trick I'm going to exploit is the fact that `env` is just a map, and
that we can add stuff to it. When we are in the context of a person, we'll add
`:person` to the environment, and pass that to a recursive call to `parser`.
"
(dc/mkdn-pprint-source parser2/read)
"
and running the query gives the expected result:
"
(parser2/parser {:state parser2/app-state} parser2/query)
"
All of the code shown here is being actively pulled (and run) from `untangled-devguide.state-reads.parser-2`.
Now, I feel compelled to mention a few things:
- Keeping track of where you are in the parse (e.g. person can be generalized to
'the current thing I'm working on') allows you to generalize this algorithm.
- `db->tree` can still do everything we've done so far.
- If you fully generalize the property and join parsing, you'll essentially recreate
`db->tree`.
So now you should be trying to remember why we're doing all of this. So let's talk
about a case that `db->tree` can't handle: parameters.
## Parameters
In the query grammar most kinds of rules accept parameters. These are intended
to be combined with dynamic queries that will allow your UI to have some control
over what you want to read from the application state (think filtering, pagination,
sorting, and such).
As you might expect, the parameters on a particular expression in the query
are just passed into your read function as the third argument.
You are responsible for both defining and interpreting them.
They have no rules other than they are maps.
To read the property `:load/start-time` with a parameter indicating a particular
time unit you might use:
```clj
[(:load/start-time {:units :seconds})]
```
this will invoke read with:
```clj
(your-read env :load/start-time { :units :seconds})
```
the implication is clear. The code is up to you. Let's add some quick support for this
in our read (in untangled-devguide.state-reads.parser-3):
"
(dc/mkdn-pprint-source parser3/app-state)
(dc/mkdn-pprint-source parser3/read)
(dc/mkdn-pprint-source parser3/parser)
"Now we can try the following queries:"
(dc/mkdn-pprint-source parser3/parse-result-mins)
parser3/parse-result-mins
(dc/mkdn-pprint-source parser3/parse-result-secs)
parser3/parse-result-secs
(dc/mkdn-pprint-source parser3/parse-result-ms)
parser3/parse-result-ms)
|
99587
|
(ns untangled-devguide.I-Building-A-Server
(:require-macros [cljs.test :refer [is]])
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[untangled-devguide.state-reads.parser-1 :as parser1]
[untangled-devguide.state-reads.parser-2 :as parser2]
[untangled-devguide.state-reads.parser-3 :as parser3]
[devcards.util.edn-renderer :refer [html-edn]]
[devcards.core :as dc :refer-macros [defcard defcard-doc deftest]]
[cljs.reader :as r]
[om.next.impl.parser :as p]
[devcards.core :as dc :refer-macros [defcard defcard-doc]]))
; TODO: make external refs (e.g. to ss component) links
(defcard-doc
"
# Building the server
The pre-built server components for Untangled use Stuart Seirra's Component library. The server has no
global state except for a debugging atom that holds the entire system. The project has already
been set up with a basic server, and we'll cover what's in there, and what you need to write.
You should have a firm understanding of Stuart's component library, since we won't be covering that
in detail here.
## Constructing a base server
The base server is trivial to create:
```
(ns app.system
(:require
[untangled.server.core :as core]
[app.api :as api]
[om.next.server :as om]))
(defn make-system []
(core/make-untangled-server
; where you want to store your override config file
:config-path \"/usr/local/etc/app.edn\"
; Standard Om parser
:parser (om/parser {:read api/api-read :mutate api/mutate})
; The keyword names of any components you want auto-injected into the parser env (e.g. databases)
:parser-injections #{}
; Additional components you want added to the server
:components {}))
```
### Configuring the server
Server configuration requires two EDN files:
- `resources/config/defaults.edn`: This file should contain a single EDN map that contains
defaults for everything that the application wants to configure.
- `/abs/path/of/choice`: This file can be named what you want (you supply the name when
making the server). It can also contain an empty map, but is meant to be machine-local
overrides of the configuration in the defaults. This file is required. We chose to do this because
it keeps people from starting the app in an unconfigured production environment.
```
(defn make-system []
(core/make-untangled-server
:config-path \"/usr/local/etc/app.edn\"
...
```
The only parameter that the default server looks for is the network port to listen on:
```
{ :port 3000 }
```
### Pre-installed components
When you start an Untangled server it comes pre-supplied with injectable components that your
own component can depend on, as well as inject into the server-side Om parsing environment.
The most important of these, of course, is the configuration itself. The available components
are known by the following keys:
- `:config`: The configuration component. The actual EDN value is in the `:value` field
of the component.
- `:handler`: The component that handles web traffic. You can inject your own Ring handlers into
two different places in the request/response processing. Early or Late (to intercept or supply a default).
- `:server`: The actual web server.
The component library, of course, figures out the dependency order and ensures things are initialized
and available where necessary.
### Making components available in the processing environment
Any components in the server can be injected into the processing pipeline so they are
available when writing your mutations and query procesing. Making them available is as simple
as putting their component keyword into the `:parser-injections` set when building the server:
```
(defn make-system []
(core/make-untangled-server
:parser-injections #{:config}
...))
```
### Provisioning a request parser
All incoming client communication will be in the form of Om Queries/Mutations. Om supplies
a parser to do the low-level parsing, but you must supply the bits that do the real logic.
Learning how to build these parts is relatively simple, and is the only thing you need
to know to process all possible communications from a client.
Om parsers require two things: A function to process reads, and a function to process mutations.
These are completely open to your choice of implementation. They simply need to be functions
with the signature:
```
(fn [env key params] ...)
```
- The `env` is the environment. On the *server* this will contain:
- Anything components you've asked to be injected during construction. Usually some kind
of database connection and configuration.
- `ast`: An AST representation of the item being parsed.
- `parser`: The Om parser itself (to allow you to do recursive calls)
- `request`: The actual incoming request (with headers)
- ... TODO: finish this
- The `key` is the dispatch key for the item being parsed. We'll cover that shortly.
- The `params` are any params being passed to the item being parsed.
")
(defcard-doc
"
## Processing reads
The Om parser is exactly what it sounds like: a parser for the query grammar. Now, formally
a parser is something that takes apart input data and figures out what the parts mean (e.g.
that's a join, that's a mutation call, etc.). In an interpreter, each time the parser finds
a bit of meaning, it invokes a function to interpret that meaning and emit a result.
In this case, the meaning is a bit of result data; thus, for Om to be able to generate a
result from the parser, you must supply the \"read\" emitter.
First, let's see what an Om parser in action.
")
(defcard om-parser
"This card will run an Om parser on an arbitrary query, record the calls to the read emitter,
and show the trace of those calls in order. Feel free to look at the source of this card.
Essentially, it creates an Om parser:
```
(om/parser {:read read-tracking})
```
where the `read-tracking` simply stores details of each call in an atom and shows those calls
when parse is complete.
The signature of a read function is:
`(read [env dispatch-key params])`
where the env contains the state of your application, a reference to your parser (so you can
call it recursively, if you wish), a query root marker, an AST node describing the exact
details of the element's meaning, a path, and *anything else* you want to put in there if
you call the parser recursively.
Try some queries like these:
- `[:a :b]`
- `[:a {:b [:c]}]` (note that the AST is recursively built, but only the top keys are actually parsed to trigger reads)
- `[(:a { :x 1 })]` (note the value of params)
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:env (assoc env :parser :function-elided)
:dispatch-key k
:params params}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
### Injecting some kind of database
In order to play with this on a server, you'll want to have some kind of state
available. The most trivial thing you can do is just create a global top-level atom
that holds data. This is sufficient for testing, and we'll assume we've done something
like this on our server:
```
(defonce state (atom {}))
```
One could also wrap that in a Stuart Sierra component and inject it (as state) into the
parser.
Much of the remainder of this section assumes this.
## Implementing read
When building your server you must build a read function such that it can
pull data to fufill what the parser needs to fill in the result of a query parse.
The Om Next parser understands the grammar, and is written in such a way that the process
is very simple:
- The parser calls your `read` with the key that it parsed, along with some other helpful information.
- Your read function returns a value for that key (possibly calling the parser recursively if it is a join).
- The parser generates the result map by putting that key/value pair into
the result at the correct position (relative to the query).
Note that the parser only processes the query one level deep. Recursion (if you need it)
is controlled by *your* read.
")
(defcard parser-read-trace
"This card is similar to the prior card, but it has a read function that just records what keys it was
triggered for. Give it an arbitrary legal query, and see what happens.
Some interesting queries:
- `[:a :b :c]`
- `[:a {:b [:x :y]} :c]`
- `[{:a {:b {:c [:x :y]}}}]`
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:read-called-with-key k}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
In the card above you should have seen that only the top-level keys trigger reads.
So, the query:
```clj
[:kw {:j [:v]}]
```
would result in a call to your read function on `:kw` and `:j`. Two calls. No
automatic recursion. Done. The output value of the *parser* will be a map (that
parse creates) which contains the keys (from the query, copied over by the
parser) and values (obtained from your read):
```clj
{ :kw value-from-read-for-kw :j value-from-read-for-j }
```
Note that if your read accidentally returns a scalar for `:j` then you've not
done the right thing...a join like `{ :j [:k] }` expects a result that is a
vector of (zero or more) things *or* a singleton *map* that contains key
`:k`.
```clj
{ :kw 21 :j { :k 42 } }
; OR
{ :kw 21 :j [{ :k 42 } {:k 43}] }
```
Dealing with recursive queries is a natural fit for a recusive algorithm, and it
is perfectly fine to invoke the `parser` function to descend the query. In fact,
the `parser` is passed as part of your environment.
So, the read function you write will receive three arguments, as described below:
1. An environment containing:
+ `:ast`: An abstract syntax *tree* for the element, which contains:
+ `:type`: The type of node (e.g. :prop, :join, etc.)
+ `:dispatch-key`: The keyword portion of the triggering query element (e.g. :people/by-id)
+ `:key`: The full key of the triggering query element (e.g. [:people/by-id 1])
+ `:query`: (same as the query in `env`)
+ `:children`: If this node has sub-queries, will be AST nodes for those
+ others...see documentation
+ `:parser`: The query parser
+ `:query`: **if** the element had one E.g. `{:people [:user/name]}` has `:query` `[:user/name]`
+ Components you requested be injected
2. A dispatch key for the item that triggered the read (same as dispatch key in the AST)
3. Parameters (which are nil if not supplied in the query)
It must return a value that has the shape implied the grammar element being read.
So, lets try it out.
")
(defn read-42 [env key params] {:value 42})
(def parser-42 (om/parser {:read read-42}))
(defcard-doc
"
### Reading a keyword
If the parser encounters a keyword `:kw`, your function will be called with:
```clj
(your-read
{ :dispatch-key :kw :parser (fn ...) } ;; the environment: parser, etc.
:kw ;; the keyword
nil) ;; no parameters
```
your read function should return some value that makes sense for
that spot in the grammar. There are no real restrictions on what that data
value has to be in this case. You are reading a simple property.
There is no further shape implied by the grammar.
It could be a string, number, Entity Object, JS Date, nil, etc.
Due to additional features of the parser, *your return value must be wrapped in a
map with the key `:value`*. If you fail to do this, you will get nothing
in the result.
Thus, a very simple read for props (keywords) could be:
```clj
(defn read [env key params] { :value 42 })
```
below is a devcard that implements exactly this `read` and plugs it into a
parser like this:"
(dc/mkdn-pprint-source read-42)
(dc/mkdn-pprint-source parser-42))
(defn parser-tester [parser]
(fn [state _]
(let [{:keys [v error]} @state]
(dom/div nil
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(swap! state assoc :error "" :result (parser {:state (atom (:db @state))} (r/read-string v)))
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(when error
(dom/div nil (str error)))
(dom/h4 nil "Query Result")
(html-edn (:result @state))
(dom/h4 nil "Database")
(html-edn (:db @state))))))
(defcard property-read-for-the-meaning-of-life-the-universe-and-everything
"This card is using the parser/read pairing shown above (the read returns
the value 42 no matter what it is asked for). Run any query you
want in it, and check out the answer.
This card just runs `(parser-42 {} your-query)` and reports the result.
Some examples to try:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester parser-42)
{:db {}})
(defn property-read [{:keys [state]} key params] {:value (get @state key :not-found)})
(def property-parser (om/parser {:read property-read}))
(defcard-doc
"
So now you have a read function that returns the meaning of life the universe and
everything in a single line of code! But now it is obvious that we need to build
an even bigger machine to understand the question.
If your server state is just a flat set of scalar values with unique keyword
identities, then a better read is similarly trivial.
The read function:
"
(dc/mkdn-pprint-source property-read)
"
Just assumes the property will be in the top-level of some injected state atom.
")
(defcard trivial-property-reader
"This card is using the `property-read` function above in a parser.
The database we're emulating is shown at the bottom of the card, after the
result.
Run some queries and see what you get. Some suggestions:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester property-parser)
{:db {:a 1 :b 2 :c 99}}
{:inspect-data true})
(def flat-app-state (atom {:a 1 :user/name "<NAME>" :c 99}))
(defn flat-state-read [{:keys [state parser query] :as env} key params]
(if (= :user key)
{:value (parser env query)} ; recursive call. query is now [:user/name]
{:value (get @state key)})) ; gets called for :user/name :a and :c
(def my-parser (om/parser {:read flat-state-read}))
(defcard-doc
"
The result of those nested queries is supposed to be a nested map. So, obviously we
have more work to do.
### Reading a join
Your state probably has some more structure to it than just a flat
bag of properties. Joins are naturally recursive in syntax, and
those that are accustomed to writing parsers probably already see the solution.
First, let's clarify what the read function will receive for a join. When
parsing:
```clj
{ :j [:a :b :c] }
```
your read function will be called with:
```clj
(your-read { :state state :parser (fn ...) :query [:a :b :c] } ; the environment
:j ; keyword of the join
nil) ; no parameters
```
But just to prove a point about the separation of database format and
query structure we'll implement this next example
with a basic recursive parse, *but use more flat data* (the following is live code):
"
(dc/mkdn-pprint-source flat-app-state)
(dc/mkdn-pprint-source flat-state-read)
(dc/mkdn-pprint-source my-parser)
"
The important bit is the `then` part of the `if`. Return a value that is
the recursive parse of the sub-query. Otherwise, we just look up the keyword
in the state (which as you can see is a very flat map).
The result of running this parser on the query shown is:
"
(my-parser {:state flat-app-state} '[:a {:user [:user/name]} :c])
"
The first (possibly surprising thing) is that your result includes a nested
object. The parser creates the result, and the recusion natually nested the
result correctly.
Next you should remember that join implies a there could be one OR many results.
The singleton case is fine (e.g. putting a single map there). If there are
multiple results it should be a vector.
In this case, we're just showing that you can use the parser recursively
and it in turn will call your read function again.
In a real application, your data will not be this flat, so you
will almost certainly not do things in quite this
way.
So, let's put a little better state in our application, and write a
more realistic parser.
### A Non-trivial, recursive example
Let's start with the following hand-normalized application state:
"
(dc/mkdn-pprint-source parser1/app-state)
"
Our friend `db->tree` could handle queries against this database,
but let's implement it by hand.
Say we want to run this query:
"
(dc/mkdn-pprint-source parser1/query)
"
From the earlier discussion you see that we'll have to handle the
top level keys one at a time.
For this query there are only two keys to handle: `:friends`
and `:window-size`. So, let's write a case for each:
"
(dc/mkdn-pprint-source parser1/read)
"
The default case is `nil`, which means if we supply an errant key in the query no
exception will happen.
when we run the query, we get:
"
(parser1/parser {:state parser1/app-state} parser1/query)
"
Those of you paying close attention will notice that we have yet to need
recursion. We've also done something a bit naive: select-keys assumes
that query contains only keys! What if app state and query were instead:
"
(dc/mkdn-pprint-source parser2/app-state)
(dc/mkdn-pprint-source parser2/query)
"
Now things get interesting, and I'm sure more than one reader will have an
opinion on how to proceed. My aim is to show that the parser can be called
recursively to handle these things, not to find the perfect structure for the
parser in general, so I'm going to do something simple.
The primary trick I'm going to exploit is the fact that `env` is just a map, and
that we can add stuff to it. When we are in the context of a person, we'll add
`:person` to the environment, and pass that to a recursive call to `parser`.
"
(dc/mkdn-pprint-source parser2/read)
"
and running the query gives the expected result:
"
(parser2/parser {:state parser2/app-state} parser2/query)
"
All of the code shown here is being actively pulled (and run) from `untangled-devguide.state-reads.parser-2`.
Now, I feel compelled to mention a few things:
- Keeping track of where you are in the parse (e.g. person can be generalized to
'the current thing I'm working on') allows you to generalize this algorithm.
- `db->tree` can still do everything we've done so far.
- If you fully generalize the property and join parsing, you'll essentially recreate
`db->tree`.
So now you should be trying to remember why we're doing all of this. So let's talk
about a case that `db->tree` can't handle: parameters.
## Parameters
In the query grammar most kinds of rules accept parameters. These are intended
to be combined with dynamic queries that will allow your UI to have some control
over what you want to read from the application state (think filtering, pagination,
sorting, and such).
As you might expect, the parameters on a particular expression in the query
are just passed into your read function as the third argument.
You are responsible for both defining and interpreting them.
They have no rules other than they are maps.
To read the property `:load/start-time` with a parameter indicating a particular
time unit you might use:
```clj
[(:load/start-time {:units :seconds})]
```
this will invoke read with:
```clj
(your-read env :load/start-time { :units :seconds})
```
the implication is clear. The code is up to you. Let's add some quick support for this
in our read (in untangled-devguide.state-reads.parser-3):
"
(dc/mkdn-pprint-source parser3/app-state)
(dc/mkdn-pprint-source parser3/read)
(dc/mkdn-pprint-source parser3/parser)
"Now we can try the following queries:"
(dc/mkdn-pprint-source parser3/parse-result-mins)
parser3/parse-result-mins
(dc/mkdn-pprint-source parser3/parse-result-secs)
parser3/parse-result-secs
(dc/mkdn-pprint-source parser3/parse-result-ms)
parser3/parse-result-ms)
| true |
(ns untangled-devguide.I-Building-A-Server
(:require-macros [cljs.test :refer [is]])
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[untangled-devguide.state-reads.parser-1 :as parser1]
[untangled-devguide.state-reads.parser-2 :as parser2]
[untangled-devguide.state-reads.parser-3 :as parser3]
[devcards.util.edn-renderer :refer [html-edn]]
[devcards.core :as dc :refer-macros [defcard defcard-doc deftest]]
[cljs.reader :as r]
[om.next.impl.parser :as p]
[devcards.core :as dc :refer-macros [defcard defcard-doc]]))
; TODO: make external refs (e.g. to ss component) links
(defcard-doc
"
# Building the server
The pre-built server components for Untangled use Stuart Seirra's Component library. The server has no
global state except for a debugging atom that holds the entire system. The project has already
been set up with a basic server, and we'll cover what's in there, and what you need to write.
You should have a firm understanding of Stuart's component library, since we won't be covering that
in detail here.
## Constructing a base server
The base server is trivial to create:
```
(ns app.system
(:require
[untangled.server.core :as core]
[app.api :as api]
[om.next.server :as om]))
(defn make-system []
(core/make-untangled-server
; where you want to store your override config file
:config-path \"/usr/local/etc/app.edn\"
; Standard Om parser
:parser (om/parser {:read api/api-read :mutate api/mutate})
; The keyword names of any components you want auto-injected into the parser env (e.g. databases)
:parser-injections #{}
; Additional components you want added to the server
:components {}))
```
### Configuring the server
Server configuration requires two EDN files:
- `resources/config/defaults.edn`: This file should contain a single EDN map that contains
defaults for everything that the application wants to configure.
- `/abs/path/of/choice`: This file can be named what you want (you supply the name when
making the server). It can also contain an empty map, but is meant to be machine-local
overrides of the configuration in the defaults. This file is required. We chose to do this because
it keeps people from starting the app in an unconfigured production environment.
```
(defn make-system []
(core/make-untangled-server
:config-path \"/usr/local/etc/app.edn\"
...
```
The only parameter that the default server looks for is the network port to listen on:
```
{ :port 3000 }
```
### Pre-installed components
When you start an Untangled server it comes pre-supplied with injectable components that your
own component can depend on, as well as inject into the server-side Om parsing environment.
The most important of these, of course, is the configuration itself. The available components
are known by the following keys:
- `:config`: The configuration component. The actual EDN value is in the `:value` field
of the component.
- `:handler`: The component that handles web traffic. You can inject your own Ring handlers into
two different places in the request/response processing. Early or Late (to intercept or supply a default).
- `:server`: The actual web server.
The component library, of course, figures out the dependency order and ensures things are initialized
and available where necessary.
### Making components available in the processing environment
Any components in the server can be injected into the processing pipeline so they are
available when writing your mutations and query procesing. Making them available is as simple
as putting their component keyword into the `:parser-injections` set when building the server:
```
(defn make-system []
(core/make-untangled-server
:parser-injections #{:config}
...))
```
### Provisioning a request parser
All incoming client communication will be in the form of Om Queries/Mutations. Om supplies
a parser to do the low-level parsing, but you must supply the bits that do the real logic.
Learning how to build these parts is relatively simple, and is the only thing you need
to know to process all possible communications from a client.
Om parsers require two things: A function to process reads, and a function to process mutations.
These are completely open to your choice of implementation. They simply need to be functions
with the signature:
```
(fn [env key params] ...)
```
- The `env` is the environment. On the *server* this will contain:
- Anything components you've asked to be injected during construction. Usually some kind
of database connection and configuration.
- `ast`: An AST representation of the item being parsed.
- `parser`: The Om parser itself (to allow you to do recursive calls)
- `request`: The actual incoming request (with headers)
- ... TODO: finish this
- The `key` is the dispatch key for the item being parsed. We'll cover that shortly.
- The `params` are any params being passed to the item being parsed.
")
(defcard-doc
"
## Processing reads
The Om parser is exactly what it sounds like: a parser for the query grammar. Now, formally
a parser is something that takes apart input data and figures out what the parts mean (e.g.
that's a join, that's a mutation call, etc.). In an interpreter, each time the parser finds
a bit of meaning, it invokes a function to interpret that meaning and emit a result.
In this case, the meaning is a bit of result data; thus, for Om to be able to generate a
result from the parser, you must supply the \"read\" emitter.
First, let's see what an Om parser in action.
")
(defcard om-parser
"This card will run an Om parser on an arbitrary query, record the calls to the read emitter,
and show the trace of those calls in order. Feel free to look at the source of this card.
Essentially, it creates an Om parser:
```
(om/parser {:read read-tracking})
```
where the `read-tracking` simply stores details of each call in an atom and shows those calls
when parse is complete.
The signature of a read function is:
`(read [env dispatch-key params])`
where the env contains the state of your application, a reference to your parser (so you can
call it recursively, if you wish), a query root marker, an AST node describing the exact
details of the element's meaning, a path, and *anything else* you want to put in there if
you call the parser recursively.
Try some queries like these:
- `[:a :b]`
- `[:a {:b [:c]}]` (note that the AST is recursively built, but only the top keys are actually parsed to trigger reads)
- `[(:a { :x 1 })]` (note the value of params)
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:env (assoc env :parser :function-elided)
:dispatch-key k
:params params}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
### Injecting some kind of database
In order to play with this on a server, you'll want to have some kind of state
available. The most trivial thing you can do is just create a global top-level atom
that holds data. This is sufficient for testing, and we'll assume we've done something
like this on our server:
```
(defonce state (atom {}))
```
One could also wrap that in a Stuart Sierra component and inject it (as state) into the
parser.
Much of the remainder of this section assumes this.
## Implementing read
When building your server you must build a read function such that it can
pull data to fufill what the parser needs to fill in the result of a query parse.
The Om Next parser understands the grammar, and is written in such a way that the process
is very simple:
- The parser calls your `read` with the key that it parsed, along with some other helpful information.
- Your read function returns a value for that key (possibly calling the parser recursively if it is a join).
- The parser generates the result map by putting that key/value pair into
the result at the correct position (relative to the query).
Note that the parser only processes the query one level deep. Recursion (if you need it)
is controlled by *your* read.
")
(defcard parser-read-trace
"This card is similar to the prior card, but it has a read function that just records what keys it was
triggered for. Give it an arbitrary legal query, and see what happens.
Some interesting queries:
- `[:a :b :c]`
- `[:a {:b [:x :y]} :c]`
- `[{:a {:b {:c [:x :y]}}}]`
"
(fn [state _]
(let [{:keys [v error]} @state
trace (atom [])
read-tracking (fn [env k params]
(swap! trace conj {:read-called-with-key k}))
parser (om/parser {:read read-tracking})]
(dom/div nil
(when error
(dom/div nil (str error)))
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(reset! trace [])
(swap! state assoc :error nil)
(parser {} (r/read-string v))
(swap! state assoc :result @trace)
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(dom/h4 nil "Parsing Trace")
(html-edn (:result @state)))))
{}
{:inspect-data false})
(defcard-doc
"
In the card above you should have seen that only the top-level keys trigger reads.
So, the query:
```clj
[:kw {:j [:v]}]
```
would result in a call to your read function on `:kw` and `:j`. Two calls. No
automatic recursion. Done. The output value of the *parser* will be a map (that
parse creates) which contains the keys (from the query, copied over by the
parser) and values (obtained from your read):
```clj
{ :kw value-from-read-for-kw :j value-from-read-for-j }
```
Note that if your read accidentally returns a scalar for `:j` then you've not
done the right thing...a join like `{ :j [:k] }` expects a result that is a
vector of (zero or more) things *or* a singleton *map* that contains key
`:k`.
```clj
{ :kw 21 :j { :k 42 } }
; OR
{ :kw 21 :j [{ :k 42 } {:k 43}] }
```
Dealing with recursive queries is a natural fit for a recusive algorithm, and it
is perfectly fine to invoke the `parser` function to descend the query. In fact,
the `parser` is passed as part of your environment.
So, the read function you write will receive three arguments, as described below:
1. An environment containing:
+ `:ast`: An abstract syntax *tree* for the element, which contains:
+ `:type`: The type of node (e.g. :prop, :join, etc.)
+ `:dispatch-key`: The keyword portion of the triggering query element (e.g. :people/by-id)
+ `:key`: The full key of the triggering query element (e.g. [:people/by-id 1])
+ `:query`: (same as the query in `env`)
+ `:children`: If this node has sub-queries, will be AST nodes for those
+ others...see documentation
+ `:parser`: The query parser
+ `:query`: **if** the element had one E.g. `{:people [:user/name]}` has `:query` `[:user/name]`
+ Components you requested be injected
2. A dispatch key for the item that triggered the read (same as dispatch key in the AST)
3. Parameters (which are nil if not supplied in the query)
It must return a value that has the shape implied the grammar element being read.
So, lets try it out.
")
(defn read-42 [env key params] {:value 42})
(def parser-42 (om/parser {:read read-42}))
(defcard-doc
"
### Reading a keyword
If the parser encounters a keyword `:kw`, your function will be called with:
```clj
(your-read
{ :dispatch-key :kw :parser (fn ...) } ;; the environment: parser, etc.
:kw ;; the keyword
nil) ;; no parameters
```
your read function should return some value that makes sense for
that spot in the grammar. There are no real restrictions on what that data
value has to be in this case. You are reading a simple property.
There is no further shape implied by the grammar.
It could be a string, number, Entity Object, JS Date, nil, etc.
Due to additional features of the parser, *your return value must be wrapped in a
map with the key `:value`*. If you fail to do this, you will get nothing
in the result.
Thus, a very simple read for props (keywords) could be:
```clj
(defn read [env key params] { :value 42 })
```
below is a devcard that implements exactly this `read` and plugs it into a
parser like this:"
(dc/mkdn-pprint-source read-42)
(dc/mkdn-pprint-source parser-42))
(defn parser-tester [parser]
(fn [state _]
(let [{:keys [v error]} @state]
(dom/div nil
(dom/input #js {:type "text"
:value v
:onChange (fn [evt] (swap! state assoc :v (.. evt -target -value)))})
(dom/button #js {:onClick #(try
(swap! state assoc :error "" :result (parser {:state (atom (:db @state))} (r/read-string v)))
(catch js/Error e (swap! state assoc :error e))
)} "Run Parser")
(when error
(dom/div nil (str error)))
(dom/h4 nil "Query Result")
(html-edn (:result @state))
(dom/h4 nil "Database")
(html-edn (:db @state))))))
(defcard property-read-for-the-meaning-of-life-the-universe-and-everything
"This card is using the parser/read pairing shown above (the read returns
the value 42 no matter what it is asked for). Run any query you
want in it, and check out the answer.
This card just runs `(parser-42 {} your-query)` and reports the result.
Some examples to try:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester parser-42)
{:db {}})
(defn property-read [{:keys [state]} key params] {:value (get @state key :not-found)})
(def property-parser (om/parser {:read property-read}))
(defcard-doc
"
So now you have a read function that returns the meaning of life the universe and
everything in a single line of code! But now it is obvious that we need to build
an even bigger machine to understand the question.
If your server state is just a flat set of scalar values with unique keyword
identities, then a better read is similarly trivial.
The read function:
"
(dc/mkdn-pprint-source property-read)
"
Just assumes the property will be in the top-level of some injected state atom.
")
(defcard trivial-property-reader
"This card is using the `property-read` function above in a parser.
The database we're emulating is shown at the bottom of the card, after the
result.
Run some queries and see what you get. Some suggestions:
- `[:a :b :c]`
- `[:what-is-6-x-7]`
- `[{:a {:b {:c {:d [:e]}}}}]` (yes, there is only one answer)
"
(parser-tester property-parser)
{:db {:a 1 :b 2 :c 99}}
{:inspect-data true})
(def flat-app-state (atom {:a 1 :user/name "PI:NAME:<NAME>END_PI" :c 99}))
(defn flat-state-read [{:keys [state parser query] :as env} key params]
(if (= :user key)
{:value (parser env query)} ; recursive call. query is now [:user/name]
{:value (get @state key)})) ; gets called for :user/name :a and :c
(def my-parser (om/parser {:read flat-state-read}))
(defcard-doc
"
The result of those nested queries is supposed to be a nested map. So, obviously we
have more work to do.
### Reading a join
Your state probably has some more structure to it than just a flat
bag of properties. Joins are naturally recursive in syntax, and
those that are accustomed to writing parsers probably already see the solution.
First, let's clarify what the read function will receive for a join. When
parsing:
```clj
{ :j [:a :b :c] }
```
your read function will be called with:
```clj
(your-read { :state state :parser (fn ...) :query [:a :b :c] } ; the environment
:j ; keyword of the join
nil) ; no parameters
```
But just to prove a point about the separation of database format and
query structure we'll implement this next example
with a basic recursive parse, *but use more flat data* (the following is live code):
"
(dc/mkdn-pprint-source flat-app-state)
(dc/mkdn-pprint-source flat-state-read)
(dc/mkdn-pprint-source my-parser)
"
The important bit is the `then` part of the `if`. Return a value that is
the recursive parse of the sub-query. Otherwise, we just look up the keyword
in the state (which as you can see is a very flat map).
The result of running this parser on the query shown is:
"
(my-parser {:state flat-app-state} '[:a {:user [:user/name]} :c])
"
The first (possibly surprising thing) is that your result includes a nested
object. The parser creates the result, and the recusion natually nested the
result correctly.
Next you should remember that join implies a there could be one OR many results.
The singleton case is fine (e.g. putting a single map there). If there are
multiple results it should be a vector.
In this case, we're just showing that you can use the parser recursively
and it in turn will call your read function again.
In a real application, your data will not be this flat, so you
will almost certainly not do things in quite this
way.
So, let's put a little better state in our application, and write a
more realistic parser.
### A Non-trivial, recursive example
Let's start with the following hand-normalized application state:
"
(dc/mkdn-pprint-source parser1/app-state)
"
Our friend `db->tree` could handle queries against this database,
but let's implement it by hand.
Say we want to run this query:
"
(dc/mkdn-pprint-source parser1/query)
"
From the earlier discussion you see that we'll have to handle the
top level keys one at a time.
For this query there are only two keys to handle: `:friends`
and `:window-size`. So, let's write a case for each:
"
(dc/mkdn-pprint-source parser1/read)
"
The default case is `nil`, which means if we supply an errant key in the query no
exception will happen.
when we run the query, we get:
"
(parser1/parser {:state parser1/app-state} parser1/query)
"
Those of you paying close attention will notice that we have yet to need
recursion. We've also done something a bit naive: select-keys assumes
that query contains only keys! What if app state and query were instead:
"
(dc/mkdn-pprint-source parser2/app-state)
(dc/mkdn-pprint-source parser2/query)
"
Now things get interesting, and I'm sure more than one reader will have an
opinion on how to proceed. My aim is to show that the parser can be called
recursively to handle these things, not to find the perfect structure for the
parser in general, so I'm going to do something simple.
The primary trick I'm going to exploit is the fact that `env` is just a map, and
that we can add stuff to it. When we are in the context of a person, we'll add
`:person` to the environment, and pass that to a recursive call to `parser`.
"
(dc/mkdn-pprint-source parser2/read)
"
and running the query gives the expected result:
"
(parser2/parser {:state parser2/app-state} parser2/query)
"
All of the code shown here is being actively pulled (and run) from `untangled-devguide.state-reads.parser-2`.
Now, I feel compelled to mention a few things:
- Keeping track of where you are in the parse (e.g. person can be generalized to
'the current thing I'm working on') allows you to generalize this algorithm.
- `db->tree` can still do everything we've done so far.
- If you fully generalize the property and join parsing, you'll essentially recreate
`db->tree`.
So now you should be trying to remember why we're doing all of this. So let's talk
about a case that `db->tree` can't handle: parameters.
## Parameters
In the query grammar most kinds of rules accept parameters. These are intended
to be combined with dynamic queries that will allow your UI to have some control
over what you want to read from the application state (think filtering, pagination,
sorting, and such).
As you might expect, the parameters on a particular expression in the query
are just passed into your read function as the third argument.
You are responsible for both defining and interpreting them.
They have no rules other than they are maps.
To read the property `:load/start-time` with a parameter indicating a particular
time unit you might use:
```clj
[(:load/start-time {:units :seconds})]
```
this will invoke read with:
```clj
(your-read env :load/start-time { :units :seconds})
```
the implication is clear. The code is up to you. Let's add some quick support for this
in our read (in untangled-devguide.state-reads.parser-3):
"
(dc/mkdn-pprint-source parser3/app-state)
(dc/mkdn-pprint-source parser3/read)
(dc/mkdn-pprint-source parser3/parser)
"Now we can try the following queries:"
(dc/mkdn-pprint-source parser3/parse-result-mins)
parser3/parse-result-mins
(dc/mkdn-pprint-source parser3/parse-result-secs)
parser3/parse-result-secs
(dc/mkdn-pprint-source parser3/parse-result-ms)
parser3/parse-result-ms)
|
[
{
"context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day13b\n (:r",
"end": 39,
"score": 0.999570369720459,
"start": 21,
"tag": "NAME",
"value": "Mikołaj Kuranowski"
}
] |
src/day13b.clj
|
MKuranowski/AdventOfCode2020
| 0 |
; Copyright (c) 2021 Mikołaj Kuranowski
; SPDX-License-Identifier: WTFPL
(ns day13b
(:require [core]
[clojure.string :refer [split]]))
(defn parse-bus-lines
[file-line] (->> (split file-line #",")
(map list (iterate inc 0)) ;; similar to Python 'enumerate'
(filter #(not= (second %) "x"))
(map #(list (first %) (core/parse-int (second %))))))
(defn parse-file [filename]
(->> filename
core/lines-from-file
second
parse-bus-lines))
(defn modulus-result [[offset modulus]]
(list
modulus
(mod (- modulus offset) modulus)))
;; Stolen from https://rosettacode.org/wiki/Modular_inverse#Recursive_implementation
(defn multiplicative-inverse [a-arg b-arg]
(loop [a a-arg, b b-arg, s0 1, s1 0]
(if (= 0 b) (mod s0 b-arg)
(recur b, (mod a b), s1, (- s0 (* s1 (quot a b)))))))
;; Stolen from https://fangya.medium.com/chinese-remainder-theorem-with-python-a483de81fbb8
(defn chinese-remainder-theroem [mods-and-results]
(let [prod (reduce * (map first mods-and-results))]
(mod
(reduce
+
(for [[modulus result] mods-and-results
:let [p (quot prod modulus)]]
(* p result (multiplicative-inverse p modulus))))
prod)))
(defn -main [filename]
(->> filename
parse-file
(map modulus-result)
chinese-remainder-theroem
prn))
|
4994
|
; Copyright (c) 2021 <NAME>
; SPDX-License-Identifier: WTFPL
(ns day13b
(:require [core]
[clojure.string :refer [split]]))
(defn parse-bus-lines
[file-line] (->> (split file-line #",")
(map list (iterate inc 0)) ;; similar to Python 'enumerate'
(filter #(not= (second %) "x"))
(map #(list (first %) (core/parse-int (second %))))))
(defn parse-file [filename]
(->> filename
core/lines-from-file
second
parse-bus-lines))
(defn modulus-result [[offset modulus]]
(list
modulus
(mod (- modulus offset) modulus)))
;; Stolen from https://rosettacode.org/wiki/Modular_inverse#Recursive_implementation
(defn multiplicative-inverse [a-arg b-arg]
(loop [a a-arg, b b-arg, s0 1, s1 0]
(if (= 0 b) (mod s0 b-arg)
(recur b, (mod a b), s1, (- s0 (* s1 (quot a b)))))))
;; Stolen from https://fangya.medium.com/chinese-remainder-theorem-with-python-a483de81fbb8
(defn chinese-remainder-theroem [mods-and-results]
(let [prod (reduce * (map first mods-and-results))]
(mod
(reduce
+
(for [[modulus result] mods-and-results
:let [p (quot prod modulus)]]
(* p result (multiplicative-inverse p modulus))))
prod)))
(defn -main [filename]
(->> filename
parse-file
(map modulus-result)
chinese-remainder-theroem
prn))
| true |
; Copyright (c) 2021 PI:NAME:<NAME>END_PI
; SPDX-License-Identifier: WTFPL
(ns day13b
(:require [core]
[clojure.string :refer [split]]))
(defn parse-bus-lines
[file-line] (->> (split file-line #",")
(map list (iterate inc 0)) ;; similar to Python 'enumerate'
(filter #(not= (second %) "x"))
(map #(list (first %) (core/parse-int (second %))))))
(defn parse-file [filename]
(->> filename
core/lines-from-file
second
parse-bus-lines))
(defn modulus-result [[offset modulus]]
(list
modulus
(mod (- modulus offset) modulus)))
;; Stolen from https://rosettacode.org/wiki/Modular_inverse#Recursive_implementation
(defn multiplicative-inverse [a-arg b-arg]
(loop [a a-arg, b b-arg, s0 1, s1 0]
(if (= 0 b) (mod s0 b-arg)
(recur b, (mod a b), s1, (- s0 (* s1 (quot a b)))))))
;; Stolen from https://fangya.medium.com/chinese-remainder-theorem-with-python-a483de81fbb8
(defn chinese-remainder-theroem [mods-and-results]
(let [prod (reduce * (map first mods-and-results))]
(mod
(reduce
+
(for [[modulus result] mods-and-results
:let [p (quot prod modulus)]]
(* p result (multiplicative-inverse p modulus))))
prod)))
(defn -main [filename]
(->> filename
parse-file
(map modulus-result)
chinese-remainder-theroem
prn))
|
[
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License",
"end": 49,
"score": 0.9998836517333984,
"start": 37,
"tag": "NAME",
"value": "Ronen Narkis"
},
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ",
"end": 62,
"score": 0.8289394378662109,
"start": 51,
"tag": "EMAIL",
"value": "narkisr.com"
}
] |
src/es/core.clj
|
celestial-ops/core
| 1 |
(comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.core
"Core elasticsearch module"
(:require
[components.core :refer (Lifecyle)]
[es.common :refer (initialize index)]
[es.node :refer (connect stop)]))
(defrecord Elastic
[]
Lifecyle
(setup [this]
(connect)
(initialize))
(start [this]
(connect))
(stop [this]
(stop)))
(defn instance
"creates a Elastic components"
[]
(Elastic.))
|
44730
|
(comment
re-core, Copyright 2012 <NAME>, <EMAIL>
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.core
"Core elasticsearch module"
(:require
[components.core :refer (Lifecyle)]
[es.common :refer (initialize index)]
[es.node :refer (connect stop)]))
(defrecord Elastic
[]
Lifecyle
(setup [this]
(connect)
(initialize))
(start [this]
(connect))
(stop [this]
(stop)))
(defn instance
"creates a Elastic components"
[]
(Elastic.))
| true |
(comment
re-core, Copyright 2012 PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.core
"Core elasticsearch module"
(:require
[components.core :refer (Lifecyle)]
[es.common :refer (initialize index)]
[es.node :refer (connect stop)]))
(defrecord Elastic
[]
Lifecyle
(setup [this]
(connect)
(initialize))
(start [this]
(connect))
(stop [this]
(stop)))
(defn instance
"creates a Elastic components"
[]
(Elastic.))
|
[
{
"context": " [clj-http \"3.9.0\"]\n [jarohen/chime \"0.2.2\"]]\n :profiles {:uberjar {:main chic",
"end": 1558,
"score": 0.7917730808258057,
"start": 1554,
"tag": "USERNAME",
"value": "ohen"
},
{
"context": "gresql://localhost:5432/chick?user=chick&password=chick\"\n :redis-url \"redis://loc",
"end": 1976,
"score": 0.9986062049865723,
"start": 1971,
"tag": "PASSWORD",
"value": "chick"
},
{
"context": "lein-ring \"0.12.0\"]\n [jonase/eastwood \"0.2.7\"]\n [l",
"end": 2385,
"score": 0.6915654540061951,
"start": 2379,
"tag": "USERNAME",
"value": "jonase"
}
] |
project.clj
|
harehare/chick-japanese-api
| 0 |
(defproject chick "0.1.0-SNAPSHOT"
:description "Japanese morphological analysis API for Chick"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:ring {:handler chick.handler/app :async? true}
:uberjar-name "chick.jar"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:min-lein-version "2.7.1"
:migratus {:store :database
:migration-dir "migrations"
:db ~(get (System/getenv) "JDBC_DATABASE_URL")}
:dependencies [[com.atilika.kuromoji/kuromoji-ipadic "0.9.0"]
[com.layerware/hugsql "0.4.9"]
[org.clojure/clojure "1.9.0"]
[org.jsoup/jsoup "1.11.3"]
[org.clojure/java.jdbc "0.7.7"]
[org.clojure/data.json "0.2.6"]
[org.clojure/core.async "0.4.474"]
[org.clojure/test.check "0.9.0"]
[org.clojure/tools.logging "0.4.1"]
[org.slf4j/slf4j-api "1.7.25"]
[metosin/compojure-api "2.0.0-alpha20"]
[ring/ring-core "1.7.0-RC1"]
[ring/ring-jetty-adapter "1.7.0-RC1"]
[ring-ratelimit "0.2.2"]
[migratus "1.0.6"]
[org.postgresql/postgresql "42.2.2"]
[com.taoensso/carmine "2.18.1"]
[integrant "0.6.3"]
[ch.qos.logback/logback-classic "1.2.3"]
[compojure "1.6.1"]
[environ "1.1.0"]
[clj-http "3.9.0"]
[jarohen/chime "0.2.2"]]
:profiles {:uberjar {:main chick.core :aot :all}
:precomp {:source-paths ["src/java"] :aot :all}
:dev {:dependencies [[integrant/repl "0.2.0"]
[org.clojure/tools.nrepl "0.2.12"]
[cljfmt "0.5.7"]]
:env {:jdbc-database-url "jdbc:postgresql://localhost:5432/chick?user=chick&password=chick"
:redis-url "redis://localhost:6379"
:port "8080"}
:global-vars {*warn-on-reflection* true}
:plugins [[cider/cider-nrepl "0.17.0"]
[migratus-lein "0.5.7"]
[lein-kibit "0.1.6"]
[lein-ring "0.12.0"]
[jonase/eastwood "0.2.7"]
[lein-environ "1.1.0"]]
:source-paths ["env/dev/clj"]}})
|
19143
|
(defproject chick "0.1.0-SNAPSHOT"
:description "Japanese morphological analysis API for Chick"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:ring {:handler chick.handler/app :async? true}
:uberjar-name "chick.jar"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:min-lein-version "2.7.1"
:migratus {:store :database
:migration-dir "migrations"
:db ~(get (System/getenv) "JDBC_DATABASE_URL")}
:dependencies [[com.atilika.kuromoji/kuromoji-ipadic "0.9.0"]
[com.layerware/hugsql "0.4.9"]
[org.clojure/clojure "1.9.0"]
[org.jsoup/jsoup "1.11.3"]
[org.clojure/java.jdbc "0.7.7"]
[org.clojure/data.json "0.2.6"]
[org.clojure/core.async "0.4.474"]
[org.clojure/test.check "0.9.0"]
[org.clojure/tools.logging "0.4.1"]
[org.slf4j/slf4j-api "1.7.25"]
[metosin/compojure-api "2.0.0-alpha20"]
[ring/ring-core "1.7.0-RC1"]
[ring/ring-jetty-adapter "1.7.0-RC1"]
[ring-ratelimit "0.2.2"]
[migratus "1.0.6"]
[org.postgresql/postgresql "42.2.2"]
[com.taoensso/carmine "2.18.1"]
[integrant "0.6.3"]
[ch.qos.logback/logback-classic "1.2.3"]
[compojure "1.6.1"]
[environ "1.1.0"]
[clj-http "3.9.0"]
[jarohen/chime "0.2.2"]]
:profiles {:uberjar {:main chick.core :aot :all}
:precomp {:source-paths ["src/java"] :aot :all}
:dev {:dependencies [[integrant/repl "0.2.0"]
[org.clojure/tools.nrepl "0.2.12"]
[cljfmt "0.5.7"]]
:env {:jdbc-database-url "jdbc:postgresql://localhost:5432/chick?user=chick&password=<PASSWORD>"
:redis-url "redis://localhost:6379"
:port "8080"}
:global-vars {*warn-on-reflection* true}
:plugins [[cider/cider-nrepl "0.17.0"]
[migratus-lein "0.5.7"]
[lein-kibit "0.1.6"]
[lein-ring "0.12.0"]
[jonase/eastwood "0.2.7"]
[lein-environ "1.1.0"]]
:source-paths ["env/dev/clj"]}})
| true |
(defproject chick "0.1.0-SNAPSHOT"
:description "Japanese morphological analysis API for Chick"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:ring {:handler chick.handler/app :async? true}
:uberjar-name "chick.jar"
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:min-lein-version "2.7.1"
:migratus {:store :database
:migration-dir "migrations"
:db ~(get (System/getenv) "JDBC_DATABASE_URL")}
:dependencies [[com.atilika.kuromoji/kuromoji-ipadic "0.9.0"]
[com.layerware/hugsql "0.4.9"]
[org.clojure/clojure "1.9.0"]
[org.jsoup/jsoup "1.11.3"]
[org.clojure/java.jdbc "0.7.7"]
[org.clojure/data.json "0.2.6"]
[org.clojure/core.async "0.4.474"]
[org.clojure/test.check "0.9.0"]
[org.clojure/tools.logging "0.4.1"]
[org.slf4j/slf4j-api "1.7.25"]
[metosin/compojure-api "2.0.0-alpha20"]
[ring/ring-core "1.7.0-RC1"]
[ring/ring-jetty-adapter "1.7.0-RC1"]
[ring-ratelimit "0.2.2"]
[migratus "1.0.6"]
[org.postgresql/postgresql "42.2.2"]
[com.taoensso/carmine "2.18.1"]
[integrant "0.6.3"]
[ch.qos.logback/logback-classic "1.2.3"]
[compojure "1.6.1"]
[environ "1.1.0"]
[clj-http "3.9.0"]
[jarohen/chime "0.2.2"]]
:profiles {:uberjar {:main chick.core :aot :all}
:precomp {:source-paths ["src/java"] :aot :all}
:dev {:dependencies [[integrant/repl "0.2.0"]
[org.clojure/tools.nrepl "0.2.12"]
[cljfmt "0.5.7"]]
:env {:jdbc-database-url "jdbc:postgresql://localhost:5432/chick?user=chick&password=PI:PASSWORD:<PASSWORD>END_PI"
:redis-url "redis://localhost:6379"
:port "8080"}
:global-vars {*warn-on-reflection* true}
:plugins [[cider/cider-nrepl "0.17.0"]
[migratus-lein "0.5.7"]
[lein-kibit "0.1.6"]
[lein-ring "0.12.0"]
[jonase/eastwood "0.2.7"]
[lein-environ "1.1.0"]]
:source-paths ["env/dev/clj"]}})
|
[
{
"context": " :dbpedia.resource/Pablo-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"",
"end": 833,
"score": 0.9995059967041016,
"start": 828,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "-Picasso ; id\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"}\n #inst \"1881-10-25T09",
"end": 859,
"score": 0.9995893239974976,
"start": 852,
"tag": "NAME",
"value": "Picasso"
},
{
"context": ".resource/Pablo-Picasso ; old version\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"",
"end": 1146,
"score": 0.9994680881500244,
"start": 1141,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "; old version\n :name \"Pablo\"\n :last-name \"Picasso\"\n :location \"Spain\"}\n {:crux.db/id :dbpedi",
"end": 1172,
"score": 0.9996047019958496,
"start": 1165,
"tag": "NAME",
"value": "Picasso"
},
{
"context": ".resource/Pablo-Picasso ; new version\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n ",
"end": 1278,
"score": 0.9996002912521362,
"start": 1273,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "; new version\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n :location \"France\"}\n #",
"end": 1304,
"score": 0.9995490312576294,
"start": 1297,
"tag": "NAME",
"value": "Picasso"
},
{
"context": "ux/db system)\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true}) ; using `:full-resul",
"end": 2144,
"score": 0.9974247813224792,
"start": 2139,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "7.966-00:00\")\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true})\n\n\n; `put` the new ve",
"end": 2410,
"score": 0.9986141920089722,
"start": 2405,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "db/id :dbpedia.resource/Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n ",
"end": 2596,
"score": 0.9996871948242188,
"start": 2591,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "Pablo-Picasso\n :name \"Pablo\"\n :last-name \"Picasso\"\n :height 1.63\n :location \"France\"}\n #",
"end": 2622,
"score": 0.999618411064148,
"start": 2615,
"tag": "NAME",
"value": "Picasso"
},
{
"context": "ux/db system)\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true})\n\n\n; again, query the",
"end": 2818,
"score": 0.9979735016822815,
"start": 2813,
"tag": "NAME",
"value": "Pablo"
},
{
"context": "7.966-00:00\")\n '{:find [e]\n :where [[e :name \"Pablo\"]]\n :full-results? true})\n\n\n(comment\n ; use t",
"end": 3037,
"score": 0.9985644817352295,
"start": 3032,
"tag": "NAME",
"value": "Pablo"
}
] |
example/repl-walkthrough/walkthrough.clj
|
souenzzo/crux
| 0 |
; load a repl with the latest Crux dependency, e.g. using clj:
; $ clj -Sdeps '{:deps {juxt/crux {:mvn/version "19.06-1.1.0-alpha"}}}'
(ns walkthrough.crux-standalone
(:require [crux.api :as crux])
(:import (crux.api ICruxAPI)))
; this standalone configuration is the easiest way to try Crux, no Kafka needed
(def crux-options
{:kv-backend "crux.kv.memdb.MemKv" ; in-memory, see docs for LMDB/RocksDB storage
:event-log-dir "data/event-log-dir-1" ; :event-log-dir is ignored when using MemKv
:db-dir "data/db-dir-1"}) ; :db-dir is ignored when using MemKv
(def system (crux/start-standalone-system crux-options))
; transaction containing a `put` operation, optionally specifying a valid time
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; id
:name "Pablo"
:last-name "Picasso"
:location "Spain"}
#inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth
; transaction containing a `cas` (compare-and-swap) operation
(crux/submit-tx
system
[[:crux.tx/cas
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; old version
:name "Pablo"
:last-name "Picasso"
:location "Spain"}
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; new version
:name "Pablo"
:last-name "Picasso"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death
; transaction containing a `delete` operation, historical versions remain
(crux/submit-tx
system
[[:crux.tx/delete :dbpedia.resource/Pablo-Picasso
#inst "1973-04-08T09:20:27.966-00:00"]])
; transaction containing an `evict` operation, historical data is destroyed
(crux/submit-tx
system
[[:crux.tx/evict :dbpedia.resource/Pablo-Picasso
#inst "1973-04-07T09:20:27.966-00:00" ; start-valid-time
#inst "1973-04-09T09:20:27.966-00:00" ; end-valid-time (optional)
false ; keep-latest? (optional)
true]]) ; keep-earliest? (optional)
; query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "Pablo"]]
:full-results? true}) ; using `:full-results?` is useful for manual queries
; query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "Pablo"]]
:full-results? true})
; `put` the new version of the document again
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "Pablo"
:last-name "Picasso"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]])
; again, query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "Pablo"]]
:full-results? true})
; again, query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "Pablo"]]
:full-results? true})
(comment
; use the following to help when not starting the system from the REPL
(defn run-system [{:keys [server-port] :as options} with-system-fn]
(with-open [crux-system (crux/start-standalone-system options)]
(with-system-fn crux-system)))
(declare s system)
; run a system and return control to the REPL
(def ^ICruxAPI s
(future
(run-system
crux-options
(fn [crux-system]
(def system crux-system)
(Thread/sleep Long/MAX_VALUE)))))
; close the system by cancelling the future
(future-cancel s)
; ...or close the system directly
(.close system)
)
|
48745
|
; load a repl with the latest Crux dependency, e.g. using clj:
; $ clj -Sdeps '{:deps {juxt/crux {:mvn/version "19.06-1.1.0-alpha"}}}'
(ns walkthrough.crux-standalone
(:require [crux.api :as crux])
(:import (crux.api ICruxAPI)))
; this standalone configuration is the easiest way to try Crux, no Kafka needed
(def crux-options
{:kv-backend "crux.kv.memdb.MemKv" ; in-memory, see docs for LMDB/RocksDB storage
:event-log-dir "data/event-log-dir-1" ; :event-log-dir is ignored when using MemKv
:db-dir "data/db-dir-1"}) ; :db-dir is ignored when using MemKv
(def system (crux/start-standalone-system crux-options))
; transaction containing a `put` operation, optionally specifying a valid time
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; id
:name "<NAME>"
:last-name "<NAME>"
:location "Spain"}
#inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth
; transaction containing a `cas` (compare-and-swap) operation
(crux/submit-tx
system
[[:crux.tx/cas
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; old version
:name "<NAME>"
:last-name "<NAME>"
:location "Spain"}
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; new version
:name "<NAME>"
:last-name "<NAME>"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death
; transaction containing a `delete` operation, historical versions remain
(crux/submit-tx
system
[[:crux.tx/delete :dbpedia.resource/Pablo-Picasso
#inst "1973-04-08T09:20:27.966-00:00"]])
; transaction containing an `evict` operation, historical data is destroyed
(crux/submit-tx
system
[[:crux.tx/evict :dbpedia.resource/Pablo-Picasso
#inst "1973-04-07T09:20:27.966-00:00" ; start-valid-time
#inst "1973-04-09T09:20:27.966-00:00" ; end-valid-time (optional)
false ; keep-latest? (optional)
true]]) ; keep-earliest? (optional)
; query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "<NAME>"]]
:full-results? true}) ; using `:full-results?` is useful for manual queries
; query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "<NAME>"]]
:full-results? true})
; `put` the new version of the document again
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "<NAME>"
:last-name "<NAME>"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]])
; again, query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "<NAME>"]]
:full-results? true})
; again, query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "<NAME>"]]
:full-results? true})
(comment
; use the following to help when not starting the system from the REPL
(defn run-system [{:keys [server-port] :as options} with-system-fn]
(with-open [crux-system (crux/start-standalone-system options)]
(with-system-fn crux-system)))
(declare s system)
; run a system and return control to the REPL
(def ^ICruxAPI s
(future
(run-system
crux-options
(fn [crux-system]
(def system crux-system)
(Thread/sleep Long/MAX_VALUE)))))
; close the system by cancelling the future
(future-cancel s)
; ...or close the system directly
(.close system)
)
| true |
; load a repl with the latest Crux dependency, e.g. using clj:
; $ clj -Sdeps '{:deps {juxt/crux {:mvn/version "19.06-1.1.0-alpha"}}}'
(ns walkthrough.crux-standalone
(:require [crux.api :as crux])
(:import (crux.api ICruxAPI)))
; this standalone configuration is the easiest way to try Crux, no Kafka needed
(def crux-options
{:kv-backend "crux.kv.memdb.MemKv" ; in-memory, see docs for LMDB/RocksDB storage
:event-log-dir "data/event-log-dir-1" ; :event-log-dir is ignored when using MemKv
:db-dir "data/db-dir-1"}) ; :db-dir is ignored when using MemKv
(def system (crux/start-standalone-system crux-options))
; transaction containing a `put` operation, optionally specifying a valid time
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; id
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:location "Spain"}
#inst "1881-10-25T09:20:27.966-00:00"]]) ; valid time, Picasso's birth
; transaction containing a `cas` (compare-and-swap) operation
(crux/submit-tx
system
[[:crux.tx/cas
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; old version
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:location "Spain"}
{:crux.db/id :dbpedia.resource/Pablo-Picasso ; new version
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]]) ; valid time, Picasso's death
; transaction containing a `delete` operation, historical versions remain
(crux/submit-tx
system
[[:crux.tx/delete :dbpedia.resource/Pablo-Picasso
#inst "1973-04-08T09:20:27.966-00:00"]])
; transaction containing an `evict` operation, historical data is destroyed
(crux/submit-tx
system
[[:crux.tx/evict :dbpedia.resource/Pablo-Picasso
#inst "1973-04-07T09:20:27.966-00:00" ; start-valid-time
#inst "1973-04-09T09:20:27.966-00:00" ; end-valid-time (optional)
false ; keep-latest? (optional)
true]]) ; keep-earliest? (optional)
; query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]
:full-results? true}) ; using `:full-results?` is useful for manual queries
; query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]
:full-results? true})
; `put` the new version of the document again
(crux/submit-tx
system
[[:crux.tx/put
{:crux.db/id :dbpedia.resource/Pablo-Picasso
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:height 1.63
:location "France"}
#inst "1973-04-08T09:20:27.966-00:00"]])
; again, query the system as-of now
(crux/q
(crux/db system)
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]
:full-results? true})
; again, query the system as-of now, as-at #inst "1973-04-07T09:20:27.966-00:00"
(crux/q
(crux/db system #inst "1973-04-07T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]
:full-results? true})
(comment
; use the following to help when not starting the system from the REPL
(defn run-system [{:keys [server-port] :as options} with-system-fn]
(with-open [crux-system (crux/start-standalone-system options)]
(with-system-fn crux-system)))
(declare s system)
; run a system and return control to the REPL
(def ^ICruxAPI s
(future
(run-system
crux-options
(fn [crux-system]
(def system crux-system)
(Thread/sleep Long/MAX_VALUE)))))
; close the system by cancelling the future
(future-cancel s)
; ...or close the system directly
(.close system)
)
|
[
{
"context": "yerPartner/\") n))\n\n(def lawyerPartnerMap { \n\t:name fullname\n\t:type type\n\t:city city})\n\n(defrecord LawyerPartn",
"end": 363,
"score": 0.993579626083374,
"start": 355,
"tag": "NAME",
"value": "fullname"
}
] |
src/clojsesame/integration/lawyer_partnerships.clj
|
hotlib/datanest2rdf
| 0 |
(ns clojsesame.integration.lawyer_partnerships
(:require
[clojsesame.vocabulary :refer :all]
[clojsesame.sesame :refer :all]))
(def lawyerPartnerInfo {:filename "dumps/lawyer_partnerships-dump.csv" :type :lawyerPartner})
(defn- lawyerPartnerURI [{ n :name}]
(createURI (str basicNamespace "/lawyerPartner/") n))
(def lawyerPartnerMap {
:name fullname
:type type
:city city})
(defrecord LawyerPartnership [name type city]
SesameRepository
(store [x]
(storeRecord lawyerPartnerURI lawyerPartnerMap x)))
(defmethod convert :lawyerPartner [x type]
(let [[_ fullName type _ _ _ _ city] x]
(->LawyerPartnership fullName type city)))
|
58633
|
(ns clojsesame.integration.lawyer_partnerships
(:require
[clojsesame.vocabulary :refer :all]
[clojsesame.sesame :refer :all]))
(def lawyerPartnerInfo {:filename "dumps/lawyer_partnerships-dump.csv" :type :lawyerPartner})
(defn- lawyerPartnerURI [{ n :name}]
(createURI (str basicNamespace "/lawyerPartner/") n))
(def lawyerPartnerMap {
:name <NAME>
:type type
:city city})
(defrecord LawyerPartnership [name type city]
SesameRepository
(store [x]
(storeRecord lawyerPartnerURI lawyerPartnerMap x)))
(defmethod convert :lawyerPartner [x type]
(let [[_ fullName type _ _ _ _ city] x]
(->LawyerPartnership fullName type city)))
| true |
(ns clojsesame.integration.lawyer_partnerships
(:require
[clojsesame.vocabulary :refer :all]
[clojsesame.sesame :refer :all]))
(def lawyerPartnerInfo {:filename "dumps/lawyer_partnerships-dump.csv" :type :lawyerPartner})
(defn- lawyerPartnerURI [{ n :name}]
(createURI (str basicNamespace "/lawyerPartner/") n))
(def lawyerPartnerMap {
:name PI:NAME:<NAME>END_PI
:type type
:city city})
(defrecord LawyerPartnership [name type city]
SesameRepository
(store [x]
(storeRecord lawyerPartnerURI lawyerPartnerMap x)))
(defmethod convert :lawyerPartner [x type]
(let [[_ fullName type _ _ _ _ city] x]
(->LawyerPartnership fullName type city)))
|
[
{
"context": " handling, logging, caching, etc.\n \"\n {:author \"Jon Anthony\"}\n\n (:gen-class)\n\n (:require [clojure.string :a",
"end": 164,
"score": 0.9998712539672852,
"start": 153,
"tag": "NAME",
"value": "Jon Anthony"
}
] |
src/iobio/core.clj
|
jsa-aerial/clj-iobio
| 1 |
(ns iobio.core
"A robust, flexible clj iobio with full tree graphs, function nodes,
superior error handling, logging, caching, etc.
"
{:author "Jon Anthony"}
(:gen-class)
(:require [clojure.string :as cstr]
[clojure.java.io :as io]
[cpath-clj.core :as cp] ; Extract Jar resources
[clj-dns.core :as rdns] ; reverse dns
[aerial.fs :as fs]
[aerial.utils.misc :refer [getenv]]
[aerial.utils.coll :as coll]
[iobio.server :as svr])
(:import [java.io File]
[java.net NetworkInterface Inet4Address Inet6Address]))
(defn- digits? [s] (let [x (re-find #"[0-9]+" s)] (and x (= x s))))
(defn host-ipaddress []
(->> (NetworkInterface/getNetworkInterfaces)
enumeration-seq
(filter #(and (.isUp %) (not (.isVirtual %)) (not (.isLoopback %))))
(map #(vector (.getName %) %))
(mapv (fn[[n intf]]
[(keyword n)
(->> intf .getInetAddresses enumeration-seq
(group-by #(cond (instance? Inet4Address %) :inet4
(instance? Inet6Address %) :inet6
:else :unknown))
(reduce (fn[M [k ifv]]
(assoc M k (mapv #(.getHostAddress %) ifv)))
{})
)]))
(into {})))
(defn host-dns-name []
(-> (host-ipaddress) :eth0 :inet4 first rdns/hostname))
(defn- get-install-dir
"Query user for location that will be iobio installation and home
directory
"
[]
(print "Enter installation directory [~/.iobio]: ")
(flush)
(let [input (read-line)
input (fs/fullpath (if (= input "") "~.iobio" input))]
(println "Selected installation location:" input)
input))
(defn- install-host-dns-name [bamiobio]
(let [rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
[hline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
host-line (str " this.clj_iobio_host = " (host-dns-name) ";")
tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [host-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :done))
(defn install-iobio
"Create installation directory, mark it as the home directory and
install required resources and set the host machine dns lookup name
in websocket address. IOBIODIR is the directory user gave on query
for location to install.
"
[iobiodir]
(let [resmap #{"bam.iobio.io" "vcf.iobio.io"}
resdir "resources/"]
(println "Creating installation(iobio home) directory")
(fs/mkdirs iobiodir)
(println "Marking installation directory as iobio home")
(spit (fs/join iobiodir ".iobio-home-dir") "Home directory of iobio")
(println "Installing resources...")
(fs/mkdir (fs/join iobiodir "pipes"))
(fs/mkdir (fs/join iobiodir "cache"))
(doseq [res ["services" "bin" #_"bam.iobio.io" #_"vcf.iobio.io"]]
(doseq [[path uris] (cp/resources (io/resource res))
:let [uri (first uris)
relative-path (subs path 1)
output-dir (->> relative-path
fs/dirname
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath)
output-file (->> relative-path
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath io/file)]]
(when (not (re-find #"^pack/" path)) ; bug in cp/resources regexer
(println :PATH path)
(println :RELATIVE-PATH relative-path)
(when (not (fs/exists? output-dir))
(fs/mkdirs output-dir))
(println uri :->> output-file)
(with-open [in (io/input-stream uri)]
(io/copy in output-file))
(when (= res "bin")
(.setExecutable output-file true false)))))
#_(println "Setting host dns name for websockets ...")
#_(install-host-dns-name
(fs/join (fs/fullpath iobiodir)
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js"))
#_(println "Host name used: " (host-dns-name))
(println "\n\n*** Installation complete")))
(defn- find-set-home-dir
"Tries to find the iobio home directory and, if not current working
directory sets working directory to home directory.
"
[]
(let [iobioev "IOBIO_HOME"
evdir (-> iobioev getenv fs/fullpath)
curdir (fs/pwd)
stdhm (fs/fullpath "~/.iobio")]
(cond
(and (getenv iobioev) (not= evdir curdir)
(->> ".iobio-home-dir" (fs/join evdir) fs/exists?))
(do (fs/cd evdir) evdir)
(->> ".iobio-home-dir" (fs/join curdir) fs/exists?) curdir
(and (fs/exists? stdhm) (not= stdhm curdir)
(->> ".iobio-home-dir" (fs/join stdhm) fs/exists?))
(do (fs/cd stdhm) stdhm)
:else nil)))
(defn- ensure-correct-port-in-bamiobio
"Change clj-iobio-port in bam.iobio.io if it is not the same as
port. This ensures user can start server on different ports w/o
needing to edit JS files. Only changes/writes new bam.iobio.js if
the clj-iobio port in the current file is not the same as port.
"
[port]
(let [bamiobio (fs/normpath
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js")
rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
[pline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
curport (-> pline (cstr/split #"=") second
cstr/trim (cstr/split #";") first Integer.)
port-line (str " this.clj_iobio_port = " port ";")]
(if (= port curport)
(.close rdr)
(let [tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [port-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :fixed))))
(defn- run-server
"Run the iobio server on port PORT. Change clj-iobio-port in
bam.iobio.io if it is not the same as port. This ensures user can
start server on different ports w/o needing to edit JS files.
"
[port]
#_(ensure-correct-port-in-bamiobio port)
(svr/start! port))
(defn -main
"Self installation and web server"
[& [port]]
(cond
(and port (digits? port))
(if (find-set-home-dir)
(run-server (Integer. port))
(do (println "iobio server must run in home directory") (System/exit 1)))
port (do (println "Port must be an integer, e.g., 8080") (System/exit 1))
:else ; Install iobio
(let [iobiodir (get-install-dir)]
(if (fs/exists? iobiodir)
(do (println "Selected install dir already exists!") (System/exit 1))
(install-iobio iobiodir)))))
|
22718
|
(ns iobio.core
"A robust, flexible clj iobio with full tree graphs, function nodes,
superior error handling, logging, caching, etc.
"
{:author "<NAME>"}
(:gen-class)
(:require [clojure.string :as cstr]
[clojure.java.io :as io]
[cpath-clj.core :as cp] ; Extract Jar resources
[clj-dns.core :as rdns] ; reverse dns
[aerial.fs :as fs]
[aerial.utils.misc :refer [getenv]]
[aerial.utils.coll :as coll]
[iobio.server :as svr])
(:import [java.io File]
[java.net NetworkInterface Inet4Address Inet6Address]))
(defn- digits? [s] (let [x (re-find #"[0-9]+" s)] (and x (= x s))))
(defn host-ipaddress []
(->> (NetworkInterface/getNetworkInterfaces)
enumeration-seq
(filter #(and (.isUp %) (not (.isVirtual %)) (not (.isLoopback %))))
(map #(vector (.getName %) %))
(mapv (fn[[n intf]]
[(keyword n)
(->> intf .getInetAddresses enumeration-seq
(group-by #(cond (instance? Inet4Address %) :inet4
(instance? Inet6Address %) :inet6
:else :unknown))
(reduce (fn[M [k ifv]]
(assoc M k (mapv #(.getHostAddress %) ifv)))
{})
)]))
(into {})))
(defn host-dns-name []
(-> (host-ipaddress) :eth0 :inet4 first rdns/hostname))
(defn- get-install-dir
"Query user for location that will be iobio installation and home
directory
"
[]
(print "Enter installation directory [~/.iobio]: ")
(flush)
(let [input (read-line)
input (fs/fullpath (if (= input "") "~.iobio" input))]
(println "Selected installation location:" input)
input))
(defn- install-host-dns-name [bamiobio]
(let [rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
[hline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
host-line (str " this.clj_iobio_host = " (host-dns-name) ";")
tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [host-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :done))
(defn install-iobio
"Create installation directory, mark it as the home directory and
install required resources and set the host machine dns lookup name
in websocket address. IOBIODIR is the directory user gave on query
for location to install.
"
[iobiodir]
(let [resmap #{"bam.iobio.io" "vcf.iobio.io"}
resdir "resources/"]
(println "Creating installation(iobio home) directory")
(fs/mkdirs iobiodir)
(println "Marking installation directory as iobio home")
(spit (fs/join iobiodir ".iobio-home-dir") "Home directory of iobio")
(println "Installing resources...")
(fs/mkdir (fs/join iobiodir "pipes"))
(fs/mkdir (fs/join iobiodir "cache"))
(doseq [res ["services" "bin" #_"bam.iobio.io" #_"vcf.iobio.io"]]
(doseq [[path uris] (cp/resources (io/resource res))
:let [uri (first uris)
relative-path (subs path 1)
output-dir (->> relative-path
fs/dirname
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath)
output-file (->> relative-path
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath io/file)]]
(when (not (re-find #"^pack/" path)) ; bug in cp/resources regexer
(println :PATH path)
(println :RELATIVE-PATH relative-path)
(when (not (fs/exists? output-dir))
(fs/mkdirs output-dir))
(println uri :->> output-file)
(with-open [in (io/input-stream uri)]
(io/copy in output-file))
(when (= res "bin")
(.setExecutable output-file true false)))))
#_(println "Setting host dns name for websockets ...")
#_(install-host-dns-name
(fs/join (fs/fullpath iobiodir)
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js"))
#_(println "Host name used: " (host-dns-name))
(println "\n\n*** Installation complete")))
(defn- find-set-home-dir
"Tries to find the iobio home directory and, if not current working
directory sets working directory to home directory.
"
[]
(let [iobioev "IOBIO_HOME"
evdir (-> iobioev getenv fs/fullpath)
curdir (fs/pwd)
stdhm (fs/fullpath "~/.iobio")]
(cond
(and (getenv iobioev) (not= evdir curdir)
(->> ".iobio-home-dir" (fs/join evdir) fs/exists?))
(do (fs/cd evdir) evdir)
(->> ".iobio-home-dir" (fs/join curdir) fs/exists?) curdir
(and (fs/exists? stdhm) (not= stdhm curdir)
(->> ".iobio-home-dir" (fs/join stdhm) fs/exists?))
(do (fs/cd stdhm) stdhm)
:else nil)))
(defn- ensure-correct-port-in-bamiobio
"Change clj-iobio-port in bam.iobio.io if it is not the same as
port. This ensures user can start server on different ports w/o
needing to edit JS files. Only changes/writes new bam.iobio.js if
the clj-iobio port in the current file is not the same as port.
"
[port]
(let [bamiobio (fs/normpath
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js")
rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
[pline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
curport (-> pline (cstr/split #"=") second
cstr/trim (cstr/split #";") first Integer.)
port-line (str " this.clj_iobio_port = " port ";")]
(if (= port curport)
(.close rdr)
(let [tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [port-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :fixed))))
(defn- run-server
"Run the iobio server on port PORT. Change clj-iobio-port in
bam.iobio.io if it is not the same as port. This ensures user can
start server on different ports w/o needing to edit JS files.
"
[port]
#_(ensure-correct-port-in-bamiobio port)
(svr/start! port))
(defn -main
"Self installation and web server"
[& [port]]
(cond
(and port (digits? port))
(if (find-set-home-dir)
(run-server (Integer. port))
(do (println "iobio server must run in home directory") (System/exit 1)))
port (do (println "Port must be an integer, e.g., 8080") (System/exit 1))
:else ; Install iobio
(let [iobiodir (get-install-dir)]
(if (fs/exists? iobiodir)
(do (println "Selected install dir already exists!") (System/exit 1))
(install-iobio iobiodir)))))
| true |
(ns iobio.core
"A robust, flexible clj iobio with full tree graphs, function nodes,
superior error handling, logging, caching, etc.
"
{:author "PI:NAME:<NAME>END_PI"}
(:gen-class)
(:require [clojure.string :as cstr]
[clojure.java.io :as io]
[cpath-clj.core :as cp] ; Extract Jar resources
[clj-dns.core :as rdns] ; reverse dns
[aerial.fs :as fs]
[aerial.utils.misc :refer [getenv]]
[aerial.utils.coll :as coll]
[iobio.server :as svr])
(:import [java.io File]
[java.net NetworkInterface Inet4Address Inet6Address]))
(defn- digits? [s] (let [x (re-find #"[0-9]+" s)] (and x (= x s))))
(defn host-ipaddress []
(->> (NetworkInterface/getNetworkInterfaces)
enumeration-seq
(filter #(and (.isUp %) (not (.isVirtual %)) (not (.isLoopback %))))
(map #(vector (.getName %) %))
(mapv (fn[[n intf]]
[(keyword n)
(->> intf .getInetAddresses enumeration-seq
(group-by #(cond (instance? Inet4Address %) :inet4
(instance? Inet6Address %) :inet6
:else :unknown))
(reduce (fn[M [k ifv]]
(assoc M k (mapv #(.getHostAddress %) ifv)))
{})
)]))
(into {})))
(defn host-dns-name []
(-> (host-ipaddress) :eth0 :inet4 first rdns/hostname))
(defn- get-install-dir
"Query user for location that will be iobio installation and home
directory
"
[]
(print "Enter installation directory [~/.iobio]: ")
(flush)
(let [input (read-line)
input (fs/fullpath (if (= input "") "~.iobio" input))]
(println "Selected installation location:" input)
input))
(defn- install-host-dns-name [bamiobio]
(let [rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
[hline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_host" %) lines)
host-line (str " this.clj_iobio_host = " (host-dns-name) ";")
tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [host-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :done))
(defn install-iobio
"Create installation directory, mark it as the home directory and
install required resources and set the host machine dns lookup name
in websocket address. IOBIODIR is the directory user gave on query
for location to install.
"
[iobiodir]
(let [resmap #{"bam.iobio.io" "vcf.iobio.io"}
resdir "resources/"]
(println "Creating installation(iobio home) directory")
(fs/mkdirs iobiodir)
(println "Marking installation directory as iobio home")
(spit (fs/join iobiodir ".iobio-home-dir") "Home directory of iobio")
(println "Installing resources...")
(fs/mkdir (fs/join iobiodir "pipes"))
(fs/mkdir (fs/join iobiodir "cache"))
(doseq [res ["services" "bin" #_"bam.iobio.io" #_"vcf.iobio.io"]]
(doseq [[path uris] (cp/resources (io/resource res))
:let [uri (first uris)
relative-path (subs path 1)
output-dir (->> relative-path
fs/dirname
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath)
output-file (->> relative-path
(fs/join
iobiodir
(if (resmap res) (str resdir res) res))
fs/fullpath io/file)]]
(when (not (re-find #"^pack/" path)) ; bug in cp/resources regexer
(println :PATH path)
(println :RELATIVE-PATH relative-path)
(when (not (fs/exists? output-dir))
(fs/mkdirs output-dir))
(println uri :->> output-file)
(with-open [in (io/input-stream uri)]
(io/copy in output-file))
(when (= res "bin")
(.setExecutable output-file true false)))))
#_(println "Setting host dns name for websockets ...")
#_(install-host-dns-name
(fs/join (fs/fullpath iobiodir)
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js"))
#_(println "Host name used: " (host-dns-name))
(println "\n\n*** Installation complete")))
(defn- find-set-home-dir
"Tries to find the iobio home directory and, if not current working
directory sets working directory to home directory.
"
[]
(let [iobioev "IOBIO_HOME"
evdir (-> iobioev getenv fs/fullpath)
curdir (fs/pwd)
stdhm (fs/fullpath "~/.iobio")]
(cond
(and (getenv iobioev) (not= evdir curdir)
(->> ".iobio-home-dir" (fs/join evdir) fs/exists?))
(do (fs/cd evdir) evdir)
(->> ".iobio-home-dir" (fs/join curdir) fs/exists?) curdir
(and (fs/exists? stdhm) (not= stdhm curdir)
(->> ".iobio-home-dir" (fs/join stdhm) fs/exists?))
(do (fs/cd stdhm) stdhm)
:else nil)))
(defn- ensure-correct-port-in-bamiobio
"Change clj-iobio-port in bam.iobio.io if it is not the same as
port. This ensures user can start server on different ports w/o
needing to edit JS files. Only changes/writes new bam.iobio.js if
the clj-iobio port in the current file is not the same as port.
"
[port]
(let [bamiobio (fs/normpath
"resources/bam.iobio.io/js/bam.iobio.js/bam.iobio.js")
rdr (io/reader bamiobio)
lines (line-seq rdr)
prefix (coll/takev-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
[pline & suffix] (coll/dropv-until
#(re-find #"^ *this.clj_iobio_port" %) lines)
curport (-> pline (cstr/split #"=") second
cstr/trim (cstr/split #";") first Integer.)
port-line (str " this.clj_iobio_port = " port ";")]
(if (= port curport)
(.close rdr)
(let [tmp (fs/tempfile "bam.iobio")]
(with-open [wtr (io/writer tmp)]
(binding [*out* wtr]
(doseq [l (concat prefix [port-line] suffix)]
(println l))))
(.close rdr)
(fs/copy tmp bamiobio)
(fs/delete tmp) :fixed))))
(defn- run-server
"Run the iobio server on port PORT. Change clj-iobio-port in
bam.iobio.io if it is not the same as port. This ensures user can
start server on different ports w/o needing to edit JS files.
"
[port]
#_(ensure-correct-port-in-bamiobio port)
(svr/start! port))
(defn -main
"Self installation and web server"
[& [port]]
(cond
(and port (digits? port))
(if (find-set-home-dir)
(run-server (Integer. port))
(do (println "iobio server must run in home directory") (System/exit 1)))
port (do (println "Port must be an integer, e.g., 8080") (System/exit 1))
:else ; Install iobio
(let [iobiodir (get-install-dir)]
(if (fs/exists? iobiodir)
(do (println "Selected install dir already exists!") (System/exit 1))
(install-iobio iobiodir)))))
|
[
{
"context": ";; Copyright © 2017 Douglas P. Fields, Jr. All Rights Reserved.\n;; Web: https://symboli",
"end": 37,
"score": 0.999852180480957,
"start": 20,
"tag": "NAME",
"value": "Douglas P. Fields"
},
{
"context": "; Web: https://symbolics.lisp.engineer/\n;; E-mail: [email protected]\n;; Twitter: @LispEngineer\n\n\n(ns engineer.lisp.fas",
"end": 139,
"score": 0.9999136328697205,
"start": 116,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "er/\n;; E-mail: [email protected]\n;; Twitter: @LispEngineer\n\n\n(ns engineer.lisp.fast-atom.core)\n\n(defn foo\n ",
"end": 165,
"score": 0.998304545879364,
"start": 152,
"tag": "USERNAME",
"value": "@LispEngineer"
}
] |
src/engineer/lisp/fast_atom/core.clj
|
LispEngineer/fast-atom
| 0 |
;; Copyright © 2017 Douglas P. Fields, Jr. All Rights Reserved.
;; Web: https://symbolics.lisp.engineer/
;; E-mail: [email protected]
;; Twitter: @LispEngineer
(ns engineer.lisp.fast-atom.core)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
|
52088
|
;; Copyright © 2017 <NAME>, Jr. All Rights Reserved.
;; Web: https://symbolics.lisp.engineer/
;; E-mail: <EMAIL>
;; Twitter: @LispEngineer
(ns engineer.lisp.fast-atom.core)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
| true |
;; Copyright © 2017 PI:NAME:<NAME>END_PI, Jr. All Rights Reserved.
;; Web: https://symbolics.lisp.engineer/
;; E-mail: PI:EMAIL:<EMAIL>END_PI
;; Twitter: @LispEngineer
(ns engineer.lisp.fast-atom.core)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
|
[
{
"context": "; Copyright (c) Chris Houser, Dec 2008. All rights reserved.\r\n; The use and ",
"end": 31,
"score": 0.9998650550842285,
"start": 19,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "ed interactively at the REPL\r\n\r\n(ns\r\n ^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim\"",
"end": 558,
"score": 0.9998833537101746,
"start": 546,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "ely at the REPL\r\n\r\n(ns\r\n ^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim\"\r\n :doc \"Utili",
"end": 576,
"score": 0.999862015247345,
"start": 560,
"tag": "NAME",
"value": "Christophe Grand"
},
{
"context": "\n(ns\r\n ^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim\"\r\n :doc \"Utilities meant to be ",
"end": 593,
"score": 0.9998475909233093,
"start": 578,
"tag": "NAME",
"value": "Stephen Gilardi"
},
{
"context": " \"Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim\"\r\n :doc \"Utilities meant to be used interacti",
"end": 607,
"score": 0.9998339414596558,
"start": 595,
"tag": "NAME",
"value": "Michel Salim"
}
] |
Source/clojure/repl.clj
|
pjago/Arcadia
| 0 |
; Copyright (c) Chris Houser, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT 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.
; Utilities meant to be used interactively at the REPL
(ns
^{:author "Chris Houser, Christophe Grand, Stephen Gilardi, Michel Salim"
:doc "Utilities meant to be used interactively at the REPL"}
clojure.repl
(:require [clojure.spec :as spec])
) ;;;(:import (java.io LineNumberReader InputStreamReader PushbackReader)
;;; (clojure.lang RT Reflector)))
(def ^:private special-doc-map
'{. {:url "java_interop#dot"
:forms [(.instanceMember instance args*)
(.instanceMember Classname args*)
(Classname/staticMethod args*)
Classname/staticField]
:doc "The instance member form works for both fields and methods.
They all expand into calls to the dot operator at macroexpansion time."}
def {:forms [(def symbol doc-string? init?)]
:doc "Creates and interns a global var with the name
of symbol in the current namespace (*ns*) or locates such a var if
it already exists. If init is supplied, it is evaluated, and the
root binding of the var is set to the resulting value. If init is
not supplied, the root binding of the var is unaffected."}
do {:forms [(do exprs*)]
:doc "Evaluates the expressions in order and returns the value of
the last. If no expressions are supplied, returns nil."}
if {:forms [(if test then else?)]
:doc "Evaluates test. If not the singular values nil or false,
evaluates and yields then, otherwise, evaluates and yields else. If
else is not supplied it defaults to nil."}
monitor-enter {:forms [(monitor-enter x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
monitor-exit {:forms [(monitor-exit x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
new {:forms [(Classname. args*) (new Classname args*)]
:url "java_interop#new"
:doc "The args, if any, are evaluated from left to right, and
passed to the constructor of the class named by Classname. The
constructed object is returned."}
quote {:forms [(quote form)]
:doc "Yields the unevaluated form."}
recur {:forms [(recur exprs*)]
:doc "Evaluates the exprs in order, then, in parallel, rebinds
the bindings of the recursion point to the values of the exprs.
Execution then jumps back to the recursion point, a loop or fn method."}
set! {:forms[(set! var-symbol expr)
(set! (. instance-expr instanceFieldName-symbol) expr)
(set! (. Classname-symbol staticFieldName-symbol) expr)]
:url "vars#set"
:doc "Used to set thread-local-bound vars, Java object instance
fields, and Java class static fields."}
throw {:forms [(throw expr)]
:doc "The expr is evaluated and thrown, therefore it should
yield an instance of some derivee of Throwable."}
try {:forms [(try expr* catch-clause* finally-clause?)]
:doc "catch-clause => (catch classname name expr*)
finally-clause => (finally expr*)
Catches and handles Java exceptions."}
var {:forms [(var symbol)]
:doc "The symbol must resolve to a var, and the Var object
itself (not its value) is returned. The reader macro #'x expands to (var x)."}})
(defn- special-doc [name-symbol]
(assoc (or (special-doc-map name-symbol) (meta (resolve name-symbol)))
:name name-symbol
:special-form true))
(defn- namespace-doc [nspace]
(assoc (meta nspace) :name (ns-name nspace)))
(defn- print-doc [{n :ns
nm :name
:keys [forms arglists special-form doc url macro spec]
:as m}]
(println "-------------------------")
(println (or spec (str (when n (str (ns-name n) "/")) nm)))
(when forms
(doseq [f forms]
(print " ")
(prn f)))
(when arglists
(prn arglists))
(cond
special-form
(do
(println "Special Form")
(println " " doc)
(if (contains? m :url)
(when url
(println (str "\n Please see http://clojure.org/" url)))
(println (str "\n Please see http://clojure.org/special_forms#" nm))))
macro
(println "Macro")
spec
(println "Spec"))
(when doc (println " " doc))
(when n
(when-let [fnspec (spec/get-spec (symbol (str (ns-name n)) (name nm)))]
(println "Spec")
(doseq [role [:args :ret :fn]]
(when-let [spec (get fnspec role)]
(println " " (str (name role) ":") (spec/describe spec)))))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
{:added "1.0"}
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)
ms (concat (mapcat #(sort-by :name (map meta (vals (ns-interns %))))
(all-ns))
(map namespace-doc (all-ns))
(map special-doc (keys special-doc-map)))]
(doseq [m ms
:when (and (:doc m)
(or (re-find (re-matcher re (:doc m)))
(re-find (re-matcher re (str (:name m))))))]
(print-doc m))))
(defmacro doc
"Prints documentation for a var or special form given its name,
or for a spec if given a keyword"
{:added "1.0"}
[name]
(if-let [special-name ('{& fn catch try finally try} name)]
(#'print-doc (#'special-doc special-name))
(cond
(special-doc-map name) `(#'print-doc (#'special-doc '~name))
(keyword? name) `(#'print-doc {:spec '~name :doc '~(spec/describe name)})
(find-ns name) `(#'print-doc (#'namespace-doc (find-ns '~name)))
(resolve name) `(#'print-doc (meta (var ~name))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn source-fn
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (source-fn 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [ ^System.IO.FileInfo info (clojure.lang.RT/FindFile filepath) ] ;;; [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [ ^System.IO.TextReader rdr (.OpenText info)] ;;; [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.ReadLine rdr)) ;;; .readLine
(let [text (StringBuilder.)
pbr (proxy [clojure.lang.PushbackTextReader] [rdr] ;;; [PushbackReader] [rdr]
(Read [] (let [i (proxy-super Read)] ;;; read read
(.Append text (char i)) ;;; .append
i)))
read-opts (if (.EndsWith ^String filepath "cljc") {:read-cond :allow} {})] ;;; .endsWith
(if (= :unknown *read-eval*)
(throw (InvalidOperationException. "Unable to read source while *read-eval* is :unknown.")) ;;; IllegalStateException
(read read-opts (clojure.lang.PushbackTextReader. pbr))) ;;; (read read-opts(PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (source-fn '~n) (str "Source not found"))))
(defn apropos
"Given a regular expression or stringable thing, return a seq of all
public definitions in all currently-loaded namespaces that match the
str-or-pattern."
[str-or-pattern]
(let [matches? (if (instance? System.Text.RegularExpressions.Regex str-or-pattern) ;;; java.util.regex.Pattern
#(re-find str-or-pattern (str %))
#(.Contains (str %) (str str-or-pattern)))] ;;; .contains
(sort (mapcat (fn [ns]
(let [ns-name (str ns)]
(map #(symbol ns-name (str %))
(filter matches? (keys (ns-publics ns))))))
(all-ns)))))
(defn dir-fn
"Returns a sorted seq of symbols naming public vars in
a namespace or namespace alias. Looks for aliases in *ns*"
[ns]
(sort (map first (ns-publics (the-ns (get (ns-aliases *ns*) ns ns))))))
(defmacro dir
"Prints a sorted directory of public vars in a namespace"
[nsname]
`(doseq [v# (dir-fn '~nsname)]
(println v#)))
(defn demunge
"Given a string representation of a fn class,
as in a stack trace element, returns a readable version."
{:added "1.3"}
[fn-name]
(clojure.lang.Compiler/demunge fn-name))
(defn root-cause
"Returns the initial cause of an exception or error by peeling off all of
its wrappers"
[ ^Exception t] ;;; ^Throwable
(loop [cause t]
(if (and (instance? clojure.lang.Compiler+CompilerException cause)
(not= (.Source ^clojure.lang.Compiler+CompilerException cause) "NO_SOURCE_FILE")) ;;; .source
cause
(if-let [cause (.InnerException cause)] ;;; .getCause
(recur cause)
cause))))
;;; Added -DM
(defn get-stack-trace
"Gets the stack trace for an Exception"
[^Exception e]
(.GetFrames (System.Diagnostics.StackTrace. e true)))
(defn stack-element-classname
[^System.Diagnostics.StackFrame el]
(if-let [t (.. el (GetMethod) ReflectedType)]
(.FullName t)
""))
(defn stack-element-methodname
[^System.Diagnostics.StackFrame el]
(.. el (GetMethod) Name))
;;;
(defn stack-element-str
"Returns a (possibly unmunged) string representation of a StackTraceElement"
{:added "1.3"}
[^System.Diagnostics.StackFrame el] ;;; StackTraceElement
(let [file (.GetFileName el) ;;; getFileName
clojure-fn? (and file (or (.EndsWith file ".clj") ;;; endsWith
(.EndsWith file ".cljc") ;;; endsWith
(= file "NO_SOURCE_FILE")))]
(str (if clojure-fn?
(demunge (stack-element-classname el)) ;;; (.getClassName el))
(str (stack-element-classname el) "." (stack-element-methodname el))) ;;; (.getClassName el) (.getMethodName el)
" (" (.GetFileName el) ":" (.GetFileLineNumber el) ")"))) ;;; getFileName getLineNumber
(defn pst
"Prints a stack trace of the exception, to the depth requsted. If none supplied, uses the root cause of the
most recent repl exception (*e), and a depth of 12."
{:added "1.3"}
([] (pst 12))
([e-or-depth]
(if (instance? Exception e-or-depth) ;;; Throwable
(pst e-or-depth 12)
(when-let [e *e]
(pst (root-cause e) e-or-depth))))
([^Exception e depth] ;;; Throwable
(binding [*out* *err*]
(println (str (-> e class .Name) " " ;;; .getSimpleName
(.Message e) ;;; getMessage
(when-let [info (ex-data e)] (str " " (pr-str info)))))
(let [st (get-stack-trace e) ;;; (.getStackTrace e)
cause (.InnerException e)] ;;; .getCause
(doseq [el (take depth
(remove #(#{"clojure.lang.RestFn" "clojure.lang.AFn" "clojure.lang.AFnImpl" "clojure.lang.RestFnImpl"} (stack-element-classname %)) ;;; (.getClassName %)
st))]
(println (str \tab (stack-element-str el))))
(when cause
(println "Caused by:")
(pst cause (min depth
(+ 2 (- (count (get-stack-trace cause)) ;;; (.getStackTrace cause)
(count st))))))))))
|
73600
|
; Copyright (c) <NAME>, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT 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.
; Utilities meant to be used interactively at the REPL
(ns
^{:author "<NAME>, <NAME>, <NAME>, <NAME>"
:doc "Utilities meant to be used interactively at the REPL"}
clojure.repl
(:require [clojure.spec :as spec])
) ;;;(:import (java.io LineNumberReader InputStreamReader PushbackReader)
;;; (clojure.lang RT Reflector)))
(def ^:private special-doc-map
'{. {:url "java_interop#dot"
:forms [(.instanceMember instance args*)
(.instanceMember Classname args*)
(Classname/staticMethod args*)
Classname/staticField]
:doc "The instance member form works for both fields and methods.
They all expand into calls to the dot operator at macroexpansion time."}
def {:forms [(def symbol doc-string? init?)]
:doc "Creates and interns a global var with the name
of symbol in the current namespace (*ns*) or locates such a var if
it already exists. If init is supplied, it is evaluated, and the
root binding of the var is set to the resulting value. If init is
not supplied, the root binding of the var is unaffected."}
do {:forms [(do exprs*)]
:doc "Evaluates the expressions in order and returns the value of
the last. If no expressions are supplied, returns nil."}
if {:forms [(if test then else?)]
:doc "Evaluates test. If not the singular values nil or false,
evaluates and yields then, otherwise, evaluates and yields else. If
else is not supplied it defaults to nil."}
monitor-enter {:forms [(monitor-enter x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
monitor-exit {:forms [(monitor-exit x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
new {:forms [(Classname. args*) (new Classname args*)]
:url "java_interop#new"
:doc "The args, if any, are evaluated from left to right, and
passed to the constructor of the class named by Classname. The
constructed object is returned."}
quote {:forms [(quote form)]
:doc "Yields the unevaluated form."}
recur {:forms [(recur exprs*)]
:doc "Evaluates the exprs in order, then, in parallel, rebinds
the bindings of the recursion point to the values of the exprs.
Execution then jumps back to the recursion point, a loop or fn method."}
set! {:forms[(set! var-symbol expr)
(set! (. instance-expr instanceFieldName-symbol) expr)
(set! (. Classname-symbol staticFieldName-symbol) expr)]
:url "vars#set"
:doc "Used to set thread-local-bound vars, Java object instance
fields, and Java class static fields."}
throw {:forms [(throw expr)]
:doc "The expr is evaluated and thrown, therefore it should
yield an instance of some derivee of Throwable."}
try {:forms [(try expr* catch-clause* finally-clause?)]
:doc "catch-clause => (catch classname name expr*)
finally-clause => (finally expr*)
Catches and handles Java exceptions."}
var {:forms [(var symbol)]
:doc "The symbol must resolve to a var, and the Var object
itself (not its value) is returned. The reader macro #'x expands to (var x)."}})
(defn- special-doc [name-symbol]
(assoc (or (special-doc-map name-symbol) (meta (resolve name-symbol)))
:name name-symbol
:special-form true))
(defn- namespace-doc [nspace]
(assoc (meta nspace) :name (ns-name nspace)))
(defn- print-doc [{n :ns
nm :name
:keys [forms arglists special-form doc url macro spec]
:as m}]
(println "-------------------------")
(println (or spec (str (when n (str (ns-name n) "/")) nm)))
(when forms
(doseq [f forms]
(print " ")
(prn f)))
(when arglists
(prn arglists))
(cond
special-form
(do
(println "Special Form")
(println " " doc)
(if (contains? m :url)
(when url
(println (str "\n Please see http://clojure.org/" url)))
(println (str "\n Please see http://clojure.org/special_forms#" nm))))
macro
(println "Macro")
spec
(println "Spec"))
(when doc (println " " doc))
(when n
(when-let [fnspec (spec/get-spec (symbol (str (ns-name n)) (name nm)))]
(println "Spec")
(doseq [role [:args :ret :fn]]
(when-let [spec (get fnspec role)]
(println " " (str (name role) ":") (spec/describe spec)))))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
{:added "1.0"}
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)
ms (concat (mapcat #(sort-by :name (map meta (vals (ns-interns %))))
(all-ns))
(map namespace-doc (all-ns))
(map special-doc (keys special-doc-map)))]
(doseq [m ms
:when (and (:doc m)
(or (re-find (re-matcher re (:doc m)))
(re-find (re-matcher re (str (:name m))))))]
(print-doc m))))
(defmacro doc
"Prints documentation for a var or special form given its name,
or for a spec if given a keyword"
{:added "1.0"}
[name]
(if-let [special-name ('{& fn catch try finally try} name)]
(#'print-doc (#'special-doc special-name))
(cond
(special-doc-map name) `(#'print-doc (#'special-doc '~name))
(keyword? name) `(#'print-doc {:spec '~name :doc '~(spec/describe name)})
(find-ns name) `(#'print-doc (#'namespace-doc (find-ns '~name)))
(resolve name) `(#'print-doc (meta (var ~name))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn source-fn
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (source-fn 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [ ^System.IO.FileInfo info (clojure.lang.RT/FindFile filepath) ] ;;; [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [ ^System.IO.TextReader rdr (.OpenText info)] ;;; [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.ReadLine rdr)) ;;; .readLine
(let [text (StringBuilder.)
pbr (proxy [clojure.lang.PushbackTextReader] [rdr] ;;; [PushbackReader] [rdr]
(Read [] (let [i (proxy-super Read)] ;;; read read
(.Append text (char i)) ;;; .append
i)))
read-opts (if (.EndsWith ^String filepath "cljc") {:read-cond :allow} {})] ;;; .endsWith
(if (= :unknown *read-eval*)
(throw (InvalidOperationException. "Unable to read source while *read-eval* is :unknown.")) ;;; IllegalStateException
(read read-opts (clojure.lang.PushbackTextReader. pbr))) ;;; (read read-opts(PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (source-fn '~n) (str "Source not found"))))
(defn apropos
"Given a regular expression or stringable thing, return a seq of all
public definitions in all currently-loaded namespaces that match the
str-or-pattern."
[str-or-pattern]
(let [matches? (if (instance? System.Text.RegularExpressions.Regex str-or-pattern) ;;; java.util.regex.Pattern
#(re-find str-or-pattern (str %))
#(.Contains (str %) (str str-or-pattern)))] ;;; .contains
(sort (mapcat (fn [ns]
(let [ns-name (str ns)]
(map #(symbol ns-name (str %))
(filter matches? (keys (ns-publics ns))))))
(all-ns)))))
(defn dir-fn
"Returns a sorted seq of symbols naming public vars in
a namespace or namespace alias. Looks for aliases in *ns*"
[ns]
(sort (map first (ns-publics (the-ns (get (ns-aliases *ns*) ns ns))))))
(defmacro dir
"Prints a sorted directory of public vars in a namespace"
[nsname]
`(doseq [v# (dir-fn '~nsname)]
(println v#)))
(defn demunge
"Given a string representation of a fn class,
as in a stack trace element, returns a readable version."
{:added "1.3"}
[fn-name]
(clojure.lang.Compiler/demunge fn-name))
(defn root-cause
"Returns the initial cause of an exception or error by peeling off all of
its wrappers"
[ ^Exception t] ;;; ^Throwable
(loop [cause t]
(if (and (instance? clojure.lang.Compiler+CompilerException cause)
(not= (.Source ^clojure.lang.Compiler+CompilerException cause) "NO_SOURCE_FILE")) ;;; .source
cause
(if-let [cause (.InnerException cause)] ;;; .getCause
(recur cause)
cause))))
;;; Added -DM
(defn get-stack-trace
"Gets the stack trace for an Exception"
[^Exception e]
(.GetFrames (System.Diagnostics.StackTrace. e true)))
(defn stack-element-classname
[^System.Diagnostics.StackFrame el]
(if-let [t (.. el (GetMethod) ReflectedType)]
(.FullName t)
""))
(defn stack-element-methodname
[^System.Diagnostics.StackFrame el]
(.. el (GetMethod) Name))
;;;
(defn stack-element-str
"Returns a (possibly unmunged) string representation of a StackTraceElement"
{:added "1.3"}
[^System.Diagnostics.StackFrame el] ;;; StackTraceElement
(let [file (.GetFileName el) ;;; getFileName
clojure-fn? (and file (or (.EndsWith file ".clj") ;;; endsWith
(.EndsWith file ".cljc") ;;; endsWith
(= file "NO_SOURCE_FILE")))]
(str (if clojure-fn?
(demunge (stack-element-classname el)) ;;; (.getClassName el))
(str (stack-element-classname el) "." (stack-element-methodname el))) ;;; (.getClassName el) (.getMethodName el)
" (" (.GetFileName el) ":" (.GetFileLineNumber el) ")"))) ;;; getFileName getLineNumber
(defn pst
"Prints a stack trace of the exception, to the depth requsted. If none supplied, uses the root cause of the
most recent repl exception (*e), and a depth of 12."
{:added "1.3"}
([] (pst 12))
([e-or-depth]
(if (instance? Exception e-or-depth) ;;; Throwable
(pst e-or-depth 12)
(when-let [e *e]
(pst (root-cause e) e-or-depth))))
([^Exception e depth] ;;; Throwable
(binding [*out* *err*]
(println (str (-> e class .Name) " " ;;; .getSimpleName
(.Message e) ;;; getMessage
(when-let [info (ex-data e)] (str " " (pr-str info)))))
(let [st (get-stack-trace e) ;;; (.getStackTrace e)
cause (.InnerException e)] ;;; .getCause
(doseq [el (take depth
(remove #(#{"clojure.lang.RestFn" "clojure.lang.AFn" "clojure.lang.AFnImpl" "clojure.lang.RestFnImpl"} (stack-element-classname %)) ;;; (.getClassName %)
st))]
(println (str \tab (stack-element-str el))))
(when cause
(println "Caused by:")
(pst cause (min depth
(+ 2 (- (count (get-stack-trace cause)) ;;; (.getStackTrace cause)
(count st))))))))))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT 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.
; Utilities meant to be used interactively at the REPL
(ns
^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"
:doc "Utilities meant to be used interactively at the REPL"}
clojure.repl
(:require [clojure.spec :as spec])
) ;;;(:import (java.io LineNumberReader InputStreamReader PushbackReader)
;;; (clojure.lang RT Reflector)))
(def ^:private special-doc-map
'{. {:url "java_interop#dot"
:forms [(.instanceMember instance args*)
(.instanceMember Classname args*)
(Classname/staticMethod args*)
Classname/staticField]
:doc "The instance member form works for both fields and methods.
They all expand into calls to the dot operator at macroexpansion time."}
def {:forms [(def symbol doc-string? init?)]
:doc "Creates and interns a global var with the name
of symbol in the current namespace (*ns*) or locates such a var if
it already exists. If init is supplied, it is evaluated, and the
root binding of the var is set to the resulting value. If init is
not supplied, the root binding of the var is unaffected."}
do {:forms [(do exprs*)]
:doc "Evaluates the expressions in order and returns the value of
the last. If no expressions are supplied, returns nil."}
if {:forms [(if test then else?)]
:doc "Evaluates test. If not the singular values nil or false,
evaluates and yields then, otherwise, evaluates and yields else. If
else is not supplied it defaults to nil."}
monitor-enter {:forms [(monitor-enter x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
monitor-exit {:forms [(monitor-exit x)]
:doc "Synchronization primitive that should be avoided
in user code. Use the 'locking' macro."}
new {:forms [(Classname. args*) (new Classname args*)]
:url "java_interop#new"
:doc "The args, if any, are evaluated from left to right, and
passed to the constructor of the class named by Classname. The
constructed object is returned."}
quote {:forms [(quote form)]
:doc "Yields the unevaluated form."}
recur {:forms [(recur exprs*)]
:doc "Evaluates the exprs in order, then, in parallel, rebinds
the bindings of the recursion point to the values of the exprs.
Execution then jumps back to the recursion point, a loop or fn method."}
set! {:forms[(set! var-symbol expr)
(set! (. instance-expr instanceFieldName-symbol) expr)
(set! (. Classname-symbol staticFieldName-symbol) expr)]
:url "vars#set"
:doc "Used to set thread-local-bound vars, Java object instance
fields, and Java class static fields."}
throw {:forms [(throw expr)]
:doc "The expr is evaluated and thrown, therefore it should
yield an instance of some derivee of Throwable."}
try {:forms [(try expr* catch-clause* finally-clause?)]
:doc "catch-clause => (catch classname name expr*)
finally-clause => (finally expr*)
Catches and handles Java exceptions."}
var {:forms [(var symbol)]
:doc "The symbol must resolve to a var, and the Var object
itself (not its value) is returned. The reader macro #'x expands to (var x)."}})
(defn- special-doc [name-symbol]
(assoc (or (special-doc-map name-symbol) (meta (resolve name-symbol)))
:name name-symbol
:special-form true))
(defn- namespace-doc [nspace]
(assoc (meta nspace) :name (ns-name nspace)))
(defn- print-doc [{n :ns
nm :name
:keys [forms arglists special-form doc url macro spec]
:as m}]
(println "-------------------------")
(println (or spec (str (when n (str (ns-name n) "/")) nm)))
(when forms
(doseq [f forms]
(print " ")
(prn f)))
(when arglists
(prn arglists))
(cond
special-form
(do
(println "Special Form")
(println " " doc)
(if (contains? m :url)
(when url
(println (str "\n Please see http://clojure.org/" url)))
(println (str "\n Please see http://clojure.org/special_forms#" nm))))
macro
(println "Macro")
spec
(println "Spec"))
(when doc (println " " doc))
(when n
(when-let [fnspec (spec/get-spec (symbol (str (ns-name n)) (name nm)))]
(println "Spec")
(doseq [role [:args :ret :fn]]
(when-let [spec (get fnspec role)]
(println " " (str (name role) ":") (spec/describe spec)))))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
{:added "1.0"}
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)
ms (concat (mapcat #(sort-by :name (map meta (vals (ns-interns %))))
(all-ns))
(map namespace-doc (all-ns))
(map special-doc (keys special-doc-map)))]
(doseq [m ms
:when (and (:doc m)
(or (re-find (re-matcher re (:doc m)))
(re-find (re-matcher re (str (:name m))))))]
(print-doc m))))
(defmacro doc
"Prints documentation for a var or special form given its name,
or for a spec if given a keyword"
{:added "1.0"}
[name]
(if-let [special-name ('{& fn catch try finally try} name)]
(#'print-doc (#'special-doc special-name))
(cond
(special-doc-map name) `(#'print-doc (#'special-doc '~name))
(keyword? name) `(#'print-doc {:spec '~name :doc '~(spec/describe name)})
(find-ns name) `(#'print-doc (#'namespace-doc (find-ns '~name)))
(resolve name) `(#'print-doc (meta (var ~name))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn source-fn
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (source-fn 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [ ^System.IO.FileInfo info (clojure.lang.RT/FindFile filepath) ] ;;; [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [ ^System.IO.TextReader rdr (.OpenText info)] ;;; [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.ReadLine rdr)) ;;; .readLine
(let [text (StringBuilder.)
pbr (proxy [clojure.lang.PushbackTextReader] [rdr] ;;; [PushbackReader] [rdr]
(Read [] (let [i (proxy-super Read)] ;;; read read
(.Append text (char i)) ;;; .append
i)))
read-opts (if (.EndsWith ^String filepath "cljc") {:read-cond :allow} {})] ;;; .endsWith
(if (= :unknown *read-eval*)
(throw (InvalidOperationException. "Unable to read source while *read-eval* is :unknown.")) ;;; IllegalStateException
(read read-opts (clojure.lang.PushbackTextReader. pbr))) ;;; (read read-opts(PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (source-fn '~n) (str "Source not found"))))
(defn apropos
"Given a regular expression or stringable thing, return a seq of all
public definitions in all currently-loaded namespaces that match the
str-or-pattern."
[str-or-pattern]
(let [matches? (if (instance? System.Text.RegularExpressions.Regex str-or-pattern) ;;; java.util.regex.Pattern
#(re-find str-or-pattern (str %))
#(.Contains (str %) (str str-or-pattern)))] ;;; .contains
(sort (mapcat (fn [ns]
(let [ns-name (str ns)]
(map #(symbol ns-name (str %))
(filter matches? (keys (ns-publics ns))))))
(all-ns)))))
(defn dir-fn
"Returns a sorted seq of symbols naming public vars in
a namespace or namespace alias. Looks for aliases in *ns*"
[ns]
(sort (map first (ns-publics (the-ns (get (ns-aliases *ns*) ns ns))))))
(defmacro dir
"Prints a sorted directory of public vars in a namespace"
[nsname]
`(doseq [v# (dir-fn '~nsname)]
(println v#)))
(defn demunge
"Given a string representation of a fn class,
as in a stack trace element, returns a readable version."
{:added "1.3"}
[fn-name]
(clojure.lang.Compiler/demunge fn-name))
(defn root-cause
"Returns the initial cause of an exception or error by peeling off all of
its wrappers"
[ ^Exception t] ;;; ^Throwable
(loop [cause t]
(if (and (instance? clojure.lang.Compiler+CompilerException cause)
(not= (.Source ^clojure.lang.Compiler+CompilerException cause) "NO_SOURCE_FILE")) ;;; .source
cause
(if-let [cause (.InnerException cause)] ;;; .getCause
(recur cause)
cause))))
;;; Added -DM
(defn get-stack-trace
"Gets the stack trace for an Exception"
[^Exception e]
(.GetFrames (System.Diagnostics.StackTrace. e true)))
(defn stack-element-classname
[^System.Diagnostics.StackFrame el]
(if-let [t (.. el (GetMethod) ReflectedType)]
(.FullName t)
""))
(defn stack-element-methodname
[^System.Diagnostics.StackFrame el]
(.. el (GetMethod) Name))
;;;
(defn stack-element-str
"Returns a (possibly unmunged) string representation of a StackTraceElement"
{:added "1.3"}
[^System.Diagnostics.StackFrame el] ;;; StackTraceElement
(let [file (.GetFileName el) ;;; getFileName
clojure-fn? (and file (or (.EndsWith file ".clj") ;;; endsWith
(.EndsWith file ".cljc") ;;; endsWith
(= file "NO_SOURCE_FILE")))]
(str (if clojure-fn?
(demunge (stack-element-classname el)) ;;; (.getClassName el))
(str (stack-element-classname el) "." (stack-element-methodname el))) ;;; (.getClassName el) (.getMethodName el)
" (" (.GetFileName el) ":" (.GetFileLineNumber el) ")"))) ;;; getFileName getLineNumber
(defn pst
"Prints a stack trace of the exception, to the depth requsted. If none supplied, uses the root cause of the
most recent repl exception (*e), and a depth of 12."
{:added "1.3"}
([] (pst 12))
([e-or-depth]
(if (instance? Exception e-or-depth) ;;; Throwable
(pst e-or-depth 12)
(when-let [e *e]
(pst (root-cause e) e-or-depth))))
([^Exception e depth] ;;; Throwable
(binding [*out* *err*]
(println (str (-> e class .Name) " " ;;; .getSimpleName
(.Message e) ;;; getMessage
(when-let [info (ex-data e)] (str " " (pr-str info)))))
(let [st (get-stack-trace e) ;;; (.getStackTrace e)
cause (.InnerException e)] ;;; .getCause
(doseq [el (take depth
(remove #(#{"clojure.lang.RestFn" "clojure.lang.AFn" "clojure.lang.AFnImpl" "clojure.lang.RestFnImpl"} (stack-element-classname %)) ;;; (.getClassName %)
st))]
(println (str \tab (stack-element-str el))))
(when cause
(println "Caused by:")
(pst cause (min depth
(+ 2 (- (count (get-stack-trace cause)) ;;; (.getStackTrace cause)
(count st))))))))))
|
[
{
"context": "clj (config/get-in path default-value)\n ; TODO(Richo): Make the CLJS version work for real...\n :clj",
"end": 1089,
"score": 0.9569216370582581,
"start": 1084,
"tag": "NAME",
"value": "Richo"
},
{
"context": " (ports/disconnect! conn)\n ; TODO(Richo): I used to think there was some sort of race con",
"end": 2967,
"score": 0.9973429441452026,
"start": 2962,
"tag": "NAME",
"value": "Richo"
},
{
"context": "ram)\n sent))\n\n(defn install [program]\n ; TODO(Richo): Should I store the installed program?\n (let [b",
"end": 5649,
"score": 0.7177413702011108,
"start": 5644,
"tag": "NAME",
"value": "Richo"
},
{
"context": " sent (send! (p/install bytecodes))]\n ; TODO(Richo): This message is actually a lie, we really don't",
"end": 5788,
"score": 0.9916115999221802,
"start": 5783,
"tag": "NAME",
"value": "Richo"
},
{
"context": " keep-alive-loop []\n (go\n (loop []\n ; TODO(Richo): We shouldn't need to send a keep alive unless\n ",
"end": 7137,
"score": 0.972391664981842,
"start": 7132,
"tag": "NAME",
"value": "Richo"
}
] |
middleware/server/src/middleware/device/controller.cljc
|
GIRA/PhysicalBits
| 2 |
(ns middleware.device.controller
(:require #?(:clj [clojure.tools.logging :as log])
[middleware.device.ports.scanner :as port-scanner]
[clojure.core.async :as a :refer [<! >! go go-loop timeout]]
[middleware.device.ports.common :as ports]
[middleware.device.protocol :as p]
[middleware.device.boards :refer [UNO get-pin-number get-pin-name]]
[middleware.compilation.encoder :as en]
[middleware.ast.utils :as ast]
[middleware.program.utils :as program]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.logger :as logger]
#?(:clj [middleware.utils.config :as config])
[middleware.utils.core :refer [millis clamp]]))
(comment
(start-profiling)
(stop-profiling)
(.getTime (js/Date.))
(set-report-interval 5)
@state
,)
(defn- log-error [msg e]
#?(:clj (log/error msg e)
:cljs (println "ERROR:" msg e)))
(defn- get-config [path default-value]
#?(:clj (config/get-in path default-value)
; TODO(Richo): Make the CLJS version work for real...
:cljs default-value))
(def initial-state {:connection nil
:board UNO
:reporting {:pins #{}, :globals #{}}
:pins {}
:globals {}
:pseudo-vars {:timestamp nil, :data {}}
:scripts []
:profiler nil
:debugger nil
:timing {:arduino nil, :middleware nil, :diffs nil}
:memory {:arduino nil, :uzi nil}
:program {:current nil, :running nil}})
(def state (atom initial-state))
(def update-chan (a/chan 100))
(def updates (a/mult update-chan))
(defn- add-pseudo-var! [name value]
(if (get-config [:device :pseudo-vars?] false)
(let [now (or (-> @state :timing :arduino) 0)]
(swap! state
#(-> %
(assoc-in [:pseudo-vars :timestamp] now)
(assoc-in [:pseudo-vars :data name]
{:name name, :value value, :ts now})))
(a/put! update-chan :pseudo-vars))))
(defn get-pin-value [pin-name]
(-> @state :pins (get pin-name) :value))
(defn available-ports []
@port-scanner/available-ports)
(defn connected? []
(when-let [connection (-> @state :connection)]
(and (not= :pending connection)
(ports/connected? connection))))
(defn disconnect! []
(go
(let [[{{:keys [connected?] :as conn} :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(nil? connection))
state
(assoc state :connection :pending))))]
(when connected?
(logger/error "Connection lost!")
(try
(ports/disconnect! conn)
; TODO(Richo): I used to think there was some sort of race condition in my
; code that prevented me from being able to quickly disconnect and reconnect.
; However, after further testing it seems to be some OS related issue. So
; just to be safe I'm adding the 1s delay here.
(<! (timeout 1000))
(catch #?(:clj Throwable :cljs :default) e
(log-error "ERROR WHILE DISCONNECTING ->" e)))
(port-scanner/start!)
(swap! state (fn [state]
(assoc-in initial-state [:program :current]
(-> state :program :current))))
(>! update-chan :connection)))))
(defn send! [bytes]
(when-let [out (-> @state :connection :out)]
(when-not (a/put! out bytes)
(disconnect!)))
bytes)
(defn- get-global-number [global-name]
(program/index-of-variable (-> @state :program :running)
global-name
nil))
(defn set-global-value [global-name ^double value]
(when-let [global-number (get-global-number global-name)]
(send! (p/set-global-value global-number value))))
(defn set-global-report [global-name report?]
(when-let [global-number (get-global-number global-name)]
(swap! state update-in [:reporting :globals]
(if report? conj disj) global-name)
(send! (p/set-global-report global-number report?))))
(defn set-pin-value [pin-name ^double value]
(when-let [pin-number (get-pin-number pin-name)]
(send! (p/set-pin-value pin-number value))))
(defn set-pin-report [pin-name report?]
(when-let [pin-number (get-pin-number pin-name)]
(swap! state update-in [:reporting :pins]
(if report? conj disj) pin-name)
(send! (p/set-pin-report pin-number report?))))
(defn send-pins-reporting []
(let [pins (-> @state :reporting :pins)]
(doseq [pin-name pins]
(set-pin-report pin-name true))))
(defn- update-reporting [program]
"All pins and globals referenced in the program must be enabled"
(doseq [global (filter :name (-> program :globals))]
(set-global-report (:name global) true))
(doseq [{:keys [type number]} (filter ast/pin-literal?
(-> (meta program)
:final-ast
ast/all-children))]
(set-pin-report (str type number) true)))
(defn run [program]
(swap! state assoc-in [:reporting :globals] #{})
(swap! state assoc-in [:program :running] program)
(let [bytecodes (en/encode program)
sent (send! (p/run bytecodes))]
(update-reporting program)
sent))
(defn install [program]
; TODO(Richo): Should I store the installed program?
(let [bytecodes (en/encode program)
sent (send! (p/install bytecodes))]
; TODO(Richo): This message is actually a lie, we really don't know yet if the
; program was installed successfully. I think we need to add a confirmation
; message coming from the firmware
(logger/success "Installed program successfully!")))
(defn start-reporting [] (send! (p/start-reporting)))
(defn stop-reporting [] (send! (p/stop-reporting)))
(defn start-profiling [] (send! (p/start-profiling)))
(defn stop-profiling [] (send! (p/stop-profiling)))
(defn set-report-interval [interval]
(let [interval (int (clamp interval
(get-config [:device :report-interval-min] 0)
(get-config [:device :report-interval-max] 100)))]
(when-not (= (-> @state :reporting :interval)
interval)
(swap! state assoc-in [:reporting :interval] interval)
(send! (p/set-report-interval interval)))))
(defn set-all-breakpoints [] (send! (p/set-all-breakpoints)))
(defn clear-all-breakpoints [] (send! (p/clear-all-breakpoints)))
(defn send-continue []
(swap! state assoc :debugger nil)
(send! (p/continue)))
(comment
(send-continue)
(clear-all-breakpoints)
(set-all-breakpoints)
(go-loop [c 0]
(when (< c 100)
(send-continue)
(<! (timeout 100))
(recur (inc c))))
(a/close! *1)
,,)
(defn- keep-alive-loop []
(go
(loop []
; TODO(Richo): We shouldn't need to send a keep alive unless
; we haven't send anything in the last 100 ms.
(when (connected?)
(send! (p/keep-alive))
(<! (timeout 100))
(recur)))))
(defn- process-timestamp [^long timestamp]
"Calculating the time since the last snapshot (both in the vm and the middleware)
and then calculating the difference between these intervals and adding it as
pseudo variable so that I can observe it in the inspector. Its value should always
be close to 0. If not, we try increasing the report interval."
(let [arduino-time timestamp
middleware-time (millis)
timing (-> @state :timing)
^long previous-arduino-time (or (get timing :arduino) arduino-time)
^long previous-middleware-time (or (get timing :middleware) middleware-time)
delta-arduino (- arduino-time previous-arduino-time)
delta-middleware (- middleware-time previous-middleware-time)
delta (- delta-arduino delta-middleware)
timing-diffs (:diffs timing)]
(rb/push! timing-diffs delta)
(swap! state update :timing
#(assoc %
:arduino arduino-time
:middleware middleware-time))
(add-pseudo-var! "__delta" delta)
(let [^long report-interval (-> @state :reporting :interval)
^long report-interval-inc (get-config [:device :report-interval-inc] 5)
delta-smooth (Math/abs (rb/avg timing-diffs))
^long delta-threshold-min (get-config [:device :delta-threshold-min] 1)
^long delta-threshold-max (get-config [:device :delta-threshold-max] 25)]
(add-pseudo-var! "__delta_smooth" delta-smooth)
(add-pseudo-var! "__report_interval" report-interval)
; If the delta-smooth goes below the min we decrement the report-interval
(when (< delta-smooth delta-threshold-min)
(set-report-interval (- report-interval report-interval-inc)))
; If the delta-smooth goes above the max we increment the report-interval
(when (> delta-smooth delta-threshold-max)
(set-report-interval (+ report-interval report-interval-inc))))))
(defn process-pin-value [{:keys [timestamp data]}]
(let [pins (into {}
(map (fn [pin]
(when-let [name (get-pin-name (:number pin))]
[name (assoc pin :name name)]))
data))]
(swap! state assoc
:pins {:timestamp timestamp :data pins})))
(defn process-global-value [{:keys [timestamp data]}]
(let [globals (vec (program/all-globals
(-> @state :program :running)))]
(let [globals (into {}
(map (fn [{:keys [number] :as global}]
(when-let [name (:name (nth globals number {}))]
[name (assoc global :name name)]))
data))]
(swap! state assoc
:globals
{:timestamp timestamp :data globals}))))
(defn process-free-ram [{:keys [memory]}]
(swap! state assoc :memory memory))
(defn process-running-scripts [{:keys [scripts]}]
(let [program (-> @state :program :running)
get-script-name (fn [i] (-> program :scripts (get i) :name))
task? (fn [i] (-> (meta program) :final-ast :scripts (get i) ast/task?))
[old new] (swap-vals! state assoc
:scripts
(into {} (map-indexed
(fn [i script]
(let [name (get-script-name i)]
[name
(assoc script
:index i
:name name
:task? (task? i))]))
scripts)))]
(doseq [script (filter :error? (sort-by :index (-> new :scripts vals)))]
(when-not (= (-> old :scripts (get (:name script)) :error-code)
(:error-code script))
(logger/warning "%1 detected on script \"%2\". The script has been stopped."
(:error-msg script)
(:name script))))))
(defn process-profile [{:keys [data]}]
(swap! state assoc :profiler data)
(add-pseudo-var! "__tps" (* 10 (:ticks data)))
(add-pseudo-var! "__vm-report-interval" (:report-interval data)))
(defn process-coroutine-state [{:keys [data]}]
(swap! state assoc :debugger data))
(defn process-error [{{:keys [code msg]} :error}]
(go
(logger/newline)
(logger/warning "%1 detected. The program has been stopped" msg)
(if (p/error-disconnect? code)
(<! (disconnect!)))))
(defn process-trace [{:keys [msg]}]
(logger/log "TRACE:" msg))
(defn process-serial-tunnel [{:keys [data]}]
(logger/log "SERIAL: %1" data))
(defn process-next-message [in]
(go
(when-let [{:keys [tag timestamp] :or {timestamp nil} :as cmd}
(<! (p/process-next-message in))]
(when timestamp
(process-timestamp timestamp))
(case tag
:pin-value (process-pin-value cmd)
:global-value (process-global-value cmd)
:running-scripts (process-running-scripts cmd)
:free-ram (process-free-ram cmd)
:profile (process-profile cmd)
:coroutine-state (process-coroutine-state cmd)
:trace (process-trace cmd)
:serial (process-serial-tunnel cmd)
:error (<! (process-error cmd)) ; Special case because it calls disconnect!
:unknown-cmd (logger/warning "Uzi - Invalid response code: %1"
(:code cmd)))
(when tag (>! update-chan tag))
cmd)))
(defn- process-input-loop [{:keys [in]}]
(go
(loop []
(when (connected?)
(if-not (<! (process-next-message in))
(<! (disconnect!))
(recur))))))
(defn- clean-up-reports-loop []
(go
(loop []
(when (connected?)
; If we have pseudo vars, remove old ones (older than 1s)
(if-not (zero? (count (-> @state :pseudo-vars :data)))
(if (get-config [:device :pseudo-vars?] false)
(swap! state update-in [:pseudo-vars :data]
#(let [^long timestamp (or (get-in @state [:pseudo-vars :timestamp]) 0)
limit (- timestamp 1000)]
(into {} (remove (fn [[_ {^long ts :ts}]] (< ts limit)) %))))
(swap! state assoc-in [:pseudo-vars :data] {})))
; Now remove pins/globals that are not being reported anymore
(let [reporting (:reporting @state)]
(swap! state update-in [:pins :data] #(select-keys % (:pins reporting)))
(swap! state update-in [:globals :data] #(select-keys % (:globals reporting))))
; Trigger the update event
(a/onto-chan! update-chan [:pins :globals :pseudo-vars] false)
; Finally wait 1s and start over
(<! (timeout 1000))
(recur)))))
(defn- request-connection [port-name baud-rate]
(go
(try
(logger/newline) ; TODO(Richo): Maybe clear the output console before connecting??
(logger/log "Opening port: %1" port-name)
(if-let [connection (ports/connect! port-name baud-rate)]
(do
(<! (timeout 2000)) ; NOTE(Richo): Needed in Mac
(logger/log "Requesting connection...")
(let [handshake (p/perform-handshake connection)
timeout (a/timeout 1000)]
(if (a/alt! handshake ([success?]
(if success?
(logger/success "Connection accepted!")
(logger/error "Connection rejected"))
success?)
timeout (do
(logger/error "Connection timeout")
false)
:priority true)
connection
(do
(ports/disconnect! connection)
nil))))
(do
(logger/error "Opening port failed!")
nil))
(catch #?(:clj Throwable :cljs :default) ex
(log-error "ERROR WHILE OPENING PORT ->" ex)))))
(defn- connection-successful [connection board baud-rate reporting?]
(port-scanner/stop!)
(swap! state assoc
:connection connection
:board board
:timing {:diffs (rb/make-ring-buffer
(get-config [:device :timing-diffs-size] 10))
:arduino nil
:middleware nil}
:reporting {:pins #{}
:globals #{}})
(set-report-interval (get-config [:device :report-interval-min] 0))
(process-input-loop connection)
(clean-up-reports-loop)
(keep-alive-loop)
(when reporting?
(start-reporting)
(send-pins-reporting)))
(defn connect!
([] (connect! (first (available-ports))))
([port-name & {:keys [board baud-rate reporting?]
:or {board UNO, baud-rate 9600, reporting? true}}]
(go
(let [[{old-connection :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(ports/connected? connection))
state
(assoc state :connection :pending))))]
(when (nil? old-connection)
(if-let [connection (<! (request-connection port-name baud-rate))]
(connection-successful connection board baud-rate reporting?)
(swap! state assoc :connection nil))
(>! update-chan :connection))))))
|
3826
|
(ns middleware.device.controller
(:require #?(:clj [clojure.tools.logging :as log])
[middleware.device.ports.scanner :as port-scanner]
[clojure.core.async :as a :refer [<! >! go go-loop timeout]]
[middleware.device.ports.common :as ports]
[middleware.device.protocol :as p]
[middleware.device.boards :refer [UNO get-pin-number get-pin-name]]
[middleware.compilation.encoder :as en]
[middleware.ast.utils :as ast]
[middleware.program.utils :as program]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.logger :as logger]
#?(:clj [middleware.utils.config :as config])
[middleware.utils.core :refer [millis clamp]]))
(comment
(start-profiling)
(stop-profiling)
(.getTime (js/Date.))
(set-report-interval 5)
@state
,)
(defn- log-error [msg e]
#?(:clj (log/error msg e)
:cljs (println "ERROR:" msg e)))
(defn- get-config [path default-value]
#?(:clj (config/get-in path default-value)
; TODO(<NAME>): Make the CLJS version work for real...
:cljs default-value))
(def initial-state {:connection nil
:board UNO
:reporting {:pins #{}, :globals #{}}
:pins {}
:globals {}
:pseudo-vars {:timestamp nil, :data {}}
:scripts []
:profiler nil
:debugger nil
:timing {:arduino nil, :middleware nil, :diffs nil}
:memory {:arduino nil, :uzi nil}
:program {:current nil, :running nil}})
(def state (atom initial-state))
(def update-chan (a/chan 100))
(def updates (a/mult update-chan))
(defn- add-pseudo-var! [name value]
(if (get-config [:device :pseudo-vars?] false)
(let [now (or (-> @state :timing :arduino) 0)]
(swap! state
#(-> %
(assoc-in [:pseudo-vars :timestamp] now)
(assoc-in [:pseudo-vars :data name]
{:name name, :value value, :ts now})))
(a/put! update-chan :pseudo-vars))))
(defn get-pin-value [pin-name]
(-> @state :pins (get pin-name) :value))
(defn available-ports []
@port-scanner/available-ports)
(defn connected? []
(when-let [connection (-> @state :connection)]
(and (not= :pending connection)
(ports/connected? connection))))
(defn disconnect! []
(go
(let [[{{:keys [connected?] :as conn} :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(nil? connection))
state
(assoc state :connection :pending))))]
(when connected?
(logger/error "Connection lost!")
(try
(ports/disconnect! conn)
; TODO(<NAME>): I used to think there was some sort of race condition in my
; code that prevented me from being able to quickly disconnect and reconnect.
; However, after further testing it seems to be some OS related issue. So
; just to be safe I'm adding the 1s delay here.
(<! (timeout 1000))
(catch #?(:clj Throwable :cljs :default) e
(log-error "ERROR WHILE DISCONNECTING ->" e)))
(port-scanner/start!)
(swap! state (fn [state]
(assoc-in initial-state [:program :current]
(-> state :program :current))))
(>! update-chan :connection)))))
(defn send! [bytes]
(when-let [out (-> @state :connection :out)]
(when-not (a/put! out bytes)
(disconnect!)))
bytes)
(defn- get-global-number [global-name]
(program/index-of-variable (-> @state :program :running)
global-name
nil))
(defn set-global-value [global-name ^double value]
(when-let [global-number (get-global-number global-name)]
(send! (p/set-global-value global-number value))))
(defn set-global-report [global-name report?]
(when-let [global-number (get-global-number global-name)]
(swap! state update-in [:reporting :globals]
(if report? conj disj) global-name)
(send! (p/set-global-report global-number report?))))
(defn set-pin-value [pin-name ^double value]
(when-let [pin-number (get-pin-number pin-name)]
(send! (p/set-pin-value pin-number value))))
(defn set-pin-report [pin-name report?]
(when-let [pin-number (get-pin-number pin-name)]
(swap! state update-in [:reporting :pins]
(if report? conj disj) pin-name)
(send! (p/set-pin-report pin-number report?))))
(defn send-pins-reporting []
(let [pins (-> @state :reporting :pins)]
(doseq [pin-name pins]
(set-pin-report pin-name true))))
(defn- update-reporting [program]
"All pins and globals referenced in the program must be enabled"
(doseq [global (filter :name (-> program :globals))]
(set-global-report (:name global) true))
(doseq [{:keys [type number]} (filter ast/pin-literal?
(-> (meta program)
:final-ast
ast/all-children))]
(set-pin-report (str type number) true)))
(defn run [program]
(swap! state assoc-in [:reporting :globals] #{})
(swap! state assoc-in [:program :running] program)
(let [bytecodes (en/encode program)
sent (send! (p/run bytecodes))]
(update-reporting program)
sent))
(defn install [program]
; TODO(<NAME>): Should I store the installed program?
(let [bytecodes (en/encode program)
sent (send! (p/install bytecodes))]
; TODO(<NAME>): This message is actually a lie, we really don't know yet if the
; program was installed successfully. I think we need to add a confirmation
; message coming from the firmware
(logger/success "Installed program successfully!")))
(defn start-reporting [] (send! (p/start-reporting)))
(defn stop-reporting [] (send! (p/stop-reporting)))
(defn start-profiling [] (send! (p/start-profiling)))
(defn stop-profiling [] (send! (p/stop-profiling)))
(defn set-report-interval [interval]
(let [interval (int (clamp interval
(get-config [:device :report-interval-min] 0)
(get-config [:device :report-interval-max] 100)))]
(when-not (= (-> @state :reporting :interval)
interval)
(swap! state assoc-in [:reporting :interval] interval)
(send! (p/set-report-interval interval)))))
(defn set-all-breakpoints [] (send! (p/set-all-breakpoints)))
(defn clear-all-breakpoints [] (send! (p/clear-all-breakpoints)))
(defn send-continue []
(swap! state assoc :debugger nil)
(send! (p/continue)))
(comment
(send-continue)
(clear-all-breakpoints)
(set-all-breakpoints)
(go-loop [c 0]
(when (< c 100)
(send-continue)
(<! (timeout 100))
(recur (inc c))))
(a/close! *1)
,,)
(defn- keep-alive-loop []
(go
(loop []
; TODO(<NAME>): We shouldn't need to send a keep alive unless
; we haven't send anything in the last 100 ms.
(when (connected?)
(send! (p/keep-alive))
(<! (timeout 100))
(recur)))))
(defn- process-timestamp [^long timestamp]
"Calculating the time since the last snapshot (both in the vm and the middleware)
and then calculating the difference between these intervals and adding it as
pseudo variable so that I can observe it in the inspector. Its value should always
be close to 0. If not, we try increasing the report interval."
(let [arduino-time timestamp
middleware-time (millis)
timing (-> @state :timing)
^long previous-arduino-time (or (get timing :arduino) arduino-time)
^long previous-middleware-time (or (get timing :middleware) middleware-time)
delta-arduino (- arduino-time previous-arduino-time)
delta-middleware (- middleware-time previous-middleware-time)
delta (- delta-arduino delta-middleware)
timing-diffs (:diffs timing)]
(rb/push! timing-diffs delta)
(swap! state update :timing
#(assoc %
:arduino arduino-time
:middleware middleware-time))
(add-pseudo-var! "__delta" delta)
(let [^long report-interval (-> @state :reporting :interval)
^long report-interval-inc (get-config [:device :report-interval-inc] 5)
delta-smooth (Math/abs (rb/avg timing-diffs))
^long delta-threshold-min (get-config [:device :delta-threshold-min] 1)
^long delta-threshold-max (get-config [:device :delta-threshold-max] 25)]
(add-pseudo-var! "__delta_smooth" delta-smooth)
(add-pseudo-var! "__report_interval" report-interval)
; If the delta-smooth goes below the min we decrement the report-interval
(when (< delta-smooth delta-threshold-min)
(set-report-interval (- report-interval report-interval-inc)))
; If the delta-smooth goes above the max we increment the report-interval
(when (> delta-smooth delta-threshold-max)
(set-report-interval (+ report-interval report-interval-inc))))))
(defn process-pin-value [{:keys [timestamp data]}]
(let [pins (into {}
(map (fn [pin]
(when-let [name (get-pin-name (:number pin))]
[name (assoc pin :name name)]))
data))]
(swap! state assoc
:pins {:timestamp timestamp :data pins})))
(defn process-global-value [{:keys [timestamp data]}]
(let [globals (vec (program/all-globals
(-> @state :program :running)))]
(let [globals (into {}
(map (fn [{:keys [number] :as global}]
(when-let [name (:name (nth globals number {}))]
[name (assoc global :name name)]))
data))]
(swap! state assoc
:globals
{:timestamp timestamp :data globals}))))
(defn process-free-ram [{:keys [memory]}]
(swap! state assoc :memory memory))
(defn process-running-scripts [{:keys [scripts]}]
(let [program (-> @state :program :running)
get-script-name (fn [i] (-> program :scripts (get i) :name))
task? (fn [i] (-> (meta program) :final-ast :scripts (get i) ast/task?))
[old new] (swap-vals! state assoc
:scripts
(into {} (map-indexed
(fn [i script]
(let [name (get-script-name i)]
[name
(assoc script
:index i
:name name
:task? (task? i))]))
scripts)))]
(doseq [script (filter :error? (sort-by :index (-> new :scripts vals)))]
(when-not (= (-> old :scripts (get (:name script)) :error-code)
(:error-code script))
(logger/warning "%1 detected on script \"%2\". The script has been stopped."
(:error-msg script)
(:name script))))))
(defn process-profile [{:keys [data]}]
(swap! state assoc :profiler data)
(add-pseudo-var! "__tps" (* 10 (:ticks data)))
(add-pseudo-var! "__vm-report-interval" (:report-interval data)))
(defn process-coroutine-state [{:keys [data]}]
(swap! state assoc :debugger data))
(defn process-error [{{:keys [code msg]} :error}]
(go
(logger/newline)
(logger/warning "%1 detected. The program has been stopped" msg)
(if (p/error-disconnect? code)
(<! (disconnect!)))))
(defn process-trace [{:keys [msg]}]
(logger/log "TRACE:" msg))
(defn process-serial-tunnel [{:keys [data]}]
(logger/log "SERIAL: %1" data))
(defn process-next-message [in]
(go
(when-let [{:keys [tag timestamp] :or {timestamp nil} :as cmd}
(<! (p/process-next-message in))]
(when timestamp
(process-timestamp timestamp))
(case tag
:pin-value (process-pin-value cmd)
:global-value (process-global-value cmd)
:running-scripts (process-running-scripts cmd)
:free-ram (process-free-ram cmd)
:profile (process-profile cmd)
:coroutine-state (process-coroutine-state cmd)
:trace (process-trace cmd)
:serial (process-serial-tunnel cmd)
:error (<! (process-error cmd)) ; Special case because it calls disconnect!
:unknown-cmd (logger/warning "Uzi - Invalid response code: %1"
(:code cmd)))
(when tag (>! update-chan tag))
cmd)))
(defn- process-input-loop [{:keys [in]}]
(go
(loop []
(when (connected?)
(if-not (<! (process-next-message in))
(<! (disconnect!))
(recur))))))
(defn- clean-up-reports-loop []
(go
(loop []
(when (connected?)
; If we have pseudo vars, remove old ones (older than 1s)
(if-not (zero? (count (-> @state :pseudo-vars :data)))
(if (get-config [:device :pseudo-vars?] false)
(swap! state update-in [:pseudo-vars :data]
#(let [^long timestamp (or (get-in @state [:pseudo-vars :timestamp]) 0)
limit (- timestamp 1000)]
(into {} (remove (fn [[_ {^long ts :ts}]] (< ts limit)) %))))
(swap! state assoc-in [:pseudo-vars :data] {})))
; Now remove pins/globals that are not being reported anymore
(let [reporting (:reporting @state)]
(swap! state update-in [:pins :data] #(select-keys % (:pins reporting)))
(swap! state update-in [:globals :data] #(select-keys % (:globals reporting))))
; Trigger the update event
(a/onto-chan! update-chan [:pins :globals :pseudo-vars] false)
; Finally wait 1s and start over
(<! (timeout 1000))
(recur)))))
(defn- request-connection [port-name baud-rate]
(go
(try
(logger/newline) ; TODO(Richo): Maybe clear the output console before connecting??
(logger/log "Opening port: %1" port-name)
(if-let [connection (ports/connect! port-name baud-rate)]
(do
(<! (timeout 2000)) ; NOTE(Richo): Needed in Mac
(logger/log "Requesting connection...")
(let [handshake (p/perform-handshake connection)
timeout (a/timeout 1000)]
(if (a/alt! handshake ([success?]
(if success?
(logger/success "Connection accepted!")
(logger/error "Connection rejected"))
success?)
timeout (do
(logger/error "Connection timeout")
false)
:priority true)
connection
(do
(ports/disconnect! connection)
nil))))
(do
(logger/error "Opening port failed!")
nil))
(catch #?(:clj Throwable :cljs :default) ex
(log-error "ERROR WHILE OPENING PORT ->" ex)))))
(defn- connection-successful [connection board baud-rate reporting?]
(port-scanner/stop!)
(swap! state assoc
:connection connection
:board board
:timing {:diffs (rb/make-ring-buffer
(get-config [:device :timing-diffs-size] 10))
:arduino nil
:middleware nil}
:reporting {:pins #{}
:globals #{}})
(set-report-interval (get-config [:device :report-interval-min] 0))
(process-input-loop connection)
(clean-up-reports-loop)
(keep-alive-loop)
(when reporting?
(start-reporting)
(send-pins-reporting)))
(defn connect!
([] (connect! (first (available-ports))))
([port-name & {:keys [board baud-rate reporting?]
:or {board UNO, baud-rate 9600, reporting? true}}]
(go
(let [[{old-connection :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(ports/connected? connection))
state
(assoc state :connection :pending))))]
(when (nil? old-connection)
(if-let [connection (<! (request-connection port-name baud-rate))]
(connection-successful connection board baud-rate reporting?)
(swap! state assoc :connection nil))
(>! update-chan :connection))))))
| true |
(ns middleware.device.controller
(:require #?(:clj [clojure.tools.logging :as log])
[middleware.device.ports.scanner :as port-scanner]
[clojure.core.async :as a :refer [<! >! go go-loop timeout]]
[middleware.device.ports.common :as ports]
[middleware.device.protocol :as p]
[middleware.device.boards :refer [UNO get-pin-number get-pin-name]]
[middleware.compilation.encoder :as en]
[middleware.ast.utils :as ast]
[middleware.program.utils :as program]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.logger :as logger]
#?(:clj [middleware.utils.config :as config])
[middleware.utils.core :refer [millis clamp]]))
(comment
(start-profiling)
(stop-profiling)
(.getTime (js/Date.))
(set-report-interval 5)
@state
,)
(defn- log-error [msg e]
#?(:clj (log/error msg e)
:cljs (println "ERROR:" msg e)))
(defn- get-config [path default-value]
#?(:clj (config/get-in path default-value)
; TODO(PI:NAME:<NAME>END_PI): Make the CLJS version work for real...
:cljs default-value))
(def initial-state {:connection nil
:board UNO
:reporting {:pins #{}, :globals #{}}
:pins {}
:globals {}
:pseudo-vars {:timestamp nil, :data {}}
:scripts []
:profiler nil
:debugger nil
:timing {:arduino nil, :middleware nil, :diffs nil}
:memory {:arduino nil, :uzi nil}
:program {:current nil, :running nil}})
(def state (atom initial-state))
(def update-chan (a/chan 100))
(def updates (a/mult update-chan))
(defn- add-pseudo-var! [name value]
(if (get-config [:device :pseudo-vars?] false)
(let [now (or (-> @state :timing :arduino) 0)]
(swap! state
#(-> %
(assoc-in [:pseudo-vars :timestamp] now)
(assoc-in [:pseudo-vars :data name]
{:name name, :value value, :ts now})))
(a/put! update-chan :pseudo-vars))))
(defn get-pin-value [pin-name]
(-> @state :pins (get pin-name) :value))
(defn available-ports []
@port-scanner/available-ports)
(defn connected? []
(when-let [connection (-> @state :connection)]
(and (not= :pending connection)
(ports/connected? connection))))
(defn disconnect! []
(go
(let [[{{:keys [connected?] :as conn} :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(nil? connection))
state
(assoc state :connection :pending))))]
(when connected?
(logger/error "Connection lost!")
(try
(ports/disconnect! conn)
; TODO(PI:NAME:<NAME>END_PI): I used to think there was some sort of race condition in my
; code that prevented me from being able to quickly disconnect and reconnect.
; However, after further testing it seems to be some OS related issue. So
; just to be safe I'm adding the 1s delay here.
(<! (timeout 1000))
(catch #?(:clj Throwable :cljs :default) e
(log-error "ERROR WHILE DISCONNECTING ->" e)))
(port-scanner/start!)
(swap! state (fn [state]
(assoc-in initial-state [:program :current]
(-> state :program :current))))
(>! update-chan :connection)))))
(defn send! [bytes]
(when-let [out (-> @state :connection :out)]
(when-not (a/put! out bytes)
(disconnect!)))
bytes)
(defn- get-global-number [global-name]
(program/index-of-variable (-> @state :program :running)
global-name
nil))
(defn set-global-value [global-name ^double value]
(when-let [global-number (get-global-number global-name)]
(send! (p/set-global-value global-number value))))
(defn set-global-report [global-name report?]
(when-let [global-number (get-global-number global-name)]
(swap! state update-in [:reporting :globals]
(if report? conj disj) global-name)
(send! (p/set-global-report global-number report?))))
(defn set-pin-value [pin-name ^double value]
(when-let [pin-number (get-pin-number pin-name)]
(send! (p/set-pin-value pin-number value))))
(defn set-pin-report [pin-name report?]
(when-let [pin-number (get-pin-number pin-name)]
(swap! state update-in [:reporting :pins]
(if report? conj disj) pin-name)
(send! (p/set-pin-report pin-number report?))))
(defn send-pins-reporting []
(let [pins (-> @state :reporting :pins)]
(doseq [pin-name pins]
(set-pin-report pin-name true))))
(defn- update-reporting [program]
"All pins and globals referenced in the program must be enabled"
(doseq [global (filter :name (-> program :globals))]
(set-global-report (:name global) true))
(doseq [{:keys [type number]} (filter ast/pin-literal?
(-> (meta program)
:final-ast
ast/all-children))]
(set-pin-report (str type number) true)))
(defn run [program]
(swap! state assoc-in [:reporting :globals] #{})
(swap! state assoc-in [:program :running] program)
(let [bytecodes (en/encode program)
sent (send! (p/run bytecodes))]
(update-reporting program)
sent))
(defn install [program]
; TODO(PI:NAME:<NAME>END_PI): Should I store the installed program?
(let [bytecodes (en/encode program)
sent (send! (p/install bytecodes))]
; TODO(PI:NAME:<NAME>END_PI): This message is actually a lie, we really don't know yet if the
; program was installed successfully. I think we need to add a confirmation
; message coming from the firmware
(logger/success "Installed program successfully!")))
(defn start-reporting [] (send! (p/start-reporting)))
(defn stop-reporting [] (send! (p/stop-reporting)))
(defn start-profiling [] (send! (p/start-profiling)))
(defn stop-profiling [] (send! (p/stop-profiling)))
(defn set-report-interval [interval]
(let [interval (int (clamp interval
(get-config [:device :report-interval-min] 0)
(get-config [:device :report-interval-max] 100)))]
(when-not (= (-> @state :reporting :interval)
interval)
(swap! state assoc-in [:reporting :interval] interval)
(send! (p/set-report-interval interval)))))
(defn set-all-breakpoints [] (send! (p/set-all-breakpoints)))
(defn clear-all-breakpoints [] (send! (p/clear-all-breakpoints)))
(defn send-continue []
(swap! state assoc :debugger nil)
(send! (p/continue)))
(comment
(send-continue)
(clear-all-breakpoints)
(set-all-breakpoints)
(go-loop [c 0]
(when (< c 100)
(send-continue)
(<! (timeout 100))
(recur (inc c))))
(a/close! *1)
,,)
(defn- keep-alive-loop []
(go
(loop []
; TODO(PI:NAME:<NAME>END_PI): We shouldn't need to send a keep alive unless
; we haven't send anything in the last 100 ms.
(when (connected?)
(send! (p/keep-alive))
(<! (timeout 100))
(recur)))))
(defn- process-timestamp [^long timestamp]
"Calculating the time since the last snapshot (both in the vm and the middleware)
and then calculating the difference between these intervals and adding it as
pseudo variable so that I can observe it in the inspector. Its value should always
be close to 0. If not, we try increasing the report interval."
(let [arduino-time timestamp
middleware-time (millis)
timing (-> @state :timing)
^long previous-arduino-time (or (get timing :arduino) arduino-time)
^long previous-middleware-time (or (get timing :middleware) middleware-time)
delta-arduino (- arduino-time previous-arduino-time)
delta-middleware (- middleware-time previous-middleware-time)
delta (- delta-arduino delta-middleware)
timing-diffs (:diffs timing)]
(rb/push! timing-diffs delta)
(swap! state update :timing
#(assoc %
:arduino arduino-time
:middleware middleware-time))
(add-pseudo-var! "__delta" delta)
(let [^long report-interval (-> @state :reporting :interval)
^long report-interval-inc (get-config [:device :report-interval-inc] 5)
delta-smooth (Math/abs (rb/avg timing-diffs))
^long delta-threshold-min (get-config [:device :delta-threshold-min] 1)
^long delta-threshold-max (get-config [:device :delta-threshold-max] 25)]
(add-pseudo-var! "__delta_smooth" delta-smooth)
(add-pseudo-var! "__report_interval" report-interval)
; If the delta-smooth goes below the min we decrement the report-interval
(when (< delta-smooth delta-threshold-min)
(set-report-interval (- report-interval report-interval-inc)))
; If the delta-smooth goes above the max we increment the report-interval
(when (> delta-smooth delta-threshold-max)
(set-report-interval (+ report-interval report-interval-inc))))))
(defn process-pin-value [{:keys [timestamp data]}]
(let [pins (into {}
(map (fn [pin]
(when-let [name (get-pin-name (:number pin))]
[name (assoc pin :name name)]))
data))]
(swap! state assoc
:pins {:timestamp timestamp :data pins})))
(defn process-global-value [{:keys [timestamp data]}]
(let [globals (vec (program/all-globals
(-> @state :program :running)))]
(let [globals (into {}
(map (fn [{:keys [number] :as global}]
(when-let [name (:name (nth globals number {}))]
[name (assoc global :name name)]))
data))]
(swap! state assoc
:globals
{:timestamp timestamp :data globals}))))
(defn process-free-ram [{:keys [memory]}]
(swap! state assoc :memory memory))
(defn process-running-scripts [{:keys [scripts]}]
(let [program (-> @state :program :running)
get-script-name (fn [i] (-> program :scripts (get i) :name))
task? (fn [i] (-> (meta program) :final-ast :scripts (get i) ast/task?))
[old new] (swap-vals! state assoc
:scripts
(into {} (map-indexed
(fn [i script]
(let [name (get-script-name i)]
[name
(assoc script
:index i
:name name
:task? (task? i))]))
scripts)))]
(doseq [script (filter :error? (sort-by :index (-> new :scripts vals)))]
(when-not (= (-> old :scripts (get (:name script)) :error-code)
(:error-code script))
(logger/warning "%1 detected on script \"%2\". The script has been stopped."
(:error-msg script)
(:name script))))))
(defn process-profile [{:keys [data]}]
(swap! state assoc :profiler data)
(add-pseudo-var! "__tps" (* 10 (:ticks data)))
(add-pseudo-var! "__vm-report-interval" (:report-interval data)))
(defn process-coroutine-state [{:keys [data]}]
(swap! state assoc :debugger data))
(defn process-error [{{:keys [code msg]} :error}]
(go
(logger/newline)
(logger/warning "%1 detected. The program has been stopped" msg)
(if (p/error-disconnect? code)
(<! (disconnect!)))))
(defn process-trace [{:keys [msg]}]
(logger/log "TRACE:" msg))
(defn process-serial-tunnel [{:keys [data]}]
(logger/log "SERIAL: %1" data))
(defn process-next-message [in]
(go
(when-let [{:keys [tag timestamp] :or {timestamp nil} :as cmd}
(<! (p/process-next-message in))]
(when timestamp
(process-timestamp timestamp))
(case tag
:pin-value (process-pin-value cmd)
:global-value (process-global-value cmd)
:running-scripts (process-running-scripts cmd)
:free-ram (process-free-ram cmd)
:profile (process-profile cmd)
:coroutine-state (process-coroutine-state cmd)
:trace (process-trace cmd)
:serial (process-serial-tunnel cmd)
:error (<! (process-error cmd)) ; Special case because it calls disconnect!
:unknown-cmd (logger/warning "Uzi - Invalid response code: %1"
(:code cmd)))
(when tag (>! update-chan tag))
cmd)))
(defn- process-input-loop [{:keys [in]}]
(go
(loop []
(when (connected?)
(if-not (<! (process-next-message in))
(<! (disconnect!))
(recur))))))
(defn- clean-up-reports-loop []
(go
(loop []
(when (connected?)
; If we have pseudo vars, remove old ones (older than 1s)
(if-not (zero? (count (-> @state :pseudo-vars :data)))
(if (get-config [:device :pseudo-vars?] false)
(swap! state update-in [:pseudo-vars :data]
#(let [^long timestamp (or (get-in @state [:pseudo-vars :timestamp]) 0)
limit (- timestamp 1000)]
(into {} (remove (fn [[_ {^long ts :ts}]] (< ts limit)) %))))
(swap! state assoc-in [:pseudo-vars :data] {})))
; Now remove pins/globals that are not being reported anymore
(let [reporting (:reporting @state)]
(swap! state update-in [:pins :data] #(select-keys % (:pins reporting)))
(swap! state update-in [:globals :data] #(select-keys % (:globals reporting))))
; Trigger the update event
(a/onto-chan! update-chan [:pins :globals :pseudo-vars] false)
; Finally wait 1s and start over
(<! (timeout 1000))
(recur)))))
(defn- request-connection [port-name baud-rate]
(go
(try
(logger/newline) ; TODO(Richo): Maybe clear the output console before connecting??
(logger/log "Opening port: %1" port-name)
(if-let [connection (ports/connect! port-name baud-rate)]
(do
(<! (timeout 2000)) ; NOTE(Richo): Needed in Mac
(logger/log "Requesting connection...")
(let [handshake (p/perform-handshake connection)
timeout (a/timeout 1000)]
(if (a/alt! handshake ([success?]
(if success?
(logger/success "Connection accepted!")
(logger/error "Connection rejected"))
success?)
timeout (do
(logger/error "Connection timeout")
false)
:priority true)
connection
(do
(ports/disconnect! connection)
nil))))
(do
(logger/error "Opening port failed!")
nil))
(catch #?(:clj Throwable :cljs :default) ex
(log-error "ERROR WHILE OPENING PORT ->" ex)))))
(defn- connection-successful [connection board baud-rate reporting?]
(port-scanner/stop!)
(swap! state assoc
:connection connection
:board board
:timing {:diffs (rb/make-ring-buffer
(get-config [:device :timing-diffs-size] 10))
:arduino nil
:middleware nil}
:reporting {:pins #{}
:globals #{}})
(set-report-interval (get-config [:device :report-interval-min] 0))
(process-input-loop connection)
(clean-up-reports-loop)
(keep-alive-loop)
(when reporting?
(start-reporting)
(send-pins-reporting)))
(defn connect!
([] (connect! (first (available-ports))))
([port-name & {:keys [board baud-rate reporting?]
:or {board UNO, baud-rate 9600, reporting? true}}]
(go
(let [[{old-connection :connection}]
(swap-vals! state
(fn [{:keys [connection] :as state}]
(if (or (= :pending connection)
(ports/connected? connection))
state
(assoc state :connection :pending))))]
(when (nil? old-connection)
(if-let [connection (<! (request-connection port-name baud-rate))]
(connection-successful connection board baud-rate reporting?)
(swap! state assoc :connection nil))
(>! update-chan :connection))))))
|
[
{
"context": "\n [pass\n (-> pMap\n (assoc :password pass)\n )\n ]\n )\n )\n(defn- setup-indicie",
"end": 4108,
"score": 0.8353391885757446,
"start": 4104,
"tag": "PASSWORD",
"value": "pass"
}
] |
src/hphelper/server/live/control.clj
|
lsenjov/hphelper
| 2 |
(ns hphelper.server.live.control
(:require [hphelper.server.shared.sql :as sql]
[hphelper.server.shared.saveload :as sl]
[hphelper.server.shared.unique :as uni]
[hphelper.server.shared.indicies :as indicies]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[hphelper.server.shared.spec :as ss]
[hphelper.server.shared.calls :as cs]
[clojure.data.json :as json]
[hphelper.server.shared.helpers :as help]
)
(:gen-class)
)
;; Current games, keyed by uuid
(defonce ^:private current-games
(atom {}
:validator (fn [m] (ss/valid? ::ss/liveGames m))
)
)
;; Current indicies, keyed by zone string
(defonce ^:private current-indicies
(atom (try (-> "indicies.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read indicies.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? (s/map-of ::ss/zone ::ss/access) m)
(do (future (spit "indicies.edn" (pr-str m))) true)
false
))
)
)
;; Current player purchases
(defonce ^:private current-investments
(atom (try (-> "investments.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read investments.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? ::ss/investments m)
(do (future (spit "investments.edn" (pr-str m))) true)
false
))
)
)
(defn get-investments
"Returns the current investments"
[]
@current-investments)
;If locked, can't trade investments in that zone
(defonce ^:private investment-locks
(atom {}
:validator (partial s/valid? (s/map-of ::ss/zone (s/nilable boolean?)))
)
)
(defn get-lock
"Returns the lock status of a zone"
[^String zone]
(get @investment-locks zone))
(defn set-lock
"Sets the lock of a zone"
[^String zone ^Boolean status]
(swap! investment-locks assoc zone status))
;; TODO change the above to refs and adjust other items accordingly
;; TODO save and load the above
;; Indicies manipulation
(defn new-game-indicies
"If the zone doesn't already exist, associates the indicies and returns them.
If the zone already exists, ignores inds and returns the associated indicies"
[^String zone inds]
(log/trace "new-game-indicies." "zone:" zone "inds:" inds "already stored:" (get @current-indicies zone))
(if-let [i (get @current-indicies zone)]
;; Indicies already exist for this zone, get them
i
;; Indicies dont exist
(let [string-inds (->> inds
;; Remove any list wrapping
(#(if (sequential? %) (first %) %))
;; Make sure all the keys are strings, not keywords
(map (fn [[k v]] [(name k) v]))
;; Put it back into a map
(apply merge {})
;; Make it a list once more
list
)
]
(log/trace "string-inds:" string-inds)
(-> (swap! current-indicies assoc zone
;; If it's a map, put it in a list. Otherwise assume it's a list of maps
string-inds)
(get zone)
)
)
)
)
;; Gets the current time in milliseconds
(defn current-time
"Returns the current time as a long"
[]
(.getTimeInMillis (java.util.Calendar/getInstance))
)
;; Changing a stored scenario into a live scenario for online play
(defn- player-setup
"Adds a uuid key under :password to a player map, performs other live setup, returns the map"
[[_ pMap]]
(let [pass (uni/uuid)
t (current-time)]
[pass
(-> pMap
(assoc :password pass)
)
]
)
)
(defn- setup-indicies-history
"Sets the initial indicies history to a list of the current indicies map"
[{inds :indicies zone :zone :as sMap}]
(log/trace "setup-indicies-history.")
(assoc sMap :indicies (new-game-indicies zone inds)))
(defn- setup-current-access-totals
"Sets up a map of player names to current access, and starts indicies history"
[{players :hps :as sMap}]
(log/trace "setup-current-access-totals. players:" (vals players))
(let [at (reduce merge {"Misc" 0 "Pool" 0}
(map (fn [pMap]
(log/trace "pMap:" pMap)
{(:name pMap) (:accessRemaining pMap)})
(vals players)))]
(-> sMap
(assoc :access (list at))
)
)
)
(defn- setup-last-updated
"Sets up a map of last updated times for all keys"
[sMap ^Integer t]
(log/trace "setup-last-updated. time:" t)
(-> sMap
(assoc :updated (reduce merge {} (map (fn [k] {k t}) (conj (keys sMap) :missions :hps :investments :calls))))
)
)
(defn- player-all-setup
"Adds a uuid password to all players in a scenMap, returns the map"
[sMap]
(-> sMap
;; Setup individual players
(update-in [:hps] (fn [pl] (apply merge {}
(map player-setup pl))))
)
)
(defn new-game
"Creates a new game, either from an existing map or straight 0s."
([valMap]
{:post (s/valid? ::ss/liveScenario %)}
(uni/add-uuid-atom! current-games
(-> valMap
;; Fill in any missing indices
(update-in [:indicies]
(partial merge
(indicies/create-base-indicies-list)))
;; Make sure the news is in the correct format
(update-in [:news]
(partial concat
'()))
;; Set the admin login
(assoc :adminPass (uni/uuid))
;; Adds passwords to everyone
(player-all-setup)
;; Setup indicies history
setup-indicies-history
;; Setup current access totals and access history
setup-current-access-totals
;; Setup last updated to now
(setup-last-updated (current-time))
;; Make sure cbay exists, even if it's just an empty list
(update-in [:cbay] (partial concat []))
;; Add the call queue.
;; While it *should* be a queue, our queue won't ever be more than 9 objects long,
;; so we can just use a vector instead
(assoc :calls cs/empty-calls)
)))
([]
(new-game {:indicies (indicies/create-base-indicies-list)})))
;; Gets a full game structure by uuid from current-games
(defn get-game
"Gets the game associated with the uid"
[^String uid]
(uni/get-uuid-atom current-games uid))
;; Performs func with the arguments on the uuid game. Returns the modified game
(defn- swap-game!
"Applys the function to the game associated with the uuid
Asserts afterwards the game matches spec."
[uid func & args]
(log/trace "swap-game! uid:" uid "func:" func)
(apply uni/swap-uuid! current-games uid (comp #(s/assert ::ss/liveScenario %) func) args))
;; Changes the access amount of an access member
(defn modify-access-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[scenMap player ^Number amount]
(log/trace "modify-access-inner. player:" player "amount:" amount "access:" (-> scenMap :access first))
(let [newAccess (-> (first (:access scenMap))
(update-in [player] + amount)
)]
(log/trace "modify-index-inner. newAccess:" newAccess)
(-> scenMap
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn modify-access
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-access:" uid player amount)
(if (string? amount)
(modify-access uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :access first (get player))
(do
(log/trace "modify-access. Modifying access.")
(swap-game! uid modify-access-inner player amount)
)
(do
(log/error "modify-access. Could not find game.")
nil))
))
;; Changes the public standing of a player
(defn modify-public-standing-inner
"Modifies a player's public standing by a certain amount"
[scenMap player ^Integer amount]
(log/trace "modify-public-standing-inner. player:" player "amount:" amount)
(let [uid (some (fn [[pass {p-name :name}]]
(if (= player p-name) pass nil))
(:hps scenMap))]
(log/trace "modify-public-standing-inner. uid:" uid)
(if uid
(-> scenMap
(update-in [:hps uid :publicStanding] (fn [ps] (-> (if ps (+ ps amount) amount) (max -10) (min 10))))
(assoc-in [:updated :hps] (current-time))
)
scenMap
)
)
)
(defn modify-public-standing
"Modifys a player's public standing by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-public-standing:" uid player amount)
(if (string? amount)
(modify-public-standing
uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (help/is-hp-name? (get-game uid) player)
(do
(log/trace "modify-public-standing. Modifying public standing.")
(swap-game! uid modify-public-standing-inner player amount)
)
(do
(log/error "modify-public-standing. Could not find game.")
nil))
))
;; Sends access from one account to another
(defn send-access-inner
"Actually sends access, adding a single line to access and updating :updated"
[g ^String player-from ^String player-to ^Integer amount]
(log/trace "send-access-inner" player-from player-to amount (type amount))
(let [newAccess (-> (first (:access g))
(update-in [player-from] + (- amount))
(update-in [player-to] + amount)
)]
(log/trace "send-access-inner. newAccess:" newAccess)
(-> g
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn send-access
"Sends access from one player to another"
[^String uid ^String player-from ^String player-to amount]
(let [g (get-game uid)
am (help/parse-int amount)]
(log/trace "send-access" uid player-from player-to "amount:" amount "parsedamount:" am (type am))
(cond
;; game invalid
(not g)
nil
;; Couldn't parse amount
(not am)
nil
;; Targets don't exist in the access pool
(not (and ((-> g :access first keys set) player-from)
((-> g :access first keys set) player-to)
)
)
nil
;; All is well, do it
:all-good
(swap-game! uid send-access-inner player-from player-to am)
)
)
)
;; Modifies a single index. Fuzzifies all indicies, then normalises the service group indicies
(defn modify-index-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[{:keys [zone] :as scenMap} index ^Integer amount]
(log/trace "modify-index-inner. index:" index "amount:" amount "indicies:" (-> scenMap :indicies first))
(let [newInds (-> (swap! current-indicies
update-in [zone]
;; Functions takes a list of indicies, conjoins a modified index to the beginning
(fn [l]
;; Limit history to 20 items for now
(take 20
(conj l
(-> l
first
(update-in [index] + amount)
indicies/fuzzify-indicies
indicies/normalise-all-indicies
)
)
)
)
)
;; We have the result of the swap, now we get the indicies
(get zone)
)
]
(log/trace "modify-index-inner. newInds:" newInds)
(-> scenMap
(assoc-in [:indicies] newInds)
(assoc-in [:updated :indicies] (current-time))
)
)
)
(defn modify-index
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid index amount]
(log/trace "modify-index:" uid index amount)
(if (string? amount)
(modify-index uid
index
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it will just fuzzify
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :indicies first (get (name index)))
(do
(log/trace "modify-index. Modifying index.")
(swap-game! uid modify-index-inner (name index) amount)
)
(do
(log/error "modify-index. Could not find game.")
nil))
))
;; Sets the owner of a service group
(defn- set-sg-owner-inner
"Actually sets the owner of the service group, along with the updated time"
[g sgIndex newOwner]
{:pre [(s/assert ::ss/liveScenario g)]
:post [(s/assert ::ss/liveScenario %)]}
(log/trace "set-sg-owner-inner. sgIndex:" sgIndex "newOwner:" newOwner)
(log/trace "set-sg-owner-inner. Servicegroups:" (:serviceGroups g))
(-> g
(assoc-in [:serviceGroups sgIndex :owner] newOwner)
(assoc-in [:updated :serviceGroups] (current-time))
(assoc-in [:updated :directives] (current-time))
)
)
(defn set-sg-owner
"Sets the owner of a service group, returns the sg_id, or nil if failure.
sg can be either the name, id, or abbreviation"
[^String uid ^String sg ^String newOwner]
(log/trace "set-sg-owner:" uid sg newOwner)
(if-let [index (help/get-sg-abbr (get-game uid) sg)]
(do
(log/trace "set-sg-owner. Found sg index:" index)
(swap-game! uid set-sg-owner-inner index newOwner)
)
(do
(log/trace "set-sg-owner. Found no index for sg:" sg)
nil
)
)
)
;; Adds or gets news from a game
(defn add-news-item
"Adds a single news item to a game"
[uid ^String newsItem]
(swap-game! uid update-in [:news] conj newsItem))
(defn get-news
"Gets the news list of a game"
[uid]
((uni/get-uuid-atom current-games uid) :news))
;; Lets a player purchase a minion. Automatically adjusts their access total
(defn- set-minion-bought-status
"Sets a minion's status to bought or not"
[g ^Integer sgid ^Integer minionid bought?]
(log/trace "set-minion-bought-status:" sgid minionid bought?)
(let [sgindex (help/get-sg-abbr g sgid)]
(log/trace "sgindex:" sgindex)
(-> g
(update-in [:serviceGroups sgindex :minions]
(fn [ms]
(doall
(map (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
;; Minion we're after
(let [ret (assoc m :bought? bought?)]
(log/trace "bought minion:" ret)
ret
)
;; Not after this one
(do
;(log/trace "Didn't edit minion:" m)
m
)
)
)
ms
)
)
)
)
(assoc-in [:updated :serviceGroups] (current-time))
)
)
)
(defn purchase-minion-inner
"Actually purchases the minion for the player."
[g ^String player ^Integer sgid ^Integer minionid ^Integer cost]
(log/trace "purchase-minion-inner:" player sgid minionid cost)
(-> g
(set-minion-bought-status sgid minionid true)
(modify-access-inner player (- cost))
)
)
(defn purchase-minion
"Has a player purchase a minion. Deducting the required amount of access, and setting :bought on the minion"
[^String uid ^String player ^Integer sgid ^Integer minionid]
(log/trace "purchase-minion:" uid player sgid minionid)
(let [g (get-game uid)
sg_abbr (help/get-sg-abbr g sgid)
_ (log/trace "sg_abbr:" sg_abbr)
minion (as-> g v
(:serviceGroups v)
;; Get the service group
(get v sg_abbr)
;; We have the service group, now to get the minion
(:minions v)
;; Get the minion
(some (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
m
nil))
v)
)
]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Is the minion already purchased?
(:bought? minion)
(do (log/trace "Minion is already bought.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid purchase-minion-inner player sgid minionid (:minion_cost minion))
)
)
)
;; Trading service group investments
(defn player-trade-investment
"Player trades a certain amount of shares in a service group
Positive for buy, negative for sell
Does NOT protect against a player putting their account into negatives, however"
[^String gUid ^String player ^String zone ^String group ^Integer amount]
(let [g (get-game gUid)
;; Current number owned by the player, may be nil
current (-> (get-in @current-investments [player group])
(#(do (log/trace "current:" %) %)))
;; Current index, should not be nil
index (-> @current-indicies
(#(do (log/trace "current-indicies:" %) %))
(get zone)
first
(get group)
;; Logging
(#(do (log/trace "index:" %) %)))
;; Total price
;price (-> index (+ 100) (/ 100) (max 0.1) (* (- amount)))
price (if (neg? amount)
;; Are we selling? If so, it sells for a slightly lower price
(* 0.9 (- amount))
(- amount))
]
(log/trace "player-trade-investment:" gUid player zone group amount)
(cond
;; After this trade, will the total shares be less than zero?
(< (+ amount (if current current 0)) 0)
(log/trace "total shares will be less than 0")
;; Does the game exist?
(not g)
nil
;; Is the player a player?
(not (help/is-hp-name? g player))
nil
;; Is the investments of the sector locked?
(get-lock zone)
nil
;; I can't think of any other problems... go for it
:okay
(do
(swap! current-investments update-in [player group] #(if % (+ % amount) amount))
(swap-game! gUid assoc-in [:updated :investments] (current-time))
(modify-access gUid player price)
)
)
)
)
;; Call queue
(defn player-make-call-inner
"Actually adds/replaces a player's call in the call queue"
[g player sg minionId privateCall]
(-> g
(update-in [:calls] cs/add-call (cs/construct-call player sg minionId privateCall))
(assoc-in [:updated :calls] (current-time))
))
(defn player-make-call
"Adds/replaces a player's call in the call queue"
[^String uid ^String player ^String sg ^Integer minionId ^Integer privateCall]
(log/trace "player-make-call. uid:" uid "player:" player "sg:" sg "minionId:" minionId "privateCall:" privateCall)
(let [g (get-game uid)
minion (as-> g v
(get-in v [:serviceGroups sg :minions])
(do (log/trace "Servicegroups:" v) v)
(some (fn [{minion_id :minion_id :as m}]
(log/trace "player-make-call. minion_id:" minion_id "Equals?" (= minionId minion_id) "Minion:" m)
(if (= minionId minion_id) m nil))
v))]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid player-make-call-inner player sg minionId privateCall))))
(defn admin-call-next
"Moves the call queue to the next call"
[^String uid]
(log/trace "admin-call-next. uid:" uid)
(swap-game! uid #(-> %
(update-in [:calls] cs/next-call)
(assoc-in [:updated :calls] (current-time)))))
;; Adding custom minions
(defonce next-minion-id-number (atom (int 100000))) ; We start this at a high number, just to be sure
(defn add-custom-minion
"Constructs and adds a custom minion to the specified service group. Assumes fields have been validated"
[gameUuid sg_abbr minionName minionClearance minionDesc]
(let [minionId (swap! next-minion-id-number inc)]
(log/trace "add-custom-minion. guid:" gameUuid "abbr:" sg_abbr "minionName:" minionName "minionClearance:" minionClearance "minionDesc:" minionDesc "minionId:" minionId)
(swap-game! gameUuid #(-> %
(update-in [:serviceGroups sg_abbr :minions]
conj
{:minion_id minionId
:minion_name minionName
:minion_clearance minionClearance
:minion_cost 0
:mskills minionDesc
:bought? true})
(assoc-in [:updated :serviceGroups] (current-time))))))
;; Kills a player
;; Removes skills at random, and takes off 20 ACCESS
(defn- remove-stat
"Given a priStats map, will attempt to remove a single skill point at random.
If the skill is already at one, will leave at one and waste the attempt"
[priStats]
(log/info "remove-stat" priStats)
(let [rand-key (-> priStats keys rand-nth)]
(update-in priStats [rand-key] (comp (partial max 1) dec)))
)
(defn- remove-stats
"Given a character, will remove stats and recalculate"
[hp]
(let [degredation (-> hp :secStats (get "Clone Degredation"))]
(update-in hp [:priStats] #(nth (iterate remove-stat %) degredation))
))
(defn zap-character-inner
[g player]
(if-let [player-uid (help/get-player-uid g player)]
(-> g
(update-in [:hps player-uid] remove-stats)
(assoc-in [:updated :hps] (current-time)))
g))
(defn zap-character
"Given a game and character, remove stats and 20 access"
[^String uid ^String player]
(log/trace "zap-character:" uid player)
(swap-game! uid #(-> %
(zap-character-inner player)
(modify-access-inner player -20)
)))
;; Debug stuff
(comment
(log/set-level! :trace)
(reset! current-games {})
; Current games in the atom
(-> @current-games keys)
(-> (zap-character (-> @current-games keys first) "Test-U-CHA-4")
:hps first)
(let [hp (-> @current-games vals first :hps first second)
]
(remove-stats hp)
)
(-> (let [player "Test-U-CHA-4"
scenMap (-> @current-games vals first)]
;;(zap-character-inner scenMap player)
(send-access-inner scenMap player "Misc" 20)
)
:hps first second :accessRemaining)
(-> @current-games vals first :hps first)
(-> @current-games vals first :serviceGroups (get "TD") :minions)
(-> @current-games vals first :serviceGroups (get "TD"))
(-> @current-games vals first keys)
(-> @current-games vals first :calls)
(-> @current-games vals first :indicies)
(-> @current-games vals first :updated)
(-> @current-games vals first :updated keys)
(reset! current-games {})
)
|
34087
|
(ns hphelper.server.live.control
(:require [hphelper.server.shared.sql :as sql]
[hphelper.server.shared.saveload :as sl]
[hphelper.server.shared.unique :as uni]
[hphelper.server.shared.indicies :as indicies]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[hphelper.server.shared.spec :as ss]
[hphelper.server.shared.calls :as cs]
[clojure.data.json :as json]
[hphelper.server.shared.helpers :as help]
)
(:gen-class)
)
;; Current games, keyed by uuid
(defonce ^:private current-games
(atom {}
:validator (fn [m] (ss/valid? ::ss/liveGames m))
)
)
;; Current indicies, keyed by zone string
(defonce ^:private current-indicies
(atom (try (-> "indicies.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read indicies.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? (s/map-of ::ss/zone ::ss/access) m)
(do (future (spit "indicies.edn" (pr-str m))) true)
false
))
)
)
;; Current player purchases
(defonce ^:private current-investments
(atom (try (-> "investments.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read investments.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? ::ss/investments m)
(do (future (spit "investments.edn" (pr-str m))) true)
false
))
)
)
(defn get-investments
"Returns the current investments"
[]
@current-investments)
;If locked, can't trade investments in that zone
(defonce ^:private investment-locks
(atom {}
:validator (partial s/valid? (s/map-of ::ss/zone (s/nilable boolean?)))
)
)
(defn get-lock
"Returns the lock status of a zone"
[^String zone]
(get @investment-locks zone))
(defn set-lock
"Sets the lock of a zone"
[^String zone ^Boolean status]
(swap! investment-locks assoc zone status))
;; TODO change the above to refs and adjust other items accordingly
;; TODO save and load the above
;; Indicies manipulation
(defn new-game-indicies
"If the zone doesn't already exist, associates the indicies and returns them.
If the zone already exists, ignores inds and returns the associated indicies"
[^String zone inds]
(log/trace "new-game-indicies." "zone:" zone "inds:" inds "already stored:" (get @current-indicies zone))
(if-let [i (get @current-indicies zone)]
;; Indicies already exist for this zone, get them
i
;; Indicies dont exist
(let [string-inds (->> inds
;; Remove any list wrapping
(#(if (sequential? %) (first %) %))
;; Make sure all the keys are strings, not keywords
(map (fn [[k v]] [(name k) v]))
;; Put it back into a map
(apply merge {})
;; Make it a list once more
list
)
]
(log/trace "string-inds:" string-inds)
(-> (swap! current-indicies assoc zone
;; If it's a map, put it in a list. Otherwise assume it's a list of maps
string-inds)
(get zone)
)
)
)
)
;; Gets the current time in milliseconds
(defn current-time
"Returns the current time as a long"
[]
(.getTimeInMillis (java.util.Calendar/getInstance))
)
;; Changing a stored scenario into a live scenario for online play
(defn- player-setup
"Adds a uuid key under :password to a player map, performs other live setup, returns the map"
[[_ pMap]]
(let [pass (uni/uuid)
t (current-time)]
[pass
(-> pMap
(assoc :password <PASSWORD>)
)
]
)
)
(defn- setup-indicies-history
"Sets the initial indicies history to a list of the current indicies map"
[{inds :indicies zone :zone :as sMap}]
(log/trace "setup-indicies-history.")
(assoc sMap :indicies (new-game-indicies zone inds)))
(defn- setup-current-access-totals
"Sets up a map of player names to current access, and starts indicies history"
[{players :hps :as sMap}]
(log/trace "setup-current-access-totals. players:" (vals players))
(let [at (reduce merge {"Misc" 0 "Pool" 0}
(map (fn [pMap]
(log/trace "pMap:" pMap)
{(:name pMap) (:accessRemaining pMap)})
(vals players)))]
(-> sMap
(assoc :access (list at))
)
)
)
(defn- setup-last-updated
"Sets up a map of last updated times for all keys"
[sMap ^Integer t]
(log/trace "setup-last-updated. time:" t)
(-> sMap
(assoc :updated (reduce merge {} (map (fn [k] {k t}) (conj (keys sMap) :missions :hps :investments :calls))))
)
)
(defn- player-all-setup
"Adds a uuid password to all players in a scenMap, returns the map"
[sMap]
(-> sMap
;; Setup individual players
(update-in [:hps] (fn [pl] (apply merge {}
(map player-setup pl))))
)
)
(defn new-game
"Creates a new game, either from an existing map or straight 0s."
([valMap]
{:post (s/valid? ::ss/liveScenario %)}
(uni/add-uuid-atom! current-games
(-> valMap
;; Fill in any missing indices
(update-in [:indicies]
(partial merge
(indicies/create-base-indicies-list)))
;; Make sure the news is in the correct format
(update-in [:news]
(partial concat
'()))
;; Set the admin login
(assoc :adminPass (uni/uuid))
;; Adds passwords to everyone
(player-all-setup)
;; Setup indicies history
setup-indicies-history
;; Setup current access totals and access history
setup-current-access-totals
;; Setup last updated to now
(setup-last-updated (current-time))
;; Make sure cbay exists, even if it's just an empty list
(update-in [:cbay] (partial concat []))
;; Add the call queue.
;; While it *should* be a queue, our queue won't ever be more than 9 objects long,
;; so we can just use a vector instead
(assoc :calls cs/empty-calls)
)))
([]
(new-game {:indicies (indicies/create-base-indicies-list)})))
;; Gets a full game structure by uuid from current-games
(defn get-game
"Gets the game associated with the uid"
[^String uid]
(uni/get-uuid-atom current-games uid))
;; Performs func with the arguments on the uuid game. Returns the modified game
(defn- swap-game!
"Applys the function to the game associated with the uuid
Asserts afterwards the game matches spec."
[uid func & args]
(log/trace "swap-game! uid:" uid "func:" func)
(apply uni/swap-uuid! current-games uid (comp #(s/assert ::ss/liveScenario %) func) args))
;; Changes the access amount of an access member
(defn modify-access-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[scenMap player ^Number amount]
(log/trace "modify-access-inner. player:" player "amount:" amount "access:" (-> scenMap :access first))
(let [newAccess (-> (first (:access scenMap))
(update-in [player] + amount)
)]
(log/trace "modify-index-inner. newAccess:" newAccess)
(-> scenMap
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn modify-access
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-access:" uid player amount)
(if (string? amount)
(modify-access uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :access first (get player))
(do
(log/trace "modify-access. Modifying access.")
(swap-game! uid modify-access-inner player amount)
)
(do
(log/error "modify-access. Could not find game.")
nil))
))
;; Changes the public standing of a player
(defn modify-public-standing-inner
"Modifies a player's public standing by a certain amount"
[scenMap player ^Integer amount]
(log/trace "modify-public-standing-inner. player:" player "amount:" amount)
(let [uid (some (fn [[pass {p-name :name}]]
(if (= player p-name) pass nil))
(:hps scenMap))]
(log/trace "modify-public-standing-inner. uid:" uid)
(if uid
(-> scenMap
(update-in [:hps uid :publicStanding] (fn [ps] (-> (if ps (+ ps amount) amount) (max -10) (min 10))))
(assoc-in [:updated :hps] (current-time))
)
scenMap
)
)
)
(defn modify-public-standing
"Modifys a player's public standing by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-public-standing:" uid player amount)
(if (string? amount)
(modify-public-standing
uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (help/is-hp-name? (get-game uid) player)
(do
(log/trace "modify-public-standing. Modifying public standing.")
(swap-game! uid modify-public-standing-inner player amount)
)
(do
(log/error "modify-public-standing. Could not find game.")
nil))
))
;; Sends access from one account to another
(defn send-access-inner
"Actually sends access, adding a single line to access and updating :updated"
[g ^String player-from ^String player-to ^Integer amount]
(log/trace "send-access-inner" player-from player-to amount (type amount))
(let [newAccess (-> (first (:access g))
(update-in [player-from] + (- amount))
(update-in [player-to] + amount)
)]
(log/trace "send-access-inner. newAccess:" newAccess)
(-> g
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn send-access
"Sends access from one player to another"
[^String uid ^String player-from ^String player-to amount]
(let [g (get-game uid)
am (help/parse-int amount)]
(log/trace "send-access" uid player-from player-to "amount:" amount "parsedamount:" am (type am))
(cond
;; game invalid
(not g)
nil
;; Couldn't parse amount
(not am)
nil
;; Targets don't exist in the access pool
(not (and ((-> g :access first keys set) player-from)
((-> g :access first keys set) player-to)
)
)
nil
;; All is well, do it
:all-good
(swap-game! uid send-access-inner player-from player-to am)
)
)
)
;; Modifies a single index. Fuzzifies all indicies, then normalises the service group indicies
(defn modify-index-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[{:keys [zone] :as scenMap} index ^Integer amount]
(log/trace "modify-index-inner. index:" index "amount:" amount "indicies:" (-> scenMap :indicies first))
(let [newInds (-> (swap! current-indicies
update-in [zone]
;; Functions takes a list of indicies, conjoins a modified index to the beginning
(fn [l]
;; Limit history to 20 items for now
(take 20
(conj l
(-> l
first
(update-in [index] + amount)
indicies/fuzzify-indicies
indicies/normalise-all-indicies
)
)
)
)
)
;; We have the result of the swap, now we get the indicies
(get zone)
)
]
(log/trace "modify-index-inner. newInds:" newInds)
(-> scenMap
(assoc-in [:indicies] newInds)
(assoc-in [:updated :indicies] (current-time))
)
)
)
(defn modify-index
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid index amount]
(log/trace "modify-index:" uid index amount)
(if (string? amount)
(modify-index uid
index
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it will just fuzzify
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :indicies first (get (name index)))
(do
(log/trace "modify-index. Modifying index.")
(swap-game! uid modify-index-inner (name index) amount)
)
(do
(log/error "modify-index. Could not find game.")
nil))
))
;; Sets the owner of a service group
(defn- set-sg-owner-inner
"Actually sets the owner of the service group, along with the updated time"
[g sgIndex newOwner]
{:pre [(s/assert ::ss/liveScenario g)]
:post [(s/assert ::ss/liveScenario %)]}
(log/trace "set-sg-owner-inner. sgIndex:" sgIndex "newOwner:" newOwner)
(log/trace "set-sg-owner-inner. Servicegroups:" (:serviceGroups g))
(-> g
(assoc-in [:serviceGroups sgIndex :owner] newOwner)
(assoc-in [:updated :serviceGroups] (current-time))
(assoc-in [:updated :directives] (current-time))
)
)
(defn set-sg-owner
"Sets the owner of a service group, returns the sg_id, or nil if failure.
sg can be either the name, id, or abbreviation"
[^String uid ^String sg ^String newOwner]
(log/trace "set-sg-owner:" uid sg newOwner)
(if-let [index (help/get-sg-abbr (get-game uid) sg)]
(do
(log/trace "set-sg-owner. Found sg index:" index)
(swap-game! uid set-sg-owner-inner index newOwner)
)
(do
(log/trace "set-sg-owner. Found no index for sg:" sg)
nil
)
)
)
;; Adds or gets news from a game
(defn add-news-item
"Adds a single news item to a game"
[uid ^String newsItem]
(swap-game! uid update-in [:news] conj newsItem))
(defn get-news
"Gets the news list of a game"
[uid]
((uni/get-uuid-atom current-games uid) :news))
;; Lets a player purchase a minion. Automatically adjusts their access total
(defn- set-minion-bought-status
"Sets a minion's status to bought or not"
[g ^Integer sgid ^Integer minionid bought?]
(log/trace "set-minion-bought-status:" sgid minionid bought?)
(let [sgindex (help/get-sg-abbr g sgid)]
(log/trace "sgindex:" sgindex)
(-> g
(update-in [:serviceGroups sgindex :minions]
(fn [ms]
(doall
(map (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
;; Minion we're after
(let [ret (assoc m :bought? bought?)]
(log/trace "bought minion:" ret)
ret
)
;; Not after this one
(do
;(log/trace "Didn't edit minion:" m)
m
)
)
)
ms
)
)
)
)
(assoc-in [:updated :serviceGroups] (current-time))
)
)
)
(defn purchase-minion-inner
"Actually purchases the minion for the player."
[g ^String player ^Integer sgid ^Integer minionid ^Integer cost]
(log/trace "purchase-minion-inner:" player sgid minionid cost)
(-> g
(set-minion-bought-status sgid minionid true)
(modify-access-inner player (- cost))
)
)
(defn purchase-minion
"Has a player purchase a minion. Deducting the required amount of access, and setting :bought on the minion"
[^String uid ^String player ^Integer sgid ^Integer minionid]
(log/trace "purchase-minion:" uid player sgid minionid)
(let [g (get-game uid)
sg_abbr (help/get-sg-abbr g sgid)
_ (log/trace "sg_abbr:" sg_abbr)
minion (as-> g v
(:serviceGroups v)
;; Get the service group
(get v sg_abbr)
;; We have the service group, now to get the minion
(:minions v)
;; Get the minion
(some (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
m
nil))
v)
)
]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Is the minion already purchased?
(:bought? minion)
(do (log/trace "Minion is already bought.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid purchase-minion-inner player sgid minionid (:minion_cost minion))
)
)
)
;; Trading service group investments
(defn player-trade-investment
"Player trades a certain amount of shares in a service group
Positive for buy, negative for sell
Does NOT protect against a player putting their account into negatives, however"
[^String gUid ^String player ^String zone ^String group ^Integer amount]
(let [g (get-game gUid)
;; Current number owned by the player, may be nil
current (-> (get-in @current-investments [player group])
(#(do (log/trace "current:" %) %)))
;; Current index, should not be nil
index (-> @current-indicies
(#(do (log/trace "current-indicies:" %) %))
(get zone)
first
(get group)
;; Logging
(#(do (log/trace "index:" %) %)))
;; Total price
;price (-> index (+ 100) (/ 100) (max 0.1) (* (- amount)))
price (if (neg? amount)
;; Are we selling? If so, it sells for a slightly lower price
(* 0.9 (- amount))
(- amount))
]
(log/trace "player-trade-investment:" gUid player zone group amount)
(cond
;; After this trade, will the total shares be less than zero?
(< (+ amount (if current current 0)) 0)
(log/trace "total shares will be less than 0")
;; Does the game exist?
(not g)
nil
;; Is the player a player?
(not (help/is-hp-name? g player))
nil
;; Is the investments of the sector locked?
(get-lock zone)
nil
;; I can't think of any other problems... go for it
:okay
(do
(swap! current-investments update-in [player group] #(if % (+ % amount) amount))
(swap-game! gUid assoc-in [:updated :investments] (current-time))
(modify-access gUid player price)
)
)
)
)
;; Call queue
(defn player-make-call-inner
"Actually adds/replaces a player's call in the call queue"
[g player sg minionId privateCall]
(-> g
(update-in [:calls] cs/add-call (cs/construct-call player sg minionId privateCall))
(assoc-in [:updated :calls] (current-time))
))
(defn player-make-call
"Adds/replaces a player's call in the call queue"
[^String uid ^String player ^String sg ^Integer minionId ^Integer privateCall]
(log/trace "player-make-call. uid:" uid "player:" player "sg:" sg "minionId:" minionId "privateCall:" privateCall)
(let [g (get-game uid)
minion (as-> g v
(get-in v [:serviceGroups sg :minions])
(do (log/trace "Servicegroups:" v) v)
(some (fn [{minion_id :minion_id :as m}]
(log/trace "player-make-call. minion_id:" minion_id "Equals?" (= minionId minion_id) "Minion:" m)
(if (= minionId minion_id) m nil))
v))]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid player-make-call-inner player sg minionId privateCall))))
(defn admin-call-next
"Moves the call queue to the next call"
[^String uid]
(log/trace "admin-call-next. uid:" uid)
(swap-game! uid #(-> %
(update-in [:calls] cs/next-call)
(assoc-in [:updated :calls] (current-time)))))
;; Adding custom minions
(defonce next-minion-id-number (atom (int 100000))) ; We start this at a high number, just to be sure
(defn add-custom-minion
"Constructs and adds a custom minion to the specified service group. Assumes fields have been validated"
[gameUuid sg_abbr minionName minionClearance minionDesc]
(let [minionId (swap! next-minion-id-number inc)]
(log/trace "add-custom-minion. guid:" gameUuid "abbr:" sg_abbr "minionName:" minionName "minionClearance:" minionClearance "minionDesc:" minionDesc "minionId:" minionId)
(swap-game! gameUuid #(-> %
(update-in [:serviceGroups sg_abbr :minions]
conj
{:minion_id minionId
:minion_name minionName
:minion_clearance minionClearance
:minion_cost 0
:mskills minionDesc
:bought? true})
(assoc-in [:updated :serviceGroups] (current-time))))))
;; Kills a player
;; Removes skills at random, and takes off 20 ACCESS
(defn- remove-stat
"Given a priStats map, will attempt to remove a single skill point at random.
If the skill is already at one, will leave at one and waste the attempt"
[priStats]
(log/info "remove-stat" priStats)
(let [rand-key (-> priStats keys rand-nth)]
(update-in priStats [rand-key] (comp (partial max 1) dec)))
)
(defn- remove-stats
"Given a character, will remove stats and recalculate"
[hp]
(let [degredation (-> hp :secStats (get "Clone Degredation"))]
(update-in hp [:priStats] #(nth (iterate remove-stat %) degredation))
))
(defn zap-character-inner
[g player]
(if-let [player-uid (help/get-player-uid g player)]
(-> g
(update-in [:hps player-uid] remove-stats)
(assoc-in [:updated :hps] (current-time)))
g))
(defn zap-character
"Given a game and character, remove stats and 20 access"
[^String uid ^String player]
(log/trace "zap-character:" uid player)
(swap-game! uid #(-> %
(zap-character-inner player)
(modify-access-inner player -20)
)))
;; Debug stuff
(comment
(log/set-level! :trace)
(reset! current-games {})
; Current games in the atom
(-> @current-games keys)
(-> (zap-character (-> @current-games keys first) "Test-U-CHA-4")
:hps first)
(let [hp (-> @current-games vals first :hps first second)
]
(remove-stats hp)
)
(-> (let [player "Test-U-CHA-4"
scenMap (-> @current-games vals first)]
;;(zap-character-inner scenMap player)
(send-access-inner scenMap player "Misc" 20)
)
:hps first second :accessRemaining)
(-> @current-games vals first :hps first)
(-> @current-games vals first :serviceGroups (get "TD") :minions)
(-> @current-games vals first :serviceGroups (get "TD"))
(-> @current-games vals first keys)
(-> @current-games vals first :calls)
(-> @current-games vals first :indicies)
(-> @current-games vals first :updated)
(-> @current-games vals first :updated keys)
(reset! current-games {})
)
| true |
(ns hphelper.server.live.control
(:require [hphelper.server.shared.sql :as sql]
[hphelper.server.shared.saveload :as sl]
[hphelper.server.shared.unique :as uni]
[hphelper.server.shared.indicies :as indicies]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[hphelper.server.shared.spec :as ss]
[hphelper.server.shared.calls :as cs]
[clojure.data.json :as json]
[hphelper.server.shared.helpers :as help]
)
(:gen-class)
)
;; Current games, keyed by uuid
(defonce ^:private current-games
(atom {}
:validator (fn [m] (ss/valid? ::ss/liveGames m))
)
)
;; Current indicies, keyed by zone string
(defonce ^:private current-indicies
(atom (try (-> "indicies.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read indicies.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? (s/map-of ::ss/zone ::ss/access) m)
(do (future (spit "indicies.edn" (pr-str m))) true)
false
))
)
)
;; Current player purchases
(defonce ^:private current-investments
(atom (try (-> "investments.edn" slurp clojure.edn/read-string)
(catch Exception e
(log/trace "Could not read investments.edn")
;; Return an empty map
{}
)
)
:validator (fn [m] (if (s/valid? ::ss/investments m)
(do (future (spit "investments.edn" (pr-str m))) true)
false
))
)
)
(defn get-investments
"Returns the current investments"
[]
@current-investments)
;If locked, can't trade investments in that zone
(defonce ^:private investment-locks
(atom {}
:validator (partial s/valid? (s/map-of ::ss/zone (s/nilable boolean?)))
)
)
(defn get-lock
"Returns the lock status of a zone"
[^String zone]
(get @investment-locks zone))
(defn set-lock
"Sets the lock of a zone"
[^String zone ^Boolean status]
(swap! investment-locks assoc zone status))
;; TODO change the above to refs and adjust other items accordingly
;; TODO save and load the above
;; Indicies manipulation
(defn new-game-indicies
"If the zone doesn't already exist, associates the indicies and returns them.
If the zone already exists, ignores inds and returns the associated indicies"
[^String zone inds]
(log/trace "new-game-indicies." "zone:" zone "inds:" inds "already stored:" (get @current-indicies zone))
(if-let [i (get @current-indicies zone)]
;; Indicies already exist for this zone, get them
i
;; Indicies dont exist
(let [string-inds (->> inds
;; Remove any list wrapping
(#(if (sequential? %) (first %) %))
;; Make sure all the keys are strings, not keywords
(map (fn [[k v]] [(name k) v]))
;; Put it back into a map
(apply merge {})
;; Make it a list once more
list
)
]
(log/trace "string-inds:" string-inds)
(-> (swap! current-indicies assoc zone
;; If it's a map, put it in a list. Otherwise assume it's a list of maps
string-inds)
(get zone)
)
)
)
)
;; Gets the current time in milliseconds
(defn current-time
"Returns the current time as a long"
[]
(.getTimeInMillis (java.util.Calendar/getInstance))
)
;; Changing a stored scenario into a live scenario for online play
(defn- player-setup
"Adds a uuid key under :password to a player map, performs other live setup, returns the map"
[[_ pMap]]
(let [pass (uni/uuid)
t (current-time)]
[pass
(-> pMap
(assoc :password PI:PASSWORD:<PASSWORD>END_PI)
)
]
)
)
(defn- setup-indicies-history
"Sets the initial indicies history to a list of the current indicies map"
[{inds :indicies zone :zone :as sMap}]
(log/trace "setup-indicies-history.")
(assoc sMap :indicies (new-game-indicies zone inds)))
(defn- setup-current-access-totals
"Sets up a map of player names to current access, and starts indicies history"
[{players :hps :as sMap}]
(log/trace "setup-current-access-totals. players:" (vals players))
(let [at (reduce merge {"Misc" 0 "Pool" 0}
(map (fn [pMap]
(log/trace "pMap:" pMap)
{(:name pMap) (:accessRemaining pMap)})
(vals players)))]
(-> sMap
(assoc :access (list at))
)
)
)
(defn- setup-last-updated
"Sets up a map of last updated times for all keys"
[sMap ^Integer t]
(log/trace "setup-last-updated. time:" t)
(-> sMap
(assoc :updated (reduce merge {} (map (fn [k] {k t}) (conj (keys sMap) :missions :hps :investments :calls))))
)
)
(defn- player-all-setup
"Adds a uuid password to all players in a scenMap, returns the map"
[sMap]
(-> sMap
;; Setup individual players
(update-in [:hps] (fn [pl] (apply merge {}
(map player-setup pl))))
)
)
(defn new-game
"Creates a new game, either from an existing map or straight 0s."
([valMap]
{:post (s/valid? ::ss/liveScenario %)}
(uni/add-uuid-atom! current-games
(-> valMap
;; Fill in any missing indices
(update-in [:indicies]
(partial merge
(indicies/create-base-indicies-list)))
;; Make sure the news is in the correct format
(update-in [:news]
(partial concat
'()))
;; Set the admin login
(assoc :adminPass (uni/uuid))
;; Adds passwords to everyone
(player-all-setup)
;; Setup indicies history
setup-indicies-history
;; Setup current access totals and access history
setup-current-access-totals
;; Setup last updated to now
(setup-last-updated (current-time))
;; Make sure cbay exists, even if it's just an empty list
(update-in [:cbay] (partial concat []))
;; Add the call queue.
;; While it *should* be a queue, our queue won't ever be more than 9 objects long,
;; so we can just use a vector instead
(assoc :calls cs/empty-calls)
)))
([]
(new-game {:indicies (indicies/create-base-indicies-list)})))
;; Gets a full game structure by uuid from current-games
(defn get-game
"Gets the game associated with the uid"
[^String uid]
(uni/get-uuid-atom current-games uid))
;; Performs func with the arguments on the uuid game. Returns the modified game
(defn- swap-game!
"Applys the function to the game associated with the uuid
Asserts afterwards the game matches spec."
[uid func & args]
(log/trace "swap-game! uid:" uid "func:" func)
(apply uni/swap-uuid! current-games uid (comp #(s/assert ::ss/liveScenario %) func) args))
;; Changes the access amount of an access member
(defn modify-access-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[scenMap player ^Number amount]
(log/trace "modify-access-inner. player:" player "amount:" amount "access:" (-> scenMap :access first))
(let [newAccess (-> (first (:access scenMap))
(update-in [player] + amount)
)]
(log/trace "modify-index-inner. newAccess:" newAccess)
(-> scenMap
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn modify-access
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-access:" uid player amount)
(if (string? amount)
(modify-access uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :access first (get player))
(do
(log/trace "modify-access. Modifying access.")
(swap-game! uid modify-access-inner player amount)
)
(do
(log/error "modify-access. Could not find game.")
nil))
))
;; Changes the public standing of a player
(defn modify-public-standing-inner
"Modifies a player's public standing by a certain amount"
[scenMap player ^Integer amount]
(log/trace "modify-public-standing-inner. player:" player "amount:" amount)
(let [uid (some (fn [[pass {p-name :name}]]
(if (= player p-name) pass nil))
(:hps scenMap))]
(log/trace "modify-public-standing-inner. uid:" uid)
(if uid
(-> scenMap
(update-in [:hps uid :publicStanding] (fn [ps] (-> (if ps (+ ps amount) amount) (max -10) (min 10))))
(assoc-in [:updated :hps] (current-time))
)
scenMap
)
)
)
(defn modify-public-standing
"Modifys a player's public standing by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid player amount]
(log/trace "modify-public-standing:" uid player amount)
(if (string? amount)
(modify-public-standing
uid
player
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it won't do anything
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (help/is-hp-name? (get-game uid) player)
(do
(log/trace "modify-public-standing. Modifying public standing.")
(swap-game! uid modify-public-standing-inner player amount)
)
(do
(log/error "modify-public-standing. Could not find game.")
nil))
))
;; Sends access from one account to another
(defn send-access-inner
"Actually sends access, adding a single line to access and updating :updated"
[g ^String player-from ^String player-to ^Integer amount]
(log/trace "send-access-inner" player-from player-to amount (type amount))
(let [newAccess (-> (first (:access g))
(update-in [player-from] + (- amount))
(update-in [player-to] + amount)
)]
(log/trace "send-access-inner. newAccess:" newAccess)
(-> g
(update-in [:access] (comp (partial take 20) (partial cons newAccess)))
(assoc-in [:updated :access] (current-time))
)
)
)
(defn send-access
"Sends access from one player to another"
[^String uid ^String player-from ^String player-to amount]
(let [g (get-game uid)
am (help/parse-int amount)]
(log/trace "send-access" uid player-from player-to "amount:" amount "parsedamount:" am (type am))
(cond
;; game invalid
(not g)
nil
;; Couldn't parse amount
(not am)
nil
;; Targets don't exist in the access pool
(not (and ((-> g :access first keys set) player-from)
((-> g :access first keys set) player-to)
)
)
nil
;; All is well, do it
:all-good
(swap-game! uid send-access-inner player-from player-to am)
)
)
)
;; Modifies a single index. Fuzzifies all indicies, then normalises the service group indicies
(defn modify-index-inner
"Modifies an index by a certain amount, and fuzzifies the indices"
[{:keys [zone] :as scenMap} index ^Integer amount]
(log/trace "modify-index-inner. index:" index "amount:" amount "indicies:" (-> scenMap :indicies first))
(let [newInds (-> (swap! current-indicies
update-in [zone]
;; Functions takes a list of indicies, conjoins a modified index to the beginning
(fn [l]
;; Limit history to 20 items for now
(take 20
(conj l
(-> l
first
(update-in [index] + amount)
indicies/fuzzify-indicies
indicies/normalise-all-indicies
)
)
)
)
)
;; We have the result of the swap, now we get the indicies
(get zone)
)
]
(log/trace "modify-index-inner. newInds:" newInds)
(-> scenMap
(assoc-in [:indicies] newInds)
(assoc-in [:updated :indicies] (current-time))
)
)
)
(defn modify-index
"Modifys an index by a certain amount, returns the map, or nil if the game doesn't exist"
[^String uid index amount]
(log/trace "modify-index:" uid index amount)
(if (string? amount)
(modify-index uid
index
(try (Integer/parseInt amount)
(catch Exception e ;; If fails to parse, return 0 so it will just fuzzify
(do
(log/debug "modify-item: could not parse" amount)
0))))
(if (-> @current-games (get uid) :indicies first (get (name index)))
(do
(log/trace "modify-index. Modifying index.")
(swap-game! uid modify-index-inner (name index) amount)
)
(do
(log/error "modify-index. Could not find game.")
nil))
))
;; Sets the owner of a service group
(defn- set-sg-owner-inner
"Actually sets the owner of the service group, along with the updated time"
[g sgIndex newOwner]
{:pre [(s/assert ::ss/liveScenario g)]
:post [(s/assert ::ss/liveScenario %)]}
(log/trace "set-sg-owner-inner. sgIndex:" sgIndex "newOwner:" newOwner)
(log/trace "set-sg-owner-inner. Servicegroups:" (:serviceGroups g))
(-> g
(assoc-in [:serviceGroups sgIndex :owner] newOwner)
(assoc-in [:updated :serviceGroups] (current-time))
(assoc-in [:updated :directives] (current-time))
)
)
(defn set-sg-owner
"Sets the owner of a service group, returns the sg_id, or nil if failure.
sg can be either the name, id, or abbreviation"
[^String uid ^String sg ^String newOwner]
(log/trace "set-sg-owner:" uid sg newOwner)
(if-let [index (help/get-sg-abbr (get-game uid) sg)]
(do
(log/trace "set-sg-owner. Found sg index:" index)
(swap-game! uid set-sg-owner-inner index newOwner)
)
(do
(log/trace "set-sg-owner. Found no index for sg:" sg)
nil
)
)
)
;; Adds or gets news from a game
(defn add-news-item
"Adds a single news item to a game"
[uid ^String newsItem]
(swap-game! uid update-in [:news] conj newsItem))
(defn get-news
"Gets the news list of a game"
[uid]
((uni/get-uuid-atom current-games uid) :news))
;; Lets a player purchase a minion. Automatically adjusts their access total
(defn- set-minion-bought-status
"Sets a minion's status to bought or not"
[g ^Integer sgid ^Integer minionid bought?]
(log/trace "set-minion-bought-status:" sgid minionid bought?)
(let [sgindex (help/get-sg-abbr g sgid)]
(log/trace "sgindex:" sgindex)
(-> g
(update-in [:serviceGroups sgindex :minions]
(fn [ms]
(doall
(map (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
;; Minion we're after
(let [ret (assoc m :bought? bought?)]
(log/trace "bought minion:" ret)
ret
)
;; Not after this one
(do
;(log/trace "Didn't edit minion:" m)
m
)
)
)
ms
)
)
)
)
(assoc-in [:updated :serviceGroups] (current-time))
)
)
)
(defn purchase-minion-inner
"Actually purchases the minion for the player."
[g ^String player ^Integer sgid ^Integer minionid ^Integer cost]
(log/trace "purchase-minion-inner:" player sgid minionid cost)
(-> g
(set-minion-bought-status sgid minionid true)
(modify-access-inner player (- cost))
)
)
(defn purchase-minion
"Has a player purchase a minion. Deducting the required amount of access, and setting :bought on the minion"
[^String uid ^String player ^Integer sgid ^Integer minionid]
(log/trace "purchase-minion:" uid player sgid minionid)
(let [g (get-game uid)
sg_abbr (help/get-sg-abbr g sgid)
_ (log/trace "sg_abbr:" sg_abbr)
minion (as-> g v
(:serviceGroups v)
;; Get the service group
(get v sg_abbr)
;; We have the service group, now to get the minion
(:minions v)
;; Get the minion
(some (fn [{minion_id :minion_id :as m}]
(if (= minion_id minionid)
m
nil))
v)
)
]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Is the minion already purchased?
(:bought? minion)
(do (log/trace "Minion is already bought.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid purchase-minion-inner player sgid minionid (:minion_cost minion))
)
)
)
;; Trading service group investments
(defn player-trade-investment
"Player trades a certain amount of shares in a service group
Positive for buy, negative for sell
Does NOT protect against a player putting their account into negatives, however"
[^String gUid ^String player ^String zone ^String group ^Integer amount]
(let [g (get-game gUid)
;; Current number owned by the player, may be nil
current (-> (get-in @current-investments [player group])
(#(do (log/trace "current:" %) %)))
;; Current index, should not be nil
index (-> @current-indicies
(#(do (log/trace "current-indicies:" %) %))
(get zone)
first
(get group)
;; Logging
(#(do (log/trace "index:" %) %)))
;; Total price
;price (-> index (+ 100) (/ 100) (max 0.1) (* (- amount)))
price (if (neg? amount)
;; Are we selling? If so, it sells for a slightly lower price
(* 0.9 (- amount))
(- amount))
]
(log/trace "player-trade-investment:" gUid player zone group amount)
(cond
;; After this trade, will the total shares be less than zero?
(< (+ amount (if current current 0)) 0)
(log/trace "total shares will be less than 0")
;; Does the game exist?
(not g)
nil
;; Is the player a player?
(not (help/is-hp-name? g player))
nil
;; Is the investments of the sector locked?
(get-lock zone)
nil
;; I can't think of any other problems... go for it
:okay
(do
(swap! current-investments update-in [player group] #(if % (+ % amount) amount))
(swap-game! gUid assoc-in [:updated :investments] (current-time))
(modify-access gUid player price)
)
)
)
)
;; Call queue
(defn player-make-call-inner
"Actually adds/replaces a player's call in the call queue"
[g player sg minionId privateCall]
(-> g
(update-in [:calls] cs/add-call (cs/construct-call player sg minionId privateCall))
(assoc-in [:updated :calls] (current-time))
))
(defn player-make-call
"Adds/replaces a player's call in the call queue"
[^String uid ^String player ^String sg ^Integer minionId ^Integer privateCall]
(log/trace "player-make-call. uid:" uid "player:" player "sg:" sg "minionId:" minionId "privateCall:" privateCall)
(let [g (get-game uid)
minion (as-> g v
(get-in v [:serviceGroups sg :minions])
(do (log/trace "Servicegroups:" v) v)
(some (fn [{minion_id :minion_id :as m}]
(log/trace "player-make-call. minion_id:" minion_id "Equals?" (= minionId minion_id) "Minion:" m)
(if (= minionId minion_id) m nil))
v))]
(cond
;; Does the minion exist?
(not minion)
(do (log/trace "Minion does not exist.") nil)
;; Does the character not exist?
(not (help/is-hp-name? g player))
(do (log/trace "Character" player "does not exist.") nil)
;; All seems well
:all-well
(swap-game! uid player-make-call-inner player sg minionId privateCall))))
(defn admin-call-next
"Moves the call queue to the next call"
[^String uid]
(log/trace "admin-call-next. uid:" uid)
(swap-game! uid #(-> %
(update-in [:calls] cs/next-call)
(assoc-in [:updated :calls] (current-time)))))
;; Adding custom minions
(defonce next-minion-id-number (atom (int 100000))) ; We start this at a high number, just to be sure
(defn add-custom-minion
"Constructs and adds a custom minion to the specified service group. Assumes fields have been validated"
[gameUuid sg_abbr minionName minionClearance minionDesc]
(let [minionId (swap! next-minion-id-number inc)]
(log/trace "add-custom-minion. guid:" gameUuid "abbr:" sg_abbr "minionName:" minionName "minionClearance:" minionClearance "minionDesc:" minionDesc "minionId:" minionId)
(swap-game! gameUuid #(-> %
(update-in [:serviceGroups sg_abbr :minions]
conj
{:minion_id minionId
:minion_name minionName
:minion_clearance minionClearance
:minion_cost 0
:mskills minionDesc
:bought? true})
(assoc-in [:updated :serviceGroups] (current-time))))))
;; Kills a player
;; Removes skills at random, and takes off 20 ACCESS
(defn- remove-stat
"Given a priStats map, will attempt to remove a single skill point at random.
If the skill is already at one, will leave at one and waste the attempt"
[priStats]
(log/info "remove-stat" priStats)
(let [rand-key (-> priStats keys rand-nth)]
(update-in priStats [rand-key] (comp (partial max 1) dec)))
)
(defn- remove-stats
"Given a character, will remove stats and recalculate"
[hp]
(let [degredation (-> hp :secStats (get "Clone Degredation"))]
(update-in hp [:priStats] #(nth (iterate remove-stat %) degredation))
))
(defn zap-character-inner
[g player]
(if-let [player-uid (help/get-player-uid g player)]
(-> g
(update-in [:hps player-uid] remove-stats)
(assoc-in [:updated :hps] (current-time)))
g))
(defn zap-character
"Given a game and character, remove stats and 20 access"
[^String uid ^String player]
(log/trace "zap-character:" uid player)
(swap-game! uid #(-> %
(zap-character-inner player)
(modify-access-inner player -20)
)))
;; Debug stuff
(comment
(log/set-level! :trace)
(reset! current-games {})
; Current games in the atom
(-> @current-games keys)
(-> (zap-character (-> @current-games keys first) "Test-U-CHA-4")
:hps first)
(let [hp (-> @current-games vals first :hps first second)
]
(remove-stats hp)
)
(-> (let [player "Test-U-CHA-4"
scenMap (-> @current-games vals first)]
;;(zap-character-inner scenMap player)
(send-access-inner scenMap player "Misc" 20)
)
:hps first second :accessRemaining)
(-> @current-games vals first :hps first)
(-> @current-games vals first :serviceGroups (get "TD") :minions)
(-> @current-games vals first :serviceGroups (get "TD"))
(-> @current-games vals first keys)
(-> @current-games vals first :calls)
(-> @current-games vals first :indicies)
(-> @current-games vals first :updated)
(-> @current-games vals first :updated keys)
(reset! current-games {})
)
|
[
{
"context": "tdb/wipe-database! *db*)\n (user/create! \"user1\" \"password1\")\n (testing \"We get a login token when authentic",
"end": 866,
"score": 0.9954404830932617,
"start": 857,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "data] (post-request \"/api/auth/login\" {:username \"user1\" :password \"password1\"} nil)]\n (is (= 200 (:",
"end": 1029,
"score": 0.9986612796783447,
"start": 1024,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "t \"/api/auth/login\" {:username \"user1\" :password \"password1\"} nil)]\n (is (= 200 (:status response)))\n ",
"end": 1051,
"score": 0.9993767738342285,
"start": 1042,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "data] (post-request \"/api/auth/login\" {:username \"User1\" :password \"password1\"} nil)]\n (is (= 200 (:",
"end": 1300,
"score": 0.9971669912338257,
"start": 1295,
"tag": "USERNAME",
"value": "User1"
},
{
"context": "t \"/api/auth/login\" {:username \"User1\" :password \"password1\"} nil)]\n (is (= 200 (:status response)))\n ",
"end": 1322,
"score": 0.9994111657142639,
"start": 1313,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "data] (post-request \"/api/auth/login\" {:username \"user2\" :password \"password1\"} nil)]\n (is (= 401 (:",
"end": 1595,
"score": 0.9970760345458984,
"start": 1590,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "t \"/api/auth/login\" {:username \"user2\" :password \"password1\"} nil)]\n (is (= 401 (:status response)))\n ",
"end": 1617,
"score": 0.9993942379951477,
"start": 1608,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "data] (post-request \"/api/auth/login\" {:username \"user1\" :password \"Password1\"} nil)]\n (is (= 401 (:",
"end": 1836,
"score": 0.9993075728416443,
"start": 1831,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "t \"/api/auth/login\" {:username \"user1\" :password \"Password1\"} nil)]\n (is (= 401 (:status response)))\n ",
"end": 1858,
"score": 0.9993340969085693,
"start": 1849,
"tag": "PASSWORD",
"value": "Password1"
},
{
"context": "tdb/wipe-database! *db*)\n (user/create! \"user1\" \"password1\")\n (testing \"We can validate a token we just cre",
"end": 2045,
"score": 0.9814412593841553,
"start": 2036,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "oken] (post-request \"/api/auth/login\" {:username \"user1\" :password \"password1\"} nil)\n [response ",
"end": 2184,
"score": 0.9985605478286743,
"start": 2179,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "t \"/api/auth/login\" {:username \"user1\" :password \"password1\"} nil)\n [response body] (get-request \"/a",
"end": 2206,
"score": 0.9992870092391968,
"start": 2197,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "nup\n (tdb/wipe-database! *db*)\n (let [username \"newuser\"\n password \"password\"]\n (testing \"Attem",
"end": 3372,
"score": 0.9994451999664307,
"start": 3365,
"tag": "USERNAME",
"value": "newuser"
},
{
"context": "db*)\n (let [username \"newuser\"\n password \"password\"]\n (testing \"Attempting to log in with the cre",
"end": 3400,
"score": 0.9994112253189087,
"start": 3392,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "e data] (post-request \"/api/auth/login\" {:username username :password password} nil)]\n (is (= 401 (:st",
"end": 3566,
"score": 0.9929956197738647,
"start": 3558,
"tag": "USERNAME",
"value": "username"
},
{
"context": " data] (post-request \"/api/auth/signup\" {:username username :password password} nil)]\n (is (= 201 (:st",
"end": 3843,
"score": 0.9925811886787415,
"start": 3835,
"tag": "USERNAME",
"value": "username"
},
{
"context": "e data] (post-request \"/api/auth/login\" {:username username :password password} nil)]\n (is (= 200 (:st",
"end": 4162,
"score": 0.9911876320838928,
"start": 4154,
"tag": "USERNAME",
"value": "username"
},
{
"context": " data] (post-request \"/api/auth/signup\" {:username username :password password} nil)]\n (is (= 409 (:st",
"end": 4450,
"score": 0.982515811920166,
"start": 4442,
"tag": "USERNAME",
"value": "username"
},
{
"context": " data] (post-request \"/api/auth/signup\" {:username username :password \"password2\"} nil)]\n (is (= 409 (",
"end": 4741,
"score": 0.9781540632247925,
"start": 4733,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\"/api/auth/signup\" {:username username :password \"password2\"} nil)]\n (is (= 409 (:status response)))\n ",
"end": 4762,
"score": 0.9992984533309937,
"start": 4753,
"tag": "PASSWORD",
"value": "password2"
},
{
"context": " data] (post-request \"/api/auth/signup\" {:username username :password \"\"} nil)]\n (is (= 409 (:status r",
"end": 5286,
"score": 0.9899160265922546,
"start": 5278,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ata] (post-request \"/api/auth/signup\" {:username \"u1\" :password \"p1\"} nil)]\n (is (= 201 (:statu",
"end": 5567,
"score": 0.9987528324127197,
"start": 5565,
"tag": "USERNAME",
"value": "u1"
},
{
"context": "est \"/api/auth/signup\" {:username \"u1\" :password \"p1\"} nil)]\n (is (= 201 (:status response)))\n ",
"end": 5582,
"score": 0.9993555545806885,
"start": 5580,
"tag": "PASSWORD",
"value": "p1"
}
] |
test/clj/memento/test/routes/api/auth.clj
|
ricardojmendez/memento
| 2 |
(ns memento.test.routes.api.auth
(:require [clojure.test :refer :all]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[numergent.auth :refer [create-auth-token decode-token]] ; Only for validation, all other calls should go through the API
[mount.core :as mount]))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Authentication
;;;
(deftest test-login
(tdb/wipe-database! *db*)
(user/create! "user1" "password1")
(testing "We get a login token when authenticating with a valid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "password1"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "Auth is not case-sensitive on the username"
(let [[response data] (post-request "/api/auth/login" {:username "User1" :password "password1"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "We get a 401 when authenticating with an invalid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user2" :password "password1"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "Auth is case-sensitive on the password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "Password1"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
)
(deftest test-auth-validate
(tdb/wipe-database! *db*)
(user/create! "user1" "password1")
(testing "We can validate a token we just created through login"
(let [[_ token] (post-request "/api/auth/login" {:username "user1" :password "password1"} nil)
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (= token body))))
(testing "We can validate a token we created directly"
(let [token (create-auth-token (:auth-conf env) "user1")
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) body))
(is (= token body))))
(testing "We cannot validate an expired token"
(let [token (create-auth-token (:auth-conf env) "user1" (t/minus (t/now) (t/minutes 1)))
[response _] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 401 (:status response)))))
(testing "We cannot validate a nil token"
(let [[response _] (get-request "/api/auth/validate" nil nil)]
(is (= 401 (:status response)))))
(testing "We cannot validate gibberish"
(let [[response _] (get-request "/api/auth/validate" nil "I'MFORREAL")]
(is (= 401 (:status response)))))
)
(deftest test-signup
(tdb/wipe-database! *db*)
(let [username "newuser"
password "password"]
(testing "Attempting to log in with the credentials initially results on a 401"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "We get a login token when signing up with a valid username/password"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 201 (:status response)))
(is data)
(is (decode-token (:auth-conf env) data))
))
(testing "Attempting to log in with the credentials after creating it results on a token"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) data))))
(testing "Attempting to sign up with the same username/password results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with the same username results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password "password2"} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty username fails"
(let [[response data] (post-request "/api/auth/signup" {:username "" :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty password fails"
(let [[response data] (post-request "/api/auth/signup" {:username username :password ""} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "We get a login token when signing up with a new username/password"
(let [[response data] (post-request "/api/auth/signup" {:username "u1" :password "p1"} nil)]
(is (= 201 (:status response)))
(is (decode-token (:auth-conf env) data))))
))
|
70073
|
(ns memento.test.routes.api.auth
(:require [clojure.test :refer :all]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[numergent.auth :refer [create-auth-token decode-token]] ; Only for validation, all other calls should go through the API
[mount.core :as mount]))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Authentication
;;;
(deftest test-login
(tdb/wipe-database! *db*)
(user/create! "user1" "<PASSWORD>")
(testing "We get a login token when authenticating with a valid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "<PASSWORD>"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "Auth is not case-sensitive on the username"
(let [[response data] (post-request "/api/auth/login" {:username "User1" :password "<PASSWORD>"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "We get a 401 when authenticating with an invalid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user2" :password "<PASSWORD>"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "Auth is case-sensitive on the password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "<PASSWORD>"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
)
(deftest test-auth-validate
(tdb/wipe-database! *db*)
(user/create! "user1" "<PASSWORD>")
(testing "We can validate a token we just created through login"
(let [[_ token] (post-request "/api/auth/login" {:username "user1" :password "<PASSWORD>"} nil)
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (= token body))))
(testing "We can validate a token we created directly"
(let [token (create-auth-token (:auth-conf env) "user1")
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) body))
(is (= token body))))
(testing "We cannot validate an expired token"
(let [token (create-auth-token (:auth-conf env) "user1" (t/minus (t/now) (t/minutes 1)))
[response _] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 401 (:status response)))))
(testing "We cannot validate a nil token"
(let [[response _] (get-request "/api/auth/validate" nil nil)]
(is (= 401 (:status response)))))
(testing "We cannot validate gibberish"
(let [[response _] (get-request "/api/auth/validate" nil "I'MFORREAL")]
(is (= 401 (:status response)))))
)
(deftest test-signup
(tdb/wipe-database! *db*)
(let [username "newuser"
password "<PASSWORD>"]
(testing "Attempting to log in with the credentials initially results on a 401"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "We get a login token when signing up with a valid username/password"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 201 (:status response)))
(is data)
(is (decode-token (:auth-conf env) data))
))
(testing "Attempting to log in with the credentials after creating it results on a token"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) data))))
(testing "Attempting to sign up with the same username/password results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with the same username results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password "<PASSWORD>"} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty username fails"
(let [[response data] (post-request "/api/auth/signup" {:username "" :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty password fails"
(let [[response data] (post-request "/api/auth/signup" {:username username :password ""} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "We get a login token when signing up with a new username/password"
(let [[response data] (post-request "/api/auth/signup" {:username "u1" :password "<PASSWORD>"} nil)]
(is (= 201 (:status response)))
(is (decode-token (:auth-conf env) data))))
))
| true |
(ns memento.test.routes.api.auth
(:require [clojure.test :refer :all]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[numergent.auth :refer [create-auth-token decode-token]] ; Only for validation, all other calls should go through the API
[mount.core :as mount]))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Authentication
;;;
(deftest test-login
(tdb/wipe-database! *db*)
(user/create! "user1" "PI:PASSWORD:<PASSWORD>END_PI")
(testing "We get a login token when authenticating with a valid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "Auth is not case-sensitive on the username"
(let [[response data] (post-request "/api/auth/login" {:username "User1" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 200 (:status response)))
(is (string? data))
(decode-token (:auth-conf env) data)))
(testing "We get a 401 when authenticating with an invalid username/password"
(let [[response data] (post-request "/api/auth/login" {:username "user2" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "Auth is case-sensitive on the password"
(let [[response data] (post-request "/api/auth/login" {:username "user1" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
)
(deftest test-auth-validate
(tdb/wipe-database! *db*)
(user/create! "user1" "PI:PASSWORD:<PASSWORD>END_PI")
(testing "We can validate a token we just created through login"
(let [[_ token] (post-request "/api/auth/login" {:username "user1" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (= token body))))
(testing "We can validate a token we created directly"
(let [token (create-auth-token (:auth-conf env) "user1")
[response body] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) body))
(is (= token body))))
(testing "We cannot validate an expired token"
(let [token (create-auth-token (:auth-conf env) "user1" (t/minus (t/now) (t/minutes 1)))
[response _] (get-request "/api/auth/validate" nil token)]
(is (some? token))
(is (= 401 (:status response)))))
(testing "We cannot validate a nil token"
(let [[response _] (get-request "/api/auth/validate" nil nil)]
(is (= 401 (:status response)))))
(testing "We cannot validate gibberish"
(let [[response _] (get-request "/api/auth/validate" nil "I'MFORREAL")]
(is (= 401 (:status response)))))
)
(deftest test-signup
(tdb/wipe-database! *db*)
(let [username "newuser"
password "PI:PASSWORD:<PASSWORD>END_PI"]
(testing "Attempting to log in with the credentials initially results on a 401"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 401 (:status response)))
(is (= "Authentication error" data))))
(testing "We get a login token when signing up with a valid username/password"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 201 (:status response)))
(is data)
(is (decode-token (:auth-conf env) data))
))
(testing "Attempting to log in with the credentials after creating it results on a token"
(let [[response data] (post-request "/api/auth/login" {:username username :password password} nil)]
(is (= 200 (:status response)))
(is (decode-token (:auth-conf env) data))))
(testing "Attempting to sign up with the same username/password results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with the same username results on an error"
(let [[response data] (post-request "/api/auth/signup" {:username username :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty username fails"
(let [[response data] (post-request "/api/auth/signup" {:username "" :password password} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "Attempting to sign up with empty password fails"
(let [[response data] (post-request "/api/auth/signup" {:username username :password ""} nil)]
(is (= 409 (:status response)))
(is (= "Invalid username/password combination" data))))
(testing "We get a login token when signing up with a new username/password"
(let [[response data] (post-request "/api/auth/signup" {:username "u1" :password "PI:PASSWORD:<PASSWORD>END_PI"} nil)]
(is (= 201 (:status response)))
(is (decode-token (:auth-conf env) data))))
))
|
[
{
"context": " [clojure.pprint :refer [pprint]]))\n\n; NOTE(Richo): Cache to avoid parsing the same file several ti",
"end": 236,
"score": 0.7293053865432739,
"start": 235,
"tag": "NAME",
"value": "o"
}
] |
middleware/server/src/middleware/compiler/linker.clj
|
kristiank/PhysicalBits
| 0 |
(ns middleware.compiler.linker
(:require [middleware.compiler.utils.ast :as ast-utils]
[clojure.java.io :as io]
[middleware.parser.parser :as parser]
[clojure.pprint :refer [pprint]]))
; NOTE(Richo): Cache to avoid parsing the same file several times if it didn't change.
(def parser-cache (atom {}))
(defn parse [file]
(let [path (.getAbsolutePath file)
last-modified (.lastModified file)
entry (get @parser-cache path)]
(if (= last-modified
(get entry :last-modified))
(get entry :content)
(let [content (parser/parse (slurp file))]
(swap! parser-cache assoc path {:last-modified last-modified
:content content})
content))))
(defn bind-primitives [ast]
(let [scripts (set (map :name
(:scripts ast)))
core-primitives (into {} (map (fn [{:keys [name alias]}] [alias name])
(:primitives ast)))]
(ast-utils/transform
ast
; NOTE(Richo): We should only associate a prim name if the selector doesn't match
; an existing script. Scripts have precedence over primitives!
"UziCallNode" (fn [{:keys [selector] :as node} _]
(if (contains? scripts selector)
node
(assoc node
:primitive-name (core-primitives selector)))))))
(defn apply-alias [ast alias]
(if-not alias
ast
(let [with-alias #(str alias "." %)
update (fn [key node _] (assoc node key (-> node key with-alias)))
update-name (partial update :name)
update-selector (partial update :selector)
update-alias (partial update :alias)
update-variable (fn [node path]
(if (ast-utils/local? node path)
node
(update :name node path)))
update-script-list (fn [node _] (assoc node :scripts (mapv with-alias (:scripts node))))]
(ast-utils/transform
ast
"UziVariableDeclarationNode" update-variable
"UziVariableNode" update-variable
"UziTaskNode" update-name
"UziFunctionNode" update-name
"UziProcedureNode" update-name
"UziCallNode" update-selector
"UziScriptStopNode" update-script-list
"UziScriptStartNode" update-script-list
"UziScriptPauseNode" update-script-list
"UziScriptResumeNode" update-script-list
"UziPrimitiveDeclarationNode" update-alias))))
(defn apply-initialization-block [ast {:keys [statements] :as init-block}]
(let [globals (into {}
(map (fn [node] [(-> node :left :name), (-> node :right)])
(filter (fn [node]
(and (= "UziAssignmentNode" (ast-utils/node-type node))
(ast-utils/compile-time-constant? (:right node))))
statements)))
scripts (into {}
(mapcat (fn [{:keys [scripts] :as node}]
(let [state (ast-utils/script-control-state node)]
(map (fn [name] [name state])
scripts)))
(filter ast-utils/script-control?
statements)))]
(assoc ast
:globals (mapv (fn [{:keys [name value] :as global}]
(assoc global :value (get globals name value)))
(:globals ast))
:scripts (mapv (fn [{:keys [name state] :as script}]
(if (= "once" state)
script
(assoc script :state (get scripts name state))))
(:scripts ast)))))
(defn implicit-imports
([] [{:__class__ "UziImportNode" :path "core.uzi"}])
([import]
(filterv #(not= (:path import) (:path %))
(implicit-imports))))
(declare resolve-imports) ; Forward declaration to be able to call it from resolve-import
(defn resolve-import
[{:keys [alias path initializationBlock] :as imp}, libs-dir, visited-imports]
(when (contains? visited-imports {:alias alias :path path})
(throw (ex-info "Dependency cycle detected" {:import imp, :visited visited-imports})))
(let [file (io/file libs-dir path)]
(if (.exists file)
(let [imported-ast (-> (parse file)
ast-utils/assign-internal-ids
(apply-initialization-block initializationBlock)
(resolve-imports libs-dir
(implicit-imports imp)
(conj visited-imports
{:alias alias :path path})))]
{:import (assoc imp
:isResolved true
:program imported-ast)
:program (apply-alias imported-ast alias)})
(throw (ex-info "File not found"
{:import imp
:file file
:absolute-path (.getAbsolutePath file)})))))
(defn build-new-program [ast resolved-imports]
(let [imported-programs (map :program resolved-imports)
imported-globals (mapcat :globals imported-programs)
imported-scripts (mapcat :scripts imported-programs)
imported-prims (mapcat :primitives imported-programs)]
(assoc ast
:imports (mapv :import resolved-imports)
:globals (vec (concat imported-globals (:globals ast)))
:scripts (vec (concat imported-scripts (:scripts ast)))
:primitives (vec (concat imported-prims (:primitives ast))))))
(defn resolve-imports
([ast libs-dir]
(resolve-imports ast libs-dir (implicit-imports) #{}))
([ast libs-dir implicit-imports visited-imports]
(let [resolved-imports (map (fn [imp] (resolve-import imp libs-dir visited-imports))
(concat implicit-imports
(filter (complement :isResolved)
(:imports ast))))]
(-> ast
(build-new-program resolved-imports)
bind-primitives))))
|
24566
|
(ns middleware.compiler.linker
(:require [middleware.compiler.utils.ast :as ast-utils]
[clojure.java.io :as io]
[middleware.parser.parser :as parser]
[clojure.pprint :refer [pprint]]))
; NOTE(Rich<NAME>): Cache to avoid parsing the same file several times if it didn't change.
(def parser-cache (atom {}))
(defn parse [file]
(let [path (.getAbsolutePath file)
last-modified (.lastModified file)
entry (get @parser-cache path)]
(if (= last-modified
(get entry :last-modified))
(get entry :content)
(let [content (parser/parse (slurp file))]
(swap! parser-cache assoc path {:last-modified last-modified
:content content})
content))))
(defn bind-primitives [ast]
(let [scripts (set (map :name
(:scripts ast)))
core-primitives (into {} (map (fn [{:keys [name alias]}] [alias name])
(:primitives ast)))]
(ast-utils/transform
ast
; NOTE(Richo): We should only associate a prim name if the selector doesn't match
; an existing script. Scripts have precedence over primitives!
"UziCallNode" (fn [{:keys [selector] :as node} _]
(if (contains? scripts selector)
node
(assoc node
:primitive-name (core-primitives selector)))))))
(defn apply-alias [ast alias]
(if-not alias
ast
(let [with-alias #(str alias "." %)
update (fn [key node _] (assoc node key (-> node key with-alias)))
update-name (partial update :name)
update-selector (partial update :selector)
update-alias (partial update :alias)
update-variable (fn [node path]
(if (ast-utils/local? node path)
node
(update :name node path)))
update-script-list (fn [node _] (assoc node :scripts (mapv with-alias (:scripts node))))]
(ast-utils/transform
ast
"UziVariableDeclarationNode" update-variable
"UziVariableNode" update-variable
"UziTaskNode" update-name
"UziFunctionNode" update-name
"UziProcedureNode" update-name
"UziCallNode" update-selector
"UziScriptStopNode" update-script-list
"UziScriptStartNode" update-script-list
"UziScriptPauseNode" update-script-list
"UziScriptResumeNode" update-script-list
"UziPrimitiveDeclarationNode" update-alias))))
(defn apply-initialization-block [ast {:keys [statements] :as init-block}]
(let [globals (into {}
(map (fn [node] [(-> node :left :name), (-> node :right)])
(filter (fn [node]
(and (= "UziAssignmentNode" (ast-utils/node-type node))
(ast-utils/compile-time-constant? (:right node))))
statements)))
scripts (into {}
(mapcat (fn [{:keys [scripts] :as node}]
(let [state (ast-utils/script-control-state node)]
(map (fn [name] [name state])
scripts)))
(filter ast-utils/script-control?
statements)))]
(assoc ast
:globals (mapv (fn [{:keys [name value] :as global}]
(assoc global :value (get globals name value)))
(:globals ast))
:scripts (mapv (fn [{:keys [name state] :as script}]
(if (= "once" state)
script
(assoc script :state (get scripts name state))))
(:scripts ast)))))
(defn implicit-imports
([] [{:__class__ "UziImportNode" :path "core.uzi"}])
([import]
(filterv #(not= (:path import) (:path %))
(implicit-imports))))
(declare resolve-imports) ; Forward declaration to be able to call it from resolve-import
(defn resolve-import
[{:keys [alias path initializationBlock] :as imp}, libs-dir, visited-imports]
(when (contains? visited-imports {:alias alias :path path})
(throw (ex-info "Dependency cycle detected" {:import imp, :visited visited-imports})))
(let [file (io/file libs-dir path)]
(if (.exists file)
(let [imported-ast (-> (parse file)
ast-utils/assign-internal-ids
(apply-initialization-block initializationBlock)
(resolve-imports libs-dir
(implicit-imports imp)
(conj visited-imports
{:alias alias :path path})))]
{:import (assoc imp
:isResolved true
:program imported-ast)
:program (apply-alias imported-ast alias)})
(throw (ex-info "File not found"
{:import imp
:file file
:absolute-path (.getAbsolutePath file)})))))
(defn build-new-program [ast resolved-imports]
(let [imported-programs (map :program resolved-imports)
imported-globals (mapcat :globals imported-programs)
imported-scripts (mapcat :scripts imported-programs)
imported-prims (mapcat :primitives imported-programs)]
(assoc ast
:imports (mapv :import resolved-imports)
:globals (vec (concat imported-globals (:globals ast)))
:scripts (vec (concat imported-scripts (:scripts ast)))
:primitives (vec (concat imported-prims (:primitives ast))))))
(defn resolve-imports
([ast libs-dir]
(resolve-imports ast libs-dir (implicit-imports) #{}))
([ast libs-dir implicit-imports visited-imports]
(let [resolved-imports (map (fn [imp] (resolve-import imp libs-dir visited-imports))
(concat implicit-imports
(filter (complement :isResolved)
(:imports ast))))]
(-> ast
(build-new-program resolved-imports)
bind-primitives))))
| true |
(ns middleware.compiler.linker
(:require [middleware.compiler.utils.ast :as ast-utils]
[clojure.java.io :as io]
[middleware.parser.parser :as parser]
[clojure.pprint :refer [pprint]]))
; NOTE(RichPI:NAME:<NAME>END_PI): Cache to avoid parsing the same file several times if it didn't change.
(def parser-cache (atom {}))
(defn parse [file]
(let [path (.getAbsolutePath file)
last-modified (.lastModified file)
entry (get @parser-cache path)]
(if (= last-modified
(get entry :last-modified))
(get entry :content)
(let [content (parser/parse (slurp file))]
(swap! parser-cache assoc path {:last-modified last-modified
:content content})
content))))
(defn bind-primitives [ast]
(let [scripts (set (map :name
(:scripts ast)))
core-primitives (into {} (map (fn [{:keys [name alias]}] [alias name])
(:primitives ast)))]
(ast-utils/transform
ast
; NOTE(Richo): We should only associate a prim name if the selector doesn't match
; an existing script. Scripts have precedence over primitives!
"UziCallNode" (fn [{:keys [selector] :as node} _]
(if (contains? scripts selector)
node
(assoc node
:primitive-name (core-primitives selector)))))))
(defn apply-alias [ast alias]
(if-not alias
ast
(let [with-alias #(str alias "." %)
update (fn [key node _] (assoc node key (-> node key with-alias)))
update-name (partial update :name)
update-selector (partial update :selector)
update-alias (partial update :alias)
update-variable (fn [node path]
(if (ast-utils/local? node path)
node
(update :name node path)))
update-script-list (fn [node _] (assoc node :scripts (mapv with-alias (:scripts node))))]
(ast-utils/transform
ast
"UziVariableDeclarationNode" update-variable
"UziVariableNode" update-variable
"UziTaskNode" update-name
"UziFunctionNode" update-name
"UziProcedureNode" update-name
"UziCallNode" update-selector
"UziScriptStopNode" update-script-list
"UziScriptStartNode" update-script-list
"UziScriptPauseNode" update-script-list
"UziScriptResumeNode" update-script-list
"UziPrimitiveDeclarationNode" update-alias))))
(defn apply-initialization-block [ast {:keys [statements] :as init-block}]
(let [globals (into {}
(map (fn [node] [(-> node :left :name), (-> node :right)])
(filter (fn [node]
(and (= "UziAssignmentNode" (ast-utils/node-type node))
(ast-utils/compile-time-constant? (:right node))))
statements)))
scripts (into {}
(mapcat (fn [{:keys [scripts] :as node}]
(let [state (ast-utils/script-control-state node)]
(map (fn [name] [name state])
scripts)))
(filter ast-utils/script-control?
statements)))]
(assoc ast
:globals (mapv (fn [{:keys [name value] :as global}]
(assoc global :value (get globals name value)))
(:globals ast))
:scripts (mapv (fn [{:keys [name state] :as script}]
(if (= "once" state)
script
(assoc script :state (get scripts name state))))
(:scripts ast)))))
(defn implicit-imports
([] [{:__class__ "UziImportNode" :path "core.uzi"}])
([import]
(filterv #(not= (:path import) (:path %))
(implicit-imports))))
(declare resolve-imports) ; Forward declaration to be able to call it from resolve-import
(defn resolve-import
[{:keys [alias path initializationBlock] :as imp}, libs-dir, visited-imports]
(when (contains? visited-imports {:alias alias :path path})
(throw (ex-info "Dependency cycle detected" {:import imp, :visited visited-imports})))
(let [file (io/file libs-dir path)]
(if (.exists file)
(let [imported-ast (-> (parse file)
ast-utils/assign-internal-ids
(apply-initialization-block initializationBlock)
(resolve-imports libs-dir
(implicit-imports imp)
(conj visited-imports
{:alias alias :path path})))]
{:import (assoc imp
:isResolved true
:program imported-ast)
:program (apply-alias imported-ast alias)})
(throw (ex-info "File not found"
{:import imp
:file file
:absolute-path (.getAbsolutePath file)})))))
(defn build-new-program [ast resolved-imports]
(let [imported-programs (map :program resolved-imports)
imported-globals (mapcat :globals imported-programs)
imported-scripts (mapcat :scripts imported-programs)
imported-prims (mapcat :primitives imported-programs)]
(assoc ast
:imports (mapv :import resolved-imports)
:globals (vec (concat imported-globals (:globals ast)))
:scripts (vec (concat imported-scripts (:scripts ast)))
:primitives (vec (concat imported-prims (:primitives ast))))))
(defn resolve-imports
([ast libs-dir]
(resolve-imports ast libs-dir (implicit-imports) #{}))
([ast libs-dir implicit-imports visited-imports]
(let [resolved-imports (map (fn [imp] (resolve-import imp libs-dir visited-imports))
(concat implicit-imports
(filter (complement :isResolved)
(:imports ast))))]
(-> ast
(build-new-program resolved-imports)
bind-primitives))))
|
[
{
"context": ")\n\n(def vconcat (comp vec concat))\n\n;; copied from Ben Sless - posted in clojurians slack\n#?(:clj (defn compar",
"end": 2716,
"score": 0.9995463490486145,
"start": 2707,
"tag": "NAME",
"value": "Ben Sless"
},
{
"context": "; update to use this setup:\n;; https://github.com/bsless/malli-keys-relations\n;; send PR for cljs support ",
"end": 5248,
"score": 0.9995551109313965,
"start": 5242,
"tag": "USERNAME",
"value": "bsless"
}
] |
src/dev/space/matterandvoid/util.cljc
|
dvingo/malli-code-gen
| 16 |
(ns space.matterandvoid.util
; todo make sure this won't overlap with the util ns from src, maybe name this dev-util?
(:refer-clojure :exclude [uuid])
(:require
[malli.core :as m]
[malli.error :as me]
[malli.registry :as mr]
[space.matterandvoid.data-model.db :as db]
[taoensso.timbre :as log])
;#?(:cljs (:require-macros [space.matterandvoid.util :refer [make-compare-date-fns-js]]))
#?(:clj (:import [java.util UUID])))
#?(:cljs (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (random-uuid))
([s] (cljs.core/uuid s)))
:clj (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (UUID/randomUUID))
([int-or-str]
(if (int? int-or-str)
(UUID/fromString
(format "ffffffff-ffff-ffff-ffff-%012d" int-or-str))
(UUID/fromString int-or-str)))))
;(m/=> uuid
; [:function
; [:=> [:cat] :uuid]
; [:=> [:cat [:or [:string {:max 16}] :int]] :uuid]])
(defn make-compare-date-fn
[cmp fn]
(let [fn-sym (symbol fn)]
(println "fn-sym: " fn-sym)
(println "fn: " fn)
(println "cmp: " cmp)
(println "cmp: " (symbol (str cmp "date")))
`(defn ~(symbol (str cmp "date"))
[a# b#]
(println "Comparing: " a# " with " b#)
(~cmp (~fn-sym a# b#) 0))))
(comment
(>date #inst "2020" #inst "2021") #_false (>date #inst "2021" #inst "2020") #_true
(=date #inst "2020" #inst "2021") #_false (=date #inst "2020" #inst "2020") #_true
(<=date #inst "2020" #inst "2021") #_true (<=date #inst "2020" #inst "2020") #_true
(>=date #inst "2020" #inst "2021") #_false (>=date #inst "2020" #inst "2020") #_true
;(clojure.repl/source >date)
)
(defmacro make-compare-date-fns-java []
(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
`(do ~@(->> fns# (map #(make-compare-date-fn % ".compareTo"))))))
;(defmacro make-compare-date-fns-js []
; `(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
; (do ~@(->> fns# (map #(make-compare-date-fn % "-"))))))
#_#_:cljs
(defmacro make-compare-date-fns []
(let [c #?(:clj ".compareTo" :cljs "-")
fns ['< '> '= '<= '>=]]
`(do ~@(->> fns (map #(make-compare-date-fn % c))))))
;#?(:clj (make-compare-date-fns-java))
(quote .compareTo)
(comment
(macroexpand-1 '(make-compare-date-fn > '.compareTo))
(macroexpand '(make-compare-date-java-fns)))
(comment
(symbol (name '.compareTo))
(ns-unalias *ns* '>date)
(>date #inst "2020" #inst "2021")
(>date #inst "2021" #inst "2020"))
(def vconcat (comp vec concat))
;; copied from Ben Sless - posted in clojurians slack
#?(:clj (defn comparator-relation
[[sym msg]]
;(log/info "sym: " sym)
(let [f (try @(resolve sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
;_ (log/info "after that f: " f)
type (keyword "!" (name sym))]
(when-not f
(let [msg (str "Comparison function not found: '" (pr-str sym) "'")]
(throw (ex-info msg {:sym sym}))))
{type
(m/-simple-schema
(fn [_ [a b]]
(let [fa #(get % a)
fb #(get % b)]
{:type type
:pred (m/-safe-pred #(f (fa %) (fb %))),
:type-properties
{:error/fn
{:en (fn [{:keys [schema value]} _]
(str "value at key " a ", " (fa value)
", should be " msg
" value at key " b ", " (fb value)))}}
:min 2,
:max 2})))})))
(defn comparator-relation2
[[sym msg]]
(log/info "sym: " sym)
`(let [f# (try @(resolve ~sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
_ (log/info "after that f: " f#)
type# (keyword "!" (name ~sym))]
(when-not f#
(let [msg# (str "Comparison function not found: '" (pr-str ~sym) "'")]
(throw (ex-info msg# {:sym ~sym}))))
{type#
(m/-simple-schema
(fn [_ [a# b#]]
(let [fa# #(get % a#)
fb# #(get % b#)]
{:type type
:pred (m/-safe-pred #(f# (fa# %) (fb# %))),
:type-properties
{:error/fn
{:en (fn [{:keys [~'_ value#]} ~'_]
(str
"value at key " a# ", " (fa# value#)
", should be " ~msg
" value at key " b# ", " (fb# value#)))}}
:min 2,
:max 2})))}))
;; needs more work for cljs support - dynamic resolve isn't supported
;; likely easiest to just set it up statically for each comparison function
;; will need to anyway for more involved custom schema
;; then it will work in cljs without needing more macros as well.
;; see: https://cljs.github.io/api/cljs.core/resolve
;; the hard mode is to convert all of this to macros to be consumed from cljs
;; to get a literal symbol in place for cljs resolve
;; or get rid of resolve
;;
;; todo
;; update to use this setup:
;; https://github.com/bsless/malli-keys-relations
;; send PR for cljs support and maybe dates
#?(:clj (defn -comparator-relation-schemas
[]
(into
{}
(map comparator-relation)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]]))))
(defmacro -comparator-relation-schemas2
[]
`(into
{}
(map comparator-relation2)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]])))
;(comment
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x :int]
; [:y :int]]
; [:!/> :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x 1 :y 1}))
;
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x inst?]
; [:y inst?]]
; [:!/>date :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x #inst "2020" :y #inst "2021"})))
(defn get-keyword-schemas [registry]
(->>
registry
mr/schemas
keys
(filter keyword?)
sort
)
#_(sort (filter keyword? (keys (mr/schemas m/default-registry))))
)
(comment
(get-keyword-schemas m/default-registry)
(get-keyword-schemas
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(sort (filter keyword? (keys (mr/schemas m/default-registry))))
(let)
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(comment
[:and
[:map
::id
::description
::comments
[::sub-tasks {:optional true}]
[::db/updated-at {:optional true}]
[::db/created-at {:optional true}]]
[:fn (fn [{::db/keys [created-at updated-at]}]
#?(:clj (<= (.compareTo created-at updated-at) 0)
:cljs (<= created-at updated-at)))]])
|
56743
|
(ns space.matterandvoid.util
; todo make sure this won't overlap with the util ns from src, maybe name this dev-util?
(:refer-clojure :exclude [uuid])
(:require
[malli.core :as m]
[malli.error :as me]
[malli.registry :as mr]
[space.matterandvoid.data-model.db :as db]
[taoensso.timbre :as log])
;#?(:cljs (:require-macros [space.matterandvoid.util :refer [make-compare-date-fns-js]]))
#?(:clj (:import [java.util UUID])))
#?(:cljs (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (random-uuid))
([s] (cljs.core/uuid s)))
:clj (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (UUID/randomUUID))
([int-or-str]
(if (int? int-or-str)
(UUID/fromString
(format "ffffffff-ffff-ffff-ffff-%012d" int-or-str))
(UUID/fromString int-or-str)))))
;(m/=> uuid
; [:function
; [:=> [:cat] :uuid]
; [:=> [:cat [:or [:string {:max 16}] :int]] :uuid]])
(defn make-compare-date-fn
[cmp fn]
(let [fn-sym (symbol fn)]
(println "fn-sym: " fn-sym)
(println "fn: " fn)
(println "cmp: " cmp)
(println "cmp: " (symbol (str cmp "date")))
`(defn ~(symbol (str cmp "date"))
[a# b#]
(println "Comparing: " a# " with " b#)
(~cmp (~fn-sym a# b#) 0))))
(comment
(>date #inst "2020" #inst "2021") #_false (>date #inst "2021" #inst "2020") #_true
(=date #inst "2020" #inst "2021") #_false (=date #inst "2020" #inst "2020") #_true
(<=date #inst "2020" #inst "2021") #_true (<=date #inst "2020" #inst "2020") #_true
(>=date #inst "2020" #inst "2021") #_false (>=date #inst "2020" #inst "2020") #_true
;(clojure.repl/source >date)
)
(defmacro make-compare-date-fns-java []
(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
`(do ~@(->> fns# (map #(make-compare-date-fn % ".compareTo"))))))
;(defmacro make-compare-date-fns-js []
; `(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
; (do ~@(->> fns# (map #(make-compare-date-fn % "-"))))))
#_#_:cljs
(defmacro make-compare-date-fns []
(let [c #?(:clj ".compareTo" :cljs "-")
fns ['< '> '= '<= '>=]]
`(do ~@(->> fns (map #(make-compare-date-fn % c))))))
;#?(:clj (make-compare-date-fns-java))
(quote .compareTo)
(comment
(macroexpand-1 '(make-compare-date-fn > '.compareTo))
(macroexpand '(make-compare-date-java-fns)))
(comment
(symbol (name '.compareTo))
(ns-unalias *ns* '>date)
(>date #inst "2020" #inst "2021")
(>date #inst "2021" #inst "2020"))
(def vconcat (comp vec concat))
;; copied from <NAME> - posted in clojurians slack
#?(:clj (defn comparator-relation
[[sym msg]]
;(log/info "sym: " sym)
(let [f (try @(resolve sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
;_ (log/info "after that f: " f)
type (keyword "!" (name sym))]
(when-not f
(let [msg (str "Comparison function not found: '" (pr-str sym) "'")]
(throw (ex-info msg {:sym sym}))))
{type
(m/-simple-schema
(fn [_ [a b]]
(let [fa #(get % a)
fb #(get % b)]
{:type type
:pred (m/-safe-pred #(f (fa %) (fb %))),
:type-properties
{:error/fn
{:en (fn [{:keys [schema value]} _]
(str "value at key " a ", " (fa value)
", should be " msg
" value at key " b ", " (fb value)))}}
:min 2,
:max 2})))})))
(defn comparator-relation2
[[sym msg]]
(log/info "sym: " sym)
`(let [f# (try @(resolve ~sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
_ (log/info "after that f: " f#)
type# (keyword "!" (name ~sym))]
(when-not f#
(let [msg# (str "Comparison function not found: '" (pr-str ~sym) "'")]
(throw (ex-info msg# {:sym ~sym}))))
{type#
(m/-simple-schema
(fn [_ [a# b#]]
(let [fa# #(get % a#)
fb# #(get % b#)]
{:type type
:pred (m/-safe-pred #(f# (fa# %) (fb# %))),
:type-properties
{:error/fn
{:en (fn [{:keys [~'_ value#]} ~'_]
(str
"value at key " a# ", " (fa# value#)
", should be " ~msg
" value at key " b# ", " (fb# value#)))}}
:min 2,
:max 2})))}))
;; needs more work for cljs support - dynamic resolve isn't supported
;; likely easiest to just set it up statically for each comparison function
;; will need to anyway for more involved custom schema
;; then it will work in cljs without needing more macros as well.
;; see: https://cljs.github.io/api/cljs.core/resolve
;; the hard mode is to convert all of this to macros to be consumed from cljs
;; to get a literal symbol in place for cljs resolve
;; or get rid of resolve
;;
;; todo
;; update to use this setup:
;; https://github.com/bsless/malli-keys-relations
;; send PR for cljs support and maybe dates
#?(:clj (defn -comparator-relation-schemas
[]
(into
{}
(map comparator-relation)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]]))))
(defmacro -comparator-relation-schemas2
[]
`(into
{}
(map comparator-relation2)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]])))
;(comment
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x :int]
; [:y :int]]
; [:!/> :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x 1 :y 1}))
;
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x inst?]
; [:y inst?]]
; [:!/>date :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x #inst "2020" :y #inst "2021"})))
(defn get-keyword-schemas [registry]
(->>
registry
mr/schemas
keys
(filter keyword?)
sort
)
#_(sort (filter keyword? (keys (mr/schemas m/default-registry))))
)
(comment
(get-keyword-schemas m/default-registry)
(get-keyword-schemas
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(sort (filter keyword? (keys (mr/schemas m/default-registry))))
(let)
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(comment
[:and
[:map
::id
::description
::comments
[::sub-tasks {:optional true}]
[::db/updated-at {:optional true}]
[::db/created-at {:optional true}]]
[:fn (fn [{::db/keys [created-at updated-at]}]
#?(:clj (<= (.compareTo created-at updated-at) 0)
:cljs (<= created-at updated-at)))]])
| true |
(ns space.matterandvoid.util
; todo make sure this won't overlap with the util ns from src, maybe name this dev-util?
(:refer-clojure :exclude [uuid])
(:require
[malli.core :as m]
[malli.error :as me]
[malli.registry :as mr]
[space.matterandvoid.data-model.db :as db]
[taoensso.timbre :as log])
;#?(:cljs (:require-macros [space.matterandvoid.util :refer [make-compare-date-fns-js]]))
#?(:clj (:import [java.util UUID])))
#?(:cljs (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (random-uuid))
([s] (cljs.core/uuid s)))
:clj (defn uuid
"Without args gives random UUID.
With args, builds UUID based on input (useful in tests)."
([] (UUID/randomUUID))
([int-or-str]
(if (int? int-or-str)
(UUID/fromString
(format "ffffffff-ffff-ffff-ffff-%012d" int-or-str))
(UUID/fromString int-or-str)))))
;(m/=> uuid
; [:function
; [:=> [:cat] :uuid]
; [:=> [:cat [:or [:string {:max 16}] :int]] :uuid]])
(defn make-compare-date-fn
[cmp fn]
(let [fn-sym (symbol fn)]
(println "fn-sym: " fn-sym)
(println "fn: " fn)
(println "cmp: " cmp)
(println "cmp: " (symbol (str cmp "date")))
`(defn ~(symbol (str cmp "date"))
[a# b#]
(println "Comparing: " a# " with " b#)
(~cmp (~fn-sym a# b#) 0))))
(comment
(>date #inst "2020" #inst "2021") #_false (>date #inst "2021" #inst "2020") #_true
(=date #inst "2020" #inst "2021") #_false (=date #inst "2020" #inst "2020") #_true
(<=date #inst "2020" #inst "2021") #_true (<=date #inst "2020" #inst "2020") #_true
(>=date #inst "2020" #inst "2021") #_false (>=date #inst "2020" #inst "2020") #_true
;(clojure.repl/source >date)
)
(defmacro make-compare-date-fns-java []
(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
`(do ~@(->> fns# (map #(make-compare-date-fn % ".compareTo"))))))
;(defmacro make-compare-date-fns-js []
; `(let [fns# [~'< ~'> ~'= ~'<= ~'>=]]
; (do ~@(->> fns# (map #(make-compare-date-fn % "-"))))))
#_#_:cljs
(defmacro make-compare-date-fns []
(let [c #?(:clj ".compareTo" :cljs "-")
fns ['< '> '= '<= '>=]]
`(do ~@(->> fns (map #(make-compare-date-fn % c))))))
;#?(:clj (make-compare-date-fns-java))
(quote .compareTo)
(comment
(macroexpand-1 '(make-compare-date-fn > '.compareTo))
(macroexpand '(make-compare-date-java-fns)))
(comment
(symbol (name '.compareTo))
(ns-unalias *ns* '>date)
(>date #inst "2020" #inst "2021")
(>date #inst "2021" #inst "2020"))
(def vconcat (comp vec concat))
;; copied from PI:NAME:<NAME>END_PI - posted in clojurians slack
#?(:clj (defn comparator-relation
[[sym msg]]
;(log/info "sym: " sym)
(let [f (try @(resolve sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
;_ (log/info "after that f: " f)
type (keyword "!" (name sym))]
(when-not f
(let [msg (str "Comparison function not found: '" (pr-str sym) "'")]
(throw (ex-info msg {:sym sym}))))
{type
(m/-simple-schema
(fn [_ [a b]]
(let [fa #(get % a)
fb #(get % b)]
{:type type
:pred (m/-safe-pred #(f (fa %) (fb %))),
:type-properties
{:error/fn
{:en (fn [{:keys [schema value]} _]
(str "value at key " a ", " (fa value)
", should be " msg
" value at key " b ", " (fb value)))}}
:min 2,
:max 2})))})))
(defn comparator-relation2
[[sym msg]]
(log/info "sym: " sym)
`(let [f# (try @(resolve ~sym)
(catch #?(:clj NullPointerException :cljs :error) e nil))
_ (log/info "after that f: " f#)
type# (keyword "!" (name ~sym))]
(when-not f#
(let [msg# (str "Comparison function not found: '" (pr-str ~sym) "'")]
(throw (ex-info msg# {:sym ~sym}))))
{type#
(m/-simple-schema
(fn [_ [a# b#]]
(let [fa# #(get % a#)
fb# #(get % b#)]
{:type type
:pred (m/-safe-pred #(f# (fa# %) (fb# %))),
:type-properties
{:error/fn
{:en (fn [{:keys [~'_ value#]} ~'_]
(str
"value at key " a# ", " (fa# value#)
", should be " ~msg
" value at key " b# ", " (fb# value#)))}}
:min 2,
:max 2})))}))
;; needs more work for cljs support - dynamic resolve isn't supported
;; likely easiest to just set it up statically for each comparison function
;; will need to anyway for more involved custom schema
;; then it will work in cljs without needing more macros as well.
;; see: https://cljs.github.io/api/cljs.core/resolve
;; the hard mode is to convert all of this to macros to be consumed from cljs
;; to get a literal symbol in place for cljs resolve
;; or get rid of resolve
;;
;; todo
;; update to use this setup:
;; https://github.com/bsless/malli-keys-relations
;; send PR for cljs support and maybe dates
#?(:clj (defn -comparator-relation-schemas
[]
(into
{}
(map comparator-relation)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]]))))
(defmacro -comparator-relation-schemas2
[]
`(into
{}
(map comparator-relation2)
(vconcat
[['> "greater than"]
['>= "greater than or equal to"]
['= "equal to"]
['== "equal to"]
['<= "lesser than or equal to"]
['< "lesser than"]]
[['>date "greater than"]
['>=date "greater than or equal to"]
['=date "equal to"]
['<=date "lesser than or equal to"]
['<date "lesser than"]])))
;(comment
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x :int]
; [:y :int]]
; [:!/> :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x 1 :y 1}))
;
; (me/humanize
; (m/explain
; (m/schema
; [:and
; [:map
; [:x inst?]
; [:y inst?]]
; [:!/>date :x :y]]
; {:registry
; (mr/composite-registry
; m/default-registry
; (-comparator-relation-schemas))})
; {:x #inst "2020" :y #inst "2021"})))
(defn get-keyword-schemas [registry]
(->>
registry
mr/schemas
keys
(filter keyword?)
sort
)
#_(sort (filter keyword? (keys (mr/schemas m/default-registry))))
)
(comment
(get-keyword-schemas m/default-registry)
(get-keyword-schemas
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(sort (filter keyword? (keys (mr/schemas m/default-registry))))
(let)
(mr/composite-registry
m/default-registry
(-comparator-relation-schemas))
)
(comment
[:and
[:map
::id
::description
::comments
[::sub-tasks {:optional true}]
[::db/updated-at {:optional true}]
[::db/created-at {:optional true}]]
[:fn (fn [{::db/keys [created-at updated-at]}]
#?(:clj (<= (.compareTo created-at updated-at) 0)
:cljs (<= created-at updated-at)))]])
|
[
{
"context": "s state :corp)\n (play-from-hand state :runner \"Djinn\")\n (is (= 3 (:memory (get-runner))))\n (let ",
"end": 6891,
"score": 0.9901599884033203,
"start": 6886,
"tag": "NAME",
"value": "Djinn"
},
{
"context": "s state :corp)\n (play-from-hand state :runner \"Djinn\")\n (core/move state :runner (find-card \"Parasi",
"end": 7593,
"score": 0.9908415675163269,
"start": 7588,
"tag": "NAME",
"value": "Djinn"
},
{
"context": "s state :corp)\n (play-from-hand state :runner \"Datasucker\")\n (play-from-hand state :runner \"Incubator\")\n",
"end": 14597,
"score": 0.9175897240638733,
"start": 14587,
"tag": "NAME",
"value": "Datasucker"
},
{
"context": "s state :corp)\n (play-from-hand state :runner \"Origami\")\n (is (= 6 (core/hand-size state :runner)))\n ",
"end": 19533,
"score": 0.7277816534042358,
"start": 19526,
"tag": "NAME",
"value": "Origami"
},
{
"context": "ate :runner)))\n (play-from-hand state :runner \"Origami\")\n (is (= 9 (core/hand-size state :runner)) \"M",
"end": 19624,
"score": 0.6203356981277466,
"start": 19617,
"tag": "NAME",
"value": "Origami"
},
{
"context": "))))\n\n(deftest sneakdoor-ash\n ;; Sneakdoor Beta - Gabriel Santiago, Ash on HQ should prevent Sneakdoor HQ access but",
"end": 31628,
"score": 0.9998800754547119,
"start": 31612,
"tag": "NAME",
"value": "Gabriel Santiago"
},
{
"context": "qty \"Ash 2X3ZB9CY\" 1)])\n (make-deck \"Gabriel Santiago: Consummate Professional\" [(qty \"Sneakdoor Beta\" ",
"end": 31829,
"score": 0.9997283816337585,
"start": 31813,
"tag": "NAME",
"value": "Gabriel Santiago"
},
{
"context": "ts state :corp)\n (play-from-hand state :runner \"Surfer\")\n (is (= 3 (:credit (get-runner))) \"Paid 2 cre",
"end": 35693,
"score": 0.5284865498542786,
"start": 35687,
"tag": "USERNAME",
"value": "Surfer"
}
] |
src/clj/test/cards/programs.clj
|
erbridge/netrunner
| 0 |
(ns test.cards.programs
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest au-revoir
;; Au Revoir - Gain 1 credit every time you jack out
(do-game
(new-game (default-corp) (default-runner [(qty "Au Revoir" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out")
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir")))
(deftest crescentus
;; Crescentus should only work on rezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 1)])
(default-runner [(qty "Crescentus" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Crescentus")
(run-on state "HQ")
(let [cres (get-in @state [:runner :rig :program 0])
q (get-ice state :hq 0)]
(card-ability state :runner cres 0)
(is (not (nil? (get-in @state [:runner :rig :program 0]))) "Crescentus could not be used because the ICE is not rezzed")
(core/rez state :corp q)
(is (get-in (refresh q) [:rezzed]) "Quandary is now rezzed")
(card-ability state :runner cres 0)
(is (nil? (get-in @state [:runner :rig :program 0])) "Crescentus could be used because the ICE is rezzed")
(is (not (get-in (refresh q) [:rezzed])) "Quandary is no longer rezzed"))))
(deftest datasucker
;; Datasucker - Reduce strength of encountered ICE
(do-game
(new-game (default-corp [(qty "Fire Wall" 1)])
(default-runner [(qty "Datasucker" 1)]))
(play-from-hand state :corp "Fire Wall" "New remote")
(take-credits state :corp)
(core/gain state :runner :click 3)
(play-from-hand state :runner "Datasucker")
(let [ds (get-in @state [:runner :rig :program 0])
fw (get-ice state :remote1 0)]
(run-empty-server state "Archives")
(is (= 1 (get-counters (refresh ds) :virus)))
(run-empty-server state "Archives")
(is (= 2 (get-counters (refresh ds) :virus)))
(run-on state "Server 1")
(run-continue state)
(run-successful state)
(is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server")
(run-on state "Server 1")
(core/rez state :corp fw)
(is (= 5 (:current-strength (refresh fw))))
(card-ability state :runner ds 0)
(is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker")
(is (= 4 (:current-strength (refresh fw))) "Fire Wall strength lowered by 1"))))
(deftest datasucker-trashed
;; Datasucker - does not affect next ice when current is trashed. Issue #1788.
(do-game
(new-game
(default-corp [(qty "Wraparound" 1) (qty "Spiderweb" 1)])
(default-corp [(qty "Datasucker" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Spiderweb" "HQ")
(play-from-hand state :corp "Wraparound" "HQ")
(take-credits state :corp)
(core/gain state :corp :credit 10)
(play-from-hand state :runner "Datasucker")
(let [sucker (get-program state 0)
spider (get-ice state :hq 0)
wrap (get-ice state :hq 1)]
(core/add-counter state :runner sucker :virus 2)
(core/rez state :corp spider)
(core/rez state :corp wrap)
(play-from-hand state :runner "Parasite")
(prompt-select :runner (refresh spider))
(run-on state "HQ")
(run-continue state)
(card-ability state :runner (refresh sucker) 0)
(card-ability state :runner (refresh sucker) 0)
(is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker")
(is (= 7 (:current-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))
(deftest diwan
;; Diwan - Full test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)])
(default-runner [(qty "Diwan" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Diwan")
(prompt-choice :runner "HQ")
(take-credits state :runner)
(is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn")
(play-from-hand state :corp "Ice Wall" "R&D")
(is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server")
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server")
(play-from-hand state :corp "Crisium Grid" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ")
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server")
(core/gain state :corp :click 1)
(core/purge state :corp)
(play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost
(is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge")
(is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged")))
(deftest djinn-host-chakana
;; Djinn - Hosted Chakana does not disable advancing agendas. Issue #750
(do-game
(new-game (default-corp [(qty "Priority Requisition" 1)])
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(play-from-hand state :corp "Priority Requisition" "New remote")
(take-credits state :corp 2)
(play-from-hand state :runner "Djinn")
(let [djinn (get-in @state [:runner :rig :program 0])
agenda (get-content state :remote1 0)]
(is agenda "Agenda was installed")
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(let [chak (first (:hosted (refresh djinn)))]
(is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana")
;; manually add 3 counters
(core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3)
(take-credits state :runner 2)
(core/advance state :corp {:card agenda})
(is (= 1 (:advance-counter (refresh agenda))) "Agenda was advanced")))))
(deftest djinn-host-program
;; Djinn - Host a non-icebreaker program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Djinn")
(is (= 3 (:memory (get-runner))))
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(is (= 3 (:memory (get-runner))) "No memory used to host on Djinn")
(is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana")
(is (= 1 (:credit (get-runner))) "Full cost to host on Djinn"))))
(deftest djinn-tutor-virus
;; Djinn - Tutor a virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Parasite" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Djinn")
(core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck)
(is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck")
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 0)
(prompt-card :runner (find-card "Parasite" (:deck (get-runner))))
(is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand")
(is (= 2 (:credit (get-runner))) "1cr to use Djinn ability")
(is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))
(deftest equivocation
;; Equivocation - interactions with other successful-run events.
(do-game
(new-game
(default-corp [(qty "Restructure" 3) (qty "Hedge Fund" 3)])
(make-deck "Laramy Fisk: Savvy Investor" [(qty "Equivocation" 1) (qty "Desperado" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Equivocation")
(play-from-hand state :runner "Desperado")
(run-empty-server state :rd)
(prompt-choice :runner "Laramy Fisk: Savvy Investor")
(prompt-choice :runner "Yes")
(is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk")
(prompt-choice :runner "Yes") ; Equivocation prompt
(prompt-choice :runner "Yes") ; force the draw
(is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado")
(is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest false-echo
;; False Echo - choice for Corp
(do-game
(new-game (default-corp [(qty "Ice Wall" 3)])
(default-runner [(qty "False Echo" 3)]))
(play-from-hand state :corp "Ice Wall" "Archives")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :corp)
(play-from-hand state :runner "False Echo")
(play-from-hand state :runner "False Echo")
(run-on state "Archives")
(run-continue state)
(let [echo1 (get-program state 0)
echo2 (get-program state 1)]
(card-ability state :runner echo1 0)
(prompt-choice :corp "Add to HQ")
(is (= 2 (count (:hand (get-corp)))) "Ice Wall added to HQ")
(is (= 1 (count (:discard (get-runner)))) "False Echo trashed")
(run-continue state)
(card-ability state :runner echo2 0)
(prompt-choice :corp "Rez")
(is (:rezzed (get-ice state :archives 0)) "Ice Wall rezzed")
(is (= 2 (count (:discard (get-runner)))) "False Echo trashed"))))
(deftest gravedigger
;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp
(do-game
(new-game (default-corp [(qty "Launch Campaign" 2) (qty "Enigma" 2)])
(default-runner [(qty "Gravedigger" 1)]))
(play-from-hand state :corp "Launch Campaign" "New remote")
(play-from-hand state :corp "Launch Campaign" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Gravedigger")
(let [gd (get-in @state [:runner :rig :program 0])]
(core/trash state :corp (get-content state :remote1 0))
(is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/trash state :corp (get-content state :remote2 0))
(is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(is (= 2 (count (:deck (get-corp)))))
(card-ability state :runner gd 0)
(is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger")
(is (= 2 (:click (get-runner))) "Spent 1 click")
(is (= 1 (count (:deck (get-corp)))))
(is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D"))))
(deftest harbinger-blacklist
;; Harbinger - install facedown when Blacklist installed
(do-game
(new-game (default-corp [(qty "Blacklist" 1)])
(default-runner [(qty "Harbinger" 1)]))
(play-from-hand state :corp "Blacklist" "New remote")
(core/rez state :corp (get-content state :remote1 0) )
(take-credits state :corp)
(play-from-hand state :runner "Harbinger")
(core/trash state :runner (-> (get-runner) :rig :program first))
(is (= 0 (count (:discard (get-runner)))) "Harbinger not in heap")
(is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))
(deftest hyperdriver
;; Hyperdriver - Remove from game to gain 3 clicks
(do-game
(new-game (default-corp)
(default-runner [(qty "Hyperdriver" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Hyperdriver")
(is (= 1 (:memory (get-runner))) "3 MU used")
(take-credits state :runner)
(take-credits state :corp)
(is (:runner-phase-12 @state) "Runner in Step 1.2")
(let [hyp (get-in @state [:runner :rig :program 0])]
(card-ability state :runner hyp 0)
(core/end-phase-12 state :runner nil)
(is (= 7 (:click (get-runner))) "Gained 3 clicks")
(is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game"))))
(deftest imp-the-future-perfect
;; Trashing TFP with Imp should not trigger psi-game -- Issue #1844
(do-game
(new-game (default-corp [(qty "The Future Perfect" 1)])
(default-runner [(qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Imp")
(testing "Trash before access click"
(run-empty-server state "HQ")
;; Should access TFP at this point
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no psi-game prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP")
(core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand))
(take-credits state :runner)
(take-credits state :corp)
(testing "Trashing after lose psi game"
(run-empty-server state "HQ")
;; Access prompt for TFP
(prompt-choice :runner "Access")
(prompt-choice :corp "0 [Credit]")
(prompt-choice :runner "1 [Credit]")
;; Fail psi game
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no steal prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP"))))
(deftest incubator-transfer-virus-counters
;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Incubator" 1) (qty "Datasucker" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Datasucker")
(play-from-hand state :runner "Incubator")
(take-credits state :runner)
(take-credits state :corp)
(let [ds (get-in @state [:runner :rig :program 0])
incub (get-in @state [:runner :rig :program 1])]
(is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter")
(take-credits state :runner)
(take-credits state :corp)
(is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters")
(card-ability state :runner incub 0)
(prompt-select :runner ds)
(is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator")
(is (= 1 (count (get-in @state [:runner :rig :program]))))
(is (= 1 (count (:discard (get-runner)))) "Incubator trashed")
(is (= 3 (:click (get-runner)))))))
(deftest ixodidae
;; Ixodidae should not trigger on psi-games
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner [(qty "Ixodidae" 1) (qty "Lamprey" 1)]))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))) "Corp at 7 credits")
(play-from-hand state :runner "Ixodidae")
(play-from-hand state :runner "Lamprey")
(is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey")
(run-on state :hq)
(let [s (get-ice state :hq 0)]
(core/rez state :corp s)
(card-subroutine state :corp s 0)
(is (prompt-is-card? :corp s) "Corp prompt is on Snowflake")
(is (prompt-is-card? :runner s) "Runner prompt is on Snowflake")
(is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake")
(prompt-choice :corp "1")
(prompt-choice :runner "1")
(is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game")
(is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game")
(run-continue state)
(run-successful state)
(is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey")
(is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey"))))
(deftest lamprey
;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge
(do-game
(new-game (default-corp)
(default-runner [(qty "Lamprey" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Lamprey")
(let [lamp (get-in @state [:runner :rig :program 0])]
(run-empty-server state :hq)
(is (= 7 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 6 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 5 (:credit (get-corp))) "Corp lost 1 credit")
(take-credits state :runner)
(core/purge state :corp)
(is (empty? (get-in @state [:runner :rig :program])) "Lamprey trashed by purge"))))
(deftest leprechaun-mu-savings
;; Leprechaun - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Leprechaun" 1) (qty "Hyperdriver" 1) (qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Leprechaun")
(let [lep (get-in @state [:runner :rig :program 0])]
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Hyperdriver" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not deducted from available MU")
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Imp" (:hand (get-runner))))
(is (= 1 (:click (get-runner))))
(is (= 0 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Imp 1 MU not deducted from available MU")
;; Trash Hyperdriver
(core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard)
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not added to available MU")
(core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp
(is (= 3 (:memory (get-runner))) "Imp 1 MU not added to available MU"))))
(deftest magnum-opus-click
;; Magnum Opus - Gain 2 cr
(do-game
(new-game (default-corp)
(default-runner [(qty "Magnum Opus" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Magnum Opus")
(is (= 2 (:memory (get-runner))))
(is (= 0 (:credit (get-runner))))
(let [mopus (get-in @state [:runner :rig :program 0])]
(card-ability state :runner mopus 0)
(is (= 2 (:credit (get-runner))) "Gain 2cr"))))
(deftest origami
;; Origami - Increases Runner max hand size
(do-game
(new-game (default-corp)
(default-runner [(qty "Origami" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "Origami")
(is (= 6 (core/hand-size state :runner)))
(play-from-hand state :runner "Origami")
(is (= 9 (core/hand-size state :runner)) "Max hand size increased by 2 for each copy installed")))
(deftest paintbrush
;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run
(do-game
(new-game (default-corp [(qty "Ice Wall" 1)])
(default-runner [(qty "Paintbrush" 1)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Paintbrush")
(is (= 2 (:memory (get-runner))))
(let [iwall (get-ice state :hq 0)
pb (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged")
(prompt-choice :runner "Done") ; cancel out
(core/rez state :corp iwall)
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(prompt-choice :runner "Code Gate")
(is (= 2 (:click (get-runner))) "Click charged")
(is (= true (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall gained Code Gate")
(run-empty-server state "Archives")
(is (= false (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall lost Code Gate at the end of the run"))))
(deftest parasite-apex
;; Parasite - Installed facedown w/ Apex
(do-game
(new-game (default-corp)
(make-deck "Apex: Invasive Predator" [(qty "Parasite" 1)]))
(take-credits state :corp)
(prompt-select :runner (find-card "Parasite" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "No prompt to host Parasite")
(is (= 1 (count (get-in @state [:runner :rig :facedown]))) "Parasite installed face down")))
(deftest parasite-architect
;; Parasite - Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative
(do-game
(new-game (default-corp [(qty "Architect" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Architect" "HQ")
(let [arch (get-ice state :hq 0)]
(core/rez state :corp arch)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner arch)
(let [psite (first (:hosted (refresh arch)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters")
(is (= -1 (:current-strength (refresh arch))) "Architect at -1 strength")))))
(deftest parasite-builder-moved
;; Parasite - Should stay on hosted card moved by Builder
(do-game
(new-game (default-corp [(qty "Builder" 3) (qty "Ice Wall" 1)])
(default-runner [(qty "Parasite" 3)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Builder" "Archives")
(let [builder (get-ice state :archives 0)
_ (core/rez state :corp builder)
_ (take-credits state :corp)
_ (play-from-hand state :runner "Parasite")
_ (prompt-select :runner builder)
psite (first (:hosted (refresh builder)))
_ (take-credits state :runner)
_ (take-credits state :corp)
_ (is (= 3 (:current-strength (refresh builder))) "Builder reduced to 3 strength")
_ (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
_ (take-credits state :runner)
orig-builder (refresh builder)
_ (card-ability state :corp builder 0)
_ (prompt-choice :corp "HQ")
moved-builder (get-ice state :hq 1)
_ (is (= (:current-strength orig-builder) (:current-strength moved-builder)) "Builder's state is maintained")
orig-psite (dissoc (first (:hosted orig-builder)) :host)
moved-psite (dissoc (first (:hosted moved-builder)) :host)
_ (is (= orig-psite moved-psite) "Hosted Parasite is maintained")
_ (take-credits state :corp)
updated-builder (refresh moved-builder)
updated-psite (first (:hosted updated-builder))
_ (is (= 2 (:current-strength updated-builder)) "Builder strength still reduced")
_ (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented")])))
(deftest parasite-gain-counter
;; Parasite - Gain 1 counter every Runner turn
(do-game
(new-game (default-corp [(qty "Wraparound" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(take-credits state :corp)
(play-from-hand state :runner "Parasite")
(prompt-select :runner wrap)
(is (= 3 (:memory (get-runner))) "Parasite consumes 1 MU")
(let [psite (first (:hosted (refresh wrap)))]
(is (= 0 (get-counters psite :virus)) "Parasite has no counters yet")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (get-counters (refresh psite) :virus))
"Parasite gained 1 virus counter at start of Runner turn")
(is (= 6 (:current-strength (refresh wrap))) "Wraparound reduced to 6 strength")))))
(deftest parasite-hivemind-instant-ice-trash
;; Parasite - Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 1)
(qty "Grimoire" 1)
(qty "Hivemind" 1)
(qty "Sure Gamble" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Sure Gamble")
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Hivemind")
(let [hive (get-in @state [:runner :rig :program 0])]
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly")
(is (= 4 (:memory (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest parasite-ice-trashed
;; Parasite - Trashed along with host ICE when its strength has been reduced to 0
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(let [psite (first (:hosted (refresh enig)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(is (= 1 (:current-strength (refresh enig))) "Enigma reduced to 1 strength")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed")
(is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest progenitor-host-hivemind
;; Progenitor - Hosting Hivemind, using Virus Breeding Ground. Issue #738
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Virus Breeding Ground" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(play-from-hand state :runner "Virus Breeding Ground")
(is (= 4 (:memory (get-runner))))
(let [prog (get-in @state [:runner :rig :program 0])
vbg (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner prog 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 4 (:memory (get-runner))) "No memory used to host on Progenitor")
(let [hive (first (:hosted (refresh prog)))]
(is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor")
(is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter")
(is (= 0 (:credit (get-runner))) "Full cost to host on Progenitor")
(take-credits state :runner 1)
(take-credits state :corp)
(card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind
(prompt-select :runner hive)
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter")
(is (= 0 (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter")))))
(deftest progenitor-mu-savings
;; Progenitor - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(let [pro (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pro 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not deducted from available MU")
;; Trash Hivemind
(core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard)
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not added to available MU"))))
(deftest scheherazade
;; Scheherazade - Gain 1 credit when it hosts a program
(do-game
(new-game (default-corp)
(default-runner [(qty "Scheherazade" 1) (qty "Cache" 1)
(qty "Inti" 1) (qty "Fall Guy" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Scheherazade")
(let [sch (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Inti" (:hand (get-runner))))
(is (= 1 (count (:hosted (refresh sch)))))
(is (= 2 (:click (get-runner))) "Spent 1 click to install and host")
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(is (= 3 (:memory (get-runner))) "Programs hosted on Scheh consume MU")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Cache" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))))
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Fall Guy" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program")
(is (= 1 (count (:hand (get-runner))))))))
(deftest sneakdoor-nerve-agent
;; Sneakdoor Beta - Allow Nerve Agent to gain counters. Issue #1158/#955
(do-game
(new-game (default-corp)
(default-runner [(qty "Sneakdoor Beta" 1) (qty "Nerve Agent" 1)]))
(take-credits state :corp)
(core/gain state :runner :credit 10)
(play-from-hand state :runner "Nerve Agent")
(play-from-hand state :runner "Sneakdoor Beta")
(let [nerve (get-in @state [:runner :rig :program 0])
sb (get-in @state [:runner :rig :program 1])]
(card-ability state :runner sb 0)
(run-successful state)
(is (= 1 (get-counters (refresh nerve) :virus)))
(card-ability state :runner sb 0)
(run-successful state)
(is (= 2 (get-counters (refresh nerve) :virus))))))
(deftest sneakdoor-ash
;; Sneakdoor Beta - Gabriel Santiago, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits.
;; Issue #1138.
(do-game
(new-game (default-corp [(qty "Ash 2X3ZB9CY" 1)])
(make-deck "Gabriel Santiago: Consummate Professional" [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Ash 2X3ZB9CY" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits")
(let [sb (get-in @state [:runner :rig :program 0])
ash (get-content state :hq 0)]
(core/rez state :corp ash)
(card-ability state :runner sb 0)
(run-successful state)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability")
(is (= (:cid ash) (-> (get-runner) :prompt first :card :cid)) "Ash interrupted HQ access after Sneakdoor run")
(is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded"))))
(deftest sneakdoor-crisium
;; Sneakdoor Beta - do not switch to HQ if Archives has Crisium Grid. Issue #1229.
(do-game
(new-game (default-corp [(qty "Crisium Grid" 1) (qty "Priority Requisition" 1) (qty "Private Security Force" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Crisium Grid" "Archives")
(trash-from-hand state :corp "Priority Requisition")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(let [sb (get-program state 0)
cr (get-content state :archives 0)]
(core/rez state :corp cr)
(card-ability state :runner sb 0)
(run-successful state)
(is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ"))))
(deftest sneakdoor-sectest
;; Sneakdoor Beta - Grant Security Testing credits on HQ.
(do-game
(new-game (default-corp)
(default-runner [(qty "Security Testing" 1) (qty "Sneakdoor Beta" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(play-from-hand state :runner "Security Testing")
(take-credits state :runner)
(is (= 3 (:credit (get-runner))))
(take-credits state :corp)
(let [sb (get-in @state [:runner :rig :program 0])]
(prompt-choice :runner "HQ")
(card-ability state :runner sb 0)
(run-successful state)
(is (not (:run @state)) "Switched to HQ and ended the run from Security Testing")
(is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits"))))
(deftest snitch
;; Snitch - Only works on unrezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 2)])
(default-runner [(qty "Snitch" 1)]))
(play-from-hand state :corp "Quandary" "R&D")
(play-from-hand state :corp "Quandary" "HQ")
(let [hqice (get-ice state :hq 0)]
(core/rez state :corp hqice))
(take-credits state :corp)
(play-from-hand state :runner "Snitch")
(let [snitch (get-in @state [:runner :rig :program 0])]
;; unrezzed ice scenario
(run-on state "R&D")
(card-ability state :runner snitch 0)
(is (prompt-is-card? :runner snitch) "Option to jack out")
(prompt-choice :runner "Yes")
;; rezzed ice scenario
(run-on state "HQ")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out")
;; no ice scenario
(run-on state "Archives")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out"))))
(deftest surfer
;; Surfer - Swap position with ice before or after when encountering a barrier ice
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Quandary" 1)])
(default-runner [(qty "Surfer" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Surfer")
(is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer")
(core/rez state :corp (get-ice state :hq 1))
(run-on state "HQ")
(is (= 2 (get-in @state [:run :position])) "Starting run at position 2")
(let [surf (get-in @state [:runner :rig :program 0])]
(card-ability state :runner surf 0)
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer")
(is (= 1 (get-in @state [:run :position])) "Now at next position (1)")
(is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1"))))
|
25926
|
(ns test.cards.programs
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest au-revoir
;; Au Revoir - Gain 1 credit every time you jack out
(do-game
(new-game (default-corp) (default-runner [(qty "Au Revoir" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out")
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir")))
(deftest crescentus
;; Crescentus should only work on rezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 1)])
(default-runner [(qty "Crescentus" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Crescentus")
(run-on state "HQ")
(let [cres (get-in @state [:runner :rig :program 0])
q (get-ice state :hq 0)]
(card-ability state :runner cres 0)
(is (not (nil? (get-in @state [:runner :rig :program 0]))) "Crescentus could not be used because the ICE is not rezzed")
(core/rez state :corp q)
(is (get-in (refresh q) [:rezzed]) "Quandary is now rezzed")
(card-ability state :runner cres 0)
(is (nil? (get-in @state [:runner :rig :program 0])) "Crescentus could be used because the ICE is rezzed")
(is (not (get-in (refresh q) [:rezzed])) "Quandary is no longer rezzed"))))
(deftest datasucker
;; Datasucker - Reduce strength of encountered ICE
(do-game
(new-game (default-corp [(qty "Fire Wall" 1)])
(default-runner [(qty "Datasucker" 1)]))
(play-from-hand state :corp "Fire Wall" "New remote")
(take-credits state :corp)
(core/gain state :runner :click 3)
(play-from-hand state :runner "Datasucker")
(let [ds (get-in @state [:runner :rig :program 0])
fw (get-ice state :remote1 0)]
(run-empty-server state "Archives")
(is (= 1 (get-counters (refresh ds) :virus)))
(run-empty-server state "Archives")
(is (= 2 (get-counters (refresh ds) :virus)))
(run-on state "Server 1")
(run-continue state)
(run-successful state)
(is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server")
(run-on state "Server 1")
(core/rez state :corp fw)
(is (= 5 (:current-strength (refresh fw))))
(card-ability state :runner ds 0)
(is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker")
(is (= 4 (:current-strength (refresh fw))) "Fire Wall strength lowered by 1"))))
(deftest datasucker-trashed
;; Datasucker - does not affect next ice when current is trashed. Issue #1788.
(do-game
(new-game
(default-corp [(qty "Wraparound" 1) (qty "Spiderweb" 1)])
(default-corp [(qty "Datasucker" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Spiderweb" "HQ")
(play-from-hand state :corp "Wraparound" "HQ")
(take-credits state :corp)
(core/gain state :corp :credit 10)
(play-from-hand state :runner "Datasucker")
(let [sucker (get-program state 0)
spider (get-ice state :hq 0)
wrap (get-ice state :hq 1)]
(core/add-counter state :runner sucker :virus 2)
(core/rez state :corp spider)
(core/rez state :corp wrap)
(play-from-hand state :runner "Parasite")
(prompt-select :runner (refresh spider))
(run-on state "HQ")
(run-continue state)
(card-ability state :runner (refresh sucker) 0)
(card-ability state :runner (refresh sucker) 0)
(is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker")
(is (= 7 (:current-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))
(deftest diwan
;; Diwan - Full test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)])
(default-runner [(qty "Diwan" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Diwan")
(prompt-choice :runner "HQ")
(take-credits state :runner)
(is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn")
(play-from-hand state :corp "Ice Wall" "R&D")
(is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server")
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server")
(play-from-hand state :corp "Crisium Grid" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ")
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server")
(core/gain state :corp :click 1)
(core/purge state :corp)
(play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost
(is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge")
(is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged")))
(deftest djinn-host-chakana
;; Djinn - Hosted Chakana does not disable advancing agendas. Issue #750
(do-game
(new-game (default-corp [(qty "Priority Requisition" 1)])
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(play-from-hand state :corp "Priority Requisition" "New remote")
(take-credits state :corp 2)
(play-from-hand state :runner "Djinn")
(let [djinn (get-in @state [:runner :rig :program 0])
agenda (get-content state :remote1 0)]
(is agenda "Agenda was installed")
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(let [chak (first (:hosted (refresh djinn)))]
(is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana")
;; manually add 3 counters
(core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3)
(take-credits state :runner 2)
(core/advance state :corp {:card agenda})
(is (= 1 (:advance-counter (refresh agenda))) "Agenda was advanced")))))
(deftest djinn-host-program
;; Djinn - Host a non-icebreaker program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "<NAME>")
(is (= 3 (:memory (get-runner))))
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(is (= 3 (:memory (get-runner))) "No memory used to host on Djinn")
(is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana")
(is (= 1 (:credit (get-runner))) "Full cost to host on Djinn"))))
(deftest djinn-tutor-virus
;; Djinn - Tutor a virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Parasite" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "<NAME>")
(core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck)
(is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck")
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 0)
(prompt-card :runner (find-card "Parasite" (:deck (get-runner))))
(is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand")
(is (= 2 (:credit (get-runner))) "1cr to use Djinn ability")
(is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))
(deftest equivocation
;; Equivocation - interactions with other successful-run events.
(do-game
(new-game
(default-corp [(qty "Restructure" 3) (qty "Hedge Fund" 3)])
(make-deck "Laramy Fisk: Savvy Investor" [(qty "Equivocation" 1) (qty "Desperado" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Equivocation")
(play-from-hand state :runner "Desperado")
(run-empty-server state :rd)
(prompt-choice :runner "Laramy Fisk: Savvy Investor")
(prompt-choice :runner "Yes")
(is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk")
(prompt-choice :runner "Yes") ; Equivocation prompt
(prompt-choice :runner "Yes") ; force the draw
(is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado")
(is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest false-echo
;; False Echo - choice for Corp
(do-game
(new-game (default-corp [(qty "Ice Wall" 3)])
(default-runner [(qty "False Echo" 3)]))
(play-from-hand state :corp "Ice Wall" "Archives")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :corp)
(play-from-hand state :runner "False Echo")
(play-from-hand state :runner "False Echo")
(run-on state "Archives")
(run-continue state)
(let [echo1 (get-program state 0)
echo2 (get-program state 1)]
(card-ability state :runner echo1 0)
(prompt-choice :corp "Add to HQ")
(is (= 2 (count (:hand (get-corp)))) "Ice Wall added to HQ")
(is (= 1 (count (:discard (get-runner)))) "False Echo trashed")
(run-continue state)
(card-ability state :runner echo2 0)
(prompt-choice :corp "Rez")
(is (:rezzed (get-ice state :archives 0)) "Ice Wall rezzed")
(is (= 2 (count (:discard (get-runner)))) "False Echo trashed"))))
(deftest gravedigger
;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp
(do-game
(new-game (default-corp [(qty "Launch Campaign" 2) (qty "Enigma" 2)])
(default-runner [(qty "Gravedigger" 1)]))
(play-from-hand state :corp "Launch Campaign" "New remote")
(play-from-hand state :corp "Launch Campaign" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Gravedigger")
(let [gd (get-in @state [:runner :rig :program 0])]
(core/trash state :corp (get-content state :remote1 0))
(is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/trash state :corp (get-content state :remote2 0))
(is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(is (= 2 (count (:deck (get-corp)))))
(card-ability state :runner gd 0)
(is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger")
(is (= 2 (:click (get-runner))) "Spent 1 click")
(is (= 1 (count (:deck (get-corp)))))
(is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D"))))
(deftest harbinger-blacklist
;; Harbinger - install facedown when Blacklist installed
(do-game
(new-game (default-corp [(qty "Blacklist" 1)])
(default-runner [(qty "Harbinger" 1)]))
(play-from-hand state :corp "Blacklist" "New remote")
(core/rez state :corp (get-content state :remote1 0) )
(take-credits state :corp)
(play-from-hand state :runner "Harbinger")
(core/trash state :runner (-> (get-runner) :rig :program first))
(is (= 0 (count (:discard (get-runner)))) "Harbinger not in heap")
(is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))
(deftest hyperdriver
;; Hyperdriver - Remove from game to gain 3 clicks
(do-game
(new-game (default-corp)
(default-runner [(qty "Hyperdriver" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Hyperdriver")
(is (= 1 (:memory (get-runner))) "3 MU used")
(take-credits state :runner)
(take-credits state :corp)
(is (:runner-phase-12 @state) "Runner in Step 1.2")
(let [hyp (get-in @state [:runner :rig :program 0])]
(card-ability state :runner hyp 0)
(core/end-phase-12 state :runner nil)
(is (= 7 (:click (get-runner))) "Gained 3 clicks")
(is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game"))))
(deftest imp-the-future-perfect
;; Trashing TFP with Imp should not trigger psi-game -- Issue #1844
(do-game
(new-game (default-corp [(qty "The Future Perfect" 1)])
(default-runner [(qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Imp")
(testing "Trash before access click"
(run-empty-server state "HQ")
;; Should access TFP at this point
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no psi-game prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP")
(core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand))
(take-credits state :runner)
(take-credits state :corp)
(testing "Trashing after lose psi game"
(run-empty-server state "HQ")
;; Access prompt for TFP
(prompt-choice :runner "Access")
(prompt-choice :corp "0 [Credit]")
(prompt-choice :runner "1 [Credit]")
;; Fail psi game
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no steal prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP"))))
(deftest incubator-transfer-virus-counters
;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Incubator" 1) (qty "Datasucker" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "<NAME>")
(play-from-hand state :runner "Incubator")
(take-credits state :runner)
(take-credits state :corp)
(let [ds (get-in @state [:runner :rig :program 0])
incub (get-in @state [:runner :rig :program 1])]
(is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter")
(take-credits state :runner)
(take-credits state :corp)
(is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters")
(card-ability state :runner incub 0)
(prompt-select :runner ds)
(is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator")
(is (= 1 (count (get-in @state [:runner :rig :program]))))
(is (= 1 (count (:discard (get-runner)))) "Incubator trashed")
(is (= 3 (:click (get-runner)))))))
(deftest ixodidae
;; Ixodidae should not trigger on psi-games
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner [(qty "Ixodidae" 1) (qty "Lamprey" 1)]))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))) "Corp at 7 credits")
(play-from-hand state :runner "Ixodidae")
(play-from-hand state :runner "Lamprey")
(is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey")
(run-on state :hq)
(let [s (get-ice state :hq 0)]
(core/rez state :corp s)
(card-subroutine state :corp s 0)
(is (prompt-is-card? :corp s) "Corp prompt is on Snowflake")
(is (prompt-is-card? :runner s) "Runner prompt is on Snowflake")
(is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake")
(prompt-choice :corp "1")
(prompt-choice :runner "1")
(is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game")
(is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game")
(run-continue state)
(run-successful state)
(is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey")
(is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey"))))
(deftest lamprey
;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge
(do-game
(new-game (default-corp)
(default-runner [(qty "Lamprey" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Lamprey")
(let [lamp (get-in @state [:runner :rig :program 0])]
(run-empty-server state :hq)
(is (= 7 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 6 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 5 (:credit (get-corp))) "Corp lost 1 credit")
(take-credits state :runner)
(core/purge state :corp)
(is (empty? (get-in @state [:runner :rig :program])) "Lamprey trashed by purge"))))
(deftest leprechaun-mu-savings
;; Leprechaun - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Leprechaun" 1) (qty "Hyperdriver" 1) (qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Leprechaun")
(let [lep (get-in @state [:runner :rig :program 0])]
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Hyperdriver" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not deducted from available MU")
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Imp" (:hand (get-runner))))
(is (= 1 (:click (get-runner))))
(is (= 0 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Imp 1 MU not deducted from available MU")
;; Trash Hyperdriver
(core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard)
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not added to available MU")
(core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp
(is (= 3 (:memory (get-runner))) "Imp 1 MU not added to available MU"))))
(deftest magnum-opus-click
;; Magnum Opus - Gain 2 cr
(do-game
(new-game (default-corp)
(default-runner [(qty "Magnum Opus" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Magnum Opus")
(is (= 2 (:memory (get-runner))))
(is (= 0 (:credit (get-runner))))
(let [mopus (get-in @state [:runner :rig :program 0])]
(card-ability state :runner mopus 0)
(is (= 2 (:credit (get-runner))) "Gain 2cr"))))
(deftest origami
;; Origami - Increases Runner max hand size
(do-game
(new-game (default-corp)
(default-runner [(qty "Origami" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "<NAME>")
(is (= 6 (core/hand-size state :runner)))
(play-from-hand state :runner "<NAME>")
(is (= 9 (core/hand-size state :runner)) "Max hand size increased by 2 for each copy installed")))
(deftest paintbrush
;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run
(do-game
(new-game (default-corp [(qty "Ice Wall" 1)])
(default-runner [(qty "Paintbrush" 1)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Paintbrush")
(is (= 2 (:memory (get-runner))))
(let [iwall (get-ice state :hq 0)
pb (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged")
(prompt-choice :runner "Done") ; cancel out
(core/rez state :corp iwall)
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(prompt-choice :runner "Code Gate")
(is (= 2 (:click (get-runner))) "Click charged")
(is (= true (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall gained Code Gate")
(run-empty-server state "Archives")
(is (= false (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall lost Code Gate at the end of the run"))))
(deftest parasite-apex
;; Parasite - Installed facedown w/ Apex
(do-game
(new-game (default-corp)
(make-deck "Apex: Invasive Predator" [(qty "Parasite" 1)]))
(take-credits state :corp)
(prompt-select :runner (find-card "Parasite" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "No prompt to host Parasite")
(is (= 1 (count (get-in @state [:runner :rig :facedown]))) "Parasite installed face down")))
(deftest parasite-architect
;; Parasite - Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative
(do-game
(new-game (default-corp [(qty "Architect" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Architect" "HQ")
(let [arch (get-ice state :hq 0)]
(core/rez state :corp arch)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner arch)
(let [psite (first (:hosted (refresh arch)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters")
(is (= -1 (:current-strength (refresh arch))) "Architect at -1 strength")))))
(deftest parasite-builder-moved
;; Parasite - Should stay on hosted card moved by Builder
(do-game
(new-game (default-corp [(qty "Builder" 3) (qty "Ice Wall" 1)])
(default-runner [(qty "Parasite" 3)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Builder" "Archives")
(let [builder (get-ice state :archives 0)
_ (core/rez state :corp builder)
_ (take-credits state :corp)
_ (play-from-hand state :runner "Parasite")
_ (prompt-select :runner builder)
psite (first (:hosted (refresh builder)))
_ (take-credits state :runner)
_ (take-credits state :corp)
_ (is (= 3 (:current-strength (refresh builder))) "Builder reduced to 3 strength")
_ (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
_ (take-credits state :runner)
orig-builder (refresh builder)
_ (card-ability state :corp builder 0)
_ (prompt-choice :corp "HQ")
moved-builder (get-ice state :hq 1)
_ (is (= (:current-strength orig-builder) (:current-strength moved-builder)) "Builder's state is maintained")
orig-psite (dissoc (first (:hosted orig-builder)) :host)
moved-psite (dissoc (first (:hosted moved-builder)) :host)
_ (is (= orig-psite moved-psite) "Hosted Parasite is maintained")
_ (take-credits state :corp)
updated-builder (refresh moved-builder)
updated-psite (first (:hosted updated-builder))
_ (is (= 2 (:current-strength updated-builder)) "Builder strength still reduced")
_ (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented")])))
(deftest parasite-gain-counter
;; Parasite - Gain 1 counter every Runner turn
(do-game
(new-game (default-corp [(qty "Wraparound" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(take-credits state :corp)
(play-from-hand state :runner "Parasite")
(prompt-select :runner wrap)
(is (= 3 (:memory (get-runner))) "Parasite consumes 1 MU")
(let [psite (first (:hosted (refresh wrap)))]
(is (= 0 (get-counters psite :virus)) "Parasite has no counters yet")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (get-counters (refresh psite) :virus))
"Parasite gained 1 virus counter at start of Runner turn")
(is (= 6 (:current-strength (refresh wrap))) "Wraparound reduced to 6 strength")))))
(deftest parasite-hivemind-instant-ice-trash
;; Parasite - Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 1)
(qty "Grimoire" 1)
(qty "Hivemind" 1)
(qty "Sure Gamble" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Sure Gamble")
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Hivemind")
(let [hive (get-in @state [:runner :rig :program 0])]
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly")
(is (= 4 (:memory (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest parasite-ice-trashed
;; Parasite - Trashed along with host ICE when its strength has been reduced to 0
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(let [psite (first (:hosted (refresh enig)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(is (= 1 (:current-strength (refresh enig))) "Enigma reduced to 1 strength")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed")
(is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest progenitor-host-hivemind
;; Progenitor - Hosting Hivemind, using Virus Breeding Ground. Issue #738
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Virus Breeding Ground" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(play-from-hand state :runner "Virus Breeding Ground")
(is (= 4 (:memory (get-runner))))
(let [prog (get-in @state [:runner :rig :program 0])
vbg (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner prog 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 4 (:memory (get-runner))) "No memory used to host on Progenitor")
(let [hive (first (:hosted (refresh prog)))]
(is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor")
(is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter")
(is (= 0 (:credit (get-runner))) "Full cost to host on Progenitor")
(take-credits state :runner 1)
(take-credits state :corp)
(card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind
(prompt-select :runner hive)
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter")
(is (= 0 (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter")))))
(deftest progenitor-mu-savings
;; Progenitor - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(let [pro (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pro 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not deducted from available MU")
;; Trash Hivemind
(core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard)
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not added to available MU"))))
(deftest scheherazade
;; Scheherazade - Gain 1 credit when it hosts a program
(do-game
(new-game (default-corp)
(default-runner [(qty "Scheherazade" 1) (qty "Cache" 1)
(qty "Inti" 1) (qty "Fall Guy" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Scheherazade")
(let [sch (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Inti" (:hand (get-runner))))
(is (= 1 (count (:hosted (refresh sch)))))
(is (= 2 (:click (get-runner))) "Spent 1 click to install and host")
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(is (= 3 (:memory (get-runner))) "Programs hosted on Scheh consume MU")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Cache" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))))
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Fall Guy" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program")
(is (= 1 (count (:hand (get-runner))))))))
(deftest sneakdoor-nerve-agent
;; Sneakdoor Beta - Allow Nerve Agent to gain counters. Issue #1158/#955
(do-game
(new-game (default-corp)
(default-runner [(qty "Sneakdoor Beta" 1) (qty "Nerve Agent" 1)]))
(take-credits state :corp)
(core/gain state :runner :credit 10)
(play-from-hand state :runner "Nerve Agent")
(play-from-hand state :runner "Sneakdoor Beta")
(let [nerve (get-in @state [:runner :rig :program 0])
sb (get-in @state [:runner :rig :program 1])]
(card-ability state :runner sb 0)
(run-successful state)
(is (= 1 (get-counters (refresh nerve) :virus)))
(card-ability state :runner sb 0)
(run-successful state)
(is (= 2 (get-counters (refresh nerve) :virus))))))
(deftest sneakdoor-ash
;; Sneakdoor Beta - <NAME>, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits.
;; Issue #1138.
(do-game
(new-game (default-corp [(qty "Ash 2X3ZB9CY" 1)])
(make-deck "<NAME>: Consummate Professional" [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Ash 2X3ZB9CY" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits")
(let [sb (get-in @state [:runner :rig :program 0])
ash (get-content state :hq 0)]
(core/rez state :corp ash)
(card-ability state :runner sb 0)
(run-successful state)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability")
(is (= (:cid ash) (-> (get-runner) :prompt first :card :cid)) "Ash interrupted HQ access after Sneakdoor run")
(is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded"))))
(deftest sneakdoor-crisium
;; Sneakdoor Beta - do not switch to HQ if Archives has Crisium Grid. Issue #1229.
(do-game
(new-game (default-corp [(qty "Crisium Grid" 1) (qty "Priority Requisition" 1) (qty "Private Security Force" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Crisium Grid" "Archives")
(trash-from-hand state :corp "Priority Requisition")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(let [sb (get-program state 0)
cr (get-content state :archives 0)]
(core/rez state :corp cr)
(card-ability state :runner sb 0)
(run-successful state)
(is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ"))))
(deftest sneakdoor-sectest
;; Sneakdoor Beta - Grant Security Testing credits on HQ.
(do-game
(new-game (default-corp)
(default-runner [(qty "Security Testing" 1) (qty "Sneakdoor Beta" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(play-from-hand state :runner "Security Testing")
(take-credits state :runner)
(is (= 3 (:credit (get-runner))))
(take-credits state :corp)
(let [sb (get-in @state [:runner :rig :program 0])]
(prompt-choice :runner "HQ")
(card-ability state :runner sb 0)
(run-successful state)
(is (not (:run @state)) "Switched to HQ and ended the run from Security Testing")
(is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits"))))
(deftest snitch
;; Snitch - Only works on unrezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 2)])
(default-runner [(qty "Snitch" 1)]))
(play-from-hand state :corp "Quandary" "R&D")
(play-from-hand state :corp "Quandary" "HQ")
(let [hqice (get-ice state :hq 0)]
(core/rez state :corp hqice))
(take-credits state :corp)
(play-from-hand state :runner "Snitch")
(let [snitch (get-in @state [:runner :rig :program 0])]
;; unrezzed ice scenario
(run-on state "R&D")
(card-ability state :runner snitch 0)
(is (prompt-is-card? :runner snitch) "Option to jack out")
(prompt-choice :runner "Yes")
;; rezzed ice scenario
(run-on state "HQ")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out")
;; no ice scenario
(run-on state "Archives")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out"))))
(deftest surfer
;; Surfer - Swap position with ice before or after when encountering a barrier ice
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Quandary" 1)])
(default-runner [(qty "Surfer" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Surfer")
(is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer")
(core/rez state :corp (get-ice state :hq 1))
(run-on state "HQ")
(is (= 2 (get-in @state [:run :position])) "Starting run at position 2")
(let [surf (get-in @state [:runner :rig :program 0])]
(card-ability state :runner surf 0)
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer")
(is (= 1 (get-in @state [:run :position])) "Now at next position (1)")
(is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1"))))
| true |
(ns test.cards.programs
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest au-revoir
;; Au Revoir - Gain 1 credit every time you jack out
(do-game
(new-game (default-corp) (default-runner [(qty "Au Revoir" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 5 (:credit (get-runner))) "Gained 1 credit from jacking out")
(play-from-hand state :runner "Au Revoir")
(run-on state "Archives")
(core/no-action state :corp nil)
(core/jack-out state :runner nil)
(is (= 6 (:credit (get-runner))) "Gained 1 credit from each copy of Au Revoir")))
(deftest crescentus
;; Crescentus should only work on rezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 1)])
(default-runner [(qty "Crescentus" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Crescentus")
(run-on state "HQ")
(let [cres (get-in @state [:runner :rig :program 0])
q (get-ice state :hq 0)]
(card-ability state :runner cres 0)
(is (not (nil? (get-in @state [:runner :rig :program 0]))) "Crescentus could not be used because the ICE is not rezzed")
(core/rez state :corp q)
(is (get-in (refresh q) [:rezzed]) "Quandary is now rezzed")
(card-ability state :runner cres 0)
(is (nil? (get-in @state [:runner :rig :program 0])) "Crescentus could be used because the ICE is rezzed")
(is (not (get-in (refresh q) [:rezzed])) "Quandary is no longer rezzed"))))
(deftest datasucker
;; Datasucker - Reduce strength of encountered ICE
(do-game
(new-game (default-corp [(qty "Fire Wall" 1)])
(default-runner [(qty "Datasucker" 1)]))
(play-from-hand state :corp "Fire Wall" "New remote")
(take-credits state :corp)
(core/gain state :runner :click 3)
(play-from-hand state :runner "Datasucker")
(let [ds (get-in @state [:runner :rig :program 0])
fw (get-ice state :remote1 0)]
(run-empty-server state "Archives")
(is (= 1 (get-counters (refresh ds) :virus)))
(run-empty-server state "Archives")
(is (= 2 (get-counters (refresh ds) :virus)))
(run-on state "Server 1")
(run-continue state)
(run-successful state)
(is (= 2 (get-counters (refresh ds) :virus)) "No counter gained, not a central server")
(run-on state "Server 1")
(core/rez state :corp fw)
(is (= 5 (:current-strength (refresh fw))))
(card-ability state :runner ds 0)
(is (= 1 (get-counters (refresh ds) :virus)) "1 counter spent from Datasucker")
(is (= 4 (:current-strength (refresh fw))) "Fire Wall strength lowered by 1"))))
(deftest datasucker-trashed
;; Datasucker - does not affect next ice when current is trashed. Issue #1788.
(do-game
(new-game
(default-corp [(qty "Wraparound" 1) (qty "Spiderweb" 1)])
(default-corp [(qty "Datasucker" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Spiderweb" "HQ")
(play-from-hand state :corp "Wraparound" "HQ")
(take-credits state :corp)
(core/gain state :corp :credit 10)
(play-from-hand state :runner "Datasucker")
(let [sucker (get-program state 0)
spider (get-ice state :hq 0)
wrap (get-ice state :hq 1)]
(core/add-counter state :runner sucker :virus 2)
(core/rez state :corp spider)
(core/rez state :corp wrap)
(play-from-hand state :runner "Parasite")
(prompt-select :runner (refresh spider))
(run-on state "HQ")
(run-continue state)
(card-ability state :runner (refresh sucker) 0)
(card-ability state :runner (refresh sucker) 0)
(is (find-card "Spiderweb" (:discard (get-corp))) "Spiderweb trashed by Parasite + Datasucker")
(is (= 7 (:current-strength (refresh wrap))) "Wraparound not reduced by Datasucker"))))
(deftest diwan
;; Diwan - Full test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Fire Wall" 3) (qty "Crisium Grid" 2)])
(default-runner [(qty "Diwan" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Diwan")
(prompt-choice :runner "HQ")
(take-credits state :runner)
(is (= 8 (:credit (get-corp))) "8 credits for corp at start of second turn")
(play-from-hand state :corp "Ice Wall" "R&D")
(is (= 8 (:credit (get-corp))) "Diwan did not charge extra for install on another server")
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan charged 1cr to install ice protecting the named server")
(play-from-hand state :corp "Crisium Grid" "HQ")
(is (= 7 (:credit (get-corp))) "Diwan didn't charge to install another upgrade in root of HQ")
(take-credits state :corp)
(take-credits state :runner)
(play-from-hand state :corp "Ice Wall" "HQ")
(is (= 5 (:credit (get-corp))) "Diwan charged 1cr + 1cr to install a second ice protecting the named server")
(core/gain state :corp :click 1)
(core/purge state :corp)
(play-from-hand state :corp "Fire Wall" "HQ") ; 2cr cost from normal install cost
(is (= "Diwan" (-> (get-runner) :discard first :title)) "Diwan was trashed from purge")
(is (= 3 (:credit (get-corp))) "No charge for installs after Diwan purged")))
(deftest djinn-host-chakana
;; Djinn - Hosted Chakana does not disable advancing agendas. Issue #750
(do-game
(new-game (default-corp [(qty "Priority Requisition" 1)])
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(play-from-hand state :corp "Priority Requisition" "New remote")
(take-credits state :corp 2)
(play-from-hand state :runner "Djinn")
(let [djinn (get-in @state [:runner :rig :program 0])
agenda (get-content state :remote1 0)]
(is agenda "Agenda was installed")
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(let [chak (first (:hosted (refresh djinn)))]
(is (= "Chakana" (:title chak)) "Djinn has a hosted Chakana")
;; manually add 3 counters
(core/add-counter state :runner (first (:hosted (refresh djinn))) :virus 3)
(take-credits state :runner 2)
(core/advance state :corp {:card agenda})
(is (= 1 (:advance-counter (refresh agenda))) "Agenda was advanced")))))
(deftest djinn-host-program
;; Djinn - Host a non-icebreaker program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Chakana" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(is (= 3 (:memory (get-runner))))
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 1)
(prompt-select :runner (find-card "Chakana" (:hand (get-runner))))
(is (= 3 (:memory (get-runner))) "No memory used to host on Djinn")
(is (= "Chakana" (:title (first (:hosted (refresh djinn))))) "Djinn has a hosted Chakana")
(is (= 1 (:credit (get-runner))) "Full cost to host on Djinn"))))
(deftest djinn-tutor-virus
;; Djinn - Tutor a virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Djinn" 1) (qty "Parasite" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(core/move state :runner (find-card "Parasite" (:hand (get-runner))) :deck)
(is (zero? (count (:hand (get-runner)))) "No cards in hand after moving Parasite to deck")
(let [djinn (get-in @state [:runner :rig :program 0])]
(card-ability state :runner djinn 0)
(prompt-card :runner (find-card "Parasite" (:deck (get-runner))))
(is (= "Parasite" (:title (first (:hand (get-runner))))) "Djinn moved Parasite to hand")
(is (= 2 (:credit (get-runner))) "1cr to use Djinn ability")
(is (= 2 (:click (get-runner))) "1click to use Djinn ability"))))
(deftest equivocation
;; Equivocation - interactions with other successful-run events.
(do-game
(new-game
(default-corp [(qty "Restructure" 3) (qty "Hedge Fund" 3)])
(make-deck "Laramy Fisk: Savvy Investor" [(qty "Equivocation" 1) (qty "Desperado" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Equivocation")
(play-from-hand state :runner "Desperado")
(run-empty-server state :rd)
(prompt-choice :runner "Laramy Fisk: Savvy Investor")
(prompt-choice :runner "Yes")
(is (= 2 (count (:hand (get-corp)))) "Corp forced to draw by Fisk")
(prompt-choice :runner "Yes") ; Equivocation prompt
(prompt-choice :runner "Yes") ; force the draw
(is (= 1 (:credit (get-runner))) "Runner gained 1cr from Desperado")
(is (= 3 (count (:hand (get-corp)))) "Corp forced to draw by Equivocation")
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest false-echo
;; False Echo - choice for Corp
(do-game
(new-game (default-corp [(qty "Ice Wall" 3)])
(default-runner [(qty "False Echo" 3)]))
(play-from-hand state :corp "Ice Wall" "Archives")
(play-from-hand state :corp "Ice Wall" "Archives")
(take-credits state :corp)
(play-from-hand state :runner "False Echo")
(play-from-hand state :runner "False Echo")
(run-on state "Archives")
(run-continue state)
(let [echo1 (get-program state 0)
echo2 (get-program state 1)]
(card-ability state :runner echo1 0)
(prompt-choice :corp "Add to HQ")
(is (= 2 (count (:hand (get-corp)))) "Ice Wall added to HQ")
(is (= 1 (count (:discard (get-runner)))) "False Echo trashed")
(run-continue state)
(card-ability state :runner echo2 0)
(prompt-choice :corp "Rez")
(is (:rezzed (get-ice state :archives 0)) "Ice Wall rezzed")
(is (= 2 (count (:discard (get-runner)))) "False Echo trashed"))))
(deftest gravedigger
;; Gravedigger - Gain counters when Corp cards are trashed, spend click-counter to mill Corp
(do-game
(new-game (default-corp [(qty "Launch Campaign" 2) (qty "Enigma" 2)])
(default-runner [(qty "Gravedigger" 1)]))
(play-from-hand state :corp "Launch Campaign" "New remote")
(play-from-hand state :corp "Launch Campaign" "New remote")
(take-credits state :corp)
(play-from-hand state :runner "Gravedigger")
(let [gd (get-in @state [:runner :rig :program 0])]
(core/trash state :corp (get-content state :remote1 0))
(is (= 1 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/trash state :corp (get-content state :remote2 0))
(is (= 2 (get-counters (refresh gd) :virus)) "Gravedigger gained 1 counter")
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(core/move state :corp (find-card "Enigma" (:hand (get-corp))) :deck)
(is (= 2 (count (:deck (get-corp)))))
(card-ability state :runner gd 0)
(is (= 1 (get-counters (refresh gd) :virus)) "Spent 1 counter from Gravedigger")
(is (= 2 (:click (get-runner))) "Spent 1 click")
(is (= 1 (count (:deck (get-corp)))))
(is (= 3 (count (:discard (get-corp)))) "Milled 1 card from R&D"))))
(deftest harbinger-blacklist
;; Harbinger - install facedown when Blacklist installed
(do-game
(new-game (default-corp [(qty "Blacklist" 1)])
(default-runner [(qty "Harbinger" 1)]))
(play-from-hand state :corp "Blacklist" "New remote")
(core/rez state :corp (get-content state :remote1 0) )
(take-credits state :corp)
(play-from-hand state :runner "Harbinger")
(core/trash state :runner (-> (get-runner) :rig :program first))
(is (= 0 (count (:discard (get-runner)))) "Harbinger not in heap")
(is (-> (get-runner) :rig :facedown first :facedown) "Harbinger installed facedown")))
(deftest hyperdriver
;; Hyperdriver - Remove from game to gain 3 clicks
(do-game
(new-game (default-corp)
(default-runner [(qty "Hyperdriver" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Hyperdriver")
(is (= 1 (:memory (get-runner))) "3 MU used")
(take-credits state :runner)
(take-credits state :corp)
(is (:runner-phase-12 @state) "Runner in Step 1.2")
(let [hyp (get-in @state [:runner :rig :program 0])]
(card-ability state :runner hyp 0)
(core/end-phase-12 state :runner nil)
(is (= 7 (:click (get-runner))) "Gained 3 clicks")
(is (= 1 (count (:rfg (get-runner)))) "Hyperdriver removed from game"))))
(deftest imp-the-future-perfect
;; Trashing TFP with Imp should not trigger psi-game -- Issue #1844
(do-game
(new-game (default-corp [(qty "The Future Perfect" 1)])
(default-runner [(qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Imp")
(testing "Trash before access click"
(run-empty-server state "HQ")
;; Should access TFP at this point
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no psi-game prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP")
(core/move state :corp (find-card "The Future Perfect" (:discard (get-corp))) :hand))
(take-credits state :runner)
(take-credits state :corp)
(testing "Trashing after lose psi game"
(run-empty-server state "HQ")
;; Access prompt for TFP
(prompt-choice :runner "Access")
(prompt-choice :corp "0 [Credit]")
(prompt-choice :runner "1 [Credit]")
;; Fail psi game
(card-ability state :runner (get-program state 0) 0)
(is (empty? (get-in @state [:runner :prompt])) "Should be no steal prompt for TFP")
(is (= "The Future Perfect" (get-in @state [:corp :discard 0 :title])) "TFP trashed")
(is (= 0 (:agenda-point (get-runner))) "Runner did not steal TFP"))))
(deftest incubator-transfer-virus-counters
;; Incubator - Gain 1 virus counter per turn; trash to move them to an installed virus program
(do-game
(new-game (default-corp)
(default-runner [(qty "Incubator" 1) (qty "Datasucker" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(play-from-hand state :runner "Incubator")
(take-credits state :runner)
(take-credits state :corp)
(let [ds (get-in @state [:runner :rig :program 0])
incub (get-in @state [:runner :rig :program 1])]
(is (= 1 (get-counters (refresh incub) :virus)) "Incubator gained 1 virus counter")
(take-credits state :runner)
(take-credits state :corp)
(is (= 2 (get-counters (refresh incub) :virus)) "Incubator has 2 virus counters")
(card-ability state :runner incub 0)
(prompt-select :runner ds)
(is (= 2 (get-counters (refresh ds) :virus)) "Datasucker has 2 virus counters moved from Incubator")
(is (= 1 (count (get-in @state [:runner :rig :program]))))
(is (= 1 (count (:discard (get-runner)))) "Incubator trashed")
(is (= 3 (:click (get-runner)))))))
(deftest ixodidae
;; Ixodidae should not trigger on psi-games
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner [(qty "Ixodidae" 1) (qty "Lamprey" 1)]))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(is (= 7 (:credit (get-corp))) "Corp at 7 credits")
(play-from-hand state :runner "Ixodidae")
(play-from-hand state :runner "Lamprey")
(is (= 3 (:credit (get-runner))) "Runner paid 3 credits to install Ixodidae and Lamprey")
(run-on state :hq)
(let [s (get-ice state :hq 0)]
(core/rez state :corp s)
(card-subroutine state :corp s 0)
(is (prompt-is-card? :corp s) "Corp prompt is on Snowflake")
(is (prompt-is-card? :runner s) "Runner prompt is on Snowflake")
(is (= 6 (:credit (get-corp))) "Corp paid 1 credit to rezz Snowflake")
(prompt-choice :corp "1")
(prompt-choice :runner "1")
(is (= 5 (:credit (get-corp))) "Corp paid 1 credit to psi game")
(is (= 2 (:credit (get-runner))) "Runner did not gain 1 credit from Ixodidae when corp spent on psi game")
(run-continue state)
(run-successful state)
(is (= 4 (:credit (get-corp))) "Corp lost 1 credit to Lamprey")
(is (= 3 (:credit (get-runner))) "Runner gains 1 credit from Ixodidae due to Lamprey"))))
(deftest lamprey
;; Lamprey - Corp loses 1 credit for each successful HQ run; trashed on purge
(do-game
(new-game (default-corp)
(default-runner [(qty "Lamprey" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Lamprey")
(let [lamp (get-in @state [:runner :rig :program 0])]
(run-empty-server state :hq)
(is (= 7 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 6 (:credit (get-corp))) "Corp lost 1 credit")
(run-empty-server state :hq)
(is (= 5 (:credit (get-corp))) "Corp lost 1 credit")
(take-credits state :runner)
(core/purge state :corp)
(is (empty? (get-in @state [:runner :rig :program])) "Lamprey trashed by purge"))))
(deftest leprechaun-mu-savings
;; Leprechaun - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Leprechaun" 1) (qty "Hyperdriver" 1) (qty "Imp" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Leprechaun")
(let [lep (get-in @state [:runner :rig :program 0])]
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Hyperdriver" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not deducted from available MU")
(card-ability state :runner lep 0)
(prompt-select :runner (find-card "Imp" (:hand (get-runner))))
(is (= 1 (:click (get-runner))))
(is (= 0 (:credit (get-runner))))
(is (= 3 (:memory (get-runner))) "Imp 1 MU not deducted from available MU")
;; Trash Hyperdriver
(core/move state :runner (find-card "Hyperdriver" (:hosted (refresh lep))) :discard)
(is (= 3 (:memory (get-runner))) "Hyperdriver 3 MU not added to available MU")
(core/move state :runner (find-card "Imp" (:hosted (refresh lep))) :discard) ; trash Imp
(is (= 3 (:memory (get-runner))) "Imp 1 MU not added to available MU"))))
(deftest magnum-opus-click
;; Magnum Opus - Gain 2 cr
(do-game
(new-game (default-corp)
(default-runner [(qty "Magnum Opus" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Magnum Opus")
(is (= 2 (:memory (get-runner))))
(is (= 0 (:credit (get-runner))))
(let [mopus (get-in @state [:runner :rig :program 0])]
(card-ability state :runner mopus 0)
(is (= 2 (:credit (get-runner))) "Gain 2cr"))))
(deftest origami
;; Origami - Increases Runner max hand size
(do-game
(new-game (default-corp)
(default-runner [(qty "Origami" 2)]))
(take-credits state :corp)
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(is (= 6 (core/hand-size state :runner)))
(play-from-hand state :runner "PI:NAME:<NAME>END_PI")
(is (= 9 (core/hand-size state :runner)) "Max hand size increased by 2 for each copy installed")))
(deftest paintbrush
;; Paintbrush - Give rezzed ICE a chosen subtype until the end of the next run
(do-game
(new-game (default-corp [(qty "Ice Wall" 1)])
(default-runner [(qty "Paintbrush" 1)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Paintbrush")
(is (= 2 (:memory (get-runner))))
(let [iwall (get-ice state :hq 0)
pb (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(is (= 3 (:click (get-runner))) "Ice Wall not rezzed, so no click charged")
(prompt-choice :runner "Done") ; cancel out
(core/rez state :corp iwall)
(card-ability state :runner pb 0)
(prompt-select :runner iwall)
(prompt-choice :runner "Code Gate")
(is (= 2 (:click (get-runner))) "Click charged")
(is (= true (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall gained Code Gate")
(run-empty-server state "Archives")
(is (= false (has? (refresh iwall) :subtype "Code Gate")) "Ice Wall lost Code Gate at the end of the run"))))
(deftest parasite-apex
;; Parasite - Installed facedown w/ Apex
(do-game
(new-game (default-corp)
(make-deck "Apex: Invasive Predator" [(qty "Parasite" 1)]))
(take-credits state :corp)
(prompt-select :runner (find-card "Parasite" (:hand (get-runner))))
(is (empty? (:prompt (get-runner))) "No prompt to host Parasite")
(is (= 1 (count (get-in @state [:runner :rig :facedown]))) "Parasite installed face down")))
(deftest parasite-architect
;; Parasite - Installed on untrashable Architect should keep gaining counters past 3 and make strength go negative
(do-game
(new-game (default-corp [(qty "Architect" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Architect" "HQ")
(let [arch (get-ice state :hq 0)]
(core/rez state :corp arch)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner arch)
(let [psite (first (:hosted (refresh arch)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(take-credits state :runner)
(take-credits state :corp)
(is (= 4 (get-counters (refresh psite) :virus)) "Parasite has 4 counters")
(is (= -1 (:current-strength (refresh arch))) "Architect at -1 strength")))))
(deftest parasite-builder-moved
;; Parasite - Should stay on hosted card moved by Builder
(do-game
(new-game (default-corp [(qty "Builder" 3) (qty "Ice Wall" 1)])
(default-runner [(qty "Parasite" 3)]))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Builder" "Archives")
(let [builder (get-ice state :archives 0)
_ (core/rez state :corp builder)
_ (take-credits state :corp)
_ (play-from-hand state :runner "Parasite")
_ (prompt-select :runner builder)
psite (first (:hosted (refresh builder)))
_ (take-credits state :runner)
_ (take-credits state :corp)
_ (is (= 3 (:current-strength (refresh builder))) "Builder reduced to 3 strength")
_ (is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
_ (take-credits state :runner)
orig-builder (refresh builder)
_ (card-ability state :corp builder 0)
_ (prompt-choice :corp "HQ")
moved-builder (get-ice state :hq 1)
_ (is (= (:current-strength orig-builder) (:current-strength moved-builder)) "Builder's state is maintained")
orig-psite (dissoc (first (:hosted orig-builder)) :host)
moved-psite (dissoc (first (:hosted moved-builder)) :host)
_ (is (= orig-psite moved-psite) "Hosted Parasite is maintained")
_ (take-credits state :corp)
updated-builder (refresh moved-builder)
updated-psite (first (:hosted updated-builder))
_ (is (= 2 (:current-strength updated-builder)) "Builder strength still reduced")
_ (is (= 2 (get-counters (refresh updated-psite) :virus)) "Parasite counters still incremented")])))
(deftest parasite-gain-counter
;; Parasite - Gain 1 counter every Runner turn
(do-game
(new-game (default-corp [(qty "Wraparound" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(take-credits state :corp)
(play-from-hand state :runner "Parasite")
(prompt-select :runner wrap)
(is (= 3 (:memory (get-runner))) "Parasite consumes 1 MU")
(let [psite (first (:hosted (refresh wrap)))]
(is (= 0 (get-counters psite :virus)) "Parasite has no counters yet")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (get-counters (refresh psite) :virus))
"Parasite gained 1 virus counter at start of Runner turn")
(is (= 6 (:current-strength (refresh wrap))) "Wraparound reduced to 6 strength")))))
(deftest parasite-hivemind-instant-ice-trash
;; Parasite - Use Hivemind counters when installed; instantly trash ICE if counters >= ICE strength
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 1)
(qty "Grimoire" 1)
(qty "Hivemind" 1)
(qty "Sure Gamble" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Sure Gamble")
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Hivemind")
(let [hive (get-in @state [:runner :rig :program 0])]
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind has 2 counters")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed instantly")
(is (= 4 (:memory (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest parasite-ice-trashed
;; Parasite - Trashed along with host ICE when its strength has been reduced to 0
(do-game
(new-game (default-corp [(qty "Enigma" 3) (qty "Hedge Fund" 3)])
(default-runner [(qty "Parasite" 3) (qty "Grimoire" 1)]))
(play-from-hand state :corp "Enigma" "HQ")
(let [enig (get-ice state :hq 0)]
(core/rez state :corp enig)
(take-credits state :corp)
(play-from-hand state :runner "Grimoire")
(play-from-hand state :runner "Parasite")
(prompt-select :runner enig)
(let [psite (first (:hosted (refresh enig)))]
(is (= 1 (get-counters (refresh psite) :virus)) "Parasite has 1 counter")
(is (= 1 (:current-strength (refresh enig))) "Enigma reduced to 1 strength")
(take-credits state :runner)
(take-credits state :corp)
(is (= 1 (count (:discard (get-corp)))) "Enigma trashed")
(is (= 1 (count (:discard (get-runner)))) "Parasite trashed when Enigma was trashed")))))
(deftest progenitor-host-hivemind
;; Progenitor - Hosting Hivemind, using Virus Breeding Ground. Issue #738
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Virus Breeding Ground" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(play-from-hand state :runner "Virus Breeding Ground")
(is (= 4 (:memory (get-runner))))
(let [prog (get-in @state [:runner :rig :program 0])
vbg (get-in @state [:runner :rig :resource 0])]
(card-ability state :runner prog 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 4 (:memory (get-runner))) "No memory used to host on Progenitor")
(let [hive (first (:hosted (refresh prog)))]
(is (= "Hivemind" (:title hive)) "Hivemind is hosted on Progenitor")
(is (= 1 (get-counters hive :virus)) "Hivemind has 1 counter")
(is (= 0 (:credit (get-runner))) "Full cost to host on Progenitor")
(take-credits state :runner 1)
(take-credits state :corp)
(card-ability state :runner vbg 0) ; use VBG to transfer 1 token to Hivemind
(prompt-select :runner hive)
(is (= 2 (get-counters (refresh hive) :virus)) "Hivemind gained 1 counter")
(is (= 0 (get-counters (refresh vbg) :virus)) "Virus Breeding Ground lost 1 counter")))))
(deftest progenitor-mu-savings
;; Progenitor - Keep MU the same when hosting or trashing hosted programs
(do-game
(new-game (default-corp)
(default-runner [(qty "Progenitor" 1) (qty "Hivemind" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Progenitor")
(let [pro (get-in @state [:runner :rig :program 0])]
(card-ability state :runner pro 0)
(prompt-select :runner (find-card "Hivemind" (:hand (get-runner))))
(is (= 2 (:click (get-runner))))
(is (= 2 (:credit (get-runner))))
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not deducted from available MU")
;; Trash Hivemind
(core/move state :runner (find-card "Hivemind" (:hosted (refresh pro))) :discard)
(is (= 4 (:memory (get-runner))) "Hivemind 2 MU not added to available MU"))))
(deftest scheherazade
;; Scheherazade - Gain 1 credit when it hosts a program
(do-game
(new-game (default-corp)
(default-runner [(qty "Scheherazade" 1) (qty "Cache" 1)
(qty "Inti" 1) (qty "Fall Guy" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Scheherazade")
(let [sch (get-in @state [:runner :rig :program 0])]
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Inti" (:hand (get-runner))))
(is (= 1 (count (:hosted (refresh sch)))))
(is (= 2 (:click (get-runner))) "Spent 1 click to install and host")
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(is (= 3 (:memory (get-runner))) "Programs hosted on Scheh consume MU")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Cache" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))))
(is (= 6 (:credit (get-runner))) "Gained 1 credit")
(card-ability state :runner sch 0)
(prompt-select :runner (find-card "Fall Guy" (:hand (get-runner))))
(is (= 2 (count (:hosted (refresh sch)))) "Can't host non-program")
(is (= 1 (count (:hand (get-runner))))))))
(deftest sneakdoor-nerve-agent
;; Sneakdoor Beta - Allow Nerve Agent to gain counters. Issue #1158/#955
(do-game
(new-game (default-corp)
(default-runner [(qty "Sneakdoor Beta" 1) (qty "Nerve Agent" 1)]))
(take-credits state :corp)
(core/gain state :runner :credit 10)
(play-from-hand state :runner "Nerve Agent")
(play-from-hand state :runner "Sneakdoor Beta")
(let [nerve (get-in @state [:runner :rig :program 0])
sb (get-in @state [:runner :rig :program 1])]
(card-ability state :runner sb 0)
(run-successful state)
(is (= 1 (get-counters (refresh nerve) :virus)))
(card-ability state :runner sb 0)
(run-successful state)
(is (= 2 (get-counters (refresh nerve) :virus))))))
(deftest sneakdoor-ash
;; Sneakdoor Beta - PI:NAME:<NAME>END_PI, Ash on HQ should prevent Sneakdoor HQ access but still give Gabe credits.
;; Issue #1138.
(do-game
(new-game (default-corp [(qty "Ash 2X3ZB9CY" 1)])
(make-deck "PI:NAME:<NAME>END_PI: Consummate Professional" [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Ash 2X3ZB9CY" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(is (= 1 (:credit (get-runner))) "Sneakdoor cost 4 credits")
(let [sb (get-in @state [:runner :rig :program 0])
ash (get-content state :hq 0)]
(core/rez state :corp ash)
(card-ability state :runner sb 0)
(run-successful state)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 3 (:credit (get-runner))) "Gained 2 credits from Gabe's ability")
(is (= (:cid ash) (-> (get-runner) :prompt first :card :cid)) "Ash interrupted HQ access after Sneakdoor run")
(is (= :hq (-> (get-runner) :register :successful-run first)) "Successful Run on HQ recorded"))))
(deftest sneakdoor-crisium
;; Sneakdoor Beta - do not switch to HQ if Archives has Crisium Grid. Issue #1229.
(do-game
(new-game (default-corp [(qty "Crisium Grid" 1) (qty "Priority Requisition" 1) (qty "Private Security Force" 1)])
(default-runner [(qty "Sneakdoor Beta" 1)]))
(play-from-hand state :corp "Crisium Grid" "Archives")
(trash-from-hand state :corp "Priority Requisition")
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(let [sb (get-program state 0)
cr (get-content state :archives 0)]
(core/rez state :corp cr)
(card-ability state :runner sb 0)
(run-successful state)
(is (= :archives (get-in @state [:run :server 0])) "Crisium Grid stopped Sneakdoor Beta from switching to HQ"))))
(deftest sneakdoor-sectest
;; Sneakdoor Beta - Grant Security Testing credits on HQ.
(do-game
(new-game (default-corp)
(default-runner [(qty "Security Testing" 1) (qty "Sneakdoor Beta" 1)]))
(take-credits state :corp)
(play-from-hand state :runner "Sneakdoor Beta")
(play-from-hand state :runner "Security Testing")
(take-credits state :runner)
(is (= 3 (:credit (get-runner))))
(take-credits state :corp)
(let [sb (get-in @state [:runner :rig :program 0])]
(prompt-choice :runner "HQ")
(card-ability state :runner sb 0)
(run-successful state)
(is (not (:run @state)) "Switched to HQ and ended the run from Security Testing")
(is (= 5 (:credit (get-runner))) "Sneakdoor switched to HQ and earned Security Testing credits"))))
(deftest snitch
;; Snitch - Only works on unrezzed ice
(do-game
(new-game (default-corp [(qty "Quandary" 2)])
(default-runner [(qty "Snitch" 1)]))
(play-from-hand state :corp "Quandary" "R&D")
(play-from-hand state :corp "Quandary" "HQ")
(let [hqice (get-ice state :hq 0)]
(core/rez state :corp hqice))
(take-credits state :corp)
(play-from-hand state :runner "Snitch")
(let [snitch (get-in @state [:runner :rig :program 0])]
;; unrezzed ice scenario
(run-on state "R&D")
(card-ability state :runner snitch 0)
(is (prompt-is-card? :runner snitch) "Option to jack out")
(prompt-choice :runner "Yes")
;; rezzed ice scenario
(run-on state "HQ")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out")
;; no ice scenario
(run-on state "Archives")
(card-ability state :runner snitch 0)
(is (empty? (get-in @state [:runner :prompt])) "No option to jack out"))))
(deftest surfer
;; Surfer - Swap position with ice before or after when encountering a barrier ice
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Quandary" 1)])
(default-runner [(qty "Surfer" 1)]))
(play-from-hand state :corp "Quandary" "HQ")
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Surfer")
(is (= 3 (:credit (get-runner))) "Paid 2 credits to install Surfer")
(core/rez state :corp (get-ice state :hq 1))
(run-on state "HQ")
(is (= 2 (get-in @state [:run :position])) "Starting run at position 2")
(let [surf (get-in @state [:runner :rig :program 0])]
(card-ability state :runner surf 0)
(prompt-select :runner (get-ice state :hq 0))
(is (= 1 (:credit (get-runner))) "Paid 2 credits to use Surfer")
(is (= 1 (get-in @state [:run :position])) "Now at next position (1)")
(is (= "Ice Wall" (:title (get-ice state :hq 0))) "Ice Wall now at position 1"))))
|
[
{
"context": "ls.cli/parse-opts\n args [[\"-u\" \"--username USERNAME\" \"Hive username - required\"\n :miss",
"end": 2353,
"score": 0.9291775226593018,
"start": 2345,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "ername missing.\"]\n [\"-p\" \"--password PASSWORD\" \"Hive password - required\"\n :miss",
"end": 2469,
"score": 0.9970362782478333,
"start": 2461,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] |
hive.clj
|
philjackson/hive.bb
| 0 |
#!/usr/bin/env bb
(require '[babashka.curl :as curl]
'[clojure.pprint :refer [pprint]])
(import 'java.time.format.DateTimeFormatter
'java.time.ZonedDateTime)
(def beekeeper-base "https://beekeeper.hivehome.com")
(defn extract-config [data]
(select-keys data [:token :accessToken :refreshToken]))
;; location of the configuration file
(def config-filename (str (or (System/getenv "XDG_CONFIG_HOME")
(str (System/getenv "HOME") "/.config"))
"/hive.edn"))
(defn now-gmt []
(.format
(ZonedDateTime/now)
(DateTimeFormatter/ofPattern "EEE, dd MMM yyyy HH:mm:ss z")))
(defn write-config [config]
(spit config-filename (pr-str config))
config)
(declare hive-post)
(defn hive-refresh-token [config]
(hive-post config
(str beekeeper-base "/1.0/cognito/refresh-token")
{:body (json/generate-string config)}))
(defn hive-call [method config url options]
(let [res (method url (merge options {:throw false
:headers (cond-> {"Content-Type" "application/json"
"Accept" "application/json"
"Date" (now-gmt)}
(:auth? options)
(assoc "authorization" (:token config)))}))
status (:status res)
body (json/parse-string (:body res) keyword)]
(cond
;; we need to refresh the auth token
(and (= body {:error "NOT_AUTHORIZED"})
(not (:no-refresh? options)))
(do
(-> (hive-refresh-token config)
extract-config
write-config)
;; make the call again
(hive-call method config url (assoc options :no-refresh? true)))
(and (>= status 200) (< status 300))
body
:else
(do
body
(System/exit 1)))))
(def hive-get (partial hive-call curl/get))
(def hive-post (partial hive-call curl/post))
(defn product-url [product]
(str beekeeper-base
"/1.0/nodes/"
(:type product)
"/"
(:id product)))
(defn authenticate [config args]
(let [{:keys [options summary errors]}
(tools.cli/parse-opts
args [["-u" "--username USERNAME" "Hive username - required"
:missing "Username missing."]
["-p" "--password PASSWORD" "Hive password - required"
:missing "Password missing."]])]
(if (not (seq errors))
(do
(-> (hive-post config
(str beekeeper-base "/1.0/cognito/login")
{:body (json/generate-string (select-keys options [:username :password]))})
extract-config
write-config)
(println "That's you authenticated. Good on you."))
(do
(doall (map println errors))
(println summary)
(System/exit 1)))))
(defn products [config _]
(->> (hive-get config
(str beekeeper-base "/1.0/auth/admin-login")
{:auth? false
:body (json/generate-string {:token (:token config)
:products true})})
:products
(group-by #(get-in % [:state :name]))
(map (fn [[k [v]]] [k v]))
(into {})))
(defn lamp-brightness [config [amount]]
(let [amount (edn/read-string amount)
prods (products config [])
lamp (get prods "study lamp")
brightness (get-in lamp [:state :brightness])]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string {:brightness (+ brightness amount)})})))
(defn set-lamp-status [config status]
(let [prods (products config [])
lamp (get prods "study lamp")]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string (if status
{:status "ON"}
{:status "OFF"}))})))
(defn lamp-toggle [config args]
(let [prods (products config [])
lamp (get prods "study lamp")
status (get-in lamp [:state :status])]
(set-lamp-status config (not= status "ON"))))
(defn heating-waybar [config args]
(let [prods (products config [])
heating (get prods "heating")
heating-on? (:working (:props heating))]
(-> {:text (str (:temperature (:props heating))
"°C / "
(:target (:state heating))
"°C")
:class (if heating-on?
"heating-on"
"heating-off")}
json/generate-string
println)))
(defn lamp-waybar [config args]
(let [prods (products config [])
lamp (:state (get prods "study lamp"))
lamp-on? (boolean (= (:status lamp) "ON"))]
(-> {:percentage (:brightness lamp)
:tooltip (str "Hue: " (:hue lamp) "\n"
"Saturation: " (:saturation lamp) "\n"
"Colour mode: " (:colourMode lamp) "\n"
"Colour temp: " (:colourTemperature lamp))
:class (if lamp-on?
"lamp-on"
"lamp-off")}
json/generate-string
println)))
(def cli-options
[["-v" nil "Verbosity level" :default 0 :update-fn inc]])
#_(def *command-line-args* ["heating-waybar"])
(let [options (tools.cli/parse-opts *command-line-args* cli-options :in-order true)
config (if (.exists (io/file config-filename))
(edn/read-string (slurp config-filename))
{})]
(case (first (:arguments options))
"authenticate" (authenticate config (rest (:arguments options)))
"products" (products config (rest (:arguments options)))
"heating-waybar" (heating-waybar config (rest (:arguments options)))
"lamp-waybar" (lamp-waybar config (rest (:arguments options)))
"lamp-toggle" (lamp-toggle config (rest (:arguments options)))
"lamp-on" (set-lamp-status config true)
"lamp-off" (set-lamp-status config false)
"lamp-brightness" (lamp-brightness config (rest (:arguments options)))))
|
17471
|
#!/usr/bin/env bb
(require '[babashka.curl :as curl]
'[clojure.pprint :refer [pprint]])
(import 'java.time.format.DateTimeFormatter
'java.time.ZonedDateTime)
(def beekeeper-base "https://beekeeper.hivehome.com")
(defn extract-config [data]
(select-keys data [:token :accessToken :refreshToken]))
;; location of the configuration file
(def config-filename (str (or (System/getenv "XDG_CONFIG_HOME")
(str (System/getenv "HOME") "/.config"))
"/hive.edn"))
(defn now-gmt []
(.format
(ZonedDateTime/now)
(DateTimeFormatter/ofPattern "EEE, dd MMM yyyy HH:mm:ss z")))
(defn write-config [config]
(spit config-filename (pr-str config))
config)
(declare hive-post)
(defn hive-refresh-token [config]
(hive-post config
(str beekeeper-base "/1.0/cognito/refresh-token")
{:body (json/generate-string config)}))
(defn hive-call [method config url options]
(let [res (method url (merge options {:throw false
:headers (cond-> {"Content-Type" "application/json"
"Accept" "application/json"
"Date" (now-gmt)}
(:auth? options)
(assoc "authorization" (:token config)))}))
status (:status res)
body (json/parse-string (:body res) keyword)]
(cond
;; we need to refresh the auth token
(and (= body {:error "NOT_AUTHORIZED"})
(not (:no-refresh? options)))
(do
(-> (hive-refresh-token config)
extract-config
write-config)
;; make the call again
(hive-call method config url (assoc options :no-refresh? true)))
(and (>= status 200) (< status 300))
body
:else
(do
body
(System/exit 1)))))
(def hive-get (partial hive-call curl/get))
(def hive-post (partial hive-call curl/post))
(defn product-url [product]
(str beekeeper-base
"/1.0/nodes/"
(:type product)
"/"
(:id product)))
(defn authenticate [config args]
(let [{:keys [options summary errors]}
(tools.cli/parse-opts
args [["-u" "--username USERNAME" "Hive username - required"
:missing "Username missing."]
["-p" "--password <PASSWORD>" "Hive password - required"
:missing "Password missing."]])]
(if (not (seq errors))
(do
(-> (hive-post config
(str beekeeper-base "/1.0/cognito/login")
{:body (json/generate-string (select-keys options [:username :password]))})
extract-config
write-config)
(println "That's you authenticated. Good on you."))
(do
(doall (map println errors))
(println summary)
(System/exit 1)))))
(defn products [config _]
(->> (hive-get config
(str beekeeper-base "/1.0/auth/admin-login")
{:auth? false
:body (json/generate-string {:token (:token config)
:products true})})
:products
(group-by #(get-in % [:state :name]))
(map (fn [[k [v]]] [k v]))
(into {})))
(defn lamp-brightness [config [amount]]
(let [amount (edn/read-string amount)
prods (products config [])
lamp (get prods "study lamp")
brightness (get-in lamp [:state :brightness])]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string {:brightness (+ brightness amount)})})))
(defn set-lamp-status [config status]
(let [prods (products config [])
lamp (get prods "study lamp")]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string (if status
{:status "ON"}
{:status "OFF"}))})))
(defn lamp-toggle [config args]
(let [prods (products config [])
lamp (get prods "study lamp")
status (get-in lamp [:state :status])]
(set-lamp-status config (not= status "ON"))))
(defn heating-waybar [config args]
(let [prods (products config [])
heating (get prods "heating")
heating-on? (:working (:props heating))]
(-> {:text (str (:temperature (:props heating))
"°C / "
(:target (:state heating))
"°C")
:class (if heating-on?
"heating-on"
"heating-off")}
json/generate-string
println)))
(defn lamp-waybar [config args]
(let [prods (products config [])
lamp (:state (get prods "study lamp"))
lamp-on? (boolean (= (:status lamp) "ON"))]
(-> {:percentage (:brightness lamp)
:tooltip (str "Hue: " (:hue lamp) "\n"
"Saturation: " (:saturation lamp) "\n"
"Colour mode: " (:colourMode lamp) "\n"
"Colour temp: " (:colourTemperature lamp))
:class (if lamp-on?
"lamp-on"
"lamp-off")}
json/generate-string
println)))
(def cli-options
[["-v" nil "Verbosity level" :default 0 :update-fn inc]])
#_(def *command-line-args* ["heating-waybar"])
(let [options (tools.cli/parse-opts *command-line-args* cli-options :in-order true)
config (if (.exists (io/file config-filename))
(edn/read-string (slurp config-filename))
{})]
(case (first (:arguments options))
"authenticate" (authenticate config (rest (:arguments options)))
"products" (products config (rest (:arguments options)))
"heating-waybar" (heating-waybar config (rest (:arguments options)))
"lamp-waybar" (lamp-waybar config (rest (:arguments options)))
"lamp-toggle" (lamp-toggle config (rest (:arguments options)))
"lamp-on" (set-lamp-status config true)
"lamp-off" (set-lamp-status config false)
"lamp-brightness" (lamp-brightness config (rest (:arguments options)))))
| true |
#!/usr/bin/env bb
(require '[babashka.curl :as curl]
'[clojure.pprint :refer [pprint]])
(import 'java.time.format.DateTimeFormatter
'java.time.ZonedDateTime)
(def beekeeper-base "https://beekeeper.hivehome.com")
(defn extract-config [data]
(select-keys data [:token :accessToken :refreshToken]))
;; location of the configuration file
(def config-filename (str (or (System/getenv "XDG_CONFIG_HOME")
(str (System/getenv "HOME") "/.config"))
"/hive.edn"))
(defn now-gmt []
(.format
(ZonedDateTime/now)
(DateTimeFormatter/ofPattern "EEE, dd MMM yyyy HH:mm:ss z")))
(defn write-config [config]
(spit config-filename (pr-str config))
config)
(declare hive-post)
(defn hive-refresh-token [config]
(hive-post config
(str beekeeper-base "/1.0/cognito/refresh-token")
{:body (json/generate-string config)}))
(defn hive-call [method config url options]
(let [res (method url (merge options {:throw false
:headers (cond-> {"Content-Type" "application/json"
"Accept" "application/json"
"Date" (now-gmt)}
(:auth? options)
(assoc "authorization" (:token config)))}))
status (:status res)
body (json/parse-string (:body res) keyword)]
(cond
;; we need to refresh the auth token
(and (= body {:error "NOT_AUTHORIZED"})
(not (:no-refresh? options)))
(do
(-> (hive-refresh-token config)
extract-config
write-config)
;; make the call again
(hive-call method config url (assoc options :no-refresh? true)))
(and (>= status 200) (< status 300))
body
:else
(do
body
(System/exit 1)))))
(def hive-get (partial hive-call curl/get))
(def hive-post (partial hive-call curl/post))
(defn product-url [product]
(str beekeeper-base
"/1.0/nodes/"
(:type product)
"/"
(:id product)))
(defn authenticate [config args]
(let [{:keys [options summary errors]}
(tools.cli/parse-opts
args [["-u" "--username USERNAME" "Hive username - required"
:missing "Username missing."]
["-p" "--password PI:PASSWORD:<PASSWORD>END_PI" "Hive password - required"
:missing "Password missing."]])]
(if (not (seq errors))
(do
(-> (hive-post config
(str beekeeper-base "/1.0/cognito/login")
{:body (json/generate-string (select-keys options [:username :password]))})
extract-config
write-config)
(println "That's you authenticated. Good on you."))
(do
(doall (map println errors))
(println summary)
(System/exit 1)))))
(defn products [config _]
(->> (hive-get config
(str beekeeper-base "/1.0/auth/admin-login")
{:auth? false
:body (json/generate-string {:token (:token config)
:products true})})
:products
(group-by #(get-in % [:state :name]))
(map (fn [[k [v]]] [k v]))
(into {})))
(defn lamp-brightness [config [amount]]
(let [amount (edn/read-string amount)
prods (products config [])
lamp (get prods "study lamp")
brightness (get-in lamp [:state :brightness])]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string {:brightness (+ brightness amount)})})))
(defn set-lamp-status [config status]
(let [prods (products config [])
lamp (get prods "study lamp")]
(hive-post config
(product-url lamp)
{:auth? true
:body (json/generate-string (if status
{:status "ON"}
{:status "OFF"}))})))
(defn lamp-toggle [config args]
(let [prods (products config [])
lamp (get prods "study lamp")
status (get-in lamp [:state :status])]
(set-lamp-status config (not= status "ON"))))
(defn heating-waybar [config args]
(let [prods (products config [])
heating (get prods "heating")
heating-on? (:working (:props heating))]
(-> {:text (str (:temperature (:props heating))
"°C / "
(:target (:state heating))
"°C")
:class (if heating-on?
"heating-on"
"heating-off")}
json/generate-string
println)))
(defn lamp-waybar [config args]
(let [prods (products config [])
lamp (:state (get prods "study lamp"))
lamp-on? (boolean (= (:status lamp) "ON"))]
(-> {:percentage (:brightness lamp)
:tooltip (str "Hue: " (:hue lamp) "\n"
"Saturation: " (:saturation lamp) "\n"
"Colour mode: " (:colourMode lamp) "\n"
"Colour temp: " (:colourTemperature lamp))
:class (if lamp-on?
"lamp-on"
"lamp-off")}
json/generate-string
println)))
(def cli-options
[["-v" nil "Verbosity level" :default 0 :update-fn inc]])
#_(def *command-line-args* ["heating-waybar"])
(let [options (tools.cli/parse-opts *command-line-args* cli-options :in-order true)
config (if (.exists (io/file config-filename))
(edn/read-string (slurp config-filename))
{})]
(case (first (:arguments options))
"authenticate" (authenticate config (rest (:arguments options)))
"products" (products config (rest (:arguments options)))
"heating-waybar" (heating-waybar config (rest (:arguments options)))
"lamp-waybar" (lamp-waybar config (rest (:arguments options)))
"lamp-toggle" (lamp-toggle config (rest (:arguments options)))
"lamp-on" (set-lamp-status config true)
"lamp-off" (set-lamp-status config false)
"lamp-brightness" (lamp-brightness config (rest (:arguments options)))))
|
[
{
"context": "ATED-AT \"2020-06-14T12:47:38.000Z\")\n\n(def AUTHOR \"fred-astaire\")\n\n(def AUTHOR2 \"ginger-rogers\")\n\n(def DELETED-AT",
"end": 1370,
"score": 0.947488009929657,
"start": 1358,
"tag": "NAME",
"value": "fred-astaire"
},
{
"context": "00Z\")\n\n(def AUTHOR \"fred-astaire\")\n\n(def AUTHOR2 \"ginger-rogers\")\n\n(def DELETED-AT \"2020-06-14T12:51:38.000Z\")\n\n(",
"end": 1401,
"score": 0.9968193173408508,
"start": 1388,
"tag": "USERNAME",
"value": "ginger-rogers"
},
{
"context": "ated-at \"2020-06-14T12:48:38.000Z\"\n :author AUTHOR}\n {:id \"thread-comment2\"\n :text ",
"end": 1680,
"score": 0.9803895354270935,
"start": 1674,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": "ated-at \"2020-06-14T12:49:38.000Z\"\n :author AUTHOR2}\n {:id \"thread-comment3\"\n :text ",
"end": 1825,
"score": 0.9917608499526978,
"start": 1818,
"tag": "USERNAME",
"value": "AUTHOR2"
},
{
"context": "ated-at \"2020-06-14T12:50:38.000Z\"\n :author AUTHOR2}])\n\n(defsc Root [_this {:keys [thread]}]\n {:quer",
"end": 1996,
"score": 0.9727423191070557,
"start": 1989,
"tag": "USERNAME",
"value": "AUTHOR2"
},
{
"context": "eated-at CREATED-AT\n :author AUTHOR\n :score SCORE\n ",
"end": 3159,
"score": 0.5279185771942139,
"start": 3153,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " \"thread-account1\"\n :username AUTHOR\n :status :success}}}))\n\n(ws/def",
"end": 3437,
"score": 0.9949702620506287,
"start": 3431,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": " :author AUTHOR\n ",
"end": 4032,
"score": 0.5049378871917725,
"start": 4026,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " :username AUTHOR\n ",
"end": 4418,
"score": 0.9971514344215393,
"start": 4412,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": "eated-at CREATED-AT\n :author AUTHOR\n :score SCORE\n ",
"end": 4903,
"score": 0.8234302997589111,
"start": 4897,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " \"thread-account3\"\n :username AUTHOR\n :status :success}}}))\n\n(ws/def",
"end": 5181,
"score": 0.9935300350189209,
"start": 5175,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": "eated-at CREATED-AT\n :author AUTHOR\n :score SCORE\n ",
"end": 5660,
"score": 0.8713051080703735,
"start": 5654,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " :author AUTHOR\n ",
"end": 6468,
"score": 0.995726466178894,
"start": 6462,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " :username AUTHOR\n ",
"end": 6860,
"score": 0.996589720249176,
"start": 6854,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": "eated-at CREATED-AT\n :author AUTHOR\n :deleted-at DELETED-AT\n ",
"end": 7375,
"score": 0.9957374930381775,
"start": 7369,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " \"thread-account5\"\n :username AUTHOR\n :status :success}}}))\n\n(ws/def",
"end": 7694,
"score": 0.8704943656921387,
"start": 7688,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": " CREATED-AT\n :author AUTHOR\n :score SCORE\n ",
"end": 8224,
"score": 0.9953176975250244,
"start": 8218,
"tag": "NAME",
"value": "AUTHOR"
},
{
"context": " \"thread-account6\"\n :username AUTHOR\n :status :success}}}))\n\n(ws/def",
"end": 8583,
"score": 0.9886406064033508,
"start": 8577,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": " CREATED-AT\n :author AUTHOR\n :score SCORE\n ",
"end": 9084,
"score": 0.734948992729187,
"start": 9078,
"tag": "USERNAME",
"value": "AUTHOR"
},
{
"context": " \"thread-account7\"\n :username AUTHOR\n :status :success}}}))\n",
"end": 9448,
"score": 0.9885620474815369,
"start": 9442,
"tag": "USERNAME",
"value": "AUTHOR"
}
] |
src/workspaces/violit/threads/thread_cards.cljs
|
eoogbe/violit-clj
| 0 |
;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.model.session :as session]
[violit.schema.thread :as thread]
[violit.ui.core.dropdown-menu :as dropdown-menu]
[violit.ui.comments.comment :as comment]
[violit.ui.core.markdown :as markdown]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread :as ui.thread]))
(def TITLE "Lorem ipsum")
(def BODY "Dolor sit amet, consectetur adipiscing elit.")
(def CREATED-AT "2020-06-14T12:47:38.000Z")
(def AUTHOR "fred-astaire")
(def AUTHOR2 "ginger-rogers")
(def DELETED-AT "2020-06-14T12:51:38.000Z")
(def SCORE 1)
(def VOTE-STATUS :not-voted)
(def COMMENTS
[{:id "thread-comment1"
:text "Sed do eiusmod tempor incididunt ut labore et dolore."
:created-at "2020-06-14T12:48:38.000Z"
:author AUTHOR}
{:id "thread-comment2"
:text "Ut enim ad minim veniam."
:created-at "2020-06-14T12:49:38.000Z"
:author AUTHOR2}
{:id "thread-comment3"
:text "Quis nostrud exercitation ullamco laboris nisi ut."
:created-at "2020-06-14T12:50:38.000Z"
:author AUTHOR2}])
(defsc Root [_this {:keys [thread]}]
{:query [{:thread (comp/get-query ui.thread/Thread)}
{:ui/current-credentials (comp/get-query session/Credentials)}]
:initial-state (fn [{:keys [thread credentials]}]
{:thread
(comp/get-initial-state ui.thread/Thread thread)
:ui/current-credentials
(comp/get-initial-state session/Credentials credentials)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]
:css-include [dropdown-menu/DropdownMenu markdown/Markdown]}
(dom/div
:.root
(ui.thread/ui-thread thread)
(inj/style-element {:component Root})))
(ws/defcard thread-with-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum1"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account1"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum2"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments []}
:credentials {:id "thread-account2"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-body
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum3"
:title TITLE
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account3"
:username AUTHOR
:status :success}}}))
(ws/defcard logged-out-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum4"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:status :logged-out}}}))
(ws/defcard thread-with-comment-load-failed
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum5"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:load-failed? true}
:credentials {:id "thread-account4"
:username AUTHOR
:status :success}}}))
(ws/defcard deleted-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum6"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:deleted-at DELETED-AT
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account5"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-with-load-more-button
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum7"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:next-comment-cursor "thread-comment1="
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account6"
:username AUTHOR
:status :success}}}))
(ws/defcard editing-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum8"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)
:edit-thread-form (thread/thread-path "lorem-ipsum8")}
:credentials
{:id "thread-account7"
:username AUTHOR
:status :success}}}))
|
44006
|
;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.model.session :as session]
[violit.schema.thread :as thread]
[violit.ui.core.dropdown-menu :as dropdown-menu]
[violit.ui.comments.comment :as comment]
[violit.ui.core.markdown :as markdown]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread :as ui.thread]))
(def TITLE "Lorem ipsum")
(def BODY "Dolor sit amet, consectetur adipiscing elit.")
(def CREATED-AT "2020-06-14T12:47:38.000Z")
(def AUTHOR "<NAME>")
(def AUTHOR2 "ginger-rogers")
(def DELETED-AT "2020-06-14T12:51:38.000Z")
(def SCORE 1)
(def VOTE-STATUS :not-voted)
(def COMMENTS
[{:id "thread-comment1"
:text "Sed do eiusmod tempor incididunt ut labore et dolore."
:created-at "2020-06-14T12:48:38.000Z"
:author AUTHOR}
{:id "thread-comment2"
:text "Ut enim ad minim veniam."
:created-at "2020-06-14T12:49:38.000Z"
:author AUTHOR2}
{:id "thread-comment3"
:text "Quis nostrud exercitation ullamco laboris nisi ut."
:created-at "2020-06-14T12:50:38.000Z"
:author AUTHOR2}])
(defsc Root [_this {:keys [thread]}]
{:query [{:thread (comp/get-query ui.thread/Thread)}
{:ui/current-credentials (comp/get-query session/Credentials)}]
:initial-state (fn [{:keys [thread credentials]}]
{:thread
(comp/get-initial-state ui.thread/Thread thread)
:ui/current-credentials
(comp/get-initial-state session/Credentials credentials)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]
:css-include [dropdown-menu/DropdownMenu markdown/Markdown]}
(dom/div
:.root
(ui.thread/ui-thread thread)
(inj/style-element {:component Root})))
(ws/defcard thread-with-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum1"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account1"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum2"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:comments []}
:credentials {:id "thread-account2"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-body
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum3"
:title TITLE
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account3"
:username AUTHOR
:status :success}}}))
(ws/defcard logged-out-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum4"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:status :logged-out}}}))
(ws/defcard thread-with-comment-load-failed
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum5"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:load-failed? true}
:credentials {:id "thread-account4"
:username AUTHOR
:status :success}}}))
(ws/defcard deleted-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum6"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:deleted-at DELETED-AT
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account5"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-with-load-more-button
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum7"
:title TITLE
:body BODY
:created-at CREATED-AT
:author <NAME>
:score SCORE
:vote-status VOTE-STATUS
:next-comment-cursor "thread-comment1="
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account6"
:username AUTHOR
:status :success}}}))
(ws/defcard editing-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum8"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)
:edit-thread-form (thread/thread-path "lorem-ipsum8")}
:credentials
{:id "thread-account7"
:username AUTHOR
:status :success}}}))
| true |
;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.model.session :as session]
[violit.schema.thread :as thread]
[violit.ui.core.dropdown-menu :as dropdown-menu]
[violit.ui.comments.comment :as comment]
[violit.ui.core.markdown :as markdown]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread :as ui.thread]))
(def TITLE "Lorem ipsum")
(def BODY "Dolor sit amet, consectetur adipiscing elit.")
(def CREATED-AT "2020-06-14T12:47:38.000Z")
(def AUTHOR "PI:NAME:<NAME>END_PI")
(def AUTHOR2 "ginger-rogers")
(def DELETED-AT "2020-06-14T12:51:38.000Z")
(def SCORE 1)
(def VOTE-STATUS :not-voted)
(def COMMENTS
[{:id "thread-comment1"
:text "Sed do eiusmod tempor incididunt ut labore et dolore."
:created-at "2020-06-14T12:48:38.000Z"
:author AUTHOR}
{:id "thread-comment2"
:text "Ut enim ad minim veniam."
:created-at "2020-06-14T12:49:38.000Z"
:author AUTHOR2}
{:id "thread-comment3"
:text "Quis nostrud exercitation ullamco laboris nisi ut."
:created-at "2020-06-14T12:50:38.000Z"
:author AUTHOR2}])
(defsc Root [_this {:keys [thread]}]
{:query [{:thread (comp/get-query ui.thread/Thread)}
{:ui/current-credentials (comp/get-query session/Credentials)}]
:initial-state (fn [{:keys [thread credentials]}]
{:thread
(comp/get-initial-state ui.thread/Thread thread)
:ui/current-credentials
(comp/get-initial-state session/Credentials credentials)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]
:css-include [dropdown-menu/DropdownMenu markdown/Markdown]}
(dom/div
:.root
(ui.thread/ui-thread thread)
(inj/style-element {:component Root})))
(ws/defcard thread-with-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum1"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account1"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-comments
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum2"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:comments []}
:credentials {:id "thread-account2"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-without-body
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum3"
:title TITLE
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account3"
:username AUTHOR
:status :success}}}))
(ws/defcard logged-out-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum4"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:status :logged-out}}}))
(ws/defcard thread-with-comment-load-failed
(ct.fulcro/fulcro-card
{::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:thread {:slug "lorem-ipsum5"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:load-failed? true}
:credentials {:id "thread-account4"
:username AUTHOR
:status :success}}}))
(ws/defcard deleted-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum6"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:deleted-at DELETED-AT
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account5"
:username AUTHOR
:status :success}}}))
(ws/defcard thread-with-load-more-button
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum7"
:title TITLE
:body BODY
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE
:vote-status VOTE-STATUS
:next-comment-cursor "thread-comment1="
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)}
:credentials
{:id "thread-account6"
:username AUTHOR
:status :success}}}))
(ws/defcard editing-thread
(ct.fulcro/fulcro-card
{::ct.fulcro/root
Root
::ct.fulcro/wrap-root?
false
::ct.fulcro/initial-state
{:thread
{:slug "lorem-ipsum8"
:title TITLE
:body BODY
:created-at CREATED-AT
:author AUTHOR
:score SCORE
:vote-status VOTE-STATUS
:comments (mapv #(comp/get-initial-state comment/Comment %) COMMENTS)
:edit-thread-form (thread/thread-path "lorem-ipsum8")}
:credentials
{:id "thread-account7"
:username AUTHOR
:status :success}}}))
|
[
{
"context": "expected# [actual#])}))\n result#)))\n\n; TODO(Richo): Change implementation for sets and vectors so t",
"end": 831,
"score": 0.9820833802223206,
"start": 826,
"tag": "NAME",
"value": "Richo"
}
] |
middleware/server/test/middleware/test_utils.clj
|
kristiank/PhysicalBits
| 0 |
(ns middleware.test-utils
(:require [clojure.test :refer :all]
[clojure.data :as data]
;[ultra.test :as ultra-test]
))
#_(defmethod assert-expr 'equivalent? [msg form]
(let [args (rest form)
pred (first form)]
`(let [values# (list ~@args)
result# (apply ~pred values#)
expected# (first values#)
actual# (second values#)]
(if result#
(do-report {:type :pass
:message ~msg
:expected expected#
:actual actual#})
(do-report {:type :fail
:message ~msg
:expected expected#
:actual actual#
:diffs (ultra-test/generate-diffs expected# [actual#])}))
result#)))
; TODO(Richo): Change implementation for sets and vectors so that it checks equality
(defn equivalent? [a b]
(-> (data/diff a b) first nil?))
|
41067
|
(ns middleware.test-utils
(:require [clojure.test :refer :all]
[clojure.data :as data]
;[ultra.test :as ultra-test]
))
#_(defmethod assert-expr 'equivalent? [msg form]
(let [args (rest form)
pred (first form)]
`(let [values# (list ~@args)
result# (apply ~pred values#)
expected# (first values#)
actual# (second values#)]
(if result#
(do-report {:type :pass
:message ~msg
:expected expected#
:actual actual#})
(do-report {:type :fail
:message ~msg
:expected expected#
:actual actual#
:diffs (ultra-test/generate-diffs expected# [actual#])}))
result#)))
; TODO(<NAME>): Change implementation for sets and vectors so that it checks equality
(defn equivalent? [a b]
(-> (data/diff a b) first nil?))
| true |
(ns middleware.test-utils
(:require [clojure.test :refer :all]
[clojure.data :as data]
;[ultra.test :as ultra-test]
))
#_(defmethod assert-expr 'equivalent? [msg form]
(let [args (rest form)
pred (first form)]
`(let [values# (list ~@args)
result# (apply ~pred values#)
expected# (first values#)
actual# (second values#)]
(if result#
(do-report {:type :pass
:message ~msg
:expected expected#
:actual actual#})
(do-report {:type :fail
:message ~msg
:expected expected#
:actual actual#
:diffs (ultra-test/generate-diffs expected# [actual#])}))
result#)))
; TODO(PI:NAME:<NAME>END_PI): Change implementation for sets and vectors so that it checks equality
(defn equivalent? [a b]
(-> (data/diff a b) first nil?))
|
[
{
"context": "]\n [:footer [:p \"Copyright (c) 2011 Warren Strange\"]]]]))\n\n; Standard layout - no additional javascr",
"end": 4651,
"score": 0.9998929500579834,
"start": 4637,
"tag": "NAME",
"value": "Warren Strange"
}
] |
data/train/clojure/0d781f9e395e4ac5e29c58ab53f3e1ea9b45a152common.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
(ns cloauth.views.common
(:use noir.core
hiccup.core
hiccup.page-helpers
hiccup.form-helpers)
(:require [cloauth.models.kdb :as db]
[noir.session :as session]
[gitauth.gitkit :as gitkit]
))
; Define all of the CSS and JS includes that we might need
(def includes {:jquery (include-js "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js")
:jquery-ui (include-js "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js")
:jquery-local (include-js "/js/jquery-1.7.1.min.js")
:jquery-ui-local (include-js "/js/jquery-ui-1.8.16.custom.min.js")
:bootstrap (include-css "/css/bootstrap.css")
:bootstrap-responsive (include-css "/css/bootstrap-responsive.css")
:google-apis (include-js "https://ajax.googleapis.com/ajax/libs/googleapis/0.0.4/googleapis.min.js")
:jsapi (include-js "https://ajax.googleapis.com/jsapi")
; bootstrap javascript
:bootstrap-js (include-js "/js/bootstrap.js")
; bit of script to enable various bootstrap 2.0 javascript stuff
:bootstrap-js-init (javascript-tag "$(document).ready(function () {
$('.alert-message').alert(); });")
})
; css and js includes that every page will need
; For now this is the same as the above list!
(def base-includes [:bootstrap :bootstrap-responsive :jquery :jquery-ui
:bootstrap-js :bootstrap-js-init :jsapi :google-apis])
; create the page <head>
(defpartial build-head [static-includes]
[:head
[:meta {:charset "utf-8"}]
[:title "Cloauth"]
(map #(get includes %) static-includes)
(gitkit/generate-git-javascript)
[:style {:type "text/css"} "body { padding-top: 60px;}
.sidebar-nav { padding: 9px 0;}"]
])
; "Menu" data structure :title :check (optional fn to call to see if the menu should be rendered) :links
(def client-menu {:title "Client Management"
:links [["/client/register" "Register Client"]
["/client/admin" "Manage Clients"]]})
(def apps-menu {:title "My Authorized Applications"
:links [["/oauth2/user/grants" "Authorized Applications" ]]})
(def admin-menu {:title "Admin"
:check-fn db/user-is-admin?
:links
[["/admin/user" "Admin/Main"]
]})
(def test-menu {:title "OAuth Test Pages"
:links [["/test" "Test Page"]]})
; todo set default class for link items?
(defpartial link-item [{:keys [url cls text]}]
[:li (link-to url text)])
(defn menu-items [links]
(for [[url text] links]
[:li (link-to url text )]))
; If a menu has a check function defined call it.
; If the fn returns true we render the menu, else nil
; This is used to include/exclude menus based on some criteria (role, for example)
(defpartial render-menu [{:keys [title check-fn links]}]
(if (or (nil? check-fn)
(check-fn))
[:div
[:li.nav-header title]
(menu-items links)]))
; Navigation Side bar
(defpartial nav-content []
[:div.well.sidebar-nav
[:ul.nav.nav-list
(render-menu admin-menu)
(render-menu test-menu)
(render-menu client-menu)
(render-menu apps-menu)]])
; Top mast header
; The GIT toolkit will render a sign in button in the chooser div
; See gitkit.clj
(defpartial topmast-content []
[:div.navbar.navbar-fixed-top
[:div.navbar-inner
[:div.container-fluid
[:a.brand {:href "/"} "CloAuth"]
[:p.pull-right.navbar-text [:div#chooser "Account Chooser"] ]
]]])
; Layout with an include map for optional css / js
(defpartial layout-with-includes [ {:keys [css js]} & content]
;(prn "option map " css js "content " content)
(html5 {:lang "en"}
(build-head base-includes)
[:body
(topmast-content)
[:div.container-fluid
[:div.row-fluid
[:div.span3 (nav-content)]
[:div.span9
(if-let [message (session/flash-get :message)]
[:div.alert.alert-success.fade.in
[:a.close {:data-dismiss "alert" :href "#"} "x" ]
message])
content]]
; [:div.hero-unit ]]] ; end row-fluid
[:hr]
[:footer [:p "Copyright (c) 2011 Warren Strange"]]]]))
; Standard layout - no additional javascript or css
(defpartial layout [& content]
;(prn "Layout " content)
(layout-with-includes {}, content))
(defn- mktext [keyval text]
[:div.clearfix
(label keyval keyval)
[:div.input
(text-field {:class "large" :size "40" } keyval text)]])
;
(defpartial simple-post-form [url form-map]
(form-to [:post url]
[:fieldset
(map #(mktext (key %) (val %)) form-map)
[:div.actions
[:button.btn.primary "Submit"]
[:button.btn {:type "reset"} "Reset"]]]))
|
103904
|
(ns cloauth.views.common
(:use noir.core
hiccup.core
hiccup.page-helpers
hiccup.form-helpers)
(:require [cloauth.models.kdb :as db]
[noir.session :as session]
[gitauth.gitkit :as gitkit]
))
; Define all of the CSS and JS includes that we might need
(def includes {:jquery (include-js "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js")
:jquery-ui (include-js "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js")
:jquery-local (include-js "/js/jquery-1.7.1.min.js")
:jquery-ui-local (include-js "/js/jquery-ui-1.8.16.custom.min.js")
:bootstrap (include-css "/css/bootstrap.css")
:bootstrap-responsive (include-css "/css/bootstrap-responsive.css")
:google-apis (include-js "https://ajax.googleapis.com/ajax/libs/googleapis/0.0.4/googleapis.min.js")
:jsapi (include-js "https://ajax.googleapis.com/jsapi")
; bootstrap javascript
:bootstrap-js (include-js "/js/bootstrap.js")
; bit of script to enable various bootstrap 2.0 javascript stuff
:bootstrap-js-init (javascript-tag "$(document).ready(function () {
$('.alert-message').alert(); });")
})
; css and js includes that every page will need
; For now this is the same as the above list!
(def base-includes [:bootstrap :bootstrap-responsive :jquery :jquery-ui
:bootstrap-js :bootstrap-js-init :jsapi :google-apis])
; create the page <head>
(defpartial build-head [static-includes]
[:head
[:meta {:charset "utf-8"}]
[:title "Cloauth"]
(map #(get includes %) static-includes)
(gitkit/generate-git-javascript)
[:style {:type "text/css"} "body { padding-top: 60px;}
.sidebar-nav { padding: 9px 0;}"]
])
; "Menu" data structure :title :check (optional fn to call to see if the menu should be rendered) :links
(def client-menu {:title "Client Management"
:links [["/client/register" "Register Client"]
["/client/admin" "Manage Clients"]]})
(def apps-menu {:title "My Authorized Applications"
:links [["/oauth2/user/grants" "Authorized Applications" ]]})
(def admin-menu {:title "Admin"
:check-fn db/user-is-admin?
:links
[["/admin/user" "Admin/Main"]
]})
(def test-menu {:title "OAuth Test Pages"
:links [["/test" "Test Page"]]})
; todo set default class for link items?
(defpartial link-item [{:keys [url cls text]}]
[:li (link-to url text)])
(defn menu-items [links]
(for [[url text] links]
[:li (link-to url text )]))
; If a menu has a check function defined call it.
; If the fn returns true we render the menu, else nil
; This is used to include/exclude menus based on some criteria (role, for example)
(defpartial render-menu [{:keys [title check-fn links]}]
(if (or (nil? check-fn)
(check-fn))
[:div
[:li.nav-header title]
(menu-items links)]))
; Navigation Side bar
(defpartial nav-content []
[:div.well.sidebar-nav
[:ul.nav.nav-list
(render-menu admin-menu)
(render-menu test-menu)
(render-menu client-menu)
(render-menu apps-menu)]])
; Top mast header
; The GIT toolkit will render a sign in button in the chooser div
; See gitkit.clj
(defpartial topmast-content []
[:div.navbar.navbar-fixed-top
[:div.navbar-inner
[:div.container-fluid
[:a.brand {:href "/"} "CloAuth"]
[:p.pull-right.navbar-text [:div#chooser "Account Chooser"] ]
]]])
; Layout with an include map for optional css / js
(defpartial layout-with-includes [ {:keys [css js]} & content]
;(prn "option map " css js "content " content)
(html5 {:lang "en"}
(build-head base-includes)
[:body
(topmast-content)
[:div.container-fluid
[:div.row-fluid
[:div.span3 (nav-content)]
[:div.span9
(if-let [message (session/flash-get :message)]
[:div.alert.alert-success.fade.in
[:a.close {:data-dismiss "alert" :href "#"} "x" ]
message])
content]]
; [:div.hero-unit ]]] ; end row-fluid
[:hr]
[:footer [:p "Copyright (c) 2011 <NAME>"]]]]))
; Standard layout - no additional javascript or css
(defpartial layout [& content]
;(prn "Layout " content)
(layout-with-includes {}, content))
(defn- mktext [keyval text]
[:div.clearfix
(label keyval keyval)
[:div.input
(text-field {:class "large" :size "40" } keyval text)]])
;
(defpartial simple-post-form [url form-map]
(form-to [:post url]
[:fieldset
(map #(mktext (key %) (val %)) form-map)
[:div.actions
[:button.btn.primary "Submit"]
[:button.btn {:type "reset"} "Reset"]]]))
| true |
(ns cloauth.views.common
(:use noir.core
hiccup.core
hiccup.page-helpers
hiccup.form-helpers)
(:require [cloauth.models.kdb :as db]
[noir.session :as session]
[gitauth.gitkit :as gitkit]
))
; Define all of the CSS and JS includes that we might need
(def includes {:jquery (include-js "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js")
:jquery-ui (include-js "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js")
:jquery-local (include-js "/js/jquery-1.7.1.min.js")
:jquery-ui-local (include-js "/js/jquery-ui-1.8.16.custom.min.js")
:bootstrap (include-css "/css/bootstrap.css")
:bootstrap-responsive (include-css "/css/bootstrap-responsive.css")
:google-apis (include-js "https://ajax.googleapis.com/ajax/libs/googleapis/0.0.4/googleapis.min.js")
:jsapi (include-js "https://ajax.googleapis.com/jsapi")
; bootstrap javascript
:bootstrap-js (include-js "/js/bootstrap.js")
; bit of script to enable various bootstrap 2.0 javascript stuff
:bootstrap-js-init (javascript-tag "$(document).ready(function () {
$('.alert-message').alert(); });")
})
; css and js includes that every page will need
; For now this is the same as the above list!
(def base-includes [:bootstrap :bootstrap-responsive :jquery :jquery-ui
:bootstrap-js :bootstrap-js-init :jsapi :google-apis])
; create the page <head>
(defpartial build-head [static-includes]
[:head
[:meta {:charset "utf-8"}]
[:title "Cloauth"]
(map #(get includes %) static-includes)
(gitkit/generate-git-javascript)
[:style {:type "text/css"} "body { padding-top: 60px;}
.sidebar-nav { padding: 9px 0;}"]
])
; "Menu" data structure :title :check (optional fn to call to see if the menu should be rendered) :links
(def client-menu {:title "Client Management"
:links [["/client/register" "Register Client"]
["/client/admin" "Manage Clients"]]})
(def apps-menu {:title "My Authorized Applications"
:links [["/oauth2/user/grants" "Authorized Applications" ]]})
(def admin-menu {:title "Admin"
:check-fn db/user-is-admin?
:links
[["/admin/user" "Admin/Main"]
]})
(def test-menu {:title "OAuth Test Pages"
:links [["/test" "Test Page"]]})
; todo set default class for link items?
(defpartial link-item [{:keys [url cls text]}]
[:li (link-to url text)])
(defn menu-items [links]
(for [[url text] links]
[:li (link-to url text )]))
; If a menu has a check function defined call it.
; If the fn returns true we render the menu, else nil
; This is used to include/exclude menus based on some criteria (role, for example)
(defpartial render-menu [{:keys [title check-fn links]}]
(if (or (nil? check-fn)
(check-fn))
[:div
[:li.nav-header title]
(menu-items links)]))
; Navigation Side bar
(defpartial nav-content []
[:div.well.sidebar-nav
[:ul.nav.nav-list
(render-menu admin-menu)
(render-menu test-menu)
(render-menu client-menu)
(render-menu apps-menu)]])
; Top mast header
; The GIT toolkit will render a sign in button in the chooser div
; See gitkit.clj
(defpartial topmast-content []
[:div.navbar.navbar-fixed-top
[:div.navbar-inner
[:div.container-fluid
[:a.brand {:href "/"} "CloAuth"]
[:p.pull-right.navbar-text [:div#chooser "Account Chooser"] ]
]]])
; Layout with an include map for optional css / js
(defpartial layout-with-includes [ {:keys [css js]} & content]
;(prn "option map " css js "content " content)
(html5 {:lang "en"}
(build-head base-includes)
[:body
(topmast-content)
[:div.container-fluid
[:div.row-fluid
[:div.span3 (nav-content)]
[:div.span9
(if-let [message (session/flash-get :message)]
[:div.alert.alert-success.fade.in
[:a.close {:data-dismiss "alert" :href "#"} "x" ]
message])
content]]
; [:div.hero-unit ]]] ; end row-fluid
[:hr]
[:footer [:p "Copyright (c) 2011 PI:NAME:<NAME>END_PI"]]]]))
; Standard layout - no additional javascript or css
(defpartial layout [& content]
;(prn "Layout " content)
(layout-with-includes {}, content))
(defn- mktext [keyval text]
[:div.clearfix
(label keyval keyval)
[:div.input
(text-field {:class "large" :size "40" } keyval text)]])
;
(defpartial simple-post-form [url form-map]
(form-to [:post url]
[:fieldset
(map #(mktext (key %) (val %)) form-map)
[:div.actions
[:button.btn.primary "Submit"]
[:button.btn {:type "reset"} "Reset"]]]))
|
[
{
"context": "\\\"SubscriberId\\\":\\\"post-user\\\",\\\"EmailAddress\\\":\\\"[email protected]\\\",\\\"CollectionConceptId\\\":\\\"C1200000018-PROV1\\\",\\",
"end": 407,
"score": 0.999911367893219,
"start": 388,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
ingest-app/test/cmr/ingest/api/subscriptions_test.clj
|
chris-durbin/Common-Metadata-Repository
| 294 |
(ns cmr.ingest.api.subscriptions-test
(:require
[cheshire.core :as json]
[clojure.string :as string]
[clojure.test :refer :all]
[cmr.ingest.api.core :as api-core]
[cmr.ingest.api.subscriptions :as subscriptions]))
(deftest generate-native-id-test
(let [concept {:metadata
"{\"Name\":\"the beginning\",\"SubscriberId\":\"post-user\",\"EmailAddress\":\"[email protected]\",\"CollectionConceptId\":\"C1200000018-PROV1\",\"Query\":\"polygon=-18,-78,-13,-74,-16,-73,-22,-77,-18,-78\"}"
:format "application/vnd.nasa.cmr.umm+json;version=1.0"
:native-id nil
:concept-type :subscription
:provider-id "PROV1"}
native-id (subscriptions/generate-native-id concept)]
(is (string? native-id))
(testing "name is used as the prefix"
(is (string/starts-with? native-id "the_beginning")))))
|
75040
|
(ns cmr.ingest.api.subscriptions-test
(:require
[cheshire.core :as json]
[clojure.string :as string]
[clojure.test :refer :all]
[cmr.ingest.api.core :as api-core]
[cmr.ingest.api.subscriptions :as subscriptions]))
(deftest generate-native-id-test
(let [concept {:metadata
"{\"Name\":\"the beginning\",\"SubscriberId\":\"post-user\",\"EmailAddress\":\"<EMAIL>\",\"CollectionConceptId\":\"C1200000018-PROV1\",\"Query\":\"polygon=-18,-78,-13,-74,-16,-73,-22,-77,-18,-78\"}"
:format "application/vnd.nasa.cmr.umm+json;version=1.0"
:native-id nil
:concept-type :subscription
:provider-id "PROV1"}
native-id (subscriptions/generate-native-id concept)]
(is (string? native-id))
(testing "name is used as the prefix"
(is (string/starts-with? native-id "the_beginning")))))
| true |
(ns cmr.ingest.api.subscriptions-test
(:require
[cheshire.core :as json]
[clojure.string :as string]
[clojure.test :refer :all]
[cmr.ingest.api.core :as api-core]
[cmr.ingest.api.subscriptions :as subscriptions]))
(deftest generate-native-id-test
(let [concept {:metadata
"{\"Name\":\"the beginning\",\"SubscriberId\":\"post-user\",\"EmailAddress\":\"PI:EMAIL:<EMAIL>END_PI\",\"CollectionConceptId\":\"C1200000018-PROV1\",\"Query\":\"polygon=-18,-78,-13,-74,-16,-73,-22,-77,-18,-78\"}"
:format "application/vnd.nasa.cmr.umm+json;version=1.0"
:native-id nil
:concept-type :subscription
:provider-id "PROV1"}
native-id (subscriptions/generate-native-id concept)]
(is (string? native-id))
(testing "name is used as the prefix"
(is (string/starts-with? native-id "the_beginning")))))
|
[
{
"context": " file is part of music-compojure.\n; Copyright (c) Matthew Howlett 2009\n;\n; music-compojure is free software: you c",
"end": 73,
"score": 0.9997990131378174,
"start": 58,
"tag": "NAME",
"value": "Matthew Howlett"
}
] |
data/test/clojure/b1874e62e035e1106a1d03e4dd0712e3a37468a4event_creation.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
; This file is part of music-compojure.
; Copyright (c) Matthew Howlett 2009
;
; music-compojure is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; music-compojure is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with music-compojure. If not, see <http://www.gnu.org/licenses/>.
(ns music-compojure.event-creation
(:import javax.sound.midi.ShortMessage)
(:import javax.sound.midi.MetaMessage)
(:import javax.sound.midi.MidiEvent))
; midi file format is well described here:
; http://www.sonicspot.com/guide/midifiles.html
(defn- create-text-event [text type tick]
(let [message (new MetaMessage)
bytes (. text getBytes)]
(do
(.setMessage message type bytes (count bytes))
(new MidiEvent message tick))))
(defn create-copyright-event [copyright tick]
(create-text-event copyright 0x02 tick))
(defn create-track-name-event [track-name tick]
(create-text-event track-name 0x03 tick))
(defn create-instrument-name-event [instrument-name tick]
(create-text-event instrument-name 0x04 tick))
(defn- create-note-event [command channel note velocity tick]
(let [message (new ShortMessage)]
(do
(.setMessage message command channel note velocity)
(new MidiEvent message tick))))
(defn create-note-on-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_ON channel note velocity tick))
(defn create-note-off-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_OFF channel note velocity tick))
(defn create-tempo-event [bpm tick]
(let [TEMPO-MESSAGE 81
microseconds-per-minute 60000000
mpqn (/ microseconds-per-minute bpm) ; microseconds per quarter note
message (new MetaMessage)
bytes (make-array (. Byte TYPE) 3)]
(do
(aset bytes 0 (byte (bit-and (bit-shift-right mpqn 16) 0xFF)))
(aset bytes 1 (byte (bit-and (bit-shift-right mpqn 8) 0xFF)))
(aset bytes 2 (byte (bit-and (bit-shift-right mpqn 0) 0xFF)))
(.setMessage message TEMPO-MESSAGE bytes 3)
(new MidiEvent message tick))))
(defn create-program-change-event [channel program tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/PROGRAM_CHANGE channel program 0)
(new MidiEvent message tick))))
(defn create-controller-event [channel type value tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/CONTROL_CHANGE channel type value)
(new MidiEvent message tick))))
(defn create-sustain-down-event [channel tick]
(create-controller-event channel 0x40 127 tick))
(defn create-sustain-up-event [channel tick]
(create-controller-event channel 0x40 0 tick))
|
117573
|
; This file is part of music-compojure.
; Copyright (c) <NAME> 2009
;
; music-compojure is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; music-compojure is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with music-compojure. If not, see <http://www.gnu.org/licenses/>.
(ns music-compojure.event-creation
(:import javax.sound.midi.ShortMessage)
(:import javax.sound.midi.MetaMessage)
(:import javax.sound.midi.MidiEvent))
; midi file format is well described here:
; http://www.sonicspot.com/guide/midifiles.html
(defn- create-text-event [text type tick]
(let [message (new MetaMessage)
bytes (. text getBytes)]
(do
(.setMessage message type bytes (count bytes))
(new MidiEvent message tick))))
(defn create-copyright-event [copyright tick]
(create-text-event copyright 0x02 tick))
(defn create-track-name-event [track-name tick]
(create-text-event track-name 0x03 tick))
(defn create-instrument-name-event [instrument-name tick]
(create-text-event instrument-name 0x04 tick))
(defn- create-note-event [command channel note velocity tick]
(let [message (new ShortMessage)]
(do
(.setMessage message command channel note velocity)
(new MidiEvent message tick))))
(defn create-note-on-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_ON channel note velocity tick))
(defn create-note-off-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_OFF channel note velocity tick))
(defn create-tempo-event [bpm tick]
(let [TEMPO-MESSAGE 81
microseconds-per-minute 60000000
mpqn (/ microseconds-per-minute bpm) ; microseconds per quarter note
message (new MetaMessage)
bytes (make-array (. Byte TYPE) 3)]
(do
(aset bytes 0 (byte (bit-and (bit-shift-right mpqn 16) 0xFF)))
(aset bytes 1 (byte (bit-and (bit-shift-right mpqn 8) 0xFF)))
(aset bytes 2 (byte (bit-and (bit-shift-right mpqn 0) 0xFF)))
(.setMessage message TEMPO-MESSAGE bytes 3)
(new MidiEvent message tick))))
(defn create-program-change-event [channel program tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/PROGRAM_CHANGE channel program 0)
(new MidiEvent message tick))))
(defn create-controller-event [channel type value tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/CONTROL_CHANGE channel type value)
(new MidiEvent message tick))))
(defn create-sustain-down-event [channel tick]
(create-controller-event channel 0x40 127 tick))
(defn create-sustain-up-event [channel tick]
(create-controller-event channel 0x40 0 tick))
| true |
; This file is part of music-compojure.
; Copyright (c) PI:NAME:<NAME>END_PI 2009
;
; music-compojure is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; music-compojure is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with music-compojure. If not, see <http://www.gnu.org/licenses/>.
(ns music-compojure.event-creation
(:import javax.sound.midi.ShortMessage)
(:import javax.sound.midi.MetaMessage)
(:import javax.sound.midi.MidiEvent))
; midi file format is well described here:
; http://www.sonicspot.com/guide/midifiles.html
(defn- create-text-event [text type tick]
(let [message (new MetaMessage)
bytes (. text getBytes)]
(do
(.setMessage message type bytes (count bytes))
(new MidiEvent message tick))))
(defn create-copyright-event [copyright tick]
(create-text-event copyright 0x02 tick))
(defn create-track-name-event [track-name tick]
(create-text-event track-name 0x03 tick))
(defn create-instrument-name-event [instrument-name tick]
(create-text-event instrument-name 0x04 tick))
(defn- create-note-event [command channel note velocity tick]
(let [message (new ShortMessage)]
(do
(.setMessage message command channel note velocity)
(new MidiEvent message tick))))
(defn create-note-on-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_ON channel note velocity tick))
(defn create-note-off-event [channel note velocity tick]
(create-note-event ShortMessage/NOTE_OFF channel note velocity tick))
(defn create-tempo-event [bpm tick]
(let [TEMPO-MESSAGE 81
microseconds-per-minute 60000000
mpqn (/ microseconds-per-minute bpm) ; microseconds per quarter note
message (new MetaMessage)
bytes (make-array (. Byte TYPE) 3)]
(do
(aset bytes 0 (byte (bit-and (bit-shift-right mpqn 16) 0xFF)))
(aset bytes 1 (byte (bit-and (bit-shift-right mpqn 8) 0xFF)))
(aset bytes 2 (byte (bit-and (bit-shift-right mpqn 0) 0xFF)))
(.setMessage message TEMPO-MESSAGE bytes 3)
(new MidiEvent message tick))))
(defn create-program-change-event [channel program tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/PROGRAM_CHANGE channel program 0)
(new MidiEvent message tick))))
(defn create-controller-event [channel type value tick]
(let [message (new ShortMessage)]
(do
(.setMessage message ShortMessage/CONTROL_CHANGE channel type value)
(new MidiEvent message tick))))
(defn create-sustain-down-event [channel tick]
(create-controller-event channel 0x40 127 tick))
(defn create-sustain-up-event [channel tick]
(create-controller-event channel 0x40 0 tick))
|
[
{
"context": " (d/transact! [{:db/id 1\n :name \"Peter\"}\n {:db/id 2\n :nam",
"end": 339,
"score": 0.9994349479675293,
"start": 334,
"tag": "NAME",
"value": "Peter"
},
{
"context": " {:db/id 2\n :name \"Victoria\"}])\n\n (testing \"capture access patterns\"\n\n (i",
"end": 401,
"score": 0.9996067881584167,
"start": 393,
"tag": "NAME",
"value": "Victoria"
},
{
"context": "\n (d/transact! [[:db/add :db/settings :name \"Herman\"]])\n\n (d/compute! [:db/settings :name-x-2]\n ",
"end": 1638,
"score": 0.9996151924133301,
"start": 1632,
"tag": "NAME",
"value": "Herman"
},
{
"context": "eat (d/get :db/settings :name)))))\n\n (is (= \"HermanHerman\" (d/get :db/settings :name-x-2)))\n (is (= 1 ",
"end": 1831,
"score": 0.9996910691261292,
"start": 1819,
"tag": "NAME",
"value": "HermanHerman"
},
{
"context": " (d/transact! [[:db/add :db/settings :name \"Lily\"]])\n (is (= \"LilyLily\" (d/get :db/settings",
"end": 2023,
"score": 0.9995092749595642,
"start": 2019,
"tag": "NAME",
"value": "Lily"
},
{
"context": " (d/get :db/settings :name))))))\n\n (is (= \"Lily - Lily\" (d/get :db/settings :name-x-2)))\n ",
"end": 2367,
"score": 0.851514458656311,
"start": 2363,
"tag": "NAME",
"value": "Lily"
},
{
"context": "t :db/settings :name))))))\n\n (is (= \"Lily - Lily\" (d/get :db/settings :name-x-2)))\n (d/tran",
"end": 2374,
"score": 0.9377334117889404,
"start": 2370,
"tag": "NAME",
"value": "Lily"
},
{
"context": " (d/transact! [[:db/add :db/settings :name \"Marvin\"]])\n (is (= \"Marvin - Marvin\" (d/get :db/s",
"end": 2466,
"score": 0.9889453649520874,
"start": 2460,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "dd :db/settings :name \"Marvin\"]])\n (is (= \"Marvin - Marvin\" (d/get :db/settings :name-x-2))))\n\n ",
"end": 2493,
"score": 0.962876558303833,
"start": 2487,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "ettings :name \"Marvin\"]])\n (is (= \"Marvin - Marvin\" (d/get :db/settings :name-x-2))))\n\n (testin",
"end": 2502,
"score": 0.9668805599212646,
"start": 2496,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "x \" (d/get :db/settings :name)))\n\n (is (= \"Marvin - Marvin x Marvin\" (d/get :db/settings :name-x-2)",
"end": 2941,
"score": 0.9473198652267456,
"start": 2935,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "et :db/settings :name)))\n\n (is (= \"Marvin - Marvin x Marvin\" (d/get :db/settings :name-x-2)))\n ",
"end": 2950,
"score": 0.7849186658859253,
"start": 2944,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "ttings :name)))\n\n (is (= \"Marvin - Marvin x Marvin\" (d/get :db/settings :name-x-2)))\n (d/tran",
"end": 2959,
"score": 0.91007000207901,
"start": 2953,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "b/add :db/settings :name \"Wow\"]])\n (is (= \"Marvin - Marvin x Marvin x Wow\" (d/get :db/settings :nam",
"end": 3075,
"score": 0.8214515447616577,
"start": 3069,
"tag": "NAME",
"value": "Marvin"
},
{
"context": "ttings :name \"Wow\"]])\n (is (= \"Marvin - Marvin x Marvin x Wow\" (d/get :db/settings :name-x-2))))",
"end": 3084,
"score": 0.536636233329773,
"start": 3081,
"tag": "NAME",
"value": "vin"
},
{
"context": " (d/transact! [[:db/add :db/settings :name \"Veronica\"]])\n (is (= 6 @eval-count)))))",
"end": 3283,
"score": 0.6062557697296143,
"start": 3280,
"tag": "NAME",
"value": "Ver"
}
] |
re_db/test/re_db/reactivity_test.cljs
|
braintripping/re-view
| 32 |
(ns re-db.reactivity-test
(:require [cljs.test :refer-macros [deftest is testing]]
[re-db.d :as d]
[re-db.patterns :as patterns :include-macros true])
(:require-macros [re-db.test-helpers :refer [throws]]))
(def eval-count (atom 0))
(deftest reactivity
(d/transact! [{:db/id 1
:name "Peter"}
{:db/id 2
:name "Victoria"}])
(testing "capture access patterns"
(is (= #{1} (-> (patterns/capture-patterns
(d/entity 1))
:patterns
:e__))
"entity pattern")
(is (= #{[1 :name]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :name))
:patterns
:ea_))
"entity-attr pattern")
(is (= #{[1 :name]
[1 :dog]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :dog))
:patterns
:ea_))
"two entity-attr patterns")
(is (= {:e__ #{1}
:ea_ #{[1 :name]}}
(-> (patterns/capture-patterns
(d/get 1 :name)
(d/entity 1)
(d/get 1 :name))
:patterns
(select-keys [:e__ :ea_])))
"entity pattern")))
#_(deftest compute
(testing "Can set a computed property"
(d/transact! [[:db/add :db/settings :name "Herman"]])
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (take 2 (repeat (d/get :db/settings :name)))))
(is (= "HermanHerman" (d/get :db/settings :name-x-2)))
(is (= 1 @eval-count))
(testing "Update a computed value when a dependent value changes"
(d/transact! [[:db/add :db/settings :name "Lily"]])
(is (= "LilyLily" (d/get :db/settings :name-x-2)))
(is (= 2 @eval-count)))
(testing "Change a computed value"
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (interpose " - " (take 2 (repeat (d/get :db/settings :name))))))
(is (= "Lily - Lily" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "Marvin"]])
(is (= "Marvin - Marvin" (d/get :db/settings :name-x-2))))
(testing "If a computed property references itself, does not cause loop"
;; TODO
;; model a proper computed-value graph to avoid cycles
;; supply prev-value as `this`?
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(str (d/get :db/settings :name-x-2) " x " (d/get :db/settings :name)))
(is (= "Marvin - Marvin x Marvin" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "Wow"]])
(is (= "Marvin - Marvin x Marvin x Wow" (d/get :db/settings :name-x-2))))
(testing "Clear a computed value"
(d/compute! [:db/settings :name-x-2] false)
(d/transact! [[:db/add :db/settings :name "Veronica"]])
(is (= 6 @eval-count)))))
|
60271
|
(ns re-db.reactivity-test
(:require [cljs.test :refer-macros [deftest is testing]]
[re-db.d :as d]
[re-db.patterns :as patterns :include-macros true])
(:require-macros [re-db.test-helpers :refer [throws]]))
(def eval-count (atom 0))
(deftest reactivity
(d/transact! [{:db/id 1
:name "<NAME>"}
{:db/id 2
:name "<NAME>"}])
(testing "capture access patterns"
(is (= #{1} (-> (patterns/capture-patterns
(d/entity 1))
:patterns
:e__))
"entity pattern")
(is (= #{[1 :name]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :name))
:patterns
:ea_))
"entity-attr pattern")
(is (= #{[1 :name]
[1 :dog]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :dog))
:patterns
:ea_))
"two entity-attr patterns")
(is (= {:e__ #{1}
:ea_ #{[1 :name]}}
(-> (patterns/capture-patterns
(d/get 1 :name)
(d/entity 1)
(d/get 1 :name))
:patterns
(select-keys [:e__ :ea_])))
"entity pattern")))
#_(deftest compute
(testing "Can set a computed property"
(d/transact! [[:db/add :db/settings :name "<NAME>"]])
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (take 2 (repeat (d/get :db/settings :name)))))
(is (= "<NAME>" (d/get :db/settings :name-x-2)))
(is (= 1 @eval-count))
(testing "Update a computed value when a dependent value changes"
(d/transact! [[:db/add :db/settings :name "<NAME>"]])
(is (= "LilyLily" (d/get :db/settings :name-x-2)))
(is (= 2 @eval-count)))
(testing "Change a computed value"
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (interpose " - " (take 2 (repeat (d/get :db/settings :name))))))
(is (= "<NAME> - <NAME>" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "<NAME>"]])
(is (= "<NAME> - <NAME>" (d/get :db/settings :name-x-2))))
(testing "If a computed property references itself, does not cause loop"
;; TODO
;; model a proper computed-value graph to avoid cycles
;; supply prev-value as `this`?
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(str (d/get :db/settings :name-x-2) " x " (d/get :db/settings :name)))
(is (= "<NAME> - <NAME> x <NAME>" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "Wow"]])
(is (= "<NAME> - Mar<NAME> x Marvin x Wow" (d/get :db/settings :name-x-2))))
(testing "Clear a computed value"
(d/compute! [:db/settings :name-x-2] false)
(d/transact! [[:db/add :db/settings :name "<NAME>onica"]])
(is (= 6 @eval-count)))))
| true |
(ns re-db.reactivity-test
(:require [cljs.test :refer-macros [deftest is testing]]
[re-db.d :as d]
[re-db.patterns :as patterns :include-macros true])
(:require-macros [re-db.test-helpers :refer [throws]]))
(def eval-count (atom 0))
(deftest reactivity
(d/transact! [{:db/id 1
:name "PI:NAME:<NAME>END_PI"}
{:db/id 2
:name "PI:NAME:<NAME>END_PI"}])
(testing "capture access patterns"
(is (= #{1} (-> (patterns/capture-patterns
(d/entity 1))
:patterns
:e__))
"entity pattern")
(is (= #{[1 :name]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :name))
:patterns
:ea_))
"entity-attr pattern")
(is (= #{[1 :name]
[1 :dog]} (-> (patterns/capture-patterns
(d/get 1 :name)
(d/get 1 :dog))
:patterns
:ea_))
"two entity-attr patterns")
(is (= {:e__ #{1}
:ea_ #{[1 :name]}}
(-> (patterns/capture-patterns
(d/get 1 :name)
(d/entity 1)
(d/get 1 :name))
:patterns
(select-keys [:e__ :ea_])))
"entity pattern")))
#_(deftest compute
(testing "Can set a computed property"
(d/transact! [[:db/add :db/settings :name "PI:NAME:<NAME>END_PI"]])
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (take 2 (repeat (d/get :db/settings :name)))))
(is (= "PI:NAME:<NAME>END_PI" (d/get :db/settings :name-x-2)))
(is (= 1 @eval-count))
(testing "Update a computed value when a dependent value changes"
(d/transact! [[:db/add :db/settings :name "PI:NAME:<NAME>END_PI"]])
(is (= "LilyLily" (d/get :db/settings :name-x-2)))
(is (= 2 @eval-count)))
(testing "Change a computed value"
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(apply str (interpose " - " (take 2 (repeat (d/get :db/settings :name))))))
(is (= "PI:NAME:<NAME>END_PI - PI:NAME:<NAME>END_PI" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "PI:NAME:<NAME>END_PI"]])
(is (= "PI:NAME:<NAME>END_PI - PI:NAME:<NAME>END_PI" (d/get :db/settings :name-x-2))))
(testing "If a computed property references itself, does not cause loop"
;; TODO
;; model a proper computed-value graph to avoid cycles
;; supply prev-value as `this`?
(d/compute! [:db/settings :name-x-2]
(swap! eval-count inc)
(str (d/get :db/settings :name-x-2) " x " (d/get :db/settings :name)))
(is (= "PI:NAME:<NAME>END_PI - PI:NAME:<NAME>END_PI x PI:NAME:<NAME>END_PI" (d/get :db/settings :name-x-2)))
(d/transact! [[:db/add :db/settings :name "Wow"]])
(is (= "PI:NAME:<NAME>END_PI - MarPI:NAME:<NAME>END_PI x Marvin x Wow" (d/get :db/settings :name-x-2))))
(testing "Clear a computed value"
(d/compute! [:db/settings :name-x-2] false)
(d/transact! [[:db/add :db/settings :name "PI:NAME:<NAME>END_PIonica"]])
(is (= 6 @eval-count)))))
|
[
{
"context": "r)))))\n\n(def santa-path (let [r (reader \"D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt\")]\n (se",
"end": 918,
"score": 0.4776507318019867,
"start": 912,
"tag": "NAME",
"value": "thomas"
},
{
"context": "\n(def santa-path (let [r (reader \"D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt\")]\n (set (re",
"end": 923,
"score": 0.4960594177246094,
"start": 919,
"tag": "NAME",
"value": "ribo"
}
] |
day3.clj
|
tharibo/adventofcode
| 0 |
(use 'clojure.java.io)
(defn walk-left [[x y]]
[(dec x) y])
(defn walk-right [[x y]]
[(inc x) y])
(defn walk-up [[x y]]
[x (dec y)])
(defn walk-down [[x y]]
[x (inc y)])
(defn- walk [path step]
(conj (seq path) (let [last-pos (first path)]
(cond (= step \<) (walk-left last-pos)
(= step \>) (walk-right last-pos)
(= step \^) (walk-up last-pos)
(= step \v) (walk-down last-pos)
:default last-pos))))
(walk [[0 0]] \v)
(reduce walk [[0 0]] '(\^ \^ \< \<))
(defn char-seq
[^java.io.Reader rdr]
(let [chr (.read rdr)]
(if (> chr 0)
(cons (char chr) (lazy-seq (char-seq rdr))))))
(let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(count (set (reduce walk [[0 0]] (char-seq r)))))
(def santa-path (let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (even? %1) %2) (char-seq r))))))
(def robo-santa-path (let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (odd? %1) %2) (char-seq r))))))
(count (clojure.set/union santa-path robo-santa-path))
|
79836
|
(use 'clojure.java.io)
(defn walk-left [[x y]]
[(dec x) y])
(defn walk-right [[x y]]
[(inc x) y])
(defn walk-up [[x y]]
[x (dec y)])
(defn walk-down [[x y]]
[x (inc y)])
(defn- walk [path step]
(conj (seq path) (let [last-pos (first path)]
(cond (= step \<) (walk-left last-pos)
(= step \>) (walk-right last-pos)
(= step \^) (walk-up last-pos)
(= step \v) (walk-down last-pos)
:default last-pos))))
(walk [[0 0]] \v)
(reduce walk [[0 0]] '(\^ \^ \< \<))
(defn char-seq
[^java.io.Reader rdr]
(let [chr (.read rdr)]
(if (> chr 0)
(cons (char chr) (lazy-seq (char-seq rdr))))))
(let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(count (set (reduce walk [[0 0]] (char-seq r)))))
(def santa-path (let [r (reader "D:/users/<NAME>.<NAME>/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (even? %1) %2) (char-seq r))))))
(def robo-santa-path (let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (odd? %1) %2) (char-seq r))))))
(count (clojure.set/union santa-path robo-santa-path))
| true |
(use 'clojure.java.io)
(defn walk-left [[x y]]
[(dec x) y])
(defn walk-right [[x y]]
[(inc x) y])
(defn walk-up [[x y]]
[x (dec y)])
(defn walk-down [[x y]]
[x (inc y)])
(defn- walk [path step]
(conj (seq path) (let [last-pos (first path)]
(cond (= step \<) (walk-left last-pos)
(= step \>) (walk-right last-pos)
(= step \^) (walk-up last-pos)
(= step \v) (walk-down last-pos)
:default last-pos))))
(walk [[0 0]] \v)
(reduce walk [[0 0]] '(\^ \^ \< \<))
(defn char-seq
[^java.io.Reader rdr]
(let [chr (.read rdr)]
(if (> chr 0)
(cons (char chr) (lazy-seq (char-seq rdr))))))
(let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(count (set (reduce walk [[0 0]] (char-seq r)))))
(def santa-path (let [r (reader "D:/users/PI:NAME:<NAME>END_PI.PI:NAME:<NAME>END_PI/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (even? %1) %2) (char-seq r))))))
(def robo-santa-path (let [r (reader "D:/users/thomas.ribo/GitRepos/adventofcode/day3.input.txt")]
(set (reduce walk [[0 0]] (keep-indexed #(if (odd? %1) %2) (char-seq r))))))
(count (clojure.set/union santa-path robo-santa-path))
|
[
{
"context": ";; Copyright 2013-2016 Andrey Antukh <[email protected]>\n;;\n;; Licensed under the Apache Li",
"end": 36,
"score": 0.9998781085014343,
"start": 23,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright 2013-2016 Andrey Antukh <[email protected]>\n;;\n;; Licensed under the Apache License, Version",
"end": 50,
"score": 0.9999309778213501,
"start": 38,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/buddy/auth/protocols.clj
|
eipplusone/buddy-auth
| 292 |
;; Copyright 2013-2016 Andrey Antukh <[email protected]>
;;
;; 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.auth.protocols
"Main authentication and authorization abstractions
defined as protocols.")
(defprotocol IAuthentication
"Protocol that defines unified workflow steps for
all authentication backends."
(-parse [_ request]
"Parse token from the request. If it returns `nil`
the `authenticate` phase will be skipped and the
handler will be called directly.")
(-authenticate [_ request data]
"Given a request and parsed data (from previous step),
try to authenticate this data.
If this method returns not nil value, the request
will be considered authenticated and the value will
be attached to request under `:identity` attribute."))
(defprotocol IAuthorization
"Protocol that defines unified workflow steps for
authorization exceptions."
(-handle-unauthorized [_ request metadata]
"This function is executed when a `NotAuthorizedException`
exception is intercepted by authorization wrapper.
It should return a valid ring response."))
(defprotocol IAuthorizationdError
"Abstraction that allows the user to extend the exception
based authorization system with own types."
(-get-error-data [_] "Get error information."))
|
72911
|
;; Copyright 2013-2016 <NAME> <<EMAIL>>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns buddy.auth.protocols
"Main authentication and authorization abstractions
defined as protocols.")
(defprotocol IAuthentication
"Protocol that defines unified workflow steps for
all authentication backends."
(-parse [_ request]
"Parse token from the request. If it returns `nil`
the `authenticate` phase will be skipped and the
handler will be called directly.")
(-authenticate [_ request data]
"Given a request and parsed data (from previous step),
try to authenticate this data.
If this method returns not nil value, the request
will be considered authenticated and the value will
be attached to request under `:identity` attribute."))
(defprotocol IAuthorization
"Protocol that defines unified workflow steps for
authorization exceptions."
(-handle-unauthorized [_ request metadata]
"This function is executed when a `NotAuthorizedException`
exception is intercepted by authorization wrapper.
It should return a valid ring response."))
(defprotocol IAuthorizationdError
"Abstraction that allows the user to extend the exception
based authorization system with own types."
(-get-error-data [_] "Get error information."))
| true |
;; Copyright 2013-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns buddy.auth.protocols
"Main authentication and authorization abstractions
defined as protocols.")
(defprotocol IAuthentication
"Protocol that defines unified workflow steps for
all authentication backends."
(-parse [_ request]
"Parse token from the request. If it returns `nil`
the `authenticate` phase will be skipped and the
handler will be called directly.")
(-authenticate [_ request data]
"Given a request and parsed data (from previous step),
try to authenticate this data.
If this method returns not nil value, the request
will be considered authenticated and the value will
be attached to request under `:identity` attribute."))
(defprotocol IAuthorization
"Protocol that defines unified workflow steps for
authorization exceptions."
(-handle-unauthorized [_ request metadata]
"This function is executed when a `NotAuthorizedException`
exception is intercepted by authorization wrapper.
It should return a valid ring response."))
(defprotocol IAuthorizationdError
"Abstraction that allows the user to extend the exception
based authorization system with own types."
(-get-error-data [_] "Get error information."))
|
[
{
"context": "hres\")\n punctuation (get-words \"Nächster \\\"Charlie Hebdo\\\" wieder mit Mohammed-Karikaturen\")]\n (testing",
"end": 640,
"score": 0.9997159838676453,
"start": 627,
"tag": "NAME",
"value": "Charlie Hebdo"
},
{
"context": "(testing\n (let [words (get-words \"Nächster \\\"Charlie Hebdo\\\" wieder mit Mohammed-Karikaturen\")]\n (is ",
"end": 998,
"score": 0.999394416809082,
"start": 985,
"tag": "NAME",
"value": "Charlie Hebdo"
},
{
"context": "is (= (noun-sub-seqs words)\n (list \"Nächster\" \"Charlie\" \"Hebdo\"\n \"Nächster",
"end": 1103,
"score": 0.9920075535774231,
"start": 1095,
"tag": "NAME",
"value": "Nächster"
},
{
"context": "-sub-seqs words)\n (list \"Nächster\" \"Charlie\" \"Hebdo\"\n \"Nächster Charlie\"\n",
"end": 1113,
"score": 0.9996942281723022,
"start": 1106,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "words)\n (list \"Nächster\" \"Charlie\" \"Hebdo\"\n \"Nächster Charlie\"\n ",
"end": 1121,
"score": 0.9990290999412537,
"start": 1116,
"tag": "NAME",
"value": "Hebdo"
},
{
"context": "Nächster\" \"Charlie\" \"Hebdo\"\n \"Nächster Charlie\"\n \"Charlie Hebdo\"\n ",
"end": 1161,
"score": 0.9845258593559265,
"start": 1145,
"tag": "NAME",
"value": "Nächster Charlie"
},
{
"context": " \"Nächster Charlie\"\n \"Charlie Hebdo\"\n \"Nächster Charlie Hebdo\"\n ",
"end": 1198,
"score": 0.9998378753662109,
"start": 1185,
"tag": "NAME",
"value": "Charlie Hebdo"
},
{
"context": " \"Charlie Hebdo\"\n \"Nächster Charlie Hebdo\"\n \"Mohammed\" \"K",
"end": 1230,
"score": 0.6869232654571533,
"start": 1222,
"tag": "NAME",
"value": "Nächster"
},
{
"context": " \"Charlie Hebdo\"\n \"Nächster Charlie Hebdo\"\n \"Mohammed\" \"Karikaturen\"\n ",
"end": 1244,
"score": 0.9975358843803406,
"start": 1231,
"tag": "NAME",
"value": "Charlie Hebdo"
}
] |
test/time_slip/text_test.clj
|
BrackCurly/time-slip
| 0 |
(ns time-slip.text-test
(:require [clojure.test :refer :all]
[time-slip.text :refer :all]))
(deftest get-words-test
(testing "split string into words stop-words and seperators"
(is (= (get-words "Die Taucher bergen Stimmenrekorder der AirAsia-Maschine")
'(["Die" :stop] ["Taucher" :noun] ["bergen" :stop] ["Stimmenrekorder" :noun]
["der" :stop] ["AirAsia" :noun] ["-" :punctuation] ["Maschine" :noun])))))
(deftest noun-seqs-test
(let [headline (get-words " \"Zentraler Kampfbegriff\" - \"Lügenpresse\" ist Unwort des Jahres")
punctuation (get-words "Nächster \"Charlie Hebdo\" wieder mit Mohammed-Karikaturen")]
(testing
(is (= (noun-seqs headline)
(list '(["Zentraler" :noun] ["Kampfbegriff" :noun] ["Lügenpresse" :noun])
'(["Unwort" :noun])
'(["Jahres" :noun])))))))
(deftest noun-sub-seqs-test
(testing
(let [words (get-words "Nächster \"Charlie Hebdo\" wieder mit Mohammed-Karikaturen")]
(is (= (noun-sub-seqs words)
(list "Nächster" "Charlie" "Hebdo"
"Nächster Charlie"
"Charlie Hebdo"
"Nächster Charlie Hebdo"
"Mohammed" "Karikaturen"
"Mohammed - Karikaturen"))))))
|
12614
|
(ns time-slip.text-test
(:require [clojure.test :refer :all]
[time-slip.text :refer :all]))
(deftest get-words-test
(testing "split string into words stop-words and seperators"
(is (= (get-words "Die Taucher bergen Stimmenrekorder der AirAsia-Maschine")
'(["Die" :stop] ["Taucher" :noun] ["bergen" :stop] ["Stimmenrekorder" :noun]
["der" :stop] ["AirAsia" :noun] ["-" :punctuation] ["Maschine" :noun])))))
(deftest noun-seqs-test
(let [headline (get-words " \"Zentraler Kampfbegriff\" - \"Lügenpresse\" ist Unwort des Jahres")
punctuation (get-words "Nächster \"<NAME>\" wieder mit Mohammed-Karikaturen")]
(testing
(is (= (noun-seqs headline)
(list '(["Zentraler" :noun] ["Kampfbegriff" :noun] ["Lügenpresse" :noun])
'(["Unwort" :noun])
'(["Jahres" :noun])))))))
(deftest noun-sub-seqs-test
(testing
(let [words (get-words "Nächster \"<NAME>\" wieder mit Mohammed-Karikaturen")]
(is (= (noun-sub-seqs words)
(list "<NAME>" "<NAME>" "<NAME>"
"<NAME>"
"<NAME>"
"<NAME> <NAME>"
"Mohammed" "Karikaturen"
"Mohammed - Karikaturen"))))))
| true |
(ns time-slip.text-test
(:require [clojure.test :refer :all]
[time-slip.text :refer :all]))
(deftest get-words-test
(testing "split string into words stop-words and seperators"
(is (= (get-words "Die Taucher bergen Stimmenrekorder der AirAsia-Maschine")
'(["Die" :stop] ["Taucher" :noun] ["bergen" :stop] ["Stimmenrekorder" :noun]
["der" :stop] ["AirAsia" :noun] ["-" :punctuation] ["Maschine" :noun])))))
(deftest noun-seqs-test
(let [headline (get-words " \"Zentraler Kampfbegriff\" - \"Lügenpresse\" ist Unwort des Jahres")
punctuation (get-words "Nächster \"PI:NAME:<NAME>END_PI\" wieder mit Mohammed-Karikaturen")]
(testing
(is (= (noun-seqs headline)
(list '(["Zentraler" :noun] ["Kampfbegriff" :noun] ["Lügenpresse" :noun])
'(["Unwort" :noun])
'(["Jahres" :noun])))))))
(deftest noun-sub-seqs-test
(testing
(let [words (get-words "Nächster \"PI:NAME:<NAME>END_PI\" wieder mit Mohammed-Karikaturen")]
(is (= (noun-sub-seqs words)
(list "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"
"Mohammed" "Karikaturen"
"Mohammed - Karikaturen"))))))
|
[
{
"context": ";=> #'chapter01.src.chapter01.defns/hello\n(hello \"Nico\")\n;;=> \"Hello world Nico !\"\n(hello \"Makoto\")\n;;=>",
"end": 138,
"score": 0.9946681261062622,
"start": 134,
"tag": "NAME",
"value": "Nico"
},
{
"context": "ter01.defns/hello\n(hello \"Nico\")\n;;=> \"Hello world Nico !\"\n(hello \"Makoto\")\n;;=> \"Hello world Makoto !\"\n(",
"end": 163,
"score": 0.9936089515686035,
"start": 159,
"tag": "NAME",
"value": "Nico"
},
{
"context": "\n(hello \"Nico\")\n;;=> \"Hello world Nico !\"\n(hello \"Makoto\")\n;;=> \"Hello world Makoto !\"\n(defn simple-adder ",
"end": 181,
"score": 0.9968175292015076,
"start": 175,
"tag": "NAME",
"value": "Makoto"
},
{
"context": "o world Nico !\"\n(hello \"Makoto\")\n;;=> \"Hello world Makoto !\"\n(defn simple-adder [x y]\n (+ x y)\n )\n;;=> #'",
"end": 208,
"score": 0.9609352946281433,
"start": 202,
"tag": "NAME",
"value": "Makoto"
}
] |
Chapter 01 Code/chapter01/src/chapter01/defns.clj
|
PacktPublishing/Clojure-Programming-Cookbook
| 14 |
(ns chapter01.src.chapter01.defns)
(defn hello [s]
(str "Hello world " s " !"))
;;=> #'chapter01.src.chapter01.defns/hello
(hello "Nico")
;;=> "Hello world Nico !"
(hello "Makoto")
;;=> "Hello world Makoto !"
(defn simple-adder [x y]
(+ x y)
)
;;=> #'chapter01.src.chapter01.defns/simple-adder
(simple-adder 2 3)
;;=> 5
(defn advanced-adder [x & rest]
(apply + (conj rest x))
)
;;=> #'chapter01.src.chapter01.defns/advanced-adder
(advanced-adder 1 2 3 4 5)
;;=> 15
(defn multi-arity-hello
([] (hello "you"))
([name] (str "Hello World " name " !")))
;;=> #'chapter01.src.chapter01.defns/multi-arity-hello
(multi-arity-hello)
;;=> Hello World you !
(multi-arity-hello "Nico")
;;=> Hello World Nico !
(defn make-product
[serial &
{:keys [product-name price description]
:or [product-name "" price nil description "no description"]}
]
{:serial-no serial :product-name product-name
:price price :description description}
)
;;=> #'chapter01.src.chapter01.defns/make-product
(make-product "0000-0011"
:product-name "personal-computer"
:price 1000
:description "This is a high performance note book"
)
;;=> {:serial-no "0000-0011",
;;=> :product-name "personal-computer",
;;=> :price 1000,
;;=> :description "This is a high performance note book"}
(make-product "0000-0011"
:price 1000
)
;;=> {:serial-no "0000-0011", :product-name "", :price 1000, :description "no description !"}
(require '[clojure.math.numeric-tower :as math])
;;=> nil
(math/sqrt -10)
;;=> NaN
(defn pre-and-post-sqrt [x]
{:pre [(pos? x)]
:post [(< % 10)]}
(math/sqrt x))
;;=> #'chapter01.src.chapter01.defns/pre-and-post-sqrt
(pre-and-post-sqrt 10)
;;=> 3.1622776601683795
(pre-and-post-sqrt -10)
;;=> AssertionError Assert failed: (pos? x) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(pre-and-post-sqrt 120)
;;=> AssertionError Assert failed: (< % 10) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(defn make-triangle
[no & {:keys [char] :or {char "*"}}]
(loop [x 1]
(when (<= x no)
(dotimes
[n (- no x)] (print " "))
(dotimes
[n
(if (= x 1)
1
(dec (* x 2)))]
(print char))
(print "\n")
(recur (inc x))
)
)
)
;;=> #'chapter01.src.chapter01.defns/make-triangle
(make-triangle 5)
;;=> *
;;=> ***
;;=> *****
;;=> *******
;;=> *********
;;=> nil
(make-triangle 6 :char "x")
;;=> x
;;=> xxx
;;=> xxxxx
;;=> xxxxxxx
;;=> xxxxxxxxx
;;=> xxxxxxxxxxx
(defn pow-py-defn [x] (* x x))
;;=> #'chapter01.src.chapter01.defns/pow-py-defn
(def pow-by-def (fn [x] (* x x)))
;;=> #'chapter01.src.chapter01.defns/pow-by-def
(pow-py-defn 10)
;;=> 100
(pow-by-def 10)
;;=> 100
(require 'clojure.string)
;;=> nil
(clojure.repl/dir clojure.string)
;;=> blank?
;;=> capitalize
;;=> escape
;;=> join
;;=> lower-case
;;=> re-quote-replacement
;;=> replace
;;=> replace-first
;;=> reverse
;;=> split
;;=> split-lines
;;=> trim
;;=> trim-newline
;;=> triml
;;=> trimr
;;=> upper-case
;;=> nil
(clojure.repl/doc clojure.string/trim)
;;=> -------------------------
;;=> clojure.string/trim
;;=> ([s])
;;=> Removes whitespace from both ends of string.
;;=> nil
(clojure.repl/apropos "defn")
;;=> (clojure.core/defn
;;=> clojure.core/defn-
;;=> deps.compliment.v0v2v4.compliment.sources.local-bindings/defn-like-forms
;;=> deps.compliment.v0v2v4.deps.defprecated.v0v1v2.defprecated.core/de
|
35612
|
(ns chapter01.src.chapter01.defns)
(defn hello [s]
(str "Hello world " s " !"))
;;=> #'chapter01.src.chapter01.defns/hello
(hello "<NAME>")
;;=> "Hello world <NAME> !"
(hello "<NAME>")
;;=> "Hello world <NAME> !"
(defn simple-adder [x y]
(+ x y)
)
;;=> #'chapter01.src.chapter01.defns/simple-adder
(simple-adder 2 3)
;;=> 5
(defn advanced-adder [x & rest]
(apply + (conj rest x))
)
;;=> #'chapter01.src.chapter01.defns/advanced-adder
(advanced-adder 1 2 3 4 5)
;;=> 15
(defn multi-arity-hello
([] (hello "you"))
([name] (str "Hello World " name " !")))
;;=> #'chapter01.src.chapter01.defns/multi-arity-hello
(multi-arity-hello)
;;=> Hello World you !
(multi-arity-hello "Nico")
;;=> Hello World Nico !
(defn make-product
[serial &
{:keys [product-name price description]
:or [product-name "" price nil description "no description"]}
]
{:serial-no serial :product-name product-name
:price price :description description}
)
;;=> #'chapter01.src.chapter01.defns/make-product
(make-product "0000-0011"
:product-name "personal-computer"
:price 1000
:description "This is a high performance note book"
)
;;=> {:serial-no "0000-0011",
;;=> :product-name "personal-computer",
;;=> :price 1000,
;;=> :description "This is a high performance note book"}
(make-product "0000-0011"
:price 1000
)
;;=> {:serial-no "0000-0011", :product-name "", :price 1000, :description "no description !"}
(require '[clojure.math.numeric-tower :as math])
;;=> nil
(math/sqrt -10)
;;=> NaN
(defn pre-and-post-sqrt [x]
{:pre [(pos? x)]
:post [(< % 10)]}
(math/sqrt x))
;;=> #'chapter01.src.chapter01.defns/pre-and-post-sqrt
(pre-and-post-sqrt 10)
;;=> 3.1622776601683795
(pre-and-post-sqrt -10)
;;=> AssertionError Assert failed: (pos? x) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(pre-and-post-sqrt 120)
;;=> AssertionError Assert failed: (< % 10) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(defn make-triangle
[no & {:keys [char] :or {char "*"}}]
(loop [x 1]
(when (<= x no)
(dotimes
[n (- no x)] (print " "))
(dotimes
[n
(if (= x 1)
1
(dec (* x 2)))]
(print char))
(print "\n")
(recur (inc x))
)
)
)
;;=> #'chapter01.src.chapter01.defns/make-triangle
(make-triangle 5)
;;=> *
;;=> ***
;;=> *****
;;=> *******
;;=> *********
;;=> nil
(make-triangle 6 :char "x")
;;=> x
;;=> xxx
;;=> xxxxx
;;=> xxxxxxx
;;=> xxxxxxxxx
;;=> xxxxxxxxxxx
(defn pow-py-defn [x] (* x x))
;;=> #'chapter01.src.chapter01.defns/pow-py-defn
(def pow-by-def (fn [x] (* x x)))
;;=> #'chapter01.src.chapter01.defns/pow-by-def
(pow-py-defn 10)
;;=> 100
(pow-by-def 10)
;;=> 100
(require 'clojure.string)
;;=> nil
(clojure.repl/dir clojure.string)
;;=> blank?
;;=> capitalize
;;=> escape
;;=> join
;;=> lower-case
;;=> re-quote-replacement
;;=> replace
;;=> replace-first
;;=> reverse
;;=> split
;;=> split-lines
;;=> trim
;;=> trim-newline
;;=> triml
;;=> trimr
;;=> upper-case
;;=> nil
(clojure.repl/doc clojure.string/trim)
;;=> -------------------------
;;=> clojure.string/trim
;;=> ([s])
;;=> Removes whitespace from both ends of string.
;;=> nil
(clojure.repl/apropos "defn")
;;=> (clojure.core/defn
;;=> clojure.core/defn-
;;=> deps.compliment.v0v2v4.compliment.sources.local-bindings/defn-like-forms
;;=> deps.compliment.v0v2v4.deps.defprecated.v0v1v2.defprecated.core/de
| true |
(ns chapter01.src.chapter01.defns)
(defn hello [s]
(str "Hello world " s " !"))
;;=> #'chapter01.src.chapter01.defns/hello
(hello "PI:NAME:<NAME>END_PI")
;;=> "Hello world PI:NAME:<NAME>END_PI !"
(hello "PI:NAME:<NAME>END_PI")
;;=> "Hello world PI:NAME:<NAME>END_PI !"
(defn simple-adder [x y]
(+ x y)
)
;;=> #'chapter01.src.chapter01.defns/simple-adder
(simple-adder 2 3)
;;=> 5
(defn advanced-adder [x & rest]
(apply + (conj rest x))
)
;;=> #'chapter01.src.chapter01.defns/advanced-adder
(advanced-adder 1 2 3 4 5)
;;=> 15
(defn multi-arity-hello
([] (hello "you"))
([name] (str "Hello World " name " !")))
;;=> #'chapter01.src.chapter01.defns/multi-arity-hello
(multi-arity-hello)
;;=> Hello World you !
(multi-arity-hello "Nico")
;;=> Hello World Nico !
(defn make-product
[serial &
{:keys [product-name price description]
:or [product-name "" price nil description "no description"]}
]
{:serial-no serial :product-name product-name
:price price :description description}
)
;;=> #'chapter01.src.chapter01.defns/make-product
(make-product "0000-0011"
:product-name "personal-computer"
:price 1000
:description "This is a high performance note book"
)
;;=> {:serial-no "0000-0011",
;;=> :product-name "personal-computer",
;;=> :price 1000,
;;=> :description "This is a high performance note book"}
(make-product "0000-0011"
:price 1000
)
;;=> {:serial-no "0000-0011", :product-name "", :price 1000, :description "no description !"}
(require '[clojure.math.numeric-tower :as math])
;;=> nil
(math/sqrt -10)
;;=> NaN
(defn pre-and-post-sqrt [x]
{:pre [(pos? x)]
:post [(< % 10)]}
(math/sqrt x))
;;=> #'chapter01.src.chapter01.defns/pre-and-post-sqrt
(pre-and-post-sqrt 10)
;;=> 3.1622776601683795
(pre-and-post-sqrt -10)
;;=> AssertionError Assert failed: (pos? x) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(pre-and-post-sqrt 120)
;;=> AssertionError Assert failed: (< % 10) user/pre-and-post-sqrt (form-init2377591389478394456.clj:1)
(defn make-triangle
[no & {:keys [char] :or {char "*"}}]
(loop [x 1]
(when (<= x no)
(dotimes
[n (- no x)] (print " "))
(dotimes
[n
(if (= x 1)
1
(dec (* x 2)))]
(print char))
(print "\n")
(recur (inc x))
)
)
)
;;=> #'chapter01.src.chapter01.defns/make-triangle
(make-triangle 5)
;;=> *
;;=> ***
;;=> *****
;;=> *******
;;=> *********
;;=> nil
(make-triangle 6 :char "x")
;;=> x
;;=> xxx
;;=> xxxxx
;;=> xxxxxxx
;;=> xxxxxxxxx
;;=> xxxxxxxxxxx
(defn pow-py-defn [x] (* x x))
;;=> #'chapter01.src.chapter01.defns/pow-py-defn
(def pow-by-def (fn [x] (* x x)))
;;=> #'chapter01.src.chapter01.defns/pow-by-def
(pow-py-defn 10)
;;=> 100
(pow-by-def 10)
;;=> 100
(require 'clojure.string)
;;=> nil
(clojure.repl/dir clojure.string)
;;=> blank?
;;=> capitalize
;;=> escape
;;=> join
;;=> lower-case
;;=> re-quote-replacement
;;=> replace
;;=> replace-first
;;=> reverse
;;=> split
;;=> split-lines
;;=> trim
;;=> trim-newline
;;=> triml
;;=> trimr
;;=> upper-case
;;=> nil
(clojure.repl/doc clojure.string/trim)
;;=> -------------------------
;;=> clojure.string/trim
;;=> ([s])
;;=> Removes whitespace from both ends of string.
;;=> nil
(clojure.repl/apropos "defn")
;;=> (clojure.core/defn
;;=> clojure.core/defn-
;;=> deps.compliment.v0v2v4.compliment.sources.local-bindings/defn-like-forms
;;=> deps.compliment.v0v2v4.deps.defprecated.v0v1v2.defprecated.core/de
|
[
{
"context": "(def emp1 (GeneratedUtils/createEmployee \"12345\" \"Jhon\" (Integer. 2000)))\n(GeneratedUtils/pPrint emp1)\n(",
"end": 957,
"score": 0.9997187852859497,
"start": 953,
"tag": "NAME",
"value": "Jhon"
}
] |
src/org/apache/gora/clojure/gora_clj.clj
|
renato2099/GoraJython
| 1 |
(comment 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. )
(import '(org.apache.gora.jython.binding SimpleBinding))
(import '(org.apache.gora.utils GeneratedUtils))
(def emp1 (GeneratedUtils/createEmployee "12345" "Jhon" (Integer. 2000)))
(GeneratedUtils/pPrint emp1)
(println (GeneratedUtils/pPrint emp1))
(def h (new SimpleBinding "cassandra", "java.lang.String", "org.apache.gora.examples.generated.Employee"))
(. h put "12345" emp1)
(. h flush)
(def emp2 (. h get "12345"))
(println (GeneratedUtils/pPrint emp2))
(. h close)
|
57107
|
(comment 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. )
(import '(org.apache.gora.jython.binding SimpleBinding))
(import '(org.apache.gora.utils GeneratedUtils))
(def emp1 (GeneratedUtils/createEmployee "12345" "<NAME>" (Integer. 2000)))
(GeneratedUtils/pPrint emp1)
(println (GeneratedUtils/pPrint emp1))
(def h (new SimpleBinding "cassandra", "java.lang.String", "org.apache.gora.examples.generated.Employee"))
(. h put "12345" emp1)
(. h flush)
(def emp2 (. h get "12345"))
(println (GeneratedUtils/pPrint emp2))
(. h close)
| true |
(comment 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. )
(import '(org.apache.gora.jython.binding SimpleBinding))
(import '(org.apache.gora.utils GeneratedUtils))
(def emp1 (GeneratedUtils/createEmployee "12345" "PI:NAME:<NAME>END_PI" (Integer. 2000)))
(GeneratedUtils/pPrint emp1)
(println (GeneratedUtils/pPrint emp1))
(def h (new SimpleBinding "cassandra", "java.lang.String", "org.apache.gora.examples.generated.Employee"))
(. h put "12345" emp1)
(. h flush)
(def emp2 (. h get "12345"))
(println (GeneratedUtils/pPrint emp2))
(. h close)
|
[
{
"context": "font-awesome/5.15.4/css/all.min.css\\\" integrity=\\\"sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==\\\" crossorigin=\\\"anonymous\\\" referrerpolicy=\\\"no-r",
"end": 5256,
"score": 0.9995859861373901,
"start": 5161,
"tag": "KEY",
"value": "sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
}
] |
handlers/dashboard.cljs
|
cyppan/simple-site-analytics
| 19 |
(ns statistics
(:require [promesa.core :as p]
[reagent.dom.server :as srv]
["@aws-sdk/client-dynamodb" :as dynamo]
["date-fns" :as date-fns]
["crypto" :as crypto]))
(def dynamo-client (delay (dynamo/DynamoDBClient. #js{:region "eu-west-3"})))
(defn last-7-days
"get the last 7 days as yyyy-MM-dd strings"
[]
(for [day (->> (js/Date.)
(iterate #(date-fns/subDays % 1))
(take 7)
(reverse))]
(date-fns/format day "yyyy-MM-dd")))
(defn -parse-dynamo-item
"{:day {:S \"2021-01-30\"} :views {:N 3}}
=>
{:day \"2021-01-30 \" :views 3}"
[item]
(->> item
(map (fn [[k v]]
[k (case (-> v first key)
:S (-> v first val)
:N (-> v first val js/parseInt))]))
(into {})))
;; https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-dynamodb/classes/querycommand.html
(defn fetch-last-7-days-statistics
"returns [{day url views}]"
[]
(p/let [items (js/Promise.all
(for [day (last-7-days)]
(p/let [resp (.send @dynamo-client
(dynamo/QueryCommand.
(clj->js {:TableName "SiteStatistics"
:KeyConditionExpression "#day = :day"
:ExpressionAttributeNames {"#day" "day"}
:ExpressionAttributeValues {":day" {:S day}}})))
resp (js->clj resp :keywordize-keys true)
items (->> (:Items resp)
(map -parse-dynamo-item))]
(or (seq items) [{:day day :views 0}]))))]
(into [] cat items)))
(defn counter-cards [stat-rows]
(let [views (reduce + 0 (map :views stat-rows))
views-slack (reduce + 0 (map :views_slack stat-rows))
views-twitter (reduce + 0 (map :views_twitter stat-rows))]
[:nav.level.is-mobile
[:div.level-item.has-text-centered
[:div
[:p.heading "Total views"]
[:p.title views]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Slack"]
[:p.title views-slack]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Twitter"]
[:p.title views-twitter]]]]))
;; https://vega.github.io/vega-lite/usage/embed.html
(defn views-bar-chart [stat-rows]
(let [data (->> stat-rows
(group-by :day)
(map (fn [[day rows]]
{:day day
:views (reduce + 0 (map :views rows))}))
(sort-by :day <))
spec (clj->js {:$schema "https://vega.github.io/schema/vega-lite/v5.json"
:data {:values data}
:mark {:type "bar"}
:width "container"
:height 300
:encoding {:x {:field "day"
:type "nominal"
:axis {:labelAngle -45}}
:y {:field "views"
:type "quantitative"}}})
id (str "div-" (.toString (crypto/randomBytes 16) "hex"))
raw (str "<div id=\"" id "\" style=\"width:100%;height:300px\"></div>"
"<script type=\"text/javascript\">"
"vegaEmbed ('#" id "', JSON.parse('" (js/JSON.stringify spec) "'));"
"</script>")]
[:div {:dangerouslySetInnerHTML {:__html raw}}]))
(defn top-urls-table [stat-rows]
(let [top-urls (->> stat-rows
(filter :url)
(group-by :url)
(map (fn [[url rows]]
{:url url
:views (reduce + 0 (map :views rows))
:views_slack (reduce + 0 (map :views_slack rows))
:views_twitter (reduce + 0 (map :views_twitter rows))}))
(sort-by :views >))]
[:table.table.is-fullwidth.is-hoverable.is-striped
[:thead>tr
[:th "Rank"]
[:th "URL"]
[:th "Views"]
[:th "Slack"]
[:th "Twitter"]]
[:tbody
(for [[i {:keys [url views views_slack views_twitter]}] (map-indexed vector top-urls)]
[:tr
[:th {:style {:width "20px"}} (inc i)]
[:td [:a {:href url} url]]
[:td {:style {:width "20px"}} views]
[:td {:style {:width "20px"}} views_slack]
[:td {:style {:width "20px"}} views_twitter]])]]))
(defn wrap-template [hiccup]
(str "<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css\">
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css\" integrity=\"sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />
<link rel=\"icon\" type=\"image/png\" href=\"data:image/png;base64,iVBORw0KGgo=\">
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<title>Site Analytics</title>
</head>
<body>
<section class=\"hero is-link block\">
<div class=\"hero-body has-text-centered\">
<p class=\"title\" style=\"vertical-align:baseline\">
<span class=\"icon\">
<i class=\"fas fa-chart-pie\"></i>
</span>
Site Analytics
</p>
<p class=\"subtitle\">last 7 days</p>
</div>
</section>
<div class=\"container is-max-desktop\">
"
(srv/render-to-static-markup hiccup)
" </div>
</body>
</html>"))
(defn handler [event _ctx]
(p/let [stat-rows (fetch-last-7-days-statistics)]
(clj->js
{:statusCode 200
:headers {"Content-Type" "text/html"}
:body (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])})))
(comment
(defmacro defp [binding expr]
`(-> ~expr (.then (fn [val] (def ~binding val))) (.catch (fn [err] (def ~binding err)))))
(defp stat-rows (fetch-last-7-days-statistics))
stat-rows
(println (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])))
;; exports
#js {:handler handler}
|
75243
|
(ns statistics
(:require [promesa.core :as p]
[reagent.dom.server :as srv]
["@aws-sdk/client-dynamodb" :as dynamo]
["date-fns" :as date-fns]
["crypto" :as crypto]))
(def dynamo-client (delay (dynamo/DynamoDBClient. #js{:region "eu-west-3"})))
(defn last-7-days
"get the last 7 days as yyyy-MM-dd strings"
[]
(for [day (->> (js/Date.)
(iterate #(date-fns/subDays % 1))
(take 7)
(reverse))]
(date-fns/format day "yyyy-MM-dd")))
(defn -parse-dynamo-item
"{:day {:S \"2021-01-30\"} :views {:N 3}}
=>
{:day \"2021-01-30 \" :views 3}"
[item]
(->> item
(map (fn [[k v]]
[k (case (-> v first key)
:S (-> v first val)
:N (-> v first val js/parseInt))]))
(into {})))
;; https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-dynamodb/classes/querycommand.html
(defn fetch-last-7-days-statistics
"returns [{day url views}]"
[]
(p/let [items (js/Promise.all
(for [day (last-7-days)]
(p/let [resp (.send @dynamo-client
(dynamo/QueryCommand.
(clj->js {:TableName "SiteStatistics"
:KeyConditionExpression "#day = :day"
:ExpressionAttributeNames {"#day" "day"}
:ExpressionAttributeValues {":day" {:S day}}})))
resp (js->clj resp :keywordize-keys true)
items (->> (:Items resp)
(map -parse-dynamo-item))]
(or (seq items) [{:day day :views 0}]))))]
(into [] cat items)))
(defn counter-cards [stat-rows]
(let [views (reduce + 0 (map :views stat-rows))
views-slack (reduce + 0 (map :views_slack stat-rows))
views-twitter (reduce + 0 (map :views_twitter stat-rows))]
[:nav.level.is-mobile
[:div.level-item.has-text-centered
[:div
[:p.heading "Total views"]
[:p.title views]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Slack"]
[:p.title views-slack]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Twitter"]
[:p.title views-twitter]]]]))
;; https://vega.github.io/vega-lite/usage/embed.html
(defn views-bar-chart [stat-rows]
(let [data (->> stat-rows
(group-by :day)
(map (fn [[day rows]]
{:day day
:views (reduce + 0 (map :views rows))}))
(sort-by :day <))
spec (clj->js {:$schema "https://vega.github.io/schema/vega-lite/v5.json"
:data {:values data}
:mark {:type "bar"}
:width "container"
:height 300
:encoding {:x {:field "day"
:type "nominal"
:axis {:labelAngle -45}}
:y {:field "views"
:type "quantitative"}}})
id (str "div-" (.toString (crypto/randomBytes 16) "hex"))
raw (str "<div id=\"" id "\" style=\"width:100%;height:300px\"></div>"
"<script type=\"text/javascript\">"
"vegaEmbed ('#" id "', JSON.parse('" (js/JSON.stringify spec) "'));"
"</script>")]
[:div {:dangerouslySetInnerHTML {:__html raw}}]))
(defn top-urls-table [stat-rows]
(let [top-urls (->> stat-rows
(filter :url)
(group-by :url)
(map (fn [[url rows]]
{:url url
:views (reduce + 0 (map :views rows))
:views_slack (reduce + 0 (map :views_slack rows))
:views_twitter (reduce + 0 (map :views_twitter rows))}))
(sort-by :views >))]
[:table.table.is-fullwidth.is-hoverable.is-striped
[:thead>tr
[:th "Rank"]
[:th "URL"]
[:th "Views"]
[:th "Slack"]
[:th "Twitter"]]
[:tbody
(for [[i {:keys [url views views_slack views_twitter]}] (map-indexed vector top-urls)]
[:tr
[:th {:style {:width "20px"}} (inc i)]
[:td [:a {:href url} url]]
[:td {:style {:width "20px"}} views]
[:td {:style {:width "20px"}} views_slack]
[:td {:style {:width "20px"}} views_twitter]])]]))
(defn wrap-template [hiccup]
(str "<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css\">
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css\" integrity=\"<KEY>\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />
<link rel=\"icon\" type=\"image/png\" href=\"data:image/png;base64,iVBORw0KGgo=\">
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<title>Site Analytics</title>
</head>
<body>
<section class=\"hero is-link block\">
<div class=\"hero-body has-text-centered\">
<p class=\"title\" style=\"vertical-align:baseline\">
<span class=\"icon\">
<i class=\"fas fa-chart-pie\"></i>
</span>
Site Analytics
</p>
<p class=\"subtitle\">last 7 days</p>
</div>
</section>
<div class=\"container is-max-desktop\">
"
(srv/render-to-static-markup hiccup)
" </div>
</body>
</html>"))
(defn handler [event _ctx]
(p/let [stat-rows (fetch-last-7-days-statistics)]
(clj->js
{:statusCode 200
:headers {"Content-Type" "text/html"}
:body (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])})))
(comment
(defmacro defp [binding expr]
`(-> ~expr (.then (fn [val] (def ~binding val))) (.catch (fn [err] (def ~binding err)))))
(defp stat-rows (fetch-last-7-days-statistics))
stat-rows
(println (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])))
;; exports
#js {:handler handler}
| true |
(ns statistics
(:require [promesa.core :as p]
[reagent.dom.server :as srv]
["@aws-sdk/client-dynamodb" :as dynamo]
["date-fns" :as date-fns]
["crypto" :as crypto]))
(def dynamo-client (delay (dynamo/DynamoDBClient. #js{:region "eu-west-3"})))
(defn last-7-days
"get the last 7 days as yyyy-MM-dd strings"
[]
(for [day (->> (js/Date.)
(iterate #(date-fns/subDays % 1))
(take 7)
(reverse))]
(date-fns/format day "yyyy-MM-dd")))
(defn -parse-dynamo-item
"{:day {:S \"2021-01-30\"} :views {:N 3}}
=>
{:day \"2021-01-30 \" :views 3}"
[item]
(->> item
(map (fn [[k v]]
[k (case (-> v first key)
:S (-> v first val)
:N (-> v first val js/parseInt))]))
(into {})))
;; https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-dynamodb/classes/querycommand.html
(defn fetch-last-7-days-statistics
"returns [{day url views}]"
[]
(p/let [items (js/Promise.all
(for [day (last-7-days)]
(p/let [resp (.send @dynamo-client
(dynamo/QueryCommand.
(clj->js {:TableName "SiteStatistics"
:KeyConditionExpression "#day = :day"
:ExpressionAttributeNames {"#day" "day"}
:ExpressionAttributeValues {":day" {:S day}}})))
resp (js->clj resp :keywordize-keys true)
items (->> (:Items resp)
(map -parse-dynamo-item))]
(or (seq items) [{:day day :views 0}]))))]
(into [] cat items)))
(defn counter-cards [stat-rows]
(let [views (reduce + 0 (map :views stat-rows))
views-slack (reduce + 0 (map :views_slack stat-rows))
views-twitter (reduce + 0 (map :views_twitter stat-rows))]
[:nav.level.is-mobile
[:div.level-item.has-text-centered
[:div
[:p.heading "Total views"]
[:p.title views]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Slack"]
[:p.title views-slack]]]
[:div.level-item.has-text-centered
[:div
[:p.heading "views from Twitter"]
[:p.title views-twitter]]]]))
;; https://vega.github.io/vega-lite/usage/embed.html
(defn views-bar-chart [stat-rows]
(let [data (->> stat-rows
(group-by :day)
(map (fn [[day rows]]
{:day day
:views (reduce + 0 (map :views rows))}))
(sort-by :day <))
spec (clj->js {:$schema "https://vega.github.io/schema/vega-lite/v5.json"
:data {:values data}
:mark {:type "bar"}
:width "container"
:height 300
:encoding {:x {:field "day"
:type "nominal"
:axis {:labelAngle -45}}
:y {:field "views"
:type "quantitative"}}})
id (str "div-" (.toString (crypto/randomBytes 16) "hex"))
raw (str "<div id=\"" id "\" style=\"width:100%;height:300px\"></div>"
"<script type=\"text/javascript\">"
"vegaEmbed ('#" id "', JSON.parse('" (js/JSON.stringify spec) "'));"
"</script>")]
[:div {:dangerouslySetInnerHTML {:__html raw}}]))
(defn top-urls-table [stat-rows]
(let [top-urls (->> stat-rows
(filter :url)
(group-by :url)
(map (fn [[url rows]]
{:url url
:views (reduce + 0 (map :views rows))
:views_slack (reduce + 0 (map :views_slack rows))
:views_twitter (reduce + 0 (map :views_twitter rows))}))
(sort-by :views >))]
[:table.table.is-fullwidth.is-hoverable.is-striped
[:thead>tr
[:th "Rank"]
[:th "URL"]
[:th "Views"]
[:th "Slack"]
[:th "Twitter"]]
[:tbody
(for [[i {:keys [url views views_slack views_twitter]}] (map-indexed vector top-urls)]
[:tr
[:th {:style {:width "20px"}} (inc i)]
[:td [:a {:href url} url]]
[:td {:style {:width "20px"}} views]
[:td {:style {:width "20px"}} views_slack]
[:td {:style {:width "20px"}} views_twitter]])]]))
(defn wrap-template [hiccup]
(str "<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css\">
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css\" integrity=\"PI:KEY:<KEY>END_PI\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\" />
<link rel=\"icon\" type=\"image/png\" href=\"data:image/png;base64,iVBORw0KGgo=\">
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>
<title>Site Analytics</title>
</head>
<body>
<section class=\"hero is-link block\">
<div class=\"hero-body has-text-centered\">
<p class=\"title\" style=\"vertical-align:baseline\">
<span class=\"icon\">
<i class=\"fas fa-chart-pie\"></i>
</span>
Site Analytics
</p>
<p class=\"subtitle\">last 7 days</p>
</div>
</section>
<div class=\"container is-max-desktop\">
"
(srv/render-to-static-markup hiccup)
" </div>
</body>
</html>"))
(defn handler [event _ctx]
(p/let [stat-rows (fetch-last-7-days-statistics)]
(clj->js
{:statusCode 200
:headers {"Content-Type" "text/html"}
:body (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])})))
(comment
(defmacro defp [binding expr]
`(-> ~expr (.then (fn [val] (def ~binding val))) (.catch (fn [err] (def ~binding err)))))
(defp stat-rows (fetch-last-7-days-statistics))
stat-rows
(println (wrap-template
[:<>
[:div.box
(counter-cards stat-rows)
(views-bar-chart stat-rows)]
[:div.box
[:h1.title.is-3 "Top URLs"]
(top-urls-table stat-rows)]])))
;; exports
#js {:handler handler}
|
[
{
"context": "eck that it \\\"persist\\\"\"\n (let [user {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n",
"end": 245,
"score": 0.999367892742157,
"start": 237,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\\\"\"\n (let [user {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n db-user (db/new-u",
"end": 270,
"score": 0.9999263882637024,
"start": 258,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n db-user (db/new-user! user)\n in-",
"end": 292,
"score": 0.9999265670776367,
"start": 280,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "in-db (db/get-registered-user-by-field :username \"[email protected]\")]\n (testing \"Is the user created, and does th",
"end": 401,
"score": 0.9999266862869263,
"start": 389,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "correct values?\"\n (and\n (is (:username db-user) (:username in-db))\n (is (:email db-user) ",
"end": 525,
"score": 0.6796525120735168,
"start": 518,
"tag": "USERNAME",
"value": "db-user"
},
{
"context": "ser that already exists\"\n (let [user {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n",
"end": 742,
"score": 0.9993558526039124,
"start": 734,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ts\"\n (let [user {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n db-user (db/new-u",
"end": 767,
"score": 0.9999247789382935,
"start": 755,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"}\n db-user (db/new-user! user)]\n (is ",
"end": 789,
"score": 0.9999231100082397,
"start": 777,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "he number is correct\"\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})",
"end": 1163,
"score": 0.9994388818740845,
"start": 1155,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (db/new-user! {:passwo",
"end": 1188,
"score": 0.999923825263977,
"start": 1176,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (db/new-user! {:password \"password\" :usernam",
"end": 1210,
"score": 0.999923050403595,
"start": 1198,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "mail \"[email protected]\"})\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"",
"end": 1250,
"score": 0.999382734298706,
"start": 1242,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (db/new-user! {:passw",
"end": 1276,
"score": 0.9999253153800964,
"start": 1263,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "word \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (db/new-user! {:password \"password\" :usernam",
"end": 1299,
"score": 0.9999270439147949,
"start": 1286,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ail \"[email protected]\"})\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"",
"end": 1339,
"score": 0.9994502067565918,
"start": 1331,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\n (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (is (= 3 (count (db/g",
"end": 1365,
"score": 0.9999222159385681,
"start": 1352,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "word \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n (is (= 3 (count (db/get-all-users)))))\n\n(def",
"end": 1388,
"score": 0.999922513961792,
"start": 1375,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "in the db\"\n (let [user (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})",
"end": 2024,
"score": 0.9994596838951111,
"start": 2016,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "er (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n updated? (db/act",
"end": 2049,
"score": 0.99992436170578,
"start": 2037,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n updated? (db/activate-user (:id user))",
"end": 2071,
"score": 0.9999245405197144,
"start": 2059,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-habit\n (let [user (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})",
"end": 2300,
"score": 0.9994914531707764,
"start": 2292,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "er (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n exercise (db/cre",
"end": 2325,
"score": 0.999914824962616,
"start": 2313,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n exercise (db/create-habit \"exercising\"",
"end": 2347,
"score": 0.9999210238456726,
"start": 2335,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "(setup-db)\n user (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})",
"end": 2742,
"score": 0.9994394779205322,
"start": 2734,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "er (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n exercise (db/cre",
"end": 2767,
"score": 0.9999170303344727,
"start": 2755,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n exercise (db/create-habit \"exercising\"",
"end": 2789,
"score": 0.999921977519989,
"start": 2777,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "in the db\"\n (let [user (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})",
"end": 3174,
"score": 0.9994970560073853,
"start": 3166,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "er (db/new-user! {:password \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n habit1 (db/creat",
"end": 3199,
"score": 0.9999262094497681,
"start": 3187,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sword \"password\" :username \"[email protected]\" :email \"[email protected]\"})\n habit1 (db/create-habit \"exercising\")\n",
"end": 3221,
"score": 0.999923825263977,
"start": 3209,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
groove-api/test/groove/db_test.clj
|
MrLys/vicissitudes
| 1 |
(ns groove.db-test
(:require [clojure.test :refer :all]
[groove.db :as db]
[groove.db-test-utils :refer :all]))
(deftest new-user-test
"Create a new user, check that it \"persist\""
(let [user {:password "password" :username "[email protected]" :email "[email protected]"}
db-user (db/new-user! user)
in-db (db/get-registered-user-by-field :username "[email protected]")]
(testing "Is the user created, and does the user have the correct values?"
(and
(is (:username db-user) (:username in-db))
(is (:email db-user) (:email in-db))
(is (:id db-user) (:id in-db))))))
(deftest new-existing-user-test
"Create a new user that already exists"
(let [user {:password "password" :username "[email protected]" :email "[email protected]"}
db-user (db/new-user! user)]
(is (thrown? org.postgresql.util.PSQLException (db/new-user! user)))))
(deftest get-all-users-empty
"Get all users in empty db and assert the number is correct"
(is (= 0 (count (db/get-all-users)))))
(deftest get-all-users
"Get all users in empty db and assert the number is correct"
(db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
(db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
(db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
(is (= 3 (count (db/get-all-users)))))
(deftest create-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")
in-db (db/get-habit-by-name "exercising")]
(and
(is (= (:name db-habit) (:name in-db)))
(is (= (:id db-habit) (:id in-db))))))
(deftest create-existing-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")]
(is (thrown? org.postgresql.util.PSQLException (db/create-habit "exercising")))))
(deftest activate-user-test
"Create a user and activate it in the db"
(let [user (db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
updated? (db/activate-user (:id user))
db-user (db/get-user (:id user))]
(and (is updated?)
(is (:activated db-user)))))
(deftest create-user-habit
(let [user (db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(and
(is (= (:id exercise) (:habit_id user-habit)))
(is (= (:id user) (:owner_id user-habit))))))
(deftest create-existing-user-habit
"Try to create a user and then the same user-habit twice"
(let [_ (setup-db)
user (db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(is (thrown? org.postgresql.util.PSQLException (db/create-user-habit exercise (:id user))))))
(deftest get-habits-by-userid-test
"Create a user and two habits, assert that the correct values are
stored in the db"
(let [user (db/new-user! {:password "password" :username "[email protected]" :email "[email protected]"})
habit1 (db/create-habit "exercising")
user-habit1 (db/create-user-habit habit1 (:id user))
habit2 (db/create-habit "piano")
user-habit2 (db/create-user-habit habit2 (:id user))
habits (db/get-all-habits-by-user-id (:id user))]
(and
(is (= (count habits) 2))
(is (or (= (:id (nth habits 0)) (:id user-habit1))
(= (:id (nth habits 0)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2))))
(is (or (= (:id (nth habits 1)) (:id user-habit1))
(= (:id (nth habits 1)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2)))))))
(use-fixtures :once once-fixture)
(use-fixtures :each each-fixture)
|
70483
|
(ns groove.db-test
(:require [clojure.test :refer :all]
[groove.db :as db]
[groove.db-test-utils :refer :all]))
(deftest new-user-test
"Create a new user, check that it \"persist\""
(let [user {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"}
db-user (db/new-user! user)
in-db (db/get-registered-user-by-field :username "<EMAIL>")]
(testing "Is the user created, and does the user have the correct values?"
(and
(is (:username db-user) (:username in-db))
(is (:email db-user) (:email in-db))
(is (:id db-user) (:id in-db))))))
(deftest new-existing-user-test
"Create a new user that already exists"
(let [user {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"}
db-user (db/new-user! user)]
(is (thrown? org.postgresql.util.PSQLException (db/new-user! user)))))
(deftest get-all-users-empty
"Get all users in empty db and assert the number is correct"
(is (= 0 (count (db/get-all-users)))))
(deftest get-all-users
"Get all users in empty db and assert the number is correct"
(db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
(db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
(db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
(is (= 3 (count (db/get-all-users)))))
(deftest create-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")
in-db (db/get-habit-by-name "exercising")]
(and
(is (= (:name db-habit) (:name in-db)))
(is (= (:id db-habit) (:id in-db))))))
(deftest create-existing-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")]
(is (thrown? org.postgresql.util.PSQLException (db/create-habit "exercising")))))
(deftest activate-user-test
"Create a user and activate it in the db"
(let [user (db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
updated? (db/activate-user (:id user))
db-user (db/get-user (:id user))]
(and (is updated?)
(is (:activated db-user)))))
(deftest create-user-habit
(let [user (db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(and
(is (= (:id exercise) (:habit_id user-habit)))
(is (= (:id user) (:owner_id user-habit))))))
(deftest create-existing-user-habit
"Try to create a user and then the same user-habit twice"
(let [_ (setup-db)
user (db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(is (thrown? org.postgresql.util.PSQLException (db/create-user-habit exercise (:id user))))))
(deftest get-habits-by-userid-test
"Create a user and two habits, assert that the correct values are
stored in the db"
(let [user (db/new-user! {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"})
habit1 (db/create-habit "exercising")
user-habit1 (db/create-user-habit habit1 (:id user))
habit2 (db/create-habit "piano")
user-habit2 (db/create-user-habit habit2 (:id user))
habits (db/get-all-habits-by-user-id (:id user))]
(and
(is (= (count habits) 2))
(is (or (= (:id (nth habits 0)) (:id user-habit1))
(= (:id (nth habits 0)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2))))
(is (or (= (:id (nth habits 1)) (:id user-habit1))
(= (:id (nth habits 1)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2)))))))
(use-fixtures :once once-fixture)
(use-fixtures :each each-fixture)
| true |
(ns groove.db-test
(:require [clojure.test :refer :all]
[groove.db :as db]
[groove.db-test-utils :refer :all]))
(deftest new-user-test
"Create a new user, check that it \"persist\""
(let [user {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
db-user (db/new-user! user)
in-db (db/get-registered-user-by-field :username "PI:EMAIL:<EMAIL>END_PI")]
(testing "Is the user created, and does the user have the correct values?"
(and
(is (:username db-user) (:username in-db))
(is (:email db-user) (:email in-db))
(is (:id db-user) (:id in-db))))))
(deftest new-existing-user-test
"Create a new user that already exists"
(let [user {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
db-user (db/new-user! user)]
(is (thrown? org.postgresql.util.PSQLException (db/new-user! user)))))
(deftest get-all-users-empty
"Get all users in empty db and assert the number is correct"
(is (= 0 (count (db/get-all-users)))))
(deftest get-all-users
"Get all users in empty db and assert the number is correct"
(db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
(db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
(db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
(is (= 3 (count (db/get-all-users)))))
(deftest create-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")
in-db (db/get-habit-by-name "exercising")]
(and
(is (= (:name db-habit) (:name in-db)))
(is (= (:id db-habit) (:id in-db))))))
(deftest create-existing-habit-test
"Create a habit, verify it in db"
(let [db-habit (db/create-habit "exercising")]
(is (thrown? org.postgresql.util.PSQLException (db/create-habit "exercising")))))
(deftest activate-user-test
"Create a user and activate it in the db"
(let [user (db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
updated? (db/activate-user (:id user))
db-user (db/get-user (:id user))]
(and (is updated?)
(is (:activated db-user)))))
(deftest create-user-habit
(let [user (db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(and
(is (= (:id exercise) (:habit_id user-habit)))
(is (= (:id user) (:owner_id user-habit))))))
(deftest create-existing-user-habit
"Try to create a user and then the same user-habit twice"
(let [_ (setup-db)
user (db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
exercise (db/create-habit "exercising")
user-habit (db/create-user-habit exercise (:id user))]
(is (thrown? org.postgresql.util.PSQLException (db/create-user-habit exercise (:id user))))))
(deftest get-habits-by-userid-test
"Create a user and two habits, assert that the correct values are
stored in the db"
(let [user (db/new-user! {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
habit1 (db/create-habit "exercising")
user-habit1 (db/create-user-habit habit1 (:id user))
habit2 (db/create-habit "piano")
user-habit2 (db/create-user-habit habit2 (:id user))
habits (db/get-all-habits-by-user-id (:id user))]
(and
(is (= (count habits) 2))
(is (or (= (:id (nth habits 0)) (:id user-habit1))
(= (:id (nth habits 0)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2))))
(is (or (= (:id (nth habits 1)) (:id user-habit1))
(= (:id (nth habits 1)) (:id user-habit2))))
(is (or (= (:name (nth habits 0)) (:name habit1))
(= (:name (nth habits 0)) (:name habit2)))))))
(use-fixtures :once once-fixture)
(use-fixtures :each each-fixture)
|
[
{
"context": " :name username\n :password password\n :type \"user\"\n ",
"end": 1157,
"score": 0.999077558517456,
"start": 1149,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " salt salt\n;; :password password\n;; :type \"user\"\n;; ",
"end": 1708,
"score": 0.9991793036460876,
"start": 1700,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :password password)))))\n\n;;(defn set-password [username, password]\n;",
"end": 3000,
"score": 0.5504910349845886,
"start": 2992,
"tag": "PASSWORD",
"value": "password"
}
] |
src/joiner/user.clj
|
jalpedersen/couch-joiner
| 0 |
(ns joiner.user
(:require [clojure.string :as s]
[cemerick.url :as url]
[clojure.data.codec.base64 :as b64]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]
[joiner.admin]))
(def ^:private ^:dynamic *users-db* "_users")
(defn- get-uuid []
(first
(:uuids (http/couchdb-request :get
(database-url "_uuids")))))
(defn- to-hex [byte]
(let [clean-byte (bit-and byte 0xff)
val (Integer/toString clean-byte 16)]
(if (< clean-byte 0x10)
(str "0" val)
val)))
(defn- sha1 [string salt]
(let [bytes (.getBytes (str string salt) "UTF-8")
digester (java.security.MessageDigest/getInstance "SHA1")]
(apply str (map to-hex (.digest digester bytes)))))
(defn create-user [username, password, roles]
"Create a new user with given password and roles."
(clutch/with-db (authenticated-database *users-db*)
(clutch/put-document
{:_id (str "org.couchdb.user:" username)
:name username
:password password
:type "user"
:roles roles})))
;;Sha-1 encoding of password was only required prior to 1.2.0
;;(defn create-user [username, password, roles]
;; "Create a new user with given password and roles."
;; (let [salt (get-uuid)]
;; (with-db (authenticated-database *users-db*)
;; (put-document
;; {:_id (str "org.couchdb.user:" username)
;; :name username
;; password_sha (sha1 password salt)
;; salt salt
;; :password password
;; :type "user"
;; :roles roles}))))
(defn get-user [username]
"Get user from username"
(clutch/with-db (authenticated-database *users-db*)
(clutch/get-document (str "org.couchdb.user:" username))))
(defn- urlencode [string]
(java.net.URLEncoder/encode string "UTF-8"))
(defn authenticate [username, password]
"Seems like something is broken somewhere between here and clj-http for usernames
containing special characters (such as @) - hence these hoops"
(try
(let [url (url/url (assoc (couchdb-instance) :username nil :password nil) "_session")
^bytes auth-bytes (b64/encode (.getBytes (str username ":" password)))
authorization (String. auth-bytes)
headers {"Authorization" (str "Basic " authorization)}]
(let [resp (http/couchdb-request :get url :headers headers)]
(and (:ok resp)
(not (nil? (:name (:userCtx resp)))))))
(catch clojure.lang.ExceptionInfo e
false)))
(defn set-password [username, password]
"Set new password for user"
(let [user (get-user username)]
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document (assoc user
:password password)))))
;;(defn set-password [username, password]
;; "Set new password for user"
;; (let [salt (get-uuid)
;; user (get-user username)]
;; (with-db (authenticated-database *users-db*)
;; (update-document (assoc user
;; :salt salt
;; :password_sha (sha1 password salt))))))
(defn update-user [user]
"Update user along. Typically used when updating roles
and other meta-data"
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document user)))
(defn delete-user [user]
(clutch/with-db (authenticated-database *users-db*)
(clutch/delete-document user)))
(defn delete-private-database [user]
(if-let [db (:userdb user)]
(do
(clutch/delete-database (authenticated-database db))
(update-user (dissoc user :userdb)))))
(defn set-roles [username, roles]
"Set roles for user"
(let [user (get-user username)]
(update-user (assoc user :roles roles))))
(defn- clean-name [name]
(s/replace (s/lower-case name) #"[^a-z0-9\\+]" "\\_" ))
(defn create-private-database [user & [postfix]]
"Create new database for user and store the name
of the new database in the users meta-data"
;;Database name may only contain:
;;lower case letters, numbers, _, $, (, ), +, -, and /
(let [clean-name (clean-name (:name user))
db-name (str "userdb_"
(if (nil? postfix)
clean-name
(str clean-name "_" postfix)))
name {:names [(:name user)]}
acl {:admins name :readers name}]
(try (clutch/create-database (database-url db-name))
(try (do (clutch/with-db (authenticated-database db-name) (security acl))
(update-user (assoc user :userdb db-name)))
;;Should we remove the database
;;if we cannot update the user data?
(catch Exception _
(clutch/delete-database (database-url db-name))))
(catch java.io.IOException _
(create-private-database user
(if (nil? postfix)
0
(+ postfix 1)))))))
|
2139
|
(ns joiner.user
(:require [clojure.string :as s]
[cemerick.url :as url]
[clojure.data.codec.base64 :as b64]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]
[joiner.admin]))
(def ^:private ^:dynamic *users-db* "_users")
(defn- get-uuid []
(first
(:uuids (http/couchdb-request :get
(database-url "_uuids")))))
(defn- to-hex [byte]
(let [clean-byte (bit-and byte 0xff)
val (Integer/toString clean-byte 16)]
(if (< clean-byte 0x10)
(str "0" val)
val)))
(defn- sha1 [string salt]
(let [bytes (.getBytes (str string salt) "UTF-8")
digester (java.security.MessageDigest/getInstance "SHA1")]
(apply str (map to-hex (.digest digester bytes)))))
(defn create-user [username, password, roles]
"Create a new user with given password and roles."
(clutch/with-db (authenticated-database *users-db*)
(clutch/put-document
{:_id (str "org.couchdb.user:" username)
:name username
:password <PASSWORD>
:type "user"
:roles roles})))
;;Sha-1 encoding of password was only required prior to 1.2.0
;;(defn create-user [username, password, roles]
;; "Create a new user with given password and roles."
;; (let [salt (get-uuid)]
;; (with-db (authenticated-database *users-db*)
;; (put-document
;; {:_id (str "org.couchdb.user:" username)
;; :name username
;; password_sha (sha1 password salt)
;; salt salt
;; :password <PASSWORD>
;; :type "user"
;; :roles roles}))))
(defn get-user [username]
"Get user from username"
(clutch/with-db (authenticated-database *users-db*)
(clutch/get-document (str "org.couchdb.user:" username))))
(defn- urlencode [string]
(java.net.URLEncoder/encode string "UTF-8"))
(defn authenticate [username, password]
"Seems like something is broken somewhere between here and clj-http for usernames
containing special characters (such as @) - hence these hoops"
(try
(let [url (url/url (assoc (couchdb-instance) :username nil :password nil) "_session")
^bytes auth-bytes (b64/encode (.getBytes (str username ":" password)))
authorization (String. auth-bytes)
headers {"Authorization" (str "Basic " authorization)}]
(let [resp (http/couchdb-request :get url :headers headers)]
(and (:ok resp)
(not (nil? (:name (:userCtx resp)))))))
(catch clojure.lang.ExceptionInfo e
false)))
(defn set-password [username, password]
"Set new password for user"
(let [user (get-user username)]
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document (assoc user
:password <PASSWORD>)))))
;;(defn set-password [username, password]
;; "Set new password for user"
;; (let [salt (get-uuid)
;; user (get-user username)]
;; (with-db (authenticated-database *users-db*)
;; (update-document (assoc user
;; :salt salt
;; :password_sha (sha1 password salt))))))
(defn update-user [user]
"Update user along. Typically used when updating roles
and other meta-data"
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document user)))
(defn delete-user [user]
(clutch/with-db (authenticated-database *users-db*)
(clutch/delete-document user)))
(defn delete-private-database [user]
(if-let [db (:userdb user)]
(do
(clutch/delete-database (authenticated-database db))
(update-user (dissoc user :userdb)))))
(defn set-roles [username, roles]
"Set roles for user"
(let [user (get-user username)]
(update-user (assoc user :roles roles))))
(defn- clean-name [name]
(s/replace (s/lower-case name) #"[^a-z0-9\\+]" "\\_" ))
(defn create-private-database [user & [postfix]]
"Create new database for user and store the name
of the new database in the users meta-data"
;;Database name may only contain:
;;lower case letters, numbers, _, $, (, ), +, -, and /
(let [clean-name (clean-name (:name user))
db-name (str "userdb_"
(if (nil? postfix)
clean-name
(str clean-name "_" postfix)))
name {:names [(:name user)]}
acl {:admins name :readers name}]
(try (clutch/create-database (database-url db-name))
(try (do (clutch/with-db (authenticated-database db-name) (security acl))
(update-user (assoc user :userdb db-name)))
;;Should we remove the database
;;if we cannot update the user data?
(catch Exception _
(clutch/delete-database (database-url db-name))))
(catch java.io.IOException _
(create-private-database user
(if (nil? postfix)
0
(+ postfix 1)))))))
| true |
(ns joiner.user
(:require [clojure.string :as s]
[cemerick.url :as url]
[clojure.data.codec.base64 :as b64]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]
[joiner.admin]))
(def ^:private ^:dynamic *users-db* "_users")
(defn- get-uuid []
(first
(:uuids (http/couchdb-request :get
(database-url "_uuids")))))
(defn- to-hex [byte]
(let [clean-byte (bit-and byte 0xff)
val (Integer/toString clean-byte 16)]
(if (< clean-byte 0x10)
(str "0" val)
val)))
(defn- sha1 [string salt]
(let [bytes (.getBytes (str string salt) "UTF-8")
digester (java.security.MessageDigest/getInstance "SHA1")]
(apply str (map to-hex (.digest digester bytes)))))
(defn create-user [username, password, roles]
"Create a new user with given password and roles."
(clutch/with-db (authenticated-database *users-db*)
(clutch/put-document
{:_id (str "org.couchdb.user:" username)
:name username
:password PI:PASSWORD:<PASSWORD>END_PI
:type "user"
:roles roles})))
;;Sha-1 encoding of password was only required prior to 1.2.0
;;(defn create-user [username, password, roles]
;; "Create a new user with given password and roles."
;; (let [salt (get-uuid)]
;; (with-db (authenticated-database *users-db*)
;; (put-document
;; {:_id (str "org.couchdb.user:" username)
;; :name username
;; password_sha (sha1 password salt)
;; salt salt
;; :password PI:PASSWORD:<PASSWORD>END_PI
;; :type "user"
;; :roles roles}))))
(defn get-user [username]
"Get user from username"
(clutch/with-db (authenticated-database *users-db*)
(clutch/get-document (str "org.couchdb.user:" username))))
(defn- urlencode [string]
(java.net.URLEncoder/encode string "UTF-8"))
(defn authenticate [username, password]
"Seems like something is broken somewhere between here and clj-http for usernames
containing special characters (such as @) - hence these hoops"
(try
(let [url (url/url (assoc (couchdb-instance) :username nil :password nil) "_session")
^bytes auth-bytes (b64/encode (.getBytes (str username ":" password)))
authorization (String. auth-bytes)
headers {"Authorization" (str "Basic " authorization)}]
(let [resp (http/couchdb-request :get url :headers headers)]
(and (:ok resp)
(not (nil? (:name (:userCtx resp)))))))
(catch clojure.lang.ExceptionInfo e
false)))
(defn set-password [username, password]
"Set new password for user"
(let [user (get-user username)]
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document (assoc user
:password PI:PASSWORD:<PASSWORD>END_PI)))))
;;(defn set-password [username, password]
;; "Set new password for user"
;; (let [salt (get-uuid)
;; user (get-user username)]
;; (with-db (authenticated-database *users-db*)
;; (update-document (assoc user
;; :salt salt
;; :password_sha (sha1 password salt))))))
(defn update-user [user]
"Update user along. Typically used when updating roles
and other meta-data"
(clutch/with-db (authenticated-database *users-db*)
(clutch/update-document user)))
(defn delete-user [user]
(clutch/with-db (authenticated-database *users-db*)
(clutch/delete-document user)))
(defn delete-private-database [user]
(if-let [db (:userdb user)]
(do
(clutch/delete-database (authenticated-database db))
(update-user (dissoc user :userdb)))))
(defn set-roles [username, roles]
"Set roles for user"
(let [user (get-user username)]
(update-user (assoc user :roles roles))))
(defn- clean-name [name]
(s/replace (s/lower-case name) #"[^a-z0-9\\+]" "\\_" ))
(defn create-private-database [user & [postfix]]
"Create new database for user and store the name
of the new database in the users meta-data"
;;Database name may only contain:
;;lower case letters, numbers, _, $, (, ), +, -, and /
(let [clean-name (clean-name (:name user))
db-name (str "userdb_"
(if (nil? postfix)
clean-name
(str clean-name "_" postfix)))
name {:names [(:name user)]}
acl {:admins name :readers name}]
(try (clutch/create-database (database-url db-name))
(try (do (clutch/with-db (authenticated-database db-name) (security acl))
(update-user (assoc user :userdb db-name)))
;;Should we remove the database
;;if we cannot update the user data?
(catch Exception _
(clutch/delete-database (database-url db-name))))
(catch java.io.IOException _
(create-private-database user
(if (nil? postfix)
0
(+ postfix 1)))))))
|
[
{
"context": ";;\n;; Copyright © 2017 Colin Smith.\n;; This work is based on the Scmutils system of ",
"end": 34,
"score": 0.9996936917304993,
"start": 23,
"tag": "NAME",
"value": "Colin Smith"
}
] |
test/numerical/util/stream_test.cljc
|
dynamic-notebook/functional-numerics
| 4 |
;;
;; Copyright © 2017 Colin Smith.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.util.stream-test
"Tests of the various sequence convergence and generation utilities in the SICM
library."
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.generic :as g]
[sicmutils.numbers]
[sicmutils.util.stream :as us]))
(deftest zeno-powers-tests
(testing "zeno streams"
(is (ish? (/ 5 (g/expt 2 10))
(nth (us/zeno 2 5) 10)))
(is (ish? (/ 1 (g/expt 2 10))
(nth (us/zeno 2) 10))))
(testing "powers"
(is (ish? (* 5 (g/expt 2 10))
(nth (us/powers 2 5) 10)))
(is (ish? (g/expt 2 10)
(nth (us/powers 2) 10)))))
(deftest scan-tests
(testing "intermediate + aggregations, all negated by `present`."
(let [f (us/scan + :init 0 :present -)]
(is (= [0 -1 -3 -6 -10 -15 -21 -28]
(f (range 8))))))
(testing "intermediate + aggregations, no present, arity-based init."
(let [f (us/scan (fn ([] 0) ([l r] (+ l r))))]
(is (= [0 1 3 6 10 15 21 28]
(f (range 8)))))))
(deftest convergence-tests
(testing "empty sequence behavior."
(is (= {:converged? false, :terms-checked 0, :result nil}
(us/seq-limit []))))
(testing "normal usage."
(is (= {:converged? true, :terms-checked 11, :result (/ 1 1024)}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))}))))
(testing "maxterms stops evaluation."
(is (= {:converged? false, :terms-checked 4, :result (/ 1 8)}
(us/seq-limit (us/zeno 2)
{:maxterms 4}))))
(testing "minterms forces that number of terms to be evaluated."
(is (= {:converged? true, :terms-checked 20, :result (/ 1 (g/expt 2 19))}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20}))))
(testing "If the sequence runs out, convergence tests stop and the final
item's returned."
(is (= {:converged? false, :terms-checked 3, :result 3}
(us/seq-limit [1 2 3]
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20})))))
|
2601
|
;;
;; Copyright © 2017 <NAME>.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.util.stream-test
"Tests of the various sequence convergence and generation utilities in the SICM
library."
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.generic :as g]
[sicmutils.numbers]
[sicmutils.util.stream :as us]))
(deftest zeno-powers-tests
(testing "zeno streams"
(is (ish? (/ 5 (g/expt 2 10))
(nth (us/zeno 2 5) 10)))
(is (ish? (/ 1 (g/expt 2 10))
(nth (us/zeno 2) 10))))
(testing "powers"
(is (ish? (* 5 (g/expt 2 10))
(nth (us/powers 2 5) 10)))
(is (ish? (g/expt 2 10)
(nth (us/powers 2) 10)))))
(deftest scan-tests
(testing "intermediate + aggregations, all negated by `present`."
(let [f (us/scan + :init 0 :present -)]
(is (= [0 -1 -3 -6 -10 -15 -21 -28]
(f (range 8))))))
(testing "intermediate + aggregations, no present, arity-based init."
(let [f (us/scan (fn ([] 0) ([l r] (+ l r))))]
(is (= [0 1 3 6 10 15 21 28]
(f (range 8)))))))
(deftest convergence-tests
(testing "empty sequence behavior."
(is (= {:converged? false, :terms-checked 0, :result nil}
(us/seq-limit []))))
(testing "normal usage."
(is (= {:converged? true, :terms-checked 11, :result (/ 1 1024)}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))}))))
(testing "maxterms stops evaluation."
(is (= {:converged? false, :terms-checked 4, :result (/ 1 8)}
(us/seq-limit (us/zeno 2)
{:maxterms 4}))))
(testing "minterms forces that number of terms to be evaluated."
(is (= {:converged? true, :terms-checked 20, :result (/ 1 (g/expt 2 19))}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20}))))
(testing "If the sequence runs out, convergence tests stop and the final
item's returned."
(is (= {:converged? false, :terms-checked 3, :result 3}
(us/seq-limit [1 2 3]
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20})))))
| true |
;;
;; Copyright © 2017 PI:NAME:<NAME>END_PI.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.util.stream-test
"Tests of the various sequence convergence and generation utilities in the SICM
library."
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.generic :as g]
[sicmutils.numbers]
[sicmutils.util.stream :as us]))
(deftest zeno-powers-tests
(testing "zeno streams"
(is (ish? (/ 5 (g/expt 2 10))
(nth (us/zeno 2 5) 10)))
(is (ish? (/ 1 (g/expt 2 10))
(nth (us/zeno 2) 10))))
(testing "powers"
(is (ish? (* 5 (g/expt 2 10))
(nth (us/powers 2 5) 10)))
(is (ish? (g/expt 2 10)
(nth (us/powers 2) 10)))))
(deftest scan-tests
(testing "intermediate + aggregations, all negated by `present`."
(let [f (us/scan + :init 0 :present -)]
(is (= [0 -1 -3 -6 -10 -15 -21 -28]
(f (range 8))))))
(testing "intermediate + aggregations, no present, arity-based init."
(let [f (us/scan (fn ([] 0) ([l r] (+ l r))))]
(is (= [0 1 3 6 10 15 21 28]
(f (range 8)))))))
(deftest convergence-tests
(testing "empty sequence behavior."
(is (= {:converged? false, :terms-checked 0, :result nil}
(us/seq-limit []))))
(testing "normal usage."
(is (= {:converged? true, :terms-checked 11, :result (/ 1 1024)}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))}))))
(testing "maxterms stops evaluation."
(is (= {:converged? false, :terms-checked 4, :result (/ 1 8)}
(us/seq-limit (us/zeno 2)
{:maxterms 4}))))
(testing "minterms forces that number of terms to be evaluated."
(is (= {:converged? true, :terms-checked 20, :result (/ 1 (g/expt 2 19))}
(us/seq-limit (us/zeno 2)
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20}))))
(testing "If the sequence runs out, convergence tests stop and the final
item's returned."
(is (= {:converged? false, :terms-checked 3, :result 3}
(us/seq-limit [1 2 3]
{:tolerance (/ 1 (g/expt 2 10))
:minterms 20})))))
|
[
{
"context": "; Copyright (c) Shantanu Kumar. All rights reserved.\n; The use and distributio",
"end": 32,
"score": 0.9997974634170532,
"start": 18,
"tag": "NAME",
"value": "Shantanu Kumar"
}
] |
data/test/clojure/aab69257c8083df8b4e63d350e1df67ec9a37d76jdbc.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
; Copyright (c) Shantanu Kumar. 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 LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns preflex.instrument.jdbc
(:require
[preflex.task :as task])
(:import
[java.sql Connection]
[javax.sql DataSource]
[preflex.instrument.jdbc
ConnectionWrapper
DataSourceWrapper
JdbcEventFactory]
[preflex.instrument.task
Wrapper]))
(defn make-jdbc-event-factory
"Make a preflex.instrument.jdbc.JdbcEventFactory instance from given event generator options:
:connection-create - (fn []) -> event
:statement-create - (fn []) -> event
:prepared-create - (fn [sql]) -> event
:callable-create - (fn [sql]) -> event
:statement-sql-execute - (fn [sql]) -> event
:statement-sql-query - (fn [sql]) -> event
:statement-sql-update - (fn [sql]) -> event
:prepared-sql-execute - (fn [sql]) -> event
:prepared-sql-query - (fn [sql]) -> event
:prepared-sql-update - (fn [sql]) -> event"
([]
(make-jdbc-event-factory {}))
([{:keys [connection-create
statement-create
prepared-create
callable-create
statement-sql-execute
statement-sql-query
statement-sql-update
prepared-sql-execute
prepared-sql-query
prepared-sql-update]
:or {connection-create (fn [] {:jdbc-event :connection-create})
statement-create (fn [] {:jdbc-event :statement-create})
prepared-create (fn [sql] {:jdbc-event :prepared-create :sql sql})
callable-create (fn [sql] {:jdbc-event :callable-create :sql sql})
statement-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? false :sql sql})
statement-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? false :sql sql})
statement-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? false :sql sql})
prepared-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? true :sql sql})
prepared-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? true :sql sql})
prepared-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? true :sql sql})}}]
(reify JdbcEventFactory
(jdbcConnectionCreationEvent [_] (connection-create))
(jdbcStatementCreationEvent [_] (statement-create))
(jdbcPreparedStatementCreationEvent [_ sql] (prepared-create sql))
(jdbcCallableStatementCreationEvent [_ sql] (callable-create sql))
(sqlExecutionEventForStatement [_ sql] (statement-sql-execute sql))
(sqlQueryExecutionEventForStatement [_ sql] (statement-sql-query sql))
(sqlUpdateExecutionEventForStatement [_ sql] (statement-sql-update sql))
(sqlExecutionEventForPreparedStatement [_ sql] (prepared-sql-execute sql))
(sqlQueryExecutionEventForPreparedStatement [_ sql] (prepared-sql-query sql))
(sqlUpdateExecutionEventForPreparedStatement [_ sql] (prepared-sql-update sql)))))
(def default-jdbc-event-factory (make-jdbc-event-factory))
(defn instrument-connection
"Given a java.sql.Connection instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^Connection connection {:keys [jdbc-event-factory
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(ConnectionWrapper. connection jdbc-event-factory
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
(defn instrument-datasource
"Given a javax.sql.DataSource instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:conn-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^DataSource datasource {:keys [jdbc-event-factory
conn-creation-wrapper
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
conn-creation-wrapper Wrapper/IDENTITY
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(DataSourceWrapper. datasource jdbc-event-factory
(if (fn? conn-creation-wrapper)
(task/make-wrapper conn-creation-wrapper)
conn-creation-wrapper)
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
|
42107
|
; 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 LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns preflex.instrument.jdbc
(:require
[preflex.task :as task])
(:import
[java.sql Connection]
[javax.sql DataSource]
[preflex.instrument.jdbc
ConnectionWrapper
DataSourceWrapper
JdbcEventFactory]
[preflex.instrument.task
Wrapper]))
(defn make-jdbc-event-factory
"Make a preflex.instrument.jdbc.JdbcEventFactory instance from given event generator options:
:connection-create - (fn []) -> event
:statement-create - (fn []) -> event
:prepared-create - (fn [sql]) -> event
:callable-create - (fn [sql]) -> event
:statement-sql-execute - (fn [sql]) -> event
:statement-sql-query - (fn [sql]) -> event
:statement-sql-update - (fn [sql]) -> event
:prepared-sql-execute - (fn [sql]) -> event
:prepared-sql-query - (fn [sql]) -> event
:prepared-sql-update - (fn [sql]) -> event"
([]
(make-jdbc-event-factory {}))
([{:keys [connection-create
statement-create
prepared-create
callable-create
statement-sql-execute
statement-sql-query
statement-sql-update
prepared-sql-execute
prepared-sql-query
prepared-sql-update]
:or {connection-create (fn [] {:jdbc-event :connection-create})
statement-create (fn [] {:jdbc-event :statement-create})
prepared-create (fn [sql] {:jdbc-event :prepared-create :sql sql})
callable-create (fn [sql] {:jdbc-event :callable-create :sql sql})
statement-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? false :sql sql})
statement-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? false :sql sql})
statement-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? false :sql sql})
prepared-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? true :sql sql})
prepared-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? true :sql sql})
prepared-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? true :sql sql})}}]
(reify JdbcEventFactory
(jdbcConnectionCreationEvent [_] (connection-create))
(jdbcStatementCreationEvent [_] (statement-create))
(jdbcPreparedStatementCreationEvent [_ sql] (prepared-create sql))
(jdbcCallableStatementCreationEvent [_ sql] (callable-create sql))
(sqlExecutionEventForStatement [_ sql] (statement-sql-execute sql))
(sqlQueryExecutionEventForStatement [_ sql] (statement-sql-query sql))
(sqlUpdateExecutionEventForStatement [_ sql] (statement-sql-update sql))
(sqlExecutionEventForPreparedStatement [_ sql] (prepared-sql-execute sql))
(sqlQueryExecutionEventForPreparedStatement [_ sql] (prepared-sql-query sql))
(sqlUpdateExecutionEventForPreparedStatement [_ sql] (prepared-sql-update sql)))))
(def default-jdbc-event-factory (make-jdbc-event-factory))
(defn instrument-connection
"Given a java.sql.Connection instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^Connection connection {:keys [jdbc-event-factory
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(ConnectionWrapper. connection jdbc-event-factory
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
(defn instrument-datasource
"Given a javax.sql.DataSource instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:conn-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^DataSource datasource {:keys [jdbc-event-factory
conn-creation-wrapper
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
conn-creation-wrapper Wrapper/IDENTITY
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(DataSourceWrapper. datasource jdbc-event-factory
(if (fn? conn-creation-wrapper)
(task/make-wrapper conn-creation-wrapper)
conn-creation-wrapper)
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns preflex.instrument.jdbc
(:require
[preflex.task :as task])
(:import
[java.sql Connection]
[javax.sql DataSource]
[preflex.instrument.jdbc
ConnectionWrapper
DataSourceWrapper
JdbcEventFactory]
[preflex.instrument.task
Wrapper]))
(defn make-jdbc-event-factory
"Make a preflex.instrument.jdbc.JdbcEventFactory instance from given event generator options:
:connection-create - (fn []) -> event
:statement-create - (fn []) -> event
:prepared-create - (fn [sql]) -> event
:callable-create - (fn [sql]) -> event
:statement-sql-execute - (fn [sql]) -> event
:statement-sql-query - (fn [sql]) -> event
:statement-sql-update - (fn [sql]) -> event
:prepared-sql-execute - (fn [sql]) -> event
:prepared-sql-query - (fn [sql]) -> event
:prepared-sql-update - (fn [sql]) -> event"
([]
(make-jdbc-event-factory {}))
([{:keys [connection-create
statement-create
prepared-create
callable-create
statement-sql-execute
statement-sql-query
statement-sql-update
prepared-sql-execute
prepared-sql-query
prepared-sql-update]
:or {connection-create (fn [] {:jdbc-event :connection-create})
statement-create (fn [] {:jdbc-event :statement-create})
prepared-create (fn [sql] {:jdbc-event :prepared-create :sql sql})
callable-create (fn [sql] {:jdbc-event :callable-create :sql sql})
statement-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? false :sql sql})
statement-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? false :sql sql})
statement-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? false :sql sql})
prepared-sql-execute (fn [sql] {:jdbc-event :sql-execute :prepared? true :sql sql})
prepared-sql-query (fn [sql] {:jdbc-event :sql-query :prepared? true :sql sql})
prepared-sql-update (fn [sql] {:jdbc-event :sql-update :prepared? true :sql sql})}}]
(reify JdbcEventFactory
(jdbcConnectionCreationEvent [_] (connection-create))
(jdbcStatementCreationEvent [_] (statement-create))
(jdbcPreparedStatementCreationEvent [_ sql] (prepared-create sql))
(jdbcCallableStatementCreationEvent [_ sql] (callable-create sql))
(sqlExecutionEventForStatement [_ sql] (statement-sql-execute sql))
(sqlQueryExecutionEventForStatement [_ sql] (statement-sql-query sql))
(sqlUpdateExecutionEventForStatement [_ sql] (statement-sql-update sql))
(sqlExecutionEventForPreparedStatement [_ sql] (prepared-sql-execute sql))
(sqlQueryExecutionEventForPreparedStatement [_ sql] (prepared-sql-query sql))
(sqlUpdateExecutionEventForPreparedStatement [_ sql] (prepared-sql-update sql)))))
(def default-jdbc-event-factory (make-jdbc-event-factory))
(defn instrument-connection
"Given a java.sql.Connection instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^Connection connection {:keys [jdbc-event-factory
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(ConnectionWrapper. connection jdbc-event-factory
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
(defn instrument-datasource
"Given a javax.sql.DataSource instance, make an instrumented wrapper using the given options:
:jdbc-event-factory - a preflex.instrument.jdbc.JdbcEventFactory instance (see `make-jdbc-event-factory`)
:conn-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:stmt-creation-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`
:sql-execution-wrapper - a preflex.instrument.task.Wrapper instance or argument to `preflex.task/make-wrapper`"
[^DataSource datasource {:keys [jdbc-event-factory
conn-creation-wrapper
stmt-creation-wrapper
sql-execution-wrapper]
:or {jdbc-event-factory default-jdbc-event-factory
conn-creation-wrapper Wrapper/IDENTITY
stmt-creation-wrapper Wrapper/IDENTITY
sql-execution-wrapper Wrapper/IDENTITY}}]
(DataSourceWrapper. datasource jdbc-event-factory
(if (fn? conn-creation-wrapper)
(task/make-wrapper conn-creation-wrapper)
conn-creation-wrapper)
(if (fn? stmt-creation-wrapper)
(task/make-wrapper stmt-creation-wrapper)
stmt-creation-wrapper)
(if (fn? sql-execution-wrapper)
(task/make-wrapper sql-execution-wrapper)
sql-execution-wrapper)))
|
[
{
"context": ";Copyright (c) 2012 Christoph Mueller\n;\n;Permission is hereby granted, free of charge, ",
"end": 37,
"score": 0.9998581409454346,
"start": 20,
"tag": "NAME",
"value": "Christoph Mueller"
}
] |
clojure/cgpfun.clj
|
raytracer/CGPFun
| 1 |
;Copyright (c) 2012 Christoph Mueller
;
;Permission is hereby granted, free of charge, to any person obtaining a
;copy of this software and associated documentation files (the
;"Software"), to deal in the Software without restriction, including
;without limitation the rights to use, copy, modify, merge, publish,
;distribute, sublicense, and/or sell copies of the Software, and to
;permit persons to whom the Software is furnished to do so, subject to
;the following conditions:
;
;The above copyright notice and this permission notice shall be included
;in all copies or substantial portions of the Software.
;
;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
;IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
;CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
;TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns cgpfun)
;;helper
(set! *warn-on-reflection* true)
(defn rand-int-min
"rand-int with a minimum"
[min max]
(+ (rand-int (- max min)) min))
(defn abs [^double x] (Math/abs x))
;;nodes
(defprotocol Compute
(compute
[this nodes]
"computes the node and all its dependencies")
(compute-string
[this nodes]
"returns the string representing the mathematical operations"))
(defrecord AddNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(+ (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " + " (compute-string n2 nodes) ")"))))
(defrecord SubNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(- (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " - " (compute-string n2 nodes) ")"))))
(defrecord MulNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(* (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " * " (compute-string n2 nodes) ")"))))
(defrecord DivNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)
v2raw (compute n2 nodes)
v2 (if (zero? v2raw) Double/POSITIVE_INFINITY v2raw)]
(/ (compute n1 nodes) v2)))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " / " (compute-string n2 nodes) ")"))))
(defrecord ConstNode [value]
Compute
(compute
[this nodes]
value)
(compute-string
[this nodes]
value))
(defrecord VarNode [name]
Compute
(compute
[this nodes]
nil)
(compute-string
[this nodes]
name))
(defrecord NopNode [pos]
Compute
(compute
[this nodes]
(compute (nth nodes pos) nodes))
(compute-string
[this nodes]
(compute-string (nth nodes pos) nodes)))
(defn random-node
"returns a randomly generated node at the given pos"
[pos height offset]
(let [choose (rand-int 6)
max-pos (- pos (rem (- pos offset) height))]
(cond
(= choose 0) (AddNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 1) (SubNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 2) (MulNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 3) (DivNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 4) (NopNode.
(rand-int max-pos))
(= choose 5) (ConstNode.
(double (rand-int-min -10 11))))))
;;field
(defprotocol FieldOps
(mutate
[this factor]
"returns a mutated copy for a given mutation factor")
(fitness
[this xs ys]
"returns the fitness for a given set of xy pairs")
(print-result
[this]
"prints the resulting formula *debug*"))
(defrecord Field [width height inputs output nodes]
FieldOps
(mutate
[this factor]
(let [size (count nodes)
offset (count inputs)
n (int (* (- size offset) factor))]
(loop [i 0 mnodes nodes]
(if (< i n)
(let [x (rand-int-min offset size)]
(if (= x (dec size))
(recur (inc i) (assoc mnodes x (NopNode. (rand-int x))))
(recur (inc i) (assoc mnodes x (random-node x height offset)))))
(Field. width height inputs output mnodes)))))
(fitness
[this xs ys]
(let [n (count ys)
ins (count inputs)]
(loop [i 0 fit (double 0.0)]
(if (< i n)
(let [tempns (loop [j 0 ns nodes]
(if (< j ins)
(recur (inc j)
(assoc ns j (ConstNode. (double (nth xs (+ (* i ins) j))))))
ns))
val (compute output tempns)
diff (abs (- val (nth ys i)))]
(recur (inc i) (+ fit diff)))
fit))))
(print-result
[this]
(compute-string output nodes)))
(defn create-field
"creates a new field and fills it with random nodes"
[width height inputs]
(let [n (* width height)
output (NopNode. (rand-int (dec n)))
nodes
(loop [i 0 v (transient inputs)]
(if (< i n)
(let [offset (count inputs)]
(recur (inc i) (conj! v (random-node (+ i offset) height offset))))
(persistent! (conj! v output))))]
(Field. width height inputs output nodes)))
(defn return-best [x y xs ys]
"returns the fitter of the two individuals x and y"
(if (<= (fitness x xs ys) (fitness y xs ys))
x
y))
(defn generations
"returns the fittest individual after n generations"
[field n mutations factor xs ys]
(loop [i 0 indv field]
(if (< i n)
(recur (inc i)
(reduce #(return-best %1 %2 xs ys) indv
(take mutations (repeatedly
#(mutate indv factor)))))
indv)))
(defn islands
"creates n islands with a specified number of generation following a migration"
[n migrations gens mutations factor xs ys width height inputs]
(let [start (take n (repeatedly #(create-field width height inputs)))]
(loop [mig 0 current start]
(if (< mig migrations)
(recur (inc mig)
(repeat n (reduce #(return-best %1 %2 xs ys)
(pmap #(generations % gens mutations factor xs ys)
current))))
(first current)))))
;;test the implementation
(def field (create-field 4 4 [(VarNode. "x")]))
;test sets
(def xs [0.5 1.0 2.0 4.0 5.0 8.0])
(def ys [-2.0 -1.0 -0.5 -0.25 -0.2 -0.125])
;(def xs [1.0 1.0 2.0 4.0 5.0 8.0 10.0 2.0])
;(def ys [1.0 8.0 40.0 20.0])
;(def best (time (generations field 100 100 0.2 xs ys)))
(def best (time (islands 2 10 1000 1000 0.2 xs ys 3 3 [(VarNode. "x")])))
(println (print-result best))
(println (fitness best xs ys))
|
47999
|
;Copyright (c) 2012 <NAME>
;
;Permission is hereby granted, free of charge, to any person obtaining a
;copy of this software and associated documentation files (the
;"Software"), to deal in the Software without restriction, including
;without limitation the rights to use, copy, modify, merge, publish,
;distribute, sublicense, and/or sell copies of the Software, and to
;permit persons to whom the Software is furnished to do so, subject to
;the following conditions:
;
;The above copyright notice and this permission notice shall be included
;in all copies or substantial portions of the Software.
;
;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
;IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
;CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
;TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns cgpfun)
;;helper
(set! *warn-on-reflection* true)
(defn rand-int-min
"rand-int with a minimum"
[min max]
(+ (rand-int (- max min)) min))
(defn abs [^double x] (Math/abs x))
;;nodes
(defprotocol Compute
(compute
[this nodes]
"computes the node and all its dependencies")
(compute-string
[this nodes]
"returns the string representing the mathematical operations"))
(defrecord AddNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(+ (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " + " (compute-string n2 nodes) ")"))))
(defrecord SubNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(- (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " - " (compute-string n2 nodes) ")"))))
(defrecord MulNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(* (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " * " (compute-string n2 nodes) ")"))))
(defrecord DivNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)
v2raw (compute n2 nodes)
v2 (if (zero? v2raw) Double/POSITIVE_INFINITY v2raw)]
(/ (compute n1 nodes) v2)))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " / " (compute-string n2 nodes) ")"))))
(defrecord ConstNode [value]
Compute
(compute
[this nodes]
value)
(compute-string
[this nodes]
value))
(defrecord VarNode [name]
Compute
(compute
[this nodes]
nil)
(compute-string
[this nodes]
name))
(defrecord NopNode [pos]
Compute
(compute
[this nodes]
(compute (nth nodes pos) nodes))
(compute-string
[this nodes]
(compute-string (nth nodes pos) nodes)))
(defn random-node
"returns a randomly generated node at the given pos"
[pos height offset]
(let [choose (rand-int 6)
max-pos (- pos (rem (- pos offset) height))]
(cond
(= choose 0) (AddNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 1) (SubNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 2) (MulNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 3) (DivNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 4) (NopNode.
(rand-int max-pos))
(= choose 5) (ConstNode.
(double (rand-int-min -10 11))))))
;;field
(defprotocol FieldOps
(mutate
[this factor]
"returns a mutated copy for a given mutation factor")
(fitness
[this xs ys]
"returns the fitness for a given set of xy pairs")
(print-result
[this]
"prints the resulting formula *debug*"))
(defrecord Field [width height inputs output nodes]
FieldOps
(mutate
[this factor]
(let [size (count nodes)
offset (count inputs)
n (int (* (- size offset) factor))]
(loop [i 0 mnodes nodes]
(if (< i n)
(let [x (rand-int-min offset size)]
(if (= x (dec size))
(recur (inc i) (assoc mnodes x (NopNode. (rand-int x))))
(recur (inc i) (assoc mnodes x (random-node x height offset)))))
(Field. width height inputs output mnodes)))))
(fitness
[this xs ys]
(let [n (count ys)
ins (count inputs)]
(loop [i 0 fit (double 0.0)]
(if (< i n)
(let [tempns (loop [j 0 ns nodes]
(if (< j ins)
(recur (inc j)
(assoc ns j (ConstNode. (double (nth xs (+ (* i ins) j))))))
ns))
val (compute output tempns)
diff (abs (- val (nth ys i)))]
(recur (inc i) (+ fit diff)))
fit))))
(print-result
[this]
(compute-string output nodes)))
(defn create-field
"creates a new field and fills it with random nodes"
[width height inputs]
(let [n (* width height)
output (NopNode. (rand-int (dec n)))
nodes
(loop [i 0 v (transient inputs)]
(if (< i n)
(let [offset (count inputs)]
(recur (inc i) (conj! v (random-node (+ i offset) height offset))))
(persistent! (conj! v output))))]
(Field. width height inputs output nodes)))
(defn return-best [x y xs ys]
"returns the fitter of the two individuals x and y"
(if (<= (fitness x xs ys) (fitness y xs ys))
x
y))
(defn generations
"returns the fittest individual after n generations"
[field n mutations factor xs ys]
(loop [i 0 indv field]
(if (< i n)
(recur (inc i)
(reduce #(return-best %1 %2 xs ys) indv
(take mutations (repeatedly
#(mutate indv factor)))))
indv)))
(defn islands
"creates n islands with a specified number of generation following a migration"
[n migrations gens mutations factor xs ys width height inputs]
(let [start (take n (repeatedly #(create-field width height inputs)))]
(loop [mig 0 current start]
(if (< mig migrations)
(recur (inc mig)
(repeat n (reduce #(return-best %1 %2 xs ys)
(pmap #(generations % gens mutations factor xs ys)
current))))
(first current)))))
;;test the implementation
(def field (create-field 4 4 [(VarNode. "x")]))
;test sets
(def xs [0.5 1.0 2.0 4.0 5.0 8.0])
(def ys [-2.0 -1.0 -0.5 -0.25 -0.2 -0.125])
;(def xs [1.0 1.0 2.0 4.0 5.0 8.0 10.0 2.0])
;(def ys [1.0 8.0 40.0 20.0])
;(def best (time (generations field 100 100 0.2 xs ys)))
(def best (time (islands 2 10 1000 1000 0.2 xs ys 3 3 [(VarNode. "x")])))
(println (print-result best))
(println (fitness best xs ys))
| true |
;Copyright (c) 2012 PI:NAME:<NAME>END_PI
;
;Permission is hereby granted, free of charge, to any person obtaining a
;copy of this software and associated documentation files (the
;"Software"), to deal in the Software without restriction, including
;without limitation the rights to use, copy, modify, merge, publish,
;distribute, sublicense, and/or sell copies of the Software, and to
;permit persons to whom the Software is furnished to do so, subject to
;the following conditions:
;
;The above copyright notice and this permission notice shall be included
;in all copies or substantial portions of the Software.
;
;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
;IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
;CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
;TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns cgpfun)
;;helper
(set! *warn-on-reflection* true)
(defn rand-int-min
"rand-int with a minimum"
[min max]
(+ (rand-int (- max min)) min))
(defn abs [^double x] (Math/abs x))
;;nodes
(defprotocol Compute
(compute
[this nodes]
"computes the node and all its dependencies")
(compute-string
[this nodes]
"returns the string representing the mathematical operations"))
(defrecord AddNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(+ (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " + " (compute-string n2 nodes) ")"))))
(defrecord SubNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(- (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " - " (compute-string n2 nodes) ")"))))
(defrecord MulNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(* (compute n1 nodes) (compute n2 nodes))))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " * " (compute-string n2 nodes) ")"))))
(defrecord DivNode [pos1 pos2]
Compute
(compute
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)
v2raw (compute n2 nodes)
v2 (if (zero? v2raw) Double/POSITIVE_INFINITY v2raw)]
(/ (compute n1 nodes) v2)))
(compute-string
[this nodes]
(let [n1 (nth nodes pos1)
n2 (nth nodes pos2)]
(str "(" (compute-string n1 nodes) " / " (compute-string n2 nodes) ")"))))
(defrecord ConstNode [value]
Compute
(compute
[this nodes]
value)
(compute-string
[this nodes]
value))
(defrecord VarNode [name]
Compute
(compute
[this nodes]
nil)
(compute-string
[this nodes]
name))
(defrecord NopNode [pos]
Compute
(compute
[this nodes]
(compute (nth nodes pos) nodes))
(compute-string
[this nodes]
(compute-string (nth nodes pos) nodes)))
(defn random-node
"returns a randomly generated node at the given pos"
[pos height offset]
(let [choose (rand-int 6)
max-pos (- pos (rem (- pos offset) height))]
(cond
(= choose 0) (AddNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 1) (SubNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 2) (MulNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 3) (DivNode.
(rand-int max-pos)
(rand-int max-pos))
(= choose 4) (NopNode.
(rand-int max-pos))
(= choose 5) (ConstNode.
(double (rand-int-min -10 11))))))
;;field
(defprotocol FieldOps
(mutate
[this factor]
"returns a mutated copy for a given mutation factor")
(fitness
[this xs ys]
"returns the fitness for a given set of xy pairs")
(print-result
[this]
"prints the resulting formula *debug*"))
(defrecord Field [width height inputs output nodes]
FieldOps
(mutate
[this factor]
(let [size (count nodes)
offset (count inputs)
n (int (* (- size offset) factor))]
(loop [i 0 mnodes nodes]
(if (< i n)
(let [x (rand-int-min offset size)]
(if (= x (dec size))
(recur (inc i) (assoc mnodes x (NopNode. (rand-int x))))
(recur (inc i) (assoc mnodes x (random-node x height offset)))))
(Field. width height inputs output mnodes)))))
(fitness
[this xs ys]
(let [n (count ys)
ins (count inputs)]
(loop [i 0 fit (double 0.0)]
(if (< i n)
(let [tempns (loop [j 0 ns nodes]
(if (< j ins)
(recur (inc j)
(assoc ns j (ConstNode. (double (nth xs (+ (* i ins) j))))))
ns))
val (compute output tempns)
diff (abs (- val (nth ys i)))]
(recur (inc i) (+ fit diff)))
fit))))
(print-result
[this]
(compute-string output nodes)))
(defn create-field
"creates a new field and fills it with random nodes"
[width height inputs]
(let [n (* width height)
output (NopNode. (rand-int (dec n)))
nodes
(loop [i 0 v (transient inputs)]
(if (< i n)
(let [offset (count inputs)]
(recur (inc i) (conj! v (random-node (+ i offset) height offset))))
(persistent! (conj! v output))))]
(Field. width height inputs output nodes)))
(defn return-best [x y xs ys]
"returns the fitter of the two individuals x and y"
(if (<= (fitness x xs ys) (fitness y xs ys))
x
y))
(defn generations
"returns the fittest individual after n generations"
[field n mutations factor xs ys]
(loop [i 0 indv field]
(if (< i n)
(recur (inc i)
(reduce #(return-best %1 %2 xs ys) indv
(take mutations (repeatedly
#(mutate indv factor)))))
indv)))
(defn islands
"creates n islands with a specified number of generation following a migration"
[n migrations gens mutations factor xs ys width height inputs]
(let [start (take n (repeatedly #(create-field width height inputs)))]
(loop [mig 0 current start]
(if (< mig migrations)
(recur (inc mig)
(repeat n (reduce #(return-best %1 %2 xs ys)
(pmap #(generations % gens mutations factor xs ys)
current))))
(first current)))))
;;test the implementation
(def field (create-field 4 4 [(VarNode. "x")]))
;test sets
(def xs [0.5 1.0 2.0 4.0 5.0 8.0])
(def ys [-2.0 -1.0 -0.5 -0.25 -0.2 -0.125])
;(def xs [1.0 1.0 2.0 4.0 5.0 8.0 10.0 2.0])
;(def ys [1.0 8.0 40.0 20.0])
;(def best (time (generations field 100 100 0.2 xs ys)))
(def best (time (islands 2 10 1000 1000 0.2 xs ys 3 3 [(VarNode. "x")])))
(println (print-result best))
(println (fitness best xs ys))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.