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": "ia.org/wiki/Public-key_cryptography\"\n\n {:author \"Adam Helinski\"}\n\n (:require [convex.pfx :as $.pfx]\n ",
"end": 755,
"score": 0.9978436231613159,
"start": 742,
"tag": "NAME",
"value": "Adam Helinski"
},
{
"context": "Generating a key pair.\n ;;\n (def key-pair\n ($.sign/ed25519))\n\n\n ;; File for storing our \"key s",
"end": 2191,
"score": 0.7411918044090271,
"start": 2189,
"tag": "KEY",
"value": "($"
}
] |
project/recipe/src/clj/main/convex/recipe/key_pair.clj
|
rosejn/convex.cljc
| 30 |
(ns convex.recipe.key-pair
"Key pairs are essential, they are used by clients to sign transactions and by peers to sign
blocks of transactions.
This example shows how to create a key pair and store it securely in a PFX file.
Storing key pairs is always a sensitive topic. A PFX file allows storing one or several key pairs where
each is given a alias and protected by a dedicated password. The file itself can be protected by a
password as well.
Creating and handling Ed25519 key pairs is done using namespace `convex.sign`.
Creating and handling PFX iles is done using namespace `convex.pfx`.
More information about public-key cryptography: https://en.wikipedia.org/wiki/Public-key_cryptography"
{:author "Adam Helinski"}
(:require [convex.pfx :as $.pfx]
[convex.sign :as $.sign]))
;;;;;;;;;; One plausible example
(defn retrieve
"Tries to load the key pair from file 'keystore.pfx' in given `dir`.
When not found, generates a new key pair and saves it in a new file. A real application might require more sophisticated error handling.
Returns the key pair."
[dir]
(let [file-key-store (str dir
"/keystore.pfx")]
(try
(-> ($.pfx/load file-key-store)
($.pfx/key-pair-get "my-key-pair"
"my-password"))
(catch Throwable _ex
(let [key-pair ($.sign/ed25519)]
(-> ($.pfx/create file-key-store)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file-key-store))
key-pair)))))
;;;;;;;;;;
(comment
;; Example directory where key pair will be stored.
;;
(def dir
"private/recipe/key-pair/")
;; The first time, the key pair is generated and stored in a PFX file.
;;
;; Each subsequent time, the key pair is always retrieved from that file.
;;
;; Deleting that 'keystore.pfx' file in this directory will lose it forever.
;;
(retrieve dir)
;;
;; Let us inspect the core ideas in `retrieve`.
;;
;; Generating a key pair.
;;
(def key-pair
($.sign/ed25519))
;; File for storing our "key store" capable of securely hosting one or several key pairs.
;;
(def file
(str dir
"/keystore.pfx"))
;; We create a file for our "key store" capable of securely hosting one or several key pairs,
;; our key pair under an alias and protected by a password. Lastly, the updated key store is
;; saved to the file.
;;
(-> ($.pfx/create file)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file))
;; At any later time, we can load that file and retrieve our key pair by providing its alias and
;; its password.
;;
(= key-pair
(-> ($.pfx/load file)
($.pfx/key-pair-get "my-key-pair"
"my-password")))
;;
;; Although not mandatory, it is a good idea also specifying a password for the key store itself
;; when using `$.pfx/create`, `$.pfx/save`, and `$.pfx/load`.
;;
)
|
87563
|
(ns convex.recipe.key-pair
"Key pairs are essential, they are used by clients to sign transactions and by peers to sign
blocks of transactions.
This example shows how to create a key pair and store it securely in a PFX file.
Storing key pairs is always a sensitive topic. A PFX file allows storing one or several key pairs where
each is given a alias and protected by a dedicated password. The file itself can be protected by a
password as well.
Creating and handling Ed25519 key pairs is done using namespace `convex.sign`.
Creating and handling PFX iles is done using namespace `convex.pfx`.
More information about public-key cryptography: https://en.wikipedia.org/wiki/Public-key_cryptography"
{:author "<NAME>"}
(:require [convex.pfx :as $.pfx]
[convex.sign :as $.sign]))
;;;;;;;;;; One plausible example
(defn retrieve
"Tries to load the key pair from file 'keystore.pfx' in given `dir`.
When not found, generates a new key pair and saves it in a new file. A real application might require more sophisticated error handling.
Returns the key pair."
[dir]
(let [file-key-store (str dir
"/keystore.pfx")]
(try
(-> ($.pfx/load file-key-store)
($.pfx/key-pair-get "my-key-pair"
"my-password"))
(catch Throwable _ex
(let [key-pair ($.sign/ed25519)]
(-> ($.pfx/create file-key-store)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file-key-store))
key-pair)))))
;;;;;;;;;;
(comment
;; Example directory where key pair will be stored.
;;
(def dir
"private/recipe/key-pair/")
;; The first time, the key pair is generated and stored in a PFX file.
;;
;; Each subsequent time, the key pair is always retrieved from that file.
;;
;; Deleting that 'keystore.pfx' file in this directory will lose it forever.
;;
(retrieve dir)
;;
;; Let us inspect the core ideas in `retrieve`.
;;
;; Generating a key pair.
;;
(def key-pair
<KEY>.sign/ed25519))
;; File for storing our "key store" capable of securely hosting one or several key pairs.
;;
(def file
(str dir
"/keystore.pfx"))
;; We create a file for our "key store" capable of securely hosting one or several key pairs,
;; our key pair under an alias and protected by a password. Lastly, the updated key store is
;; saved to the file.
;;
(-> ($.pfx/create file)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file))
;; At any later time, we can load that file and retrieve our key pair by providing its alias and
;; its password.
;;
(= key-pair
(-> ($.pfx/load file)
($.pfx/key-pair-get "my-key-pair"
"my-password")))
;;
;; Although not mandatory, it is a good idea also specifying a password for the key store itself
;; when using `$.pfx/create`, `$.pfx/save`, and `$.pfx/load`.
;;
)
| true |
(ns convex.recipe.key-pair
"Key pairs are essential, they are used by clients to sign transactions and by peers to sign
blocks of transactions.
This example shows how to create a key pair and store it securely in a PFX file.
Storing key pairs is always a sensitive topic. A PFX file allows storing one or several key pairs where
each is given a alias and protected by a dedicated password. The file itself can be protected by a
password as well.
Creating and handling Ed25519 key pairs is done using namespace `convex.sign`.
Creating and handling PFX iles is done using namespace `convex.pfx`.
More information about public-key cryptography: https://en.wikipedia.org/wiki/Public-key_cryptography"
{:author "PI:NAME:<NAME>END_PI"}
(:require [convex.pfx :as $.pfx]
[convex.sign :as $.sign]))
;;;;;;;;;; One plausible example
(defn retrieve
"Tries to load the key pair from file 'keystore.pfx' in given `dir`.
When not found, generates a new key pair and saves it in a new file. A real application might require more sophisticated error handling.
Returns the key pair."
[dir]
(let [file-key-store (str dir
"/keystore.pfx")]
(try
(-> ($.pfx/load file-key-store)
($.pfx/key-pair-get "my-key-pair"
"my-password"))
(catch Throwable _ex
(let [key-pair ($.sign/ed25519)]
(-> ($.pfx/create file-key-store)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file-key-store))
key-pair)))))
;;;;;;;;;;
(comment
;; Example directory where key pair will be stored.
;;
(def dir
"private/recipe/key-pair/")
;; The first time, the key pair is generated and stored in a PFX file.
;;
;; Each subsequent time, the key pair is always retrieved from that file.
;;
;; Deleting that 'keystore.pfx' file in this directory will lose it forever.
;;
(retrieve dir)
;;
;; Let us inspect the core ideas in `retrieve`.
;;
;; Generating a key pair.
;;
(def key-pair
PI:KEY:<KEY>END_PI.sign/ed25519))
;; File for storing our "key store" capable of securely hosting one or several key pairs.
;;
(def file
(str dir
"/keystore.pfx"))
;; We create a file for our "key store" capable of securely hosting one or several key pairs,
;; our key pair under an alias and protected by a password. Lastly, the updated key store is
;; saved to the file.
;;
(-> ($.pfx/create file)
($.pfx/key-pair-set "my-key-pair"
key-pair
"my-password")
($.pfx/save file))
;; At any later time, we can load that file and retrieve our key pair by providing its alias and
;; its password.
;;
(= key-pair
(-> ($.pfx/load file)
($.pfx/key-pair-get "my-key-pair"
"my-password")))
;;
;; Although not mandatory, it is a good idea also specifying a password for the key store itself
;; when using `$.pfx/create`, `$.pfx/save`, and `$.pfx/load`.
;;
)
|
[
{
"context": "ch -- Predicate Logic, tests\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 84,
"score": 0.99986332654953,
"start": 70,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] |
test/lwb/pred/substitution_test.clj
|
esb-lwb/lwb
| 22 |
; lwb Logic WorkBench -- Predicate Logic, tests
; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.substitution-test
(:require [clojure.test :refer :all]
[lwb.pred.substitution :refer :all]
[clojure.spec.test.alpha :as stest]))
(stest/instrument)
(deftest vars-in-term-test
(is (= #{} (#'lwb.pred.substitution/vars-in-term :i)))
(is (= #{} (#'lwb.pred.substitution/vars-in-term '(f :i))))
(is (= '#{x} (#'lwb.pred.substitution/vars-in-term '(f x))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y :e))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f (g (h x y))))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(f = x y))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(and x y))))
)
(deftest freefor?-test
(is (= true (freefor? '(P x) 'x :t)))
(is (= true
(freefor? '(forall [x] (and (impl (P x) (Q x)) (S x y))) 'x '(f x y))))
(is (= true
(freefor? '(impl (forall [x] (and (P x) (Q x))) (or (not (P x)) (Q y))) 'x '(f x y))))
(is (= false
(freefor? '(and (S x) (forall [y] (impl (P x) (Q y)))) 'x '(f x y))))
(is (= false
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x y)))) 'y 'x)))
(is (= true
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x z)))) 'y 'x)))
)
(deftest substitution-test
(is (= '(P :e) (substitution '(P x) 'x :e)))
(is (= '(P (f x)) (substitution '(P x) 'x '(f x))))
(is (= '(P (f (g x))) (substitution '(P x) 'x '(f (g x)))))
(is (= '(and (P :e) (forall [x] (S x))) (substitution '(and (P x) (forall [x] (S x))) 'x :e)))
(is (thrown? Exception (substitution '(exists [y] (R x y)) 'x 'y)))
)
(run-tests)
|
33507
|
; lwb Logic WorkBench -- Predicate Logic, tests
; Copyright (c) 2016 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.substitution-test
(:require [clojure.test :refer :all]
[lwb.pred.substitution :refer :all]
[clojure.spec.test.alpha :as stest]))
(stest/instrument)
(deftest vars-in-term-test
(is (= #{} (#'lwb.pred.substitution/vars-in-term :i)))
(is (= #{} (#'lwb.pred.substitution/vars-in-term '(f :i))))
(is (= '#{x} (#'lwb.pred.substitution/vars-in-term '(f x))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y :e))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f (g (h x y))))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(f = x y))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(and x y))))
)
(deftest freefor?-test
(is (= true (freefor? '(P x) 'x :t)))
(is (= true
(freefor? '(forall [x] (and (impl (P x) (Q x)) (S x y))) 'x '(f x y))))
(is (= true
(freefor? '(impl (forall [x] (and (P x) (Q x))) (or (not (P x)) (Q y))) 'x '(f x y))))
(is (= false
(freefor? '(and (S x) (forall [y] (impl (P x) (Q y)))) 'x '(f x y))))
(is (= false
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x y)))) 'y 'x)))
(is (= true
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x z)))) 'y 'x)))
)
(deftest substitution-test
(is (= '(P :e) (substitution '(P x) 'x :e)))
(is (= '(P (f x)) (substitution '(P x) 'x '(f x))))
(is (= '(P (f (g x))) (substitution '(P x) 'x '(f (g x)))))
(is (= '(and (P :e) (forall [x] (S x))) (substitution '(and (P x) (forall [x] (S x))) 'x :e)))
(is (thrown? Exception (substitution '(exists [y] (R x y)) 'x 'y)))
)
(run-tests)
| true |
; lwb Logic WorkBench -- Predicate Logic, tests
; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.substitution-test
(:require [clojure.test :refer :all]
[lwb.pred.substitution :refer :all]
[clojure.spec.test.alpha :as stest]))
(stest/instrument)
(deftest vars-in-term-test
(is (= #{} (#'lwb.pred.substitution/vars-in-term :i)))
(is (= #{} (#'lwb.pred.substitution/vars-in-term '(f :i))))
(is (= '#{x} (#'lwb.pred.substitution/vars-in-term '(f x))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f x y :e))))
(is (= '#{x y} (#'lwb.pred.substitution/vars-in-term '(f (g (h x y))))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(f = x y))))
(is (thrown? Exception (#'lwb.pred.substitution/vars-in-term '(and x y))))
)
(deftest freefor?-test
(is (= true (freefor? '(P x) 'x :t)))
(is (= true
(freefor? '(forall [x] (and (impl (P x) (Q x)) (S x y))) 'x '(f x y))))
(is (= true
(freefor? '(impl (forall [x] (and (P x) (Q x))) (or (not (P x)) (Q y))) 'x '(f x y))))
(is (= false
(freefor? '(and (S x) (forall [y] (impl (P x) (Q y)))) 'x '(f x y))))
(is (= false
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x y)))) 'y 'x)))
(is (= true
(freefor? '(exists [z] (impl (R z y) (forall [x] (R x z)))) 'y 'x)))
)
(deftest substitution-test
(is (= '(P :e) (substitution '(P x) 'x :e)))
(is (= '(P (f x)) (substitution '(P x) 'x '(f x))))
(is (= '(P (f (g x))) (substitution '(P x) 'x '(f (g x)))))
(is (= '(and (P :e) (forall [x] (S x))) (substitution '(and (P x) (forall [x] (S x))) 'x :e)))
(is (thrown? Exception (substitution '(exists [y] (R x y)) 'x 'y)))
)
(run-tests)
|
[
{
"context": " [\"\n insert into address(name,email)\n values('Sean', '[email protected]')\n \"])\n (jdbc/execute! ds [\"selec",
"end": 360,
"score": 0.9997832179069519,
"start": 356,
"tag": "NAME",
"value": "Sean"
},
{
"context": "sert into address(name,email)\n values('Sean', '[email protected]')\n \"])\n (jdbc/execute! ds [\"select * from addre",
"end": 374,
"score": 0.9999284744262695,
"start": 364,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " * from address\"])\n ;=> [#:ADDRESS{:ID 1, :NAME \"Sean\", :EMAIL \"[email protected]\"}]\n\n (def db {:dbtype \"sqli",
"end": 465,
"score": 0.999793529510498,
"start": 461,
"tag": "NAME",
"value": "Sean"
},
{
"context": "\"])\n ;=> [#:ADDRESS{:ID 1, :NAME \"Sean\", :EMAIL \"[email protected]\"}]\n\n (def db {:dbtype \"sqlite\" :dbname \"db_p10.d",
"end": 486,
"score": 0.9999279975891113,
"start": 476,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " ;=>\n ;[#:contacts{:contact_id 101, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone \"",
"end": 679,
"score": 0.9998354911804199,
"start": 676,
"tag": "NAME",
"value": "ali"
},
{
"context": "s{:contact_id 101, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone \"+90(555)...\"}\n ; #",
"end": 698,
"score": 0.9995652437210083,
"start": 694,
"tag": "NAME",
"value": "veli"
},
{
"context": "01, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone \"+90(555)...\"}\n ; #:contacts{:contact_i",
"end": 718,
"score": 0.9999224543571472,
"start": 709,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "..\"}\n ; #:contacts{:contact_id 103, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone ",
"end": 791,
"score": 0.9998287558555603,
"start": 788,
"tag": "NAME",
"value": "ali"
},
{
"context": "s{:contact_id 103, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone \"+90(555)2...\"}]\n\n ",
"end": 810,
"score": 0.9995564222335815,
"start": 806,
"tag": "NAME",
"value": "veli"
},
{
"context": "03, :first_name \"ali\", :last_name \"veli\", :email \"[email protected]\", :phone \"+90(555)2...\"}]\n\n (jdbc/execute! ds [\"",
"end": 831,
"score": 0.9999238848686218,
"start": 821,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
clj/ex/book_practicalli_clojure_webapps/p01/src/practicalli/p09.clj
|
mertnuhoglu/study
| 1 |
(ns practicalli.p09
(:require [next.jdbc :as jdbc]))
(comment
(def db {:dbtype "h2" :dbname "example"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["
create table address (
id int auto_increment primary key,
name varchar(32),
email varchar(255)
)
"])
(jdbc/execute! ds ["
insert into address(name,email)
values('Sean', '[email protected]')
"])
(jdbc/execute! ds ["select * from address"])
;=> [#:ADDRESS{:ID 1, :NAME "Sean", :EMAIL "[email protected]"}]
(def db {:dbtype "sqlite" :dbname "db_p10.db"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["select * from contacts"])
;=>
;[#:contacts{:contact_id 101, :first_name "ali", :last_name "veli", :email "[email protected]", :phone "+90(555)..."}
; #:contacts{:contact_id 103, :first_name "ali", :last_name "veli", :email "[email protected]", :phone "+90(555)2..."}]
(jdbc/execute! ds ["select 3*5 as result"])
;=> [{:result 15}]
,)
|
101942
|
(ns practicalli.p09
(:require [next.jdbc :as jdbc]))
(comment
(def db {:dbtype "h2" :dbname "example"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["
create table address (
id int auto_increment primary key,
name varchar(32),
email varchar(255)
)
"])
(jdbc/execute! ds ["
insert into address(name,email)
values('<NAME>', '<EMAIL>')
"])
(jdbc/execute! ds ["select * from address"])
;=> [#:ADDRESS{:ID 1, :NAME "<NAME>", :EMAIL "<EMAIL>"}]
(def db {:dbtype "sqlite" :dbname "db_p10.db"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["select * from contacts"])
;=>
;[#:contacts{:contact_id 101, :first_name "<NAME>", :last_name "<NAME>", :email "<EMAIL>", :phone "+90(555)..."}
; #:contacts{:contact_id 103, :first_name "<NAME>", :last_name "<NAME>", :email "<EMAIL>", :phone "+90(555)2..."}]
(jdbc/execute! ds ["select 3*5 as result"])
;=> [{:result 15}]
,)
| true |
(ns practicalli.p09
(:require [next.jdbc :as jdbc]))
(comment
(def db {:dbtype "h2" :dbname "example"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["
create table address (
id int auto_increment primary key,
name varchar(32),
email varchar(255)
)
"])
(jdbc/execute! ds ["
insert into address(name,email)
values('PI:NAME:<NAME>END_PI', 'PI:EMAIL:<EMAIL>END_PI')
"])
(jdbc/execute! ds ["select * from address"])
;=> [#:ADDRESS{:ID 1, :NAME "PI:NAME:<NAME>END_PI", :EMAIL "PI:EMAIL:<EMAIL>END_PI"}]
(def db {:dbtype "sqlite" :dbname "db_p10.db"})
(def ds (jdbc/get-datasource db))
(jdbc/execute! ds ["select * from contacts"])
;=>
;[#:contacts{:contact_id 101, :first_name "PI:NAME:<NAME>END_PI", :last_name "PI:NAME:<NAME>END_PI", :email "PI:EMAIL:<EMAIL>END_PI", :phone "+90(555)..."}
; #:contacts{:contact_id 103, :first_name "PI:NAME:<NAME>END_PI", :last_name "PI:NAME:<NAME>END_PI", :email "PI:EMAIL:<EMAIL>END_PI", :phone "+90(555)2..."}]
(jdbc/execute! ds ["select 3*5 as result"])
;=> [{:result 15}]
,)
|
[
{
"context": ";; Copyright (c) 2021 Thomas J. Otterson\n;; \n;; This software is released under the MIT Li",
"end": 40,
"score": 0.9996358752250671,
"start": 22,
"tag": "NAME",
"value": "Thomas J. Otterson"
}
] |
src/barandis/euler/p15.clj
|
Barandis/euler-clojure
| 0 |
;; Copyright (c) 2021 Thomas J. Otterson
;;
;; This software is released under the MIT License.
;; https://opensource.org/licenses/MIT
;; Solves Project Euler problem 15:
;;
;; Starting in the top left corner of a 2×2 grid, and only being able to move to
;; the right and down, there are exactly 6 routes to the bottom right corner.
;;
;; How many such routes are there through a 20×20 grid?
;; The number of lattice paths in an n x n grid is the same as the number of
;; combinations of n elements from a set of 2n objects, so we simply calculate
;; 2nCn.
;;
;; This solution can be run using `clojure -X:p15`. It will default to the 20
;; grid size described in the problem. To run with another size, use `clojure
;; -X:p15 :size 2` or similar.
(ns barandis.euler.p15)
(defn- combinations
"Calculates the number of possible combinations of `r` elements from a set of
`n` objects (nCr)."
[n r]
(let [fact #(loop [x % acc 1] (if (<= x 1) acc (recur (dec x) (* x acc))))
n (bigint n)
r (bigint r)]
(/ (fact n) (* (fact r) (fact (- n r))))))
(defn- num-paths
"Calculates the number of lattice paths in an `n`x`n` grid."
[n]
(combinations (* 2 n) n))
(defn solve
"Displays the number of lattice paths in a (:size data) x (:size data) grid.
This number defaults to 20, making the displayed value the solution to
Project Euler problem 15."
([] (solve {}))
([data] (-> (get data :size 20) num-paths long println time)))
|
32753
|
;; Copyright (c) 2021 <NAME>
;;
;; This software is released under the MIT License.
;; https://opensource.org/licenses/MIT
;; Solves Project Euler problem 15:
;;
;; Starting in the top left corner of a 2×2 grid, and only being able to move to
;; the right and down, there are exactly 6 routes to the bottom right corner.
;;
;; How many such routes are there through a 20×20 grid?
;; The number of lattice paths in an n x n grid is the same as the number of
;; combinations of n elements from a set of 2n objects, so we simply calculate
;; 2nCn.
;;
;; This solution can be run using `clojure -X:p15`. It will default to the 20
;; grid size described in the problem. To run with another size, use `clojure
;; -X:p15 :size 2` or similar.
(ns barandis.euler.p15)
(defn- combinations
"Calculates the number of possible combinations of `r` elements from a set of
`n` objects (nCr)."
[n r]
(let [fact #(loop [x % acc 1] (if (<= x 1) acc (recur (dec x) (* x acc))))
n (bigint n)
r (bigint r)]
(/ (fact n) (* (fact r) (fact (- n r))))))
(defn- num-paths
"Calculates the number of lattice paths in an `n`x`n` grid."
[n]
(combinations (* 2 n) n))
(defn solve
"Displays the number of lattice paths in a (:size data) x (:size data) grid.
This number defaults to 20, making the displayed value the solution to
Project Euler problem 15."
([] (solve {}))
([data] (-> (get data :size 20) num-paths long println time)))
| true |
;; Copyright (c) 2021 PI:NAME:<NAME>END_PI
;;
;; This software is released under the MIT License.
;; https://opensource.org/licenses/MIT
;; Solves Project Euler problem 15:
;;
;; Starting in the top left corner of a 2×2 grid, and only being able to move to
;; the right and down, there are exactly 6 routes to the bottom right corner.
;;
;; How many such routes are there through a 20×20 grid?
;; The number of lattice paths in an n x n grid is the same as the number of
;; combinations of n elements from a set of 2n objects, so we simply calculate
;; 2nCn.
;;
;; This solution can be run using `clojure -X:p15`. It will default to the 20
;; grid size described in the problem. To run with another size, use `clojure
;; -X:p15 :size 2` or similar.
(ns barandis.euler.p15)
(defn- combinations
"Calculates the number of possible combinations of `r` elements from a set of
`n` objects (nCr)."
[n r]
(let [fact #(loop [x % acc 1] (if (<= x 1) acc (recur (dec x) (* x acc))))
n (bigint n)
r (bigint r)]
(/ (fact n) (* (fact r) (fact (- n r))))))
(defn- num-paths
"Calculates the number of lattice paths in an `n`x`n` grid."
[n]
(combinations (* 2 n) n))
(defn solve
"Displays the number of lattice paths in a (:size data) x (:size data) grid.
This number defaults to 20, making the displayed value the solution to
Project Euler problem 15."
([] (solve {}))
([data] (-> (get data :size 20) num-paths long println time)))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-10-31\"\n :do",
"end": 109,
"score": 0.9998843669891357,
"start": 87,
"tag": "NAME",
"value": "Kristina Lisa Klinkner"
},
{
"context": "n-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-10-31\"\n :doc \"Iris data unit-te",
"end": 129,
"score": 0.9998747706413269,
"start": 111,
"tag": "NAME",
"value": "John Alan McDonald"
}
] |
src/test/clojure/taiga/test/classify/iris/iris.clj
|
wahpenayo/taiga
| 4 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "Kristina Lisa Klinkner, John Alan McDonald" :date "2016-10-31"
:doc "Iris data unit-tests." }
taiga.test.classify.iris.iris
(:require [clojure.java.io :as io]
[clojure.test :as test]
[zana.api :as z]
[taiga.test.classify.iris.record :as record]))
;; mvn clean -Dtest=taiga.test.classify.iris.iris clojure:test > tests.txt
;;------------------------------------------------------------------------------
(defn options []
(test/is (= record/attributes
{:ground-truth record/species
:sepal-length record/sepal-length
:sepal-width record/sepal-width
:petal-length record/petal-length
:petal-width record/petal-width}))
(let [data (record/read-tsv-file
(io/file "data" "IrisNoSetosaBinaryData.tsv"))
_ (test/is (== 100 (z/count data)))
nterms 512
mincount 1
predictors (dissoc record/attributes :ground-truth :prediction)
mtry (int (Math/round (Math/sqrt (z/count predictors))))
opts {:data data :attributes record/attributes
:nterms 512 :mincount 1 :mtry mtry}]
(test/is (== 5 (count (:attributes opts))))
(test/is (== 2 (:mtry opts)))
opts))
;;------------------------------------------------------------------------------
|
5072
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>, <NAME>" :date "2016-10-31"
:doc "Iris data unit-tests." }
taiga.test.classify.iris.iris
(:require [clojure.java.io :as io]
[clojure.test :as test]
[zana.api :as z]
[taiga.test.classify.iris.record :as record]))
;; mvn clean -Dtest=taiga.test.classify.iris.iris clojure:test > tests.txt
;;------------------------------------------------------------------------------
(defn options []
(test/is (= record/attributes
{:ground-truth record/species
:sepal-length record/sepal-length
:sepal-width record/sepal-width
:petal-length record/petal-length
:petal-width record/petal-width}))
(let [data (record/read-tsv-file
(io/file "data" "IrisNoSetosaBinaryData.tsv"))
_ (test/is (== 100 (z/count data)))
nterms 512
mincount 1
predictors (dissoc record/attributes :ground-truth :prediction)
mtry (int (Math/round (Math/sqrt (z/count predictors))))
opts {:data data :attributes record/attributes
:nterms 512 :mincount 1 :mtry mtry}]
(test/is (== 5 (count (:attributes opts))))
(test/is (== 2 (:mtry opts)))
opts))
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :date "2016-10-31"
:doc "Iris data unit-tests." }
taiga.test.classify.iris.iris
(:require [clojure.java.io :as io]
[clojure.test :as test]
[zana.api :as z]
[taiga.test.classify.iris.record :as record]))
;; mvn clean -Dtest=taiga.test.classify.iris.iris clojure:test > tests.txt
;;------------------------------------------------------------------------------
(defn options []
(test/is (= record/attributes
{:ground-truth record/species
:sepal-length record/sepal-length
:sepal-width record/sepal-width
:petal-length record/petal-length
:petal-width record/petal-width}))
(let [data (record/read-tsv-file
(io/file "data" "IrisNoSetosaBinaryData.tsv"))
_ (test/is (== 100 (z/count data)))
nterms 512
mincount 1
predictors (dissoc record/attributes :ground-truth :prediction)
mtry (int (Math/round (Math/sqrt (z/count predictors))))
opts {:data data :attributes record/attributes
:nterms 512 :mincount 1 :mtry mtry}]
(test/is (== 5 (count (:attributes opts))))
(test/is (== 2 (:mtry opts)))
opts))
;;------------------------------------------------------------------------------
|
[
{
"context": "span \"A project by \" [:a {:href (home-page-url)} \"Jesse Claven\"] \".\"]])\n\n(defn notice\n []\n [:div.notice\n [:s",
"end": 3833,
"score": 0.9994524121284485,
"start": 3821,
"tag": "NAME",
"value": "Jesse Claven"
},
{
"context": "s) \")\"]\n [:span [:a {:href \"https://github.com/jesse-c/Brewfile#templates\"} \"Add\"]]]\n [:ul.templates-l",
"end": 4360,
"score": 0.9996505379676819,
"start": 4353,
"tag": "USERNAME",
"value": "jesse-c"
},
{
"context": " [:li \"Install \" [:a {:href \"https://github.com/mas-cli/mas\"} \"mas\"]]\n [:li \"Generate a Brewfile and p",
"end": 4685,
"score": 0.9982266426086426,
"start": 4678,
"tag": "USERNAME",
"value": "mas-cli"
},
{
"context": "(for [x api-endpoints]\n [:tr {:key (str \"api-endpoint-\" x)}\n [:td (:desc x)]\n [:t",
"end": 5315,
"score": 0.5385255217552185,
"start": 5315,
"tag": "KEY",
"value": ""
},
{
"context": " project \"\n [:a {:href \"https://github.com/jesse-c/Brewfile\"} \"source code\"]\n \".\"]]])\n\n(defn ",
"end": 5861,
"score": 0.9996541142463684,
"start": 5854,
"tag": "USERNAME",
"value": "jesse-c"
},
{
"context": "Top\"]]\n [:div [:a.home {:href (home-page-url)} \"Jesse Claven\"]]])\n\n(defn ui\n []\n [:div\n [header]\n [notic",
"end": 6038,
"score": 0.9956934452056885,
"start": 6026,
"tag": "NAME",
"value": "Jesse Claven"
}
] |
apps/website/src/brewfile/core.cljs
|
jesse-c/Brewfiles
| 1 |
(ns brewfile.core
(:require [reagent.dom :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]))
;; -- Debugging aids ----------------------------------------------------------
(enable-console-print!)
;; -- Domino 1 - Event Dispatch -----------------------------------------------
;; -- Domino 2 - Event Handlers -----------------------------------------------
(defn seq-contains?
[coll item]
(> (.indexOf coll item) -1))
(rf/reg-event-db
:initialize
(fn [_ _]
{:term ""
:selected []
:search-focused false
:terms-focused false}))
(rf/reg-event-db
:term-change
(fn [db [_ new-term-value]]
(assoc db :term new-term-value)))
(rf/reg-event-db
:term-select
(fn [db [_ term]]
(let [selected (:selected db)]
(if-not (seq-contains? selected term)
(assoc db :selected (conj selected term))
db))))
(rf/reg-event-db
:term-unselect
(fn [db [_ term]]
(let [selected (:selected db)]
(if (seq-contains? selected term)
(assoc db :selected (remove #(= % term) selected))
db))))
(rf/reg-event-db
:search-focus
(fn [db _]
(assoc db :search-focused true)))
(rf/reg-event-db
:search-unfocus
(fn [db _]
(assoc db :search-focused false)))
(rf/reg-event-db
:terms-focus
(fn [db _]
(assoc db :terms-focused true)))
(rf/reg-event-db
:terms-unfocus
(fn [db _]
(assoc db :terms-focused false)))
;; -- Domino 4 - Query -------------------------------------------------------
(rf/reg-sub
:term
(fn [db _]
(:term db)))
(rf/reg-sub
:selected
(fn [db _]
(:selected db)))
(rf/reg-sub
:search-focused
(fn [db _]
(:search-focused db)))
(rf/reg-sub
:terms-focused
(fn [db _]
(:terms-focused db)))
;; -- Domino 5 - View Functions ----------------------------------------------
(def brewfiles
["Core" "DNS" "Dev-Go" "Dev-HTTP" "Neovim" "Privacy" "Python" "Vim"])
(defn home-page-url [] "https://www.jesseclaven.com/")
(defn term-chooser-list
[remaining]
(for [x remaining]
[:li {:key (str "term-chooser-" x),
:on-click #(rf/dispatch [:term-select x])}
x]))
(defn term-chooser-empty
[]
[:li [:em "No matches"]])
(defn term-chooser
[]
(let [selected @(rf/subscribe [:selected])
term @(rf/subscribe [:term])
remaining (filterv #(str/includes? (str/lower-case %) (str/lower-case term))
(filterv #(not (seq-contains? selected %)) brewfiles))]
[:ul {:class (if (or @(rf/subscribe [:search-focused]) @(rf/subscribe [:terms-focused]))
"term-chooser focused"
"term-chooser unfocused")
:on-mouse-leave #(rf/dispatch [:terms-unfocus])
:on-mouse-enter #(rf/dispatch [:terms-focus])}
(if (> (count remaining) 0)
(term-chooser-list remaining)
(term-chooser-empty))]))
(defn term-input
[]
[:div
[:input {:type "text"
:class "search-input"
:value @(rf/subscribe [:term]),
:on-change #(rf/dispatch [:term-change (-> % .-target .-value)])
:on-blur #(rf/dispatch [:search-unfocus])
:on-focus #(rf/dispatch [:search-focus])}]
(term-chooser)])
(defn term-selected
[]
(let [selected @(rf/subscribe [:selected])]
[:div.selected
(for [x selected]
[:div {:key (str "term-selected-" x),
:on-click #(rf/dispatch [:term-unselect x])}
x])]))
(defn selected-to-href
[selected]
(str "/api/generate/" (str/join "," selected)))
(defn generate-button
[]
[:a {:href (selected-to-href @(rf/subscribe [:selected])),
:class "generate-button",
:role "button"}
[:span "Generate"]])
(defn code-inline
[content]
[:code content])
(defn header
[]
[:div.header
[:span "A project by " [:a {:href (home-page-url)} "Jesse Claven"] "."]])
(defn notice
[]
[:div.notice
[:span "NEW!"]
[:span "Welcome to Brewfiles!"]])
(defn intro
[]
[:div
[:h1 {:name "intro"} "Brewfiles"]
[:p "Generate Brewfiles from existing templates."]])
(defn search
[]
[:div.search-container
[:div.search
(term-input)
(generate-button)]
(term-selected)])
(defn templates
[]
[:div
[:div.templates-header
[:h2 "Templates"]
[:span.templates-header-count "(" (count brewfiles) ")"]
[:span [:a {:href "https://github.com/jesse-c/Brewfile#templates"} "Add"]]]
[:ul.templates-list
(for [x brewfiles]
[:li {:key (str "template-" x)} x])]])
(defn instructions
[]
[:div.instructions
[:h2 "Instructions"]
[:ol
[:li "Install " [:a {:href "https://www.brew.sh"} "Homebrew"]]
[:li "Install " [:a {:href "https://github.com/mas-cli/mas"} "mas"]]
[:li "Generate a Brewfile and place it in your " (code-inline "$HOME")]
[:li "Run " (code-inline "brew bundle")]]])
(def api-endpoints [{:desc "List all", :endpoint "list/$t1,$t2,$tX", :method "GET"}
{:desc "Search", :endpoint "search/$t1,$t2,$tX", :method "GET"}
{:desc "Generate", :endpoint "generate/$t1,$t2,$tX", :method "GET"}
{:desc "Help", :endpoint "", :method "GET"}])
(def base-endpoint "http://brewfile.io/api/")
(defn api
[]
[:div.api
[:h2 "API"]
[:table
[:tbody
(for [x api-endpoints]
[:tr {:key (str "api-endpoint-" x)}
[:td (:desc x)]
[:td (code-inline (:method x))]
[:td (-> x (get :endpoint) (#(conj [base-endpoint] %)) (str/join) (code-inline))]])]]
[:div "Where " (code-inline "$tX") " is a term, e.g. " (code-inline (rand-nth brewfiles)) "."]])
(defn notes
[]
[:div.notes
[:p [:span "Thank you to the people behind " [:a {:href "https://brew.sh"} "Homebrew"] " and " [:a {:href "https://www.gitignore.io"} "Gitignore.io."]]]
[:p [:span
"View project "
[:a {:href "https://github.com/jesse-c/Brewfile"} "source code"]
"."]]])
(defn footer
[]
[:div.footer
[:div [:a.top {:href "/#intro"} "↑ Top"]]
[:div [:a.home {:href (home-page-url)} "Jesse Claven"]]])
(defn ui
[]
[:div
[header]
[notice]
[:div.container
[intro]
[search]
[:hr]
[templates]
[:hr]
[instructions]
[:hr]
[api]
[:hr]
[notes]
[:hr]
[footer]]])
;; -- Entry Point -------------------------------------------------------------
(defn render
[]
(reagent/render [ui]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn ^:export init
[]
(rf/dispatch-sync [:initialize]) ;; put a value into application state
(render)) ;; mount the application's ui into '<div id="app" />'
|
112007
|
(ns brewfile.core
(:require [reagent.dom :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]))
;; -- Debugging aids ----------------------------------------------------------
(enable-console-print!)
;; -- Domino 1 - Event Dispatch -----------------------------------------------
;; -- Domino 2 - Event Handlers -----------------------------------------------
(defn seq-contains?
[coll item]
(> (.indexOf coll item) -1))
(rf/reg-event-db
:initialize
(fn [_ _]
{:term ""
:selected []
:search-focused false
:terms-focused false}))
(rf/reg-event-db
:term-change
(fn [db [_ new-term-value]]
(assoc db :term new-term-value)))
(rf/reg-event-db
:term-select
(fn [db [_ term]]
(let [selected (:selected db)]
(if-not (seq-contains? selected term)
(assoc db :selected (conj selected term))
db))))
(rf/reg-event-db
:term-unselect
(fn [db [_ term]]
(let [selected (:selected db)]
(if (seq-contains? selected term)
(assoc db :selected (remove #(= % term) selected))
db))))
(rf/reg-event-db
:search-focus
(fn [db _]
(assoc db :search-focused true)))
(rf/reg-event-db
:search-unfocus
(fn [db _]
(assoc db :search-focused false)))
(rf/reg-event-db
:terms-focus
(fn [db _]
(assoc db :terms-focused true)))
(rf/reg-event-db
:terms-unfocus
(fn [db _]
(assoc db :terms-focused false)))
;; -- Domino 4 - Query -------------------------------------------------------
(rf/reg-sub
:term
(fn [db _]
(:term db)))
(rf/reg-sub
:selected
(fn [db _]
(:selected db)))
(rf/reg-sub
:search-focused
(fn [db _]
(:search-focused db)))
(rf/reg-sub
:terms-focused
(fn [db _]
(:terms-focused db)))
;; -- Domino 5 - View Functions ----------------------------------------------
(def brewfiles
["Core" "DNS" "Dev-Go" "Dev-HTTP" "Neovim" "Privacy" "Python" "Vim"])
(defn home-page-url [] "https://www.jesseclaven.com/")
(defn term-chooser-list
[remaining]
(for [x remaining]
[:li {:key (str "term-chooser-" x),
:on-click #(rf/dispatch [:term-select x])}
x]))
(defn term-chooser-empty
[]
[:li [:em "No matches"]])
(defn term-chooser
[]
(let [selected @(rf/subscribe [:selected])
term @(rf/subscribe [:term])
remaining (filterv #(str/includes? (str/lower-case %) (str/lower-case term))
(filterv #(not (seq-contains? selected %)) brewfiles))]
[:ul {:class (if (or @(rf/subscribe [:search-focused]) @(rf/subscribe [:terms-focused]))
"term-chooser focused"
"term-chooser unfocused")
:on-mouse-leave #(rf/dispatch [:terms-unfocus])
:on-mouse-enter #(rf/dispatch [:terms-focus])}
(if (> (count remaining) 0)
(term-chooser-list remaining)
(term-chooser-empty))]))
(defn term-input
[]
[:div
[:input {:type "text"
:class "search-input"
:value @(rf/subscribe [:term]),
:on-change #(rf/dispatch [:term-change (-> % .-target .-value)])
:on-blur #(rf/dispatch [:search-unfocus])
:on-focus #(rf/dispatch [:search-focus])}]
(term-chooser)])
(defn term-selected
[]
(let [selected @(rf/subscribe [:selected])]
[:div.selected
(for [x selected]
[:div {:key (str "term-selected-" x),
:on-click #(rf/dispatch [:term-unselect x])}
x])]))
(defn selected-to-href
[selected]
(str "/api/generate/" (str/join "," selected)))
(defn generate-button
[]
[:a {:href (selected-to-href @(rf/subscribe [:selected])),
:class "generate-button",
:role "button"}
[:span "Generate"]])
(defn code-inline
[content]
[:code content])
(defn header
[]
[:div.header
[:span "A project by " [:a {:href (home-page-url)} "<NAME>"] "."]])
(defn notice
[]
[:div.notice
[:span "NEW!"]
[:span "Welcome to Brewfiles!"]])
(defn intro
[]
[:div
[:h1 {:name "intro"} "Brewfiles"]
[:p "Generate Brewfiles from existing templates."]])
(defn search
[]
[:div.search-container
[:div.search
(term-input)
(generate-button)]
(term-selected)])
(defn templates
[]
[:div
[:div.templates-header
[:h2 "Templates"]
[:span.templates-header-count "(" (count brewfiles) ")"]
[:span [:a {:href "https://github.com/jesse-c/Brewfile#templates"} "Add"]]]
[:ul.templates-list
(for [x brewfiles]
[:li {:key (str "template-" x)} x])]])
(defn instructions
[]
[:div.instructions
[:h2 "Instructions"]
[:ol
[:li "Install " [:a {:href "https://www.brew.sh"} "Homebrew"]]
[:li "Install " [:a {:href "https://github.com/mas-cli/mas"} "mas"]]
[:li "Generate a Brewfile and place it in your " (code-inline "$HOME")]
[:li "Run " (code-inline "brew bundle")]]])
(def api-endpoints [{:desc "List all", :endpoint "list/$t1,$t2,$tX", :method "GET"}
{:desc "Search", :endpoint "search/$t1,$t2,$tX", :method "GET"}
{:desc "Generate", :endpoint "generate/$t1,$t2,$tX", :method "GET"}
{:desc "Help", :endpoint "", :method "GET"}])
(def base-endpoint "http://brewfile.io/api/")
(defn api
[]
[:div.api
[:h2 "API"]
[:table
[:tbody
(for [x api-endpoints]
[:tr {:key (str "api<KEY>-endpoint-" x)}
[:td (:desc x)]
[:td (code-inline (:method x))]
[:td (-> x (get :endpoint) (#(conj [base-endpoint] %)) (str/join) (code-inline))]])]]
[:div "Where " (code-inline "$tX") " is a term, e.g. " (code-inline (rand-nth brewfiles)) "."]])
(defn notes
[]
[:div.notes
[:p [:span "Thank you to the people behind " [:a {:href "https://brew.sh"} "Homebrew"] " and " [:a {:href "https://www.gitignore.io"} "Gitignore.io."]]]
[:p [:span
"View project "
[:a {:href "https://github.com/jesse-c/Brewfile"} "source code"]
"."]]])
(defn footer
[]
[:div.footer
[:div [:a.top {:href "/#intro"} "↑ Top"]]
[:div [:a.home {:href (home-page-url)} "<NAME>"]]])
(defn ui
[]
[:div
[header]
[notice]
[:div.container
[intro]
[search]
[:hr]
[templates]
[:hr]
[instructions]
[:hr]
[api]
[:hr]
[notes]
[:hr]
[footer]]])
;; -- Entry Point -------------------------------------------------------------
(defn render
[]
(reagent/render [ui]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn ^:export init
[]
(rf/dispatch-sync [:initialize]) ;; put a value into application state
(render)) ;; mount the application's ui into '<div id="app" />'
| true |
(ns brewfile.core
(:require [reagent.dom :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]))
;; -- Debugging aids ----------------------------------------------------------
(enable-console-print!)
;; -- Domino 1 - Event Dispatch -----------------------------------------------
;; -- Domino 2 - Event Handlers -----------------------------------------------
(defn seq-contains?
[coll item]
(> (.indexOf coll item) -1))
(rf/reg-event-db
:initialize
(fn [_ _]
{:term ""
:selected []
:search-focused false
:terms-focused false}))
(rf/reg-event-db
:term-change
(fn [db [_ new-term-value]]
(assoc db :term new-term-value)))
(rf/reg-event-db
:term-select
(fn [db [_ term]]
(let [selected (:selected db)]
(if-not (seq-contains? selected term)
(assoc db :selected (conj selected term))
db))))
(rf/reg-event-db
:term-unselect
(fn [db [_ term]]
(let [selected (:selected db)]
(if (seq-contains? selected term)
(assoc db :selected (remove #(= % term) selected))
db))))
(rf/reg-event-db
:search-focus
(fn [db _]
(assoc db :search-focused true)))
(rf/reg-event-db
:search-unfocus
(fn [db _]
(assoc db :search-focused false)))
(rf/reg-event-db
:terms-focus
(fn [db _]
(assoc db :terms-focused true)))
(rf/reg-event-db
:terms-unfocus
(fn [db _]
(assoc db :terms-focused false)))
;; -- Domino 4 - Query -------------------------------------------------------
(rf/reg-sub
:term
(fn [db _]
(:term db)))
(rf/reg-sub
:selected
(fn [db _]
(:selected db)))
(rf/reg-sub
:search-focused
(fn [db _]
(:search-focused db)))
(rf/reg-sub
:terms-focused
(fn [db _]
(:terms-focused db)))
;; -- Domino 5 - View Functions ----------------------------------------------
(def brewfiles
["Core" "DNS" "Dev-Go" "Dev-HTTP" "Neovim" "Privacy" "Python" "Vim"])
(defn home-page-url [] "https://www.jesseclaven.com/")
(defn term-chooser-list
[remaining]
(for [x remaining]
[:li {:key (str "term-chooser-" x),
:on-click #(rf/dispatch [:term-select x])}
x]))
(defn term-chooser-empty
[]
[:li [:em "No matches"]])
(defn term-chooser
[]
(let [selected @(rf/subscribe [:selected])
term @(rf/subscribe [:term])
remaining (filterv #(str/includes? (str/lower-case %) (str/lower-case term))
(filterv #(not (seq-contains? selected %)) brewfiles))]
[:ul {:class (if (or @(rf/subscribe [:search-focused]) @(rf/subscribe [:terms-focused]))
"term-chooser focused"
"term-chooser unfocused")
:on-mouse-leave #(rf/dispatch [:terms-unfocus])
:on-mouse-enter #(rf/dispatch [:terms-focus])}
(if (> (count remaining) 0)
(term-chooser-list remaining)
(term-chooser-empty))]))
(defn term-input
[]
[:div
[:input {:type "text"
:class "search-input"
:value @(rf/subscribe [:term]),
:on-change #(rf/dispatch [:term-change (-> % .-target .-value)])
:on-blur #(rf/dispatch [:search-unfocus])
:on-focus #(rf/dispatch [:search-focus])}]
(term-chooser)])
(defn term-selected
[]
(let [selected @(rf/subscribe [:selected])]
[:div.selected
(for [x selected]
[:div {:key (str "term-selected-" x),
:on-click #(rf/dispatch [:term-unselect x])}
x])]))
(defn selected-to-href
[selected]
(str "/api/generate/" (str/join "," selected)))
(defn generate-button
[]
[:a {:href (selected-to-href @(rf/subscribe [:selected])),
:class "generate-button",
:role "button"}
[:span "Generate"]])
(defn code-inline
[content]
[:code content])
(defn header
[]
[:div.header
[:span "A project by " [:a {:href (home-page-url)} "PI:NAME:<NAME>END_PI"] "."]])
(defn notice
[]
[:div.notice
[:span "NEW!"]
[:span "Welcome to Brewfiles!"]])
(defn intro
[]
[:div
[:h1 {:name "intro"} "Brewfiles"]
[:p "Generate Brewfiles from existing templates."]])
(defn search
[]
[:div.search-container
[:div.search
(term-input)
(generate-button)]
(term-selected)])
(defn templates
[]
[:div
[:div.templates-header
[:h2 "Templates"]
[:span.templates-header-count "(" (count brewfiles) ")"]
[:span [:a {:href "https://github.com/jesse-c/Brewfile#templates"} "Add"]]]
[:ul.templates-list
(for [x brewfiles]
[:li {:key (str "template-" x)} x])]])
(defn instructions
[]
[:div.instructions
[:h2 "Instructions"]
[:ol
[:li "Install " [:a {:href "https://www.brew.sh"} "Homebrew"]]
[:li "Install " [:a {:href "https://github.com/mas-cli/mas"} "mas"]]
[:li "Generate a Brewfile and place it in your " (code-inline "$HOME")]
[:li "Run " (code-inline "brew bundle")]]])
(def api-endpoints [{:desc "List all", :endpoint "list/$t1,$t2,$tX", :method "GET"}
{:desc "Search", :endpoint "search/$t1,$t2,$tX", :method "GET"}
{:desc "Generate", :endpoint "generate/$t1,$t2,$tX", :method "GET"}
{:desc "Help", :endpoint "", :method "GET"}])
(def base-endpoint "http://brewfile.io/api/")
(defn api
[]
[:div.api
[:h2 "API"]
[:table
[:tbody
(for [x api-endpoints]
[:tr {:key (str "apiPI:KEY:<KEY>END_PI-endpoint-" x)}
[:td (:desc x)]
[:td (code-inline (:method x))]
[:td (-> x (get :endpoint) (#(conj [base-endpoint] %)) (str/join) (code-inline))]])]]
[:div "Where " (code-inline "$tX") " is a term, e.g. " (code-inline (rand-nth brewfiles)) "."]])
(defn notes
[]
[:div.notes
[:p [:span "Thank you to the people behind " [:a {:href "https://brew.sh"} "Homebrew"] " and " [:a {:href "https://www.gitignore.io"} "Gitignore.io."]]]
[:p [:span
"View project "
[:a {:href "https://github.com/jesse-c/Brewfile"} "source code"]
"."]]])
(defn footer
[]
[:div.footer
[:div [:a.top {:href "/#intro"} "↑ Top"]]
[:div [:a.home {:href (home-page-url)} "PI:NAME:<NAME>END_PI"]]])
(defn ui
[]
[:div
[header]
[notice]
[:div.container
[intro]
[search]
[:hr]
[templates]
[:hr]
[instructions]
[:hr]
[api]
[:hr]
[notes]
[:hr]
[footer]]])
;; -- Entry Point -------------------------------------------------------------
(defn render
[]
(reagent/render [ui]
(js/document.getElementById "app")))
(defn ^:dev/after-load clear-cache-and-render!
[]
;; The `:dev/after-load` metadata causes this function to be called
;; after shadow-cljs hot-reloads code. We force a UI update by clearing
;; the Reframe subscription cache.
(rf/clear-subscription-cache!)
(render))
(defn ^:export init
[]
(rf/dispatch-sync [:initialize]) ;; put a value into application state
(render)) ;; mount the application's ui into '<div id="app" />'
|
[
{
"context": "n \"Clara Rules Engine\"\n :url \"https://github.com/cerner/clara-rules\"\n :license {:name \"Apache License Ve",
"end": 122,
"score": 0.9996697306632996,
"start": 116,
"tag": "USERNAME",
"value": "cerner"
},
{
"context": "scm {:name \"git\"\n :url \"https://github.com/cerner/clara-rules\"}\n :pom-addition [:developers [:deve",
"end": 4785,
"score": 0.9983351230621338,
"start": 4779,
"tag": "USERNAME",
"value": "cerner"
},
{
"context": "s [:developer\n [:id \"rbrush\"]\n [:name \"Ryan Brus",
"end": 4883,
"score": 0.9984209537506104,
"start": 4877,
"tag": "USERNAME",
"value": "rbrush"
},
{
"context": "d \"rbrush\"]\n [:name \"Ryan Brush\"]\n [:url \"http://www",
"end": 4934,
"score": 0.999780535697937,
"start": 4924,
"tag": "NAME",
"value": "Ryan Brush"
}
] |
project.clj
|
defaultUser4/clara-rules
| 0 |
(defproject com.cerner/clara-rules "0.19.0-SNAPSHOT"
:description "Clara Rules Engine"
:url "https://github.com/cerner/clara-rules"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.7.0"]
[prismatic/schema "1.1.6"]]
:profiles {:dev {:dependencies [[org.clojure/math.combinatorics "0.1.3"]
[org.clojure/data.fressian "0.2.1"]]}
:provided {:dependencies [[org.clojure/clojurescript "1.7.170"]]}
:recent-clj {:dependencies [^:replace [org.clojure/clojure "1.9.0"]
^:replace [org.clojure/clojurescript "1.9.946"]]}}
:plugins [[lein-codox "0.10.3" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-javadoc "0.3.0" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-cljsbuild "1.1.7" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-figwheel "0.5.14" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]]
:codox {:namespaces [clara.rules clara.rules.dsl clara.rules.accumulators
clara.rules.listener clara.rules.durability
clara.tools.inspect clara.tools.tracing
clara.tools.fact-graph]
:metadata {:doc/format :markdown}}
:javadoc-opts {:package-names "clara.rules"}
:source-paths ["src/main/clojure"]
:resource-paths []
:test-paths ["src/test/clojure" "src/test/common"]
:java-source-paths ["src/main/java"]
:javac-options ["-target" "1.6" "-source" "1.6"]
:clean-targets ^{:protect false} ["resources/public/js" "target"]
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [;; Simple mode compilation for tests.
{:id "figwheel"
:source-paths ["src/test/clojurescript" "src/test/common"]
:figwheel true
:compiler {:main "clara.test"
:output-to "resources/public/js/simple.js"
:output-dir "resources/public/js/out"
:asset-path "js/out"
:optimizations :none}}
{:id "simple"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/simple.js"
:optimizations :whitespace}}
;; Advanced mode compilation for tests.
{:id "advanced"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/advanced.js"
:optimizations :advanced}}]
:test-commands {"phantom-simple" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/simple.html"]
"phantom-advanced" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/advanced.html"]}}
:repl-options {;; The large number of ClojureScript tests is causing long compilation times
;; to start the REPL.
:timeout 120000}
;; Factoring out the duplication of this test selector function causes an error,
;; perhaps because Leiningen is using this as uneval'ed code.
;; For now just duplicate the line.
:test-selectors {:default (complement (fn [x]
(let [blacklisted-packages #{"generative" "performance"}
patterns (into []
(comp
(map #(str "^clara\\." % ".*"))
(interpose "|"))
blacklisted-packages)]
(some->> x :ns ns-name str (re-matches (re-pattern (apply str patterns)))))))
:generative (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.generative.*")))
:performance (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.performance.*")))}
:scm {:name "git"
:url "https://github.com/cerner/clara-rules"}
:pom-addition [:developers [:developer
[:id "rbrush"]
[:name "Ryan Brush"]
[:url "http://www.clara-rules.org"]]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
|
22065
|
(defproject com.cerner/clara-rules "0.19.0-SNAPSHOT"
:description "Clara Rules Engine"
:url "https://github.com/cerner/clara-rules"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.7.0"]
[prismatic/schema "1.1.6"]]
:profiles {:dev {:dependencies [[org.clojure/math.combinatorics "0.1.3"]
[org.clojure/data.fressian "0.2.1"]]}
:provided {:dependencies [[org.clojure/clojurescript "1.7.170"]]}
:recent-clj {:dependencies [^:replace [org.clojure/clojure "1.9.0"]
^:replace [org.clojure/clojurescript "1.9.946"]]}}
:plugins [[lein-codox "0.10.3" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-javadoc "0.3.0" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-cljsbuild "1.1.7" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-figwheel "0.5.14" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]]
:codox {:namespaces [clara.rules clara.rules.dsl clara.rules.accumulators
clara.rules.listener clara.rules.durability
clara.tools.inspect clara.tools.tracing
clara.tools.fact-graph]
:metadata {:doc/format :markdown}}
:javadoc-opts {:package-names "clara.rules"}
:source-paths ["src/main/clojure"]
:resource-paths []
:test-paths ["src/test/clojure" "src/test/common"]
:java-source-paths ["src/main/java"]
:javac-options ["-target" "1.6" "-source" "1.6"]
:clean-targets ^{:protect false} ["resources/public/js" "target"]
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [;; Simple mode compilation for tests.
{:id "figwheel"
:source-paths ["src/test/clojurescript" "src/test/common"]
:figwheel true
:compiler {:main "clara.test"
:output-to "resources/public/js/simple.js"
:output-dir "resources/public/js/out"
:asset-path "js/out"
:optimizations :none}}
{:id "simple"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/simple.js"
:optimizations :whitespace}}
;; Advanced mode compilation for tests.
{:id "advanced"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/advanced.js"
:optimizations :advanced}}]
:test-commands {"phantom-simple" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/simple.html"]
"phantom-advanced" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/advanced.html"]}}
:repl-options {;; The large number of ClojureScript tests is causing long compilation times
;; to start the REPL.
:timeout 120000}
;; Factoring out the duplication of this test selector function causes an error,
;; perhaps because Leiningen is using this as uneval'ed code.
;; For now just duplicate the line.
:test-selectors {:default (complement (fn [x]
(let [blacklisted-packages #{"generative" "performance"}
patterns (into []
(comp
(map #(str "^clara\\." % ".*"))
(interpose "|"))
blacklisted-packages)]
(some->> x :ns ns-name str (re-matches (re-pattern (apply str patterns)))))))
:generative (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.generative.*")))
:performance (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.performance.*")))}
:scm {:name "git"
:url "https://github.com/cerner/clara-rules"}
:pom-addition [:developers [:developer
[:id "rbrush"]
[:name "<NAME>"]
[:url "http://www.clara-rules.org"]]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
| true |
(defproject com.cerner/clara-rules "0.19.0-SNAPSHOT"
:description "Clara Rules Engine"
:url "https://github.com/cerner/clara-rules"
:license {:name "Apache License Version 2.0"
:url "https://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.7.0"]
[prismatic/schema "1.1.6"]]
:profiles {:dev {:dependencies [[org.clojure/math.combinatorics "0.1.3"]
[org.clojure/data.fressian "0.2.1"]]}
:provided {:dependencies [[org.clojure/clojurescript "1.7.170"]]}
:recent-clj {:dependencies [^:replace [org.clojure/clojure "1.9.0"]
^:replace [org.clojure/clojurescript "1.9.946"]]}}
:plugins [[lein-codox "0.10.3" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-javadoc "0.3.0" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-cljsbuild "1.1.7" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]
[lein-figwheel "0.5.14" :exclusions [org.clojure/clojure
org.clojure/clojurescript]]]
:codox {:namespaces [clara.rules clara.rules.dsl clara.rules.accumulators
clara.rules.listener clara.rules.durability
clara.tools.inspect clara.tools.tracing
clara.tools.fact-graph]
:metadata {:doc/format :markdown}}
:javadoc-opts {:package-names "clara.rules"}
:source-paths ["src/main/clojure"]
:resource-paths []
:test-paths ["src/test/clojure" "src/test/common"]
:java-source-paths ["src/main/java"]
:javac-options ["-target" "1.6" "-source" "1.6"]
:clean-targets ^{:protect false} ["resources/public/js" "target"]
:hooks [leiningen.cljsbuild]
:cljsbuild {:builds [;; Simple mode compilation for tests.
{:id "figwheel"
:source-paths ["src/test/clojurescript" "src/test/common"]
:figwheel true
:compiler {:main "clara.test"
:output-to "resources/public/js/simple.js"
:output-dir "resources/public/js/out"
:asset-path "js/out"
:optimizations :none}}
{:id "simple"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/simple.js"
:optimizations :whitespace}}
;; Advanced mode compilation for tests.
{:id "advanced"
:source-paths ["src/test/clojurescript" "src/test/common"]
:compiler {:output-to "target/js/advanced.js"
:optimizations :advanced}}]
:test-commands {"phantom-simple" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/simple.html"]
"phantom-advanced" ["phantomjs"
"src/test/js/runner.js"
"src/test/html/advanced.html"]}}
:repl-options {;; The large number of ClojureScript tests is causing long compilation times
;; to start the REPL.
:timeout 120000}
;; Factoring out the duplication of this test selector function causes an error,
;; perhaps because Leiningen is using this as uneval'ed code.
;; For now just duplicate the line.
:test-selectors {:default (complement (fn [x]
(let [blacklisted-packages #{"generative" "performance"}
patterns (into []
(comp
(map #(str "^clara\\." % ".*"))
(interpose "|"))
blacklisted-packages)]
(some->> x :ns ns-name str (re-matches (re-pattern (apply str patterns)))))))
:generative (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.generative.*")))
:performance (fn [x] (some->> x :ns ns-name str (re-matches #"^clara\.performance.*")))}
:scm {:name "git"
:url "https://github.com/cerner/clara-rules"}
:pom-addition [:developers [:developer
[:id "rbrush"]
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://www.clara-rules.org"]]]
:deploy-repositories [["snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/"
:creds :gpg}]])
|
[
{
"context": ";; Copyright (c) 2015 James Gatannah. All rights reserved.\n;; The use and distributi",
"end": 38,
"score": 0.9998378753662109,
"start": 24,
"tag": "NAME",
"value": "James Gatannah"
}
] |
data/train/clojure/f0e69bfd759e7f407a553f672d4828d8c93c392csystem.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
;; Copyright (c) 2015 James Gatannah. 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 penumbra.system
(:require #_[clojure.core.async :as async]
;; Q: Debug only??
#_[clojure.tools.trace :as trace]
[com.stuartsierra.component :as component]
[penumbra
[base :as base]
[configuration :as config]]
[penumbra.app
[manager :as manager]
;; The rest of these are, for now, parts
;; associated with an App/Stage.
;; That seems wrong, but I still nood to work
;; through the implications and details.
#_[controller :as controller]
#_[event :as event]
#_[input :as input]
#_[queue :as queue]
#_[window :as window]]))
(defn base-map
[overriding-config-options]
(comment :app (app/ctor (select-keys overriding-config-options [:callbacks
:clock
:event-handler
:main-loop
:parent
:queue
:state
:threading]))
:controller (controller/ctor (select-keys overriding-config-options []))
:input (input/ctor overriding-config-options)
:event-handler (event/ctor overriding-config-options)
:queue (queue/ctor overriding-config-options)
:window (window/ctor (select-keys overriding-config-options [:hints
:position
:title])))
(component/system-map
:base (base/ctor (select-keys overriding-config-options [:error-callback]))
:done (promise)
:manager (manager/ctor {})))
(defn dependencies
[initial]
(component/system-using initial
{;; seems wrong to tie an app to a single window
;; But that's really all it is...the infrastructure that ties together
;; all the pieces that manage a particular window
;; It doesn't belong here, though:
;; Some wrapper creates this System, then the AppManager handles
;; all the Apps (tonight I'm calling them Stages)
;;:app [:controller :done :event-handler :queue :window]
;;:input [:app]
:manager [:done]
;;:queue [:controller]
;;:window [:base]
}))
(defn init
[overriding-config-options]
(set! *warn-on-reflection* true)
(let [cfg (into (config/defaults) overriding-config-options)]
;; TODO: I really need to configure logging...don't I?
(-> (base-map cfg)
(dependencies))))
|
121002
|
;; Copyright (c) 2015 <NAME>. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns penumbra.system
(:require #_[clojure.core.async :as async]
;; Q: Debug only??
#_[clojure.tools.trace :as trace]
[com.stuartsierra.component :as component]
[penumbra
[base :as base]
[configuration :as config]]
[penumbra.app
[manager :as manager]
;; The rest of these are, for now, parts
;; associated with an App/Stage.
;; That seems wrong, but I still nood to work
;; through the implications and details.
#_[controller :as controller]
#_[event :as event]
#_[input :as input]
#_[queue :as queue]
#_[window :as window]]))
(defn base-map
[overriding-config-options]
(comment :app (app/ctor (select-keys overriding-config-options [:callbacks
:clock
:event-handler
:main-loop
:parent
:queue
:state
:threading]))
:controller (controller/ctor (select-keys overriding-config-options []))
:input (input/ctor overriding-config-options)
:event-handler (event/ctor overriding-config-options)
:queue (queue/ctor overriding-config-options)
:window (window/ctor (select-keys overriding-config-options [:hints
:position
:title])))
(component/system-map
:base (base/ctor (select-keys overriding-config-options [:error-callback]))
:done (promise)
:manager (manager/ctor {})))
(defn dependencies
[initial]
(component/system-using initial
{;; seems wrong to tie an app to a single window
;; But that's really all it is...the infrastructure that ties together
;; all the pieces that manage a particular window
;; It doesn't belong here, though:
;; Some wrapper creates this System, then the AppManager handles
;; all the Apps (tonight I'm calling them Stages)
;;:app [:controller :done :event-handler :queue :window]
;;:input [:app]
:manager [:done]
;;:queue [:controller]
;;:window [:base]
}))
(defn init
[overriding-config-options]
(set! *warn-on-reflection* true)
(let [cfg (into (config/defaults) overriding-config-options)]
;; TODO: I really need to configure logging...don't I?
(-> (base-map cfg)
(dependencies))))
| true |
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns penumbra.system
(:require #_[clojure.core.async :as async]
;; Q: Debug only??
#_[clojure.tools.trace :as trace]
[com.stuartsierra.component :as component]
[penumbra
[base :as base]
[configuration :as config]]
[penumbra.app
[manager :as manager]
;; The rest of these are, for now, parts
;; associated with an App/Stage.
;; That seems wrong, but I still nood to work
;; through the implications and details.
#_[controller :as controller]
#_[event :as event]
#_[input :as input]
#_[queue :as queue]
#_[window :as window]]))
(defn base-map
[overriding-config-options]
(comment :app (app/ctor (select-keys overriding-config-options [:callbacks
:clock
:event-handler
:main-loop
:parent
:queue
:state
:threading]))
:controller (controller/ctor (select-keys overriding-config-options []))
:input (input/ctor overriding-config-options)
:event-handler (event/ctor overriding-config-options)
:queue (queue/ctor overriding-config-options)
:window (window/ctor (select-keys overriding-config-options [:hints
:position
:title])))
(component/system-map
:base (base/ctor (select-keys overriding-config-options [:error-callback]))
:done (promise)
:manager (manager/ctor {})))
(defn dependencies
[initial]
(component/system-using initial
{;; seems wrong to tie an app to a single window
;; But that's really all it is...the infrastructure that ties together
;; all the pieces that manage a particular window
;; It doesn't belong here, though:
;; Some wrapper creates this System, then the AppManager handles
;; all the Apps (tonight I'm calling them Stages)
;;:app [:controller :done :event-handler :queue :window]
;;:input [:app]
:manager [:done]
;;:queue [:controller]
;;:window [:base]
}))
(defn init
[overriding-config-options]
(set! *warn-on-reflection* true)
(let [cfg (into (config/defaults) overriding-config-options)]
;; TODO: I really need to configure logging...don't I?
(-> (base-map cfg)
(dependencies))))
|
[
{
"context": "4.474\"]\n [org.xerial/sqlite-jdbc \"3.21.0.1\"]\n [funcool/clojure.jdbc \"0.9.0\"]",
"end": 697,
"score": 0.9982119798660278,
"start": 689,
"tag": "IP_ADDRESS",
"value": "3.21.0.1"
}
] |
project.clj
|
rinx/clojure-lsp
| 0 |
(defproject clojure-lsp "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/tools.reader "1.2.2"]
[org.eclipse.lsp4j/org.eclipse.lsp4j "0.4.0" :exclusions [org.eclipse.xtend/org.eclipse.xtend.lib]]
[org.eclipse.xtend/org.eclipse.xtend.lib "2.13.0" :exclusions [com.google.guava/guava]]
[com.google.guava/guava "19.0"]
[rewrite-clj "0.6.1"]
[log4j/log4j "1.2.17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/core.async "0.4.474"]
[org.xerial/sqlite-jdbc "3.21.0.1"]
[funcool/clojure.jdbc "0.9.0"]
[digest "1.4.8"]
[cljfmt "0.5.7"]
[medley "1.0.0"]
[com.taoensso/tufte "2.0.1"]]
:jvm-opts ^:replace ["-Xmx1g" "-server"]
:main clojure-lsp.main
:profiles {:dev {:plugins [[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bin "0.3.4"]]
:bin {:name "clojure-lsp"}}
:test {:test-selectors {:focused :focused}}
:uberjar {:aot :all}})
|
45463
|
(defproject clojure-lsp "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/tools.reader "1.2.2"]
[org.eclipse.lsp4j/org.eclipse.lsp4j "0.4.0" :exclusions [org.eclipse.xtend/org.eclipse.xtend.lib]]
[org.eclipse.xtend/org.eclipse.xtend.lib "2.13.0" :exclusions [com.google.guava/guava]]
[com.google.guava/guava "19.0"]
[rewrite-clj "0.6.1"]
[log4j/log4j "1.2.17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/core.async "0.4.474"]
[org.xerial/sqlite-jdbc "192.168.3.11"]
[funcool/clojure.jdbc "0.9.0"]
[digest "1.4.8"]
[cljfmt "0.5.7"]
[medley "1.0.0"]
[com.taoensso/tufte "2.0.1"]]
:jvm-opts ^:replace ["-Xmx1g" "-server"]
:main clojure-lsp.main
:profiles {:dev {:plugins [[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bin "0.3.4"]]
:bin {:name "clojure-lsp"}}
:test {:test-selectors {:focused :focused}}
:uberjar {:aot :all}})
| true |
(defproject clojure-lsp "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/tools.reader "1.2.2"]
[org.eclipse.lsp4j/org.eclipse.lsp4j "0.4.0" :exclusions [org.eclipse.xtend/org.eclipse.xtend.lib]]
[org.eclipse.xtend/org.eclipse.xtend.lib "2.13.0" :exclusions [com.google.guava/guava]]
[com.google.guava/guava "19.0"]
[rewrite-clj "0.6.1"]
[log4j/log4j "1.2.17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/core.async "0.4.474"]
[org.xerial/sqlite-jdbc "PI:IP_ADDRESS:192.168.3.11END_PI"]
[funcool/clojure.jdbc "0.9.0"]
[digest "1.4.8"]
[cljfmt "0.5.7"]
[medley "1.0.0"]
[com.taoensso/tufte "2.0.1"]]
:jvm-opts ^:replace ["-Xmx1g" "-server"]
:main clojure-lsp.main
:profiles {:dev {:plugins [[com.jakemccrary/lein-test-refresh "0.23.0"]
[lein-bin "0.3.4"]]
:bin {:name "clojure-lsp"}}
:test {:test-selectors {:focused :focused}}
:uberjar {:aot :all}})
|
[
{
"context": "ap\"\n (read-xlsx test-file) => [{:scientificName \"Aphelandra longiflora\" :latitude \"10.10\" :longitude \"20.20\" :locality \"",
"end": 206,
"score": 0.9998570680618286,
"start": 185,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": "s\"}\n {:scientificName \"Vicia faba\" :latitude \"30.3\" :longitude \"8.9\" :locality nil ",
"end": 344,
"score": 0.9997581839561462,
"start": 334,
"tag": "NAME",
"value": "Vicia faba"
},
{
"context": "30.10\" :decimalLongitude \"10.20\" :scientificName \"Aphelandra longiflora\" :taxonRank \"species\"}\n {:locality ",
"end": 571,
"score": 0.999834418296814,
"start": 550,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": "e \"20.2\" :decimalLongitude \"9.8\" :scientificName \"Vicia faba\" :taxonRank \"species\"}]]\n (read-xlsx (write-xlsx",
"end": 700,
"score": 0.9997087717056274,
"start": 690,
"tag": "NAME",
"value": "Vicia faba"
}
] |
test/dwc_io/xlsx_test.clj
|
biodivdev/dwc
| 0 |
(ns dwc-io.xlsx-test
(:use midje.sweet)
(:use dwc-io.xlsx))
(def test-file "resources/dwc.xlsx")
(fact "Can read xlsx into hash-map"
(read-xlsx test-file) => [{:scientificName "Aphelandra longiflora" :latitude "10.10" :longitude "20.20" :locality "riverrun" :taxonRank "species"}
{:scientificName "Vicia faba" :latitude "30.3" :longitude "8.9" :locality nil :taxonRank "species"}])
(fact "Can write to xlsx"
(let [data [{:locality "riverrun" :decimalLatitude "30.10" :decimalLongitude "10.20" :scientificName "Aphelandra longiflora" :taxonRank "species"}
{:locality nil :decimalLatitude "20.2" :decimalLongitude "9.8" :scientificName "Vicia faba" :taxonRank "species"}]]
(read-xlsx (write-xlsx data)) => data))
|
53611
|
(ns dwc-io.xlsx-test
(:use midje.sweet)
(:use dwc-io.xlsx))
(def test-file "resources/dwc.xlsx")
(fact "Can read xlsx into hash-map"
(read-xlsx test-file) => [{:scientificName "<NAME>" :latitude "10.10" :longitude "20.20" :locality "riverrun" :taxonRank "species"}
{:scientificName "<NAME>" :latitude "30.3" :longitude "8.9" :locality nil :taxonRank "species"}])
(fact "Can write to xlsx"
(let [data [{:locality "riverrun" :decimalLatitude "30.10" :decimalLongitude "10.20" :scientificName "<NAME>" :taxonRank "species"}
{:locality nil :decimalLatitude "20.2" :decimalLongitude "9.8" :scientificName "<NAME>" :taxonRank "species"}]]
(read-xlsx (write-xlsx data)) => data))
| true |
(ns dwc-io.xlsx-test
(:use midje.sweet)
(:use dwc-io.xlsx))
(def test-file "resources/dwc.xlsx")
(fact "Can read xlsx into hash-map"
(read-xlsx test-file) => [{:scientificName "PI:NAME:<NAME>END_PI" :latitude "10.10" :longitude "20.20" :locality "riverrun" :taxonRank "species"}
{:scientificName "PI:NAME:<NAME>END_PI" :latitude "30.3" :longitude "8.9" :locality nil :taxonRank "species"}])
(fact "Can write to xlsx"
(let [data [{:locality "riverrun" :decimalLatitude "30.10" :decimalLongitude "10.20" :scientificName "PI:NAME:<NAME>END_PI" :taxonRank "species"}
{:locality nil :decimalLatitude "20.2" :decimalLongitude "9.8" :scientificName "PI:NAME:<NAME>END_PI" :taxonRank "species"}]]
(read-xlsx (write-xlsx data)) => data))
|
[
{
"context": "(ns ^{:author \"Leeor Engel\"}\n chapter-3.chapter-3-q6-test\n (:require [cloj",
"end": 26,
"score": 0.9998846054077148,
"start": 15,
"tag": "NAME",
"value": "Leeor Engel"
}
] |
Clojure/test/chapter_3/chapter_3_q6_test.clj
|
Kiandr/crackingcodinginterview
| 0 |
(ns ^{:author "Leeor Engel"}
chapter-3.chapter-3-q6-test
(:require [clojure.test :refer :all]
[chapter-3.chapter-3-q6 :refer :all]))
(deftest animal-shelter-test
(testing "basic tests"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "whiskers")
(let [animal (dequeue-any shelter)]
(is (= :cat (:type animal)))
(is (= "whiskers" (:name animal))))
(enqueue shelter :cat "kitty")
(let [animal (dequeue-cat shelter)]
(is (= :cat (:type animal)))
(is (= "kitty" (:name animal))))
(enqueue shelter :dog "fido")
(let [animal (dequeue-any shelter)]
(is (= :dog (:type animal)))
(is (= "fido" (:name animal))))
(enqueue shelter :dog "spot")
(let [animal (dequeue-dog shelter)]
(is (= :dog (:type animal)))
(is (= "spot" (:name animal))))
(enqueue shelter :dog "rex")
(enqueue shelter :cat "oliver")
(let [a1 (dequeue-any shelter)
a2 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "rex" (:name a1)))
(is (= :cat (:type a2))
(= "oliver" (:name a2))))
(enqueue shelter :dog "cujo")
(enqueue shelter :cat "mittens")
(let [dog (dequeue-dog shelter)
cat (dequeue-cat shelter)]
(is (= :dog (:type dog))
(= "cujo" (:name dog)))
(is (= :cat (:type cat))
(= "mittens" (:name cat))))
(enqueue shelter :dog "spot 2")
(enqueue shelter :dog "buddy")
(enqueue shelter :cat "garfield")
(enqueue shelter :cat "kiki")
(enqueue shelter :cat "tiger")
(let [a1 (dequeue-dog shelter)
a2 (dequeue-any shelter)
a3 (dequeue-cat shelter)
a4 (dequeue-any shelter)
a5 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "spot 2" (:name a1)))
(is (= :dog (:type a2))
(= "buddy" (:name a2)))
(is (= :cat (:type a3))
(= "garfield" (:name a3)))
(is (= :cat (:type a4))
(= "kiki" (:name a4)))
(is (= :cat (:type a5))
(= "tiger" (:name a5))))))
(testing "Oldest cat, rest dogs"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "kiki")
(enqueue shelter :dog "rex")
(enqueue shelter :dog "spot")
(enqueue shelter :dog "fido")
(let [a1 (dequeue-cat shelter)
a2 (dequeue-dog shelter)
a3 (dequeue-any shelter)
a4 (dequeue-cat shelter)
a5 (dequeue-any shelter)
a6 (dequeue-any shelter)
a7 (dequeue-dog shelter)]
(is (= :cat (:type a1))
(= "kiki" (:name a1)))
(is (= :dog (:type a2))
(= "rex" (:name a2)))
(is (= :dog (:type a3))
(= "spot" (:name a3)))
(is (= nil a4))
(is (= :dog (:type a5))
(= "fido" (:name a5)))
(is (= nil a6)
(= nil a7))))))
|
77602
|
(ns ^{:author "<NAME>"}
chapter-3.chapter-3-q6-test
(:require [clojure.test :refer :all]
[chapter-3.chapter-3-q6 :refer :all]))
(deftest animal-shelter-test
(testing "basic tests"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "whiskers")
(let [animal (dequeue-any shelter)]
(is (= :cat (:type animal)))
(is (= "whiskers" (:name animal))))
(enqueue shelter :cat "kitty")
(let [animal (dequeue-cat shelter)]
(is (= :cat (:type animal)))
(is (= "kitty" (:name animal))))
(enqueue shelter :dog "fido")
(let [animal (dequeue-any shelter)]
(is (= :dog (:type animal)))
(is (= "fido" (:name animal))))
(enqueue shelter :dog "spot")
(let [animal (dequeue-dog shelter)]
(is (= :dog (:type animal)))
(is (= "spot" (:name animal))))
(enqueue shelter :dog "rex")
(enqueue shelter :cat "oliver")
(let [a1 (dequeue-any shelter)
a2 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "rex" (:name a1)))
(is (= :cat (:type a2))
(= "oliver" (:name a2))))
(enqueue shelter :dog "cujo")
(enqueue shelter :cat "mittens")
(let [dog (dequeue-dog shelter)
cat (dequeue-cat shelter)]
(is (= :dog (:type dog))
(= "cujo" (:name dog)))
(is (= :cat (:type cat))
(= "mittens" (:name cat))))
(enqueue shelter :dog "spot 2")
(enqueue shelter :dog "buddy")
(enqueue shelter :cat "garfield")
(enqueue shelter :cat "kiki")
(enqueue shelter :cat "tiger")
(let [a1 (dequeue-dog shelter)
a2 (dequeue-any shelter)
a3 (dequeue-cat shelter)
a4 (dequeue-any shelter)
a5 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "spot 2" (:name a1)))
(is (= :dog (:type a2))
(= "buddy" (:name a2)))
(is (= :cat (:type a3))
(= "garfield" (:name a3)))
(is (= :cat (:type a4))
(= "kiki" (:name a4)))
(is (= :cat (:type a5))
(= "tiger" (:name a5))))))
(testing "Oldest cat, rest dogs"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "kiki")
(enqueue shelter :dog "rex")
(enqueue shelter :dog "spot")
(enqueue shelter :dog "fido")
(let [a1 (dequeue-cat shelter)
a2 (dequeue-dog shelter)
a3 (dequeue-any shelter)
a4 (dequeue-cat shelter)
a5 (dequeue-any shelter)
a6 (dequeue-any shelter)
a7 (dequeue-dog shelter)]
(is (= :cat (:type a1))
(= "kiki" (:name a1)))
(is (= :dog (:type a2))
(= "rex" (:name a2)))
(is (= :dog (:type a3))
(= "spot" (:name a3)))
(is (= nil a4))
(is (= :dog (:type a5))
(= "fido" (:name a5)))
(is (= nil a6)
(= nil a7))))))
| true |
(ns ^{:author "PI:NAME:<NAME>END_PI"}
chapter-3.chapter-3-q6-test
(:require [clojure.test :refer :all]
[chapter-3.chapter-3-q6 :refer :all]))
(deftest animal-shelter-test
(testing "basic tests"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "whiskers")
(let [animal (dequeue-any shelter)]
(is (= :cat (:type animal)))
(is (= "whiskers" (:name animal))))
(enqueue shelter :cat "kitty")
(let [animal (dequeue-cat shelter)]
(is (= :cat (:type animal)))
(is (= "kitty" (:name animal))))
(enqueue shelter :dog "fido")
(let [animal (dequeue-any shelter)]
(is (= :dog (:type animal)))
(is (= "fido" (:name animal))))
(enqueue shelter :dog "spot")
(let [animal (dequeue-dog shelter)]
(is (= :dog (:type animal)))
(is (= "spot" (:name animal))))
(enqueue shelter :dog "rex")
(enqueue shelter :cat "oliver")
(let [a1 (dequeue-any shelter)
a2 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "rex" (:name a1)))
(is (= :cat (:type a2))
(= "oliver" (:name a2))))
(enqueue shelter :dog "cujo")
(enqueue shelter :cat "mittens")
(let [dog (dequeue-dog shelter)
cat (dequeue-cat shelter)]
(is (= :dog (:type dog))
(= "cujo" (:name dog)))
(is (= :cat (:type cat))
(= "mittens" (:name cat))))
(enqueue shelter :dog "spot 2")
(enqueue shelter :dog "buddy")
(enqueue shelter :cat "garfield")
(enqueue shelter :cat "kiki")
(enqueue shelter :cat "tiger")
(let [a1 (dequeue-dog shelter)
a2 (dequeue-any shelter)
a3 (dequeue-cat shelter)
a4 (dequeue-any shelter)
a5 (dequeue-any shelter)]
(is (= :dog (:type a1))
(= "spot 2" (:name a1)))
(is (= :dog (:type a2))
(= "buddy" (:name a2)))
(is (= :cat (:type a3))
(= "garfield" (:name a3)))
(is (= :cat (:type a4))
(= "kiki" (:name a4)))
(is (= :cat (:type a5))
(= "tiger" (:name a5))))))
(testing "Oldest cat, rest dogs"
(let [shelter (create-animal-shelter)]
(enqueue shelter :cat "kiki")
(enqueue shelter :dog "rex")
(enqueue shelter :dog "spot")
(enqueue shelter :dog "fido")
(let [a1 (dequeue-cat shelter)
a2 (dequeue-dog shelter)
a3 (dequeue-any shelter)
a4 (dequeue-cat shelter)
a5 (dequeue-any shelter)
a6 (dequeue-any shelter)
a7 (dequeue-dog shelter)]
(is (= :cat (:type a1))
(= "kiki" (:name a1)))
(is (= :dog (:type a2))
(= "rex" (:name a2)))
(is (= :dog (:type a3))
(= "spot" (:name a3)))
(is (= nil a4))
(is (= :dog (:type a5))
(= "fido" (:name a5)))
(is (= nil a6)
(= nil a7))))))
|
[
{
"context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.",
"end": 32,
"score": 0.9993882179260254,
"start": 21,
"tag": "NAME",
"value": "Peter Monks"
},
{
"context": "bol identifying your project e.g. 'com.github.yourusername/yourproject\n :version -- opt: a string cont",
"end": 2080,
"score": 0.722716748714447,
"start": 2072,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\\\"\n :url \\\"https://github.com/yourusername/yourproject\\\"\n :licenses [:license",
"end": 2996,
"score": 0.9994271993637085,
"start": 2984,
"tag": "USERNAME",
"value": "yourusername"
},
{
"context": " tag\n :developers [:developer {:id \\\"yourusername\\\" :name \\\"yourname\\\" :email \\\"youremail@emailserv",
"end": 3225,
"score": 0.9995914697647095,
"start": 3213,
"tag": "USERNAME",
"value": "yourusername"
},
{
"context": "s [:developer {:id \\\"yourusername\\\" :name \\\"yourname\\\" :email \\\"[email protected]\\\"}] ",
"end": 3244,
"score": 0.7780890464782715,
"start": 3236,
"tag": "NAME",
"value": "yourname"
},
{
"context": "{:id \\\"yourusername\\\" :name \\\"yourname\\\" :email \\\"[email protected]\\\"}] ; And here\n :scm ",
"end": 3282,
"score": 0.9976204633712769,
"start": 3256,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " {:url \\\"https://github.com/yourusername/yourproject\\\"\n :connect",
"end": 3388,
"score": 0.9991458654403687,
"start": 3376,
"tag": "USERNAME",
"value": "yourusername"
},
{
"context": " :connection \\\"scm:git:git://github.com/yourusername/yourproject.git\\\"\n :dev",
"end": 3491,
"score": 0.9993109703063965,
"start": 3479,
"tag": "USERNAME",
"value": "yourusername"
},
{
"context": "veloper-connection \\\"scm:git:ssh://[email protected]/yourusername/yourproject.git\\\"}\n :issue-management {:sy",
"end": 3602,
"score": 0.9993793964385986,
"start": 3590,
"tag": "USERNAME",
"value": "yourusername"
},
{
"context": "ent {:system \\\"github\\\" :url \\\"https://github.com/yourusername/yourproject/issues\\\"}}))\"\n [opts]\n (tc/ensure-c",
"end": 3706,
"score": 0.9989118576049805,
"start": 3694,
"tag": "USERNAME",
"value": "yourusername"
}
] |
src/tools_pom/tasks.clj
|
pmonks/tools-pom
| 1 |
;
; Copyright © 2021 Peter Monks
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns tools-pom.tasks
"Clojure tools.deps tasks related to comprehensive pom.xml files.
All of the build tasks return the opts hash map they were passed
(unlike some of the functions in clojure.tools.build.api)."
(:require [clojure.java.io :as io]
[clojure.data.xml :as xml]
[tools-convenience.api :as tc]
[camel-snake-kebab.core :as csk]
[clj-xml-validation.core :as xmlv]))
; As of v1.10 this should be in core...
(defmethod print-method java.time.Instant [^java.time.Instant inst writer]
(print-method (java.util.Date/from inst) writer))
(defn- pom-keyword
"Converts a regular Clojure keyword into a POM-4.0.0-namespaced keyword."
[kw]
(keyword "xmlns.http%3A%2F%2Fmaven.apache.org%2FPOM%2F4.0.0" (csk/->camelCase (name kw))))
(defn- build-pom
"Converts the given 'element' into a POM structure in clojure.data.xml compatible EDN format."
[elem]
(cond
(map-entry? elem) [(pom-keyword (key elem)) (build-pom (val elem))]
(map? elem) (map build-pom elem)
(sequential? elem) (mapcat #(hash-map (pom-keyword (first elem)) (build-pom %)) (rest elem))
(= java.util.Date (type elem)) (str (.toInstant ^java.util.Date elem))
:else (str elem)))
(defn pom
"Writes out a pom file. opts includes:
:lib -- opt: a symbol identifying your project e.g. 'com.github.yourusername/yourproject
:version -- opt: a string containing the version of your project e.g. \"1.0.0-SNAPSHOT\"
:pom-file -- opt: the name of the file to write to (defaults to \"./pom.xml\")
:write-pom -- opt: a flag indicating whether to invoke \"clojure -Spom\" after generating the basic pom (i.e. adding dependencies and repositories from your deps.edn file) (defaults to false)
:validate-pom -- opt: a flag indicating whether to validate the generated pom.xml file after it's been constructed (defaults to false)
:pom -- opt: a map containing any other POM elements (see https://maven.apache.org/pom.html for details), using standard Clojure :keyword keys
Here is an example :pom map that will generate a valid pom.xml:
:pom {:description \"Description of your project e.g. your project's short description on GitHub.\"
:url \"https://github.com/yourusername/yourproject\"
:licenses [:license {:name \"Apache License 2.0\" :url \"http://www.apache.org/licenses/LICENSE-2.0.html\"}] ; Note first element is a tag
:developers [:developer {:id \"yourusername\" :name \"yourname\" :email \"[email protected]\"}] ; And here
:scm {:url \"https://github.com/yourusername/yourproject\"
:connection \"scm:git:git://github.com/yourusername/yourproject.git\"
:developer-connection \"scm:git:ssh://[email protected]/yourusername/yourproject.git\"}
:issue-management {:system \"github\" :url \"https://github.com/yourusername/yourproject/issues\"}}))"
[opts]
(tc/ensure-command "clojure")
(println "Generating comprehensive pom.xml...")
(let [pom-file (get opts :pom-file "./pom.xml")
pom-in (merge (when (:lib opts) {:group-id (namespace (:lib opts)) :artifact-id (name (:lib opts)) :name (name (:lib opts))})
(when (:version opts) {:version (:version opts)})
(:pom opts)) ; Merge user-supplied values last, so that they always take precedence
pom-out [(pom-keyword :project) {:xmlns "http://maven.apache.org/POM/4.0.0"
(keyword "xmlns:xsi") "http://www.w3.org/2001/XMLSchema-instance"
(keyword "xsi:schemaLocation") "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"}
(concat [[(pom-keyword :model-version) "4.0.0"]]
(build-pom pom-in))]
pom-xml (xml/sexp-as-element pom-out)]
(with-open [pom-writer (io/writer pom-file)]
(xml/emit pom-xml pom-writer :encoding "UTF8"))
(when (:write-pom opts)
(tc/clojure "-X:deps" "mvn-pom")) ; tools.build/write-pom is nowhere as useful as clojure -X:deps mvn-pom but the latter doesn't have an API so we just fork it instead..
(when (:validate-pom opts)
(let [is-pom? (xmlv/create-validation-fn (io/reader "https://maven.apache.org/xsd/maven-4.0.0.xsd"))
validation-result (is-pom? (slurp pom-file))]
(when-not (xmlv/valid? validation-result)
(println "Generated pom.xml is not valid; check your input data. Errors:")
(doall (map #(println " Line" (get % :line-number "?") "column" (str (get % :column-number "?") ":") (:message %)) (xmlv/errors validation-result)))))))
opts)
|
18933
|
;
; Copyright © 2021 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns tools-pom.tasks
"Clojure tools.deps tasks related to comprehensive pom.xml files.
All of the build tasks return the opts hash map they were passed
(unlike some of the functions in clojure.tools.build.api)."
(:require [clojure.java.io :as io]
[clojure.data.xml :as xml]
[tools-convenience.api :as tc]
[camel-snake-kebab.core :as csk]
[clj-xml-validation.core :as xmlv]))
; As of v1.10 this should be in core...
(defmethod print-method java.time.Instant [^java.time.Instant inst writer]
(print-method (java.util.Date/from inst) writer))
(defn- pom-keyword
"Converts a regular Clojure keyword into a POM-4.0.0-namespaced keyword."
[kw]
(keyword "xmlns.http%3A%2F%2Fmaven.apache.org%2FPOM%2F4.0.0" (csk/->camelCase (name kw))))
(defn- build-pom
"Converts the given 'element' into a POM structure in clojure.data.xml compatible EDN format."
[elem]
(cond
(map-entry? elem) [(pom-keyword (key elem)) (build-pom (val elem))]
(map? elem) (map build-pom elem)
(sequential? elem) (mapcat #(hash-map (pom-keyword (first elem)) (build-pom %)) (rest elem))
(= java.util.Date (type elem)) (str (.toInstant ^java.util.Date elem))
:else (str elem)))
(defn pom
"Writes out a pom file. opts includes:
:lib -- opt: a symbol identifying your project e.g. 'com.github.yourusername/yourproject
:version -- opt: a string containing the version of your project e.g. \"1.0.0-SNAPSHOT\"
:pom-file -- opt: the name of the file to write to (defaults to \"./pom.xml\")
:write-pom -- opt: a flag indicating whether to invoke \"clojure -Spom\" after generating the basic pom (i.e. adding dependencies and repositories from your deps.edn file) (defaults to false)
:validate-pom -- opt: a flag indicating whether to validate the generated pom.xml file after it's been constructed (defaults to false)
:pom -- opt: a map containing any other POM elements (see https://maven.apache.org/pom.html for details), using standard Clojure :keyword keys
Here is an example :pom map that will generate a valid pom.xml:
:pom {:description \"Description of your project e.g. your project's short description on GitHub.\"
:url \"https://github.com/yourusername/yourproject\"
:licenses [:license {:name \"Apache License 2.0\" :url \"http://www.apache.org/licenses/LICENSE-2.0.html\"}] ; Note first element is a tag
:developers [:developer {:id \"yourusername\" :name \"<NAME>\" :email \"<EMAIL>\"}] ; And here
:scm {:url \"https://github.com/yourusername/yourproject\"
:connection \"scm:git:git://github.com/yourusername/yourproject.git\"
:developer-connection \"scm:git:ssh://[email protected]/yourusername/yourproject.git\"}
:issue-management {:system \"github\" :url \"https://github.com/yourusername/yourproject/issues\"}}))"
[opts]
(tc/ensure-command "clojure")
(println "Generating comprehensive pom.xml...")
(let [pom-file (get opts :pom-file "./pom.xml")
pom-in (merge (when (:lib opts) {:group-id (namespace (:lib opts)) :artifact-id (name (:lib opts)) :name (name (:lib opts))})
(when (:version opts) {:version (:version opts)})
(:pom opts)) ; Merge user-supplied values last, so that they always take precedence
pom-out [(pom-keyword :project) {:xmlns "http://maven.apache.org/POM/4.0.0"
(keyword "xmlns:xsi") "http://www.w3.org/2001/XMLSchema-instance"
(keyword "xsi:schemaLocation") "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"}
(concat [[(pom-keyword :model-version) "4.0.0"]]
(build-pom pom-in))]
pom-xml (xml/sexp-as-element pom-out)]
(with-open [pom-writer (io/writer pom-file)]
(xml/emit pom-xml pom-writer :encoding "UTF8"))
(when (:write-pom opts)
(tc/clojure "-X:deps" "mvn-pom")) ; tools.build/write-pom is nowhere as useful as clojure -X:deps mvn-pom but the latter doesn't have an API so we just fork it instead..
(when (:validate-pom opts)
(let [is-pom? (xmlv/create-validation-fn (io/reader "https://maven.apache.org/xsd/maven-4.0.0.xsd"))
validation-result (is-pom? (slurp pom-file))]
(when-not (xmlv/valid? validation-result)
(println "Generated pom.xml is not valid; check your input data. Errors:")
(doall (map #(println " Line" (get % :line-number "?") "column" (str (get % :column-number "?") ":") (:message %)) (xmlv/errors validation-result)))))))
opts)
| true |
;
; Copyright © 2021 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns tools-pom.tasks
"Clojure tools.deps tasks related to comprehensive pom.xml files.
All of the build tasks return the opts hash map they were passed
(unlike some of the functions in clojure.tools.build.api)."
(:require [clojure.java.io :as io]
[clojure.data.xml :as xml]
[tools-convenience.api :as tc]
[camel-snake-kebab.core :as csk]
[clj-xml-validation.core :as xmlv]))
; As of v1.10 this should be in core...
(defmethod print-method java.time.Instant [^java.time.Instant inst writer]
(print-method (java.util.Date/from inst) writer))
(defn- pom-keyword
"Converts a regular Clojure keyword into a POM-4.0.0-namespaced keyword."
[kw]
(keyword "xmlns.http%3A%2F%2Fmaven.apache.org%2FPOM%2F4.0.0" (csk/->camelCase (name kw))))
(defn- build-pom
"Converts the given 'element' into a POM structure in clojure.data.xml compatible EDN format."
[elem]
(cond
(map-entry? elem) [(pom-keyword (key elem)) (build-pom (val elem))]
(map? elem) (map build-pom elem)
(sequential? elem) (mapcat #(hash-map (pom-keyword (first elem)) (build-pom %)) (rest elem))
(= java.util.Date (type elem)) (str (.toInstant ^java.util.Date elem))
:else (str elem)))
(defn pom
"Writes out a pom file. opts includes:
:lib -- opt: a symbol identifying your project e.g. 'com.github.yourusername/yourproject
:version -- opt: a string containing the version of your project e.g. \"1.0.0-SNAPSHOT\"
:pom-file -- opt: the name of the file to write to (defaults to \"./pom.xml\")
:write-pom -- opt: a flag indicating whether to invoke \"clojure -Spom\" after generating the basic pom (i.e. adding dependencies and repositories from your deps.edn file) (defaults to false)
:validate-pom -- opt: a flag indicating whether to validate the generated pom.xml file after it's been constructed (defaults to false)
:pom -- opt: a map containing any other POM elements (see https://maven.apache.org/pom.html for details), using standard Clojure :keyword keys
Here is an example :pom map that will generate a valid pom.xml:
:pom {:description \"Description of your project e.g. your project's short description on GitHub.\"
:url \"https://github.com/yourusername/yourproject\"
:licenses [:license {:name \"Apache License 2.0\" :url \"http://www.apache.org/licenses/LICENSE-2.0.html\"}] ; Note first element is a tag
:developers [:developer {:id \"yourusername\" :name \"PI:NAME:<NAME>END_PI\" :email \"PI:EMAIL:<EMAIL>END_PI\"}] ; And here
:scm {:url \"https://github.com/yourusername/yourproject\"
:connection \"scm:git:git://github.com/yourusername/yourproject.git\"
:developer-connection \"scm:git:ssh://[email protected]/yourusername/yourproject.git\"}
:issue-management {:system \"github\" :url \"https://github.com/yourusername/yourproject/issues\"}}))"
[opts]
(tc/ensure-command "clojure")
(println "Generating comprehensive pom.xml...")
(let [pom-file (get opts :pom-file "./pom.xml")
pom-in (merge (when (:lib opts) {:group-id (namespace (:lib opts)) :artifact-id (name (:lib opts)) :name (name (:lib opts))})
(when (:version opts) {:version (:version opts)})
(:pom opts)) ; Merge user-supplied values last, so that they always take precedence
pom-out [(pom-keyword :project) {:xmlns "http://maven.apache.org/POM/4.0.0"
(keyword "xmlns:xsi") "http://www.w3.org/2001/XMLSchema-instance"
(keyword "xsi:schemaLocation") "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"}
(concat [[(pom-keyword :model-version) "4.0.0"]]
(build-pom pom-in))]
pom-xml (xml/sexp-as-element pom-out)]
(with-open [pom-writer (io/writer pom-file)]
(xml/emit pom-xml pom-writer :encoding "UTF8"))
(when (:write-pom opts)
(tc/clojure "-X:deps" "mvn-pom")) ; tools.build/write-pom is nowhere as useful as clojure -X:deps mvn-pom but the latter doesn't have an API so we just fork it instead..
(when (:validate-pom opts)
(let [is-pom? (xmlv/create-validation-fn (io/reader "https://maven.apache.org/xsd/maven-4.0.0.xsd"))
validation-result (is-pom? (slurp pom-file))]
(when-not (xmlv/valid? validation-result)
(println "Generated pom.xml is not valid; check your input data. Errors:")
(doall (map #(println " Line" (get % :line-number "?") "column" (str (get % :column-number "?") ":") (:message %)) (xmlv/errors validation-result)))))))
opts)
|
[
{
"context": "ery is exposed for those who do.\"\r\n :author \"Tims Gardner and Ramsey Nasser\"}\r\n arcadia.compiler\r\n (:re",
"end": 217,
"score": 0.9998817443847656,
"start": 205,
"tag": "NAME",
"value": "Tims Gardner"
},
{
"context": "or those who do.\"\r\n :author \"Tims Gardner and Ramsey Nasser\"}\r\n arcadia.compiler\r\n (:require [arcadia.con",
"end": 235,
"score": 0.9998694658279419,
"start": 222,
"tag": "NAME",
"value": "Ramsey Nasser"
}
] |
Source/arcadia/compiler.clj
|
pjago/Arcadia
| 0 |
(ns ^{:doc "Integration with the Unity compiler pipeline. Typical
Arcadia users will not need to use this namespace,
but the machinery is exposed for those who do."
:author "Tims Gardner and Ramsey Nasser"}
arcadia.compiler
(:require [arcadia.config :as config]
[clojure.spec :as s]
[clojure.string :as str]
[arcadia.internal.state :as state]
[arcadia.internal.spec :as as]
[arcadia.internal.asset-watcher :as aw]
[arcadia.internal.filewatcher :as fw]
[arcadia.internal.editor-callbacks :as callbacks])
(:import [Arcadia StringHelper]
[clojure.lang Namespace]
[System.IO Path File StringWriter Directory]
[System.Text.RegularExpressions Regex]
[System.Collections Queue]
[System.Threading Thread ThreadStart]
[UnityEngine Debug]))
(def main-thread System.Threading.Thread/CurrentThread)
(defn on-main-thread? []
(.Equals main-thread System.Threading.Thread/CurrentThread))
(defn load-path []
(seq (clojure.lang.RT/GetFindFilePaths)))
(defn rests
"Returns a sequence of all rests of the input sequence
=> (rests [1 2 3 4 5 6 7])
((1 2 3 4 5 6 7) (2 3 4 5 6 7) (3 4 5 6 7) (4 5 6 7) (5 6 7) (6 7) (7))"
[s]
(->> (seq s)
(iterate rest)
(take-while seq)))
(defmacro if-> [v & body]
`(if ~v (-> ~v ~@body)))
(def dir-seperator-re
(re-pattern (Regex/Escape (str Path/DirectorySeparatorChar))))
(defn path->ns
"Returns a namespace from a path
=> (path->ns \"foo/bar/baz.clj\")
\"foo.bar.baz\""
[p]
(if-> p
(clojure.string/replace #"\.cljc?$" "")
(clojure.string/replace dir-seperator-re ".")
(clojure.string/replace "_" "-")))
(defn relative-to-load-path
"Sequence of subpaths relative to the load path, shortest first"
[path]
(->> (clojure.string/split path dir-seperator-re)
rests
reverse
(map #(clojure.string/join Path/DirectorySeparatorChar %))
(filter #(clojure.lang.RT/FindFile %))))
(defn clj-file?
"Is `path` a Clojure file?"
[path]
(boolean (re-find #"\.cljc?$" path)))
(defn config-file?
"Is `path` the configuration file?"
[path]
(= path
(config/user-config-file)))
(defn clj-files [paths]
(filter clj-file? paths))
(defn asset->ns [asset]
(-> asset
relative-to-load-path
first
path->ns
(#(if % (symbol %) %))))
(defn read-file [file]
(binding [*read-eval* false]
(read-string (slurp file :encoding "utf8"))))
(defn first-form-is-ns? [asset]
(boolean
(when-let [[frst & rst] (seq (read-file asset))]
(= frst 'ns))))
(defn correct-ns? [asset]
(let [[frst scnd & rst] (read-file asset)
expected-ns (asset->ns asset)]
(= scnd expected-ns)))
(defn should-compile? [file]
(if (File/Exists file)
(and (not (re-find #"data_readers.clj$" file))
(first-form-is-ns? file)
(correct-ns? file))))
(defn dependencies [ns]
(let [nss-mappings (->> ns
.getMappings
vals
(filter var?)
(map #(.. % Namespace)))
nss-aliases (->> ns
.getAliases
vals)]
(-> (into #{} (concat nss-aliases
nss-mappings))
(disj ns
(find-ns 'clojure.core)))))
(defn all-dependencies
([] (all-dependencies Namespace/all))
([nss]
(reduce
(fn [m ns]
(reduce
(fn [m* ns*]
(update m* (.Name ns*)
(fnil conj #{}) (.Name ns)))
m
(dependencies ns)))
{}
(remove #{(find-ns 'user)} nss))))
(defn reload-ns [n]
(Debug/Log (str "Loading " n))
(require n :reload))
(defn reload-ns-and-deps [n]
(let [dep-map (all-dependencies)]
(loop [nss [n]
loaded #{}]
(when-not (empty? nss)
(let [loaded (into loaded nss)]
(doseq [ns nss]
(reload-ns ns))
(recur (remove loaded (mapcat dep-map nss))
loaded))))))
(defn import-asset [asset]
(if (should-compile? asset)
(reload-ns (asset->ns asset))
(Debug/Log (str "Not Loading " asset))))
(def ^:dynamic *exporting?* false)
(defn aot-namespaces
([path nss]
(aot-namespaces path nss nil))
([path nss {:keys [file-callback] :as opts}]
;; We want to ensure that namespaces are neither double-aot'd, nor
;; _not_ aot'd if already in memory.
;; In other words, we want to walk the forest of all the provided
;; namespaces and their dependency namespaces, aot-ing each
;; namespace we encounter in this walk exactly once. `:reload-all`
;; will re-aot encountered namespaces redundantly, potentially
;; invalidating old type references (I think). Normal `require`
;; will not do a deep walk over already-loaded namespaces. So
;; instead we rebind the *loaded-libs* var to a ref with an empty
;; set and call normal `require`, which gives the desired behavior.
(let [loaded-libs' (binding [*compiler-options* (get (arcadia.config/config) :compiler/options {})
*compile-path* path
*compile-files* true
arcadia.compiler/*exporting?* true
clojure.core/*loaded-libs* (ref #{})]
(doseq [ns nss]
(require ns)
(when file-callback
(file-callback ns)))
@#'clojure.core/*loaded-libs*)]
(dosync
(alter @#'clojure.core/*loaded-libs* into @loaded-libs'))
nil)))
(defn aot-asset [path asset]
(when (should-compile? asset)
(Debug/Log (str "Compiling " asset " to " path))
(aot-namespaces path (asset->ns asset))))
(defn aot-assets [path assets]
(doseq [asset assets]
(aot-asset path asset)))
(defn import-assets [imported]
(when (some config-file? imported)
(Debug/Log (str "Updating config"))
(config/update!))
(doseq [asset (clj-files imported)]
(import-asset asset)
#_ (import-asset asset)))
(defn delete-assets [deleted]
(doseq [asset (clj-files deleted)]))
;; ============================================================
;; stand-in while building new liveload
(defn start-watching-files []
(throw (Exception. "still building liveload infrastructure")))
(defn stop-watching-files []
(throw (Exception. "still building liveload infrastructure")))
;; ============================================================
;; loadpath handling
(s/def ::loadpath-extension-fns
(s/map-of keyword? ifn?))
(defn add-loadpath-extension-fn [k f]
(swap! state/state update ::loadpath-extension-fns
(fn [loadpath-extensions]
(let [res (assoc loadpath-extensions k f)]
(if (or *compile-files* ;; annoying fix for issue #212
(as/loud-valid? ::loadpath-extension-fns res))
res
(throw
(Exception.
(str
"Result of attempt to add loadpath extension function keyed to " k
" fails:\n"
(with-out-str
(s/explain ::loadpath-extension-fns res))))))))))
(defn remove-loadpath-extension-fn [k]
(swap! state/state update ::loadpath-extensions dissoc k))
(defn loadpath-extensions
([] (loadpath-extensions nil))
([{:keys [::strict?],
:as opts}]
(let [ap (if strict?
(fn ap [bldg _ f]
(conj bldg (f)))
(fn ap [bldg k f]
(try
(conj bldg (f))
(catch Exception e
(Debug/Log
(str
"Encountered " (class e)
" exception for loadpath extension function keyed to "
k " during computation of loadpath."
e))
bldg))))]
(reduce-kv ap [] (::loadpath-extension-fns @state/state)))))
(defn configuration-extensions []
(map #(System.IO.Path/GetFullPath %)
(get-in @state/state [::config/config :arcadia.compiler/loadpaths])))
(defn loadpath-extension-string
([] (loadpath-extension-string nil))
([opts]
(str/join Path/PathSeparator
(concat
(loadpath-extensions opts)
(configuration-extensions)))))
(defn refresh-loadpath
([]
(callbacks/add-callback
#(Arcadia.Initialization/SetClojureLoadPath)))
([config]
(refresh-loadpath)))
(state/add-listener ::config/on-update ::refresh-loadpath #'refresh-loadpath)
;; ============================================================
;; listeners
(defn reload-if-loaded [path]
(when (some-> path asset->ns find-ns)
(import-asset path)))
(defn live-reload-listener [{:keys [::fw/path]}]
(callbacks/add-callback #(reload-if-loaded path)))
(defn start-watching-files []
;; (UnityEngine.Debug/Log "Starting to watch for changes in Clojure files.")
(aw/add-listener
::fw/create-modify-delete-file
::live-reload-listener
[".clj" ".cljc"]
#'live-reload-listener))
(defn stop-watching-files []
(aw/remove-listener ::live-reload-listener))
(defn manage-reload-listener [{:keys [reload-on-change]}]
(if reload-on-change
(start-watching-files)
(stop-watching-files)))
(state/add-listener ::config/on-update ::live-reload
#'manage-reload-listener)
(manage-reload-listener (config/config))
|
111897
|
(ns ^{:doc "Integration with the Unity compiler pipeline. Typical
Arcadia users will not need to use this namespace,
but the machinery is exposed for those who do."
:author "<NAME> and <NAME>"}
arcadia.compiler
(:require [arcadia.config :as config]
[clojure.spec :as s]
[clojure.string :as str]
[arcadia.internal.state :as state]
[arcadia.internal.spec :as as]
[arcadia.internal.asset-watcher :as aw]
[arcadia.internal.filewatcher :as fw]
[arcadia.internal.editor-callbacks :as callbacks])
(:import [Arcadia StringHelper]
[clojure.lang Namespace]
[System.IO Path File StringWriter Directory]
[System.Text.RegularExpressions Regex]
[System.Collections Queue]
[System.Threading Thread ThreadStart]
[UnityEngine Debug]))
(def main-thread System.Threading.Thread/CurrentThread)
(defn on-main-thread? []
(.Equals main-thread System.Threading.Thread/CurrentThread))
(defn load-path []
(seq (clojure.lang.RT/GetFindFilePaths)))
(defn rests
"Returns a sequence of all rests of the input sequence
=> (rests [1 2 3 4 5 6 7])
((1 2 3 4 5 6 7) (2 3 4 5 6 7) (3 4 5 6 7) (4 5 6 7) (5 6 7) (6 7) (7))"
[s]
(->> (seq s)
(iterate rest)
(take-while seq)))
(defmacro if-> [v & body]
`(if ~v (-> ~v ~@body)))
(def dir-seperator-re
(re-pattern (Regex/Escape (str Path/DirectorySeparatorChar))))
(defn path->ns
"Returns a namespace from a path
=> (path->ns \"foo/bar/baz.clj\")
\"foo.bar.baz\""
[p]
(if-> p
(clojure.string/replace #"\.cljc?$" "")
(clojure.string/replace dir-seperator-re ".")
(clojure.string/replace "_" "-")))
(defn relative-to-load-path
"Sequence of subpaths relative to the load path, shortest first"
[path]
(->> (clojure.string/split path dir-seperator-re)
rests
reverse
(map #(clojure.string/join Path/DirectorySeparatorChar %))
(filter #(clojure.lang.RT/FindFile %))))
(defn clj-file?
"Is `path` a Clojure file?"
[path]
(boolean (re-find #"\.cljc?$" path)))
(defn config-file?
"Is `path` the configuration file?"
[path]
(= path
(config/user-config-file)))
(defn clj-files [paths]
(filter clj-file? paths))
(defn asset->ns [asset]
(-> asset
relative-to-load-path
first
path->ns
(#(if % (symbol %) %))))
(defn read-file [file]
(binding [*read-eval* false]
(read-string (slurp file :encoding "utf8"))))
(defn first-form-is-ns? [asset]
(boolean
(when-let [[frst & rst] (seq (read-file asset))]
(= frst 'ns))))
(defn correct-ns? [asset]
(let [[frst scnd & rst] (read-file asset)
expected-ns (asset->ns asset)]
(= scnd expected-ns)))
(defn should-compile? [file]
(if (File/Exists file)
(and (not (re-find #"data_readers.clj$" file))
(first-form-is-ns? file)
(correct-ns? file))))
(defn dependencies [ns]
(let [nss-mappings (->> ns
.getMappings
vals
(filter var?)
(map #(.. % Namespace)))
nss-aliases (->> ns
.getAliases
vals)]
(-> (into #{} (concat nss-aliases
nss-mappings))
(disj ns
(find-ns 'clojure.core)))))
(defn all-dependencies
([] (all-dependencies Namespace/all))
([nss]
(reduce
(fn [m ns]
(reduce
(fn [m* ns*]
(update m* (.Name ns*)
(fnil conj #{}) (.Name ns)))
m
(dependencies ns)))
{}
(remove #{(find-ns 'user)} nss))))
(defn reload-ns [n]
(Debug/Log (str "Loading " n))
(require n :reload))
(defn reload-ns-and-deps [n]
(let [dep-map (all-dependencies)]
(loop [nss [n]
loaded #{}]
(when-not (empty? nss)
(let [loaded (into loaded nss)]
(doseq [ns nss]
(reload-ns ns))
(recur (remove loaded (mapcat dep-map nss))
loaded))))))
(defn import-asset [asset]
(if (should-compile? asset)
(reload-ns (asset->ns asset))
(Debug/Log (str "Not Loading " asset))))
(def ^:dynamic *exporting?* false)
(defn aot-namespaces
([path nss]
(aot-namespaces path nss nil))
([path nss {:keys [file-callback] :as opts}]
;; We want to ensure that namespaces are neither double-aot'd, nor
;; _not_ aot'd if already in memory.
;; In other words, we want to walk the forest of all the provided
;; namespaces and their dependency namespaces, aot-ing each
;; namespace we encounter in this walk exactly once. `:reload-all`
;; will re-aot encountered namespaces redundantly, potentially
;; invalidating old type references (I think). Normal `require`
;; will not do a deep walk over already-loaded namespaces. So
;; instead we rebind the *loaded-libs* var to a ref with an empty
;; set and call normal `require`, which gives the desired behavior.
(let [loaded-libs' (binding [*compiler-options* (get (arcadia.config/config) :compiler/options {})
*compile-path* path
*compile-files* true
arcadia.compiler/*exporting?* true
clojure.core/*loaded-libs* (ref #{})]
(doseq [ns nss]
(require ns)
(when file-callback
(file-callback ns)))
@#'clojure.core/*loaded-libs*)]
(dosync
(alter @#'clojure.core/*loaded-libs* into @loaded-libs'))
nil)))
(defn aot-asset [path asset]
(when (should-compile? asset)
(Debug/Log (str "Compiling " asset " to " path))
(aot-namespaces path (asset->ns asset))))
(defn aot-assets [path assets]
(doseq [asset assets]
(aot-asset path asset)))
(defn import-assets [imported]
(when (some config-file? imported)
(Debug/Log (str "Updating config"))
(config/update!))
(doseq [asset (clj-files imported)]
(import-asset asset)
#_ (import-asset asset)))
(defn delete-assets [deleted]
(doseq [asset (clj-files deleted)]))
;; ============================================================
;; stand-in while building new liveload
(defn start-watching-files []
(throw (Exception. "still building liveload infrastructure")))
(defn stop-watching-files []
(throw (Exception. "still building liveload infrastructure")))
;; ============================================================
;; loadpath handling
(s/def ::loadpath-extension-fns
(s/map-of keyword? ifn?))
(defn add-loadpath-extension-fn [k f]
(swap! state/state update ::loadpath-extension-fns
(fn [loadpath-extensions]
(let [res (assoc loadpath-extensions k f)]
(if (or *compile-files* ;; annoying fix for issue #212
(as/loud-valid? ::loadpath-extension-fns res))
res
(throw
(Exception.
(str
"Result of attempt to add loadpath extension function keyed to " k
" fails:\n"
(with-out-str
(s/explain ::loadpath-extension-fns res))))))))))
(defn remove-loadpath-extension-fn [k]
(swap! state/state update ::loadpath-extensions dissoc k))
(defn loadpath-extensions
([] (loadpath-extensions nil))
([{:keys [::strict?],
:as opts}]
(let [ap (if strict?
(fn ap [bldg _ f]
(conj bldg (f)))
(fn ap [bldg k f]
(try
(conj bldg (f))
(catch Exception e
(Debug/Log
(str
"Encountered " (class e)
" exception for loadpath extension function keyed to "
k " during computation of loadpath."
e))
bldg))))]
(reduce-kv ap [] (::loadpath-extension-fns @state/state)))))
(defn configuration-extensions []
(map #(System.IO.Path/GetFullPath %)
(get-in @state/state [::config/config :arcadia.compiler/loadpaths])))
(defn loadpath-extension-string
([] (loadpath-extension-string nil))
([opts]
(str/join Path/PathSeparator
(concat
(loadpath-extensions opts)
(configuration-extensions)))))
(defn refresh-loadpath
([]
(callbacks/add-callback
#(Arcadia.Initialization/SetClojureLoadPath)))
([config]
(refresh-loadpath)))
(state/add-listener ::config/on-update ::refresh-loadpath #'refresh-loadpath)
;; ============================================================
;; listeners
(defn reload-if-loaded [path]
(when (some-> path asset->ns find-ns)
(import-asset path)))
(defn live-reload-listener [{:keys [::fw/path]}]
(callbacks/add-callback #(reload-if-loaded path)))
(defn start-watching-files []
;; (UnityEngine.Debug/Log "Starting to watch for changes in Clojure files.")
(aw/add-listener
::fw/create-modify-delete-file
::live-reload-listener
[".clj" ".cljc"]
#'live-reload-listener))
(defn stop-watching-files []
(aw/remove-listener ::live-reload-listener))
(defn manage-reload-listener [{:keys [reload-on-change]}]
(if reload-on-change
(start-watching-files)
(stop-watching-files)))
(state/add-listener ::config/on-update ::live-reload
#'manage-reload-listener)
(manage-reload-listener (config/config))
| true |
(ns ^{:doc "Integration with the Unity compiler pipeline. Typical
Arcadia users will not need to use this namespace,
but the machinery is exposed for those who do."
:author "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"}
arcadia.compiler
(:require [arcadia.config :as config]
[clojure.spec :as s]
[clojure.string :as str]
[arcadia.internal.state :as state]
[arcadia.internal.spec :as as]
[arcadia.internal.asset-watcher :as aw]
[arcadia.internal.filewatcher :as fw]
[arcadia.internal.editor-callbacks :as callbacks])
(:import [Arcadia StringHelper]
[clojure.lang Namespace]
[System.IO Path File StringWriter Directory]
[System.Text.RegularExpressions Regex]
[System.Collections Queue]
[System.Threading Thread ThreadStart]
[UnityEngine Debug]))
(def main-thread System.Threading.Thread/CurrentThread)
(defn on-main-thread? []
(.Equals main-thread System.Threading.Thread/CurrentThread))
(defn load-path []
(seq (clojure.lang.RT/GetFindFilePaths)))
(defn rests
"Returns a sequence of all rests of the input sequence
=> (rests [1 2 3 4 5 6 7])
((1 2 3 4 5 6 7) (2 3 4 5 6 7) (3 4 5 6 7) (4 5 6 7) (5 6 7) (6 7) (7))"
[s]
(->> (seq s)
(iterate rest)
(take-while seq)))
(defmacro if-> [v & body]
`(if ~v (-> ~v ~@body)))
(def dir-seperator-re
(re-pattern (Regex/Escape (str Path/DirectorySeparatorChar))))
(defn path->ns
"Returns a namespace from a path
=> (path->ns \"foo/bar/baz.clj\")
\"foo.bar.baz\""
[p]
(if-> p
(clojure.string/replace #"\.cljc?$" "")
(clojure.string/replace dir-seperator-re ".")
(clojure.string/replace "_" "-")))
(defn relative-to-load-path
"Sequence of subpaths relative to the load path, shortest first"
[path]
(->> (clojure.string/split path dir-seperator-re)
rests
reverse
(map #(clojure.string/join Path/DirectorySeparatorChar %))
(filter #(clojure.lang.RT/FindFile %))))
(defn clj-file?
"Is `path` a Clojure file?"
[path]
(boolean (re-find #"\.cljc?$" path)))
(defn config-file?
"Is `path` the configuration file?"
[path]
(= path
(config/user-config-file)))
(defn clj-files [paths]
(filter clj-file? paths))
(defn asset->ns [asset]
(-> asset
relative-to-load-path
first
path->ns
(#(if % (symbol %) %))))
(defn read-file [file]
(binding [*read-eval* false]
(read-string (slurp file :encoding "utf8"))))
(defn first-form-is-ns? [asset]
(boolean
(when-let [[frst & rst] (seq (read-file asset))]
(= frst 'ns))))
(defn correct-ns? [asset]
(let [[frst scnd & rst] (read-file asset)
expected-ns (asset->ns asset)]
(= scnd expected-ns)))
(defn should-compile? [file]
(if (File/Exists file)
(and (not (re-find #"data_readers.clj$" file))
(first-form-is-ns? file)
(correct-ns? file))))
(defn dependencies [ns]
(let [nss-mappings (->> ns
.getMappings
vals
(filter var?)
(map #(.. % Namespace)))
nss-aliases (->> ns
.getAliases
vals)]
(-> (into #{} (concat nss-aliases
nss-mappings))
(disj ns
(find-ns 'clojure.core)))))
(defn all-dependencies
([] (all-dependencies Namespace/all))
([nss]
(reduce
(fn [m ns]
(reduce
(fn [m* ns*]
(update m* (.Name ns*)
(fnil conj #{}) (.Name ns)))
m
(dependencies ns)))
{}
(remove #{(find-ns 'user)} nss))))
(defn reload-ns [n]
(Debug/Log (str "Loading " n))
(require n :reload))
(defn reload-ns-and-deps [n]
(let [dep-map (all-dependencies)]
(loop [nss [n]
loaded #{}]
(when-not (empty? nss)
(let [loaded (into loaded nss)]
(doseq [ns nss]
(reload-ns ns))
(recur (remove loaded (mapcat dep-map nss))
loaded))))))
(defn import-asset [asset]
(if (should-compile? asset)
(reload-ns (asset->ns asset))
(Debug/Log (str "Not Loading " asset))))
(def ^:dynamic *exporting?* false)
(defn aot-namespaces
([path nss]
(aot-namespaces path nss nil))
([path nss {:keys [file-callback] :as opts}]
;; We want to ensure that namespaces are neither double-aot'd, nor
;; _not_ aot'd if already in memory.
;; In other words, we want to walk the forest of all the provided
;; namespaces and their dependency namespaces, aot-ing each
;; namespace we encounter in this walk exactly once. `:reload-all`
;; will re-aot encountered namespaces redundantly, potentially
;; invalidating old type references (I think). Normal `require`
;; will not do a deep walk over already-loaded namespaces. So
;; instead we rebind the *loaded-libs* var to a ref with an empty
;; set and call normal `require`, which gives the desired behavior.
(let [loaded-libs' (binding [*compiler-options* (get (arcadia.config/config) :compiler/options {})
*compile-path* path
*compile-files* true
arcadia.compiler/*exporting?* true
clojure.core/*loaded-libs* (ref #{})]
(doseq [ns nss]
(require ns)
(when file-callback
(file-callback ns)))
@#'clojure.core/*loaded-libs*)]
(dosync
(alter @#'clojure.core/*loaded-libs* into @loaded-libs'))
nil)))
(defn aot-asset [path asset]
(when (should-compile? asset)
(Debug/Log (str "Compiling " asset " to " path))
(aot-namespaces path (asset->ns asset))))
(defn aot-assets [path assets]
(doseq [asset assets]
(aot-asset path asset)))
(defn import-assets [imported]
(when (some config-file? imported)
(Debug/Log (str "Updating config"))
(config/update!))
(doseq [asset (clj-files imported)]
(import-asset asset)
#_ (import-asset asset)))
(defn delete-assets [deleted]
(doseq [asset (clj-files deleted)]))
;; ============================================================
;; stand-in while building new liveload
(defn start-watching-files []
(throw (Exception. "still building liveload infrastructure")))
(defn stop-watching-files []
(throw (Exception. "still building liveload infrastructure")))
;; ============================================================
;; loadpath handling
(s/def ::loadpath-extension-fns
(s/map-of keyword? ifn?))
(defn add-loadpath-extension-fn [k f]
(swap! state/state update ::loadpath-extension-fns
(fn [loadpath-extensions]
(let [res (assoc loadpath-extensions k f)]
(if (or *compile-files* ;; annoying fix for issue #212
(as/loud-valid? ::loadpath-extension-fns res))
res
(throw
(Exception.
(str
"Result of attempt to add loadpath extension function keyed to " k
" fails:\n"
(with-out-str
(s/explain ::loadpath-extension-fns res))))))))))
(defn remove-loadpath-extension-fn [k]
(swap! state/state update ::loadpath-extensions dissoc k))
(defn loadpath-extensions
([] (loadpath-extensions nil))
([{:keys [::strict?],
:as opts}]
(let [ap (if strict?
(fn ap [bldg _ f]
(conj bldg (f)))
(fn ap [bldg k f]
(try
(conj bldg (f))
(catch Exception e
(Debug/Log
(str
"Encountered " (class e)
" exception for loadpath extension function keyed to "
k " during computation of loadpath."
e))
bldg))))]
(reduce-kv ap [] (::loadpath-extension-fns @state/state)))))
(defn configuration-extensions []
(map #(System.IO.Path/GetFullPath %)
(get-in @state/state [::config/config :arcadia.compiler/loadpaths])))
(defn loadpath-extension-string
([] (loadpath-extension-string nil))
([opts]
(str/join Path/PathSeparator
(concat
(loadpath-extensions opts)
(configuration-extensions)))))
(defn refresh-loadpath
([]
(callbacks/add-callback
#(Arcadia.Initialization/SetClojureLoadPath)))
([config]
(refresh-loadpath)))
(state/add-listener ::config/on-update ::refresh-loadpath #'refresh-loadpath)
;; ============================================================
;; listeners
(defn reload-if-loaded [path]
(when (some-> path asset->ns find-ns)
(import-asset path)))
(defn live-reload-listener [{:keys [::fw/path]}]
(callbacks/add-callback #(reload-if-loaded path)))
(defn start-watching-files []
;; (UnityEngine.Debug/Log "Starting to watch for changes in Clojure files.")
(aw/add-listener
::fw/create-modify-delete-file
::live-reload-listener
[".clj" ".cljc"]
#'live-reload-listener))
(defn stop-watching-files []
(aw/remove-listener ::live-reload-listener))
(defn manage-reload-listener [{:keys [reload-on-change]}]
(if reload-on-change
(start-watching-files)
(stop-watching-files)))
(state/add-listener ::config/on-update ::live-reload
#'manage-reload-listener)
(manage-reload-listener (config/config))
|
[
{
"context": " (let [key-usage (utils/get-extension-value cert \"2.5.29.15\")]\n (is (= #{:key-cert-sign :crl-sign}",
"end": 15074,
"score": 0.9996488094329834,
"start": 15065,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "message \"Found extensions that are not permitted: 1.9.9.9.9.9.9\"}]\n [\"public-private ke",
"end": 37018,
"score": 0.979925274848938,
"start": 37011,
"tag": "IP_ADDRESS",
"value": "1.9.9.9"
},
{
"context": "ent-value}\n {:oid \"2.5.29.35\"\n :critical false\n ",
"end": 39436,
"score": 0.9995779395103455,
"start": 39427,
"tag": "IP_ADDRESS",
"value": "2.5.29.35"
},
{
"context": "mber nil}}\n {:oid \"2.5.29.19\"\n :critical true\n ",
"end": 39713,
"score": 0.9995389580726624,
"start": 39704,
"tag": "IP_ADDRESS",
"value": "2.5.29.19"
},
{
"context": "ca false}}\n {:oid \"2.5.29.37\"\n :critical true\n ",
"end": 39860,
"score": 0.999566912651062,
"start": 39851,
"tag": "IP_ADDRESS",
"value": "2.5.29.37"
},
{
"context": "ent-cert]}\n {:oid \"2.5.29.15\"\n :critical true\n ",
"end": 40026,
"score": 0.999610185623169,
"start": 40017,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "pherment}}\n {:oid \"2.5.29.14\"\n :critical false\n ",
"end": 40198,
"score": 0.9996382594108582,
"start": 40189,
"tag": "IP_ADDRESS",
"value": "2.5.29.14"
},
{
"context": "ent-value}\n {:oid \"2.5.29.35\"\n :critical false\n ",
"end": 40999,
"score": 0.9996257424354553,
"start": 40990,
"tag": "IP_ADDRESS",
"value": "2.5.29.35"
},
{
"context": "mber nil}}\n {:oid \"2.5.29.19\"\n :critical true\n ",
"end": 41276,
"score": 0.999628484249115,
"start": 41267,
"tag": "IP_ADDRESS",
"value": "2.5.29.19"
},
{
"context": "ca false}}\n {:oid \"2.5.29.37\"\n :critical true\n ",
"end": 41423,
"score": 0.9996359348297119,
"start": 41414,
"tag": "IP_ADDRESS",
"value": "2.5.29.37"
},
{
"context": "ent-cert]}\n {:oid \"2.5.29.15\"\n :critical true\n ",
"end": 41589,
"score": 0.9996659755706787,
"start": 41580,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "pherment}}\n {:oid \"2.5.29.14\"\n :critical false\n ",
"end": 41761,
"score": 0.9996423721313477,
"start": 41752,
"tag": "IP_ADDRESS",
"value": "2.5.29.14"
},
{
"context": "ent-value}\n {:oid \"2.5.29.35\"\n :critical false\n ",
"end": 42924,
"score": 0.9995972514152527,
"start": 42915,
"tag": "IP_ADDRESS",
"value": "2.5.29.35"
},
{
"context": "mber nil}}\n {:oid \"2.5.29.19\"\n :critical true\n ",
"end": 43201,
"score": 0.99957275390625,
"start": 43192,
"tag": "IP_ADDRESS",
"value": "2.5.29.19"
},
{
"context": "ca false}}\n {:oid \"2.5.29.37\"\n :critical true\n ",
"end": 43348,
"score": 0.999618411064148,
"start": 43339,
"tag": "IP_ADDRESS",
"value": "2.5.29.37"
},
{
"context": "ent-cert]}\n {:oid \"2.5.29.15\"\n :critical true\n ",
"end": 43514,
"score": 0.9996215105056763,
"start": 43505,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "pherment}}\n {:oid \"2.5.29.14\"\n :critical false\n ",
"end": 43686,
"score": 0.9996368885040283,
"start": 43677,
"tag": "IP_ADDRESS",
"value": "2.5.29.14"
},
{
"context": "bject-pub}\n {:oid \"2.5.29.17\"\n :critical false\n ",
"end": 43831,
"score": 0.9996598362922668,
"start": 43822,
"tag": "IP_ADDRESS",
"value": "2.5.29.17"
},
{
"context": "cluster\"}\n {:oid \"1.3.6.1.4.1.34380.1.1.17\" :critical false\n ",
"end": 46620,
"score": 0.9450653791427612,
"start": 46615,
"tag": "IP_ADDRESS",
"value": "3.6.1"
},
{
"context": " {:oid \"1.3.6.1.4.1.34380.1.1.17\" :critical false\n :val",
"end": 46637,
"score": 0.9961013793945312,
"start": 46631,
"tag": "IP_ADDRESS",
"value": "1.1.17"
},
{
"context": "message \"Found extensions that are not permitted: 1.2.3.4\"}\n (create-master-extensions subject",
"end": 47177,
"score": 0.999235987663269,
"start": 47170,
"tag": "IP_ADDRESS",
"value": "1.2.3.4"
},
{
"context": "ent-value}\n {:oid \"2.5.29.35\"\n :critical false\n ",
"end": 48244,
"score": 0.9718562364578247,
"start": 48235,
"tag": "IP_ADDRESS",
"value": "2.5.29.35"
},
{
"context": " serial)}}\n {:oid \"2.5.29.19\"\n :critical true\n ",
"end": 48546,
"score": 0.970416784286499,
"start": 48537,
"tag": "IP_ADDRESS",
"value": "2.5.29.19"
},
{
"context": "-ca true}}\n {:oid \"2.5.29.15\"\n :critical true\n ",
"end": 48692,
"score": 0.9889353513717651,
"start": 48683,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "ert-sign}}\n {:oid \"2.5.29.14\"\n :critical false\n ",
"end": 48852,
"score": 0.977742075920105,
"start": 48843,
"tag": "IP_ADDRESS",
"value": "2.5.29.14"
},
{
"context": "ent-value}\n {:oid \"2.5.29.35\"\n :critical false\n ",
"end": 49734,
"score": 0.9912221431732178,
"start": 49725,
"tag": "IP_ADDRESS",
"value": "2.5.29.35"
},
{
"context": "mber nil}}\n {:oid \"2.5.29.19\"\n :critical true\n ",
"end": 50011,
"score": 0.9880142211914062,
"start": 50002,
"tag": "IP_ADDRESS",
"value": "2.5.29.19"
},
{
"context": "ca false}}\n {:oid \"2.5.29.37\"\n :critical true\n ",
"end": 50158,
"score": 0.9942483901977539,
"start": 50149,
"tag": "IP_ADDRESS",
"value": "2.5.29.37"
},
{
"context": "ent-cert]}\n {:oid \"2.5.29.15\"\n :critical true\n ",
"end": 50324,
"score": 0.9968999028205872,
"start": 50315,
"tag": "IP_ADDRESS",
"value": "2.5.29.15"
},
{
"context": "pherment}}\n {:oid \"2.5.29.14\"\n :critical false\n ",
"end": 50496,
"score": 0.9810649156570435,
"start": 50487,
"tag": "IP_ADDRESS",
"value": "2.5.29.14"
},
{
"context": " {:oid \"1.3.6.1.4.1.34380.1.1.4\"\n :critical false\n ",
"end": 51136,
"score": 0.9979377388954163,
"start": 51135,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "nsion\"}\n (validate-dns-alt-names! {:oid \"2.5.29.17\"\n :critical fa",
"end": 52524,
"score": 0.9997487664222717,
"start": 52515,
"tag": "IP_ADDRESS",
"value": "2.5.29.17"
},
{
"context": " :value {:ip-address [\"12.34.5.6\"]}}))))\n\n (testing \"No DNS wildcards are allowed",
"end": 52645,
"score": 0.9997634887695312,
"start": 52636,
"tag": "IP_ADDRESS",
"value": "12.34.5.6"
},
{
"context": "o*bar\"}\n (validate-dns-alt-names! {:oid \"2.5.29.17\"\n :critical fa",
"end": 52912,
"score": 0.9997433423995972,
"start": 52903,
"tag": "IP_ADDRESS",
"value": "2.5.29.17"
}
] |
test/unit/puppetlabs/puppetserver/certificate_authority_test.clj
|
ahpook/puppet-server
| 0 |
(ns puppetlabs.puppetserver.certificate-authority-test
(:import (java.io StringReader ByteArrayInputStream ByteArrayOutputStream)
(java.security InvalidParameterException))
(:require [puppetlabs.puppetserver.certificate-authority :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.kitchensink.core :as ks]
[slingshot.slingshot :as sling]
[schema.test :as schema-test]
[clojure.test :refer :all]
[clojure.java.io :as io]
[clojure.string :as string]
[clj-time.core :as time]
[clj-time.coerce :as time-coerce]
[me.raynes.fs :as fs]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Test Data
(def test-resources-dir "./dev-resources/puppetlabs/puppetserver/certificate_authority_test")
(def confdir (str test-resources-dir "/master/conf"))
(def ssldir (str confdir "/ssl"))
(def cadir (str ssldir "/ca"))
(def cacert (str cadir "/ca_crt.pem"))
(def cakey (str cadir "/ca_key.pem"))
(def capub (str cadir "/ca_pub.pem"))
(def cacrl (str cadir "/ca_crl.pem"))
(def csrdir (str cadir "/requests"))
(def signeddir (str cadir "/signed"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-confs-dir (str test-resources-dir "/autosign_confs"))
(def autosign-exes-dir (str test-resources-dir "/autosign_exes"))
(def csr-attributes-dir (str test-resources-dir "/csr_attributes"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn autosign-conf-file
[autosign-conf-file-name]
(str autosign-confs-dir "/" autosign-conf-file-name))
(defn autosign-exe-file
[autosign-exe-file-name]
(str autosign-exes-dir "/" autosign-exe-file-name))
(defn csr-attributes-file
[csr-attributes-file-name]
(str csr-attributes-dir "/" csr-attributes-file-name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(defn tmp-whitelist! [& lines]
(let [whitelist (ks/temp-file)]
(doseq [line lines]
(spit whitelist (str line "\n") :append true))
(str whitelist)))
(def empty-stream (ByteArrayInputStream. (.getBytes "")))
(defn csr-stream [subject]
(io/input-stream (path-to-cert-request csrdir subject)))
(defn write-to-stream [o]
(let [s (ByteArrayOutputStream.)]
(utils/obj->pem! o s)
(-> s .toByteArray ByteArrayInputStream.)))
(defn assert-autosign [whitelist subject]
(testing subject
(is (true? (autosign-csr? whitelist subject empty-stream [])))))
(defn assert-no-autosign [whitelist subject]
(testing subject
(is (false? (autosign-csr? whitelist subject empty-stream [])))))
(defmethod assert-expr 'thrown-with-slingshot? [msg form]
(let [expected (nth form 1)
body (nthnext form 2)]
`(sling/try+
~@body
(do-report {:type :fail :message ~msg :expected ~expected :actual nil})
(catch map? actual#
(do-report {:type (if (= actual# ~expected) :pass :fail)
:message ~msg
:expected ~expected
:actual actual#})
actual#))))
(defn contains-ext?
"Does the provided extension list contain an extensions with the given OID."
[ext-list oid]
(> (count (filter #(= oid (:oid %)) ext-list)) 0))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest get-certificate-test
(testing "returns CA certificate when subject is 'ca'"
(let [actual (get-certificate "ca" cacert signeddir)
expected (slurp cacert)]
(is (= expected actual))))
(testing "returns localhost certificate when subject is 'localhost'"
(let [localhost-cert (get-certificate "localhost" cacert signeddir)
expected (slurp (path-to-cert signeddir "localhost"))]
(is (= expected localhost-cert))))
(testing "returns nil when certificate not found for subject"
(is (nil? (get-certificate "not-there" cacert signeddir)))))
(deftest get-certificate-request-test
(testing "returns certificate request for subject"
(let [cert-req (get-certificate-request "test-agent" csrdir)
expected (slurp (path-to-cert-request csrdir "test-agent"))]
(is (= expected cert-req))))
(testing "returns nil when certificate request not found for subject"
(is (nil? (get-certificate-request "not-there" csrdir)))))
(deftest autosign-csr?-test
(testing "boolean values"
(is (true? (autosign-csr? true "unused" empty-stream [])))
(is (false? (autosign-csr? false "unused" empty-stream []))))
(testing "whitelist"
(testing "autosign is false when whitelist doesn't exist"
(is (false? (autosign-csr? "Foo/conf/autosign.conf" "doubleagent"
empty-stream []))))
(testing "exact certnames"
(doto (tmp-whitelist! "foo"
"UPPERCASE"
"this.THAT."
"bar1234"
"AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-autosign "foo")
(assert-autosign "UPPERCASE")
(assert-autosign "this.THAT.")
(assert-autosign "bar1234")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-no-autosign "Foo")
(assert-no-autosign "uppercase")
(assert-no-autosign "this-THAT-")))
(testing "domain-name globs"
(doto (tmp-whitelist! "*.red"
"*.black.local"
"*.UPPER.case")
(assert-autosign "red")
(assert-autosign ".red")
(assert-autosign "green.red")
(assert-autosign "blue.1.red")
(assert-no-autosign "red.white")
(assert-autosign "black.local")
(assert-autosign ".black.local")
(assert-autosign "blue.black.local")
(assert-autosign "2.three.black.local")
(assert-no-autosign "red.local")
(assert-no-autosign "black.local.white")
(assert-autosign "one.0.upper.case")
(assert-autosign "two.upPEr.case")
(assert-autosign "one-two-three.red")))
(testing "allow all with '*'"
(doto (tmp-whitelist! "*")
(assert-autosign "foo")
(assert-autosign "BAR")
(assert-autosign "baz-buz.")
(assert-autosign "0.qux.1.xuq")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")))
(testing "ignores comments and blank lines"
(doto (tmp-whitelist! "#foo"
" "
"bar"
""
"# *.baz"
"*.qux")
(assert-no-autosign "foo")
(assert-no-autosign " ")
(assert-autosign "bar")
(assert-no-autosign "foo.baz")
(assert-autosign "bar.qux")))
(testing "invalid lines logged and ignored"
(doseq [invalid-line ["bar#bar"
" #bar"
"bar "
" bar"]]
(let [whitelist (tmp-whitelist! "foo"
invalid-line
"qux")]
(assert-autosign whitelist "foo")
(logutils/with-log-output logs
(assert-no-autosign whitelist invalid-line)
(is (logutils/logs-matching
(re-pattern (format "Invalid pattern '%s' found in %s"
invalid-line whitelist))
@logs))
(assert-autosign whitelist "qux")))))
(testing "sample file that covers everything"
(logutils/with-test-logging
(doto (autosign-conf-file "autosign-whitelist.conf")
(assert-no-autosign "aaa")
(assert-autosign "bbb123")
(assert-autosign "one_2.red")
(assert-autosign "1.blacK.6")
(assert-no-autosign "black.white")
(assert-no-autosign "coffee")
(assert-no-autosign "coffee#tea")
(assert-autosign "qux"))))))
(deftest autosign-csr?-ruby-exe-test
(let [executable (autosign-exe-file "ruby-autosign-executable")
csr-fn #(csr-stream "test-agent")
ruby-load-path ["ruby/puppet/lib" "ruby/facter/lib" "ruby/hiera/lib"]]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "Ruby load path is configured and contains Puppet"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"Ruby load path configured properly"))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"subject: test-agent"))
(is (logged? #"CSR for: test-agent"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)))
(is (false? (autosign-csr? executable "foo" (csr-fn) ruby-load-path)))))))
(deftest autosign-csr?-bash-exe-test
(let [executable (autosign-exe-file "bash-autosign-executable")
csr-fn #(csr-stream "test-agent")]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"subject: test-agent"))
(is (logged? #"-----BEGIN CERTIFICATE REQUEST-----"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) [])))
(is (false? (autosign-csr? executable "foo" (csr-fn) [])))))))
(deftest save-certificate-request!-test
(testing "requests are saved to disk"
(let [csrdir (:csrdir (testutils/ca-sandbox! cadir))
csr (utils/pem->csr (path-to-cert-request csrdir "test-agent"))
path (path-to-cert-request csrdir "foo")]
(is (false? (fs/exists? path)))
(save-certificate-request! "foo" csr csrdir)
(is (true? (fs/exists? path)))
(is (= (get-certificate-request csrdir "foo")
(get-certificate-request csrdir "test-agent"))))))
(deftest autosign-certificate-request!-test
(let [now (time/epoch)
two-years (* 60 60 24 365 2)
settings (-> (testutils/ca-sandbox! cadir)
(assoc :ca-ttl two-years))
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
expected-cert-path (path-to-cert (:signeddir settings) "test-agent")]
;; Fix the value of "now" so we can reliably test the dates
(time/do-at now
(autosign-certificate-request! "test-agent" csr settings))
(testing "requests are autosigned and saved to disk"
(is (fs/exists? expected-cert-path)))
(let [cert (utils/pem->cert expected-cert-path)]
(testing "The subject name on the agent's cert"
(testutils/assert-subject cert "CN=test-agent"))
(testing "The cert is issued by the name on the CA's cert"
(testutils/assert-issuer cert "CN=Puppet CA: localhost"))
(testing "certificate has not-before/not-after dates based on $ca-ttl"
(let [not-before (time-coerce/from-date (.getNotBefore cert))
not-after (time-coerce/from-date (.getNotAfter cert))]
(testing "not-before is 1 day before now"
(is (= (time/minus now (time/days 1)) not-before)))
(testing "not-after is 2 years from now"
(is (= (time/plus now (time/years 2)) not-after))))))))
(deftest autosign-without-capub
(testing "The CA public key file is not necessary to autosign"
(let [settings (testutils/ca-sandbox! cadir)
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
cert-path (path-to-cert (:signeddir settings) "test-agent")]
(fs/delete (:capub settings))
(autosign-certificate-request! "test-agent" csr settings)
(is (true? (fs/exists? cert-path)))
(let [cert (utils/pem->cert cert-path)
capub (-> (:cacert settings)
(utils/pem->cert)
(.getPublicKey))]
(is (nil? (.verify cert capub)))))))
(deftest revoke-without-capub
(testing "The CA public key file is not necessary to revoke"
(let [settings (testutils/ca-sandbox! cadir)
cert (-> (:signeddir settings)
(path-to-cert "localhost")
(utils/pem->cert))
revoked? (fn [cert]
(-> (:cacrl settings)
(utils/pem->crl)
(utils/revoked? cert)))]
(fs/delete (:capub settings))
(is (false? (revoked? cert)))
(revoke-existing-cert! settings "localhost")
(is (true? (revoked? cert))))))
(deftest get-certificate-revocation-list-test
(testing "`get-certificate-revocation-list` returns a valid CRL file."
(let [crl (-> (get-certificate-revocation-list cacrl)
StringReader.
utils/pem->crl)]
(testutils/assert-issuer crl "CN=Puppet CA: localhost"))))
(deftest initialize!-test
(let [settings (testutils/ca-settings (ks/temp-dir))]
(initialize! settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->cadir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "cacrl"
(let [crl (-> settings :cacrl utils/pem->crl)]
(testutils/assert-issuer crl "CN=test ca")
(testing "has CRLNumber and AuthorityKeyIdentifier extensions"
(is (not (nil? (utils/get-extension-value crl utils/crl-number-oid))))
(is (not (nil? (utils/get-extension-value crl utils/authority-key-identifier-oid)))))))
(testing "cacert"
(let [cert (-> settings :cacert utils/pem->cert)]
(is (utils/certificate? cert))
(testutils/assert-subject cert "CN=test ca")
(testutils/assert-issuer cert "CN=test ca")
(testing "has at least one expected extension - key usage"
(let [key-usage (utils/get-extension-value cert "2.5.29.15")]
(is (= #{:key-cert-sign :crl-sign} key-usage))))))
(testing "cakey"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "capub"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "cert-inventory"
(is (fs/exists? (:cert-inventory settings))))
(testing "serial"
(is (fs/exists? (:serial settings))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->cadir-paths settings)
(dissoc :csrdir :signeddir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize! settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))))
(deftest initialize!-test-with-keylength-in-settings
(let [settings (assoc (testutils/ca-settings (ks/temp-dir)) :keylength 768)]
(initialize! settings)
(testing "cakey with keylength"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "capub with keylength"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest ca-fail-fast-test
(testing "Directories not required but are created if absent"
(doseq [dir [:signeddir :csrdir]]
(testing dir
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete-dir (get settings dir))
(is (nil? (initialize! settings)))
(is (true? (fs/exists? (get settings dir))))))))
(testing "CA public key not required"
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete (:capub settings))
(is (nil? (initialize! settings)))))
(testing "Exception is thrown when required file is missing"
(doseq [file required-ca-files]
(testing file
(let [settings (testutils/ca-sandbox! cadir)
path (get settings file)]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize! settings))))))))
(deftest retrieve-ca-cert!-test
(testing "CA file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacert (:cacert ca-settings)
localcacert (:localcacert settings)
cacert-text (slurp cacert)]
(testing "Copied cacert to localcacert when localcacert not present"
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) cacert-text)
(str "Unexpected content for localcacert: " localcacert)))
(testing "Doesn't copy cacert over localcacert when different localcacert present"
(let [localcacert-contents "12345"]
(spit (:localcacert settings) localcacert-contents)
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) localcacert-contents)
(str "Unexpected content for localcacert: " localcacert))))
(testing "Throws exception if no localcacert and no cacert to copy"
(fs/delete localcacert)
(let [copy (fs/copy cacert (ks/temp-file))]
(fs/delete cacert)
(is (thrown? IllegalStateException
(retrieve-ca-cert! cacert localcacert))
"No exception thrown even though no file existed for copying")
(fs/copy copy cacert))))))
(deftest retrieve-ca-crl!-test
(testing "CRL file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacrl (:cacrl ca-settings)
hostcrl (:hostcrl settings)
cacrl-text (slurp cacrl)]
(testing "Copied cacrl to hostcrl when hostcrl not present"
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing "Copied cacrl to hostcrl when different hostcrl present"
(spit (:hostcrl settings) "12345")
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing (str "Doesn't throw exception or create dummy file if no "
"hostcrl and no cacrl to copy")
(fs/delete hostcrl)
(let [copy (fs/copy cacrl (ks/temp-file))]
(fs/delete cacrl)
(is (not (fs/exists? hostcrl))
"hostcrl file present even though no file existed for copying")
(fs/copy copy cacrl))))))
(deftest initialize-master-ssl!-test
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir "master")
(assoc :dns-alt-names "onefish,twofish"))
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(retrieve-ca-crl! (:cacrl ca-settings) (:hostcrl settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->ssldir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "hostcert"
(let [hostcert (-> settings :hostcert utils/pem->cert)]
(is (utils/certificate? hostcert))
(testutils/assert-subject hostcert "CN=master")
(testutils/assert-issuer hostcert "CN=Puppet CA: localhost")
(testing "has alt names extension"
(let [dns-alt-names (utils/get-subject-dns-alt-names hostcert)]
(is (= #{"master" "onefish" "twofish"} (set dns-alt-names))
"The Subject Alternative Names extension should contain the
master's actual hostname and the hostnames in $dns-alt-names")))
(testing "is also saved in the CA's $signeddir"
(let [signedpath (path-to-cert (:signeddir ca-settings) "master")]
(is (fs/exists? signedpath))
(is (= hostcert (utils/pem->cert signedpath)))))))
(testing "hostprivkey"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "hostpubkey"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->ssldir-paths settings)
(dissoc :certdir :requestdir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize-master-ssl! settings "master" ca-settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))
(testing "Throws an exception if required file is missing"
(doseq [file required-master-files]
(testing file
(let [path (get settings file)
copy (fs/copy path (ks/temp-file))]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize-master-ssl! settings "master" ca-settings)))
(fs/copy copy path)))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest parse-serial-number-test
(is (= (parse-serial-number "0001") 1))
(is (= (parse-serial-number "0010") 16))
(is (= (parse-serial-number "002A") 42)))
(deftest format-serial-number-test
(is (= (format-serial-number 1) "0001"))
(is (= (format-serial-number 16) "0010"))
(is (= (format-serial-number 42) "002A")))
(deftest next-serial-number!-test
(let [serial-file (str (ks/temp-file))]
(testing "Serial file is initialized to 1"
(initialize-serial-file! serial-file)
(is (= (next-serial-number! serial-file) 1)))
(testing "The serial number file should contain the next serial number"
(is (= "0002" (slurp serial-file))))
(testing "subsequent calls produce increasing serial numbers"
(is (= (next-serial-number! serial-file) 2))
(is (= "0003" (slurp serial-file)))
(is (= (next-serial-number! serial-file) 3))
(is (= "0004" (slurp serial-file))))))
;; If the locking is deleted from `next-serial-number!`, this test will hang,
;; which is not as nice as simply failing ...
;; This seems to happen due to a deadlock caused by concurrently reading and
;; writing to the same file (via `slurp` and `spit`)
(deftest next-serial-number-threadsafety
(testing "next-serial-number! is thread-safe and
never returns a duplicate serial number"
(let [serial-file (doto (str (ks/temp-file)) (spit "0001"))
serials (atom [])
;; spin off a new thread for each CPU
promises (for [_ (range (ks/num-cpus))]
(let [p (promise)]
(future
;; get a bunch of serial numbers and keep track of them
(dotimes [_ 100]
(let [serial-number (next-serial-number! serial-file)]
(swap! serials conj serial-number)))
(deliver p 'done))
p))
contains-duplicates? #(not= (count %) (count (distinct %)))]
; wait on all the threads to finish
(doseq [p promises] (deref p))
(is (false? (contains-duplicates? @serials))
"Got a duplicate serial number"))))
(defn verify-inventory-entry!
[inventory-entry serial-number not-before not-after subject]
(let [parts (string/split inventory-entry #" ")]
(is (= serial-number (first parts)))
(is (= not-before (second parts)))
(is (= not-after (nth parts 2)))
(is (= subject (string/join " " (subvec parts 3))))))
(deftest test-write-cert-to-inventory
(testing "Certs can be written to an inventory file."
(let [first-cert (utils/pem->cert cacert)
second-cert (utils/pem->cert (path-to-cert signeddir "localhost"))
inventory-file (str (ks/temp-file))]
(write-cert-to-inventory! first-cert inventory-file)
(write-cert-to-inventory! second-cert inventory-file)
(testing "The format of a cert in the inventory matches the existing
format used by the ruby puppet code."
(let [inventory (slurp inventory-file)
entries (string/split inventory #"\n")]
(is (= (count entries) 2))
(verify-inventory-entry!
(first entries)
"0x0001"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=Puppet CA: localhost")
(verify-inventory-entry!
(second entries)
"0x0002"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=localhost"))))))
(deftest allow-duplicate-certs-test
(let [settings (assoc (testutils/ca-sandbox! cadir) :autosign false)]
(testing "when false"
(let [settings (assoc settings :allow-duplicate-certs false)]
(testing "throws exception if CSR already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "test-agent" (csr-stream "test-agent") settings))))
(testing "throws exception if certificate already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "localhost already has a signed certificate; ignoring certificate request"}
(process-csr-submission! "localhost"
(io/input-stream (test-pem-file "localhost-csr.pem"))
settings)))
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "revoked-agent already has a revoked certificate; ignoring certificate request"}
(process-csr-submission! "revoked-agent"
(io/input-stream (test-pem-file "revoked-agent-csr.pem"))
settings))))))
(testing "when true"
(let [settings (assoc settings :allow-duplicate-certs true)]
(testing "new CSR overwrites existing one"
(let [csr-path (path-to-cert-request (:csrdir settings) "test-agent")
csr (ByteArrayInputStream. (.getBytes (slurp csr-path)))]
(spit csr-path "should be overwritten")
(logutils/with-test-logging
(process-csr-submission! "test-agent" csr settings)
(is (logged? #"test-agent already has a requested certificate; new certificate will overwrite it" :info))
(is (not= "should be overwritten" (slurp csr-path))
"Existing CSR was not overwritten"))))
(testing "new certificate overwrites existing one"
(let [settings (assoc settings :autosign true)
cert-path (path-to-cert (:signeddir settings) "localhost")
old-cert (slurp cert-path)
csr (io/input-stream (test-pem-file "localhost-csr.pem"))]
(logutils/with-test-logging
(process-csr-submission! "localhost" csr settings)
(is (logged? #"localhost already has a signed certificate; new certificate will overwrite it" :info))
(is (not= old-cert (slurp cert-path)) "Existing certificate was not overwritten"))))))))
(deftest process-csr-submission!-test
(let [settings (testutils/ca-sandbox! cadir)]
(testing "CSR validation policies"
(testing "when autosign is false"
(let [settings (assoc settings :autosign false)]
(testing "subject policies are checked"
(doseq [[policy subject csr-file exception]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["invalid characters in name" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["wildcard in name" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? exception (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "extension & key policies are not checked"
(doseq [[policy subject csr-file]
[["subject alt name extension" "hostwithaltnames" "hostwithaltnames.pem"]
["unknown extension" "meow" "meow-bad-extension.pem"]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(process-csr-submission! subject csr settings)
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "when autosign is true, all policies are checked, and"
(let [settings (assoc settings :autosign true)]
(testing "CSR will not be saved when"
(doseq [[policy subject csr-file expected]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["subject contains invalid characters" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["subject contains wildcard character" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "CSR will be saved when"
(doseq [[policy subject csr-file expected]
[["subject alt name extension exists" "hostwithaltnames" "hostwithaltnames.pem"
{:type :disallowed-extension
:message (str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request.")}]
["unknown extension exists" "meow" "meow-bad-extension.pem"
{:type :disallowed-extension
:message "Found extensions that are not permitted: 1.9.9.9.9.9.9"}]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"
{:type :invalid-signature
:message "CSR contains a public key that does not correspond to the signing key"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "order of validations"
(testing "duplicates checked before subject policies"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-with-mismatched-name (csr-stream "test-agent")]
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "not-test-agent" csr-with-mismatched-name settings)))))
(testing "subject policies checked before extension & key policies"
(let [csr-with-disallowed-alt-names (io/input-stream (test-pem-file "hostwithaltnames.pem"))]
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}
(process-csr-submission! "foo" csr-with-disallowed-alt-names settings)))))))))
(deftest cert-signing-extension-test
(let [issuer-keys (utils/generate-key-pair 512)
issuer-pub (utils/get-public-key issuer-keys)
subject-keys (utils/generate-key-pair 512)
subject-pub (utils/get-public-key subject-keys)
subject "subject"
subject-dn (utils/cn subject)]
(testing "basic extensions are created for an agent"
(let [csr (utils/generate-certificate-request subject-keys subject-dn)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "2.5.29.35"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "2.5.29.19"
:critical true
:value {:is-ca false}}
{:oid "2.5.29.37"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "2.5.29.15"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "2.5.29.14"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "basic extensions are created for a master"
(let [settings (assoc (testutils/master-settings confdir)
:csr-attributes "doesntexist")
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "2.5.29.35"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "2.5.29.19"
:critical true
:value {:is-ca false}}
{:oid "2.5.29.37"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "2.5.29.15"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "2.5.29.14"
:critical false
:value subject-pub}
{:oid utils/subject-alt-name-oid
:critical false
:value {:dns-name ["puppet" "subject"]}}]]
(is (= (set exts) (set exts-expected)))))
(testing "additional extensions are created for a master"
(let [dns-alt-names "onefish,twofish"
settings (-> (testutils/master-settings confdir)
(assoc :dns-alt-names dns-alt-names)
(assoc :csr-attributes (csr-attributes-file "csr_attributes.yaml")))
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [
{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "2.5.29.35"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "2.5.29.19"
:critical true
:value {:is-ca false}}
{:oid "2.5.29.37"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "2.5.29.15"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "2.5.29.14"
:critical false
:value subject-pub}
{:oid "2.5.29.17"
:critical false
:value {:dns-name ["subject"
"onefish"
"twofish"]}}
;; These extensions come form csr_attributes.yaml
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "ED803750-E3C7-44F5-BB08-41A04433FE2E"}
{:oid "1.3.6.1.4.1.34380.1.1.1.4"
:critical false
:value "I am undefined but still work"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "thisisanid"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "my_ami_image"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "342thbjkt82094y0uthhor289jnqthpc2290"}
{:oid "1.3.6.1.4.1.34380.1.1.5" :critical false
:value "center"}
{:oid "1.3.6.1.4.1.34380.1.1.6" :critical false
:value "product"}
{:oid "1.3.6.1.4.1.34380.1.1.7" :critical false
:value "project"}
{:oid "1.3.6.1.4.1.34380.1.1.8" :critical false
:value "application"}
{:oid "1.3.6.1.4.1.34380.1.1.9" :critical false
:value "service"}
{:oid "1.3.6.1.4.1.34380.1.1.10" :critical false
:value "employee"}
{:oid "1.3.6.1.4.1.34380.1.1.11" :critical false
:value "created"}
{:oid "1.3.6.1.4.1.34380.1.1.12" :critical false
:value "environment"}
{:oid "1.3.6.1.4.1.34380.1.1.13" :critical false
:value "role"}
{:oid "1.3.6.1.4.1.34380.1.1.14" :critical false
:value "version"}
{:oid "1.3.6.1.4.1.34380.1.1.15" :critical false
:value "deparment"}
{:oid "1.3.6.1.4.1.34380.1.1.16" :critical false
:value "cluster"}
{:oid "1.3.6.1.4.1.34380.1.1.17" :critical false
:value "provisioner"}]]
(is (= (set exts) (set exts-expected)))))
(testing "A non-puppet OID read from a CSR attributes file is rejected"
(let [config (assoc (testutils/master-settings confdir)
:csr-attributes
(csr-attributes-file "insecure_csr_attributes.yaml"))]
(is (thrown-with-slingshot?
{:type :disallowed-extension
:message "Found extensions that are not permitted: 1.2.3.4"}
(create-master-extensions subject subject-pub issuer-pub config)))))
(testing "invalid DNS alt names are rejected"
(let [dns-alt-names "*.wildcard"]
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: *.wildcard"}
(create-master-extensions subject subject-pub issuer-pub
(assoc (testutils/master-settings confdir)
:dns-alt-names dns-alt-names))))))
(testing "basic extensions are created for a CA"
(let [serial 42
exts (create-ca-extensions subject-dn
serial
subject-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "2.5.29.35"
:critical false
:value {:issuer-dn (str "CN=" subject)
:public-key nil
:serial-number (biginteger serial)}}
{:oid "2.5.29.19"
:critical true
:value {:is-ca true}}
{:oid "2.5.29.15"
:critical true
:value #{:crl-sign :key-cert-sign}}
{:oid "2.5.29.14"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "trusted fact extensions are properly unfiltered"
(let [csr-exts [(utils/puppet-node-image-name "imagename" false)
(utils/puppet-node-preshared-key "key" false)
(utils/puppet-node-instance-id "instance" false)
(utils/puppet-node-uid "UUUU-IIIII-DDD" false)]
csr (utils/generate-certificate-request
subject-keys subject-dn csr-exts)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "2.5.29.35"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "2.5.29.19"
:critical true
:value {:is-ca false}}
{:oid "2.5.29.37"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "2.5.29.15"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "2.5.29.14"
:critical false
:value subject-pub}
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "UUUU-IIIII-DDD"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "instance"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "imagename"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "key"}]]
(is (= (set exts) (set exts-expected))
"The puppet trusted facts extensions were not added by create-agent-extensions")))))
(deftest netscape-comment-value-test
(testing "Netscape comment constant has expected value"
(is (= "Puppet Server Internal Certificate" netscape-comment-value))))
(deftest validate-subject!-test
(testing "an exception is thrown when the hostnames don't match"
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"test-agent\" does not match requested key \"not-test-agent\""}
(validate-subject!
"not-test-agent" "test-agent"))))
(testing "an exception is thrown if the subject name contains a capital letter"
(is (thrown-with-slingshot?
{:type :invalid-subject-name
:message "Certificate names must be lower case."}
(validate-subject! "Host-With-Capital-Letters"
"Host-With-Capital-Letters")))))
(deftest validate-dns-alt-names!-test
(testing "Only DNS alt names are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Only DNS names are allowed in the Subject Alternative Names extension"}
(validate-dns-alt-names! {:oid "2.5.29.17"
:critical false
:value {:ip-address ["12.34.5.6"]}}))))
(testing "No DNS wildcards are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: foo*bar"}
(validate-dns-alt-names! {:oid "2.5.29.17"
:critical false
:value {:dns-name ["ahostname" "foo*bar"]}})))))
(deftest default-master-dns-alt-names
(testing "Master certificate has default DNS alt names if none are specified"
(let [settings (assoc (testutils/master-settings confdir)
:dns-alt-names "")
pubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
capubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
alt-names (-> (create-master-extensions "master" pubkey capubkey settings)
(utils/get-extension-value utils/subject-alt-name-oid)
(:dns-name))]
(is (= #{"puppet" "master"} (set alt-names))))))
|
73639
|
(ns puppetlabs.puppetserver.certificate-authority-test
(:import (java.io StringReader ByteArrayInputStream ByteArrayOutputStream)
(java.security InvalidParameterException))
(:require [puppetlabs.puppetserver.certificate-authority :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.kitchensink.core :as ks]
[slingshot.slingshot :as sling]
[schema.test :as schema-test]
[clojure.test :refer :all]
[clojure.java.io :as io]
[clojure.string :as string]
[clj-time.core :as time]
[clj-time.coerce :as time-coerce]
[me.raynes.fs :as fs]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Test Data
(def test-resources-dir "./dev-resources/puppetlabs/puppetserver/certificate_authority_test")
(def confdir (str test-resources-dir "/master/conf"))
(def ssldir (str confdir "/ssl"))
(def cadir (str ssldir "/ca"))
(def cacert (str cadir "/ca_crt.pem"))
(def cakey (str cadir "/ca_key.pem"))
(def capub (str cadir "/ca_pub.pem"))
(def cacrl (str cadir "/ca_crl.pem"))
(def csrdir (str cadir "/requests"))
(def signeddir (str cadir "/signed"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-confs-dir (str test-resources-dir "/autosign_confs"))
(def autosign-exes-dir (str test-resources-dir "/autosign_exes"))
(def csr-attributes-dir (str test-resources-dir "/csr_attributes"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn autosign-conf-file
[autosign-conf-file-name]
(str autosign-confs-dir "/" autosign-conf-file-name))
(defn autosign-exe-file
[autosign-exe-file-name]
(str autosign-exes-dir "/" autosign-exe-file-name))
(defn csr-attributes-file
[csr-attributes-file-name]
(str csr-attributes-dir "/" csr-attributes-file-name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(defn tmp-whitelist! [& lines]
(let [whitelist (ks/temp-file)]
(doseq [line lines]
(spit whitelist (str line "\n") :append true))
(str whitelist)))
(def empty-stream (ByteArrayInputStream. (.getBytes "")))
(defn csr-stream [subject]
(io/input-stream (path-to-cert-request csrdir subject)))
(defn write-to-stream [o]
(let [s (ByteArrayOutputStream.)]
(utils/obj->pem! o s)
(-> s .toByteArray ByteArrayInputStream.)))
(defn assert-autosign [whitelist subject]
(testing subject
(is (true? (autosign-csr? whitelist subject empty-stream [])))))
(defn assert-no-autosign [whitelist subject]
(testing subject
(is (false? (autosign-csr? whitelist subject empty-stream [])))))
(defmethod assert-expr 'thrown-with-slingshot? [msg form]
(let [expected (nth form 1)
body (nthnext form 2)]
`(sling/try+
~@body
(do-report {:type :fail :message ~msg :expected ~expected :actual nil})
(catch map? actual#
(do-report {:type (if (= actual# ~expected) :pass :fail)
:message ~msg
:expected ~expected
:actual actual#})
actual#))))
(defn contains-ext?
"Does the provided extension list contain an extensions with the given OID."
[ext-list oid]
(> (count (filter #(= oid (:oid %)) ext-list)) 0))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest get-certificate-test
(testing "returns CA certificate when subject is 'ca'"
(let [actual (get-certificate "ca" cacert signeddir)
expected (slurp cacert)]
(is (= expected actual))))
(testing "returns localhost certificate when subject is 'localhost'"
(let [localhost-cert (get-certificate "localhost" cacert signeddir)
expected (slurp (path-to-cert signeddir "localhost"))]
(is (= expected localhost-cert))))
(testing "returns nil when certificate not found for subject"
(is (nil? (get-certificate "not-there" cacert signeddir)))))
(deftest get-certificate-request-test
(testing "returns certificate request for subject"
(let [cert-req (get-certificate-request "test-agent" csrdir)
expected (slurp (path-to-cert-request csrdir "test-agent"))]
(is (= expected cert-req))))
(testing "returns nil when certificate request not found for subject"
(is (nil? (get-certificate-request "not-there" csrdir)))))
(deftest autosign-csr?-test
(testing "boolean values"
(is (true? (autosign-csr? true "unused" empty-stream [])))
(is (false? (autosign-csr? false "unused" empty-stream []))))
(testing "whitelist"
(testing "autosign is false when whitelist doesn't exist"
(is (false? (autosign-csr? "Foo/conf/autosign.conf" "doubleagent"
empty-stream []))))
(testing "exact certnames"
(doto (tmp-whitelist! "foo"
"UPPERCASE"
"this.THAT."
"bar1234"
"AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-autosign "foo")
(assert-autosign "UPPERCASE")
(assert-autosign "this.THAT.")
(assert-autosign "bar1234")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-no-autosign "Foo")
(assert-no-autosign "uppercase")
(assert-no-autosign "this-THAT-")))
(testing "domain-name globs"
(doto (tmp-whitelist! "*.red"
"*.black.local"
"*.UPPER.case")
(assert-autosign "red")
(assert-autosign ".red")
(assert-autosign "green.red")
(assert-autosign "blue.1.red")
(assert-no-autosign "red.white")
(assert-autosign "black.local")
(assert-autosign ".black.local")
(assert-autosign "blue.black.local")
(assert-autosign "2.three.black.local")
(assert-no-autosign "red.local")
(assert-no-autosign "black.local.white")
(assert-autosign "one.0.upper.case")
(assert-autosign "two.upPEr.case")
(assert-autosign "one-two-three.red")))
(testing "allow all with '*'"
(doto (tmp-whitelist! "*")
(assert-autosign "foo")
(assert-autosign "BAR")
(assert-autosign "baz-buz.")
(assert-autosign "0.qux.1.xuq")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")))
(testing "ignores comments and blank lines"
(doto (tmp-whitelist! "#foo"
" "
"bar"
""
"# *.baz"
"*.qux")
(assert-no-autosign "foo")
(assert-no-autosign " ")
(assert-autosign "bar")
(assert-no-autosign "foo.baz")
(assert-autosign "bar.qux")))
(testing "invalid lines logged and ignored"
(doseq [invalid-line ["bar#bar"
" #bar"
"bar "
" bar"]]
(let [whitelist (tmp-whitelist! "foo"
invalid-line
"qux")]
(assert-autosign whitelist "foo")
(logutils/with-log-output logs
(assert-no-autosign whitelist invalid-line)
(is (logutils/logs-matching
(re-pattern (format "Invalid pattern '%s' found in %s"
invalid-line whitelist))
@logs))
(assert-autosign whitelist "qux")))))
(testing "sample file that covers everything"
(logutils/with-test-logging
(doto (autosign-conf-file "autosign-whitelist.conf")
(assert-no-autosign "aaa")
(assert-autosign "bbb123")
(assert-autosign "one_2.red")
(assert-autosign "1.blacK.6")
(assert-no-autosign "black.white")
(assert-no-autosign "coffee")
(assert-no-autosign "coffee#tea")
(assert-autosign "qux"))))))
(deftest autosign-csr?-ruby-exe-test
(let [executable (autosign-exe-file "ruby-autosign-executable")
csr-fn #(csr-stream "test-agent")
ruby-load-path ["ruby/puppet/lib" "ruby/facter/lib" "ruby/hiera/lib"]]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "Ruby load path is configured and contains Puppet"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"Ruby load path configured properly"))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"subject: test-agent"))
(is (logged? #"CSR for: test-agent"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)))
(is (false? (autosign-csr? executable "foo" (csr-fn) ruby-load-path)))))))
(deftest autosign-csr?-bash-exe-test
(let [executable (autosign-exe-file "bash-autosign-executable")
csr-fn #(csr-stream "test-agent")]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"subject: test-agent"))
(is (logged? #"-----BEGIN CERTIFICATE REQUEST-----"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) [])))
(is (false? (autosign-csr? executable "foo" (csr-fn) [])))))))
(deftest save-certificate-request!-test
(testing "requests are saved to disk"
(let [csrdir (:csrdir (testutils/ca-sandbox! cadir))
csr (utils/pem->csr (path-to-cert-request csrdir "test-agent"))
path (path-to-cert-request csrdir "foo")]
(is (false? (fs/exists? path)))
(save-certificate-request! "foo" csr csrdir)
(is (true? (fs/exists? path)))
(is (= (get-certificate-request csrdir "foo")
(get-certificate-request csrdir "test-agent"))))))
(deftest autosign-certificate-request!-test
(let [now (time/epoch)
two-years (* 60 60 24 365 2)
settings (-> (testutils/ca-sandbox! cadir)
(assoc :ca-ttl two-years))
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
expected-cert-path (path-to-cert (:signeddir settings) "test-agent")]
;; Fix the value of "now" so we can reliably test the dates
(time/do-at now
(autosign-certificate-request! "test-agent" csr settings))
(testing "requests are autosigned and saved to disk"
(is (fs/exists? expected-cert-path)))
(let [cert (utils/pem->cert expected-cert-path)]
(testing "The subject name on the agent's cert"
(testutils/assert-subject cert "CN=test-agent"))
(testing "The cert is issued by the name on the CA's cert"
(testutils/assert-issuer cert "CN=Puppet CA: localhost"))
(testing "certificate has not-before/not-after dates based on $ca-ttl"
(let [not-before (time-coerce/from-date (.getNotBefore cert))
not-after (time-coerce/from-date (.getNotAfter cert))]
(testing "not-before is 1 day before now"
(is (= (time/minus now (time/days 1)) not-before)))
(testing "not-after is 2 years from now"
(is (= (time/plus now (time/years 2)) not-after))))))))
(deftest autosign-without-capub
(testing "The CA public key file is not necessary to autosign"
(let [settings (testutils/ca-sandbox! cadir)
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
cert-path (path-to-cert (:signeddir settings) "test-agent")]
(fs/delete (:capub settings))
(autosign-certificate-request! "test-agent" csr settings)
(is (true? (fs/exists? cert-path)))
(let [cert (utils/pem->cert cert-path)
capub (-> (:cacert settings)
(utils/pem->cert)
(.getPublicKey))]
(is (nil? (.verify cert capub)))))))
(deftest revoke-without-capub
(testing "The CA public key file is not necessary to revoke"
(let [settings (testutils/ca-sandbox! cadir)
cert (-> (:signeddir settings)
(path-to-cert "localhost")
(utils/pem->cert))
revoked? (fn [cert]
(-> (:cacrl settings)
(utils/pem->crl)
(utils/revoked? cert)))]
(fs/delete (:capub settings))
(is (false? (revoked? cert)))
(revoke-existing-cert! settings "localhost")
(is (true? (revoked? cert))))))
(deftest get-certificate-revocation-list-test
(testing "`get-certificate-revocation-list` returns a valid CRL file."
(let [crl (-> (get-certificate-revocation-list cacrl)
StringReader.
utils/pem->crl)]
(testutils/assert-issuer crl "CN=Puppet CA: localhost"))))
(deftest initialize!-test
(let [settings (testutils/ca-settings (ks/temp-dir))]
(initialize! settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->cadir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "cacrl"
(let [crl (-> settings :cacrl utils/pem->crl)]
(testutils/assert-issuer crl "CN=test ca")
(testing "has CRLNumber and AuthorityKeyIdentifier extensions"
(is (not (nil? (utils/get-extension-value crl utils/crl-number-oid))))
(is (not (nil? (utils/get-extension-value crl utils/authority-key-identifier-oid)))))))
(testing "cacert"
(let [cert (-> settings :cacert utils/pem->cert)]
(is (utils/certificate? cert))
(testutils/assert-subject cert "CN=test ca")
(testutils/assert-issuer cert "CN=test ca")
(testing "has at least one expected extension - key usage"
(let [key-usage (utils/get-extension-value cert "172.16.58.3")]
(is (= #{:key-cert-sign :crl-sign} key-usage))))))
(testing "cakey"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "capub"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "cert-inventory"
(is (fs/exists? (:cert-inventory settings))))
(testing "serial"
(is (fs/exists? (:serial settings))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->cadir-paths settings)
(dissoc :csrdir :signeddir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize! settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))))
(deftest initialize!-test-with-keylength-in-settings
(let [settings (assoc (testutils/ca-settings (ks/temp-dir)) :keylength 768)]
(initialize! settings)
(testing "cakey with keylength"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "capub with keylength"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest ca-fail-fast-test
(testing "Directories not required but are created if absent"
(doseq [dir [:signeddir :csrdir]]
(testing dir
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete-dir (get settings dir))
(is (nil? (initialize! settings)))
(is (true? (fs/exists? (get settings dir))))))))
(testing "CA public key not required"
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete (:capub settings))
(is (nil? (initialize! settings)))))
(testing "Exception is thrown when required file is missing"
(doseq [file required-ca-files]
(testing file
(let [settings (testutils/ca-sandbox! cadir)
path (get settings file)]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize! settings))))))))
(deftest retrieve-ca-cert!-test
(testing "CA file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacert (:cacert ca-settings)
localcacert (:localcacert settings)
cacert-text (slurp cacert)]
(testing "Copied cacert to localcacert when localcacert not present"
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) cacert-text)
(str "Unexpected content for localcacert: " localcacert)))
(testing "Doesn't copy cacert over localcacert when different localcacert present"
(let [localcacert-contents "12345"]
(spit (:localcacert settings) localcacert-contents)
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) localcacert-contents)
(str "Unexpected content for localcacert: " localcacert))))
(testing "Throws exception if no localcacert and no cacert to copy"
(fs/delete localcacert)
(let [copy (fs/copy cacert (ks/temp-file))]
(fs/delete cacert)
(is (thrown? IllegalStateException
(retrieve-ca-cert! cacert localcacert))
"No exception thrown even though no file existed for copying")
(fs/copy copy cacert))))))
(deftest retrieve-ca-crl!-test
(testing "CRL file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacrl (:cacrl ca-settings)
hostcrl (:hostcrl settings)
cacrl-text (slurp cacrl)]
(testing "Copied cacrl to hostcrl when hostcrl not present"
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing "Copied cacrl to hostcrl when different hostcrl present"
(spit (:hostcrl settings) "12345")
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing (str "Doesn't throw exception or create dummy file if no "
"hostcrl and no cacrl to copy")
(fs/delete hostcrl)
(let [copy (fs/copy cacrl (ks/temp-file))]
(fs/delete cacrl)
(is (not (fs/exists? hostcrl))
"hostcrl file present even though no file existed for copying")
(fs/copy copy cacrl))))))
(deftest initialize-master-ssl!-test
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir "master")
(assoc :dns-alt-names "onefish,twofish"))
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(retrieve-ca-crl! (:cacrl ca-settings) (:hostcrl settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->ssldir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "hostcert"
(let [hostcert (-> settings :hostcert utils/pem->cert)]
(is (utils/certificate? hostcert))
(testutils/assert-subject hostcert "CN=master")
(testutils/assert-issuer hostcert "CN=Puppet CA: localhost")
(testing "has alt names extension"
(let [dns-alt-names (utils/get-subject-dns-alt-names hostcert)]
(is (= #{"master" "onefish" "twofish"} (set dns-alt-names))
"The Subject Alternative Names extension should contain the
master's actual hostname and the hostnames in $dns-alt-names")))
(testing "is also saved in the CA's $signeddir"
(let [signedpath (path-to-cert (:signeddir ca-settings) "master")]
(is (fs/exists? signedpath))
(is (= hostcert (utils/pem->cert signedpath)))))))
(testing "hostprivkey"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "hostpubkey"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->ssldir-paths settings)
(dissoc :certdir :requestdir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize-master-ssl! settings "master" ca-settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))
(testing "Throws an exception if required file is missing"
(doseq [file required-master-files]
(testing file
(let [path (get settings file)
copy (fs/copy path (ks/temp-file))]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize-master-ssl! settings "master" ca-settings)))
(fs/copy copy path)))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest parse-serial-number-test
(is (= (parse-serial-number "0001") 1))
(is (= (parse-serial-number "0010") 16))
(is (= (parse-serial-number "002A") 42)))
(deftest format-serial-number-test
(is (= (format-serial-number 1) "0001"))
(is (= (format-serial-number 16) "0010"))
(is (= (format-serial-number 42) "002A")))
(deftest next-serial-number!-test
(let [serial-file (str (ks/temp-file))]
(testing "Serial file is initialized to 1"
(initialize-serial-file! serial-file)
(is (= (next-serial-number! serial-file) 1)))
(testing "The serial number file should contain the next serial number"
(is (= "0002" (slurp serial-file))))
(testing "subsequent calls produce increasing serial numbers"
(is (= (next-serial-number! serial-file) 2))
(is (= "0003" (slurp serial-file)))
(is (= (next-serial-number! serial-file) 3))
(is (= "0004" (slurp serial-file))))))
;; If the locking is deleted from `next-serial-number!`, this test will hang,
;; which is not as nice as simply failing ...
;; This seems to happen due to a deadlock caused by concurrently reading and
;; writing to the same file (via `slurp` and `spit`)
(deftest next-serial-number-threadsafety
(testing "next-serial-number! is thread-safe and
never returns a duplicate serial number"
(let [serial-file (doto (str (ks/temp-file)) (spit "0001"))
serials (atom [])
;; spin off a new thread for each CPU
promises (for [_ (range (ks/num-cpus))]
(let [p (promise)]
(future
;; get a bunch of serial numbers and keep track of them
(dotimes [_ 100]
(let [serial-number (next-serial-number! serial-file)]
(swap! serials conj serial-number)))
(deliver p 'done))
p))
contains-duplicates? #(not= (count %) (count (distinct %)))]
; wait on all the threads to finish
(doseq [p promises] (deref p))
(is (false? (contains-duplicates? @serials))
"Got a duplicate serial number"))))
(defn verify-inventory-entry!
[inventory-entry serial-number not-before not-after subject]
(let [parts (string/split inventory-entry #" ")]
(is (= serial-number (first parts)))
(is (= not-before (second parts)))
(is (= not-after (nth parts 2)))
(is (= subject (string/join " " (subvec parts 3))))))
(deftest test-write-cert-to-inventory
(testing "Certs can be written to an inventory file."
(let [first-cert (utils/pem->cert cacert)
second-cert (utils/pem->cert (path-to-cert signeddir "localhost"))
inventory-file (str (ks/temp-file))]
(write-cert-to-inventory! first-cert inventory-file)
(write-cert-to-inventory! second-cert inventory-file)
(testing "The format of a cert in the inventory matches the existing
format used by the ruby puppet code."
(let [inventory (slurp inventory-file)
entries (string/split inventory #"\n")]
(is (= (count entries) 2))
(verify-inventory-entry!
(first entries)
"0x0001"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=Puppet CA: localhost")
(verify-inventory-entry!
(second entries)
"0x0002"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=localhost"))))))
(deftest allow-duplicate-certs-test
(let [settings (assoc (testutils/ca-sandbox! cadir) :autosign false)]
(testing "when false"
(let [settings (assoc settings :allow-duplicate-certs false)]
(testing "throws exception if CSR already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "test-agent" (csr-stream "test-agent") settings))))
(testing "throws exception if certificate already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "localhost already has a signed certificate; ignoring certificate request"}
(process-csr-submission! "localhost"
(io/input-stream (test-pem-file "localhost-csr.pem"))
settings)))
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "revoked-agent already has a revoked certificate; ignoring certificate request"}
(process-csr-submission! "revoked-agent"
(io/input-stream (test-pem-file "revoked-agent-csr.pem"))
settings))))))
(testing "when true"
(let [settings (assoc settings :allow-duplicate-certs true)]
(testing "new CSR overwrites existing one"
(let [csr-path (path-to-cert-request (:csrdir settings) "test-agent")
csr (ByteArrayInputStream. (.getBytes (slurp csr-path)))]
(spit csr-path "should be overwritten")
(logutils/with-test-logging
(process-csr-submission! "test-agent" csr settings)
(is (logged? #"test-agent already has a requested certificate; new certificate will overwrite it" :info))
(is (not= "should be overwritten" (slurp csr-path))
"Existing CSR was not overwritten"))))
(testing "new certificate overwrites existing one"
(let [settings (assoc settings :autosign true)
cert-path (path-to-cert (:signeddir settings) "localhost")
old-cert (slurp cert-path)
csr (io/input-stream (test-pem-file "localhost-csr.pem"))]
(logutils/with-test-logging
(process-csr-submission! "localhost" csr settings)
(is (logged? #"localhost already has a signed certificate; new certificate will overwrite it" :info))
(is (not= old-cert (slurp cert-path)) "Existing certificate was not overwritten"))))))))
(deftest process-csr-submission!-test
(let [settings (testutils/ca-sandbox! cadir)]
(testing "CSR validation policies"
(testing "when autosign is false"
(let [settings (assoc settings :autosign false)]
(testing "subject policies are checked"
(doseq [[policy subject csr-file exception]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["invalid characters in name" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["wildcard in name" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? exception (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "extension & key policies are not checked"
(doseq [[policy subject csr-file]
[["subject alt name extension" "hostwithaltnames" "hostwithaltnames.pem"]
["unknown extension" "meow" "meow-bad-extension.pem"]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(process-csr-submission! subject csr settings)
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "when autosign is true, all policies are checked, and"
(let [settings (assoc settings :autosign true)]
(testing "CSR will not be saved when"
(doseq [[policy subject csr-file expected]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["subject contains invalid characters" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["subject contains wildcard character" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "CSR will be saved when"
(doseq [[policy subject csr-file expected]
[["subject alt name extension exists" "hostwithaltnames" "hostwithaltnames.pem"
{:type :disallowed-extension
:message (str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request.")}]
["unknown extension exists" "meow" "meow-bad-extension.pem"
{:type :disallowed-extension
:message "Found extensions that are not permitted: 172.16.31.10.9.9.9"}]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"
{:type :invalid-signature
:message "CSR contains a public key that does not correspond to the signing key"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "order of validations"
(testing "duplicates checked before subject policies"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-with-mismatched-name (csr-stream "test-agent")]
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "not-test-agent" csr-with-mismatched-name settings)))))
(testing "subject policies checked before extension & key policies"
(let [csr-with-disallowed-alt-names (io/input-stream (test-pem-file "hostwithaltnames.pem"))]
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}
(process-csr-submission! "foo" csr-with-disallowed-alt-names settings)))))))))
(deftest cert-signing-extension-test
(let [issuer-keys (utils/generate-key-pair 512)
issuer-pub (utils/get-public-key issuer-keys)
subject-keys (utils/generate-key-pair 512)
subject-pub (utils/get-public-key subject-keys)
subject "subject"
subject-dn (utils/cn subject)]
(testing "basic extensions are created for an agent"
(let [csr (utils/generate-certificate-request subject-keys subject-dn)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "172.16.58.3"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "172.16.17.32"
:critical true
:value {:is-ca false}}
{:oid "192.168.127.12"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "172.16.58.3"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "172.16.17.32"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "basic extensions are created for a master"
(let [settings (assoc (testutils/master-settings confdir)
:csr-attributes "doesntexist")
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "172.16.58.3"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "172.16.17.32"
:critical true
:value {:is-ca false}}
{:oid "192.168.127.12"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "172.16.58.3"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "172.16.17.32"
:critical false
:value subject-pub}
{:oid utils/subject-alt-name-oid
:critical false
:value {:dns-name ["puppet" "subject"]}}]]
(is (= (set exts) (set exts-expected)))))
(testing "additional extensions are created for a master"
(let [dns-alt-names "onefish,twofish"
settings (-> (testutils/master-settings confdir)
(assoc :dns-alt-names dns-alt-names)
(assoc :csr-attributes (csr-attributes-file "csr_attributes.yaml")))
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [
{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "172.16.58.3"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "172.16.17.32"
:critical true
:value {:is-ca false}}
{:oid "192.168.127.12"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "172.16.58.3"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "172.16.17.32"
:critical false
:value subject-pub}
{:oid "192.168.3.11"
:critical false
:value {:dns-name ["subject"
"onefish"
"twofish"]}}
;; These extensions come form csr_attributes.yaml
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "ED803750-E3C7-44F5-BB08-41A04433FE2E"}
{:oid "1.3.6.1.4.1.34380.1.1.1.4"
:critical false
:value "I am undefined but still work"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "thisisanid"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "my_ami_image"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "342thbjkt82094y0uthhor289jnqthpc2290"}
{:oid "1.3.6.1.4.1.34380.1.1.5" :critical false
:value "center"}
{:oid "1.3.6.1.4.1.34380.1.1.6" :critical false
:value "product"}
{:oid "1.3.6.1.4.1.34380.1.1.7" :critical false
:value "project"}
{:oid "1.3.6.1.4.1.34380.1.1.8" :critical false
:value "application"}
{:oid "1.3.6.1.4.1.34380.1.1.9" :critical false
:value "service"}
{:oid "1.3.6.1.4.1.34380.1.1.10" :critical false
:value "employee"}
{:oid "1.3.6.1.4.1.34380.1.1.11" :critical false
:value "created"}
{:oid "1.3.6.1.4.1.34380.1.1.12" :critical false
:value "environment"}
{:oid "1.3.6.1.4.1.34380.1.1.13" :critical false
:value "role"}
{:oid "1.3.6.1.4.1.34380.1.1.14" :critical false
:value "version"}
{:oid "1.3.6.1.4.1.34380.1.1.15" :critical false
:value "deparment"}
{:oid "1.3.6.1.4.1.34380.1.1.16" :critical false
:value "cluster"}
{:oid "1.3.6.1.4.1.34380.1.1.17" :critical false
:value "provisioner"}]]
(is (= (set exts) (set exts-expected)))))
(testing "A non-puppet OID read from a CSR attributes file is rejected"
(let [config (assoc (testutils/master-settings confdir)
:csr-attributes
(csr-attributes-file "insecure_csr_attributes.yaml"))]
(is (thrown-with-slingshot?
{:type :disallowed-extension
:message "Found extensions that are not permitted: 172.16.58.3"}
(create-master-extensions subject subject-pub issuer-pub config)))))
(testing "invalid DNS alt names are rejected"
(let [dns-alt-names "*.wildcard"]
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: *.wildcard"}
(create-master-extensions subject subject-pub issuer-pub
(assoc (testutils/master-settings confdir)
:dns-alt-names dns-alt-names))))))
(testing "basic extensions are created for a CA"
(let [serial 42
exts (create-ca-extensions subject-dn
serial
subject-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "172.16.58.3"
:critical false
:value {:issuer-dn (str "CN=" subject)
:public-key nil
:serial-number (biginteger serial)}}
{:oid "172.16.17.32"
:critical true
:value {:is-ca true}}
{:oid "172.16.58.3"
:critical true
:value #{:crl-sign :key-cert-sign}}
{:oid "172.16.17.32"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "trusted fact extensions are properly unfiltered"
(let [csr-exts [(utils/puppet-node-image-name "imagename" false)
(utils/puppet-node-preshared-key "key" false)
(utils/puppet-node-instance-id "instance" false)
(utils/puppet-node-uid "UUUU-IIIII-DDD" false)]
csr (utils/generate-certificate-request
subject-keys subject-dn csr-exts)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "172.16.58.3"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "172.16.17.32"
:critical true
:value {:is-ca false}}
{:oid "192.168.127.12"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "172.16.58.3"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "172.16.17.32"
:critical false
:value subject-pub}
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "UUUU-IIIII-DDD"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "instance"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "imagename"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "key"}]]
(is (= (set exts) (set exts-expected))
"The puppet trusted facts extensions were not added by create-agent-extensions")))))
(deftest netscape-comment-value-test
(testing "Netscape comment constant has expected value"
(is (= "Puppet Server Internal Certificate" netscape-comment-value))))
(deftest validate-subject!-test
(testing "an exception is thrown when the hostnames don't match"
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"test-agent\" does not match requested key \"not-test-agent\""}
(validate-subject!
"not-test-agent" "test-agent"))))
(testing "an exception is thrown if the subject name contains a capital letter"
(is (thrown-with-slingshot?
{:type :invalid-subject-name
:message "Certificate names must be lower case."}
(validate-subject! "Host-With-Capital-Letters"
"Host-With-Capital-Letters")))))
(deftest validate-dns-alt-names!-test
(testing "Only DNS alt names are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Only DNS names are allowed in the Subject Alternative Names extension"}
(validate-dns-alt-names! {:oid "192.168.3.11"
:critical false
:value {:ip-address ["172.16.17.32"]}}))))
(testing "No DNS wildcards are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: foo*bar"}
(validate-dns-alt-names! {:oid "192.168.3.11"
:critical false
:value {:dns-name ["ahostname" "foo*bar"]}})))))
(deftest default-master-dns-alt-names
(testing "Master certificate has default DNS alt names if none are specified"
(let [settings (assoc (testutils/master-settings confdir)
:dns-alt-names "")
pubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
capubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
alt-names (-> (create-master-extensions "master" pubkey capubkey settings)
(utils/get-extension-value utils/subject-alt-name-oid)
(:dns-name))]
(is (= #{"puppet" "master"} (set alt-names))))))
| true |
(ns puppetlabs.puppetserver.certificate-authority-test
(:import (java.io StringReader ByteArrayInputStream ByteArrayOutputStream)
(java.security InvalidParameterException))
(:require [puppetlabs.puppetserver.certificate-authority :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.kitchensink.core :as ks]
[slingshot.slingshot :as sling]
[schema.test :as schema-test]
[clojure.test :refer :all]
[clojure.java.io :as io]
[clojure.string :as string]
[clj-time.core :as time]
[clj-time.coerce :as time-coerce]
[me.raynes.fs :as fs]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Test Data
(def test-resources-dir "./dev-resources/puppetlabs/puppetserver/certificate_authority_test")
(def confdir (str test-resources-dir "/master/conf"))
(def ssldir (str confdir "/ssl"))
(def cadir (str ssldir "/ca"))
(def cacert (str cadir "/ca_crt.pem"))
(def cakey (str cadir "/ca_key.pem"))
(def capub (str cadir "/ca_pub.pem"))
(def cacrl (str cadir "/ca_crl.pem"))
(def csrdir (str cadir "/requests"))
(def signeddir (str cadir "/signed"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-confs-dir (str test-resources-dir "/autosign_confs"))
(def autosign-exes-dir (str test-resources-dir "/autosign_exes"))
(def csr-attributes-dir (str test-resources-dir "/csr_attributes"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn autosign-conf-file
[autosign-conf-file-name]
(str autosign-confs-dir "/" autosign-conf-file-name))
(defn autosign-exe-file
[autosign-exe-file-name]
(str autosign-exes-dir "/" autosign-exe-file-name))
(defn csr-attributes-file
[csr-attributes-file-name]
(str csr-attributes-dir "/" csr-attributes-file-name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(defn tmp-whitelist! [& lines]
(let [whitelist (ks/temp-file)]
(doseq [line lines]
(spit whitelist (str line "\n") :append true))
(str whitelist)))
(def empty-stream (ByteArrayInputStream. (.getBytes "")))
(defn csr-stream [subject]
(io/input-stream (path-to-cert-request csrdir subject)))
(defn write-to-stream [o]
(let [s (ByteArrayOutputStream.)]
(utils/obj->pem! o s)
(-> s .toByteArray ByteArrayInputStream.)))
(defn assert-autosign [whitelist subject]
(testing subject
(is (true? (autosign-csr? whitelist subject empty-stream [])))))
(defn assert-no-autosign [whitelist subject]
(testing subject
(is (false? (autosign-csr? whitelist subject empty-stream [])))))
(defmethod assert-expr 'thrown-with-slingshot? [msg form]
(let [expected (nth form 1)
body (nthnext form 2)]
`(sling/try+
~@body
(do-report {:type :fail :message ~msg :expected ~expected :actual nil})
(catch map? actual#
(do-report {:type (if (= actual# ~expected) :pass :fail)
:message ~msg
:expected ~expected
:actual actual#})
actual#))))
(defn contains-ext?
"Does the provided extension list contain an extensions with the given OID."
[ext-list oid]
(> (count (filter #(= oid (:oid %)) ext-list)) 0))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest get-certificate-test
(testing "returns CA certificate when subject is 'ca'"
(let [actual (get-certificate "ca" cacert signeddir)
expected (slurp cacert)]
(is (= expected actual))))
(testing "returns localhost certificate when subject is 'localhost'"
(let [localhost-cert (get-certificate "localhost" cacert signeddir)
expected (slurp (path-to-cert signeddir "localhost"))]
(is (= expected localhost-cert))))
(testing "returns nil when certificate not found for subject"
(is (nil? (get-certificate "not-there" cacert signeddir)))))
(deftest get-certificate-request-test
(testing "returns certificate request for subject"
(let [cert-req (get-certificate-request "test-agent" csrdir)
expected (slurp (path-to-cert-request csrdir "test-agent"))]
(is (= expected cert-req))))
(testing "returns nil when certificate request not found for subject"
(is (nil? (get-certificate-request "not-there" csrdir)))))
(deftest autosign-csr?-test
(testing "boolean values"
(is (true? (autosign-csr? true "unused" empty-stream [])))
(is (false? (autosign-csr? false "unused" empty-stream []))))
(testing "whitelist"
(testing "autosign is false when whitelist doesn't exist"
(is (false? (autosign-csr? "Foo/conf/autosign.conf" "doubleagent"
empty-stream []))))
(testing "exact certnames"
(doto (tmp-whitelist! "foo"
"UPPERCASE"
"this.THAT."
"bar1234"
"AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-autosign "foo")
(assert-autosign "UPPERCASE")
(assert-autosign "this.THAT.")
(assert-autosign "bar1234")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")
(assert-no-autosign "Foo")
(assert-no-autosign "uppercase")
(assert-no-autosign "this-THAT-")))
(testing "domain-name globs"
(doto (tmp-whitelist! "*.red"
"*.black.local"
"*.UPPER.case")
(assert-autosign "red")
(assert-autosign ".red")
(assert-autosign "green.red")
(assert-autosign "blue.1.red")
(assert-no-autosign "red.white")
(assert-autosign "black.local")
(assert-autosign ".black.local")
(assert-autosign "blue.black.local")
(assert-autosign "2.three.black.local")
(assert-no-autosign "red.local")
(assert-no-autosign "black.local.white")
(assert-autosign "one.0.upper.case")
(assert-autosign "two.upPEr.case")
(assert-autosign "one-two-three.red")))
(testing "allow all with '*'"
(doto (tmp-whitelist! "*")
(assert-autosign "foo")
(assert-autosign "BAR")
(assert-autosign "baz-buz.")
(assert-autosign "0.qux.1.xuq")
(assert-autosign "AB=foo,BC=bar,CD=rab,DE=oof,EF=1a2b3d")))
(testing "ignores comments and blank lines"
(doto (tmp-whitelist! "#foo"
" "
"bar"
""
"# *.baz"
"*.qux")
(assert-no-autosign "foo")
(assert-no-autosign " ")
(assert-autosign "bar")
(assert-no-autosign "foo.baz")
(assert-autosign "bar.qux")))
(testing "invalid lines logged and ignored"
(doseq [invalid-line ["bar#bar"
" #bar"
"bar "
" bar"]]
(let [whitelist (tmp-whitelist! "foo"
invalid-line
"qux")]
(assert-autosign whitelist "foo")
(logutils/with-log-output logs
(assert-no-autosign whitelist invalid-line)
(is (logutils/logs-matching
(re-pattern (format "Invalid pattern '%s' found in %s"
invalid-line whitelist))
@logs))
(assert-autosign whitelist "qux")))))
(testing "sample file that covers everything"
(logutils/with-test-logging
(doto (autosign-conf-file "autosign-whitelist.conf")
(assert-no-autosign "aaa")
(assert-autosign "bbb123")
(assert-autosign "one_2.red")
(assert-autosign "1.blacK.6")
(assert-no-autosign "black.white")
(assert-no-autosign "coffee")
(assert-no-autosign "coffee#tea")
(assert-autosign "qux"))))))
(deftest autosign-csr?-ruby-exe-test
(let [executable (autosign-exe-file "ruby-autosign-executable")
csr-fn #(csr-stream "test-agent")
ruby-load-path ["ruby/puppet/lib" "ruby/facter/lib" "ruby/hiera/lib"]]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "Ruby load path is configured and contains Puppet"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"Ruby load path configured properly"))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)
(is (logged? #"subject: test-agent"))
(is (logged? #"CSR for: test-agent"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) ruby-load-path)))
(is (false? (autosign-csr? executable "foo" (csr-fn) ruby-load-path)))))))
(deftest autosign-csr?-bash-exe-test
(let [executable (autosign-exe-file "bash-autosign-executable")
csr-fn #(csr-stream "test-agent")]
(testing "stdout and stderr are copied to master's log at debug level"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"print to stdout" :debug))
(is (logged? #"print to stderr" :debug))))
(testing "subject is passed as argument and CSR is provided on stdin"
(logutils/with-test-logging
(autosign-csr? executable "test-agent" (csr-fn) [])
(is (logged? #"subject: test-agent"))
(is (logged? #"-----BEGIN CERTIFICATE REQUEST-----"))))
(testing "only exit code 0 results in autosigning"
(logutils/with-test-logging
(is (true? (autosign-csr? executable "test-agent" (csr-fn) [])))
(is (false? (autosign-csr? executable "foo" (csr-fn) [])))))))
(deftest save-certificate-request!-test
(testing "requests are saved to disk"
(let [csrdir (:csrdir (testutils/ca-sandbox! cadir))
csr (utils/pem->csr (path-to-cert-request csrdir "test-agent"))
path (path-to-cert-request csrdir "foo")]
(is (false? (fs/exists? path)))
(save-certificate-request! "foo" csr csrdir)
(is (true? (fs/exists? path)))
(is (= (get-certificate-request csrdir "foo")
(get-certificate-request csrdir "test-agent"))))))
(deftest autosign-certificate-request!-test
(let [now (time/epoch)
two-years (* 60 60 24 365 2)
settings (-> (testutils/ca-sandbox! cadir)
(assoc :ca-ttl two-years))
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
expected-cert-path (path-to-cert (:signeddir settings) "test-agent")]
;; Fix the value of "now" so we can reliably test the dates
(time/do-at now
(autosign-certificate-request! "test-agent" csr settings))
(testing "requests are autosigned and saved to disk"
(is (fs/exists? expected-cert-path)))
(let [cert (utils/pem->cert expected-cert-path)]
(testing "The subject name on the agent's cert"
(testutils/assert-subject cert "CN=test-agent"))
(testing "The cert is issued by the name on the CA's cert"
(testutils/assert-issuer cert "CN=Puppet CA: localhost"))
(testing "certificate has not-before/not-after dates based on $ca-ttl"
(let [not-before (time-coerce/from-date (.getNotBefore cert))
not-after (time-coerce/from-date (.getNotAfter cert))]
(testing "not-before is 1 day before now"
(is (= (time/minus now (time/days 1)) not-before)))
(testing "not-after is 2 years from now"
(is (= (time/plus now (time/years 2)) not-after))))))))
(deftest autosign-without-capub
(testing "The CA public key file is not necessary to autosign"
(let [settings (testutils/ca-sandbox! cadir)
csr (-> (:csrdir settings)
(path-to-cert-request "test-agent")
(utils/pem->csr))
cert-path (path-to-cert (:signeddir settings) "test-agent")]
(fs/delete (:capub settings))
(autosign-certificate-request! "test-agent" csr settings)
(is (true? (fs/exists? cert-path)))
(let [cert (utils/pem->cert cert-path)
capub (-> (:cacert settings)
(utils/pem->cert)
(.getPublicKey))]
(is (nil? (.verify cert capub)))))))
(deftest revoke-without-capub
(testing "The CA public key file is not necessary to revoke"
(let [settings (testutils/ca-sandbox! cadir)
cert (-> (:signeddir settings)
(path-to-cert "localhost")
(utils/pem->cert))
revoked? (fn [cert]
(-> (:cacrl settings)
(utils/pem->crl)
(utils/revoked? cert)))]
(fs/delete (:capub settings))
(is (false? (revoked? cert)))
(revoke-existing-cert! settings "localhost")
(is (true? (revoked? cert))))))
(deftest get-certificate-revocation-list-test
(testing "`get-certificate-revocation-list` returns a valid CRL file."
(let [crl (-> (get-certificate-revocation-list cacrl)
StringReader.
utils/pem->crl)]
(testutils/assert-issuer crl "CN=Puppet CA: localhost"))))
(deftest initialize!-test
(let [settings (testutils/ca-settings (ks/temp-dir))]
(initialize! settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->cadir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "cacrl"
(let [crl (-> settings :cacrl utils/pem->crl)]
(testutils/assert-issuer crl "CN=test ca")
(testing "has CRLNumber and AuthorityKeyIdentifier extensions"
(is (not (nil? (utils/get-extension-value crl utils/crl-number-oid))))
(is (not (nil? (utils/get-extension-value crl utils/authority-key-identifier-oid)))))))
(testing "cacert"
(let [cert (-> settings :cacert utils/pem->cert)]
(is (utils/certificate? cert))
(testutils/assert-subject cert "CN=test ca")
(testutils/assert-issuer cert "CN=test ca")
(testing "has at least one expected extension - key usage"
(let [key-usage (utils/get-extension-value cert "PI:IP_ADDRESS:172.16.58.3END_PI")]
(is (= #{:key-cert-sign :crl-sign} key-usage))))))
(testing "cakey"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "capub"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "cert-inventory"
(is (fs/exists? (:cert-inventory settings))))
(testing "serial"
(is (fs/exists? (:serial settings))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->cadir-paths settings)
(dissoc :csrdir :signeddir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize! settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))))
(deftest initialize!-test-with-keylength-in-settings
(let [settings (assoc (testutils/ca-settings (ks/temp-dir)) :keylength 768)]
(initialize! settings)
(testing "cakey with keylength"
(let [key (-> settings :cakey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "capub with keylength"
(let [key (-> settings :capub utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest ca-fail-fast-test
(testing "Directories not required but are created if absent"
(doseq [dir [:signeddir :csrdir]]
(testing dir
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete-dir (get settings dir))
(is (nil? (initialize! settings)))
(is (true? (fs/exists? (get settings dir))))))))
(testing "CA public key not required"
(let [settings (testutils/ca-sandbox! cadir)]
(fs/delete (:capub settings))
(is (nil? (initialize! settings)))))
(testing "Exception is thrown when required file is missing"
(doseq [file required-ca-files]
(testing file
(let [settings (testutils/ca-sandbox! cadir)
path (get settings file)]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize! settings))))))))
(deftest retrieve-ca-cert!-test
(testing "CA file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacert (:cacert ca-settings)
localcacert (:localcacert settings)
cacert-text (slurp cacert)]
(testing "Copied cacert to localcacert when localcacert not present"
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) cacert-text)
(str "Unexpected content for localcacert: " localcacert)))
(testing "Doesn't copy cacert over localcacert when different localcacert present"
(let [localcacert-contents "12345"]
(spit (:localcacert settings) localcacert-contents)
(retrieve-ca-cert! cacert localcacert)
(is (= (slurp localcacert) localcacert-contents)
(str "Unexpected content for localcacert: " localcacert))))
(testing "Throws exception if no localcacert and no cacert to copy"
(fs/delete localcacert)
(let [copy (fs/copy cacert (ks/temp-file))]
(fs/delete cacert)
(is (thrown? IllegalStateException
(retrieve-ca-cert! cacert localcacert))
"No exception thrown even though no file existed for copying")
(fs/copy copy cacert))))))
(deftest retrieve-ca-crl!-test
(testing "CRL file copied when it doesn't already exist"
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))
cacrl (:cacrl ca-settings)
hostcrl (:hostcrl settings)
cacrl-text (slurp cacrl)]
(testing "Copied cacrl to hostcrl when hostcrl not present"
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing "Copied cacrl to hostcrl when different hostcrl present"
(spit (:hostcrl settings) "12345")
(retrieve-ca-crl! cacrl hostcrl)
(is (= (slurp hostcrl) cacrl-text)
(str "Unexpected content for hostcrl: " hostcrl)))
(testing (str "Doesn't throw exception or create dummy file if no "
"hostcrl and no cacrl to copy")
(fs/delete hostcrl)
(let [copy (fs/copy cacrl (ks/temp-file))]
(fs/delete cacrl)
(is (not (fs/exists? hostcrl))
"hostcrl file present even though no file existed for copying")
(fs/copy copy cacrl))))))
(deftest initialize-master-ssl!-test
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir "master")
(assoc :dns-alt-names "onefish,twofish"))
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(retrieve-ca-crl! (:cacrl ca-settings) (:hostcrl settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "Generated SSL file"
(doseq [file (vals (settings->ssldir-paths settings))]
(testing file
(is (fs/exists? file)))))
(testing "hostcert"
(let [hostcert (-> settings :hostcert utils/pem->cert)]
(is (utils/certificate? hostcert))
(testutils/assert-subject hostcert "CN=master")
(testutils/assert-issuer hostcert "CN=Puppet CA: localhost")
(testing "has alt names extension"
(let [dns-alt-names (utils/get-subject-dns-alt-names hostcert)]
(is (= #{"master" "onefish" "twofish"} (set dns-alt-names))
"The Subject Alternative Names extension should contain the
master's actual hostname and the hostnames in $dns-alt-names")))
(testing "is also saved in the CA's $signeddir"
(let [signedpath (path-to-cert (:signeddir ca-settings) "master")]
(is (fs/exists? signedpath))
(is (= hostcert (utils/pem->cert signedpath)))))))
(testing "hostprivkey"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 512 (utils/keylength key)))))
(testing "hostpubkey"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 512 (utils/keylength key)))))
(testing "Does not replace files if they all exist"
(let [files (-> (settings->ssldir-paths settings)
(dissoc :certdir :requestdir)
(vals))]
(doseq [f files] (spit f "testable string"))
(initialize-master-ssl! settings "master" ca-settings)
(doseq [f files] (is (= "testable string" (slurp f))
"File was replaced"))))
(testing "Throws an exception if required file is missing"
(doseq [file required-master-files]
(testing file
(let [path (get settings file)
copy (fs/copy path (ks/temp-file))]
(fs/delete path)
(is (thrown-with-msg?
IllegalStateException
(re-pattern (str "Missing:\n" path))
(initialize-master-ssl! settings "master" ca-settings)))
(fs/copy copy path)))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest initialize-master-ssl!-test-with-keylength-settings
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (-> (testutils/master-settings tmp-confdir)
(assoc :keylength 768))
ca-settings (assoc (testutils/ca-settings (str tmp-confdir "/ssl/ca")) :keylength 768)]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(initialize-master-ssl! settings "master" ca-settings)
(testing "hostprivkey should have correct keylength"
(let [key (-> settings :hostprivkey utils/pem->private-key)]
(is (utils/private-key? key))
(is (= 768 (utils/keylength key)))))
(testing "hostpubkey should have correct keylength"
(let [key (-> settings :hostpubkey utils/pem->public-key)]
(is (utils/public-key? key))
(is (= 768 (utils/keylength key)))))))
(deftest initialize-master-ssl!-test-with-incorrect-keylength
(let [tmp-confdir (fs/copy-dir confdir (ks/temp-dir))
settings (testutils/master-settings tmp-confdir)
ca-settings (testutils/ca-settings (str tmp-confdir "/ssl/ca"))]
(retrieve-ca-cert! (:cacert ca-settings) (:localcacert settings))
(testing "should throw an error message with too short keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be at least 512 bits long.*"
(initialize-master-ssl! (assoc settings :keylength 128) "master" ca-settings))))
(testing "should throw an error message with too large keylength"
(is (thrown-with-msg?
InvalidParameterException
#".*RSA keys must be no longer than 16384 bits.*"
(initialize-master-ssl! (assoc settings :keylength 32768) "master" ca-settings))))))
(deftest parse-serial-number-test
(is (= (parse-serial-number "0001") 1))
(is (= (parse-serial-number "0010") 16))
(is (= (parse-serial-number "002A") 42)))
(deftest format-serial-number-test
(is (= (format-serial-number 1) "0001"))
(is (= (format-serial-number 16) "0010"))
(is (= (format-serial-number 42) "002A")))
(deftest next-serial-number!-test
(let [serial-file (str (ks/temp-file))]
(testing "Serial file is initialized to 1"
(initialize-serial-file! serial-file)
(is (= (next-serial-number! serial-file) 1)))
(testing "The serial number file should contain the next serial number"
(is (= "0002" (slurp serial-file))))
(testing "subsequent calls produce increasing serial numbers"
(is (= (next-serial-number! serial-file) 2))
(is (= "0003" (slurp serial-file)))
(is (= (next-serial-number! serial-file) 3))
(is (= "0004" (slurp serial-file))))))
;; If the locking is deleted from `next-serial-number!`, this test will hang,
;; which is not as nice as simply failing ...
;; This seems to happen due to a deadlock caused by concurrently reading and
;; writing to the same file (via `slurp` and `spit`)
(deftest next-serial-number-threadsafety
(testing "next-serial-number! is thread-safe and
never returns a duplicate serial number"
(let [serial-file (doto (str (ks/temp-file)) (spit "0001"))
serials (atom [])
;; spin off a new thread for each CPU
promises (for [_ (range (ks/num-cpus))]
(let [p (promise)]
(future
;; get a bunch of serial numbers and keep track of them
(dotimes [_ 100]
(let [serial-number (next-serial-number! serial-file)]
(swap! serials conj serial-number)))
(deliver p 'done))
p))
contains-duplicates? #(not= (count %) (count (distinct %)))]
; wait on all the threads to finish
(doseq [p promises] (deref p))
(is (false? (contains-duplicates? @serials))
"Got a duplicate serial number"))))
(defn verify-inventory-entry!
[inventory-entry serial-number not-before not-after subject]
(let [parts (string/split inventory-entry #" ")]
(is (= serial-number (first parts)))
(is (= not-before (second parts)))
(is (= not-after (nth parts 2)))
(is (= subject (string/join " " (subvec parts 3))))))
(deftest test-write-cert-to-inventory
(testing "Certs can be written to an inventory file."
(let [first-cert (utils/pem->cert cacert)
second-cert (utils/pem->cert (path-to-cert signeddir "localhost"))
inventory-file (str (ks/temp-file))]
(write-cert-to-inventory! first-cert inventory-file)
(write-cert-to-inventory! second-cert inventory-file)
(testing "The format of a cert in the inventory matches the existing
format used by the ruby puppet code."
(let [inventory (slurp inventory-file)
entries (string/split inventory #"\n")]
(is (= (count entries) 2))
(verify-inventory-entry!
(first entries)
"0x0001"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=Puppet CA: localhost")
(verify-inventory-entry!
(second entries)
"0x0002"
"2014-02-14T18:09:07UTC"
"2019-02-14T18:09:07UTC"
"/CN=localhost"))))))
(deftest allow-duplicate-certs-test
(let [settings (assoc (testutils/ca-sandbox! cadir) :autosign false)]
(testing "when false"
(let [settings (assoc settings :allow-duplicate-certs false)]
(testing "throws exception if CSR already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "test-agent" (csr-stream "test-agent") settings))))
(testing "throws exception if certificate already exists"
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "localhost already has a signed certificate; ignoring certificate request"}
(process-csr-submission! "localhost"
(io/input-stream (test-pem-file "localhost-csr.pem"))
settings)))
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "revoked-agent already has a revoked certificate; ignoring certificate request"}
(process-csr-submission! "revoked-agent"
(io/input-stream (test-pem-file "revoked-agent-csr.pem"))
settings))))))
(testing "when true"
(let [settings (assoc settings :allow-duplicate-certs true)]
(testing "new CSR overwrites existing one"
(let [csr-path (path-to-cert-request (:csrdir settings) "test-agent")
csr (ByteArrayInputStream. (.getBytes (slurp csr-path)))]
(spit csr-path "should be overwritten")
(logutils/with-test-logging
(process-csr-submission! "test-agent" csr settings)
(is (logged? #"test-agent already has a requested certificate; new certificate will overwrite it" :info))
(is (not= "should be overwritten" (slurp csr-path))
"Existing CSR was not overwritten"))))
(testing "new certificate overwrites existing one"
(let [settings (assoc settings :autosign true)
cert-path (path-to-cert (:signeddir settings) "localhost")
old-cert (slurp cert-path)
csr (io/input-stream (test-pem-file "localhost-csr.pem"))]
(logutils/with-test-logging
(process-csr-submission! "localhost" csr settings)
(is (logged? #"localhost already has a signed certificate; new certificate will overwrite it" :info))
(is (not= old-cert (slurp cert-path)) "Existing certificate was not overwritten"))))))))
(deftest process-csr-submission!-test
(let [settings (testutils/ca-sandbox! cadir)]
(testing "CSR validation policies"
(testing "when autosign is false"
(let [settings (assoc settings :autosign false)]
(testing "subject policies are checked"
(doseq [[policy subject csr-file exception]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["invalid characters in name" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["wildcard in name" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? exception (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "extension & key policies are not checked"
(doseq [[policy subject csr-file]
[["subject alt name extension" "hostwithaltnames" "hostwithaltnames.pem"]
["unknown extension" "meow" "meow-bad-extension.pem"]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(process-csr-submission! subject csr settings)
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "when autosign is true, all policies are checked, and"
(let [settings (assoc settings :autosign true)]
(testing "CSR will not be saved when"
(doseq [[policy subject csr-file expected]
[["subject-hostname mismatch" "foo" "hostwithaltnames.pem"
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}]
["subject contains invalid characters" "super/bad" "bad-subject-name-1.pem"
{:type :invalid-subject-name
:message "Subject contains unprintable or non-ASCII characters"}]
["subject contains wildcard character" "foo*bar" "bad-subject-name-wildcard.pem"
{:type :invalid-subject-name
:message "Subject contains a wildcard, which is not allowed: foo*bar"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (false? (fs/exists? path)))))))
(testing "CSR will be saved when"
(doseq [[policy subject csr-file expected]
[["subject alt name extension exists" "hostwithaltnames" "hostwithaltnames.pem"
{:type :disallowed-extension
:message (str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request.")}]
["unknown extension exists" "meow" "meow-bad-extension.pem"
{:type :disallowed-extension
:message "Found extensions that are not permitted: PI:IP_ADDRESS:172.16.31.10END_PI.9.9.9"}]
["public-private key mismatch" "luke.madstop.com" "luke.madstop.com-bad-public-key.pem"
{:type :invalid-signature
:message "CSR contains a public key that does not correspond to the signing key"}]]]
(testing policy
(let [path (path-to-cert-request (:csrdir settings) subject)
csr (io/input-stream (test-pem-file csr-file))]
(is (false? (fs/exists? path)))
(is (thrown-with-slingshot? expected (process-csr-submission! subject csr settings)))
(is (true? (fs/exists? path)))
(fs/delete path)))))))
(testing "order of validations"
(testing "duplicates checked before subject policies"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-with-mismatched-name (csr-stream "test-agent")]
(is (thrown-with-slingshot?
{:type :duplicate-cert
:message "test-agent already has a requested certificate; ignoring certificate request"}
(process-csr-submission! "not-test-agent" csr-with-mismatched-name settings)))))
(testing "subject policies checked before extension & key policies"
(let [csr-with-disallowed-alt-names (io/input-stream (test-pem-file "hostwithaltnames.pem"))]
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"hostwithaltnames\" does not match requested key \"foo\""}
(process-csr-submission! "foo" csr-with-disallowed-alt-names settings)))))))))
(deftest cert-signing-extension-test
(let [issuer-keys (utils/generate-key-pair 512)
issuer-pub (utils/get-public-key issuer-keys)
subject-keys (utils/generate-key-pair 512)
subject-pub (utils/get-public-key subject-keys)
subject "subject"
subject-dn (utils/cn subject)]
(testing "basic extensions are created for an agent"
(let [csr (utils/generate-certificate-request subject-keys subject-dn)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical true
:value {:is-ca false}}
{:oid "PI:IP_ADDRESS:192.168.127.12END_PI"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "basic extensions are created for a master"
(let [settings (assoc (testutils/master-settings confdir)
:csr-attributes "doesntexist")
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical true
:value {:is-ca false}}
{:oid "PI:IP_ADDRESS:192.168.127.12END_PI"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical false
:value subject-pub}
{:oid utils/subject-alt-name-oid
:critical false
:value {:dns-name ["puppet" "subject"]}}]]
(is (= (set exts) (set exts-expected)))))
(testing "additional extensions are created for a master"
(let [dns-alt-names "onefish,twofish"
settings (-> (testutils/master-settings confdir)
(assoc :dns-alt-names dns-alt-names)
(assoc :csr-attributes (csr-attributes-file "csr_attributes.yaml")))
exts (create-master-extensions subject
subject-pub
issuer-pub
settings)
exts-expected [
{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical true
:value {:is-ca false}}
{:oid "PI:IP_ADDRESS:192.168.127.12END_PI"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical false
:value subject-pub}
{:oid "PI:IP_ADDRESS:192.168.3.11END_PI"
:critical false
:value {:dns-name ["subject"
"onefish"
"twofish"]}}
;; These extensions come form csr_attributes.yaml
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "ED803750-E3C7-44F5-BB08-41A04433FE2E"}
{:oid "1.3.6.1.4.1.34380.1.1.1.4"
:critical false
:value "I am undefined but still work"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "thisisanid"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "my_ami_image"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "342thbjkt82094y0uthhor289jnqthpc2290"}
{:oid "1.3.6.1.4.1.34380.1.1.5" :critical false
:value "center"}
{:oid "1.3.6.1.4.1.34380.1.1.6" :critical false
:value "product"}
{:oid "1.3.6.1.4.1.34380.1.1.7" :critical false
:value "project"}
{:oid "1.3.6.1.4.1.34380.1.1.8" :critical false
:value "application"}
{:oid "1.3.6.1.4.1.34380.1.1.9" :critical false
:value "service"}
{:oid "1.3.6.1.4.1.34380.1.1.10" :critical false
:value "employee"}
{:oid "1.3.6.1.4.1.34380.1.1.11" :critical false
:value "created"}
{:oid "1.3.6.1.4.1.34380.1.1.12" :critical false
:value "environment"}
{:oid "1.3.6.1.4.1.34380.1.1.13" :critical false
:value "role"}
{:oid "1.3.6.1.4.1.34380.1.1.14" :critical false
:value "version"}
{:oid "1.3.6.1.4.1.34380.1.1.15" :critical false
:value "deparment"}
{:oid "1.3.6.1.4.1.34380.1.1.16" :critical false
:value "cluster"}
{:oid "1.3.6.1.4.1.34380.1.1.17" :critical false
:value "provisioner"}]]
(is (= (set exts) (set exts-expected)))))
(testing "A non-puppet OID read from a CSR attributes file is rejected"
(let [config (assoc (testutils/master-settings confdir)
:csr-attributes
(csr-attributes-file "insecure_csr_attributes.yaml"))]
(is (thrown-with-slingshot?
{:type :disallowed-extension
:message "Found extensions that are not permitted: PI:IP_ADDRESS:172.16.58.3END_PI"}
(create-master-extensions subject subject-pub issuer-pub config)))))
(testing "invalid DNS alt names are rejected"
(let [dns-alt-names "*.wildcard"]
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: *.wildcard"}
(create-master-extensions subject subject-pub issuer-pub
(assoc (testutils/master-settings confdir)
:dns-alt-names dns-alt-names))))))
(testing "basic extensions are created for a CA"
(let [serial 42
exts (create-ca-extensions subject-dn
serial
subject-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical false
:value {:issuer-dn (str "CN=" subject)
:public-key nil
:serial-number (biginteger serial)}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical true
:value {:is-ca true}}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical true
:value #{:crl-sign :key-cert-sign}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical false
:value subject-pub}]]
(is (= (set exts) (set exts-expected)))))
(testing "trusted fact extensions are properly unfiltered"
(let [csr-exts [(utils/puppet-node-image-name "imagename" false)
(utils/puppet-node-preshared-key "key" false)
(utils/puppet-node-instance-id "instance" false)
(utils/puppet-node-uid "UUUU-IIIII-DDD" false)]
csr (utils/generate-certificate-request
subject-keys subject-dn csr-exts)
exts (create-agent-extensions csr issuer-pub)
exts-expected [{:oid "2.16.840.1.113730.1.13"
:critical false
:value netscape-comment-value}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical false
:value {:issuer-dn nil
:public-key issuer-pub
:serial-number nil}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical true
:value {:is-ca false}}
{:oid "PI:IP_ADDRESS:192.168.127.12END_PI"
:critical true
:value [ssl-server-cert ssl-client-cert]}
{:oid "PI:IP_ADDRESS:172.16.58.3END_PI"
:critical true
:value #{:digital-signature :key-encipherment}}
{:oid "PI:IP_ADDRESS:172.16.17.32END_PI"
:critical false
:value subject-pub}
{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value "UUUU-IIIII-DDD"}
{:oid "1.3.6.1.4.1.34380.1.1.2"
:critical false
:value "instance"}
{:oid "1.3.6.1.4.1.34380.1.1.3"
:critical false
:value "imagename"}
{:oid "1.3.6.1.4.1.34380.1.1.4"
:critical false
:value "key"}]]
(is (= (set exts) (set exts-expected))
"The puppet trusted facts extensions were not added by create-agent-extensions")))))
(deftest netscape-comment-value-test
(testing "Netscape comment constant has expected value"
(is (= "Puppet Server Internal Certificate" netscape-comment-value))))
(deftest validate-subject!-test
(testing "an exception is thrown when the hostnames don't match"
(is (thrown-with-slingshot?
{:type :hostname-mismatch
:message "Instance name \"test-agent\" does not match requested key \"not-test-agent\""}
(validate-subject!
"not-test-agent" "test-agent"))))
(testing "an exception is thrown if the subject name contains a capital letter"
(is (thrown-with-slingshot?
{:type :invalid-subject-name
:message "Certificate names must be lower case."}
(validate-subject! "Host-With-Capital-Letters"
"Host-With-Capital-Letters")))))
(deftest validate-dns-alt-names!-test
(testing "Only DNS alt names are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Only DNS names are allowed in the Subject Alternative Names extension"}
(validate-dns-alt-names! {:oid "PI:IP_ADDRESS:192.168.3.11END_PI"
:critical false
:value {:ip-address ["PI:IP_ADDRESS:172.16.17.32END_PI"]}}))))
(testing "No DNS wildcards are allowed"
(is (thrown-with-slingshot?
{:type :invalid-alt-name
:message "Cert subjectAltName contains a wildcard, which is not allowed: foo*bar"}
(validate-dns-alt-names! {:oid "PI:IP_ADDRESS:192.168.3.11END_PI"
:critical false
:value {:dns-name ["ahostname" "foo*bar"]}})))))
(deftest default-master-dns-alt-names
(testing "Master certificate has default DNS alt names if none are specified"
(let [settings (assoc (testutils/master-settings confdir)
:dns-alt-names "")
pubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
capubkey (-> (utils/generate-key-pair 512)
(utils/get-public-key))
alt-names (-> (create-master-extensions "master" pubkey capubkey settings)
(utils/get-extension-value utils/subject-alt-name-oid)
(:dns-name))]
(is (= #{"puppet" "master"} (set alt-names))))))
|
[
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redi",
"end": 34,
"score": 0.9998722076416016,
"start": 21,
"tag": "NAME",
"value": "Sebastian Hoß"
},
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redistribute it and",
"end": 49,
"score": 0.9999275803565979,
"start": 36,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/test/clojure/finj/loan_test.clj
|
sebhoss/finj
| 30 |
;
; Copyright © 2013 Sebastian Hoß <[email protected]>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.loan-test
(:require [finj.loan :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest rate-balance-due-test
(testing "with positive values"
(is (≈ 200 (rate-balance-due :loan 500 :period 3 :repayment-period 5)))))
(deftest rate-interest-amount-test
(testing "with positive values"
(is (≈ 30 (rate-interest-amount :loan 500 :period 3 :repayment-period 5 :rate 0.1)))))
(deftest annuity-test
(testing "with positive values"
(is (≈ 131 (annuity :loan 500 :period 5 :accumulation-factor 1.1)))))
(deftest annuity-amount-test
(testing "with positive values"
(is (≈ 98 (annuity-amount :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-balance-due-test
(testing "with positive values"
(is (≈ 231 (annuity-balance-due :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-interest-amount-test
(testing "with positive values"
(is (≈ 106 (annuity-interest-amount :annuity 131 :first-annuity-amount 20 :period 3 :accumulation-factor 1.1)))))
(deftest period-test
(testing "with positive values"
(is (≈ 5 (period :loan 500 :annuity 131 :accumulation-factor 1.1)))))
|
14893
|
;
; Copyright © 2013 <NAME> <<EMAIL>>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.loan-test
(:require [finj.loan :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest rate-balance-due-test
(testing "with positive values"
(is (≈ 200 (rate-balance-due :loan 500 :period 3 :repayment-period 5)))))
(deftest rate-interest-amount-test
(testing "with positive values"
(is (≈ 30 (rate-interest-amount :loan 500 :period 3 :repayment-period 5 :rate 0.1)))))
(deftest annuity-test
(testing "with positive values"
(is (≈ 131 (annuity :loan 500 :period 5 :accumulation-factor 1.1)))))
(deftest annuity-amount-test
(testing "with positive values"
(is (≈ 98 (annuity-amount :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-balance-due-test
(testing "with positive values"
(is (≈ 231 (annuity-balance-due :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-interest-amount-test
(testing "with positive values"
(is (≈ 106 (annuity-interest-amount :annuity 131 :first-annuity-amount 20 :period 3 :accumulation-factor 1.1)))))
(deftest period-test
(testing "with positive values"
(is (≈ 5 (period :loan 500 :annuity 131 :accumulation-factor 1.1)))))
| true |
;
; Copyright © 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.loan-test
(:require [finj.loan :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest rate-balance-due-test
(testing "with positive values"
(is (≈ 200 (rate-balance-due :loan 500 :period 3 :repayment-period 5)))))
(deftest rate-interest-amount-test
(testing "with positive values"
(is (≈ 30 (rate-interest-amount :loan 500 :period 3 :repayment-period 5 :rate 0.1)))))
(deftest annuity-test
(testing "with positive values"
(is (≈ 131 (annuity :loan 500 :period 5 :accumulation-factor 1.1)))))
(deftest annuity-amount-test
(testing "with positive values"
(is (≈ 98 (annuity-amount :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-balance-due-test
(testing "with positive values"
(is (≈ 231 (annuity-balance-due :loan 500 :annuity 131 :period 3 :accumulation-factor 1.1)))))
(deftest annuity-interest-amount-test
(testing "with positive values"
(is (≈ 106 (annuity-interest-amount :annuity 131 :first-annuity-amount 20 :period 3 :accumulation-factor 1.1)))))
(deftest period-test
(testing "with positive values"
(is (≈ 5 (period :loan 500 :annuity 131 :accumulation-factor 1.1)))))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-11-23\"\n :doc \"scored vs all sub",
"end": 105,
"score": 0.9998733401298523,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] |
src/test/clojure/taiga/test/classify/split/all_subsets.clj
|
wahpenayo/taiga
| 4 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.test.classify.split.all-subsets
(:require [clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.split.api :as split]
[taiga.split.numerical.categorical.scored :as scored]
[taiga.split.object.categorical.all-subsets :as all-subsets]
[taiga.split.object.categorical.bottom-up :as bottom-up]
[taiga.split.object.categorical.heuristic :as heuristic]
[taiga.forest :as forest]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.split.all-subsets clojure:test > tests.txt
;;------------------------------------------------------------------------------
(test/deftest primate
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
(test/deftest kolor
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/kolor])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
|
78498
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.test.classify.split.all-subsets
(:require [clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.split.api :as split]
[taiga.split.numerical.categorical.scored :as scored]
[taiga.split.object.categorical.all-subsets :as all-subsets]
[taiga.split.object.categorical.bottom-up :as bottom-up]
[taiga.split.object.categorical.heuristic :as heuristic]
[taiga.forest :as forest]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.split.all-subsets clojure:test > tests.txt
;;------------------------------------------------------------------------------
(test/deftest primate
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
(test/deftest kolor
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/kolor])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.test.classify.split.all-subsets
(:require [clojure.pprint :as pp]
[clojure.test :as test]
[zana.api :as z]
[taiga.split.api :as split]
[taiga.split.numerical.categorical.scored :as scored]
[taiga.split.object.categorical.all-subsets :as all-subsets]
[taiga.split.object.categorical.bottom-up :as bottom-up]
[taiga.split.object.categorical.heuristic :as heuristic]
[taiga.forest :as forest]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.split.all-subsets clojure:test > tests.txt
;;------------------------------------------------------------------------------
(test/deftest primate
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
(test/deftest kolor
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))
options (assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/kolor])
scored (z/seconds "scored" (scored/split options))
all-subsets (z/seconds "all-subsets" (all-subsets/split options))
bottom-up (z/seconds "bottom-up" (bottom-up/split options))
heuristic (z/seconds "heuristic" (heuristic/split options))]
(println scored)
(println all-subsets)
(println bottom-up)
(println heuristic)
;; bottom-up won't always be the same, but scored and all-subsets should be
(test/is (= scored all-subsets bottom-up heuristic))))
;;------------------------------------------------------------------------------
|
[
{
"context": ";;\n;; Classifiers\n;; @author Antonio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <antoniogarro",
"end": 44,
"score": 0.9998968839645386,
"start": 29,
"tag": "NAME",
"value": "Antonio Garrote"
},
{
"context": "rs\n;; @author Antonio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <[email protected]>\"}\n clj-ml.classifiers",
"end": 80,
"score": 0.999895453453064,
"start": 65,
"tag": "NAME",
"value": "Antonio Garrote"
},
{
"context": "onio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <[email protected]>\"}\n clj-ml.classifiers\n \"This namespace contain",
"end": 106,
"score": 0.999930202960968,
"start": 82,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " (serialize-to-file *classifier*\n \\\"/Users/antonio.garrote/Desktop/classifier.bin\\\")\n\"\n (:use [clj-ml utils",
"end": 2317,
"score": 0.9395530819892883,
"start": 2302,
"tag": "USERNAME",
"value": "antonio.garrote"
}
] |
src/clj_ml/classifiers.clj
|
yogsototh/clj-ml
| 0 |
;;
;; Classifiers
;; @author Antonio Garrote
;;
(ns #^{:author "Antonio Garrote <[email protected]>"}
clj-ml.classifiers
"This namespace contains several functions for building classifiers using different
classification algorithms: Bayes networks, multilayer perceptron, decision tree or
support vector machines are available. Some of these classifiers have incremental
versions so they can be built without having all the dataset instances in memory.
Functions for evaluating the classifiers built using cross validation or a training
set are also provided.
A sample use of the API for classifiers is shown below:
(use 'clj-ml.classifiers)
; Building a classifier using a C4.5 decision tree
(def *classifier* (make-classifier :decision-tree :c45))
; We set the class attribute for the loaded dataset.
; *dataset* is supposed to contain a set of instances.
(dataset-set-class *dataset* 4)
; Training the classifier
(classifier-train *classifier* *dataset*)
; We evaluate the classifier using a test dataset
(def *evaluation* (classifier-evaluate *classifier* :dataset *dataset* *trainingset*))
; We retrieve some data from the evaluation result
(:kappa *evaluation*)
(:root-mean-squared-error *evaluation*)
(:precision *evaluation*)
; A trained classifier can be used to classify new instances
(def *to-classify* (make-instance *dataset* {:class :Iris-versicolor
:petalwidth 0.2
:petallength 1.4
:sepalwidth 3.5
:sepallength 5.1}))
; We retrieve the index of the class value assigned by the classifier
(classifier-classify *classifier* *to-classify*)
; We retrieve a symbol with the value assigned by the classifier
; and assigns it to a certain instance
(classifier-label *classifier* *to-classify*)
A classifier can also be trained using cross-validation:
(classifier-evaluate *classifier* :cross-validation *dataset* 10)
Finally a classifier can be stored in a file for later use:
(use 'clj-ml.utils)
(serialize-to-file *classifier*
\"/Users/antonio.garrote/Desktop/classifier.bin\")
"
(:use [clj-ml utils data kernel-functions options-utils])
(:import (java.util Date Random)
(weka.core Instance Instances)
(weka.classifiers.lazy IBk)
(weka.classifiers.trees J48 RandomForest M5P)
(weka.classifiers.meta LogitBoost AdditiveRegression RotationForest)
(weka.classifiers.bayes NaiveBayes NaiveBayesUpdateable)
(weka.classifiers.functions MultilayerPerceptron SMO LinearRegression Logistic PaceRegression SPegasos LibSVM)
(weka.classifiers AbstractClassifier Classifier Evaluation)))
;; Setting up classifier options
(defmulti #^{:skip-wiki true}
make-classifier-options
"Creates the right parameters for a classifier. Returns the parameters as a Clojure vector."
(fn [kind algorithm map] [kind algorithm]))
(defmethod make-classifier-options [:lazy :ibk]
([kind algorithm m]
(->> (check-options m
{:inverse-weighted "-I"
:similarity-weighted "-F"
:no-normalization "-N"})
(check-option-values m
{:num-neighbors "-K"}))))
(defmethod make-classifier-options [:decision-tree :c45]
([kind algorithm m]
(->> (check-options m
{:unpruned "-U"
:reduced-error-pruning "-R"
:only-binary-splits "-B"
:no-raising "-S"
:no-cleanup "-L"
:laplace-smoothing "-A"})
(check-option-values m
{:pruning-confidence "-C"
:minimum-instances "-M"
:pruning-number-folds "-N"
:random-seed "-Q"}))))
(defmethod make-classifier-options [:bayes :naive]
([kind algorithm m]
(check-options m
{:kernel-estimator "-K"
:supervised-discretization "-D"
:old-format "-O"})))
(defmethod make-classifier-options [:neural-network :multilayer-perceptron]
([kind algorithm m]
(->> (check-options m
{:no-nominal-to-binary "-B"
:no-numeric-normalization "-C"
:no-normalization "-I"
:no-reset "-R"
:learning-rate-decay "-D"})
(check-option-values m
{:learning-rate "-L"
:momentum "-M"
:epochs "-N"
:percentage-validation-set "-V"
:random-seed "-S"
:threshold-number-errors "-E"
:hidden-layers-string "-H"}))))
(defmethod make-classifier-options [:support-vector-machine :smo]
([kind algorithm m]
(->> (check-options m {:fit-logistic-models "-M"})
(check-option-values m
{:complexity-constant "-C"
:normalize "-N"
:tolerance "-L"
:epsilon-roundoff "-P"
:folds-for-cross-validation "-V"
:random-seed "-W"}))))
(defmethod make-classifier-options [:support-vector-machine :spegasos]
([kind algorithm m]
(->> (check-options m {:no-normalization "-N"
:no-replace-missing"-M"})
(check-option-values m
{:loss-fn "-F"
:epochs "-E"
:lambda "-L"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-gamma "-G"
:kernel-coef0 "-R"
:param-C "-C"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm-grid]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-coef0 "-R"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:regression :linear]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:keep-colinear "-C"})
(check-option-values m
{:attribute-selection "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :logistic]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:max-iterations "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :pace]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:shrinkage "-S"
:estimator "-E"}))))
(defmethod make-classifier-options [:regression :boosted-regression]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:threshold "-S"
:num-iterations "-I"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :boosted-stump]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:resampling "-Q"})
(check-option-values m
{:weak-learning-class "-W"
:num-iterations "-I"
:random-seed "-S"
:percentage-weight-mass "-P"
:folds-for-cross-validation "-F"
:runs-for-cross-validation "-R"
:log-likelihood-improvement-threshold "-L"
:shrinkage-parameter "-H"}))))
(defmethod make-classifier-options [:decision-tree :random-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-trees-in-forest "-I"
:num-features-to-consider "-K"
:random-seed "-S"
:depth "-depth"}))))
(defmethod make-classifier-options [:decision-tree :rotation-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-iterations "-I"
:use-number-of-groups "-N"
:min-attribute-group-size "-G"
:max-attribute-group-size "-H"
:percentage-of-instances-to-remove "-P"
:filter "-F"
:random-seed "-S"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :m5p]
([kind algorithm m]
(->>
(check-options m {:unsmoothed-predictions "-U"
:regression "-R"
:unpruned "-N"})
(check-option-values m {:minimum-instances "-M"}))))
;; Building classifiers
(defn make-classifier-with
#^{:skip-wiki true}
[kind algorithm ^Class classifier-class options]
(capture-out-err
(let [options-read (if (empty? options) {} (first options))
^Classifier classifier (.newInstance classifier-class)
opts (into-array String (make-classifier-options kind algorithm options-read))]
(.setOptions classifier opts)
classifier)))
(defmulti make-classifier
"Creates a new classifier for the given kind algorithm and options.
The first argument identifies the kind of classifier and the second
argument the algorithm to use, e.g. :decision-tree :c45.
The classifiers currently supported are:
- :lazy :ibk
- :decision-tree :c45
- :decision-tree :boosted-stump
- :decision-tree :boosted-decision-tree
- :decision-tree :M5P
- :decision-tree :random-forest
- :decision-tree :rotation-forest
- :bayes :naive
- :neural-network :mutilayer-perceptron
- :support-vector-machine :smo
- :regression :linear
- :regression :logistic
- :regression :pace
Optionally, a map of options can also be passed as an argument with
a set of classifier specific options.
This is the description of the supported classifiers and the accepted
option parameters for each of them:
* :lazy :ibk
K-nearest neighbor classification.
Parameters:
- :inverse-weighted
Neighbors will be weighted by the inverse of their distance when voting. (default equal weighting)
Sample value: true
- :similarity-weighted
Neighbors will be weighted by their similarity when voting. (default equal weighting)
Sample value: true
- :no-normalization
Turns off normalization.
Sample value: true
- :num-neighbors
Set the number of nearest neighbors to use in prediction (default 1)
Sample value: 3
* :decision-tree :c45
A classifier building a pruned or unpruned C 4.5 decision tree using
Weka J 4.8 implementation.
Parameters:
- :unpruned
Use unpruned tree. Sample value: true
- :reduce-error-pruning
Sample value: true
- :only-binary-splits
Sample value: true
- :no-raising
Sample value: true
- :no-cleanup
Sample value: true
- :laplace-smoothing
For predicted probabilities. Sample value: true
- :pruning-confidence
Threshold for pruning. Default value: 0.25
- :minimum-instances
Minimum number of instances per leave. Default value: 2
- :pruning-number-folds
Set number of folds for reduced error pruning. Default value: 3
- :random-seed
Seed for random data shuffling. Default value: 1
* :bayes :naive
Classifier based on the Bayes' theorem with strong independence assumptions, among the
probabilistic variables.
Parameters:
- :kernel-estimator
Use kernel desity estimator rather than normal. Sample value: true
- :supervised-discretization
Use supervised discretization to to process numeric attributes (see :supervised-discretize
filter in clj-ml.filters/make-filter function). Sample value: true
* :neural-network :multilayer-perceptron
Classifier built using a feedforward artificial neural network with three or more layers
of neurons and nonlinear activation functions. It is able to distinguish data that is not
linearly separable.
Parameters:
- :no-nominal-to-binary
A :nominal-to-binary filter will not be applied by default. (see :supervised-nominal-to-binary
filter in clj-ml.filters/make-filter function). Default value: false
- :no-numeric-normalization
A numeric class will not be normalized. Default value: false
- :no-normalization
No attribute will be normalized. Default value: false
- :no-reset
Reseting the network will not be allowed. Default value: false
- :learning-rate-decay
Learning rate decay will occur. Default value: false
- :learning-rate
Learning rate for the backpropagation algorithm. Value should be between [0,1].
Default value: 0.3
- :momentum
Momentum rate for the backpropagation algorithm. Value shuld be between [0,1].
Default value: 0.2
- :epochs
Number of iteration to train through. Default value: 500
- :percentage-validation-set
Percentage size of validation set to use to terminate training. If it is not zero
it takes precende over the number of epochs to finish training. Values should be
between [0,100]. Default value: 0
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
- :threshold-number-errors
The consequetive number of errors allowed for validation testing before the network
terminates. Values should be greater thant 0. Default value: 20
* :support-vector-machine :smo
Support vector machine (SVM) classifier built using the sequential minimal optimization (SMO)
training algorithm.
Parameters:
- :fit-logistic-models
Fit logistic models to SVM outputs. Default value :false
- :complexity-constant
The complexity constance. Default value: 1
- :tolerance
Tolerance parameter. Default value: 1.0e-3
- :epsilon-roundoff
Epsilon round-off error. Default value: 1.0e-12
- :folds-for-cross-validation
Number of folds for the internal cross-validation. Sample value: 10
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
* :support-vector-machine :libsvm
TODO
* :regression :linear
Parameters:
- :attribute-selection
Set the attribute selection method to use. 1 = None, 2 = Greedy. (default 0 = M5' method)
- :keep-colinear
Do not try to eliminate colinear attributes.
- :ridge
Set ridge parameter (default 1.0e-8).
* :regression :logistic
Parameters:
- :max-iterations
Set the maximum number of iterations (default -1, until convergence).
- :ridge
Set the ridge in the log-likelihood.
"
(fn [kind algorithm & options] [kind algorithm]))
(defmethod make-classifier [:lazy :ibk]
([kind algorithm & options]
(make-classifier-with kind algorithm IBk options)))
(defmethod make-classifier [:decision-tree :c45]
([kind algorithm & options]
(make-classifier-with kind algorithm J48 options)))
(defmethod make-classifier [:bayes :naive]
([kind algorithm & options]
(if (or (nil? (:updateable (first options)))
(= (:updateable (first options)) false))
(make-classifier-with kind algorithm NaiveBayes options)
(make-classifier-with kind algorithm NaiveBayesUpdateable options))))
(defmethod make-classifier [:neural-network :multilayer-perceptron]
([kind algorithm & options]
(make-classifier-with kind algorithm MultilayerPerceptron options)))
(defmethod make-classifier [:support-vector-machine :smo]
([kind algorithm & options]
(let [options-read (if (empty? options) {} (first options))
classifier (new SMO)
opts (into-array String (make-classifier-options :support-vector-machine :smo options-read))]
(.setOptions classifier opts)
(when (not (empty? (get options-read :kernel-function)))
;; We have to setup a different kernel function
(let [kernel (get options-read :kernel-function)
real-kernel (if (map? kernel)
(make-kernel-function (first (keys kernel))
(first (vals kernel)))
kernel)]
(.setKernel classifier real-kernel)))
classifier)))
(defmethod make-classifier [:support-vector-machine :spegasos]
([kind algorithm & options]
(make-classifier-with kind algorithm SPegasos options)))
(defmethod make-classifier [:support-vector-machine :libsvm]
([kind algorithm & options]
(make-classifier-with kind algorithm LibSVM options)))
(defmethod make-classifier [:support-vector-machine :libsvm-grid]
([kind algorithm & options]
(for [c (range -5 17 2) g (range 3 -17 -2)]
(make-classifier-with
:support-vector-machine :libsvm
LibSVM (concat options [:param-C (Math/pow 2.0 c)
:kernel-gamma (Math/pow 2.0 g)])))))
(defmethod make-classifier [:regression :linear]
([kind algorithm & options]
(make-classifier-with kind algorithm LinearRegression options)))
(defmethod make-classifier [:regression :logistic]
([kind algorithm & options]
(make-classifier-with kind algorithm Logistic options)))
(defmethod make-classifier [:regression :pace]
([kind algorithm & options]
(make-classifier-with kind algorithm PaceRegression options)))
(defmethod make-classifier [:regression :boosted-regression]
([kind algorithm & options]
(make-classifier-with kind algorithm AdditiveRegression options)))
(defmethod make-classifier [:decision-tree :boosted-stump]
([kind algorithm & options]
(make-classifier-with kind algorithm LogitBoost options)))
(defmethod make-classifier [:decision-tree :random-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RandomForest options)))
(defmethod make-classifier [:decision-tree :rotation-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RotationForest options)))
(defmethod make-classifier [:decision-tree :m5p]
([kind algorithm & options]
(make-classifier-with kind algorithm M5P options)))
;; Training classifiers
(defn classifier-train
"Trains a classifier with the given dataset as the training data."
([^Classifier classifier dataset]
(do (.buildClassifier classifier dataset)
classifier)))
(defn classifier-copy
"Performs a deep copy of the classifier"
[^Classifier classifier]
(AbstractClassifier/makeCopy classifier))
(defn classifier-copy-and-train
"Performs a deep copy of the classifier, trains the copy, and returns it."
[classifier dataset]
(classifier-train (classifier-copy classifier) dataset))
(defn classifier-update
"If the classifier is updateable it updates the classifier with the given instance or set of instances."
([^Classifier classifier instance-s]
;; Arg... weka doesn't provide a formal interface for updateClassifer- How do I type hint this?
(if (is-dataset? instance-s)
(do (doseq [i (dataset-seq instance-s)]
(.updateClassifier classifier ^Instance i))
classifier)
(do (.updateClassifier classifier ^Instance instance-s)
classifier))))
;; Evaluating classifiers
(defn- collect-evaluation-results
"Collects all the statistics from the evaluation of a classifier."
([class-labels ^Evaluation evaluation]
{:confusion-matrix (.toMatrixString evaluation)
:summary (.toSummaryString evaluation)
:correct (try-metric #(.correct evaluation))
:incorrect (try-metric #(.incorrect evaluation))
:unclassified (try-metric #(.unclassified evaluation))
:percentage-correct (try-metric #(.pctCorrect evaluation))
:percentage-incorrect (try-metric #(.pctIncorrect evaluation))
:percentage-unclassified (try-metric #(.pctUnclassified evaluation))
:error-rate (try-metric #(.errorRate evaluation))
:mean-absolute-error (try-metric #(.meanAbsoluteError evaluation))
:relative-absolute-error (try-metric #(.relativeAbsoluteError evaluation))
:root-mean-squared-error (try-metric #(.rootMeanSquaredError evaluation))
:root-relative-squared-error (try-metric #(.rootRelativeSquaredError evaluation))
:correlation-coefficient (try-metric #(.correlationCoefficient evaluation))
:average-cost (try-metric #(.avgCost evaluation))
:kappa (try-metric #(.kappa evaluation))
:kb-information (try-metric #(.KBInformation evaluation))
:kb-mean-information (try-metric #(.KBMeanInformation evaluation))
:kb-relative-information (try-metric #(.KBRelativeInformation evaluation))
:sf-entropy-gain (try-metric #(.SFEntropyGain evaluation))
:sf-mean-entropy-gain (try-metric #(.SFMeanEntropyGain evaluation))
:roc-area (try-multiple-values-metric class-labels (fn [i] (try-metric #(.areaUnderROC evaluation i))))
:false-positive-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falsePositiveRate evaluation i))))
:false-negative-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falseNegativeRate evaluation i))))
:f-measure (try-multiple-values-metric class-labels (fn [i] (try-metric #(.fMeasure evaluation i))))
:precision (try-multiple-values-metric class-labels (fn [i] (try-metric #(.precision evaluation i))))
:recall (try-multiple-values-metric class-labels (fn [i] (try-metric #(.recall evaluation i))))
:evaluation-object evaluation}))
(defmulti classifier-evaluate
"Evaluates a trained classifier using the provided dataset or cross-validation.
The first argument must be the classifier to evaluate, the second argument is
the kind of evaluation to do.
Two possible evaluations ara availabe: dataset and cross-validations. The values
for the second argument can be:
- :dataset
- :cross-validation
* :dataset
If dataset evaluation is desired, the function call must receive as the second
parameter the keyword :dataset and as third and fourth parameters the original
dataset used to build the classifier and the training data:
(classifier-evaluate *classifier* :dataset *training* *evaluation*)
* :cross-validation
If cross-validation is desired, the function call must receive as the second
parameter the keyword :cross-validation and as third and fourth parameters the dataset
where for training and the number of folds.
(classifier-evaluate *classifier* :cross-validation *training* 10)
The metrics available in the evaluation are listed below:
- :correct
Number of instances correctly classified
- :incorrect
Number of instances incorrectly evaluated
- :unclassified
Number of instances incorrectly classified
- :percentage-correct
Percentage of correctly classified instances
- :percentage-incorrect
Percentage of incorrectly classified instances
- :percentage-unclassified
Percentage of not classified instances
- :error-rate
- :mean-absolute-error
- :relative-absolute-error
- :root-mean-squared-error
- :root-relative-squared-error
- :correlation-coefficient
- :average-cost
- :kappa
The kappa statistic
- :kb-information
- :kb-mean-information
- :kb-relative-information
- :sf-entropy-gain
- :sf-mean-entropy-gain
- :roc-area
- :false-positive-rate
- :false-negative-rate
- :f-measure
- :precision
- :recall
- :evaluation-object
The underlying Weka's Java object containing the evaluation
"
(fn [classifier mode & evaluation-data] mode))
(defmethod classifier-evaluate :dataset
([^Classifier classifier mode & [training-data test-data]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.evaluateModel evaluation c test-data (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
(defmethod classifier-evaluate :cross-validation
([classifier mode & [training-data folds]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.crossValidateModel evaluation c training-data folds
(new Random (.getTime (new Date))) (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
;; Classifying instances
(defn classifier-classify
"Classifies an instance using the provided classifier. Returns the
class as a keyword."
([^Classifier classifier ^Instance instance]
(let [pred (.classifyInstance classifier instance)]
(keyword (.value (.classAttribute instance) pred)))))
(defn classifier-predict-numeric
"Predicts the class attribute of an instance using the provided
classifier. Returns the value as a floating-point value (e.g., for
regression)."
([^Classifier classifier ^Instance instance]
(.classifyInstance classifier instance)))
(defn classifier-label
"Classifies and assign a label to a dataset instance.
The function returns the newly classified instance. This call is
destructive, the instance passed as an argument is modified."
([^Classifier classifier ^Instance instance]
(let [cls (.classifyInstance classifier instance)]
(doto instance (.setClassValue cls)))))
|
35256
|
;;
;; Classifiers
;; @author <NAME>
;;
(ns #^{:author "<NAME> <<EMAIL>>"}
clj-ml.classifiers
"This namespace contains several functions for building classifiers using different
classification algorithms: Bayes networks, multilayer perceptron, decision tree or
support vector machines are available. Some of these classifiers have incremental
versions so they can be built without having all the dataset instances in memory.
Functions for evaluating the classifiers built using cross validation or a training
set are also provided.
A sample use of the API for classifiers is shown below:
(use 'clj-ml.classifiers)
; Building a classifier using a C4.5 decision tree
(def *classifier* (make-classifier :decision-tree :c45))
; We set the class attribute for the loaded dataset.
; *dataset* is supposed to contain a set of instances.
(dataset-set-class *dataset* 4)
; Training the classifier
(classifier-train *classifier* *dataset*)
; We evaluate the classifier using a test dataset
(def *evaluation* (classifier-evaluate *classifier* :dataset *dataset* *trainingset*))
; We retrieve some data from the evaluation result
(:kappa *evaluation*)
(:root-mean-squared-error *evaluation*)
(:precision *evaluation*)
; A trained classifier can be used to classify new instances
(def *to-classify* (make-instance *dataset* {:class :Iris-versicolor
:petalwidth 0.2
:petallength 1.4
:sepalwidth 3.5
:sepallength 5.1}))
; We retrieve the index of the class value assigned by the classifier
(classifier-classify *classifier* *to-classify*)
; We retrieve a symbol with the value assigned by the classifier
; and assigns it to a certain instance
(classifier-label *classifier* *to-classify*)
A classifier can also be trained using cross-validation:
(classifier-evaluate *classifier* :cross-validation *dataset* 10)
Finally a classifier can be stored in a file for later use:
(use 'clj-ml.utils)
(serialize-to-file *classifier*
\"/Users/antonio.garrote/Desktop/classifier.bin\")
"
(:use [clj-ml utils data kernel-functions options-utils])
(:import (java.util Date Random)
(weka.core Instance Instances)
(weka.classifiers.lazy IBk)
(weka.classifiers.trees J48 RandomForest M5P)
(weka.classifiers.meta LogitBoost AdditiveRegression RotationForest)
(weka.classifiers.bayes NaiveBayes NaiveBayesUpdateable)
(weka.classifiers.functions MultilayerPerceptron SMO LinearRegression Logistic PaceRegression SPegasos LibSVM)
(weka.classifiers AbstractClassifier Classifier Evaluation)))
;; Setting up classifier options
(defmulti #^{:skip-wiki true}
make-classifier-options
"Creates the right parameters for a classifier. Returns the parameters as a Clojure vector."
(fn [kind algorithm map] [kind algorithm]))
(defmethod make-classifier-options [:lazy :ibk]
([kind algorithm m]
(->> (check-options m
{:inverse-weighted "-I"
:similarity-weighted "-F"
:no-normalization "-N"})
(check-option-values m
{:num-neighbors "-K"}))))
(defmethod make-classifier-options [:decision-tree :c45]
([kind algorithm m]
(->> (check-options m
{:unpruned "-U"
:reduced-error-pruning "-R"
:only-binary-splits "-B"
:no-raising "-S"
:no-cleanup "-L"
:laplace-smoothing "-A"})
(check-option-values m
{:pruning-confidence "-C"
:minimum-instances "-M"
:pruning-number-folds "-N"
:random-seed "-Q"}))))
(defmethod make-classifier-options [:bayes :naive]
([kind algorithm m]
(check-options m
{:kernel-estimator "-K"
:supervised-discretization "-D"
:old-format "-O"})))
(defmethod make-classifier-options [:neural-network :multilayer-perceptron]
([kind algorithm m]
(->> (check-options m
{:no-nominal-to-binary "-B"
:no-numeric-normalization "-C"
:no-normalization "-I"
:no-reset "-R"
:learning-rate-decay "-D"})
(check-option-values m
{:learning-rate "-L"
:momentum "-M"
:epochs "-N"
:percentage-validation-set "-V"
:random-seed "-S"
:threshold-number-errors "-E"
:hidden-layers-string "-H"}))))
(defmethod make-classifier-options [:support-vector-machine :smo]
([kind algorithm m]
(->> (check-options m {:fit-logistic-models "-M"})
(check-option-values m
{:complexity-constant "-C"
:normalize "-N"
:tolerance "-L"
:epsilon-roundoff "-P"
:folds-for-cross-validation "-V"
:random-seed "-W"}))))
(defmethod make-classifier-options [:support-vector-machine :spegasos]
([kind algorithm m]
(->> (check-options m {:no-normalization "-N"
:no-replace-missing"-M"})
(check-option-values m
{:loss-fn "-F"
:epochs "-E"
:lambda "-L"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-gamma "-G"
:kernel-coef0 "-R"
:param-C "-C"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm-grid]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-coef0 "-R"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:regression :linear]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:keep-colinear "-C"})
(check-option-values m
{:attribute-selection "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :logistic]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:max-iterations "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :pace]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:shrinkage "-S"
:estimator "-E"}))))
(defmethod make-classifier-options [:regression :boosted-regression]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:threshold "-S"
:num-iterations "-I"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :boosted-stump]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:resampling "-Q"})
(check-option-values m
{:weak-learning-class "-W"
:num-iterations "-I"
:random-seed "-S"
:percentage-weight-mass "-P"
:folds-for-cross-validation "-F"
:runs-for-cross-validation "-R"
:log-likelihood-improvement-threshold "-L"
:shrinkage-parameter "-H"}))))
(defmethod make-classifier-options [:decision-tree :random-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-trees-in-forest "-I"
:num-features-to-consider "-K"
:random-seed "-S"
:depth "-depth"}))))
(defmethod make-classifier-options [:decision-tree :rotation-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-iterations "-I"
:use-number-of-groups "-N"
:min-attribute-group-size "-G"
:max-attribute-group-size "-H"
:percentage-of-instances-to-remove "-P"
:filter "-F"
:random-seed "-S"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :m5p]
([kind algorithm m]
(->>
(check-options m {:unsmoothed-predictions "-U"
:regression "-R"
:unpruned "-N"})
(check-option-values m {:minimum-instances "-M"}))))
;; Building classifiers
(defn make-classifier-with
#^{:skip-wiki true}
[kind algorithm ^Class classifier-class options]
(capture-out-err
(let [options-read (if (empty? options) {} (first options))
^Classifier classifier (.newInstance classifier-class)
opts (into-array String (make-classifier-options kind algorithm options-read))]
(.setOptions classifier opts)
classifier)))
(defmulti make-classifier
"Creates a new classifier for the given kind algorithm and options.
The first argument identifies the kind of classifier and the second
argument the algorithm to use, e.g. :decision-tree :c45.
The classifiers currently supported are:
- :lazy :ibk
- :decision-tree :c45
- :decision-tree :boosted-stump
- :decision-tree :boosted-decision-tree
- :decision-tree :M5P
- :decision-tree :random-forest
- :decision-tree :rotation-forest
- :bayes :naive
- :neural-network :mutilayer-perceptron
- :support-vector-machine :smo
- :regression :linear
- :regression :logistic
- :regression :pace
Optionally, a map of options can also be passed as an argument with
a set of classifier specific options.
This is the description of the supported classifiers and the accepted
option parameters for each of them:
* :lazy :ibk
K-nearest neighbor classification.
Parameters:
- :inverse-weighted
Neighbors will be weighted by the inverse of their distance when voting. (default equal weighting)
Sample value: true
- :similarity-weighted
Neighbors will be weighted by their similarity when voting. (default equal weighting)
Sample value: true
- :no-normalization
Turns off normalization.
Sample value: true
- :num-neighbors
Set the number of nearest neighbors to use in prediction (default 1)
Sample value: 3
* :decision-tree :c45
A classifier building a pruned or unpruned C 4.5 decision tree using
Weka J 4.8 implementation.
Parameters:
- :unpruned
Use unpruned tree. Sample value: true
- :reduce-error-pruning
Sample value: true
- :only-binary-splits
Sample value: true
- :no-raising
Sample value: true
- :no-cleanup
Sample value: true
- :laplace-smoothing
For predicted probabilities. Sample value: true
- :pruning-confidence
Threshold for pruning. Default value: 0.25
- :minimum-instances
Minimum number of instances per leave. Default value: 2
- :pruning-number-folds
Set number of folds for reduced error pruning. Default value: 3
- :random-seed
Seed for random data shuffling. Default value: 1
* :bayes :naive
Classifier based on the Bayes' theorem with strong independence assumptions, among the
probabilistic variables.
Parameters:
- :kernel-estimator
Use kernel desity estimator rather than normal. Sample value: true
- :supervised-discretization
Use supervised discretization to to process numeric attributes (see :supervised-discretize
filter in clj-ml.filters/make-filter function). Sample value: true
* :neural-network :multilayer-perceptron
Classifier built using a feedforward artificial neural network with three or more layers
of neurons and nonlinear activation functions. It is able to distinguish data that is not
linearly separable.
Parameters:
- :no-nominal-to-binary
A :nominal-to-binary filter will not be applied by default. (see :supervised-nominal-to-binary
filter in clj-ml.filters/make-filter function). Default value: false
- :no-numeric-normalization
A numeric class will not be normalized. Default value: false
- :no-normalization
No attribute will be normalized. Default value: false
- :no-reset
Reseting the network will not be allowed. Default value: false
- :learning-rate-decay
Learning rate decay will occur. Default value: false
- :learning-rate
Learning rate for the backpropagation algorithm. Value should be between [0,1].
Default value: 0.3
- :momentum
Momentum rate for the backpropagation algorithm. Value shuld be between [0,1].
Default value: 0.2
- :epochs
Number of iteration to train through. Default value: 500
- :percentage-validation-set
Percentage size of validation set to use to terminate training. If it is not zero
it takes precende over the number of epochs to finish training. Values should be
between [0,100]. Default value: 0
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
- :threshold-number-errors
The consequetive number of errors allowed for validation testing before the network
terminates. Values should be greater thant 0. Default value: 20
* :support-vector-machine :smo
Support vector machine (SVM) classifier built using the sequential minimal optimization (SMO)
training algorithm.
Parameters:
- :fit-logistic-models
Fit logistic models to SVM outputs. Default value :false
- :complexity-constant
The complexity constance. Default value: 1
- :tolerance
Tolerance parameter. Default value: 1.0e-3
- :epsilon-roundoff
Epsilon round-off error. Default value: 1.0e-12
- :folds-for-cross-validation
Number of folds for the internal cross-validation. Sample value: 10
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
* :support-vector-machine :libsvm
TODO
* :regression :linear
Parameters:
- :attribute-selection
Set the attribute selection method to use. 1 = None, 2 = Greedy. (default 0 = M5' method)
- :keep-colinear
Do not try to eliminate colinear attributes.
- :ridge
Set ridge parameter (default 1.0e-8).
* :regression :logistic
Parameters:
- :max-iterations
Set the maximum number of iterations (default -1, until convergence).
- :ridge
Set the ridge in the log-likelihood.
"
(fn [kind algorithm & options] [kind algorithm]))
(defmethod make-classifier [:lazy :ibk]
([kind algorithm & options]
(make-classifier-with kind algorithm IBk options)))
(defmethod make-classifier [:decision-tree :c45]
([kind algorithm & options]
(make-classifier-with kind algorithm J48 options)))
(defmethod make-classifier [:bayes :naive]
([kind algorithm & options]
(if (or (nil? (:updateable (first options)))
(= (:updateable (first options)) false))
(make-classifier-with kind algorithm NaiveBayes options)
(make-classifier-with kind algorithm NaiveBayesUpdateable options))))
(defmethod make-classifier [:neural-network :multilayer-perceptron]
([kind algorithm & options]
(make-classifier-with kind algorithm MultilayerPerceptron options)))
(defmethod make-classifier [:support-vector-machine :smo]
([kind algorithm & options]
(let [options-read (if (empty? options) {} (first options))
classifier (new SMO)
opts (into-array String (make-classifier-options :support-vector-machine :smo options-read))]
(.setOptions classifier opts)
(when (not (empty? (get options-read :kernel-function)))
;; We have to setup a different kernel function
(let [kernel (get options-read :kernel-function)
real-kernel (if (map? kernel)
(make-kernel-function (first (keys kernel))
(first (vals kernel)))
kernel)]
(.setKernel classifier real-kernel)))
classifier)))
(defmethod make-classifier [:support-vector-machine :spegasos]
([kind algorithm & options]
(make-classifier-with kind algorithm SPegasos options)))
(defmethod make-classifier [:support-vector-machine :libsvm]
([kind algorithm & options]
(make-classifier-with kind algorithm LibSVM options)))
(defmethod make-classifier [:support-vector-machine :libsvm-grid]
([kind algorithm & options]
(for [c (range -5 17 2) g (range 3 -17 -2)]
(make-classifier-with
:support-vector-machine :libsvm
LibSVM (concat options [:param-C (Math/pow 2.0 c)
:kernel-gamma (Math/pow 2.0 g)])))))
(defmethod make-classifier [:regression :linear]
([kind algorithm & options]
(make-classifier-with kind algorithm LinearRegression options)))
(defmethod make-classifier [:regression :logistic]
([kind algorithm & options]
(make-classifier-with kind algorithm Logistic options)))
(defmethod make-classifier [:regression :pace]
([kind algorithm & options]
(make-classifier-with kind algorithm PaceRegression options)))
(defmethod make-classifier [:regression :boosted-regression]
([kind algorithm & options]
(make-classifier-with kind algorithm AdditiveRegression options)))
(defmethod make-classifier [:decision-tree :boosted-stump]
([kind algorithm & options]
(make-classifier-with kind algorithm LogitBoost options)))
(defmethod make-classifier [:decision-tree :random-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RandomForest options)))
(defmethod make-classifier [:decision-tree :rotation-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RotationForest options)))
(defmethod make-classifier [:decision-tree :m5p]
([kind algorithm & options]
(make-classifier-with kind algorithm M5P options)))
;; Training classifiers
(defn classifier-train
"Trains a classifier with the given dataset as the training data."
([^Classifier classifier dataset]
(do (.buildClassifier classifier dataset)
classifier)))
(defn classifier-copy
"Performs a deep copy of the classifier"
[^Classifier classifier]
(AbstractClassifier/makeCopy classifier))
(defn classifier-copy-and-train
"Performs a deep copy of the classifier, trains the copy, and returns it."
[classifier dataset]
(classifier-train (classifier-copy classifier) dataset))
(defn classifier-update
"If the classifier is updateable it updates the classifier with the given instance or set of instances."
([^Classifier classifier instance-s]
;; Arg... weka doesn't provide a formal interface for updateClassifer- How do I type hint this?
(if (is-dataset? instance-s)
(do (doseq [i (dataset-seq instance-s)]
(.updateClassifier classifier ^Instance i))
classifier)
(do (.updateClassifier classifier ^Instance instance-s)
classifier))))
;; Evaluating classifiers
(defn- collect-evaluation-results
"Collects all the statistics from the evaluation of a classifier."
([class-labels ^Evaluation evaluation]
{:confusion-matrix (.toMatrixString evaluation)
:summary (.toSummaryString evaluation)
:correct (try-metric #(.correct evaluation))
:incorrect (try-metric #(.incorrect evaluation))
:unclassified (try-metric #(.unclassified evaluation))
:percentage-correct (try-metric #(.pctCorrect evaluation))
:percentage-incorrect (try-metric #(.pctIncorrect evaluation))
:percentage-unclassified (try-metric #(.pctUnclassified evaluation))
:error-rate (try-metric #(.errorRate evaluation))
:mean-absolute-error (try-metric #(.meanAbsoluteError evaluation))
:relative-absolute-error (try-metric #(.relativeAbsoluteError evaluation))
:root-mean-squared-error (try-metric #(.rootMeanSquaredError evaluation))
:root-relative-squared-error (try-metric #(.rootRelativeSquaredError evaluation))
:correlation-coefficient (try-metric #(.correlationCoefficient evaluation))
:average-cost (try-metric #(.avgCost evaluation))
:kappa (try-metric #(.kappa evaluation))
:kb-information (try-metric #(.KBInformation evaluation))
:kb-mean-information (try-metric #(.KBMeanInformation evaluation))
:kb-relative-information (try-metric #(.KBRelativeInformation evaluation))
:sf-entropy-gain (try-metric #(.SFEntropyGain evaluation))
:sf-mean-entropy-gain (try-metric #(.SFMeanEntropyGain evaluation))
:roc-area (try-multiple-values-metric class-labels (fn [i] (try-metric #(.areaUnderROC evaluation i))))
:false-positive-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falsePositiveRate evaluation i))))
:false-negative-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falseNegativeRate evaluation i))))
:f-measure (try-multiple-values-metric class-labels (fn [i] (try-metric #(.fMeasure evaluation i))))
:precision (try-multiple-values-metric class-labels (fn [i] (try-metric #(.precision evaluation i))))
:recall (try-multiple-values-metric class-labels (fn [i] (try-metric #(.recall evaluation i))))
:evaluation-object evaluation}))
(defmulti classifier-evaluate
"Evaluates a trained classifier using the provided dataset or cross-validation.
The first argument must be the classifier to evaluate, the second argument is
the kind of evaluation to do.
Two possible evaluations ara availabe: dataset and cross-validations. The values
for the second argument can be:
- :dataset
- :cross-validation
* :dataset
If dataset evaluation is desired, the function call must receive as the second
parameter the keyword :dataset and as third and fourth parameters the original
dataset used to build the classifier and the training data:
(classifier-evaluate *classifier* :dataset *training* *evaluation*)
* :cross-validation
If cross-validation is desired, the function call must receive as the second
parameter the keyword :cross-validation and as third and fourth parameters the dataset
where for training and the number of folds.
(classifier-evaluate *classifier* :cross-validation *training* 10)
The metrics available in the evaluation are listed below:
- :correct
Number of instances correctly classified
- :incorrect
Number of instances incorrectly evaluated
- :unclassified
Number of instances incorrectly classified
- :percentage-correct
Percentage of correctly classified instances
- :percentage-incorrect
Percentage of incorrectly classified instances
- :percentage-unclassified
Percentage of not classified instances
- :error-rate
- :mean-absolute-error
- :relative-absolute-error
- :root-mean-squared-error
- :root-relative-squared-error
- :correlation-coefficient
- :average-cost
- :kappa
The kappa statistic
- :kb-information
- :kb-mean-information
- :kb-relative-information
- :sf-entropy-gain
- :sf-mean-entropy-gain
- :roc-area
- :false-positive-rate
- :false-negative-rate
- :f-measure
- :precision
- :recall
- :evaluation-object
The underlying Weka's Java object containing the evaluation
"
(fn [classifier mode & evaluation-data] mode))
(defmethod classifier-evaluate :dataset
([^Classifier classifier mode & [training-data test-data]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.evaluateModel evaluation c test-data (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
(defmethod classifier-evaluate :cross-validation
([classifier mode & [training-data folds]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.crossValidateModel evaluation c training-data folds
(new Random (.getTime (new Date))) (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
;; Classifying instances
(defn classifier-classify
"Classifies an instance using the provided classifier. Returns the
class as a keyword."
([^Classifier classifier ^Instance instance]
(let [pred (.classifyInstance classifier instance)]
(keyword (.value (.classAttribute instance) pred)))))
(defn classifier-predict-numeric
"Predicts the class attribute of an instance using the provided
classifier. Returns the value as a floating-point value (e.g., for
regression)."
([^Classifier classifier ^Instance instance]
(.classifyInstance classifier instance)))
(defn classifier-label
"Classifies and assign a label to a dataset instance.
The function returns the newly classified instance. This call is
destructive, the instance passed as an argument is modified."
([^Classifier classifier ^Instance instance]
(let [cls (.classifyInstance classifier instance)]
(doto instance (.setClassValue cls)))))
| true |
;;
;; Classifiers
;; @author PI:NAME:<NAME>END_PI
;;
(ns #^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"}
clj-ml.classifiers
"This namespace contains several functions for building classifiers using different
classification algorithms: Bayes networks, multilayer perceptron, decision tree or
support vector machines are available. Some of these classifiers have incremental
versions so they can be built without having all the dataset instances in memory.
Functions for evaluating the classifiers built using cross validation or a training
set are also provided.
A sample use of the API for classifiers is shown below:
(use 'clj-ml.classifiers)
; Building a classifier using a C4.5 decision tree
(def *classifier* (make-classifier :decision-tree :c45))
; We set the class attribute for the loaded dataset.
; *dataset* is supposed to contain a set of instances.
(dataset-set-class *dataset* 4)
; Training the classifier
(classifier-train *classifier* *dataset*)
; We evaluate the classifier using a test dataset
(def *evaluation* (classifier-evaluate *classifier* :dataset *dataset* *trainingset*))
; We retrieve some data from the evaluation result
(:kappa *evaluation*)
(:root-mean-squared-error *evaluation*)
(:precision *evaluation*)
; A trained classifier can be used to classify new instances
(def *to-classify* (make-instance *dataset* {:class :Iris-versicolor
:petalwidth 0.2
:petallength 1.4
:sepalwidth 3.5
:sepallength 5.1}))
; We retrieve the index of the class value assigned by the classifier
(classifier-classify *classifier* *to-classify*)
; We retrieve a symbol with the value assigned by the classifier
; and assigns it to a certain instance
(classifier-label *classifier* *to-classify*)
A classifier can also be trained using cross-validation:
(classifier-evaluate *classifier* :cross-validation *dataset* 10)
Finally a classifier can be stored in a file for later use:
(use 'clj-ml.utils)
(serialize-to-file *classifier*
\"/Users/antonio.garrote/Desktop/classifier.bin\")
"
(:use [clj-ml utils data kernel-functions options-utils])
(:import (java.util Date Random)
(weka.core Instance Instances)
(weka.classifiers.lazy IBk)
(weka.classifiers.trees J48 RandomForest M5P)
(weka.classifiers.meta LogitBoost AdditiveRegression RotationForest)
(weka.classifiers.bayes NaiveBayes NaiveBayesUpdateable)
(weka.classifiers.functions MultilayerPerceptron SMO LinearRegression Logistic PaceRegression SPegasos LibSVM)
(weka.classifiers AbstractClassifier Classifier Evaluation)))
;; Setting up classifier options
(defmulti #^{:skip-wiki true}
make-classifier-options
"Creates the right parameters for a classifier. Returns the parameters as a Clojure vector."
(fn [kind algorithm map] [kind algorithm]))
(defmethod make-classifier-options [:lazy :ibk]
([kind algorithm m]
(->> (check-options m
{:inverse-weighted "-I"
:similarity-weighted "-F"
:no-normalization "-N"})
(check-option-values m
{:num-neighbors "-K"}))))
(defmethod make-classifier-options [:decision-tree :c45]
([kind algorithm m]
(->> (check-options m
{:unpruned "-U"
:reduced-error-pruning "-R"
:only-binary-splits "-B"
:no-raising "-S"
:no-cleanup "-L"
:laplace-smoothing "-A"})
(check-option-values m
{:pruning-confidence "-C"
:minimum-instances "-M"
:pruning-number-folds "-N"
:random-seed "-Q"}))))
(defmethod make-classifier-options [:bayes :naive]
([kind algorithm m]
(check-options m
{:kernel-estimator "-K"
:supervised-discretization "-D"
:old-format "-O"})))
(defmethod make-classifier-options [:neural-network :multilayer-perceptron]
([kind algorithm m]
(->> (check-options m
{:no-nominal-to-binary "-B"
:no-numeric-normalization "-C"
:no-normalization "-I"
:no-reset "-R"
:learning-rate-decay "-D"})
(check-option-values m
{:learning-rate "-L"
:momentum "-M"
:epochs "-N"
:percentage-validation-set "-V"
:random-seed "-S"
:threshold-number-errors "-E"
:hidden-layers-string "-H"}))))
(defmethod make-classifier-options [:support-vector-machine :smo]
([kind algorithm m]
(->> (check-options m {:fit-logistic-models "-M"})
(check-option-values m
{:complexity-constant "-C"
:normalize "-N"
:tolerance "-L"
:epsilon-roundoff "-P"
:folds-for-cross-validation "-V"
:random-seed "-W"}))))
(defmethod make-classifier-options [:support-vector-machine :spegasos]
([kind algorithm m]
(->> (check-options m {:no-normalization "-N"
:no-replace-missing"-M"})
(check-option-values m
{:loss-fn "-F"
:epochs "-E"
:lambda "-L"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-gamma "-G"
:kernel-coef0 "-R"
:param-C "-C"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:support-vector-machine :libsvm-grid]
([kind algorithm m]
(->> (check-options m {:normalization "-Z"
:no-nominal-to-binary "-J"
:no-missing-value-replacement "-V"
:no-shrinking-heuristics "-H"
:probability-estimates "-B"})
(check-option-values m
{:svm-type "-S"
:kernel-type "-K"
:kernel-degree "-D"
:kernel-coef0 "-R"
:param-nu "-N"
:loss-epsilon "-P"
:memory-cache "-M"
:tolerance-of-termination "-E"
:class-weight "-W"
:random-seed "-seed"}))))
(defmethod make-classifier-options [:regression :linear]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:keep-colinear "-C"})
(check-option-values m
{:attribute-selection "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :logistic]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:max-iterations "-S"
:ridge "-R"}))))
(defmethod make-classifier-options [:regression :pace]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:shrinkage "-S"
:estimator "-E"}))))
(defmethod make-classifier-options [:regression :boosted-regression]
([kind algorithm m]
(->> (check-options m {:debug "-D"})
(check-option-values m
{:threshold "-S"
:num-iterations "-I"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :boosted-stump]
([kind algorithm m]
(->> (check-options m {:debug "-D"
:resampling "-Q"})
(check-option-values m
{:weak-learning-class "-W"
:num-iterations "-I"
:random-seed "-S"
:percentage-weight-mass "-P"
:folds-for-cross-validation "-F"
:runs-for-cross-validation "-R"
:log-likelihood-improvement-threshold "-L"
:shrinkage-parameter "-H"}))))
(defmethod make-classifier-options [:decision-tree :random-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-trees-in-forest "-I"
:num-features-to-consider "-K"
:random-seed "-S"
:depth "-depth"}))))
(defmethod make-classifier-options [:decision-tree :rotation-forest]
([kind algorithm m]
(->>
(check-options m {:debug "-D"})
(check-option-values m
{:num-iterations "-I"
:use-number-of-groups "-N"
:min-attribute-group-size "-G"
:max-attribute-group-size "-H"
:percentage-of-instances-to-remove "-P"
:filter "-F"
:random-seed "-S"
:weak-learning-class "-W"}))))
(defmethod make-classifier-options [:decision-tree :m5p]
([kind algorithm m]
(->>
(check-options m {:unsmoothed-predictions "-U"
:regression "-R"
:unpruned "-N"})
(check-option-values m {:minimum-instances "-M"}))))
;; Building classifiers
(defn make-classifier-with
#^{:skip-wiki true}
[kind algorithm ^Class classifier-class options]
(capture-out-err
(let [options-read (if (empty? options) {} (first options))
^Classifier classifier (.newInstance classifier-class)
opts (into-array String (make-classifier-options kind algorithm options-read))]
(.setOptions classifier opts)
classifier)))
(defmulti make-classifier
"Creates a new classifier for the given kind algorithm and options.
The first argument identifies the kind of classifier and the second
argument the algorithm to use, e.g. :decision-tree :c45.
The classifiers currently supported are:
- :lazy :ibk
- :decision-tree :c45
- :decision-tree :boosted-stump
- :decision-tree :boosted-decision-tree
- :decision-tree :M5P
- :decision-tree :random-forest
- :decision-tree :rotation-forest
- :bayes :naive
- :neural-network :mutilayer-perceptron
- :support-vector-machine :smo
- :regression :linear
- :regression :logistic
- :regression :pace
Optionally, a map of options can also be passed as an argument with
a set of classifier specific options.
This is the description of the supported classifiers and the accepted
option parameters for each of them:
* :lazy :ibk
K-nearest neighbor classification.
Parameters:
- :inverse-weighted
Neighbors will be weighted by the inverse of their distance when voting. (default equal weighting)
Sample value: true
- :similarity-weighted
Neighbors will be weighted by their similarity when voting. (default equal weighting)
Sample value: true
- :no-normalization
Turns off normalization.
Sample value: true
- :num-neighbors
Set the number of nearest neighbors to use in prediction (default 1)
Sample value: 3
* :decision-tree :c45
A classifier building a pruned or unpruned C 4.5 decision tree using
Weka J 4.8 implementation.
Parameters:
- :unpruned
Use unpruned tree. Sample value: true
- :reduce-error-pruning
Sample value: true
- :only-binary-splits
Sample value: true
- :no-raising
Sample value: true
- :no-cleanup
Sample value: true
- :laplace-smoothing
For predicted probabilities. Sample value: true
- :pruning-confidence
Threshold for pruning. Default value: 0.25
- :minimum-instances
Minimum number of instances per leave. Default value: 2
- :pruning-number-folds
Set number of folds for reduced error pruning. Default value: 3
- :random-seed
Seed for random data shuffling. Default value: 1
* :bayes :naive
Classifier based on the Bayes' theorem with strong independence assumptions, among the
probabilistic variables.
Parameters:
- :kernel-estimator
Use kernel desity estimator rather than normal. Sample value: true
- :supervised-discretization
Use supervised discretization to to process numeric attributes (see :supervised-discretize
filter in clj-ml.filters/make-filter function). Sample value: true
* :neural-network :multilayer-perceptron
Classifier built using a feedforward artificial neural network with three or more layers
of neurons and nonlinear activation functions. It is able to distinguish data that is not
linearly separable.
Parameters:
- :no-nominal-to-binary
A :nominal-to-binary filter will not be applied by default. (see :supervised-nominal-to-binary
filter in clj-ml.filters/make-filter function). Default value: false
- :no-numeric-normalization
A numeric class will not be normalized. Default value: false
- :no-normalization
No attribute will be normalized. Default value: false
- :no-reset
Reseting the network will not be allowed. Default value: false
- :learning-rate-decay
Learning rate decay will occur. Default value: false
- :learning-rate
Learning rate for the backpropagation algorithm. Value should be between [0,1].
Default value: 0.3
- :momentum
Momentum rate for the backpropagation algorithm. Value shuld be between [0,1].
Default value: 0.2
- :epochs
Number of iteration to train through. Default value: 500
- :percentage-validation-set
Percentage size of validation set to use to terminate training. If it is not zero
it takes precende over the number of epochs to finish training. Values should be
between [0,100]. Default value: 0
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
- :threshold-number-errors
The consequetive number of errors allowed for validation testing before the network
terminates. Values should be greater thant 0. Default value: 20
* :support-vector-machine :smo
Support vector machine (SVM) classifier built using the sequential minimal optimization (SMO)
training algorithm.
Parameters:
- :fit-logistic-models
Fit logistic models to SVM outputs. Default value :false
- :complexity-constant
The complexity constance. Default value: 1
- :tolerance
Tolerance parameter. Default value: 1.0e-3
- :epsilon-roundoff
Epsilon round-off error. Default value: 1.0e-12
- :folds-for-cross-validation
Number of folds for the internal cross-validation. Sample value: 10
- :random-seed
Value of the seed for the random generator. Values should be longs greater than
0. Default value: 1
* :support-vector-machine :libsvm
TODO
* :regression :linear
Parameters:
- :attribute-selection
Set the attribute selection method to use. 1 = None, 2 = Greedy. (default 0 = M5' method)
- :keep-colinear
Do not try to eliminate colinear attributes.
- :ridge
Set ridge parameter (default 1.0e-8).
* :regression :logistic
Parameters:
- :max-iterations
Set the maximum number of iterations (default -1, until convergence).
- :ridge
Set the ridge in the log-likelihood.
"
(fn [kind algorithm & options] [kind algorithm]))
(defmethod make-classifier [:lazy :ibk]
([kind algorithm & options]
(make-classifier-with kind algorithm IBk options)))
(defmethod make-classifier [:decision-tree :c45]
([kind algorithm & options]
(make-classifier-with kind algorithm J48 options)))
(defmethod make-classifier [:bayes :naive]
([kind algorithm & options]
(if (or (nil? (:updateable (first options)))
(= (:updateable (first options)) false))
(make-classifier-with kind algorithm NaiveBayes options)
(make-classifier-with kind algorithm NaiveBayesUpdateable options))))
(defmethod make-classifier [:neural-network :multilayer-perceptron]
([kind algorithm & options]
(make-classifier-with kind algorithm MultilayerPerceptron options)))
(defmethod make-classifier [:support-vector-machine :smo]
([kind algorithm & options]
(let [options-read (if (empty? options) {} (first options))
classifier (new SMO)
opts (into-array String (make-classifier-options :support-vector-machine :smo options-read))]
(.setOptions classifier opts)
(when (not (empty? (get options-read :kernel-function)))
;; We have to setup a different kernel function
(let [kernel (get options-read :kernel-function)
real-kernel (if (map? kernel)
(make-kernel-function (first (keys kernel))
(first (vals kernel)))
kernel)]
(.setKernel classifier real-kernel)))
classifier)))
(defmethod make-classifier [:support-vector-machine :spegasos]
([kind algorithm & options]
(make-classifier-with kind algorithm SPegasos options)))
(defmethod make-classifier [:support-vector-machine :libsvm]
([kind algorithm & options]
(make-classifier-with kind algorithm LibSVM options)))
(defmethod make-classifier [:support-vector-machine :libsvm-grid]
([kind algorithm & options]
(for [c (range -5 17 2) g (range 3 -17 -2)]
(make-classifier-with
:support-vector-machine :libsvm
LibSVM (concat options [:param-C (Math/pow 2.0 c)
:kernel-gamma (Math/pow 2.0 g)])))))
(defmethod make-classifier [:regression :linear]
([kind algorithm & options]
(make-classifier-with kind algorithm LinearRegression options)))
(defmethod make-classifier [:regression :logistic]
([kind algorithm & options]
(make-classifier-with kind algorithm Logistic options)))
(defmethod make-classifier [:regression :pace]
([kind algorithm & options]
(make-classifier-with kind algorithm PaceRegression options)))
(defmethod make-classifier [:regression :boosted-regression]
([kind algorithm & options]
(make-classifier-with kind algorithm AdditiveRegression options)))
(defmethod make-classifier [:decision-tree :boosted-stump]
([kind algorithm & options]
(make-classifier-with kind algorithm LogitBoost options)))
(defmethod make-classifier [:decision-tree :random-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RandomForest options)))
(defmethod make-classifier [:decision-tree :rotation-forest]
([kind algorithm & options]
(make-classifier-with kind algorithm RotationForest options)))
(defmethod make-classifier [:decision-tree :m5p]
([kind algorithm & options]
(make-classifier-with kind algorithm M5P options)))
;; Training classifiers
(defn classifier-train
"Trains a classifier with the given dataset as the training data."
([^Classifier classifier dataset]
(do (.buildClassifier classifier dataset)
classifier)))
(defn classifier-copy
"Performs a deep copy of the classifier"
[^Classifier classifier]
(AbstractClassifier/makeCopy classifier))
(defn classifier-copy-and-train
"Performs a deep copy of the classifier, trains the copy, and returns it."
[classifier dataset]
(classifier-train (classifier-copy classifier) dataset))
(defn classifier-update
"If the classifier is updateable it updates the classifier with the given instance or set of instances."
([^Classifier classifier instance-s]
;; Arg... weka doesn't provide a formal interface for updateClassifer- How do I type hint this?
(if (is-dataset? instance-s)
(do (doseq [i (dataset-seq instance-s)]
(.updateClassifier classifier ^Instance i))
classifier)
(do (.updateClassifier classifier ^Instance instance-s)
classifier))))
;; Evaluating classifiers
(defn- collect-evaluation-results
"Collects all the statistics from the evaluation of a classifier."
([class-labels ^Evaluation evaluation]
{:confusion-matrix (.toMatrixString evaluation)
:summary (.toSummaryString evaluation)
:correct (try-metric #(.correct evaluation))
:incorrect (try-metric #(.incorrect evaluation))
:unclassified (try-metric #(.unclassified evaluation))
:percentage-correct (try-metric #(.pctCorrect evaluation))
:percentage-incorrect (try-metric #(.pctIncorrect evaluation))
:percentage-unclassified (try-metric #(.pctUnclassified evaluation))
:error-rate (try-metric #(.errorRate evaluation))
:mean-absolute-error (try-metric #(.meanAbsoluteError evaluation))
:relative-absolute-error (try-metric #(.relativeAbsoluteError evaluation))
:root-mean-squared-error (try-metric #(.rootMeanSquaredError evaluation))
:root-relative-squared-error (try-metric #(.rootRelativeSquaredError evaluation))
:correlation-coefficient (try-metric #(.correlationCoefficient evaluation))
:average-cost (try-metric #(.avgCost evaluation))
:kappa (try-metric #(.kappa evaluation))
:kb-information (try-metric #(.KBInformation evaluation))
:kb-mean-information (try-metric #(.KBMeanInformation evaluation))
:kb-relative-information (try-metric #(.KBRelativeInformation evaluation))
:sf-entropy-gain (try-metric #(.SFEntropyGain evaluation))
:sf-mean-entropy-gain (try-metric #(.SFMeanEntropyGain evaluation))
:roc-area (try-multiple-values-metric class-labels (fn [i] (try-metric #(.areaUnderROC evaluation i))))
:false-positive-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falsePositiveRate evaluation i))))
:false-negative-rate (try-multiple-values-metric class-labels (fn [i] (try-metric #(.falseNegativeRate evaluation i))))
:f-measure (try-multiple-values-metric class-labels (fn [i] (try-metric #(.fMeasure evaluation i))))
:precision (try-multiple-values-metric class-labels (fn [i] (try-metric #(.precision evaluation i))))
:recall (try-multiple-values-metric class-labels (fn [i] (try-metric #(.recall evaluation i))))
:evaluation-object evaluation}))
(defmulti classifier-evaluate
"Evaluates a trained classifier using the provided dataset or cross-validation.
The first argument must be the classifier to evaluate, the second argument is
the kind of evaluation to do.
Two possible evaluations ara availabe: dataset and cross-validations. The values
for the second argument can be:
- :dataset
- :cross-validation
* :dataset
If dataset evaluation is desired, the function call must receive as the second
parameter the keyword :dataset and as third and fourth parameters the original
dataset used to build the classifier and the training data:
(classifier-evaluate *classifier* :dataset *training* *evaluation*)
* :cross-validation
If cross-validation is desired, the function call must receive as the second
parameter the keyword :cross-validation and as third and fourth parameters the dataset
where for training and the number of folds.
(classifier-evaluate *classifier* :cross-validation *training* 10)
The metrics available in the evaluation are listed below:
- :correct
Number of instances correctly classified
- :incorrect
Number of instances incorrectly evaluated
- :unclassified
Number of instances incorrectly classified
- :percentage-correct
Percentage of correctly classified instances
- :percentage-incorrect
Percentage of incorrectly classified instances
- :percentage-unclassified
Percentage of not classified instances
- :error-rate
- :mean-absolute-error
- :relative-absolute-error
- :root-mean-squared-error
- :root-relative-squared-error
- :correlation-coefficient
- :average-cost
- :kappa
The kappa statistic
- :kb-information
- :kb-mean-information
- :kb-relative-information
- :sf-entropy-gain
- :sf-mean-entropy-gain
- :roc-area
- :false-positive-rate
- :false-negative-rate
- :f-measure
- :precision
- :recall
- :evaluation-object
The underlying Weka's Java object containing the evaluation
"
(fn [classifier mode & evaluation-data] mode))
(defmethod classifier-evaluate :dataset
([^Classifier classifier mode & [training-data test-data]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.evaluateModel evaluation c test-data (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
(defmethod classifier-evaluate :cross-validation
([classifier mode & [training-data folds]]
(capture-out-err
(letfn [(eval-fn [c]
(let [evaluation (new Evaluation training-data)
class-labels (dataset-class-labels training-data)]
(.crossValidateModel evaluation c training-data folds
(new Random (.getTime (new Date))) (into-array []))
(collect-evaluation-results class-labels evaluation)))]
(if (seq? classifier)
(last (sort-by :correct (map eval-fn classifier)))
(eval-fn classifier))))))
;; Classifying instances
(defn classifier-classify
"Classifies an instance using the provided classifier. Returns the
class as a keyword."
([^Classifier classifier ^Instance instance]
(let [pred (.classifyInstance classifier instance)]
(keyword (.value (.classAttribute instance) pred)))))
(defn classifier-predict-numeric
"Predicts the class attribute of an instance using the provided
classifier. Returns the value as a floating-point value (e.g., for
regression)."
([^Classifier classifier ^Instance instance]
(.classifyInstance classifier instance)))
(defn classifier-label
"Classifies and assign a label to a dataset instance.
The function returns the newly classified instance. This call is
destructive, the instance passed as an argument is modified."
([^Classifier classifier ^Instance instance]
(let [cls (.classifyInstance classifier instance)]
(doto instance (.setClassValue cls)))))
|
[
{
"context": "j: JavaScript Object Notation (JSON) parser\n\n;; by Stuart Sierra, http://stuartsierra.com/\n;; February 13, 2009\n\n;",
"end": 80,
"score": 0.9998825788497925,
"start": 67,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "sierra.com/\n;; February 13, 2009\n\n;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use\n;; and distr",
"end": 159,
"score": 0.9998732805252075,
"start": 146,
"tag": "NAME",
"value": "Stuart Sierra"
}
] |
data/train/clojure/7276e0893abf54db06b38612e032ee3ccfe618b3read.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
;;; json/read.clj: JavaScript Object Notation (JSON) parser
;; by Stuart Sierra, http://stuartsierra.com/
;; February 13, 2009
;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; Change Log
;;
;; February 13, 2009: added custom handler for quoted strings, to
;; allow escaped forward backslash characters ("\/") in strings.
;;
;; January 26, 2009: initial version
;; For more information on JSON, see http://www.json.org/
;;
;; This library parses data in JSON format. This is a fairly strict
;; implementation of JSON as described at json.org, not a full-fledged
;; JavaScript parser. JavaScript functions and object constructors
;; are not supported. Object field names must be quoted strings; they
;; may not be bare symbols.
(ns clojure.contrib.json.read
(:import (java.io PushbackReader StringReader EOFException))
(:use [clojure.contrib.test-is :only (deftest- is)]))
(declare read-json)
(defn- read-json-array [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), result []]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside array)"))
(Character/isWhitespace c) (recur (.read stream) result)
(= c \,) (recur (.read stream) result)
(= c \]) result
:else (do (.unread stream (int c))
(let [element (read-json stream)]
(recur (.read stream) (conj result element))))))))
(defn- read-json-object [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), key nil, result {}]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside object)"))
(Character/isWhitespace c) (recur (.read stream) key result)
(= c \,) (recur (.read stream) nil result)
(= c \:) (recur (.read stream) key result)
(= c \}) (if (nil? key)
result
(throw (Exception. "JSON error (key missing value in object)")))
:else (do (.unread stream i)
(let [element (read-json stream)]
(if (nil? key)
(if (string? element)
(recur (.read stream) element result)
(throw (Exception. "JSON error (non-string key in object)")))
(recur (.read stream) nil (assoc result key element)))))))))
(defn- read-json-hex-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial "\u". Reads the next four characters from the stream.
(let [digits [(.read stream)
(.read stream)
(.read stream)
(.read stream)]]
(when (some neg? digits)
(throw (EOFException. "JSON error (end-of-file inside Unicode character escape)")))
(let [chars (map char digits)]
(when-not (every? #{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f \A \B \C \D \E \F}
chars)
(throw (Exception. "JSON error (invalid hex character in Unicode character escape)")))
(char (Integer/parseInt (apply str chars) 16)))))
(defn- read-json-escaped-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial backslash.
(let [c (char (.read stream))]
(cond
(#{\" \\ \/} c) c
(= c \b) \backspace
(= c \f) \formfeed
(= c \n) \newline
(= c \r) \return
(= c \t) \tab
(= c \u) (read-json-hex-character stream))))
(defn- read-json-quoted-string [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening quotation mark.
(let [buffer (StringBuilder.)]
(loop [i (.read stream)]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside string)"))
(= c \") (str buffer)
(= c \\) (do (.append buffer (read-json-escaped-character stream))
(recur (.read stream)))
:else (do (.append buffer c)
(recur (.read stream))))))))
(defn read-json
"Read the next JSON record from stream, which must be an instance of
java.io.PushbackReader."
([] (read-json *in* true nil))
([stream] (read-json stream true nil))
([#^PushbackReader stream eof-error? eof-value]
(loop [i (.read stream)]
(let [c (char i)]
(cond
;; Handle end-of-stream
(= i -1) (if eof-error?
(throw (EOFException. "JSON error (end-of-file)"))
eof-value)
;; Ignore whitespace
(Character/isWhitespace c) (recur (.read stream))
;; Read numbers, true, and false with Clojure reader
(#{\- \0 \1 \2 \3 \4 \5 \6 \7 \8 \9} c)
(do (.unread stream i)
(read stream true nil))
;; Read strings
(= c \") (read-json-quoted-string stream)
;; Read null as nil
(= c \n) (let [ull [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= ull [\u \l \l])
nil
(throw (Exception. (str "JSON error (expected null): " c ull)))))
;; Read true
(= c \t) (let [rue [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= rue [\r \u \e])
true
(throw (Exception. (str "JSON error (expected true): " c rue)))))
;; Read false
(= c \f) (let [alse [(char (.read stream))
(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= alse [\a \l \s \e])
false
(throw (Exception. (str "JSON error (expected false): " c alse)))))
;; Read JSON objects
(= c \{) (read-json-object stream)
;; Read JSON arrays
(= c \[) (read-json-array stream)
:else (throw (Exception. (str "JSON error (unexpected character): " c))))))))
(defn read-json-string [string]
(read-json (PushbackReader. (StringReader. string))))
;;; TESTS
(deftest- can-read-numbers
(is (= 42 (read-json-string "42")))
(is (= -3 (read-json-string "-3")))
(is (= 3.14159 (read-json-string "3.14159")))
(is (= 6.022e23 (read-json-string "6.022e23"))))
(deftest- can-read-null
(is (= nil (read-json-string "null"))))
(deftest- can-read-strings
(is (= "Hello, World!" (read-json-string "\"Hello, World!\""))))
(deftest- handles-escaped-slashes-in-strings
(is (= "/foo/bar" (read-json-string "\"\\/foo\\/bar\""))))
(deftest- handles-unicode-escapes
(is (= " \u0beb " (read-json-string "\" \\u0bEb \""))))
(deftest- handles-escaped-whitespace
(is (= "foo\nbar" (read-json-string "\"foo\\nbar\"")))
(is (= "foo\rbar" (read-json-string "\"foo\\rbar\"")))
(is (= "foo\tbar" (read-json-string "\"foo\\tbar\""))))
(deftest- can-read-booleans
(is (= true (read-json-string "true")))
(is (= false (read-json-string "false"))))
(deftest- can-ignore-whitespace
(is (= nil (read-json-string "\r\n null"))))
(deftest- can-read-arrays
(is (= [1 2 3] (read-json-string "[1,2,3]")))
(is (= ["Ole" "Lena"] (read-json-string "[\"Ole\", \r\n \"Lena\"]"))))
(deftest- can-read-objects
(is (= {"a" 1, "b" 2} (read-json-string "{\"a\": 1, \"b\": 2}"))))
(deftest- can-read-nested-structures
(is (= {"a" [1 2 {"b" [3 "four"]} 5.5]}
(read-json-string "{\"a\":[1,2,{\"b\":[3,\"four\"]},5.5]}"))))
(deftest- disallows-non-string-keys
(is (thrown? Exception (read-json-string "{26:\"z\""))))
(deftest- disallows-barewords
(is (thrown? Exception (read-json-string " foo "))))
(deftest- disallows-unclosed-arrays
(is (thrown? Exception (read-json-string "[1, 2, "))))
(deftest- disallows-unclosed-objects
(is (thrown? Exception (read-json-string "{\"a\":1, "))))
|
74401
|
;;; json/read.clj: JavaScript Object Notation (JSON) parser
;; by <NAME>, http://stuartsierra.com/
;; February 13, 2009
;; Copyright (c) <NAME>, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; Change Log
;;
;; February 13, 2009: added custom handler for quoted strings, to
;; allow escaped forward backslash characters ("\/") in strings.
;;
;; January 26, 2009: initial version
;; For more information on JSON, see http://www.json.org/
;;
;; This library parses data in JSON format. This is a fairly strict
;; implementation of JSON as described at json.org, not a full-fledged
;; JavaScript parser. JavaScript functions and object constructors
;; are not supported. Object field names must be quoted strings; they
;; may not be bare symbols.
(ns clojure.contrib.json.read
(:import (java.io PushbackReader StringReader EOFException))
(:use [clojure.contrib.test-is :only (deftest- is)]))
(declare read-json)
(defn- read-json-array [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), result []]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside array)"))
(Character/isWhitespace c) (recur (.read stream) result)
(= c \,) (recur (.read stream) result)
(= c \]) result
:else (do (.unread stream (int c))
(let [element (read-json stream)]
(recur (.read stream) (conj result element))))))))
(defn- read-json-object [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), key nil, result {}]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside object)"))
(Character/isWhitespace c) (recur (.read stream) key result)
(= c \,) (recur (.read stream) nil result)
(= c \:) (recur (.read stream) key result)
(= c \}) (if (nil? key)
result
(throw (Exception. "JSON error (key missing value in object)")))
:else (do (.unread stream i)
(let [element (read-json stream)]
(if (nil? key)
(if (string? element)
(recur (.read stream) element result)
(throw (Exception. "JSON error (non-string key in object)")))
(recur (.read stream) nil (assoc result key element)))))))))
(defn- read-json-hex-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial "\u". Reads the next four characters from the stream.
(let [digits [(.read stream)
(.read stream)
(.read stream)
(.read stream)]]
(when (some neg? digits)
(throw (EOFException. "JSON error (end-of-file inside Unicode character escape)")))
(let [chars (map char digits)]
(when-not (every? #{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f \A \B \C \D \E \F}
chars)
(throw (Exception. "JSON error (invalid hex character in Unicode character escape)")))
(char (Integer/parseInt (apply str chars) 16)))))
(defn- read-json-escaped-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial backslash.
(let [c (char (.read stream))]
(cond
(#{\" \\ \/} c) c
(= c \b) \backspace
(= c \f) \formfeed
(= c \n) \newline
(= c \r) \return
(= c \t) \tab
(= c \u) (read-json-hex-character stream))))
(defn- read-json-quoted-string [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening quotation mark.
(let [buffer (StringBuilder.)]
(loop [i (.read stream)]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside string)"))
(= c \") (str buffer)
(= c \\) (do (.append buffer (read-json-escaped-character stream))
(recur (.read stream)))
:else (do (.append buffer c)
(recur (.read stream))))))))
(defn read-json
"Read the next JSON record from stream, which must be an instance of
java.io.PushbackReader."
([] (read-json *in* true nil))
([stream] (read-json stream true nil))
([#^PushbackReader stream eof-error? eof-value]
(loop [i (.read stream)]
(let [c (char i)]
(cond
;; Handle end-of-stream
(= i -1) (if eof-error?
(throw (EOFException. "JSON error (end-of-file)"))
eof-value)
;; Ignore whitespace
(Character/isWhitespace c) (recur (.read stream))
;; Read numbers, true, and false with Clojure reader
(#{\- \0 \1 \2 \3 \4 \5 \6 \7 \8 \9} c)
(do (.unread stream i)
(read stream true nil))
;; Read strings
(= c \") (read-json-quoted-string stream)
;; Read null as nil
(= c \n) (let [ull [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= ull [\u \l \l])
nil
(throw (Exception. (str "JSON error (expected null): " c ull)))))
;; Read true
(= c \t) (let [rue [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= rue [\r \u \e])
true
(throw (Exception. (str "JSON error (expected true): " c rue)))))
;; Read false
(= c \f) (let [alse [(char (.read stream))
(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= alse [\a \l \s \e])
false
(throw (Exception. (str "JSON error (expected false): " c alse)))))
;; Read JSON objects
(= c \{) (read-json-object stream)
;; Read JSON arrays
(= c \[) (read-json-array stream)
:else (throw (Exception. (str "JSON error (unexpected character): " c))))))))
(defn read-json-string [string]
(read-json (PushbackReader. (StringReader. string))))
;;; TESTS
(deftest- can-read-numbers
(is (= 42 (read-json-string "42")))
(is (= -3 (read-json-string "-3")))
(is (= 3.14159 (read-json-string "3.14159")))
(is (= 6.022e23 (read-json-string "6.022e23"))))
(deftest- can-read-null
(is (= nil (read-json-string "null"))))
(deftest- can-read-strings
(is (= "Hello, World!" (read-json-string "\"Hello, World!\""))))
(deftest- handles-escaped-slashes-in-strings
(is (= "/foo/bar" (read-json-string "\"\\/foo\\/bar\""))))
(deftest- handles-unicode-escapes
(is (= " \u0beb " (read-json-string "\" \\u0bEb \""))))
(deftest- handles-escaped-whitespace
(is (= "foo\nbar" (read-json-string "\"foo\\nbar\"")))
(is (= "foo\rbar" (read-json-string "\"foo\\rbar\"")))
(is (= "foo\tbar" (read-json-string "\"foo\\tbar\""))))
(deftest- can-read-booleans
(is (= true (read-json-string "true")))
(is (= false (read-json-string "false"))))
(deftest- can-ignore-whitespace
(is (= nil (read-json-string "\r\n null"))))
(deftest- can-read-arrays
(is (= [1 2 3] (read-json-string "[1,2,3]")))
(is (= ["Ole" "Lena"] (read-json-string "[\"Ole\", \r\n \"Lena\"]"))))
(deftest- can-read-objects
(is (= {"a" 1, "b" 2} (read-json-string "{\"a\": 1, \"b\": 2}"))))
(deftest- can-read-nested-structures
(is (= {"a" [1 2 {"b" [3 "four"]} 5.5]}
(read-json-string "{\"a\":[1,2,{\"b\":[3,\"four\"]},5.5]}"))))
(deftest- disallows-non-string-keys
(is (thrown? Exception (read-json-string "{26:\"z\""))))
(deftest- disallows-barewords
(is (thrown? Exception (read-json-string " foo "))))
(deftest- disallows-unclosed-arrays
(is (thrown? Exception (read-json-string "[1, 2, "))))
(deftest- disallows-unclosed-objects
(is (thrown? Exception (read-json-string "{\"a\":1, "))))
| true |
;;; json/read.clj: JavaScript Object Notation (JSON) parser
;; by PI:NAME:<NAME>END_PI, http://stuartsierra.com/
;; February 13, 2009
;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; Change Log
;;
;; February 13, 2009: added custom handler for quoted strings, to
;; allow escaped forward backslash characters ("\/") in strings.
;;
;; January 26, 2009: initial version
;; For more information on JSON, see http://www.json.org/
;;
;; This library parses data in JSON format. This is a fairly strict
;; implementation of JSON as described at json.org, not a full-fledged
;; JavaScript parser. JavaScript functions and object constructors
;; are not supported. Object field names must be quoted strings; they
;; may not be bare symbols.
(ns clojure.contrib.json.read
(:import (java.io PushbackReader StringReader EOFException))
(:use [clojure.contrib.test-is :only (deftest- is)]))
(declare read-json)
(defn- read-json-array [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), result []]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside array)"))
(Character/isWhitespace c) (recur (.read stream) result)
(= c \,) (recur (.read stream) result)
(= c \]) result
:else (do (.unread stream (int c))
(let [element (read-json stream)]
(recur (.read stream) (conj result element))))))))
(defn- read-json-object [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
(loop [i (.read stream), key nil, result {}]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside object)"))
(Character/isWhitespace c) (recur (.read stream) key result)
(= c \,) (recur (.read stream) nil result)
(= c \:) (recur (.read stream) key result)
(= c \}) (if (nil? key)
result
(throw (Exception. "JSON error (key missing value in object)")))
:else (do (.unread stream i)
(let [element (read-json stream)]
(if (nil? key)
(if (string? element)
(recur (.read stream) element result)
(throw (Exception. "JSON error (non-string key in object)")))
(recur (.read stream) nil (assoc result key element)))))))))
(defn- read-json-hex-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial "\u". Reads the next four characters from the stream.
(let [digits [(.read stream)
(.read stream)
(.read stream)
(.read stream)]]
(when (some neg? digits)
(throw (EOFException. "JSON error (end-of-file inside Unicode character escape)")))
(let [chars (map char digits)]
(when-not (every? #{\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f \A \B \C \D \E \F}
chars)
(throw (Exception. "JSON error (invalid hex character in Unicode character escape)")))
(char (Integer/parseInt (apply str chars) 16)))))
(defn- read-json-escaped-character [stream]
;; Expects to be called with the head of the stream AFTER the
;; initial backslash.
(let [c (char (.read stream))]
(cond
(#{\" \\ \/} c) c
(= c \b) \backspace
(= c \f) \formfeed
(= c \n) \newline
(= c \r) \return
(= c \t) \tab
(= c \u) (read-json-hex-character stream))))
(defn- read-json-quoted-string [#^PushbackReader stream]
;; Expects to be called with the head of the stream AFTER the
;; opening quotation mark.
(let [buffer (StringBuilder.)]
(loop [i (.read stream)]
(let [c (char i)]
(cond
(= i -1) (throw (EOFException. "JSON error (end-of-file inside string)"))
(= c \") (str buffer)
(= c \\) (do (.append buffer (read-json-escaped-character stream))
(recur (.read stream)))
:else (do (.append buffer c)
(recur (.read stream))))))))
(defn read-json
"Read the next JSON record from stream, which must be an instance of
java.io.PushbackReader."
([] (read-json *in* true nil))
([stream] (read-json stream true nil))
([#^PushbackReader stream eof-error? eof-value]
(loop [i (.read stream)]
(let [c (char i)]
(cond
;; Handle end-of-stream
(= i -1) (if eof-error?
(throw (EOFException. "JSON error (end-of-file)"))
eof-value)
;; Ignore whitespace
(Character/isWhitespace c) (recur (.read stream))
;; Read numbers, true, and false with Clojure reader
(#{\- \0 \1 \2 \3 \4 \5 \6 \7 \8 \9} c)
(do (.unread stream i)
(read stream true nil))
;; Read strings
(= c \") (read-json-quoted-string stream)
;; Read null as nil
(= c \n) (let [ull [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= ull [\u \l \l])
nil
(throw (Exception. (str "JSON error (expected null): " c ull)))))
;; Read true
(= c \t) (let [rue [(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= rue [\r \u \e])
true
(throw (Exception. (str "JSON error (expected true): " c rue)))))
;; Read false
(= c \f) (let [alse [(char (.read stream))
(char (.read stream))
(char (.read stream))
(char (.read stream))]]
(if (= alse [\a \l \s \e])
false
(throw (Exception. (str "JSON error (expected false): " c alse)))))
;; Read JSON objects
(= c \{) (read-json-object stream)
;; Read JSON arrays
(= c \[) (read-json-array stream)
:else (throw (Exception. (str "JSON error (unexpected character): " c))))))))
(defn read-json-string [string]
(read-json (PushbackReader. (StringReader. string))))
;;; TESTS
(deftest- can-read-numbers
(is (= 42 (read-json-string "42")))
(is (= -3 (read-json-string "-3")))
(is (= 3.14159 (read-json-string "3.14159")))
(is (= 6.022e23 (read-json-string "6.022e23"))))
(deftest- can-read-null
(is (= nil (read-json-string "null"))))
(deftest- can-read-strings
(is (= "Hello, World!" (read-json-string "\"Hello, World!\""))))
(deftest- handles-escaped-slashes-in-strings
(is (= "/foo/bar" (read-json-string "\"\\/foo\\/bar\""))))
(deftest- handles-unicode-escapes
(is (= " \u0beb " (read-json-string "\" \\u0bEb \""))))
(deftest- handles-escaped-whitespace
(is (= "foo\nbar" (read-json-string "\"foo\\nbar\"")))
(is (= "foo\rbar" (read-json-string "\"foo\\rbar\"")))
(is (= "foo\tbar" (read-json-string "\"foo\\tbar\""))))
(deftest- can-read-booleans
(is (= true (read-json-string "true")))
(is (= false (read-json-string "false"))))
(deftest- can-ignore-whitespace
(is (= nil (read-json-string "\r\n null"))))
(deftest- can-read-arrays
(is (= [1 2 3] (read-json-string "[1,2,3]")))
(is (= ["Ole" "Lena"] (read-json-string "[\"Ole\", \r\n \"Lena\"]"))))
(deftest- can-read-objects
(is (= {"a" 1, "b" 2} (read-json-string "{\"a\": 1, \"b\": 2}"))))
(deftest- can-read-nested-structures
(is (= {"a" [1 2 {"b" [3 "four"]} 5.5]}
(read-json-string "{\"a\":[1,2,{\"b\":[3,\"four\"]},5.5]}"))))
(deftest- disallows-non-string-keys
(is (thrown? Exception (read-json-string "{26:\"z\""))))
(deftest- disallows-barewords
(is (thrown? Exception (read-json-string " foo "))))
(deftest- disallows-unclosed-arrays
(is (thrown? Exception (read-json-string "[1, 2, "))))
(deftest- disallows-unclosed-objects
(is (thrown? Exception (read-json-string "{\"a\":1, "))))
|
[
{
"context": " [Math/PI Math/PI Math/PI]]))\"\n contributor \"Joseph Wilk\"))\n\n(defexamples dyn-klank\n (:mouse\n \"Use mous",
"end": 679,
"score": 0.9998979568481445,
"start": 668,
"tag": "NAME",
"value": "Joseph Wilk"
},
{
"context": "imes] (* 0.1 (impulse:ar 2 0))))\"\n contributor \"Joseph Wilk\"))\n",
"end": 1303,
"score": 0.999891459941864,
"start": 1292,
"tag": "NAME",
"value": "Joseph Wilk"
}
] |
src/overtone/sc/examples/dyn.clj
|
ABaldwinHunter/overtone
| 3,870 |
(ns overtone.sc.examples.dyn
(:use [overtone.sc.machinery defexample]
[overtone.sc ugens]
[overtone.sc.cgens dyn]))
(defexamples dyn-klang
(:sin-osc
"Use a sin-osc to change 3 running sine oscillators"
"Starts 3 sine oscillators with different frequencies but fixed amplitudes
and phases of 0.3 and PI respectively. Uses a further sine oscillator
running at control rate to control the 3 oscillator's frequencies."
rate :ar
[]
"
(* 0.1 (dyn-klang:ar [(+ [800 1000 1200] (* [13 24 12] (sin-osc:kr [2 3 4.2] 0)))
[0.3 0.3 0.3]
[Math/PI Math/PI Math/PI]]))"
contributor "Joseph Wilk"))
(defexamples dyn-klank
(:mouse
"Use mouse to change 3 running frequency resonators"
"Starts 3 ringz with varying frequencies and ring-times but a fixed
amplitude of 1.0 (this is the default when nil is specified).
The mouse X location effects the frequencies while the mouse Y location
effects the ring-times (which is effectively the speed the sounds decay at)."
rate :ar
[]
"
(let [freqs (* [800 1071 1153] (mouse-x:kr 0.5, 2, 1))
ring-times (* [1 1 1] (mouse-y:kr 0.1, 10, 1))]
(dyn-klank:ar [freqs nil ring-times] (* 0.1 (impulse:ar 2 0))))"
contributor "Joseph Wilk"))
|
78938
|
(ns overtone.sc.examples.dyn
(:use [overtone.sc.machinery defexample]
[overtone.sc ugens]
[overtone.sc.cgens dyn]))
(defexamples dyn-klang
(:sin-osc
"Use a sin-osc to change 3 running sine oscillators"
"Starts 3 sine oscillators with different frequencies but fixed amplitudes
and phases of 0.3 and PI respectively. Uses a further sine oscillator
running at control rate to control the 3 oscillator's frequencies."
rate :ar
[]
"
(* 0.1 (dyn-klang:ar [(+ [800 1000 1200] (* [13 24 12] (sin-osc:kr [2 3 4.2] 0)))
[0.3 0.3 0.3]
[Math/PI Math/PI Math/PI]]))"
contributor "<NAME>"))
(defexamples dyn-klank
(:mouse
"Use mouse to change 3 running frequency resonators"
"Starts 3 ringz with varying frequencies and ring-times but a fixed
amplitude of 1.0 (this is the default when nil is specified).
The mouse X location effects the frequencies while the mouse Y location
effects the ring-times (which is effectively the speed the sounds decay at)."
rate :ar
[]
"
(let [freqs (* [800 1071 1153] (mouse-x:kr 0.5, 2, 1))
ring-times (* [1 1 1] (mouse-y:kr 0.1, 10, 1))]
(dyn-klank:ar [freqs nil ring-times] (* 0.1 (impulse:ar 2 0))))"
contributor "<NAME>"))
| true |
(ns overtone.sc.examples.dyn
(:use [overtone.sc.machinery defexample]
[overtone.sc ugens]
[overtone.sc.cgens dyn]))
(defexamples dyn-klang
(:sin-osc
"Use a sin-osc to change 3 running sine oscillators"
"Starts 3 sine oscillators with different frequencies but fixed amplitudes
and phases of 0.3 and PI respectively. Uses a further sine oscillator
running at control rate to control the 3 oscillator's frequencies."
rate :ar
[]
"
(* 0.1 (dyn-klang:ar [(+ [800 1000 1200] (* [13 24 12] (sin-osc:kr [2 3 4.2] 0)))
[0.3 0.3 0.3]
[Math/PI Math/PI Math/PI]]))"
contributor "PI:NAME:<NAME>END_PI"))
(defexamples dyn-klank
(:mouse
"Use mouse to change 3 running frequency resonators"
"Starts 3 ringz with varying frequencies and ring-times but a fixed
amplitude of 1.0 (this is the default when nil is specified).
The mouse X location effects the frequencies while the mouse Y location
effects the ring-times (which is effectively the speed the sounds decay at)."
rate :ar
[]
"
(let [freqs (* [800 1071 1153] (mouse-x:kr 0.5, 2, 1))
ring-times (* [1 1 1] (mouse-y:kr 0.1, 10, 1))]
(dyn-klank:ar [freqs nil ring-times] (* 0.1 (impulse:ar 2 0))))"
contributor "PI:NAME:<NAME>END_PI"))
|
[
{
"context": "and structure computation in time.\"\n :author \"Jeff Rose and Sam Aaron\"}\n overtone.music.time\n (:use [ov",
"end": 98,
"score": 0.9998742341995239,
"start": 89,
"tag": "NAME",
"value": "Jeff Rose"
},
{
"context": " computation in time.\"\n :author \"Jeff Rose and Sam Aaron\"}\n overtone.music.time\n (:use [overtone.libs ev",
"end": 112,
"score": 0.9998782277107239,
"start": 103,
"tag": "NAME",
"value": "Sam Aaron"
}
] |
src/overtone/music/time.clj
|
rosejn/overtone
| 4 |
(ns
^{:doc "Functions to help manage and structure computation in time."
:author "Jeff Rose and Sam Aaron"}
overtone.music.time
(:use [overtone.libs event]
[overtone.util lib])
(:require [overtone.at-at :as at-at]))
;;Scheduled thread pool (created by at-at) which is to be used by default for
;;all scheduled musical functions (players).
(defonce player-pool (at-at/mk-pool))
(defn now
"Returns the current time in ms"
[]
(System/currentTimeMillis))
(defn after-delay
"Schedules fun to be executed after ms-delay milliseconds. Pool
defaults to the player-pool."
([ms-delay fun] (after-delay ms-delay fun "Overtone delayed fn"))
([ms-delay fun description]
(at-at/at (+ (now) ms-delay) fun player-pool :desc description)))
(defn periodic
"Calls fun every ms-period, and takes an optional initial-delay for
the first call in ms. Pool defaults to the player-pool."
([ms-period fun] (periodic ms-period fun 0))
([ms-period fun initial-delay] (periodic ms-period fun initial-delay "Overtone periodic fn"))
([ms-period fun initial-delay description]
(at-at/every ms-period
fun
player-pool
:initial-delay initial-delay
:desc description)))
;;Ensure all scheduled player fns are stopped when Overtone is reset
;;(typically triggered by a call to stop)
(on-sync-event :reset
(fn [event-info] (at-at/stop-and-reset-pool! player-pool
:strategy :kill))
::player-reset)
(defn stop-player
"Stop scheduled fn gracefully if it hasn't already executed."
[sched-fn] (at-at/stop sched-fn player-pool))
(defn kill-player
"Kills scheduled fn immediately if it hasn't already executed. You
are also able to specify player by job id - see print-schedule."
[sched-fn] (at-at/kill sched-fn player-pool))
(def ^{:dynamic true} *apply-ahead*
"Amount of time apply-at is scheduled to execute *before* it was
scheduled by the user. This is to give room for any computation/gc
cycles and to allow the executing fn to schedule actions on scsynth
ahead of time using the at macro."
300)
(defn apply-at
"Recursion in Time. Calls (apply f args argseq) *apply-ahead* ms
before ms-time.
By passing a function using #'foo syntax instead of just foo, when
later called by the scheduler it will lookup based on the symbol
rather than using the instance of the function defined earlier.
(apply-at (+ dur (now)) #'my-melody arg1 arg2 [])"
{:arglists '([ms-time f args* argseq])}
[#^clojure.lang.IFn ms-time f & args]
(let [delay-time (- ms-time *apply-ahead* (now))]
(if (<= delay-time 0)
(after-delay 0 #(apply f (#'clojure.core/spread args)))
(after-delay delay-time #(apply f (#'clojure.core/spread args))))))
(defn show-schedule
"Print the schedule of currently running audio players."
[]
(at-at/show-schedule player-pool))
|
47654
|
(ns
^{:doc "Functions to help manage and structure computation in time."
:author "<NAME> and <NAME>"}
overtone.music.time
(:use [overtone.libs event]
[overtone.util lib])
(:require [overtone.at-at :as at-at]))
;;Scheduled thread pool (created by at-at) which is to be used by default for
;;all scheduled musical functions (players).
(defonce player-pool (at-at/mk-pool))
(defn now
"Returns the current time in ms"
[]
(System/currentTimeMillis))
(defn after-delay
"Schedules fun to be executed after ms-delay milliseconds. Pool
defaults to the player-pool."
([ms-delay fun] (after-delay ms-delay fun "Overtone delayed fn"))
([ms-delay fun description]
(at-at/at (+ (now) ms-delay) fun player-pool :desc description)))
(defn periodic
"Calls fun every ms-period, and takes an optional initial-delay for
the first call in ms. Pool defaults to the player-pool."
([ms-period fun] (periodic ms-period fun 0))
([ms-period fun initial-delay] (periodic ms-period fun initial-delay "Overtone periodic fn"))
([ms-period fun initial-delay description]
(at-at/every ms-period
fun
player-pool
:initial-delay initial-delay
:desc description)))
;;Ensure all scheduled player fns are stopped when Overtone is reset
;;(typically triggered by a call to stop)
(on-sync-event :reset
(fn [event-info] (at-at/stop-and-reset-pool! player-pool
:strategy :kill))
::player-reset)
(defn stop-player
"Stop scheduled fn gracefully if it hasn't already executed."
[sched-fn] (at-at/stop sched-fn player-pool))
(defn kill-player
"Kills scheduled fn immediately if it hasn't already executed. You
are also able to specify player by job id - see print-schedule."
[sched-fn] (at-at/kill sched-fn player-pool))
(def ^{:dynamic true} *apply-ahead*
"Amount of time apply-at is scheduled to execute *before* it was
scheduled by the user. This is to give room for any computation/gc
cycles and to allow the executing fn to schedule actions on scsynth
ahead of time using the at macro."
300)
(defn apply-at
"Recursion in Time. Calls (apply f args argseq) *apply-ahead* ms
before ms-time.
By passing a function using #'foo syntax instead of just foo, when
later called by the scheduler it will lookup based on the symbol
rather than using the instance of the function defined earlier.
(apply-at (+ dur (now)) #'my-melody arg1 arg2 [])"
{:arglists '([ms-time f args* argseq])}
[#^clojure.lang.IFn ms-time f & args]
(let [delay-time (- ms-time *apply-ahead* (now))]
(if (<= delay-time 0)
(after-delay 0 #(apply f (#'clojure.core/spread args)))
(after-delay delay-time #(apply f (#'clojure.core/spread args))))))
(defn show-schedule
"Print the schedule of currently running audio players."
[]
(at-at/show-schedule player-pool))
| true |
(ns
^{:doc "Functions to help manage and structure computation in time."
:author "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"}
overtone.music.time
(:use [overtone.libs event]
[overtone.util lib])
(:require [overtone.at-at :as at-at]))
;;Scheduled thread pool (created by at-at) which is to be used by default for
;;all scheduled musical functions (players).
(defonce player-pool (at-at/mk-pool))
(defn now
"Returns the current time in ms"
[]
(System/currentTimeMillis))
(defn after-delay
"Schedules fun to be executed after ms-delay milliseconds. Pool
defaults to the player-pool."
([ms-delay fun] (after-delay ms-delay fun "Overtone delayed fn"))
([ms-delay fun description]
(at-at/at (+ (now) ms-delay) fun player-pool :desc description)))
(defn periodic
"Calls fun every ms-period, and takes an optional initial-delay for
the first call in ms. Pool defaults to the player-pool."
([ms-period fun] (periodic ms-period fun 0))
([ms-period fun initial-delay] (periodic ms-period fun initial-delay "Overtone periodic fn"))
([ms-period fun initial-delay description]
(at-at/every ms-period
fun
player-pool
:initial-delay initial-delay
:desc description)))
;;Ensure all scheduled player fns are stopped when Overtone is reset
;;(typically triggered by a call to stop)
(on-sync-event :reset
(fn [event-info] (at-at/stop-and-reset-pool! player-pool
:strategy :kill))
::player-reset)
(defn stop-player
"Stop scheduled fn gracefully if it hasn't already executed."
[sched-fn] (at-at/stop sched-fn player-pool))
(defn kill-player
"Kills scheduled fn immediately if it hasn't already executed. You
are also able to specify player by job id - see print-schedule."
[sched-fn] (at-at/kill sched-fn player-pool))
(def ^{:dynamic true} *apply-ahead*
"Amount of time apply-at is scheduled to execute *before* it was
scheduled by the user. This is to give room for any computation/gc
cycles and to allow the executing fn to schedule actions on scsynth
ahead of time using the at macro."
300)
(defn apply-at
"Recursion in Time. Calls (apply f args argseq) *apply-ahead* ms
before ms-time.
By passing a function using #'foo syntax instead of just foo, when
later called by the scheduler it will lookup based on the symbol
rather than using the instance of the function defined earlier.
(apply-at (+ dur (now)) #'my-melody arg1 arg2 [])"
{:arglists '([ms-time f args* argseq])}
[#^clojure.lang.IFn ms-time f & args]
(let [delay-time (- ms-time *apply-ahead* (now))]
(if (<= delay-time 0)
(after-delay 0 #(apply f (#'clojure.core/spread args)))
(after-delay delay-time #(apply f (#'clojure.core/spread args))))))
(defn show-schedule
"Print the schedule of currently running audio players."
[]
(at-at/show-schedule player-pool))
|
[
{
"context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 33,
"score": 0.9791629910469055,
"start": 30,
"tag": "NAME",
"value": "Net"
}
] |
pigpen-core/src/test/clojure/pigpen/functional/code_test.clj
|
ombagus/Netflix
| 327 |
;;
;;
;; Copyright 2013-2015 Netflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.code-test
(:require [pigpen.functional-test :as t]
[pigpen.extensions.test :refer [test-diff]]
[pigpen.map :as pig-map]
[pigpen.set :as pig-set]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig-map/map (fn [x] (+ (test-fn x) y z))))))
(t/deftest test-closure
"make sure fns are available"
[harness]
(test-diff
(->>
(t/data harness [1 2 3])
(test-param 37)
(t/dump harness))
'[80 83 88]))
(t/deftest test-for
"make sure for doesn't produce hidden vars we can't serialize"
[harness]
(test-diff
(sort
(t/dump harness
(apply pig-set/concat
(for [x [1 2 3]]
(->>
(t/data harness [1 2 3])
(pig-map/map (fn [y] (+ x y))))))))
[2 3 3 4 4 4 5 5 6]))
|
1675
|
;;
;;
;; 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.functional.code-test
(:require [pigpen.functional-test :as t]
[pigpen.extensions.test :refer [test-diff]]
[pigpen.map :as pig-map]
[pigpen.set :as pig-set]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig-map/map (fn [x] (+ (test-fn x) y z))))))
(t/deftest test-closure
"make sure fns are available"
[harness]
(test-diff
(->>
(t/data harness [1 2 3])
(test-param 37)
(t/dump harness))
'[80 83 88]))
(t/deftest test-for
"make sure for doesn't produce hidden vars we can't serialize"
[harness]
(test-diff
(sort
(t/dump harness
(apply pig-set/concat
(for [x [1 2 3]]
(->>
(t/data harness [1 2 3])
(pig-map/map (fn [y] (+ x y))))))))
[2 3 3 4 4 4 5 5 6]))
| 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.functional.code-test
(:require [pigpen.functional-test :as t]
[pigpen.extensions.test :refer [test-diff]]
[pigpen.map :as pig-map]
[pigpen.set :as pig-set]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig-map/map (fn [x] (+ (test-fn x) y z))))))
(t/deftest test-closure
"make sure fns are available"
[harness]
(test-diff
(->>
(t/data harness [1 2 3])
(test-param 37)
(t/dump harness))
'[80 83 88]))
(t/deftest test-for
"make sure for doesn't produce hidden vars we can't serialize"
[harness]
(test-diff
(sort
(t/dump harness
(apply pig-set/concat
(for [x [1 2 3]]
(->>
(t/data harness [1 2 3])
(pig-map/map (fn [y] (+ x y))))))))
[2 3 3 4 4 4 5 5 6]))
|
[
{
"context": ";; Copyright (c) 2020-2021 Saidone\n\n(ns clj-ssh-keygen.oid\n (:gen-class))\n\n(require",
"end": 34,
"score": 0.9884189963340759,
"start": 27,
"tag": "NAME",
"value": "Saidone"
}
] |
src/clj_ssh_keygen/oid.clj
|
saidone75/clj-ssh-keygen
| 17 |
;; Copyright (c) 2020-2021 Saidone
(ns clj-ssh-keygen.oid
(:gen-class))
(require '[clojure.string :as str])
(defn- token-to-bytes [token]
(let [bitlist
(partition-all
7
;; prepend zeros to match multiple of 7 length
(concat (repeat (- 7 (rem (count (Integer/toString token 2)) 7)) \0)
(Integer/toString token 2)))]
(concat
(map
#(Integer/valueOf (apply str (cons \1 %)) 2)
(butlast bitlist))
(list (Integer/valueOf (apply str (cons \0 (last bitlist))) 2)))))
;; https://stackoverflow.com/questions/3376357/how-to-convert-object-identifiers-to-hex-strings
(defn oid-string-to-bytes [oid]
(let [tokens (map #(Integer/parseInt %) (str/split oid #"\."))]
(flatten
(concat
;; first two tokens encoded separately
(list (+ (* 40 (first tokens)) (second tokens)))
(map
token-to-bytes
(drop 2 tokens))))))
|
87125
|
;; Copyright (c) 2020-2021 <NAME>
(ns clj-ssh-keygen.oid
(:gen-class))
(require '[clojure.string :as str])
(defn- token-to-bytes [token]
(let [bitlist
(partition-all
7
;; prepend zeros to match multiple of 7 length
(concat (repeat (- 7 (rem (count (Integer/toString token 2)) 7)) \0)
(Integer/toString token 2)))]
(concat
(map
#(Integer/valueOf (apply str (cons \1 %)) 2)
(butlast bitlist))
(list (Integer/valueOf (apply str (cons \0 (last bitlist))) 2)))))
;; https://stackoverflow.com/questions/3376357/how-to-convert-object-identifiers-to-hex-strings
(defn oid-string-to-bytes [oid]
(let [tokens (map #(Integer/parseInt %) (str/split oid #"\."))]
(flatten
(concat
;; first two tokens encoded separately
(list (+ (* 40 (first tokens)) (second tokens)))
(map
token-to-bytes
(drop 2 tokens))))))
| true |
;; Copyright (c) 2020-2021 PI:NAME:<NAME>END_PI
(ns clj-ssh-keygen.oid
(:gen-class))
(require '[clojure.string :as str])
(defn- token-to-bytes [token]
(let [bitlist
(partition-all
7
;; prepend zeros to match multiple of 7 length
(concat (repeat (- 7 (rem (count (Integer/toString token 2)) 7)) \0)
(Integer/toString token 2)))]
(concat
(map
#(Integer/valueOf (apply str (cons \1 %)) 2)
(butlast bitlist))
(list (Integer/valueOf (apply str (cons \0 (last bitlist))) 2)))))
;; https://stackoverflow.com/questions/3376357/how-to-convert-object-identifiers-to-hex-strings
(defn oid-string-to-bytes [oid]
(let [tokens (map #(Integer/parseInt %) (str/split oid #"\."))]
(flatten
(concat
;; first two tokens encoded separately
(list (+ (* 40 (first tokens)) (second tokens)))
(map
token-to-bytes
(drop 2 tokens))))))
|
[
{
"context": "ol \"\"\n :data-key \"pressure\"\n :id \"press",
"end": 1379,
"score": 0.8855009078979492,
"start": 1371,
"tag": "KEY",
"value": "pressure"
}
] |
src/main/app/ui/dashboard/pressure.cljs
|
joshuawood2894/fulcro_postgresql_mqtt_template
| 0 |
(ns app.ui.dashboard.pressure
(:require
[app.model.dashboard.pressure :as mp]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.pressure :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 PressureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Pressure in Hectopascals"
mp/toggle-pressure-settings! (:toggle-settings props))
:cover (if (empty? (:pressure props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:pressure props)
:x-axis-label "Time"
:y-axis-label "Pressure (hPa)"
:unit-symbol ""
:data-key "pressure"
:id "pressure-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mp/set-pressure-start-end-datetime!
mp/set-pressure-color!
mp/set-pressure-min-bound!
mp/set-pressure-max-bound!
mp/redo-pressure-min-max-bound!
(:chart-type props)
mp/set-pressure-chart-type!)}))
(def ui-pressure-chart (comp/factory PressureChart))
(defsc PressureData [this {:pressure-data/keys [pressure
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:pressure-data/pressure (comp/get-query dl/PressureReading)}
:pressure-data/start-date :pressure-data/end-date
:pressure-data/toggle-settings :pressure-data/color
:pressure-data/min-bound :pressure-data/max-bound
:pressure-data/chart-type]
:ident (fn [] [:component/id :pressure-data])
:initial-state {:pressure-data/toggle-settings false
:pressure-data/min-bound js/NaN
:pressure-data/max-bound js/NaN
:pressure-data/chart-type "line"
:pressure-data/color ant/blue-primary
:pressure-data/start-date (js/Date.)
:pressure-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:pressure-data/pressure [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:pressure 1000}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:pressure 999}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:pressure 998}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:pressure 1001}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:pressure 1001}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:pressure 998}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:pressure 997}]}}
(ui-pressure-chart {:pressure pressure
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-pressure-data (comp/factory PressureData))
|
20193
|
(ns app.ui.dashboard.pressure
(:require
[app.model.dashboard.pressure :as mp]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.pressure :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 PressureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Pressure in Hectopascals"
mp/toggle-pressure-settings! (:toggle-settings props))
:cover (if (empty? (:pressure props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:pressure props)
:x-axis-label "Time"
:y-axis-label "Pressure (hPa)"
:unit-symbol ""
:data-key "<KEY>"
:id "pressure-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mp/set-pressure-start-end-datetime!
mp/set-pressure-color!
mp/set-pressure-min-bound!
mp/set-pressure-max-bound!
mp/redo-pressure-min-max-bound!
(:chart-type props)
mp/set-pressure-chart-type!)}))
(def ui-pressure-chart (comp/factory PressureChart))
(defsc PressureData [this {:pressure-data/keys [pressure
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:pressure-data/pressure (comp/get-query dl/PressureReading)}
:pressure-data/start-date :pressure-data/end-date
:pressure-data/toggle-settings :pressure-data/color
:pressure-data/min-bound :pressure-data/max-bound
:pressure-data/chart-type]
:ident (fn [] [:component/id :pressure-data])
:initial-state {:pressure-data/toggle-settings false
:pressure-data/min-bound js/NaN
:pressure-data/max-bound js/NaN
:pressure-data/chart-type "line"
:pressure-data/color ant/blue-primary
:pressure-data/start-date (js/Date.)
:pressure-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:pressure-data/pressure [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:pressure 1000}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:pressure 999}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:pressure 998}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:pressure 1001}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:pressure 1001}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:pressure 998}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:pressure 997}]}}
(ui-pressure-chart {:pressure pressure
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-pressure-data (comp/factory PressureData))
| true |
(ns app.ui.dashboard.pressure
(:require
[app.model.dashboard.pressure :as mp]
[app.ui.dashboard.config :as dc]
[app.ui.antd.components :as ant]
[app.ui.data-logger.pressure :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 PressureChart [this props]
(ant/card {:style {:width 500
:textAlign "center"}
:bodyStyle {:margin "0px"
:padding "0px"}
:headStyle {:backgroundColor "#001529"
:color "white"}
:title (dc/create-card-title "Pressure in Hectopascals"
mp/toggle-pressure-settings! (:toggle-settings props))
:cover (if (empty? (:pressure props))
(div {:style {:width 485 :height 275}}
(ant/ant-empty {:style {:paddingTop "15%"}}))
(dc/create-rechart (:chart-type props)
{:data (:pressure props)
:x-axis-label "Time"
:y-axis-label "Pressure (hPa)"
:unit-symbol ""
:data-key "PI:KEY:<KEY>END_PI"
:id "pressure-id"
:color (:color props)
:min-bound (:min-bound props)
:max-bound (:max-bound props)}))
:actions (dc/create-dropdown-settings (:toggle-settings props)
mp/set-pressure-start-end-datetime!
mp/set-pressure-color!
mp/set-pressure-min-bound!
mp/set-pressure-max-bound!
mp/redo-pressure-min-max-bound!
(:chart-type props)
mp/set-pressure-chart-type!)}))
(def ui-pressure-chart (comp/factory PressureChart))
(defsc PressureData [this {:pressure-data/keys [pressure
start-date end-date
toggle-settings color
min-bound max-bound
chart-type]
:as props}]
{:query [{:pressure-data/pressure (comp/get-query dl/PressureReading)}
:pressure-data/start-date :pressure-data/end-date
:pressure-data/toggle-settings :pressure-data/color
:pressure-data/min-bound :pressure-data/max-bound
:pressure-data/chart-type]
:ident (fn [] [:component/id :pressure-data])
:initial-state {:pressure-data/toggle-settings false
:pressure-data/min-bound js/NaN
:pressure-data/max-bound js/NaN
:pressure-data/chart-type "line"
:pressure-data/color ant/blue-primary
:pressure-data/start-date (js/Date.)
:pressure-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24)))
:pressure-data/pressure [{:id 1 :time (js/Date.
"March
17, 2021
15:24:00")
:pressure 1000}
{:id 2 :time (js/Date.
"March
17, 2021
15:25:00")
:pressure 999}
{:id 3 :time (js/Date.
"March
17, 2021
15:26:00")
:pressure 998}
{:id 4 :time (js/Date.
"March
17, 2021
15:27:00")
:pressure 1001}
{:id 5 :time (js/Date.
"March
17, 2021
15:28:00")
:pressure 1001}
{:id 6 :time (js/Date.
"March
17, 2021
15:29:00")
:pressure 998}
{:id 7 :time (js/Date.
"March
17, 2021
15:30:00")
:pressure 997}]}}
(ui-pressure-chart {:pressure pressure
:toggle-settings toggle-settings
:color color
:min-bound min-bound
:max-bound max-bound
:chart-type chart-type}))
(def ui-pressure-data (comp/factory PressureData))
|
[
{
"context": "word] (s/split decoded #\":\" 2)]\n {:username username\n :password password}))))\n\n(defn http-basi",
"end": 685,
"score": 0.9883994460105896,
"start": 677,
"tag": "USERNAME",
"value": "username"
},
{
"context": "2)]\n {:username username\n :password password}))))\n\n(defn http-basic-backend\n [{:keys [realm a",
"end": 713,
"score": 0.9987356066703796,
"start": 705,
"tag": "PASSWORD",
"value": "password"
}
] |
src/macchiato/auth/backends/basic.cljs
|
xafizoff/macchiato-auth
| 0 |
(ns macchiato.auth.backends.basic
(:require
[macchiato.auth :refer [authenticated?]]
[clojure.string :as s]
[goog.crypt.base64 :as b64]
[macchiato.auth.protocols :as proto]
[macchiato.auth.http :refer [find-header]]))
(defn- parse-header
"Given a request, try to extract and parse the basic header."
[{:keys [headers]}]
(let [pattern (re-pattern "^Basic (.+)$")
decoded (some->> (find-header headers "authorization")
(re-find pattern)
(second)
(b64/decodeString))]
(when decoded
(when-let [[username password] (s/split decoded #":" 2)]
{:username username
:password password}))))
(defn http-basic-backend
[{:keys [realm authfn unauthorized-handler] :or {realm "Macchiato Auth"}}]
{:pre [(ifn? authfn)]}
(reify
proto/IAuthentication
(-parse [_ request]
(parse-header request))
(-authenticate [_ request data]
(authfn request data))
proto/IAuthorization
(-handle-unauthorized [_ request metadata]
(if unauthorized-handler
(unauthorized-handler request (assoc metadata :realm realm))
(if (authenticated? request)
{:status 403
:headers {}
:body "Permission denied"}
{:status 401
:headers {"WWW-Authenticate" (str "Basic realm=\"" realm "\"")}
:body "Unauthorized"})))))
;vZi2PNd0A33g
|
57687
|
(ns macchiato.auth.backends.basic
(:require
[macchiato.auth :refer [authenticated?]]
[clojure.string :as s]
[goog.crypt.base64 :as b64]
[macchiato.auth.protocols :as proto]
[macchiato.auth.http :refer [find-header]]))
(defn- parse-header
"Given a request, try to extract and parse the basic header."
[{:keys [headers]}]
(let [pattern (re-pattern "^Basic (.+)$")
decoded (some->> (find-header headers "authorization")
(re-find pattern)
(second)
(b64/decodeString))]
(when decoded
(when-let [[username password] (s/split decoded #":" 2)]
{:username username
:password <PASSWORD>}))))
(defn http-basic-backend
[{:keys [realm authfn unauthorized-handler] :or {realm "Macchiato Auth"}}]
{:pre [(ifn? authfn)]}
(reify
proto/IAuthentication
(-parse [_ request]
(parse-header request))
(-authenticate [_ request data]
(authfn request data))
proto/IAuthorization
(-handle-unauthorized [_ request metadata]
(if unauthorized-handler
(unauthorized-handler request (assoc metadata :realm realm))
(if (authenticated? request)
{:status 403
:headers {}
:body "Permission denied"}
{:status 401
:headers {"WWW-Authenticate" (str "Basic realm=\"" realm "\"")}
:body "Unauthorized"})))))
;vZi2PNd0A33g
| true |
(ns macchiato.auth.backends.basic
(:require
[macchiato.auth :refer [authenticated?]]
[clojure.string :as s]
[goog.crypt.base64 :as b64]
[macchiato.auth.protocols :as proto]
[macchiato.auth.http :refer [find-header]]))
(defn- parse-header
"Given a request, try to extract and parse the basic header."
[{:keys [headers]}]
(let [pattern (re-pattern "^Basic (.+)$")
decoded (some->> (find-header headers "authorization")
(re-find pattern)
(second)
(b64/decodeString))]
(when decoded
(when-let [[username password] (s/split decoded #":" 2)]
{:username username
:password PI:PASSWORD:<PASSWORD>END_PI}))))
(defn http-basic-backend
[{:keys [realm authfn unauthorized-handler] :or {realm "Macchiato Auth"}}]
{:pre [(ifn? authfn)]}
(reify
proto/IAuthentication
(-parse [_ request]
(parse-header request))
(-authenticate [_ request data]
(authfn request data))
proto/IAuthorization
(-handle-unauthorized [_ request metadata]
(if unauthorized-handler
(unauthorized-handler request (assoc metadata :realm realm))
(if (authenticated? request)
{:status 403
:headers {}
:body "Permission denied"}
{:status 401
:headers {"WWW-Authenticate" (str "Basic realm=\"" realm "\"")}
:body "Unauthorized"})))))
;vZi2PNd0A33g
|
[
{
"context": " values with metadata\n (js/console.log (Person. \"John Doe\" \"Office 33\\n27 Colmore Row\\nBirmingham\\nEngland\"",
"end": 2611,
"score": 0.9994428157806396,
"start": 2603,
"tag": "NAME",
"value": "John Doe"
}
] |
examples/shadow/src/app/core.cljs
|
MawiraIke/cljs-devtools
| 1,125 |
(ns app.core
(:require [clojure.string :as string]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(defn demo-devtools! []
(js/console.log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(js/console.log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(js/console.log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(js/console.log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(js/console.log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(js/console.log hello filter js/document.getElementById) ; functions cljs / native
(js/console.log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(js/console.log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(js/console.log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(js/console.log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(js/console.log (Person. "John Doe" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(js/console.log (atom showcase-value)) ; atoms
(js/console.log (MyType. 1 2)))
(defn ^:export main []
(demo-devtools!))
|
36710
|
(ns app.core
(:require [clojure.string :as string]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(defn demo-devtools! []
(js/console.log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(js/console.log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(js/console.log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(js/console.log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(js/console.log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(js/console.log hello filter js/document.getElementById) ; functions cljs / native
(js/console.log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(js/console.log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(js/console.log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(js/console.log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(js/console.log (Person. "<NAME>" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(js/console.log (atom showcase-value)) ; atoms
(js/console.log (MyType. 1 2)))
(defn ^:export main []
(demo-devtools!))
| true |
(ns app.core
(:require [clojure.string :as string]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(defn demo-devtools! []
(js/console.log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(js/console.log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(js/console.log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(js/console.log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(js/console.log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(js/console.log hello filter js/document.getElementById) ; functions cljs / native
(js/console.log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(js/console.log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(js/console.log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(js/console.log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(js/console.log (Person. "PI:NAME:<NAME>END_PI" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(js/console.log (atom showcase-value)) ; atoms
(js/console.log (MyType. 1 2)))
(defn ^:export main []
(demo-devtools!))
|
[
{
"context": ":meta {:name \"google-site-verification\" :content \"u0k33b2h-hjrHVQZIxMcmdM5YYZ_0USpephsG50KPw4\"}]\n\n [:lin",
"end": 2196,
"score": 0.7639339566230774,
"start": 2153,
"tag": "KEY",
"value": "u0k33b2h-hjrHVQZIxMcmdM5YYZ_0USpephsG50KPw4"
},
{
"context": " [:a {:href \"https://github.com/ertugrulcetin/ClojureNews/issues\" :target \"_blank\"}\n ",
"end": 6125,
"score": 0.9989774823188782,
"start": 6112,
"tag": "USERNAME",
"value": "ertugrulcetin"
},
{
"context": "lass \"pagebottomgray\", :href \"https://twitter.com/clojure_news\"} \"Twitter\"] \" | \"\n ",
"end": 7839,
"score": 0.9995532035827637,
"start": 7827,
"tag": "USERNAME",
"value": "clojure_news"
},
{
"context": "class \"pagebottomgray\", :href \"https://github.com/ertugrulcetin/ClojureNews\"} \"GitHub\"] \" | \"\n ",
"end": 7975,
"score": 0.9996973276138306,
"start": 7962,
"tag": "USERNAME",
"value": "ertugrulcetin"
},
{
"context": " [:a {:class \"pagebottomgray\", :href \"mailto:[email protected]\"} \"Contact\"]]\n ",
"end": 8122,
"score": 0.9999245405197144,
"start": 8097,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": ":story-own-entries (get-own-entries (:username user) stories)\n :story-up",
"end": 12204,
"score": 0.8665479421615601,
"start": 12200,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ry-upvoted-entries (get-upvoted-entries (:username user) stories)\n :more? ",
"end": 12304,
"score": 0.9000579714775085,
"start": 12300,
"tag": "USERNAME",
"value": "user"
},
{
"context": "story-upvote-by-created-by-and-entry-id (:username user) id)}]\n (if user\n ",
"end": 13868,
"score": 0.7328469753265381,
"start": 13864,
"tag": "USERNAME",
"value": "user"
},
{
"context": "sk-upvoted-entries (get-upvoted-entries (:username user) asks)\n :more? ",
"end": 18915,
"score": 0.970738410949707,
"start": 18911,
"tag": "USERNAME",
"value": "user"
},
{
"context": "d-ask-upvote-by-created-by-and-entry-id (:username user) id)}]\n (if user\n ",
"end": 20441,
"score": 0.9624857306480408,
"start": 20437,
"tag": "USERNAME",
"value": "user"
},
{
"context": "newest-own-entries (get-own-entries (:username user) entries)\n :newest-u",
"end": 23975,
"score": 0.9415515661239624,
"start": 23971,
"tag": "USERNAME",
"value": "user"
},
{
"context": "st-upvoted-entries (get-upvoted-entries (:username user) entries)\n :more? ",
"end": 24076,
"score": 0.9484162330627441,
"start": 24072,
"tag": "USERNAME",
"value": "user"
},
{
"context": " (if (= cookie (:cookie user))\n {:username (:username user)\n :karma (:karma user)}))))\n\n(def",
"end": 38956,
"score": 0.6401927471160889,
"start": 38946,
"tag": "USERNAME",
"value": "(:username"
},
{
"context": "okie (:cookie user))\n {:username (:username user)\n :karma (:karma user)}))))\n\n(defn gro",
"end": 38961,
"score": 0.8911562561988831,
"start": 38957,
"tag": "USERNAME",
"value": "user"
}
] |
src/clj/controller/entry.clj
|
mengu/ClojureNews
| 0 |
(ns clj.controller.entry
(:require [liberator.core :refer [resource defresource]]
[clj.util.resource :as resource-util]
[clj.dao.user :as user-dao]
[clj.dao.entry :as entry-dao]
[clj.dao.entry-job :as job-dao]
[clj.dao.entry-event :as event-dao]
[clj.dao.comment-entry :as comment-entry-dao]
[clj.dao.upvote :as upvote-dao]
[hiccup.core :as hiccup]
[cljc.validation :as validation]
[cljc.error-messages :as error-message]
[cljc.page-util :as page-util]
[clojure.string :as str]
[monger.json])
(:import (java.util Calendar Date)))
(declare get-user
create-ask
create-entry
check-story-type
check-ask-type
check-submit-type
check-submit-title
check-submit-url
check-submit-text
check-submit-city
check-submit-country
check-submit-day
check-submit-month
check-submit-year
check-entry-exist
check-job-exist
check-entry-owner
check-page-data-format
check-event-exist
group-by-parent-and-sort-by-vote
create-comment-tree
flat-one-level
flat-until-every-vector
create-comments
get-entry-by-page
get-job-by-page
get-own-entries
get-upvoted-entries
get-own-jobs
get-own-events
calendar->date)
(defn home-page
[]
(resource :allowed-methods [:get]
:available-media-types ["text/html"]
:handle-ok (fn [ctx]
(hiccup/html [:html
[:head
[:meta {:http-equiv "Content-Type" :content "text/html; charset=UTF-8"}]
[:meta {:name "referrer" :content "origin"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:name "google-site-verification" :content "u0k33b2h-hjrHVQZIxMcmdM5YYZ_0USpephsG50KPw4"}]
[:link {:rel "stylesheet" :type "text/css" :href "/css/news.css"}]
[:link {:rel "shortcut icon" :href "/img/logo.png"}]
[:style {:type "text/css"}]
[:title "Clojure News"]]
[:body {:data-gr-c-s-loaded "true" :id "bodyId"}
[:center
[:noscript "Please enable JavaScript!"]
[:table {:id "cnmain", :border "0", :cellpadding "0", :cellspacing "0", :width "85%", :bgcolor "#f6f6ef"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}
[:table {:border "0", :cellpadding "0", :cellspacing "0", :width "100%", :style "padding:2px"}
[:tbody
[:tr
[:td {:style "width:18px;padding-right:4px"}
[:a {:href "/"}
[:img {:src "/img/logo.png", :width "18", :height "18", :style "border:1px white solid;"}]]]
[:td {:style "line-height:12pt; height:10px;"}
[:span {:class "pagetop"}
[:b {:class "brandname"}
[:a {:id "headerMainId" :class "pagetopwhite", :href "/"} "Clojure News"]]
[:a {:id "headerStoryId" :class "pagetopwhite", :href "/#!/story"} "story"] " | "
[:a {:id "headerAskId" :class "pagetopwhite", :href "/#!/ask"} "ask"] " | "
[:a {:id "headerNewId" :class "pagetopwhite", :href "/#!/new"} "new"] " | "
[:a {:id "headerJobId" :class "pagetopwhite", :href "/#!/job"} "jobs"] " | "
[:a {:id "headerEventId" :class "pagetopwhite", :href "/#!/event"} "events"] " | "
[:a {:id "headerSubmitId" :class "pagetopwhite", :href "/#!/submit"} "submit"]]]
[:td {:style "text-align:right;padding-right:4px;"}
[:span {:id "pageTopId", :class "pagetop"}
(if-let [user (get-user ctx)]
[:div
[:a {:class "pagetopwhite", :id "loginId", :href (str "/#!/user/" (:username user))} (:username user)]
(str " (" (:karma user) ") | ")
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/logout"} "logout"]]
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/login"} "login"])
]]]]]]]
[:tr {:style "height:10px"}]
[:tr
[:td
[:center
[:p
"Clojure News is in beta. Please don't hesitate to report bugs to "
[:a {:href "https://github.com/ertugrulcetin/ClojureNews/issues" :target "_blank"}
[:u
"the github issues page."]]]]]]
[:tr
[:td {:id "messageContainerId"}]]
[:tr
[:td {:id "mainContainerId"}
[:p "Loading..."]]]
[:tr
[:td
[:img {:src "/img/s.gif", :height "10", :width "0"}]
[:table {:width "100%", :cellspacing "0", :cellpadding "1"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}]]]]
[:br]
[:center
[:span {:class "yclinks"}
[:a {:class "pagebottomgray", :href "/#!/formatting"} "Formatting"] " | "
[:a {:class "pagebottomgray", :href "/#!/guidelines"} "Guidelines"] " | "
[:a {:class "pagebottomgray", :href "/#!/faq"} "FAQ"] " | "
[:a {:class "pagebottomgray", :href "/rss"} "RSS"] " | "
[:a {:class "pagebottomgray", :href "https://twitter.com/clojure_news"} "Twitter"] " | "
[:a {:class "pagebottomgray", :href "https://github.com/ertugrulcetin/ClojureNews"} "GitHub"] " | "
[:a {:class "pagebottomgray", :href "mailto:[email protected]"} "Contact"]]
[:br]
[:br]]]]]]]
[:script {:src "/js/clojure-news.js", :type "text/javascript"}]
[:script (resource-util/create-google-analytics-code "UA-54741200-3")]]]))
:handle-exception (fn [_]
"Something went wrong")))
;;RSS feed
(defn get-rss-feed
[]
(resource :allowed-methods [:get]
:available-media-types ["application/rss+xml" "application/rdf+xml;q=0.8" "application/atom+xml;q=0.6" "application/xml;q=0.4" "text/xml;q=0.4"]
:handle-ok (fn [_]
(let [data-per-page-inc page-util/data-per-page
stories (get-entry-by-page "story" 1 data-per-page-inc page-util/last-n-days)]
(resource-util/create-rss-feed
(for [story stories]
(resource-util/create-rss-item (str/escape (:title story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(str/escape (:url story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(:created-date story)
(str "https://clojure.news/#!/story/" (:_id story)))))))
:handle-exception #(resource-util/get-exception-message %)))
;;Robots.txt
(defn get-robots-txt
[]
(resource :allowed-methods [:get]
:available-media-types ["text/plain"]
:handle-ok (fn [_]
"User-agent: *\nAllow: /")
:handle-exception #(resource-util/get-exception-message %)))
;;Story
(defn create-story
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)]
(check-submit-type type)
(check-story-type type)
(check-submit-title title)
(check-submit-url url)
(let [story (entry-dao/create-story (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/get-pure-url (str/trim url))
(resource-util/get-username ctx))]
(user-dao/inc-user-karma-by-username (resource-util/get-username ctx))
{:cn-story story})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
stories (get-entry-by-page "story" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-stories (if (= (count stories) data-per-page-inc) (butlast stories) stories)]
(if-let [user (get-user ctx)]
{:story-entry real-stories
:story-own-entries (get-own-entries (:username user) stories)
:story-upvoted-entries (get-upvoted-entries (:username user) stories)
:more? (= data-per-page-inc (count stories))}
{:story-entry real-stories
:more? (= data-per-page-inc (count stories))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:story-entry (entry-dao/find-by-id id)
:story-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-story-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :story-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "story-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [story (check-entry-exist id)]
{:story-entry story
:owner? (= (:created-by story) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-story-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)]
(check-submit-title title)
(entry-dao/edit-story-by-id id (resource-util/capitalize (str/trim title)))
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-story-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by story))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Ask
(defn create-ask
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-type type)
(check-ask-type type)
(check-submit-title title)
(check-submit-text text)
(let [ask (entry-dao/create-ask (resource-util/capitalize (str/trim title))
(str/trim text)
(:username (:user-obj ctx)))]
(user-dao/inc-user-karma-by-username (:created-by ask))
{:cn-ask ask})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-ask :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
asks (get-entry-by-page "ask" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-asks (if (= (count asks) data-per-page-inc) (butlast asks) asks)]
(if-let [user (get-user ctx)]
{:ask-entry real-asks
:ask-own-entries (get-own-entries (:username user) asks)
:ask-upvoted-entries (get-upvoted-entries (:username user) asks)
:more? (= data-per-page-inc (count asks))}
{:ask-entry real-asks
:more? (= data-per-page-inc (count asks))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:ask-entry (entry-dao/find-by-id id)
:ask-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-ask-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :ask-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "ask-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [ask (check-entry-exist id)]
{:ask-entry ask
:owner? (= (:created-by ask) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-ask-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-title title)
(check-submit-text text)
(entry-dao/edit-ask-by-id id (resource-util/capitalize (str/trim title)) text)
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-ask-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by ask))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Newest Ask and Story
(defn get-newest-stories-and-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [entries (entry-dao/get-newest-stories-and-asks (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:newest-entry entries
:newest-own-entries (get-own-entries (:username user) entries)
:newest-upvoted-entries (get-upvoted-entries (:username user) entries)
:more? (= page-util/data-per-page (count entries))}
{:newest-entry entries
:more? (= page-util/data-per-page (count entries))})))
:handle-exception #(resource-util/get-exception-message %)))
;;Job
(defn create-job
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(let [username (resource-util/get-username ctx)]
(job-dao/create-job (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-jobs-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [jobs (job-dao/get-last-n-days-jobs (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:job-entry jobs
:job-own-entries (get-own-jobs (:username user) jobs)
:more? (= page-util/data-per-page (count jobs))}
{:job-entry jobs
:more? (= page-util/data-per-page (count jobs))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-job-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [job (check-job-exist id)]
{:job-entry job
:owner? (= (:created-by job) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-job-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(job-dao/edit-job-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-job-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(job-dao/delete-job-by-id id)
(user-dao/dec-user-karma-by-username (:created-by job))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Event
(defn create-event
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year)
(let [username (resource-util/get-username ctx)
starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/create-event (resource-util/capitalize (str/trim title))
(str/trim url)
starting-date
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-events-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [events (event-dao/get-last-n-days-events (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:event-entry events
:event-own-entries (get-own-events (:username user) events)
:more? (= page-util/data-per-page (count events))}
{:event-entry events
:more? (= page-util/data-per-page (count events))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-event-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [event (check-event-exist id)]
{:event-entry event
:owner? (= (:created-by event) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-event-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year))
(let [starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/edit-event-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
starting-date))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-event-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(event-dao/delete-event-by-id id)
(user-dao/dec-user-karma-by-username (:created-by event))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-own-entries
[username entries]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] entries)
own-entries (entry-dao/get-entries-by-username-and-entries-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-upvoted-entries
[username entries]
(let [ids (reduce #(conj %1 (str (:_id %2))) [] entries)
upvoted-entries (upvote-dao/get-upvotes-by-username-and-upvotes-in-it username ids)]
(reduce #(conj %1 (:entry-id %2)) [] upvoted-entries)))
(defn get-entry-by-page
[entry-type page data-per-page last-n-days]
(let [entries (entry-dao/get-last-n-days-entries entry-type last-n-days)
ranked-entries (resource-util/create-ranked-links entries)]
(resource-util/get-links page data-per-page ranked-entries)))
(defn get-own-jobs
[username jobs]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] jobs)
own-entries (job-dao/get-entries-by-username-and-jobs-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-own-events
[username events]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] events)
own-entries (event-dao/get-entries-by-username-and-events-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-user
[ctx]
(if-let [cookie (resource-util/get-cookie ctx)]
(if-let [user (user-dao/find-by-username (resource-util/get-username-from-cookie ctx))]
(if (= cookie (:cookie user))
{:username (:username user)
:karma (:karma user)}))))
(defn group-by-parent-and-sort-by-vote
[comment-map]
(reduce #(assoc %1 (first %2) (vec
(sort-by :upvote (fn [a b]
(compare b a)) (second %2))))
{}
(group-by :str-parent-comment-id comment-map)))
(defn create-comment-tree
[key grouped-comments coll]
(let [comments (get grouped-comments key)]
(if (nil? comments)
(seq coll)
(for [comment* (get grouped-comments key)]
(if (nil? (:str-parent-comment-id comment*))
(create-comment-tree (:str-id comment*) grouped-comments (conj coll [comment*]))
(create-comment-tree (:str-id comment*) grouped-comments (update-in coll [(dec (count coll))] conj comment*)))))))
(defn flat-one-level [coll]
(mapcat #(if (vector? %) [%] %) coll))
(defn flat-until-every-vector
[coll]
(if (every? vector? coll)
coll
(recur (flat-one-level coll))))
(defn create-comments
[comments-map]
(let [grouped-comments (group-by-parent-and-sort-by-vote comments-map)
comment-tree (create-comment-tree nil grouped-comments [])]
(flatten
(reduce (fn [comment-coll comment-data]
(conj comment-coll (distinct
(flatten
(reduce (fn [x y]
(conj x
(reduce #(conj %1 (into {} %2)) [] (keep-indexed #(concat {:index %1} %2) y))))
[]
(flat-until-every-vector comment-data))))))
[] comment-tree))))
(defn check-submit-type
[type]
(when-not (validation/submit-type? type)
(throw (RuntimeException. "Not valid type."))))
(defn check-story-type
[type]
(when-not (= type "story")
(throw (RuntimeException. "Not valid story type."))))
(defn check-ask-type
[type]
(when-not (= type "ask")
(throw (RuntimeException. "Not valid ask type."))))
(defn check-submit-title
[title]
(when-not (validation/submit-title? title)
(throw (RuntimeException. (str "Please limit title to 80 characters.This had " (count title) ".")))))
(defn check-submit-url
[url]
(when-not (validation/submit-url? url)
(throw (RuntimeException. "Not valid url. Ex: https://www.google.com"))))
(defn check-submit-text
[text]
(when-not (validation/submit-text? text)
(throw (RuntimeException. "Please limit text to 2500 characters."))))
(defn check-submit-city
[city]
(when-not (validation/submit-city? city)
(throw (RuntimeException. error-message/city))))
(defn check-submit-country
[country]
(when-not (validation/submit-city? country)
(throw (RuntimeException. error-message/country))))
(defn check-submit-day
[day]
(when-not (validation/submit-day? day)
(throw (RuntimeException. error-message/day))))
(defn check-submit-month
[month]
(when-not (validation/submit-month? month)
(throw (RuntimeException. error-message/month))))
(defn check-submit-year
[year]
(when-not (validation/submit-year? year)
(throw (RuntimeException. error-message/year))))
(defn check-entry-exist
[id]
(try
(if-let [entry (entry-dao/find-by-id id)]
entry
(throw (RuntimeException. error-message/no-entry)))
(catch Exception e
(throw (RuntimeException. error-message/no-entry)))))
(defn check-job-exist
[id]
(try
(if-let [job (job-dao/find-by-id id)]
job
(throw (RuntimeException. error-message/no-job)))
(catch Exception e
(throw (RuntimeException. error-message/no-job)))))
(defn check-event-exist
[id]
(try
(if-let [event (event-dao/find-by-id id)]
event
(throw (RuntimeException. error-message/no-event)))
(catch Exception e
(throw (RuntimeException. error-message/no-event)))))
(defn check-entry-owner
[entry ctx]
(when-not (= (:created-by entry) (resource-util/get-username ctx))
(throw (RuntimeException. "You are not the owner."))))
(defn check-page-data-format
[page]
(try
(let [p-int (Integer/parseInt page)]
(when (<= p-int 0)
(throw (RuntimeException. "Not valid page number.")))
p-int)
(catch Exception e
(throw (RuntimeException. "Not valid page number.")))))
(defn calendar->date
[calendar]
(-> calendar .getTimeInMillis Date.))
|
1715
|
(ns clj.controller.entry
(:require [liberator.core :refer [resource defresource]]
[clj.util.resource :as resource-util]
[clj.dao.user :as user-dao]
[clj.dao.entry :as entry-dao]
[clj.dao.entry-job :as job-dao]
[clj.dao.entry-event :as event-dao]
[clj.dao.comment-entry :as comment-entry-dao]
[clj.dao.upvote :as upvote-dao]
[hiccup.core :as hiccup]
[cljc.validation :as validation]
[cljc.error-messages :as error-message]
[cljc.page-util :as page-util]
[clojure.string :as str]
[monger.json])
(:import (java.util Calendar Date)))
(declare get-user
create-ask
create-entry
check-story-type
check-ask-type
check-submit-type
check-submit-title
check-submit-url
check-submit-text
check-submit-city
check-submit-country
check-submit-day
check-submit-month
check-submit-year
check-entry-exist
check-job-exist
check-entry-owner
check-page-data-format
check-event-exist
group-by-parent-and-sort-by-vote
create-comment-tree
flat-one-level
flat-until-every-vector
create-comments
get-entry-by-page
get-job-by-page
get-own-entries
get-upvoted-entries
get-own-jobs
get-own-events
calendar->date)
(defn home-page
[]
(resource :allowed-methods [:get]
:available-media-types ["text/html"]
:handle-ok (fn [ctx]
(hiccup/html [:html
[:head
[:meta {:http-equiv "Content-Type" :content "text/html; charset=UTF-8"}]
[:meta {:name "referrer" :content "origin"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:name "google-site-verification" :content "<KEY>"}]
[:link {:rel "stylesheet" :type "text/css" :href "/css/news.css"}]
[:link {:rel "shortcut icon" :href "/img/logo.png"}]
[:style {:type "text/css"}]
[:title "Clojure News"]]
[:body {:data-gr-c-s-loaded "true" :id "bodyId"}
[:center
[:noscript "Please enable JavaScript!"]
[:table {:id "cnmain", :border "0", :cellpadding "0", :cellspacing "0", :width "85%", :bgcolor "#f6f6ef"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}
[:table {:border "0", :cellpadding "0", :cellspacing "0", :width "100%", :style "padding:2px"}
[:tbody
[:tr
[:td {:style "width:18px;padding-right:4px"}
[:a {:href "/"}
[:img {:src "/img/logo.png", :width "18", :height "18", :style "border:1px white solid;"}]]]
[:td {:style "line-height:12pt; height:10px;"}
[:span {:class "pagetop"}
[:b {:class "brandname"}
[:a {:id "headerMainId" :class "pagetopwhite", :href "/"} "Clojure News"]]
[:a {:id "headerStoryId" :class "pagetopwhite", :href "/#!/story"} "story"] " | "
[:a {:id "headerAskId" :class "pagetopwhite", :href "/#!/ask"} "ask"] " | "
[:a {:id "headerNewId" :class "pagetopwhite", :href "/#!/new"} "new"] " | "
[:a {:id "headerJobId" :class "pagetopwhite", :href "/#!/job"} "jobs"] " | "
[:a {:id "headerEventId" :class "pagetopwhite", :href "/#!/event"} "events"] " | "
[:a {:id "headerSubmitId" :class "pagetopwhite", :href "/#!/submit"} "submit"]]]
[:td {:style "text-align:right;padding-right:4px;"}
[:span {:id "pageTopId", :class "pagetop"}
(if-let [user (get-user ctx)]
[:div
[:a {:class "pagetopwhite", :id "loginId", :href (str "/#!/user/" (:username user))} (:username user)]
(str " (" (:karma user) ") | ")
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/logout"} "logout"]]
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/login"} "login"])
]]]]]]]
[:tr {:style "height:10px"}]
[:tr
[:td
[:center
[:p
"Clojure News is in beta. Please don't hesitate to report bugs to "
[:a {:href "https://github.com/ertugrulcetin/ClojureNews/issues" :target "_blank"}
[:u
"the github issues page."]]]]]]
[:tr
[:td {:id "messageContainerId"}]]
[:tr
[:td {:id "mainContainerId"}
[:p "Loading..."]]]
[:tr
[:td
[:img {:src "/img/s.gif", :height "10", :width "0"}]
[:table {:width "100%", :cellspacing "0", :cellpadding "1"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}]]]]
[:br]
[:center
[:span {:class "yclinks"}
[:a {:class "pagebottomgray", :href "/#!/formatting"} "Formatting"] " | "
[:a {:class "pagebottomgray", :href "/#!/guidelines"} "Guidelines"] " | "
[:a {:class "pagebottomgray", :href "/#!/faq"} "FAQ"] " | "
[:a {:class "pagebottomgray", :href "/rss"} "RSS"] " | "
[:a {:class "pagebottomgray", :href "https://twitter.com/clojure_news"} "Twitter"] " | "
[:a {:class "pagebottomgray", :href "https://github.com/ertugrulcetin/ClojureNews"} "GitHub"] " | "
[:a {:class "pagebottomgray", :href "mailto:<EMAIL>"} "Contact"]]
[:br]
[:br]]]]]]]
[:script {:src "/js/clojure-news.js", :type "text/javascript"}]
[:script (resource-util/create-google-analytics-code "UA-54741200-3")]]]))
:handle-exception (fn [_]
"Something went wrong")))
;;RSS feed
(defn get-rss-feed
[]
(resource :allowed-methods [:get]
:available-media-types ["application/rss+xml" "application/rdf+xml;q=0.8" "application/atom+xml;q=0.6" "application/xml;q=0.4" "text/xml;q=0.4"]
:handle-ok (fn [_]
(let [data-per-page-inc page-util/data-per-page
stories (get-entry-by-page "story" 1 data-per-page-inc page-util/last-n-days)]
(resource-util/create-rss-feed
(for [story stories]
(resource-util/create-rss-item (str/escape (:title story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(str/escape (:url story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(:created-date story)
(str "https://clojure.news/#!/story/" (:_id story)))))))
:handle-exception #(resource-util/get-exception-message %)))
;;Robots.txt
(defn get-robots-txt
[]
(resource :allowed-methods [:get]
:available-media-types ["text/plain"]
:handle-ok (fn [_]
"User-agent: *\nAllow: /")
:handle-exception #(resource-util/get-exception-message %)))
;;Story
(defn create-story
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)]
(check-submit-type type)
(check-story-type type)
(check-submit-title title)
(check-submit-url url)
(let [story (entry-dao/create-story (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/get-pure-url (str/trim url))
(resource-util/get-username ctx))]
(user-dao/inc-user-karma-by-username (resource-util/get-username ctx))
{:cn-story story})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
stories (get-entry-by-page "story" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-stories (if (= (count stories) data-per-page-inc) (butlast stories) stories)]
(if-let [user (get-user ctx)]
{:story-entry real-stories
:story-own-entries (get-own-entries (:username user) stories)
:story-upvoted-entries (get-upvoted-entries (:username user) stories)
:more? (= data-per-page-inc (count stories))}
{:story-entry real-stories
:more? (= data-per-page-inc (count stories))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:story-entry (entry-dao/find-by-id id)
:story-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-story-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :story-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "story-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [story (check-entry-exist id)]
{:story-entry story
:owner? (= (:created-by story) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-story-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)]
(check-submit-title title)
(entry-dao/edit-story-by-id id (resource-util/capitalize (str/trim title)))
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-story-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by story))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Ask
(defn create-ask
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-type type)
(check-ask-type type)
(check-submit-title title)
(check-submit-text text)
(let [ask (entry-dao/create-ask (resource-util/capitalize (str/trim title))
(str/trim text)
(:username (:user-obj ctx)))]
(user-dao/inc-user-karma-by-username (:created-by ask))
{:cn-ask ask})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-ask :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
asks (get-entry-by-page "ask" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-asks (if (= (count asks) data-per-page-inc) (butlast asks) asks)]
(if-let [user (get-user ctx)]
{:ask-entry real-asks
:ask-own-entries (get-own-entries (:username user) asks)
:ask-upvoted-entries (get-upvoted-entries (:username user) asks)
:more? (= data-per-page-inc (count asks))}
{:ask-entry real-asks
:more? (= data-per-page-inc (count asks))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:ask-entry (entry-dao/find-by-id id)
:ask-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-ask-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :ask-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "ask-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [ask (check-entry-exist id)]
{:ask-entry ask
:owner? (= (:created-by ask) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-ask-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-title title)
(check-submit-text text)
(entry-dao/edit-ask-by-id id (resource-util/capitalize (str/trim title)) text)
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-ask-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by ask))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Newest Ask and Story
(defn get-newest-stories-and-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [entries (entry-dao/get-newest-stories-and-asks (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:newest-entry entries
:newest-own-entries (get-own-entries (:username user) entries)
:newest-upvoted-entries (get-upvoted-entries (:username user) entries)
:more? (= page-util/data-per-page (count entries))}
{:newest-entry entries
:more? (= page-util/data-per-page (count entries))})))
:handle-exception #(resource-util/get-exception-message %)))
;;Job
(defn create-job
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(let [username (resource-util/get-username ctx)]
(job-dao/create-job (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-jobs-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [jobs (job-dao/get-last-n-days-jobs (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:job-entry jobs
:job-own-entries (get-own-jobs (:username user) jobs)
:more? (= page-util/data-per-page (count jobs))}
{:job-entry jobs
:more? (= page-util/data-per-page (count jobs))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-job-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [job (check-job-exist id)]
{:job-entry job
:owner? (= (:created-by job) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-job-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(job-dao/edit-job-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-job-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(job-dao/delete-job-by-id id)
(user-dao/dec-user-karma-by-username (:created-by job))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Event
(defn create-event
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year)
(let [username (resource-util/get-username ctx)
starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/create-event (resource-util/capitalize (str/trim title))
(str/trim url)
starting-date
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-events-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [events (event-dao/get-last-n-days-events (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:event-entry events
:event-own-entries (get-own-events (:username user) events)
:more? (= page-util/data-per-page (count events))}
{:event-entry events
:more? (= page-util/data-per-page (count events))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-event-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [event (check-event-exist id)]
{:event-entry event
:owner? (= (:created-by event) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-event-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year))
(let [starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/edit-event-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
starting-date))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-event-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(event-dao/delete-event-by-id id)
(user-dao/dec-user-karma-by-username (:created-by event))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-own-entries
[username entries]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] entries)
own-entries (entry-dao/get-entries-by-username-and-entries-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-upvoted-entries
[username entries]
(let [ids (reduce #(conj %1 (str (:_id %2))) [] entries)
upvoted-entries (upvote-dao/get-upvotes-by-username-and-upvotes-in-it username ids)]
(reduce #(conj %1 (:entry-id %2)) [] upvoted-entries)))
(defn get-entry-by-page
[entry-type page data-per-page last-n-days]
(let [entries (entry-dao/get-last-n-days-entries entry-type last-n-days)
ranked-entries (resource-util/create-ranked-links entries)]
(resource-util/get-links page data-per-page ranked-entries)))
(defn get-own-jobs
[username jobs]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] jobs)
own-entries (job-dao/get-entries-by-username-and-jobs-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-own-events
[username events]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] events)
own-entries (event-dao/get-entries-by-username-and-events-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-user
[ctx]
(if-let [cookie (resource-util/get-cookie ctx)]
(if-let [user (user-dao/find-by-username (resource-util/get-username-from-cookie ctx))]
(if (= cookie (:cookie user))
{:username (:username user)
:karma (:karma user)}))))
(defn group-by-parent-and-sort-by-vote
[comment-map]
(reduce #(assoc %1 (first %2) (vec
(sort-by :upvote (fn [a b]
(compare b a)) (second %2))))
{}
(group-by :str-parent-comment-id comment-map)))
(defn create-comment-tree
[key grouped-comments coll]
(let [comments (get grouped-comments key)]
(if (nil? comments)
(seq coll)
(for [comment* (get grouped-comments key)]
(if (nil? (:str-parent-comment-id comment*))
(create-comment-tree (:str-id comment*) grouped-comments (conj coll [comment*]))
(create-comment-tree (:str-id comment*) grouped-comments (update-in coll [(dec (count coll))] conj comment*)))))))
(defn flat-one-level [coll]
(mapcat #(if (vector? %) [%] %) coll))
(defn flat-until-every-vector
[coll]
(if (every? vector? coll)
coll
(recur (flat-one-level coll))))
(defn create-comments
[comments-map]
(let [grouped-comments (group-by-parent-and-sort-by-vote comments-map)
comment-tree (create-comment-tree nil grouped-comments [])]
(flatten
(reduce (fn [comment-coll comment-data]
(conj comment-coll (distinct
(flatten
(reduce (fn [x y]
(conj x
(reduce #(conj %1 (into {} %2)) [] (keep-indexed #(concat {:index %1} %2) y))))
[]
(flat-until-every-vector comment-data))))))
[] comment-tree))))
(defn check-submit-type
[type]
(when-not (validation/submit-type? type)
(throw (RuntimeException. "Not valid type."))))
(defn check-story-type
[type]
(when-not (= type "story")
(throw (RuntimeException. "Not valid story type."))))
(defn check-ask-type
[type]
(when-not (= type "ask")
(throw (RuntimeException. "Not valid ask type."))))
(defn check-submit-title
[title]
(when-not (validation/submit-title? title)
(throw (RuntimeException. (str "Please limit title to 80 characters.This had " (count title) ".")))))
(defn check-submit-url
[url]
(when-not (validation/submit-url? url)
(throw (RuntimeException. "Not valid url. Ex: https://www.google.com"))))
(defn check-submit-text
[text]
(when-not (validation/submit-text? text)
(throw (RuntimeException. "Please limit text to 2500 characters."))))
(defn check-submit-city
[city]
(when-not (validation/submit-city? city)
(throw (RuntimeException. error-message/city))))
(defn check-submit-country
[country]
(when-not (validation/submit-city? country)
(throw (RuntimeException. error-message/country))))
(defn check-submit-day
[day]
(when-not (validation/submit-day? day)
(throw (RuntimeException. error-message/day))))
(defn check-submit-month
[month]
(when-not (validation/submit-month? month)
(throw (RuntimeException. error-message/month))))
(defn check-submit-year
[year]
(when-not (validation/submit-year? year)
(throw (RuntimeException. error-message/year))))
(defn check-entry-exist
[id]
(try
(if-let [entry (entry-dao/find-by-id id)]
entry
(throw (RuntimeException. error-message/no-entry)))
(catch Exception e
(throw (RuntimeException. error-message/no-entry)))))
(defn check-job-exist
[id]
(try
(if-let [job (job-dao/find-by-id id)]
job
(throw (RuntimeException. error-message/no-job)))
(catch Exception e
(throw (RuntimeException. error-message/no-job)))))
(defn check-event-exist
[id]
(try
(if-let [event (event-dao/find-by-id id)]
event
(throw (RuntimeException. error-message/no-event)))
(catch Exception e
(throw (RuntimeException. error-message/no-event)))))
(defn check-entry-owner
[entry ctx]
(when-not (= (:created-by entry) (resource-util/get-username ctx))
(throw (RuntimeException. "You are not the owner."))))
(defn check-page-data-format
[page]
(try
(let [p-int (Integer/parseInt page)]
(when (<= p-int 0)
(throw (RuntimeException. "Not valid page number.")))
p-int)
(catch Exception e
(throw (RuntimeException. "Not valid page number.")))))
(defn calendar->date
[calendar]
(-> calendar .getTimeInMillis Date.))
| true |
(ns clj.controller.entry
(:require [liberator.core :refer [resource defresource]]
[clj.util.resource :as resource-util]
[clj.dao.user :as user-dao]
[clj.dao.entry :as entry-dao]
[clj.dao.entry-job :as job-dao]
[clj.dao.entry-event :as event-dao]
[clj.dao.comment-entry :as comment-entry-dao]
[clj.dao.upvote :as upvote-dao]
[hiccup.core :as hiccup]
[cljc.validation :as validation]
[cljc.error-messages :as error-message]
[cljc.page-util :as page-util]
[clojure.string :as str]
[monger.json])
(:import (java.util Calendar Date)))
(declare get-user
create-ask
create-entry
check-story-type
check-ask-type
check-submit-type
check-submit-title
check-submit-url
check-submit-text
check-submit-city
check-submit-country
check-submit-day
check-submit-month
check-submit-year
check-entry-exist
check-job-exist
check-entry-owner
check-page-data-format
check-event-exist
group-by-parent-and-sort-by-vote
create-comment-tree
flat-one-level
flat-until-every-vector
create-comments
get-entry-by-page
get-job-by-page
get-own-entries
get-upvoted-entries
get-own-jobs
get-own-events
calendar->date)
(defn home-page
[]
(resource :allowed-methods [:get]
:available-media-types ["text/html"]
:handle-ok (fn [ctx]
(hiccup/html [:html
[:head
[:meta {:http-equiv "Content-Type" :content "text/html; charset=UTF-8"}]
[:meta {:name "referrer" :content "origin"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:name "google-site-verification" :content "PI:KEY:<KEY>END_PI"}]
[:link {:rel "stylesheet" :type "text/css" :href "/css/news.css"}]
[:link {:rel "shortcut icon" :href "/img/logo.png"}]
[:style {:type "text/css"}]
[:title "Clojure News"]]
[:body {:data-gr-c-s-loaded "true" :id "bodyId"}
[:center
[:noscript "Please enable JavaScript!"]
[:table {:id "cnmain", :border "0", :cellpadding "0", :cellspacing "0", :width "85%", :bgcolor "#f6f6ef"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}
[:table {:border "0", :cellpadding "0", :cellspacing "0", :width "100%", :style "padding:2px"}
[:tbody
[:tr
[:td {:style "width:18px;padding-right:4px"}
[:a {:href "/"}
[:img {:src "/img/logo.png", :width "18", :height "18", :style "border:1px white solid;"}]]]
[:td {:style "line-height:12pt; height:10px;"}
[:span {:class "pagetop"}
[:b {:class "brandname"}
[:a {:id "headerMainId" :class "pagetopwhite", :href "/"} "Clojure News"]]
[:a {:id "headerStoryId" :class "pagetopwhite", :href "/#!/story"} "story"] " | "
[:a {:id "headerAskId" :class "pagetopwhite", :href "/#!/ask"} "ask"] " | "
[:a {:id "headerNewId" :class "pagetopwhite", :href "/#!/new"} "new"] " | "
[:a {:id "headerJobId" :class "pagetopwhite", :href "/#!/job"} "jobs"] " | "
[:a {:id "headerEventId" :class "pagetopwhite", :href "/#!/event"} "events"] " | "
[:a {:id "headerSubmitId" :class "pagetopwhite", :href "/#!/submit"} "submit"]]]
[:td {:style "text-align:right;padding-right:4px;"}
[:span {:id "pageTopId", :class "pagetop"}
(if-let [user (get-user ctx)]
[:div
[:a {:class "pagetopwhite", :id "loginId", :href (str "/#!/user/" (:username user))} (:username user)]
(str " (" (:karma user) ") | ")
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/logout"} "logout"]]
[:a {:class "pagetopwhite", :id "loginId", :href "/#!/login"} "login"])
]]]]]]]
[:tr {:style "height:10px"}]
[:tr
[:td
[:center
[:p
"Clojure News is in beta. Please don't hesitate to report bugs to "
[:a {:href "https://github.com/ertugrulcetin/ClojureNews/issues" :target "_blank"}
[:u
"the github issues page."]]]]]]
[:tr
[:td {:id "messageContainerId"}]]
[:tr
[:td {:id "mainContainerId"}
[:p "Loading..."]]]
[:tr
[:td
[:img {:src "/img/s.gif", :height "10", :width "0"}]
[:table {:width "100%", :cellspacing "0", :cellpadding "1"}
[:tbody
[:tr
[:td {:bgcolor "#5fba7d"}]]]]
[:br]
[:center
[:span {:class "yclinks"}
[:a {:class "pagebottomgray", :href "/#!/formatting"} "Formatting"] " | "
[:a {:class "pagebottomgray", :href "/#!/guidelines"} "Guidelines"] " | "
[:a {:class "pagebottomgray", :href "/#!/faq"} "FAQ"] " | "
[:a {:class "pagebottomgray", :href "/rss"} "RSS"] " | "
[:a {:class "pagebottomgray", :href "https://twitter.com/clojure_news"} "Twitter"] " | "
[:a {:class "pagebottomgray", :href "https://github.com/ertugrulcetin/ClojureNews"} "GitHub"] " | "
[:a {:class "pagebottomgray", :href "mailto:PI:EMAIL:<EMAIL>END_PI"} "Contact"]]
[:br]
[:br]]]]]]]
[:script {:src "/js/clojure-news.js", :type "text/javascript"}]
[:script (resource-util/create-google-analytics-code "UA-54741200-3")]]]))
:handle-exception (fn [_]
"Something went wrong")))
;;RSS feed
(defn get-rss-feed
[]
(resource :allowed-methods [:get]
:available-media-types ["application/rss+xml" "application/rdf+xml;q=0.8" "application/atom+xml;q=0.6" "application/xml;q=0.4" "text/xml;q=0.4"]
:handle-ok (fn [_]
(let [data-per-page-inc page-util/data-per-page
stories (get-entry-by-page "story" 1 data-per-page-inc page-util/last-n-days)]
(resource-util/create-rss-feed
(for [story stories]
(resource-util/create-rss-item (str/escape (:title story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(str/escape (:url story) {\< "<", \> ">", \& "&", \" """, \' "'"})
(:created-date story)
(str "https://clojure.news/#!/story/" (:_id story)))))))
:handle-exception #(resource-util/get-exception-message %)))
;;Robots.txt
(defn get-robots-txt
[]
(resource :allowed-methods [:get]
:available-media-types ["text/plain"]
:handle-ok (fn [_]
"User-agent: *\nAllow: /")
:handle-exception #(resource-util/get-exception-message %)))
;;Story
(defn create-story
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)]
(check-submit-type type)
(check-story-type type)
(check-submit-title title)
(check-submit-url url)
(let [story (entry-dao/create-story (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/get-pure-url (str/trim url))
(resource-util/get-username ctx))]
(user-dao/inc-user-karma-by-username (resource-util/get-username ctx))
{:cn-story story})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
stories (get-entry-by-page "story" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-stories (if (= (count stories) data-per-page-inc) (butlast stories) stories)]
(if-let [user (get-user ctx)]
{:story-entry real-stories
:story-own-entries (get-own-entries (:username user) stories)
:story-upvoted-entries (get-upvoted-entries (:username user) stories)
:more? (= data-per-page-inc (count stories))}
{:story-entry real-stories
:more? (= data-per-page-inc (count stories))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:story-entry (entry-dao/find-by-id id)
:story-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-story-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :story-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "story-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-story-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [story (check-entry-exist id)]
{:story-entry story
:owner? (= (:created-by story) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-story-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)]
(check-submit-title title)
(entry-dao/edit-story-by-id id (resource-util/capitalize (str/trim title)))
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-story-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [story (check-entry-exist id)]
(check-entry-owner story ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by story))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Ask
(defn create-ask
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-type type)
(check-ask-type type)
(check-submit-title title)
(check-submit-text text)
(let [ask (entry-dao/create-ask (resource-util/capitalize (str/trim title))
(str/trim text)
(:username (:user-obj ctx)))]
(user-dao/inc-user-karma-by-username (:created-by ask))
{:cn-ask ask})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-ask :_id)})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [data-per-page-inc (+ page-util/data-per-page 1)
asks (get-entry-by-page "ask" (check-page-data-format page) data-per-page-inc page-util/last-n-days)
real-asks (if (= (count asks) data-per-page-inc) (butlast asks) asks)]
(if-let [user (get-user ctx)]
{:ask-entry real-asks
:ask-own-entries (get-own-entries (:username user) asks)
:ask-upvoted-entries (get-upvoted-entries (:username user) asks)
:more? (= data-per-page-inc (count asks))}
{:ask-entry real-asks
:more? (= data-per-page-inc (count asks))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(check-entry-exist id)
(let [user (get-user ctx)
response {:user-obj user
:ask-entry (entry-dao/find-by-id id)
:ask-comments (create-comments (reduce #(conj %1 (assoc %2 :str-id (str (:_id %2))
:str-parent-comment-id (if (:parent-comment-id %2)
(:parent-comment-id %2)
nil)))
[] (comment-entry-dao/get-comments-by-entry-id id)))
:upvoted? (upvote-dao/find-ask-upvote-by-created-by-and-entry-id (:username user) id)}]
(if user
(assoc response :ask-upvoted-comments (reduce #(conj %1 (:comment-id %2)) [] (upvote-dao/find-by-type-and-entry-id "ask-comment" id)))
response)))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-ask-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [ask (check-entry-exist id)]
{:ask-entry ask
:owner? (= (:created-by ask) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-ask-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
text (:text data-as-map)]
(check-submit-title title)
(check-submit-text text)
(entry-dao/edit-ask-by-id id (resource-util/capitalize (str/trim title)) text)
{:cn-story id})))
:handle-created (fn [ctx]
{:entry-id (-> ctx :cn-story)})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-ask-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [ask (check-entry-exist id)]
(check-entry-owner ask ctx)
(entry-dao/delete-entry-by-id id)
(comment-entry-dao/delete-comments-by-entry-id id)
(upvote-dao/delete-upvotes-by-entry-id id)
(user-dao/dec-user-karma-by-username (:created-by ask))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Newest Ask and Story
(defn get-newest-stories-and-stories-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [entries (entry-dao/get-newest-stories-and-asks (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:newest-entry entries
:newest-own-entries (get-own-entries (:username user) entries)
:newest-upvoted-entries (get-upvoted-entries (:username user) entries)
:more? (= page-util/data-per-page (count entries))}
{:newest-entry entries
:more? (= page-util/data-per-page (count entries))})))
:handle-exception #(resource-util/get-exception-message %)))
;;Job
(defn create-job
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(let [username (resource-util/get-username ctx)]
(job-dao/create-job (resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-jobs-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [jobs (job-dao/get-last-n-days-jobs (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:job-entry jobs
:job-own-entries (get-own-jobs (:username user) jobs)
:more? (= page-util/data-per-page (count jobs))}
{:job-entry jobs
:more? (= page-util/data-per-page (count jobs))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-job-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [job (check-job-exist id)]
{:job-entry job
:owner? (= (:created-by job) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-job-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
remote? (:remote? data-as-map)]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(job-dao/edit-job-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
remote?))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-job-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [job (check-job-exist id)]
(check-entry-owner job ctx)
(job-dao/delete-job-by-id id)
(user-dao/dec-user-karma-by-username (:created-by job))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
;;Event
(defn create-event
[]
(resource :allowed-methods [:put]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:put! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
type (:type data-as-map)
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(check-submit-type type)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year)
(let [username (resource-util/get-username ctx)
starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/create-event (resource-util/capitalize (str/trim title))
(str/trim url)
starting-date
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
username)
(user-dao/inc-user-karma-by-username username))))
:handle-created (fn [_]
{:created? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-events-by-page
[page]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [events (event-dao/get-last-n-days-events (check-page-data-format page) page-util/data-per-page)]
(if-let [user (get-user ctx)]
{:event-entry events
:event-own-entries (get-own-events (:username user) events)
:more? (= page-util/data-per-page (count events))}
{:event-entry events
:more? (= page-util/data-per-page (count events))})))
:handle-exception #(resource-util/get-exception-message %)))
(defn get-event-litte-info-by-id
[id]
(resource :allowed-methods [:get]
:available-media-types resource-util/avaliable-media-types
:handle-ok (fn [ctx]
(let [event (check-event-exist id)]
{:event-entry event
:owner? (= (:created-by event) (-> ctx get-user :username))}))
:handle-exception #(resource-util/get-exception-message %)))
(defn edit-event-by-id
[id]
(resource :allowed-methods [:post]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:post! (fn [ctx]
(let [data-as-map (resource-util/convert-data-map (::data ctx))
title (:title data-as-map)
url (:url data-as-map)
city (:city data-as-map)
country (:country data-as-map)
starting-date-day (:starting-date-day data-as-map)
starting-date-month (:starting-date-month data-as-map)
starting-date-year (:starting-date-year data-as-map)]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(check-submit-title title)
(check-submit-url url)
(check-submit-city city)
(check-submit-country country)
(check-submit-day starting-date-day)
(check-submit-month starting-date-month)
(check-submit-year starting-date-year))
(let [starting-date (calendar->date (doto (Calendar/getInstance)
(.set (Calendar/DAY_OF_MONTH) (Integer/parseInt starting-date-day))
(.set (Calendar/MONTH) (- (Integer/parseInt starting-date-month) 1))
(.set (Calendar/YEAR) (Integer/parseInt starting-date-year))))]
(event-dao/edit-event-by-id id
(resource-util/capitalize (str/trim title))
(str/trim url)
(resource-util/capitalize (str/trim city))
(resource-util/capitalize (str/trim country))
starting-date))))
:handle-created (fn [_]
{:updated? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn delete-event-by-id
[id]
(resource :allowed-methods [:delete]
:available-media-types resource-util/avaliable-media-types
:known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types)
:malformed? #(resource-util/parse-json % ::data)
:authorized? #(resource-util/auth? %)
:new? (fn [_]
false)
:respond-with-entity? (fn [_]
true)
:delete! (fn [ctx]
(let [event (check-event-exist id)]
(check-entry-owner event ctx)
(event-dao/delete-event-by-id id)
(user-dao/dec-user-karma-by-username (:created-by event))))
:handle-ok (fn [_]
{:deleted? true})
:handle-exception #(resource-util/get-exception-message %)))
(defn get-own-entries
[username entries]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] entries)
own-entries (entry-dao/get-entries-by-username-and-entries-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-upvoted-entries
[username entries]
(let [ids (reduce #(conj %1 (str (:_id %2))) [] entries)
upvoted-entries (upvote-dao/get-upvotes-by-username-and-upvotes-in-it username ids)]
(reduce #(conj %1 (:entry-id %2)) [] upvoted-entries)))
(defn get-entry-by-page
[entry-type page data-per-page last-n-days]
(let [entries (entry-dao/get-last-n-days-entries entry-type last-n-days)
ranked-entries (resource-util/create-ranked-links entries)]
(resource-util/get-links page data-per-page ranked-entries)))
(defn get-own-jobs
[username jobs]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] jobs)
own-entries (job-dao/get-entries-by-username-and-jobs-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-own-events
[username events]
(let [object-ids (reduce #(conj %1 (:_id %2)) [] events)
own-entries (event-dao/get-entries-by-username-and-events-in-it username object-ids)]
(reduce #(conj %1 (str (:_id %2))) [] own-entries)))
(defn get-user
[ctx]
(if-let [cookie (resource-util/get-cookie ctx)]
(if-let [user (user-dao/find-by-username (resource-util/get-username-from-cookie ctx))]
(if (= cookie (:cookie user))
{:username (:username user)
:karma (:karma user)}))))
(defn group-by-parent-and-sort-by-vote
[comment-map]
(reduce #(assoc %1 (first %2) (vec
(sort-by :upvote (fn [a b]
(compare b a)) (second %2))))
{}
(group-by :str-parent-comment-id comment-map)))
(defn create-comment-tree
[key grouped-comments coll]
(let [comments (get grouped-comments key)]
(if (nil? comments)
(seq coll)
(for [comment* (get grouped-comments key)]
(if (nil? (:str-parent-comment-id comment*))
(create-comment-tree (:str-id comment*) grouped-comments (conj coll [comment*]))
(create-comment-tree (:str-id comment*) grouped-comments (update-in coll [(dec (count coll))] conj comment*)))))))
(defn flat-one-level [coll]
(mapcat #(if (vector? %) [%] %) coll))
(defn flat-until-every-vector
[coll]
(if (every? vector? coll)
coll
(recur (flat-one-level coll))))
(defn create-comments
[comments-map]
(let [grouped-comments (group-by-parent-and-sort-by-vote comments-map)
comment-tree (create-comment-tree nil grouped-comments [])]
(flatten
(reduce (fn [comment-coll comment-data]
(conj comment-coll (distinct
(flatten
(reduce (fn [x y]
(conj x
(reduce #(conj %1 (into {} %2)) [] (keep-indexed #(concat {:index %1} %2) y))))
[]
(flat-until-every-vector comment-data))))))
[] comment-tree))))
(defn check-submit-type
[type]
(when-not (validation/submit-type? type)
(throw (RuntimeException. "Not valid type."))))
(defn check-story-type
[type]
(when-not (= type "story")
(throw (RuntimeException. "Not valid story type."))))
(defn check-ask-type
[type]
(when-not (= type "ask")
(throw (RuntimeException. "Not valid ask type."))))
(defn check-submit-title
[title]
(when-not (validation/submit-title? title)
(throw (RuntimeException. (str "Please limit title to 80 characters.This had " (count title) ".")))))
(defn check-submit-url
[url]
(when-not (validation/submit-url? url)
(throw (RuntimeException. "Not valid url. Ex: https://www.google.com"))))
(defn check-submit-text
[text]
(when-not (validation/submit-text? text)
(throw (RuntimeException. "Please limit text to 2500 characters."))))
(defn check-submit-city
[city]
(when-not (validation/submit-city? city)
(throw (RuntimeException. error-message/city))))
(defn check-submit-country
[country]
(when-not (validation/submit-city? country)
(throw (RuntimeException. error-message/country))))
(defn check-submit-day
[day]
(when-not (validation/submit-day? day)
(throw (RuntimeException. error-message/day))))
(defn check-submit-month
[month]
(when-not (validation/submit-month? month)
(throw (RuntimeException. error-message/month))))
(defn check-submit-year
[year]
(when-not (validation/submit-year? year)
(throw (RuntimeException. error-message/year))))
(defn check-entry-exist
[id]
(try
(if-let [entry (entry-dao/find-by-id id)]
entry
(throw (RuntimeException. error-message/no-entry)))
(catch Exception e
(throw (RuntimeException. error-message/no-entry)))))
(defn check-job-exist
[id]
(try
(if-let [job (job-dao/find-by-id id)]
job
(throw (RuntimeException. error-message/no-job)))
(catch Exception e
(throw (RuntimeException. error-message/no-job)))))
(defn check-event-exist
[id]
(try
(if-let [event (event-dao/find-by-id id)]
event
(throw (RuntimeException. error-message/no-event)))
(catch Exception e
(throw (RuntimeException. error-message/no-event)))))
(defn check-entry-owner
[entry ctx]
(when-not (= (:created-by entry) (resource-util/get-username ctx))
(throw (RuntimeException. "You are not the owner."))))
(defn check-page-data-format
[page]
(try
(let [p-int (Integer/parseInt page)]
(when (<= p-int 0)
(throw (RuntimeException. "Not valid page number.")))
p-int)
(catch Exception e
(throw (RuntimeException. "Not valid page number.")))))
(defn calendar->date
[calendar]
(-> calendar .getTimeInMillis Date.))
|
[
{
"context": " :client-secret \"111\"\n ",
"end": 1039,
"score": 0.9879692196846008,
"start": 1036,
"tag": "KEY",
"value": "111"
},
{
"context": " :client-secret \"111\"\n ",
"end": 2076,
"score": 0.9703740477561951,
"start": 2073,
"tag": "KEY",
"value": "111"
}
] |
tools/github-crawler/test/github_crawler/core_test.clj
|
kuona/kuona
| 7 |
(ns github-crawler.core-test
(:require [midje.sweet :refer :all]
[kuona-api.core.cli :as cli]
[github-crawler.core :refer :all]))
(facts "about cli arguments"
(fact "arguments have defaults"
(cli/configure "foo" cli-options '()) => {:config "properties.edn",
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn"})
(fact "loads configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "111"
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "111"
:api-url "http://dashboard.kuona.io",
:force true
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => (contains {:force true})))
|
109125
|
(ns github-crawler.core-test
(:require [midje.sweet :refer :all]
[kuona-api.core.cli :as cli]
[github-crawler.core :refer :all]))
(facts "about cli arguments"
(fact "arguments have defaults"
(cli/configure "foo" cli-options '()) => {:config "properties.edn",
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn"})
(fact "loads configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "<KEY>"
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "<KEY>"
:api-url "http://dashboard.kuona.io",
:force true
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => (contains {:force true})))
| true |
(ns github-crawler.core-test
(:require [midje.sweet :refer :all]
[kuona-api.core.cli :as cli]
[github-crawler.core :refer :all]))
(facts "about cli arguments"
(fact "arguments have defaults"
(cli/configure "foo" cli-options '()) => {:config "properties.edn",
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn"})
(fact "loads configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "PI:KEY:<KEY>END_PI"
:api-url "http://dashboard.kuona.io",
:force false
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => {:config "test/test-properties.edn"
:client-id "000"
:client-secret "PI:KEY:<KEY>END_PI"
:api-url "http://dashboard.kuona.io",
:force true
:workspace "/Volumes/data-drive/workspace",
:page-file "page.edn",
:languages ["java" "javascript" "kotlin"]})
(fact "cli arguments override configuration from file"
(cli/configure "foo" cli-options '("-c" "test/test-properties.edn" "-f")) => (contains {:force true})))
|
[
{
"context": " :username \"foo\",\n :password \"bar\"},\n :get-params {},\n :poll-in",
"end": 1532,
"score": 0.9993909597396851,
"start": 1529,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :xapi-prefix \"/xapi\",\n :username \"foo\",\n :password \"bar\"},\n :batch",
"end": 1867,
"score": 0.982471227645874,
"start": 1864,
"tag": "USERNAME",
"value": "foo"
},
{
"context": " :username \"foo\",\n :password \"bar\"},\n :batch-size 50,\n :backoff",
"end": 1896,
"score": 0.999283492565155,
"start": 1893,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :get-params {}\n :source-username \"foo\"\n :source-password \"bar\"\n :so",
"end": 2349,
"score": 0.9254873394966125,
"start": 2346,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "ource-username \"foo\"\n :source-password \"bar\"\n :source-backoff-budget 1000\n ",
"end": 2383,
"score": 0.9992521405220032,
"start": 2380,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": "target-batch-size 50\n :target-username \"foo\"\n :target-password \"bar\"\n :ta",
"end": 2658,
"score": 0.9681834578514099,
"start": 2655,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "arget-username \"foo\"\n :target-password \"bar\"\n :target-backoff-budget 1000\n ",
"end": 2692,
"score": 0.9991534352302551,
"start": 2689,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :xapi-prefix \"/xapi\",\n :username \"foo\",\n :password \"bar\"},\n :get",
"end": 3602,
"score": 0.9887757301330566,
"start": 3599,
"tag": "USERNAME",
"value": "foo"
},
{
"context": " :username \"foo\",\n :password \"bar\"},\n :get-params {:limit 50},\n ",
"end": 3632,
"score": 0.999089241027832,
"start": 3629,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :xapi-prefix \"/xapi\",\n :username \"foo\",\n :password \"bar\"},\n :bat",
"end": 3986,
"score": 0.9941312670707703,
"start": 3983,
"tag": "USERNAME",
"value": "foo"
},
{
"context": " :username \"foo\",\n :password \"bar\"},\n :batch-size 50,\n :backo",
"end": 4016,
"score": 0.9990697503089905,
"start": 4013,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :get-params {}\n :source-username \"foo\"\n :source-password \"bar\"\n :so",
"end": 4604,
"score": 0.939030647277832,
"start": 4601,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "ource-username \"foo\"\n :source-password \"bar\"\n :source-backoff-budget 1000\n ",
"end": 4638,
"score": 0.9985098838806152,
"start": 4635,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": "arget-username \"foo\"\n :target-password \"bar\"\n :target-backoff-budget 1000\n ",
"end": 4946,
"score": 0.9987998604774475,
"start": 4943,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :username \"foo\",\n :password \"bar\"},\n :get-params {:limit 50},\n ",
"end": 5882,
"score": 0.9994326233863831,
"start": 5879,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": " :xapi-prefix \"/xapi\",\n :username \"foo\",\n :password \"bar\"},\n :batch",
"end": 6226,
"score": 0.9661598801612854,
"start": 6223,
"tag": "USERNAME",
"value": "foo"
},
{
"context": " :username \"foo\",\n :password \"bar\"},\n :batch-size 50,\n :backoff",
"end": 6255,
"score": 0.9993920922279358,
"start": 6252,
"tag": "PASSWORD",
"value": "bar"
},
{
"context": "ource-username \"baz\"\n :source-password \"quxx\"\n :source-backoff-budget 999\n ",
"end": 6659,
"score": 0.9993186593055725,
"start": 6655,
"tag": "PASSWORD",
"value": "quxx"
},
{
"context": "arget-batch-size 100\n :target-username \"baz\"\n :target-password \"quxx\"\n :t",
"end": 6932,
"score": 0.9982680678367615,
"start": 6929,
"tag": "USERNAME",
"value": "baz"
},
{
"context": "arget-username \"baz\"\n :target-password \"quxx\"\n :target-backoff-budget 999\n ",
"end": 6967,
"score": 0.9993492364883423,
"start": 6963,
"tag": "PASSWORD",
"value": "quxx"
},
{
"context": " :xapi-prefix \"/xapi2\",\n :username \"baz\",\n :password \"quxx\"},\n :",
"end": 7644,
"score": 0.9983034133911133,
"start": 7641,
"tag": "USERNAME",
"value": "baz"
},
{
"context": " :username \"baz\",\n :password \"quxx\"},\n :get-params {:format \"exact\"\n ",
"end": 7676,
"score": 0.9993155002593994,
"start": 7672,
"tag": "PASSWORD",
"value": "quxx"
},
{
"context": " :xapi-prefix \"/xapi2\",\n :username \"baz\",\n :password \"quxx\"},\n :",
"end": 8082,
"score": 0.9966847896575928,
"start": 8079,
"tag": "USERNAME",
"value": "baz"
},
{
"context": " :username \"baz\",\n :password \"quxx\"},\n :batch-size 100,\n :ba",
"end": 8114,
"score": 0.9993095993995667,
"start": 8110,
"tag": "PASSWORD",
"value": "quxx"
}
] |
src/test/com/yetanalytics/xapipe/cli_test.clj
|
yetanalytics/xapipe
| 3 |
(ns com.yetanalytics.xapipe.cli-test
(:require [clojure.test :refer :all]
[com.yetanalytics.xapipe.cli :refer :all]
[com.yetanalytics.xapipe.store :as store]
[com.yetanalytics.xapipe.test-support :as sup]))
(use-fixtures :once (sup/instrument-fixture))
(deftest create-store-test
(is (satisfies? store/XapipeStore (create-store {:storage :noop})))
(is (satisfies? store/XapipeStore (create-store {:storage :redis
:redis-uri "redis://0.0.0.0:6379"
:refis-prefix "whatever"})))
(is (satisfies? store/XapipeStore (create-store {:storage :mem}))))
(deftest parse-lrs-url-test
(is (= {:url-base "http://0.0.0.0:8080", :xapi-prefix "/xapi"}
(parse-lrs-url "http://0.0.0.0:8080/xapi"))))
(deftest options->client-opts-test
(is (= {:conn-mgr-opts
{:timeout 10,
:threads 4,
:default-per-route 2,
:io-config {:io-thread-count 16}}}
(options->client-opts
{:conn-timeout 10
:conn-threads 4
:conn-default-per-route 2
:conn-insecure? false
:conn-io-thread-count 16}))))
(deftest options->config-test
(is (= {:get-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 100
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:get-params {},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {},
:statement-buffer-size 1000,
:batch-buffer-size 100}
(options->config
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "bar"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "bar"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 100
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest create-job-test
(is (= {:id "foo",
:version 0,
:config
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}},
:state
{:status :init,
:cursor "1970-01-01T00:00:00.000000000Z",
:source {:errors []},
:target {:errors []},
:errors [],
:filter {}}}
(create-job
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "bar"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "bar"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 50
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest reconfigure-with-options-test
(let [reconfigured
(reconfigure-with-options
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "bar"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}}
{:job-id "foo"
:source-url "http://0.0.0.0:8082/xapi2"
:source-batch-size 100
:source-poll-interval 3000
:get-params {:format "exact"}
:source-username "baz"
:source-password "quxx"
:source-backoff-budget 999
:source-backoff-max-attempt 9
:source-backoff-j-range 9
:source-backoff-initial 2
:target-url "http://0.0.0.0:8083/xapi2"
:target-batch-size 100
:target-username "baz"
:target-password "quxx"
:target-backoff-budget 999
:target-backoff-max-attempt 9
:target-backoff-j-range 9
:target-backoff-initial 2
:get-buffer-size 200
:batch-timeout 300
:cleanup-buffer-size 100
:statement-buffer-size 10000
:batch-buffer-size 1000})]
(is (= {:get-buffer-size 200,
:batch-timeout 300,
:statement-buffer-size 10000,
:batch-buffer-size 1000,
:cleanup-buffer-size 100,
:source
{:request-config
{:url-base "http://0.0.0.0:8082",
:xapi-prefix "/xapi2",
:username "baz",
:password "quxx"},
:get-params {:format "exact"
:limit 100},
:poll-interval 3000,
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:target
{:request-config
{:url-base "http://0.0.0.0:8083",
:xapi-prefix "/xapi2",
:username "baz",
:password "quxx"},
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:filter {}}
reconfigured))))
|
92992
|
(ns com.yetanalytics.xapipe.cli-test
(:require [clojure.test :refer :all]
[com.yetanalytics.xapipe.cli :refer :all]
[com.yetanalytics.xapipe.store :as store]
[com.yetanalytics.xapipe.test-support :as sup]))
(use-fixtures :once (sup/instrument-fixture))
(deftest create-store-test
(is (satisfies? store/XapipeStore (create-store {:storage :noop})))
(is (satisfies? store/XapipeStore (create-store {:storage :redis
:redis-uri "redis://0.0.0.0:6379"
:refis-prefix "whatever"})))
(is (satisfies? store/XapipeStore (create-store {:storage :mem}))))
(deftest parse-lrs-url-test
(is (= {:url-base "http://0.0.0.0:8080", :xapi-prefix "/xapi"}
(parse-lrs-url "http://0.0.0.0:8080/xapi"))))
(deftest options->client-opts-test
(is (= {:conn-mgr-opts
{:timeout 10,
:threads 4,
:default-per-route 2,
:io-config {:io-thread-count 16}}}
(options->client-opts
{:conn-timeout 10
:conn-threads 4
:conn-default-per-route 2
:conn-insecure? false
:conn-io-thread-count 16}))))
(deftest options->config-test
(is (= {:get-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 100
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:get-params {},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {},
:statement-buffer-size 1000,
:batch-buffer-size 100}
(options->config
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "<PASSWORD>"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "<PASSWORD>"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 100
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest create-job-test
(is (= {:id "foo",
:version 0,
:config
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}},
:state
{:status :init,
:cursor "1970-01-01T00:00:00.000000000Z",
:source {:errors []},
:target {:errors []},
:errors [],
:filter {}}}
(create-job
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "<PASSWORD>"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "<PASSWORD>"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 50
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest reconfigure-with-options-test
(let [reconfigured
(reconfigure-with-options
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "<PASSWORD>"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}}
{:job-id "foo"
:source-url "http://0.0.0.0:8082/xapi2"
:source-batch-size 100
:source-poll-interval 3000
:get-params {:format "exact"}
:source-username "baz"
:source-password "<PASSWORD>"
:source-backoff-budget 999
:source-backoff-max-attempt 9
:source-backoff-j-range 9
:source-backoff-initial 2
:target-url "http://0.0.0.0:8083/xapi2"
:target-batch-size 100
:target-username "baz"
:target-password "<PASSWORD>"
:target-backoff-budget 999
:target-backoff-max-attempt 9
:target-backoff-j-range 9
:target-backoff-initial 2
:get-buffer-size 200
:batch-timeout 300
:cleanup-buffer-size 100
:statement-buffer-size 10000
:batch-buffer-size 1000})]
(is (= {:get-buffer-size 200,
:batch-timeout 300,
:statement-buffer-size 10000,
:batch-buffer-size 1000,
:cleanup-buffer-size 100,
:source
{:request-config
{:url-base "http://0.0.0.0:8082",
:xapi-prefix "/xapi2",
:username "baz",
:password "<PASSWORD>"},
:get-params {:format "exact"
:limit 100},
:poll-interval 3000,
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:target
{:request-config
{:url-base "http://0.0.0.0:8083",
:xapi-prefix "/xapi2",
:username "baz",
:password "<PASSWORD>"},
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:filter {}}
reconfigured))))
| true |
(ns com.yetanalytics.xapipe.cli-test
(:require [clojure.test :refer :all]
[com.yetanalytics.xapipe.cli :refer :all]
[com.yetanalytics.xapipe.store :as store]
[com.yetanalytics.xapipe.test-support :as sup]))
(use-fixtures :once (sup/instrument-fixture))
(deftest create-store-test
(is (satisfies? store/XapipeStore (create-store {:storage :noop})))
(is (satisfies? store/XapipeStore (create-store {:storage :redis
:redis-uri "redis://0.0.0.0:6379"
:refis-prefix "whatever"})))
(is (satisfies? store/XapipeStore (create-store {:storage :mem}))))
(deftest parse-lrs-url-test
(is (= {:url-base "http://0.0.0.0:8080", :xapi-prefix "/xapi"}
(parse-lrs-url "http://0.0.0.0:8080/xapi"))))
(deftest options->client-opts-test
(is (= {:conn-mgr-opts
{:timeout 10,
:threads 4,
:default-per-route 2,
:io-config {:io-thread-count 16}}}
(options->client-opts
{:conn-timeout 10
:conn-threads 4
:conn-default-per-route 2
:conn-insecure? false
:conn-io-thread-count 16}))))
(deftest options->config-test
(is (= {:get-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 100
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:get-params {},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {},
:statement-buffer-size 1000,
:batch-buffer-size 100}
(options->config
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "PI:PASSWORD:<PASSWORD>END_PI"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "PI:PASSWORD:<PASSWORD>END_PI"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 100
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest create-job-test
(is (= {:id "foo",
:version 0,
:config
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}},
:state
{:status :init,
:cursor "1970-01-01T00:00:00.000000000Z",
:source {:errors []},
:target {:errors []},
:errors [],
:filter {}}}
(create-job
{:job-id "foo"
:source-url "http://0.0.0.0:8080/xapi"
:source-batch-size 50
:source-poll-interval 1000
:get-params {}
:source-username "foo"
:source-password "PI:PASSWORD:<PASSWORD>END_PI"
:source-backoff-budget 1000
:source-backoff-max-attempt 10
:source-backoff-j-range 10
:source-backoff-initial 1
:target-url "http://0.0.0.0:8081/xapi"
:target-batch-size 50
:target-username "foo"
:target-password "PI:PASSWORD:<PASSWORD>END_PI"
:target-backoff-budget 1000
:target-backoff-max-attempt 10
:target-backoff-j-range 10
:target-backoff-initial 1
:get-buffer-size 100
:batch-timeout 200
:cleanup-buffer-size 50
:filter-template-profile-urls []
:filter-template-ids []
:filter-pattern-profile-urls []
:filter-pattern-ids []
:statement-buffer-size 1000
:batch-buffer-size 100}))))
(deftest reconfigure-with-options-test
(let [reconfigured
(reconfigure-with-options
{:get-buffer-size 100,
:statement-buffer-size 1000,
:batch-buffer-size 100,
:batch-timeout 200,
:cleanup-buffer-size 50,
:source
{:request-config
{:url-base "http://0.0.0.0:8080",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:get-params {:limit 50},
:poll-interval 1000,
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:target
{:request-config
{:url-base "http://0.0.0.0:8081",
:xapi-prefix "/xapi",
:username "foo",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:batch-size 50,
:backoff-opts
{:budget 1000, :max-attempt 10, :j-range 10, :initial 1}},
:filter {}}
{:job-id "foo"
:source-url "http://0.0.0.0:8082/xapi2"
:source-batch-size 100
:source-poll-interval 3000
:get-params {:format "exact"}
:source-username "baz"
:source-password "PI:PASSWORD:<PASSWORD>END_PI"
:source-backoff-budget 999
:source-backoff-max-attempt 9
:source-backoff-j-range 9
:source-backoff-initial 2
:target-url "http://0.0.0.0:8083/xapi2"
:target-batch-size 100
:target-username "baz"
:target-password "PI:PASSWORD:<PASSWORD>END_PI"
:target-backoff-budget 999
:target-backoff-max-attempt 9
:target-backoff-j-range 9
:target-backoff-initial 2
:get-buffer-size 200
:batch-timeout 300
:cleanup-buffer-size 100
:statement-buffer-size 10000
:batch-buffer-size 1000})]
(is (= {:get-buffer-size 200,
:batch-timeout 300,
:statement-buffer-size 10000,
:batch-buffer-size 1000,
:cleanup-buffer-size 100,
:source
{:request-config
{:url-base "http://0.0.0.0:8082",
:xapi-prefix "/xapi2",
:username "baz",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:get-params {:format "exact"
:limit 100},
:poll-interval 3000,
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:target
{:request-config
{:url-base "http://0.0.0.0:8083",
:xapi-prefix "/xapi2",
:username "baz",
:password "PI:PASSWORD:<PASSWORD>END_PI"},
:batch-size 100,
:backoff-opts
{:budget 999, :max-attempt 9, :j-range 9, :initial 2}},
:filter {}}
reconfigured))))
|
[
{
"context": "(ns crawler.core\n #^{:author \"Chris Currivan\"\n :doc \"Code for crawling Reddit and Hacker N",
"end": 45,
"score": 0.9998818635940552,
"start": 31,
"tag": "NAME",
"value": "Chris Currivan"
},
{
"context": "for each link\n(html/defsnippet link-model \"/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010",
"end": 3800,
"score": 0.9987438321113586,
"start": 3789,
"tag": "USERNAME",
"value": "josephgallo"
},
{
"context": "or page\n(html/deftemplate merged-template \"/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010",
"end": 4150,
"score": 0.9986000061035156,
"start": 4139,
"tag": "USERNAME",
"value": "josephgallo"
}
] |
2010-04-07-enlive/crawler/core.clj
|
bruceadams/clojure-pgh
| 1 |
(ns crawler.core
#^{:author "Chris Currivan"
:doc "Code for crawling Reddit and Hacker News."}
(:refer-clojure)
(:use
[clojure.set]
[clojure.stacktrace]
[compojure.core]
[ring.adapter.jetty]
[ring.middleware.stacktrace])
(:require
[clojure.contrib.string :as string]
[net.cgrand.enlive-html :as html]
[com.twinql.clojure.http :as http])
(:import
java.util.Date))
(set! *warn-on-reflection* true)
;; crawl/scrape code
(def *hn-url* "http://news.ycombinator.com/")
(def *reddit-url* "http://www.reddit.com/")
(def *hn-selector*
[:td.title :a])
(def *reddit-title-selector*
[:div#siteTable.sitetable.linklisting
:p.title
:> :a]) ; only direct children of p.title
(def *reddit-points-selector*
[:div#siteTable.sitetable.linklisting
:div.score.unvoted])
(defn get-url
"Download html from a url."
[url]
(html/html-resource (java.net.URL. url)))
(defn get-with-user-agent
"Crawl page, specifying user agent, or defaulting to Chrome."
([url]
(let [user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US)
AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9"]
(get-with-user-agent url user-agent)))
([url user-agent]
(:content (http/get url
:as :string
:headers {"user-agent" user-agent}))))
(defn sort-headlines-points
"Sort seq of vecs of [headline points] by points descending."
[s]
(reverse (sort-by second s)))
(defn safe-parse-int
"Try to parse integer, or return 0."
[x]
(try
(Integer/parseInt x)
(catch NumberFormatException e
0)))
(defn hn-headlines
"Crawls HackerNews and extracts headlines."
([] (hn-headlines (get-url *hn-url*)))
([page] (map html/text (html/select page *hn-selector*))))
(defn hn-points
"Crawls HackerNews and extracts points."
([] (hn-points (get-url *hn-url*)))
([page] (map
#(-> %
html/text
((fn [s] (re-find #"\d+" s)))
Integer/parseInt)
(html/select page [:td.subtext html/first-child]))))
(defn hn-hrefs
"Crawls HackerNews and extracts hrefs."
([] (hn-hrefs (get-url *hn-url*)))
([page] (map #(get-in % [:attrs :href]) (html/select page *hn-selector*))))
(defn scrape-hn
"Scrapes HackerNews first page and returns vecs of [headline points]."
([]
(scrape-hn (get-url *hn-url*)))
([page]
(sort-headlines-points
(map vector
(hn-headlines page)
(hn-points page)
(hn-hrefs page)))))
(defn reddit-headlines
"Crawls reddit and extracts headlines."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map html/text
(html/select page *reddit-title-selector*))))
(defn reddit-points
"Crawls reddit and extracts points."
([] (reddit-points (get-url *reddit-url*)))
([page]
(map #(-> %
html/text
safe-parse-int)
(html/select page *reddit-points-selector*))))
(defn reddit-hrefs
"Crawls reddit and extracts hrefs."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map #(get-in % [:attrs :href])
(html/select page *reddit-title-selector*))))
(defn scrape-reddit
"Scrapes Reddit main page and returns vecs of [headline points hrefs]."
([]
(scrape-reddit (get-url *reddit-url*)))
([page]
(sort-headlines-points
(map vector
(reddit-headlines page)
(reddit-points page)
(reddit-hrefs page)))))
(defn scrape-both
"Scrape both Reddit and HackerNews, and berge the results."
[]
(sort-headlines-points
(concat (scrape-reddit)
(scrape-hn))))
;; enlive templating code
;; snippet template for each link
(html/defsnippet link-model "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/link.html" [:td]
[{points :points text :text href :href}]
[:td.points] (html/do-> (html/content (str points)))
[:a] (html/do->
(html/content text)
(html/set-attr :href href)))
;; template for page
(html/deftemplate merged-template "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/merged.html" [header items]
[:title] (html/content header)
[:h1] (html/content header)
[:table :tr] (html/clone-for
[item items]
(html/content (link-model {:points (second item)
:text (first item)
:href (nth item 2 "")}))))
;; Compojure method to map requests to handler code.
(defroutes main-routes
(GET "/" []
(apply str
(merged-template "Reddit + HackerNews" (scrape-both))))
(GET "/reddit" []
(apply str
(merged-template "Reddit" (scrape-reddit))))
(GET "/hacker-news" []
(apply str
(merged-template "HackerNews" (scrape-hn))))
(ANY "*" []
"Hello world!"))
;; ring web server code
;; Wrap routes with a fn that serves stacktrace on error.
(def app
(->
#'main-routes
(wrap-stacktrace)))
(defn start-server []
(run-jetty app {:port 8080 :join? false}))
;; jetty commands:
;; (def server (start-server))
;; (. server (stop))
|
28610
|
(ns crawler.core
#^{:author "<NAME>"
:doc "Code for crawling Reddit and Hacker News."}
(:refer-clojure)
(:use
[clojure.set]
[clojure.stacktrace]
[compojure.core]
[ring.adapter.jetty]
[ring.middleware.stacktrace])
(:require
[clojure.contrib.string :as string]
[net.cgrand.enlive-html :as html]
[com.twinql.clojure.http :as http])
(:import
java.util.Date))
(set! *warn-on-reflection* true)
;; crawl/scrape code
(def *hn-url* "http://news.ycombinator.com/")
(def *reddit-url* "http://www.reddit.com/")
(def *hn-selector*
[:td.title :a])
(def *reddit-title-selector*
[:div#siteTable.sitetable.linklisting
:p.title
:> :a]) ; only direct children of p.title
(def *reddit-points-selector*
[:div#siteTable.sitetable.linklisting
:div.score.unvoted])
(defn get-url
"Download html from a url."
[url]
(html/html-resource (java.net.URL. url)))
(defn get-with-user-agent
"Crawl page, specifying user agent, or defaulting to Chrome."
([url]
(let [user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US)
AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9"]
(get-with-user-agent url user-agent)))
([url user-agent]
(:content (http/get url
:as :string
:headers {"user-agent" user-agent}))))
(defn sort-headlines-points
"Sort seq of vecs of [headline points] by points descending."
[s]
(reverse (sort-by second s)))
(defn safe-parse-int
"Try to parse integer, or return 0."
[x]
(try
(Integer/parseInt x)
(catch NumberFormatException e
0)))
(defn hn-headlines
"Crawls HackerNews and extracts headlines."
([] (hn-headlines (get-url *hn-url*)))
([page] (map html/text (html/select page *hn-selector*))))
(defn hn-points
"Crawls HackerNews and extracts points."
([] (hn-points (get-url *hn-url*)))
([page] (map
#(-> %
html/text
((fn [s] (re-find #"\d+" s)))
Integer/parseInt)
(html/select page [:td.subtext html/first-child]))))
(defn hn-hrefs
"Crawls HackerNews and extracts hrefs."
([] (hn-hrefs (get-url *hn-url*)))
([page] (map #(get-in % [:attrs :href]) (html/select page *hn-selector*))))
(defn scrape-hn
"Scrapes HackerNews first page and returns vecs of [headline points]."
([]
(scrape-hn (get-url *hn-url*)))
([page]
(sort-headlines-points
(map vector
(hn-headlines page)
(hn-points page)
(hn-hrefs page)))))
(defn reddit-headlines
"Crawls reddit and extracts headlines."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map html/text
(html/select page *reddit-title-selector*))))
(defn reddit-points
"Crawls reddit and extracts points."
([] (reddit-points (get-url *reddit-url*)))
([page]
(map #(-> %
html/text
safe-parse-int)
(html/select page *reddit-points-selector*))))
(defn reddit-hrefs
"Crawls reddit and extracts hrefs."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map #(get-in % [:attrs :href])
(html/select page *reddit-title-selector*))))
(defn scrape-reddit
"Scrapes Reddit main page and returns vecs of [headline points hrefs]."
([]
(scrape-reddit (get-url *reddit-url*)))
([page]
(sort-headlines-points
(map vector
(reddit-headlines page)
(reddit-points page)
(reddit-hrefs page)))))
(defn scrape-both
"Scrape both Reddit and HackerNews, and berge the results."
[]
(sort-headlines-points
(concat (scrape-reddit)
(scrape-hn))))
;; enlive templating code
;; snippet template for each link
(html/defsnippet link-model "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/link.html" [:td]
[{points :points text :text href :href}]
[:td.points] (html/do-> (html/content (str points)))
[:a] (html/do->
(html/content text)
(html/set-attr :href href)))
;; template for page
(html/deftemplate merged-template "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/merged.html" [header items]
[:title] (html/content header)
[:h1] (html/content header)
[:table :tr] (html/clone-for
[item items]
(html/content (link-model {:points (second item)
:text (first item)
:href (nth item 2 "")}))))
;; Compojure method to map requests to handler code.
(defroutes main-routes
(GET "/" []
(apply str
(merged-template "Reddit + HackerNews" (scrape-both))))
(GET "/reddit" []
(apply str
(merged-template "Reddit" (scrape-reddit))))
(GET "/hacker-news" []
(apply str
(merged-template "HackerNews" (scrape-hn))))
(ANY "*" []
"Hello world!"))
;; ring web server code
;; Wrap routes with a fn that serves stacktrace on error.
(def app
(->
#'main-routes
(wrap-stacktrace)))
(defn start-server []
(run-jetty app {:port 8080 :join? false}))
;; jetty commands:
;; (def server (start-server))
;; (. server (stop))
| true |
(ns crawler.core
#^{:author "PI:NAME:<NAME>END_PI"
:doc "Code for crawling Reddit and Hacker News."}
(:refer-clojure)
(:use
[clojure.set]
[clojure.stacktrace]
[compojure.core]
[ring.adapter.jetty]
[ring.middleware.stacktrace])
(:require
[clojure.contrib.string :as string]
[net.cgrand.enlive-html :as html]
[com.twinql.clojure.http :as http])
(:import
java.util.Date))
(set! *warn-on-reflection* true)
;; crawl/scrape code
(def *hn-url* "http://news.ycombinator.com/")
(def *reddit-url* "http://www.reddit.com/")
(def *hn-selector*
[:td.title :a])
(def *reddit-title-selector*
[:div#siteTable.sitetable.linklisting
:p.title
:> :a]) ; only direct children of p.title
(def *reddit-points-selector*
[:div#siteTable.sitetable.linklisting
:div.score.unvoted])
(defn get-url
"Download html from a url."
[url]
(html/html-resource (java.net.URL. url)))
(defn get-with-user-agent
"Crawl page, specifying user agent, or defaulting to Chrome."
([url]
(let [user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US)
AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9"]
(get-with-user-agent url user-agent)))
([url user-agent]
(:content (http/get url
:as :string
:headers {"user-agent" user-agent}))))
(defn sort-headlines-points
"Sort seq of vecs of [headline points] by points descending."
[s]
(reverse (sort-by second s)))
(defn safe-parse-int
"Try to parse integer, or return 0."
[x]
(try
(Integer/parseInt x)
(catch NumberFormatException e
0)))
(defn hn-headlines
"Crawls HackerNews and extracts headlines."
([] (hn-headlines (get-url *hn-url*)))
([page] (map html/text (html/select page *hn-selector*))))
(defn hn-points
"Crawls HackerNews and extracts points."
([] (hn-points (get-url *hn-url*)))
([page] (map
#(-> %
html/text
((fn [s] (re-find #"\d+" s)))
Integer/parseInt)
(html/select page [:td.subtext html/first-child]))))
(defn hn-hrefs
"Crawls HackerNews and extracts hrefs."
([] (hn-hrefs (get-url *hn-url*)))
([page] (map #(get-in % [:attrs :href]) (html/select page *hn-selector*))))
(defn scrape-hn
"Scrapes HackerNews first page and returns vecs of [headline points]."
([]
(scrape-hn (get-url *hn-url*)))
([page]
(sort-headlines-points
(map vector
(hn-headlines page)
(hn-points page)
(hn-hrefs page)))))
(defn reddit-headlines
"Crawls reddit and extracts headlines."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map html/text
(html/select page *reddit-title-selector*))))
(defn reddit-points
"Crawls reddit and extracts points."
([] (reddit-points (get-url *reddit-url*)))
([page]
(map #(-> %
html/text
safe-parse-int)
(html/select page *reddit-points-selector*))))
(defn reddit-hrefs
"Crawls reddit and extracts hrefs."
([] (reddit-headlines (get-url *reddit-url*)))
([page] (map #(get-in % [:attrs :href])
(html/select page *reddit-title-selector*))))
(defn scrape-reddit
"Scrapes Reddit main page and returns vecs of [headline points hrefs]."
([]
(scrape-reddit (get-url *reddit-url*)))
([page]
(sort-headlines-points
(map vector
(reddit-headlines page)
(reddit-points page)
(reddit-hrefs page)))))
(defn scrape-both
"Scrape both Reddit and HackerNews, and berge the results."
[]
(sort-headlines-points
(concat (scrape-reddit)
(scrape-hn))))
;; enlive templating code
;; snippet template for each link
(html/defsnippet link-model "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/link.html" [:td]
[{points :points text :text href :href}]
[:td.points] (html/do-> (html/content (str points)))
[:a] (html/do->
(html/content text)
(html/set-attr :href href)))
;; template for page
(html/deftemplate merged-template "/Users/josephgallo/Documents/Work/Personal/Projects/clojure-pgh/2010-04-07-enlive/crawler/html/merged.html" [header items]
[:title] (html/content header)
[:h1] (html/content header)
[:table :tr] (html/clone-for
[item items]
(html/content (link-model {:points (second item)
:text (first item)
:href (nth item 2 "")}))))
;; Compojure method to map requests to handler code.
(defroutes main-routes
(GET "/" []
(apply str
(merged-template "Reddit + HackerNews" (scrape-both))))
(GET "/reddit" []
(apply str
(merged-template "Reddit" (scrape-reddit))))
(GET "/hacker-news" []
(apply str
(merged-template "HackerNews" (scrape-hn))))
(ANY "*" []
"Hello world!"))
;; ring web server code
;; Wrap routes with a fn that serves stacktrace on error.
(def app
(->
#'main-routes
(wrap-stacktrace)))
(defn start-server []
(run-jetty app {:port 8080 :join? false}))
;; jetty commands:
;; (def server (start-server))
;; (. server (stop))
|
[
{
"context": "13 2 12)\n\n \"i går\"\n (datetime 2013 2 11)\n\n \"i morgen\"\n (datetime 2013 2 13)\n\n \"mandag\"\n \"man.\"\n \"p",
"end": 310,
"score": 0.8359302282333374,
"start": 305,
"tag": "NAME",
"value": "orgen"
},
{
"context": "13 2 11)\n\n \"i morgen\"\n (datetime 2013 2 13)\n\n \"mandag\"\n \"man.\"\n \"på mandag\"\n (datetime 2013 2 18 :da",
"end": 345,
"score": 0.9858763217926025,
"start": 339,
"tag": "NAME",
"value": "mandag"
},
{
"context": " \"i morgen\"\n (datetime 2013 2 13)\n\n \"mandag\"\n \"man.\"\n \"på mandag\"\n (datetime 2013 2 18 :day-of-wee",
"end": 353,
"score": 0.877286434173584,
"start": 350,
"tag": "NAME",
"value": "man"
},
{
"context": "mandag\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"Mandag den 18. februar\"\n \"Man, 18 februar\"\n (datetime ",
"end": 418,
"score": 0.971759557723999,
"start": 412,
"tag": "NAME",
"value": "Mandag"
},
{
"context": "2013 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"tirsdag\"\n (datetime 2013 2 19)\n\n \"torsdag\"\n \"tors\"\n \"",
"end": 522,
"score": 0.5255928039550781,
"start": 518,
"tag": "NAME",
"value": "sdag"
},
{
"context": ":month 2)\n\n \"tirsdag\"\n (datetime 2013 2 19)\n\n \"torsdag\"\n \"tors\"\n \"tors.\"\n (datetime 2013 2 14)\n\n \"fr",
"end": 558,
"score": 0.8117913603782654,
"start": 551,
"tag": "NAME",
"value": "torsdag"
},
{
"context": " \"tirsdag\"\n (datetime 2013 2 19)\n\n \"torsdag\"\n \"tors\"\n \"tors.\"\n (datetime 2013 2 14)\n\n \"fredag\"\n \"",
"end": 567,
"score": 0.8313359022140503,
"start": 563,
"tag": "NAME",
"value": "tors"
},
{
"context": "ag\"\n \"tors\"\n \"tors.\"\n (datetime 2013 2 14)\n\n \"fredag\"\n \"fre\"\n \"fre.\"\n (datetime 2013 2 15)\n\n \"lørd",
"end": 612,
"score": 0.9767972826957703,
"start": 606,
"tag": "NAME",
"value": "fredag"
},
{
"context": "\"\n \"tors.\"\n (datetime 2013 2 14)\n\n \"fredag\"\n \"fre\"\n \"fre.\"\n (datetime 2013 2 15)\n\n \"lørdag\"\n \"l",
"end": 620,
"score": 0.9774341583251953,
"start": 617,
"tag": "NAME",
"value": "fre"
},
{
"context": "15)\n\n \"næste tirsdag\" ; when today is Tuesday, \"mardi prochain\" is a week from now\n (datetime 2013 2 19 :d",
"end": 1690,
"score": 0.6646105647087097,
"start": 1682,
"tag": "NAME",
"value": "ardi pro"
},
{
"context": "me 2013 2 10 :day-of-week 7 :day 10 :month 2)\n\n \"Ons, Feb13\"\n \"Ons feb13\"\n (datetime 2013 2 13 :day",
"end": 1993,
"score": 0.5216859579086304,
"start": 1991,
"tag": "NAME",
"value": "On"
},
{
"context": "me 2013 2 13 :day-of-week 3 :day 13 :month 2)\n\n \"Mandag, Feb 18\"\n \"Man, februar 18\"\n (datetime 2013 2 1",
"end": 2082,
"score": 0.998775064945221,
"start": 2076,
"tag": "NAME",
"value": "Mandag"
},
{
"context": "etime-interval [2013 2 15 18] [2013 2 18 00])\n\n \"mandag morgen\"\n (datetime-interval [2013 2 18 4] [2013 2 18 12",
"end": 8370,
"score": 0.9996721148490906,
"start": 8357,
"tag": "NAME",
"value": "mandag morgen"
},
{
"context": "kken 13:30\"\n (datetime 2013 2 12 13 30)\n\n \"om 15 minutter\"\n (datetime 2013 2 12 4 45 0)\n\n \"efter frokost\"",
"end": 12374,
"score": 0.8560707569122314,
"start": 12366,
"tag": "NAME",
"value": "minutter"
},
{
"context": " 17])\n\n \"10:30\"\n (datetime 2013 2 12 10 30)\n\n \"morgen\" ;; how should we deal with fb mornings?\n (datet",
"end": 12527,
"score": 0.9027627110481262,
"start": 12521,
"tag": "NAME",
"value": "morgen"
}
] |
resources/languages/da/corpus/time.clj
|
guivn/duckling
| 922 |
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"nu"
"lige nu"
(datetime 2013 2 12 4 30 00)
"i dag"
(datetime 2013 2 12)
"i går"
(datetime 2013 2 11)
"i morgen"
(datetime 2013 2 13)
"mandag"
"man."
"på mandag"
(datetime 2013 2 18 :day-of-week 1)
"Mandag den 18. februar"
"Man, 18 februar"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"tirsdag"
(datetime 2013 2 19)
"torsdag"
"tors"
"tors."
(datetime 2013 2 14)
"fredag"
"fre"
"fre."
(datetime 2013 2 15)
"lørdag"
"lør"
"lør."
(datetime 2013 2 16)
"søndag"
"søn"
"søn."
(datetime 2013 2 17)
"Den første marts"
"1. marts"
"Den 1. marts"
(datetime 2013 3 1 :day 1 :month 3)
"3 marts"
"den tredje marts"
"den 3. marts"
(datetime 2013 3 3 :day 3 :month 3)
"3 marts 2015"
"tredje marts 2015"
"3. marts 2015"
"3-3-2015"
"03-03-2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"På den 15."
"På den 15"
"Den 15."
"Den 15"
(datetime 2013 2 15 :day 15)
"den 15. februar"
"15. februar"
"februar 15"
"15-02"
"15/02"
(datetime 2013 2 15 :day 15 :month 2)
"8 Aug"
(datetime 2013 8 8 :day 8 :month 8)
"Oktober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31/10/1974"
"31/10/74"
"31-10-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14april 2015"
"April 14, 2015"
"fjortende April 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"næste tirsdag" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 2)
"næste marts"
(datetime 2013 3)
"næste marts igen"
(datetime 2014 3)
"Søndag, 10 feb"
"Søndag 10 Feb"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Ons, Feb13"
"Ons feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"Mandag, Feb 18"
"Man, februar 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"denne uge"
(datetime 2013 2 11 :grain :week)
"sidste uge"
(datetime 2013 2 4 :grain :week)
"næste uge"
(datetime 2013 2 18 :grain :week)
"sidste måned"
(datetime 2013 1)
"næste måned"
(datetime 2013 3)
"dette kvartal"
(datetime 2013 1 1 :grain :quarter)
"næste kvartal"
(datetime 2013 4 1 :grain :quarter)
"tredje kvartal"
"3. kvartal"
(datetime 2013 7 1 :grain :quarter)
"4. kvartal 2018"
"fjerde kvartal 2018"
(datetime 2018 10 1 :grain :quarter)
"sidste år"
(datetime 2012)
"i år"
"dette år"
(datetime 2013)
"næste år"
(datetime 2014)
"sidste søndag"
"søndag i sidste uge"
(datetime 2013 2 10 :day-of-week 7)
"sidste tirsdag"
(datetime 2013 2 5 :day-of-week 2)
"næste tirsdag" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste onsdag" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"onsdag i næste uge"
"onsdag næste uge"
"næste onsdag igen"
(datetime 2013 2 20 :day-of-week 3)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 5)
"mandag i denne uge"
(datetime 2013 2 11 :day-of-week 1)
"tirsdag i denne uge"
(datetime 2013 2 12 :day-of-week 2)
"onsdag i denne uge"
(datetime 2013 2 13 :day-of-week 3)
"i overmorgen"
(datetime 2013 2 14)
"i forgårs"
(datetime 2013 2 10)
"sidste mandag i marts"
"sidste mandag i Marts"
(datetime 2013 3 25 :day-of-week 1)
"sidste søndag i marts 2014"
"sidste søndag i Marts 2014"
(datetime 2014 3 30 :day-of-week 7)
"tredje dag i oktober"
"tredje dag i Oktober"
(datetime 2013 10 3)
"første uge i oktober 2014"
"første uge i Oktober 2014"
(datetime 2014 10 6 :grain :week)
;"the week of october 6th"
;"the week of october 7th"
;(datetime 2013 10 7 :grain :week)
"sidste dag i oktober 2015"
"sidste dag i Oktober 2015"
(datetime 2015 10 31)
"sidste uge i september 2014"
"sidste uge i September 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"første tirsdag i oktober"
"første tirsdag i Oktober"
(datetime 2013 10 1)
"tredje tirsdag i september 2014"
"tredje tirsdag i September 2014"
(datetime 2014 9 16)
"første onsdag i oktober 2014"
"første onsdag i Oktober 2014"
(datetime 2014 10 1)
"anden onsdag i oktober 2014"
"anden onsdag i Oktober 2014"
(datetime 2014 10 8)
;; Hours
"klokken 3"
"kl. 3"
(datetime 2013 2 13 3)
"3:18"
(datetime 2013 2 13 3 18)
"klokken 15"
"kl. 15"
"15h"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"ca. kl. 15" ;; FIXME pm overrides precision
"cirka kl. 15"
"omkring klokken 15"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
"imorgen klokken 17 sharp" ;; FIXME precision is lost
"imorgen kl. 17 præcis"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
"kvarter over 15"
"kvart over 15"
"15:15"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"kl. 20 over 15"
"klokken 20 over 15"
"kl. 15:20"
"15:20"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"15:30"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kvarter i 12"
"kvart i 12"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;; Mixing date and time
"klokken 9 på lørdag"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fre, Jul 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
"kl. 19:30, Lør, 20 sep"
(datetime 2014 9 20 19 30 :day-of-week 6 :hour 7 :minute 30 :meridiem :pm)
; ;; Involving periods
"om 1 sekund"
"om ét sekund"
"om et sekund"
"ét sekund fra nu"
"et sekund fra nu"
(datetime 2013 2 12 4 30 1)
"om 1 minut"
"om ét minut"
"om et minut"
(datetime 2013 2 12 4 31 0)
"om 2 minutter"
"om to minutter"
"om 2 minutter mere"
"om to minutter mere"
"2 minutter fra nu"
"to minutter fra nu"
(datetime 2013 2 12 4 32 0)
"om 60 minutter"
(datetime 2013 2 12 5 30 0)
"om en halv time"
(datetime 2013 2 12 5 0 0)
"om 2,5 time"
"om 2 og en halv time"
"om to og en halv time"
(datetime 2013 2 12 7 0 0)
"om én time"
"om 1 time"
"om 1t"
(datetime 2013 2 12 5 30)
"om et par timer"
(datetime 2013 2 12 6 30)
"om 24 timer"
(datetime 2013 2 13 4 30)
"om en dag"
(datetime 2013 2 13 4)
"3 år fra i dag"
(datetime 2016 2)
"om 7 dage"
(datetime 2013 2 19 4)
"om en uge"
"om én uge"
(datetime 2013 2 19)
"om ca. en halv time" ;; FIXME precision is lost
"om cirka en halv time"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dage siden"
"syv dage siden"
(datetime 2013 2 5 4)
"14 dage siden"
"fjorten dage siden"
(datetime 2013 1 29 4)
"en uge siden"
"én uge siden"
"1 uge siden"
(datetime 2013 2 5)
"3 uger siden"
"tre uger siden"
(datetime 2013 1 22)
"3 måneder siden"
"tre måneder siden"
(datetime 2012 11 12)
"to år siden"
"2 år siden"
(datetime 2011 2)
"1954"
(datetime 1954)
"et år efter juleaften"
"ét år efter juleaften"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"denne sommer"
"den her sommer"
(datetime-interval [2013 6 21] [2013 9 24])
"denne vinter"
"den her vinter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"1 juledag"
"1. juledag"
"første juledag"
(datetime 2013 12 25)
"nytårsaftensdag"
"nytårsaften"
(datetime 2013 12 31)
"nytårsdag"
(datetime 2014 1 1)
; Part of day (morning, afternoon...)
"i aften"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"sidste weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"i morgen aften"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"i morgen middag"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"i går aftes"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"denne weekend"
"i weekenden"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"mandag morgen"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Intervals involving cycles
"sidste 2 sekunder"
"sidste to sekunder"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"næste 3 sekunder"
"næste tre sekunder"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"sidste 2 minutter"
"sidste to minutter"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"næste 3 minutter"
"næste tre minutter"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"sidste 1 time"
"seneste 1 time"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"næste 3 timer"
"næste tre timer"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"sidste 2 dage"
"sidste to dage"
"seneste 2 dage"
(datetime-interval [2013 2 10] [2013 2 12])
"næste 3 dage"
"næste tre dage"
(datetime-interval [2013 2 13] [2013 2 16])
"sidste 2 uger"
"sidste to uger"
"seneste to uger"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"næste 3 uger"
"næste tre uger"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"sidste 2 måneder"
"sidste to måneder"
"seneste to måneder"
(datetime-interval [2012 12] [2013 02])
"næste 3 måneder"
"næste tre måneder"
(datetime-interval [2013 3] [2013 6])
"sidste 2 år"
"sidste to år"
"seneste 2 år"
(datetime-interval [2011] [2013])
"næste 3 år"
"næste tre år"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 juli"
"13-15 Juli"
"13 til 15 Juli"
"13 juli til 15 juli"
(datetime-interval [2013 7 13] [2013 7 16])
"8 Aug - 12 Aug"
"8 Aug - 12 aug"
"8 aug - 12 aug"
"8 august - 12 august"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
"9:30 til 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"fra 9:30 - 11:00 på torsdag"
"fra 9:30 til 11:00 på torsdag"
"mellem 9:30 og 11:00 på torsdag"
"9:30 - 11:00 på torsdag"
"9:30 til 11:00 på torsdag"
"efter 9:30 men før 11:00 på torsdag"
"torsdag fra 9:30 til 11:00"
"torsdag mellem 9:30 og 11:00"
"fra 9:30 til 11:00 på torsdag"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"torsdag fra 9 til 11"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"indenfor 2 uger"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"inden kl. 14"
"indtil kl. 14"
"inden klokken 14"
(datetime 2013 2 12 14 :direction :before)
; Timezones
"16 CET"
"kl. 16 CET"
"klokken 16 CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"torsdag kl. 8:00 GMT"
"torsdag klokken 8:00 GMT"
"torsdag 08:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"idag kl. 14"
"idag klokken 14"
"kl. 14"
"klokken 14"
(datetime 2013 2 12 14)
"25/4 kl. 16:00"
"25/4 klokken 16:00"
"25-04 klokken 16:00"
"25-4 kl. 16:00"
(datetime 2013 4 25 16 0)
"15:00 i morgen"
"kl. 15:00 i morgen"
"klokken 15:00 i morgen"
(datetime 2013 2 13 15 0)
"efter kl. 14"
"efter klokken 14"
(datetime 2013 2 12 14 :direction :after)
"efter 5 dage"
"efter fem dage"
(datetime 2013 2 17 4 :direction :after)
"om 5 dage"
"om fem dage"
(datetime 2013 2 17 4)
"efter i morgen kl. 14"
"efter i morgen klokken 14"
"i morgen efter kl. 14" ;; FIXME this is actually not ambiguous it's 2pm - midnight.
"i morgen efter klokken 14"
(datetime 2013 2 13 14 :direction :after)
"før kl. 11"
"før klokken 11"
(datetime 2013 2 12 11 :direction :before)
"i morgen før kl. 11" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
"i morgen før klokken 11"
(datetime 2013 2 13 11 :direction :before)
"om eftermiddagen"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"kl. 13:30"
"klokken 13:30"
(datetime 2013 2 12 13 30)
"om 15 minutter"
(datetime 2013 2 12 4 45 0)
"efter frokost"
(datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
"morgen" ;; how should we deal with fb mornings?
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"næste mandag"
(datetime 2013 2 18 :day-of-week 1)
)
|
4525
|
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"nu"
"lige nu"
(datetime 2013 2 12 4 30 00)
"i dag"
(datetime 2013 2 12)
"i går"
(datetime 2013 2 11)
"i m<NAME>"
(datetime 2013 2 13)
"<NAME>"
"<NAME>."
"på mandag"
(datetime 2013 2 18 :day-of-week 1)
"<NAME> den 18. februar"
"Man, 18 februar"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"tir<NAME>"
(datetime 2013 2 19)
"<NAME>"
"<NAME>"
"tors."
(datetime 2013 2 14)
"<NAME>"
"<NAME>"
"fre."
(datetime 2013 2 15)
"lørdag"
"lør"
"lør."
(datetime 2013 2 16)
"søndag"
"søn"
"søn."
(datetime 2013 2 17)
"Den første marts"
"1. marts"
"Den 1. marts"
(datetime 2013 3 1 :day 1 :month 3)
"3 marts"
"den tredje marts"
"den 3. marts"
(datetime 2013 3 3 :day 3 :month 3)
"3 marts 2015"
"tredje marts 2015"
"3. marts 2015"
"3-3-2015"
"03-03-2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"På den 15."
"På den 15"
"Den 15."
"Den 15"
(datetime 2013 2 15 :day 15)
"den 15. februar"
"15. februar"
"februar 15"
"15-02"
"15/02"
(datetime 2013 2 15 :day 15 :month 2)
"8 Aug"
(datetime 2013 8 8 :day 8 :month 8)
"Oktober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31/10/1974"
"31/10/74"
"31-10-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14april 2015"
"April 14, 2015"
"fjortende April 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"næste tirsdag" ; when today is Tuesday, "m<NAME>chain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 2)
"næste marts"
(datetime 2013 3)
"næste marts igen"
(datetime 2014 3)
"Søndag, 10 feb"
"Søndag 10 Feb"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"<NAME>s, Feb13"
"Ons feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"<NAME>, Feb 18"
"Man, februar 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"denne uge"
(datetime 2013 2 11 :grain :week)
"sidste uge"
(datetime 2013 2 4 :grain :week)
"næste uge"
(datetime 2013 2 18 :grain :week)
"sidste måned"
(datetime 2013 1)
"næste måned"
(datetime 2013 3)
"dette kvartal"
(datetime 2013 1 1 :grain :quarter)
"næste kvartal"
(datetime 2013 4 1 :grain :quarter)
"tredje kvartal"
"3. kvartal"
(datetime 2013 7 1 :grain :quarter)
"4. kvartal 2018"
"fjerde kvartal 2018"
(datetime 2018 10 1 :grain :quarter)
"sidste år"
(datetime 2012)
"i år"
"dette år"
(datetime 2013)
"næste år"
(datetime 2014)
"sidste søndag"
"søndag i sidste uge"
(datetime 2013 2 10 :day-of-week 7)
"sidste tirsdag"
(datetime 2013 2 5 :day-of-week 2)
"næste tirsdag" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste onsdag" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"onsdag i næste uge"
"onsdag næste uge"
"næste onsdag igen"
(datetime 2013 2 20 :day-of-week 3)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 5)
"mandag i denne uge"
(datetime 2013 2 11 :day-of-week 1)
"tirsdag i denne uge"
(datetime 2013 2 12 :day-of-week 2)
"onsdag i denne uge"
(datetime 2013 2 13 :day-of-week 3)
"i overmorgen"
(datetime 2013 2 14)
"i forgårs"
(datetime 2013 2 10)
"sidste mandag i marts"
"sidste mandag i Marts"
(datetime 2013 3 25 :day-of-week 1)
"sidste søndag i marts 2014"
"sidste søndag i Marts 2014"
(datetime 2014 3 30 :day-of-week 7)
"tredje dag i oktober"
"tredje dag i Oktober"
(datetime 2013 10 3)
"første uge i oktober 2014"
"første uge i Oktober 2014"
(datetime 2014 10 6 :grain :week)
;"the week of october 6th"
;"the week of october 7th"
;(datetime 2013 10 7 :grain :week)
"sidste dag i oktober 2015"
"sidste dag i Oktober 2015"
(datetime 2015 10 31)
"sidste uge i september 2014"
"sidste uge i September 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"første tirsdag i oktober"
"første tirsdag i Oktober"
(datetime 2013 10 1)
"tredje tirsdag i september 2014"
"tredje tirsdag i September 2014"
(datetime 2014 9 16)
"første onsdag i oktober 2014"
"første onsdag i Oktober 2014"
(datetime 2014 10 1)
"anden onsdag i oktober 2014"
"anden onsdag i Oktober 2014"
(datetime 2014 10 8)
;; Hours
"klokken 3"
"kl. 3"
(datetime 2013 2 13 3)
"3:18"
(datetime 2013 2 13 3 18)
"klokken 15"
"kl. 15"
"15h"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"ca. kl. 15" ;; FIXME pm overrides precision
"cirka kl. 15"
"omkring klokken 15"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
"imorgen klokken 17 sharp" ;; FIXME precision is lost
"imorgen kl. 17 præcis"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
"kvarter over 15"
"kvart over 15"
"15:15"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"kl. 20 over 15"
"klokken 20 over 15"
"kl. 15:20"
"15:20"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"15:30"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kvarter i 12"
"kvart i 12"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;; Mixing date and time
"klokken 9 på lørdag"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fre, Jul 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
"kl. 19:30, Lør, 20 sep"
(datetime 2014 9 20 19 30 :day-of-week 6 :hour 7 :minute 30 :meridiem :pm)
; ;; Involving periods
"om 1 sekund"
"om ét sekund"
"om et sekund"
"ét sekund fra nu"
"et sekund fra nu"
(datetime 2013 2 12 4 30 1)
"om 1 minut"
"om ét minut"
"om et minut"
(datetime 2013 2 12 4 31 0)
"om 2 minutter"
"om to minutter"
"om 2 minutter mere"
"om to minutter mere"
"2 minutter fra nu"
"to minutter fra nu"
(datetime 2013 2 12 4 32 0)
"om 60 minutter"
(datetime 2013 2 12 5 30 0)
"om en halv time"
(datetime 2013 2 12 5 0 0)
"om 2,5 time"
"om 2 og en halv time"
"om to og en halv time"
(datetime 2013 2 12 7 0 0)
"om én time"
"om 1 time"
"om 1t"
(datetime 2013 2 12 5 30)
"om et par timer"
(datetime 2013 2 12 6 30)
"om 24 timer"
(datetime 2013 2 13 4 30)
"om en dag"
(datetime 2013 2 13 4)
"3 år fra i dag"
(datetime 2016 2)
"om 7 dage"
(datetime 2013 2 19 4)
"om en uge"
"om én uge"
(datetime 2013 2 19)
"om ca. en halv time" ;; FIXME precision is lost
"om cirka en halv time"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dage siden"
"syv dage siden"
(datetime 2013 2 5 4)
"14 dage siden"
"fjorten dage siden"
(datetime 2013 1 29 4)
"en uge siden"
"én uge siden"
"1 uge siden"
(datetime 2013 2 5)
"3 uger siden"
"tre uger siden"
(datetime 2013 1 22)
"3 måneder siden"
"tre måneder siden"
(datetime 2012 11 12)
"to år siden"
"2 år siden"
(datetime 2011 2)
"1954"
(datetime 1954)
"et år efter juleaften"
"ét år efter juleaften"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"denne sommer"
"den her sommer"
(datetime-interval [2013 6 21] [2013 9 24])
"denne vinter"
"den her vinter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"1 juledag"
"1. juledag"
"første juledag"
(datetime 2013 12 25)
"nytårsaftensdag"
"nytårsaften"
(datetime 2013 12 31)
"nytårsdag"
(datetime 2014 1 1)
; Part of day (morning, afternoon...)
"i aften"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"sidste weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"i morgen aften"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"i morgen middag"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"i går aftes"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"denne weekend"
"i weekenden"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"<NAME>"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Intervals involving cycles
"sidste 2 sekunder"
"sidste to sekunder"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"næste 3 sekunder"
"næste tre sekunder"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"sidste 2 minutter"
"sidste to minutter"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"næste 3 minutter"
"næste tre minutter"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"sidste 1 time"
"seneste 1 time"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"næste 3 timer"
"næste tre timer"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"sidste 2 dage"
"sidste to dage"
"seneste 2 dage"
(datetime-interval [2013 2 10] [2013 2 12])
"næste 3 dage"
"næste tre dage"
(datetime-interval [2013 2 13] [2013 2 16])
"sidste 2 uger"
"sidste to uger"
"seneste to uger"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"næste 3 uger"
"næste tre uger"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"sidste 2 måneder"
"sidste to måneder"
"seneste to måneder"
(datetime-interval [2012 12] [2013 02])
"næste 3 måneder"
"næste tre måneder"
(datetime-interval [2013 3] [2013 6])
"sidste 2 år"
"sidste to år"
"seneste 2 år"
(datetime-interval [2011] [2013])
"næste 3 år"
"næste tre år"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 juli"
"13-15 Juli"
"13 til 15 Juli"
"13 juli til 15 juli"
(datetime-interval [2013 7 13] [2013 7 16])
"8 Aug - 12 Aug"
"8 Aug - 12 aug"
"8 aug - 12 aug"
"8 august - 12 august"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
"9:30 til 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"fra 9:30 - 11:00 på torsdag"
"fra 9:30 til 11:00 på torsdag"
"mellem 9:30 og 11:00 på torsdag"
"9:30 - 11:00 på torsdag"
"9:30 til 11:00 på torsdag"
"efter 9:30 men før 11:00 på torsdag"
"torsdag fra 9:30 til 11:00"
"torsdag mellem 9:30 og 11:00"
"fra 9:30 til 11:00 på torsdag"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"torsdag fra 9 til 11"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"indenfor 2 uger"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"inden kl. 14"
"indtil kl. 14"
"inden klokken 14"
(datetime 2013 2 12 14 :direction :before)
; Timezones
"16 CET"
"kl. 16 CET"
"klokken 16 CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"torsdag kl. 8:00 GMT"
"torsdag klokken 8:00 GMT"
"torsdag 08:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"idag kl. 14"
"idag klokken 14"
"kl. 14"
"klokken 14"
(datetime 2013 2 12 14)
"25/4 kl. 16:00"
"25/4 klokken 16:00"
"25-04 klokken 16:00"
"25-4 kl. 16:00"
(datetime 2013 4 25 16 0)
"15:00 i morgen"
"kl. 15:00 i morgen"
"klokken 15:00 i morgen"
(datetime 2013 2 13 15 0)
"efter kl. 14"
"efter klokken 14"
(datetime 2013 2 12 14 :direction :after)
"efter 5 dage"
"efter fem dage"
(datetime 2013 2 17 4 :direction :after)
"om 5 dage"
"om fem dage"
(datetime 2013 2 17 4)
"efter i morgen kl. 14"
"efter i morgen klokken 14"
"i morgen efter kl. 14" ;; FIXME this is actually not ambiguous it's 2pm - midnight.
"i morgen efter klokken 14"
(datetime 2013 2 13 14 :direction :after)
"før kl. 11"
"før klokken 11"
(datetime 2013 2 12 11 :direction :before)
"i morgen før kl. 11" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
"i morgen før klokken 11"
(datetime 2013 2 13 11 :direction :before)
"om eftermiddagen"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"kl. 13:30"
"klokken 13:30"
(datetime 2013 2 12 13 30)
"om 15 <NAME>"
(datetime 2013 2 12 4 45 0)
"efter frokost"
(datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
"<NAME>" ;; how should we deal with fb mornings?
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"næste mandag"
(datetime 2013 2 18 :day-of-week 1)
)
| true |
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"nu"
"lige nu"
(datetime 2013 2 12 4 30 00)
"i dag"
(datetime 2013 2 12)
"i går"
(datetime 2013 2 11)
"i mPI:NAME:<NAME>END_PI"
(datetime 2013 2 13)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI."
"på mandag"
(datetime 2013 2 18 :day-of-week 1)
"PI:NAME:<NAME>END_PI den 18. februar"
"Man, 18 februar"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"tirPI:NAME:<NAME>END_PI"
(datetime 2013 2 19)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"tors."
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"fre."
(datetime 2013 2 15)
"lørdag"
"lør"
"lør."
(datetime 2013 2 16)
"søndag"
"søn"
"søn."
(datetime 2013 2 17)
"Den første marts"
"1. marts"
"Den 1. marts"
(datetime 2013 3 1 :day 1 :month 3)
"3 marts"
"den tredje marts"
"den 3. marts"
(datetime 2013 3 3 :day 3 :month 3)
"3 marts 2015"
"tredje marts 2015"
"3. marts 2015"
"3-3-2015"
"03-03-2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"På den 15."
"På den 15"
"Den 15."
"Den 15"
(datetime 2013 2 15 :day 15)
"den 15. februar"
"15. februar"
"februar 15"
"15-02"
"15/02"
(datetime 2013 2 15 :day 15 :month 2)
"8 Aug"
(datetime 2013 8 8 :day 8 :month 8)
"Oktober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31/10/1974"
"31/10/74"
"31-10-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14april 2015"
"April 14, 2015"
"fjortende April 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"næste tirsdag" ; when today is Tuesday, "mPI:NAME:<NAME>END_PIchain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 2)
"næste marts"
(datetime 2013 3)
"næste marts igen"
(datetime 2014 3)
"Søndag, 10 feb"
"Søndag 10 Feb"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"PI:NAME:<NAME>END_PIs, Feb13"
"Ons feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"PI:NAME:<NAME>END_PI, Feb 18"
"Man, februar 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"denne uge"
(datetime 2013 2 11 :grain :week)
"sidste uge"
(datetime 2013 2 4 :grain :week)
"næste uge"
(datetime 2013 2 18 :grain :week)
"sidste måned"
(datetime 2013 1)
"næste måned"
(datetime 2013 3)
"dette kvartal"
(datetime 2013 1 1 :grain :quarter)
"næste kvartal"
(datetime 2013 4 1 :grain :quarter)
"tredje kvartal"
"3. kvartal"
(datetime 2013 7 1 :grain :quarter)
"4. kvartal 2018"
"fjerde kvartal 2018"
(datetime 2018 10 1 :grain :quarter)
"sidste år"
(datetime 2012)
"i år"
"dette år"
(datetime 2013)
"næste år"
(datetime 2014)
"sidste søndag"
"søndag i sidste uge"
(datetime 2013 2 10 :day-of-week 7)
"sidste tirsdag"
(datetime 2013 2 5 :day-of-week 2)
"næste tirsdag" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"næste onsdag" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"onsdag i næste uge"
"onsdag næste uge"
"næste onsdag igen"
(datetime 2013 2 20 :day-of-week 3)
"næste fredag igen"
(datetime 2013 2 22 :day-of-week 5)
"mandag i denne uge"
(datetime 2013 2 11 :day-of-week 1)
"tirsdag i denne uge"
(datetime 2013 2 12 :day-of-week 2)
"onsdag i denne uge"
(datetime 2013 2 13 :day-of-week 3)
"i overmorgen"
(datetime 2013 2 14)
"i forgårs"
(datetime 2013 2 10)
"sidste mandag i marts"
"sidste mandag i Marts"
(datetime 2013 3 25 :day-of-week 1)
"sidste søndag i marts 2014"
"sidste søndag i Marts 2014"
(datetime 2014 3 30 :day-of-week 7)
"tredje dag i oktober"
"tredje dag i Oktober"
(datetime 2013 10 3)
"første uge i oktober 2014"
"første uge i Oktober 2014"
(datetime 2014 10 6 :grain :week)
;"the week of october 6th"
;"the week of october 7th"
;(datetime 2013 10 7 :grain :week)
"sidste dag i oktober 2015"
"sidste dag i Oktober 2015"
(datetime 2015 10 31)
"sidste uge i september 2014"
"sidste uge i September 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"første tirsdag i oktober"
"første tirsdag i Oktober"
(datetime 2013 10 1)
"tredje tirsdag i september 2014"
"tredje tirsdag i September 2014"
(datetime 2014 9 16)
"første onsdag i oktober 2014"
"første onsdag i Oktober 2014"
(datetime 2014 10 1)
"anden onsdag i oktober 2014"
"anden onsdag i Oktober 2014"
(datetime 2014 10 8)
;; Hours
"klokken 3"
"kl. 3"
(datetime 2013 2 13 3)
"3:18"
(datetime 2013 2 13 3 18)
"klokken 15"
"kl. 15"
"15h"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"ca. kl. 15" ;; FIXME pm overrides precision
"cirka kl. 15"
"omkring klokken 15"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
"imorgen klokken 17 sharp" ;; FIXME precision is lost
"imorgen kl. 17 præcis"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
"kvarter over 15"
"kvart over 15"
"15:15"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"kl. 20 over 15"
"klokken 20 over 15"
"kl. 15:20"
"15:20"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"15:30"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kvarter i 12"
"kvart i 12"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;; Mixing date and time
"klokken 9 på lørdag"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fre, Jul 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
"kl. 19:30, Lør, 20 sep"
(datetime 2014 9 20 19 30 :day-of-week 6 :hour 7 :minute 30 :meridiem :pm)
; ;; Involving periods
"om 1 sekund"
"om ét sekund"
"om et sekund"
"ét sekund fra nu"
"et sekund fra nu"
(datetime 2013 2 12 4 30 1)
"om 1 minut"
"om ét minut"
"om et minut"
(datetime 2013 2 12 4 31 0)
"om 2 minutter"
"om to minutter"
"om 2 minutter mere"
"om to minutter mere"
"2 minutter fra nu"
"to minutter fra nu"
(datetime 2013 2 12 4 32 0)
"om 60 minutter"
(datetime 2013 2 12 5 30 0)
"om en halv time"
(datetime 2013 2 12 5 0 0)
"om 2,5 time"
"om 2 og en halv time"
"om to og en halv time"
(datetime 2013 2 12 7 0 0)
"om én time"
"om 1 time"
"om 1t"
(datetime 2013 2 12 5 30)
"om et par timer"
(datetime 2013 2 12 6 30)
"om 24 timer"
(datetime 2013 2 13 4 30)
"om en dag"
(datetime 2013 2 13 4)
"3 år fra i dag"
(datetime 2016 2)
"om 7 dage"
(datetime 2013 2 19 4)
"om en uge"
"om én uge"
(datetime 2013 2 19)
"om ca. en halv time" ;; FIXME precision is lost
"om cirka en halv time"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dage siden"
"syv dage siden"
(datetime 2013 2 5 4)
"14 dage siden"
"fjorten dage siden"
(datetime 2013 1 29 4)
"en uge siden"
"én uge siden"
"1 uge siden"
(datetime 2013 2 5)
"3 uger siden"
"tre uger siden"
(datetime 2013 1 22)
"3 måneder siden"
"tre måneder siden"
(datetime 2012 11 12)
"to år siden"
"2 år siden"
(datetime 2011 2)
"1954"
(datetime 1954)
"et år efter juleaften"
"ét år efter juleaften"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"denne sommer"
"den her sommer"
(datetime-interval [2013 6 21] [2013 9 24])
"denne vinter"
"den her vinter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"1 juledag"
"1. juledag"
"første juledag"
(datetime 2013 12 25)
"nytårsaftensdag"
"nytårsaften"
(datetime 2013 12 31)
"nytårsdag"
(datetime 2014 1 1)
; Part of day (morning, afternoon...)
"i aften"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"sidste weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"i morgen aften"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"i morgen middag"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"i går aftes"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"denne weekend"
"i weekenden"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"PI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Intervals involving cycles
"sidste 2 sekunder"
"sidste to sekunder"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"næste 3 sekunder"
"næste tre sekunder"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"sidste 2 minutter"
"sidste to minutter"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"næste 3 minutter"
"næste tre minutter"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"sidste 1 time"
"seneste 1 time"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"næste 3 timer"
"næste tre timer"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"sidste 2 dage"
"sidste to dage"
"seneste 2 dage"
(datetime-interval [2013 2 10] [2013 2 12])
"næste 3 dage"
"næste tre dage"
(datetime-interval [2013 2 13] [2013 2 16])
"sidste 2 uger"
"sidste to uger"
"seneste to uger"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"næste 3 uger"
"næste tre uger"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"sidste 2 måneder"
"sidste to måneder"
"seneste to måneder"
(datetime-interval [2012 12] [2013 02])
"næste 3 måneder"
"næste tre måneder"
(datetime-interval [2013 3] [2013 6])
"sidste 2 år"
"sidste to år"
"seneste 2 år"
(datetime-interval [2011] [2013])
"næste 3 år"
"næste tre år"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 juli"
"13-15 Juli"
"13 til 15 Juli"
"13 juli til 15 juli"
(datetime-interval [2013 7 13] [2013 7 16])
"8 Aug - 12 Aug"
"8 Aug - 12 aug"
"8 aug - 12 aug"
"8 august - 12 august"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
"9:30 til 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"fra 9:30 - 11:00 på torsdag"
"fra 9:30 til 11:00 på torsdag"
"mellem 9:30 og 11:00 på torsdag"
"9:30 - 11:00 på torsdag"
"9:30 til 11:00 på torsdag"
"efter 9:30 men før 11:00 på torsdag"
"torsdag fra 9:30 til 11:00"
"torsdag mellem 9:30 og 11:00"
"fra 9:30 til 11:00 på torsdag"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"torsdag fra 9 til 11"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"indenfor 2 uger"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"inden kl. 14"
"indtil kl. 14"
"inden klokken 14"
(datetime 2013 2 12 14 :direction :before)
; Timezones
"16 CET"
"kl. 16 CET"
"klokken 16 CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"torsdag kl. 8:00 GMT"
"torsdag klokken 8:00 GMT"
"torsdag 08:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"idag kl. 14"
"idag klokken 14"
"kl. 14"
"klokken 14"
(datetime 2013 2 12 14)
"25/4 kl. 16:00"
"25/4 klokken 16:00"
"25-04 klokken 16:00"
"25-4 kl. 16:00"
(datetime 2013 4 25 16 0)
"15:00 i morgen"
"kl. 15:00 i morgen"
"klokken 15:00 i morgen"
(datetime 2013 2 13 15 0)
"efter kl. 14"
"efter klokken 14"
(datetime 2013 2 12 14 :direction :after)
"efter 5 dage"
"efter fem dage"
(datetime 2013 2 17 4 :direction :after)
"om 5 dage"
"om fem dage"
(datetime 2013 2 17 4)
"efter i morgen kl. 14"
"efter i morgen klokken 14"
"i morgen efter kl. 14" ;; FIXME this is actually not ambiguous it's 2pm - midnight.
"i morgen efter klokken 14"
(datetime 2013 2 13 14 :direction :after)
"før kl. 11"
"før klokken 11"
(datetime 2013 2 12 11 :direction :before)
"i morgen før kl. 11" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
"i morgen før klokken 11"
(datetime 2013 2 13 11 :direction :before)
"om eftermiddagen"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"kl. 13:30"
"klokken 13:30"
(datetime 2013 2 12 13 30)
"om 15 PI:NAME:<NAME>END_PI"
(datetime 2013 2 12 4 45 0)
"efter frokost"
(datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
"PI:NAME:<NAME>END_PI" ;; how should we deal with fb mornings?
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"næste mandag"
(datetime 2013 2 18 :day-of-week 1)
)
|
[
{
"context": "\"/some/path\"\n :key-password \"pw\"\n :truststore \"/some/other",
"end": 1056,
"score": 0.9965067505836487,
"start": 1054,
"tag": "PASSWORD",
"value": "pw"
},
{
"context": "/other/path\"\n :trust-password \"otherpw\"}]\n (testing \"should not muck with keystore/tr",
"end": 1157,
"score": 0.9993120431900024,
"start": 1150,
"tag": "PASSWORD",
"value": "otherpw"
}
] |
test/clj/puppetlabs/trapperkeeper/services/jetty/jetty_config_test.clj
|
nwolfe/trapperkeeper
| 0 |
(ns puppetlabs.trapperkeeper.services.jetty.jetty-config-test
(:require [clojure.test :refer :all]
[clojure.java.io :refer [resource]]
[puppetlabs.trapperkeeper.services.jetty.jetty-config :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-output logs-matching]]))
(deftest jetty7-minimum-threads-test
(testing "should return the same number when higher than num-cpus"
(is (= 500 (jetty7-minimum-threads 500 1))))
(testing "should set the number to min threads when it is higher and return a warning"
(with-log-output logs
(is (= 4 (jetty7-minimum-threads 1 4)))
(is (= 1 (count (logs-matching #"max-threads = 1 is less than the minium allowed on this system for Jetty 7 to operate." @logs)))))))
(deftest http-configuration
(testing "should enable need-client-auth"
(let [config (configure-web-server {:client-auth false})]
(is (= (get config :client-auth) :need))))
(let [old-config {:keystore "/some/path"
:key-password "pw"
:truststore "/some/other/path"
:trust-password "otherpw"}]
(testing "should not muck with keystore/truststore settings if PEM-based SSL settings are not provided"
(let [processed-config (configure-web-server old-config)]
(is (= old-config
(select-keys processed-config [:keystore :key-password :truststore :trust-password])))))
(testing "should fail if some but not all of the PEM-based SSL settings are found"
(let [partial-pem-config (merge old-config {:ssl-ca-cert "/some/path"})]
(is (thrown-with-msg? java.lang.IllegalArgumentException
#"If configuring SSL from PEM files, you must provide all of the following options"
(configure-web-server partial-pem-config)))))
(let [pem-config (merge old-config
{:ssl-key (resource "config/jetty/ssl/private_keys/localhost.pem")
:ssl-cert (resource "config/jetty/ssl/certs/localhost.pem")
:ssl-ca-cert (resource "config/jetty/ssl/certs/ca.pem")})]
(testing "should warn if both keystore-based and PEM-based SSL settings are found"
(with-log-output logs
(configure-web-server pem-config)
(is (= 1 (count (logs-matching #"Found settings for both keystore-based and PEM-based SSL" @logs))))))
(testing "should prefer PEM-based SSL settings, override old keystore settings
with instances of java.security.KeyStore, and remove PEM settings
from final jetty config hash"
(let [processed-config (configure-web-server pem-config)]
(is (instance? java.security.KeyStore (:keystore processed-config)))
(is (instance? java.security.KeyStore (:truststore processed-config)))
(is (string? (:key-password processed-config)))
(is (not (contains? processed-config :trust-password)))
(is (not (contains? processed-config :ssl-key)))
(is (not (contains? processed-config :ssl-cert)))
(is (not (contains? processed-config :ssl-ca-cert)))))))
(testing "should set max-threads"
(let [config (configure-web-server {})]
(is (contains? config :max-threads))))
(testing "should merge configuration with initial-configs correctly"
(let [user-config {:truststore "foo"}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 50 :client-auth :need :port 8080})))
(let [user-config {:max-threads 500 :truststore "foo" :port 8000}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 500 :client-auth :need :port 8000})))))
|
61844
|
(ns puppetlabs.trapperkeeper.services.jetty.jetty-config-test
(:require [clojure.test :refer :all]
[clojure.java.io :refer [resource]]
[puppetlabs.trapperkeeper.services.jetty.jetty-config :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-output logs-matching]]))
(deftest jetty7-minimum-threads-test
(testing "should return the same number when higher than num-cpus"
(is (= 500 (jetty7-minimum-threads 500 1))))
(testing "should set the number to min threads when it is higher and return a warning"
(with-log-output logs
(is (= 4 (jetty7-minimum-threads 1 4)))
(is (= 1 (count (logs-matching #"max-threads = 1 is less than the minium allowed on this system for Jetty 7 to operate." @logs)))))))
(deftest http-configuration
(testing "should enable need-client-auth"
(let [config (configure-web-server {:client-auth false})]
(is (= (get config :client-auth) :need))))
(let [old-config {:keystore "/some/path"
:key-password "<PASSWORD>"
:truststore "/some/other/path"
:trust-password "<PASSWORD>"}]
(testing "should not muck with keystore/truststore settings if PEM-based SSL settings are not provided"
(let [processed-config (configure-web-server old-config)]
(is (= old-config
(select-keys processed-config [:keystore :key-password :truststore :trust-password])))))
(testing "should fail if some but not all of the PEM-based SSL settings are found"
(let [partial-pem-config (merge old-config {:ssl-ca-cert "/some/path"})]
(is (thrown-with-msg? java.lang.IllegalArgumentException
#"If configuring SSL from PEM files, you must provide all of the following options"
(configure-web-server partial-pem-config)))))
(let [pem-config (merge old-config
{:ssl-key (resource "config/jetty/ssl/private_keys/localhost.pem")
:ssl-cert (resource "config/jetty/ssl/certs/localhost.pem")
:ssl-ca-cert (resource "config/jetty/ssl/certs/ca.pem")})]
(testing "should warn if both keystore-based and PEM-based SSL settings are found"
(with-log-output logs
(configure-web-server pem-config)
(is (= 1 (count (logs-matching #"Found settings for both keystore-based and PEM-based SSL" @logs))))))
(testing "should prefer PEM-based SSL settings, override old keystore settings
with instances of java.security.KeyStore, and remove PEM settings
from final jetty config hash"
(let [processed-config (configure-web-server pem-config)]
(is (instance? java.security.KeyStore (:keystore processed-config)))
(is (instance? java.security.KeyStore (:truststore processed-config)))
(is (string? (:key-password processed-config)))
(is (not (contains? processed-config :trust-password)))
(is (not (contains? processed-config :ssl-key)))
(is (not (contains? processed-config :ssl-cert)))
(is (not (contains? processed-config :ssl-ca-cert)))))))
(testing "should set max-threads"
(let [config (configure-web-server {})]
(is (contains? config :max-threads))))
(testing "should merge configuration with initial-configs correctly"
(let [user-config {:truststore "foo"}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 50 :client-auth :need :port 8080})))
(let [user-config {:max-threads 500 :truststore "foo" :port 8000}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 500 :client-auth :need :port 8000})))))
| true |
(ns puppetlabs.trapperkeeper.services.jetty.jetty-config-test
(:require [clojure.test :refer :all]
[clojure.java.io :refer [resource]]
[puppetlabs.trapperkeeper.services.jetty.jetty-config :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-output logs-matching]]))
(deftest jetty7-minimum-threads-test
(testing "should return the same number when higher than num-cpus"
(is (= 500 (jetty7-minimum-threads 500 1))))
(testing "should set the number to min threads when it is higher and return a warning"
(with-log-output logs
(is (= 4 (jetty7-minimum-threads 1 4)))
(is (= 1 (count (logs-matching #"max-threads = 1 is less than the minium allowed on this system for Jetty 7 to operate." @logs)))))))
(deftest http-configuration
(testing "should enable need-client-auth"
(let [config (configure-web-server {:client-auth false})]
(is (= (get config :client-auth) :need))))
(let [old-config {:keystore "/some/path"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:truststore "/some/other/path"
:trust-password "PI:PASSWORD:<PASSWORD>END_PI"}]
(testing "should not muck with keystore/truststore settings if PEM-based SSL settings are not provided"
(let [processed-config (configure-web-server old-config)]
(is (= old-config
(select-keys processed-config [:keystore :key-password :truststore :trust-password])))))
(testing "should fail if some but not all of the PEM-based SSL settings are found"
(let [partial-pem-config (merge old-config {:ssl-ca-cert "/some/path"})]
(is (thrown-with-msg? java.lang.IllegalArgumentException
#"If configuring SSL from PEM files, you must provide all of the following options"
(configure-web-server partial-pem-config)))))
(let [pem-config (merge old-config
{:ssl-key (resource "config/jetty/ssl/private_keys/localhost.pem")
:ssl-cert (resource "config/jetty/ssl/certs/localhost.pem")
:ssl-ca-cert (resource "config/jetty/ssl/certs/ca.pem")})]
(testing "should warn if both keystore-based and PEM-based SSL settings are found"
(with-log-output logs
(configure-web-server pem-config)
(is (= 1 (count (logs-matching #"Found settings for both keystore-based and PEM-based SSL" @logs))))))
(testing "should prefer PEM-based SSL settings, override old keystore settings
with instances of java.security.KeyStore, and remove PEM settings
from final jetty config hash"
(let [processed-config (configure-web-server pem-config)]
(is (instance? java.security.KeyStore (:keystore processed-config)))
(is (instance? java.security.KeyStore (:truststore processed-config)))
(is (string? (:key-password processed-config)))
(is (not (contains? processed-config :trust-password)))
(is (not (contains? processed-config :ssl-key)))
(is (not (contains? processed-config :ssl-cert)))
(is (not (contains? processed-config :ssl-ca-cert)))))))
(testing "should set max-threads"
(let [config (configure-web-server {})]
(is (contains? config :max-threads))))
(testing "should merge configuration with initial-configs correctly"
(let [user-config {:truststore "foo"}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 50 :client-auth :need :port 8080})))
(let [user-config {:max-threads 500 :truststore "foo" :port 8000}
config (configure-web-server user-config)]
(is (= config {:truststore "foo" :max-threads 500 :client-auth :need :port 8000})))))
|
[
{
"context": " :password ~password})\n (b/hide-modal {:id :",
"end": 4521,
"score": 0.9954765439033508,
"start": 4512,
"tag": "PASSWORD",
"value": "~password"
},
{
"context": " (co/field-with-label this props :user \"User\" :className \"form-control\")\n ",
"end": 16265,
"score": 0.9993300437927246,
"start": 16261,
"tag": "USERNAME",
"value": "User"
},
{
"context": " (co/field-with-label this props :password \"Password\" :className \"form-control\")))))\n (",
"end": 16398,
"score": 0.9994710683822632,
"start": 16390,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " (b/button {:key \"back-button\" :className \"btn-fill\" :kind :info\n ",
"end": 16585,
"score": 0.926900327205658,
"start": 16574,
"tag": "KEY",
"value": "back-button"
},
{
"context": " (b/button {:key \"ok-button\" :className \"btn-fill\" :kind :info\n ",
"end": 16874,
"score": 0.840472936630249,
"start": 16868,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"next-button\" :className \"btn-fill\" :kind :info\n ",
"end": 17123,
"score": 0.9229184985160828,
"start": 17117,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"cancel-button\" :className \"btn-fill\" :kind :danger\n ",
"end": 17475,
"score": 0.9658406376838684,
"start": 17469,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"back-button\" :className \"btn-fill\" :kind :info\n ",
"end": 22639,
"score": 0.9737627506256104,
"start": 22633,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"ok-button\" :className \"btn-fill\" :kind :info\n ",
"end": 22928,
"score": 0.9760006070137024,
"start": 22922,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"next-button\" :className \"btn-fill\" :kind :info\n ",
"end": 23171,
"score": 0.962074875831604,
"start": 23165,
"tag": "KEY",
"value": "button"
},
{
"context": " (b/button {:key \"cancel-button\" :className \"btn-fill\" :kind :danger\n ",
"end": 23485,
"score": 0.9869674444198608,
"start": 23479,
"tag": "KEY",
"value": "button"
},
{
"context": "st :show-schedule-events :schedule-event [[:name \"Name\"]\n ",
"end": 25772,
"score": 0.591262698173523,
"start": 25768,
"tag": "NAME",
"value": "Name"
}
] |
src/main/org/edgexfoundry/ui/manager/ui/schedules.cljs
|
lranjbar/edgex-ui-clojure
| 2 |
;;; Copyright (c) 2018
;;; IoTech Ltd
;;; SPDX-License-Identifier: Apache-2.0
(ns org.edgexfoundry.ui.manager.ui.schedules
(:require [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]]
[org.edgexfoundry.ui.manager.ui.dialogs :as d]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.client.localized-dom :as dom]
[fulcro.client.routing :as r]
[fulcro.i18n :refer [tr]]
[fulcro.ui.forms :as f]
[fulcro.ui.form-state :as fs]
[fulcro.ui.bootstrap3 :as b]
[org.edgexfoundry.ui.manager.api.mutations :as mu]
[org.edgexfoundry.ui.manager.ui.routing :as rt]
[org.edgexfoundry.ui.manager.ui.common :as co]
[org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp]
[org.edgexfoundry.ui.manager.ui.devices :as dv]
[org.edgexfoundry.ui.manager.ui.load :as ld]
[org.edgexfoundry.ui.manager.ui.routing :as routing]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.client.data-fetch :as df]
[clojure.set :as set]
[clojure.string :as str]
[cljs-time.coerce :as ct]
[cljs-time.format :as ft]
[cljs-time.core :as tc]))
(defn start-end-time-conv [p t]
(if t
t
"N/A"))
(defn do-delete-schedule [this id props]
(prim/transact! this `[(mu/delete-schedule {:id ~id})
(t/reset-table-page {:id :show-schedules})]))
(defn do-delete-schedule-event [this id props]
(prim/transact! this `[(mu/delete-schedule-event {:id ~id})
(t/reset-table-page {:id :show-schedule-events})]))
(defn set-schedule-events*
[state id]
(let [schedule (-> state :schedule id)
schedule-name (:name schedule)
events (vals (:schedule-event state))
selected-events (filter #(= schedule-name (:interval %)) events)
gen-refs (fn [se] [:schedule-event (:id se)])
content (mapv gen-refs selected-events)]
(-> state
(assoc-in [:show-schedule-events :singleton :content] content)
(assoc-in [:show-schedule-events :singleton :schedule-id] id)
(assoc-in (conj co/new-schedule-event-ident :schedule) schedule))))
(defmutation prepare-schedule-events
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-schedule-events* id))))))
(defmutation load-schedules
[{:keys [id]}]
(action [{:keys [state] :as env}]
(ld/load-action env :q/edgex-schedule-events dv/ScheduleEventListEntry
{:target (conj co/device-list-ident :schedule-events)
:post-mutation `prepare-schedule-events
:post-mutation-params {:id id}}))
(remote [env] (df/remote-load env)))
(defn show-schedule-events [this type id]
(prim/transact! this `[(prepare-schedule-events {:id ~id})])
(rt/nav-to! this :schedule-event {:id id}))
(defn show-schedule-event-info [this type id]
(rt/nav-to! this :schedule-event-info {:id id}))
(declare ScheduleList)
(declare ScheduleEventList)
(defn add-new-schedule-event [comp {:keys [name parameters schedule service target protocol httpMethod address port path publisher topic user password] :as form}]
(let [tmp-id (prim/tempid)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule-event {:tempid ~tmp-id
:name ~name
:parameters ~parameters
:schedule-name ~(:name schedule)
:target ~target
:protocol ~protocol
:httpMethod ~httpMethod
:address ~address
:port ~port
:path ~path
:publisher ~publisher
:topic ~topic
:user ~user
:password ~password})
(b/hide-modal {:id :add-schedule-event-modal})
(df/fallback {:action ld/reset-error})])))
(defn assoc-options [state field opts default]
(let [path (into co/new-schedule-event-ident [:fulcro.ui.forms/form :elements/by-name field])]
(-> state
(assoc-in (conj path :input/options) opts)
(assoc-in (conj path :input/default-value) default)
(assoc-in (conj co/new-schedule-event-ident field) default))))
(defn set-available-addressables* [state]
(let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m))))
dsa-ids (mk-id-set (:device-service state))
addrs (vals (:addressable state))
a-ids (into #{} (map :id addrs))
unused-ids (set/difference a-ids dsa-ids)
selected-addr (sort-by :name (filter #(unused-ids (:id %)) addrs))
opts (if (empty? selected-addr)
[(f/option :none "No addressable available")]
(mapv #(f/option (:id %) (:name %)) selected-addr))
default (or (-> selected-addr first :id) :none)]
(assoc-options state :addressable opts default)))
(defn set-schedule-services* [state]
(let [services (-> state :device-service vals)
opts (if (empty? services)
[(f/option :none "No services available")]
(mapv #(f/option (:id %) (:name %)) services))
default (or (-> services first) :none)]
(-> state
(assoc-options :target opts default))))
(defn reset-add-schedule-event* [state]
(-> state
(assoc-in [:new-schedule-event :singleton :confirm?] false)
(assoc-in (conj co/new-schedule-event-ident :name) "")
(assoc-in (conj co/new-schedule-event-ident :parameters) "")))
(defn set-new-schedule-data* [state]
(-> state
(assoc-in (conj co/new-schedule-event-ident :confirm?) true)))
(defmutation prepare-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-available-addressables*)
(reset-add-schedule-event*))))))
(defmutation prepare-confirm-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
set-new-schedule-data*)))))
(defn show-add-schedule-event-modal [comp]
(prim/transact! comp `[(prepare-add-schedule-event {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-event-ident})
(b/show-modal {:id :add-schedule-event-modal})
:modal-router]))
(def time-formatter1 (ft/formatter "yMMdd"))
(def time-formatter2 (ft/formatter "HHmmss"))
(defn get-time [tp]
(let [time (-> tp :time (ct/from-long))
time-str (str (ft/unparse time-formatter1 time) "T" (ft/unparse time-formatter2 time))]
(if (:no-default? tp) nil time-str)))
(defn add-new-schedule [comp form]
(let [tmp-id (prim/tempid)
{:keys [name start-time end-time frequency run-once]} form
start (get-time start-time)
end (get-time end-time)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule {:tempid ~tmp-id
:name ~name
:start ~start
:end ~end
:frequency ~frequency
:run-once ~run-once})
(b/hide-modal {:id :add-schedule-modal})
:show-schedules])
(df/load comp co/device-list-ident ScheduleList {:fallback `d/show-error})))
(declare AddScheduleModal)
(defn reset-add-schedule* [state]
(let [ref co/new-schedule-ident
now (-> (tc/now) (ct/to-long))]
(-> state
(assoc-in [:date-time-picker :schedule-start :time] now)
(assoc-in [:date-time-picker :schedule-end :time] now)
(assoc-in [:date-time-picker :schedule-start :no-default?] true)
(assoc-in [:date-time-picker :schedule-end :no-default?] true)
(assoc-in [:new-schedule :singleton :confirm?] false)
(assoc-in (conj ref :name) "")
(assoc-in (conj ref :frequency) "")
(assoc-in (conj ref :run-once) false))))
(defmutation prepare-add-schedule
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(reset-add-schedule*)
)))))
(defn show-add-schedule-modal [comp]
(prim/transact! comp `[(prepare-add-schedule {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-ident})
(b/show-modal {:id :add-schedule-modal})
:modal-router]))
(defn schedule-event-table [name parameters target schedule protocol httpMethod address port path publisher topic]
(let [if-avail #(or % "N/A")]
(dom/div :$schedule$container-fluid
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Name"))
(dom/div :$col-xs-8$col-md-9 name))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Parameters"))
(dom/div :$col-xs-8$col-md-9 (if (str/blank? parameters) "N/A" parameters)))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Service"))
(dom/div :$col-xs-8$col-md-9 (if-avail target)))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$schedule-title "Schedule")
(dom/div :$col-xs-4$col-md-3 "Name"
(dom/div :$short-div (tr "Start"))
(dom/div :$short-div (tr "End"))
(dom/div :$short-div (tr "Run Once")))
(dom/div :$col-xs-4$col-md-6 (:name schedule)
(dom/div :$short-div (if-avail (:start schedule)))
(dom/div :$short-div (if-avail (:end schedule)))
(dom/div :$short-div (if (nil? (:runOnce schedule)) "false" (-> schedule :runOnce str)))))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$address-title (tr "Address"))
(dom/div :$col-xs-4$col-md-3 (tr "Protocol")
(dom/div :$short-div (tr "HTTP Method"))
(dom/div :$short-div (tr "Address"))
(dom/div :$short-div (tr "Port"))
(dom/div :$short-div (tr "Path"))
(dom/div :$short-div (tr "Publisher"))
(dom/div :$short-div (tr "Topic")))
(dom/div :$col-xs-4$col-md-6 protocol
(dom/div :$short-div (co/conv-http-method httpMethod))
(dom/div :$short-div address)
(dom/div :$short-div port)
(dom/div :$short-div path)
(dom/div :$short-div publisher)
(dom/div :$short-div topic))))))
(defsc AddScheduleEventModal [this {:keys [modal name parameters target schedule protocol httpMethod address port path publisher topic confirm? modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 4})
{:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-event-modal :backdrop true})
:modal/page :new-schedule-event}))
:ident (fn [] co/new-schedule-event-ident)
:query [f/form-key :db/id :confirm? :name :parameters :schedule :target :protocol :httpMethod :address :port :path :publisher :topic :user :password
:confirm? :modal/page
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule Event" :validator `f/not-empty?)
(f/text-input :parameters :placeholder "Parameters")
(f/text-input :target :placeholder "Target")
(f/text-input :protocol)
(f/text-input :address :validator `f/not-empty?)
(f/integer-input :port)
(f/text-input :path)
(f/dropdown-input :httpMethod [(f/option :get "GET")
(f/option :post "POST")
(f/option :put "PUT")
(f/option :delete "DELETE")]
:default-value :get)
(f/text-input :publisher)
(f/text-input :topic)
(f/text-input :user)
(f/text-input :password)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule Event"))
(dom/div #js {:className "header"} "Add New Schedule Event")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule Event"))
(schedule-event-table name parameters target schedule protocol httpMethod address port path publisher topic))))
(dom/div {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(co/field-with-label this props :parameters "Parameters" :className "form-control")
(co/field-with-label this props :target "Target" :className "form-control")
(co/field-with-label this props :protocol "Protocol" :className "form-control")
(co/field-with-label this props :httpMethod "HTTP Method" :className "form-control")
(co/field-with-label this props :address "Address" :className "form-control")
(co/field-with-label this props :port "Port" :className "form-control")
(co/field-with-label this props :path "Path" :className "form-control")
(co/field-with-label this props :publisher "Publisher" :className "form-control")
(co/field-with-label this props :topic "Topic" :className "form-control")
(co/field-with-label this props :user "User" :className "form-control")
(co/field-with-label this props :password "Password" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "back-button" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-button" :className "btn-fill" :kind :info
:onClick #(add-new-schedule-event this props)}
"OK")
(b/button {:key "next-button" :className "btn-fill" :kind :info
:onClick #(prim/transact! this `[(prepare-confirm-add-schedule-event {})])
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-button" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-event-modal})])}
"Cancel")))))
(defn schedule-table [name start end freq run-once]
(let [if-time-set #(if (:no-default? %) "N/A" (->> % :time ct/from-long (ft/unparse dtp/time-formatter)))]
(dom/div
#js {:className "table-responsive"}
(dom/table
#js {:className "table table-bordered"}
(dom/tbody nil
(t/row "Name" name)
(t/row "Start" (if-time-set start))
(t/row "End" (if-time-set end))
(t/row "Frequency" (if (-> freq str/blank? not) freq "N/A"))
(t/row "Run Once" (str run-once)))))))
(defsc AddScheduleModal [this {:keys [modal confirm? name frequency run-once start-time end-time modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 5})
{:start-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-start
:time (tc/now)
:no-default true
:name "start-time"})
:end-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-end
:time (tc/now)
:no-default true
:name "end-time"})
:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-modal :backdrop true})
:modal/page :new-schedule}))
:ident (fn [] co/new-schedule-ident)
:query [f/form-key :db/id :confirm? :name :frequency :run-once :modal/page
{:start-time (prim/get-query dtp/DateTimePicker)}
{:end-time (prim/get-query dtp/DateTimePicker)}
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule" :validator `f/not-empty?)
(f/text-input :frequency :placeholder "Frequency")
(f/checkbox-input :run-once)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule"))
(dom/div #js {:className "header"} "Add New Schedule")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule"))
(schedule-table name start-time end-time frequency run-once))))
(dom/div #js {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "start-time"} "Start")
(dtp/date-time-picker start-time))
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "end-time"} "End")
(dtp/date-time-picker end-time))
(co/field-with-label this props :frequency "Frequency" :className "form-control")
(co/field-with-label this props :run-once "Run Once" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "back-button" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-button" :className "btn-fill" :kind :info
:onClick #(add-new-schedule this props)}
"OK")
(b/button {:key "next-button" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-button" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-modal})])}
"Cancel")))))
(defsc ScheduleEventInfo [this
{:keys [name interval target created protocol httpMethod address port path publisher topic] :as props}]
{:ident [:schedule-event :id]
:query [:id :type :name :interval :target :created :protocol :httpMethod :address :port :path :publisher :topic
[:show-schedule-events :singleton]]}
(let [schedule-id (:schedule-id (get props [:show-schedule-events :singleton]))]
(dom/div nil
(dom/div {:className "card"}
(dom/div {:className "fixed-table-toolbar"}
(dom/div {:className "bars pull-right"}
(b/button
{:onClick #(routing/nav-to! this :schedule-event {:id schedule-id})}
(dom/i {:className "glyphicon fa fa-caret-square-o-left"}))))
(dom/div {:className "header"}
(dom/h4 {:className "title"} "Schedule Event"))
(dom/div {:className "table-responsive"}
(dom/table {:className "table table-bordered"}
(dom/tbody nil
(t/row (tr "Name") name)
(t/row (tr "Schedule") interval)
(t/row (tr "Target") target)
(t/row (tr "Created") (co/conv-time created))
(dom/tr nil
(dom/th {:rowSpan "8"} "Address"))
(t/subrow (tr "Protocol") protocol)
(t/subrow (tr "HTTP Method") httpMethod)
(t/subrow (tr "Address") address)
(t/subrow (tr "Port") port)
(t/subrow (tr "Path") path)
(t/subrow (tr "Publisher") publisher)
(t/subrow (tr "Topic") topic))))))))
(deftable ScheduleEventList :show-schedule-events :schedule-event [[:name "Name"]
[:interval "Schedule"]
[:target "Target"]]
[{:onClick #(show-add-schedule-event-modal this) :icon "plus"}
{:onClick #(rt/nav-to! this :schedule) :icon "caret-square-o-left"}]
:modals [{:modal d/DeleteModal :params {:modal-id :dse-modal} :callbacks {:onDelete do-delete-schedule-event}}]
:actions [{:title "View Schedule Event" :action-class :info :symbol "info" :onClick show-schedule-event-info}
{:title "Delete Schedule Event" :action-class :danger :symbol "times"
:onClick (d/mk-show-modal :dse-modal)}])
(defsc ScheduleEvents [this {:keys [id type addressable]}]
{:ident [:schedule-event :id]
:query [:id :type :addressable]})
(deftable ScheduleList :show-schedules :schedule [[:name "Name"] [:start "Start" start-end-time-conv]
[:end "End" start-end-time-conv] [:frequency "Frequency"]
[:runOnce "Run Once"]]
[{:onClick #(show-add-schedule-modal this) :icon "plus"}
{:onClick #(df/refresh! this) :icon "refresh"}]
:query [{:events (prim/get-query ScheduleEvents)}]
:modals [{:modal d/DeleteModal :params {:modal-id :ds-modal} :callbacks {:onDelete do-delete-schedule}}]
:actions [{:title "Show Events" :action-class :info :symbol "cogs" :onClick show-schedule-events}
{:title "Delete Schedule" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :ds-modal)}])
|
4836
|
;;; Copyright (c) 2018
;;; IoTech Ltd
;;; SPDX-License-Identifier: Apache-2.0
(ns org.edgexfoundry.ui.manager.ui.schedules
(:require [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]]
[org.edgexfoundry.ui.manager.ui.dialogs :as d]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.client.localized-dom :as dom]
[fulcro.client.routing :as r]
[fulcro.i18n :refer [tr]]
[fulcro.ui.forms :as f]
[fulcro.ui.form-state :as fs]
[fulcro.ui.bootstrap3 :as b]
[org.edgexfoundry.ui.manager.api.mutations :as mu]
[org.edgexfoundry.ui.manager.ui.routing :as rt]
[org.edgexfoundry.ui.manager.ui.common :as co]
[org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp]
[org.edgexfoundry.ui.manager.ui.devices :as dv]
[org.edgexfoundry.ui.manager.ui.load :as ld]
[org.edgexfoundry.ui.manager.ui.routing :as routing]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.client.data-fetch :as df]
[clojure.set :as set]
[clojure.string :as str]
[cljs-time.coerce :as ct]
[cljs-time.format :as ft]
[cljs-time.core :as tc]))
(defn start-end-time-conv [p t]
(if t
t
"N/A"))
(defn do-delete-schedule [this id props]
(prim/transact! this `[(mu/delete-schedule {:id ~id})
(t/reset-table-page {:id :show-schedules})]))
(defn do-delete-schedule-event [this id props]
(prim/transact! this `[(mu/delete-schedule-event {:id ~id})
(t/reset-table-page {:id :show-schedule-events})]))
(defn set-schedule-events*
[state id]
(let [schedule (-> state :schedule id)
schedule-name (:name schedule)
events (vals (:schedule-event state))
selected-events (filter #(= schedule-name (:interval %)) events)
gen-refs (fn [se] [:schedule-event (:id se)])
content (mapv gen-refs selected-events)]
(-> state
(assoc-in [:show-schedule-events :singleton :content] content)
(assoc-in [:show-schedule-events :singleton :schedule-id] id)
(assoc-in (conj co/new-schedule-event-ident :schedule) schedule))))
(defmutation prepare-schedule-events
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-schedule-events* id))))))
(defmutation load-schedules
[{:keys [id]}]
(action [{:keys [state] :as env}]
(ld/load-action env :q/edgex-schedule-events dv/ScheduleEventListEntry
{:target (conj co/device-list-ident :schedule-events)
:post-mutation `prepare-schedule-events
:post-mutation-params {:id id}}))
(remote [env] (df/remote-load env)))
(defn show-schedule-events [this type id]
(prim/transact! this `[(prepare-schedule-events {:id ~id})])
(rt/nav-to! this :schedule-event {:id id}))
(defn show-schedule-event-info [this type id]
(rt/nav-to! this :schedule-event-info {:id id}))
(declare ScheduleList)
(declare ScheduleEventList)
(defn add-new-schedule-event [comp {:keys [name parameters schedule service target protocol httpMethod address port path publisher topic user password] :as form}]
(let [tmp-id (prim/tempid)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule-event {:tempid ~tmp-id
:name ~name
:parameters ~parameters
:schedule-name ~(:name schedule)
:target ~target
:protocol ~protocol
:httpMethod ~httpMethod
:address ~address
:port ~port
:path ~path
:publisher ~publisher
:topic ~topic
:user ~user
:password <PASSWORD>})
(b/hide-modal {:id :add-schedule-event-modal})
(df/fallback {:action ld/reset-error})])))
(defn assoc-options [state field opts default]
(let [path (into co/new-schedule-event-ident [:fulcro.ui.forms/form :elements/by-name field])]
(-> state
(assoc-in (conj path :input/options) opts)
(assoc-in (conj path :input/default-value) default)
(assoc-in (conj co/new-schedule-event-ident field) default))))
(defn set-available-addressables* [state]
(let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m))))
dsa-ids (mk-id-set (:device-service state))
addrs (vals (:addressable state))
a-ids (into #{} (map :id addrs))
unused-ids (set/difference a-ids dsa-ids)
selected-addr (sort-by :name (filter #(unused-ids (:id %)) addrs))
opts (if (empty? selected-addr)
[(f/option :none "No addressable available")]
(mapv #(f/option (:id %) (:name %)) selected-addr))
default (or (-> selected-addr first :id) :none)]
(assoc-options state :addressable opts default)))
(defn set-schedule-services* [state]
(let [services (-> state :device-service vals)
opts (if (empty? services)
[(f/option :none "No services available")]
(mapv #(f/option (:id %) (:name %)) services))
default (or (-> services first) :none)]
(-> state
(assoc-options :target opts default))))
(defn reset-add-schedule-event* [state]
(-> state
(assoc-in [:new-schedule-event :singleton :confirm?] false)
(assoc-in (conj co/new-schedule-event-ident :name) "")
(assoc-in (conj co/new-schedule-event-ident :parameters) "")))
(defn set-new-schedule-data* [state]
(-> state
(assoc-in (conj co/new-schedule-event-ident :confirm?) true)))
(defmutation prepare-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-available-addressables*)
(reset-add-schedule-event*))))))
(defmutation prepare-confirm-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
set-new-schedule-data*)))))
(defn show-add-schedule-event-modal [comp]
(prim/transact! comp `[(prepare-add-schedule-event {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-event-ident})
(b/show-modal {:id :add-schedule-event-modal})
:modal-router]))
(def time-formatter1 (ft/formatter "yMMdd"))
(def time-formatter2 (ft/formatter "HHmmss"))
(defn get-time [tp]
(let [time (-> tp :time (ct/from-long))
time-str (str (ft/unparse time-formatter1 time) "T" (ft/unparse time-formatter2 time))]
(if (:no-default? tp) nil time-str)))
(defn add-new-schedule [comp form]
(let [tmp-id (prim/tempid)
{:keys [name start-time end-time frequency run-once]} form
start (get-time start-time)
end (get-time end-time)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule {:tempid ~tmp-id
:name ~name
:start ~start
:end ~end
:frequency ~frequency
:run-once ~run-once})
(b/hide-modal {:id :add-schedule-modal})
:show-schedules])
(df/load comp co/device-list-ident ScheduleList {:fallback `d/show-error})))
(declare AddScheduleModal)
(defn reset-add-schedule* [state]
(let [ref co/new-schedule-ident
now (-> (tc/now) (ct/to-long))]
(-> state
(assoc-in [:date-time-picker :schedule-start :time] now)
(assoc-in [:date-time-picker :schedule-end :time] now)
(assoc-in [:date-time-picker :schedule-start :no-default?] true)
(assoc-in [:date-time-picker :schedule-end :no-default?] true)
(assoc-in [:new-schedule :singleton :confirm?] false)
(assoc-in (conj ref :name) "")
(assoc-in (conj ref :frequency) "")
(assoc-in (conj ref :run-once) false))))
(defmutation prepare-add-schedule
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(reset-add-schedule*)
)))))
(defn show-add-schedule-modal [comp]
(prim/transact! comp `[(prepare-add-schedule {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-ident})
(b/show-modal {:id :add-schedule-modal})
:modal-router]))
(defn schedule-event-table [name parameters target schedule protocol httpMethod address port path publisher topic]
(let [if-avail #(or % "N/A")]
(dom/div :$schedule$container-fluid
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Name"))
(dom/div :$col-xs-8$col-md-9 name))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Parameters"))
(dom/div :$col-xs-8$col-md-9 (if (str/blank? parameters) "N/A" parameters)))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Service"))
(dom/div :$col-xs-8$col-md-9 (if-avail target)))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$schedule-title "Schedule")
(dom/div :$col-xs-4$col-md-3 "Name"
(dom/div :$short-div (tr "Start"))
(dom/div :$short-div (tr "End"))
(dom/div :$short-div (tr "Run Once")))
(dom/div :$col-xs-4$col-md-6 (:name schedule)
(dom/div :$short-div (if-avail (:start schedule)))
(dom/div :$short-div (if-avail (:end schedule)))
(dom/div :$short-div (if (nil? (:runOnce schedule)) "false" (-> schedule :runOnce str)))))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$address-title (tr "Address"))
(dom/div :$col-xs-4$col-md-3 (tr "Protocol")
(dom/div :$short-div (tr "HTTP Method"))
(dom/div :$short-div (tr "Address"))
(dom/div :$short-div (tr "Port"))
(dom/div :$short-div (tr "Path"))
(dom/div :$short-div (tr "Publisher"))
(dom/div :$short-div (tr "Topic")))
(dom/div :$col-xs-4$col-md-6 protocol
(dom/div :$short-div (co/conv-http-method httpMethod))
(dom/div :$short-div address)
(dom/div :$short-div port)
(dom/div :$short-div path)
(dom/div :$short-div publisher)
(dom/div :$short-div topic))))))
(defsc AddScheduleEventModal [this {:keys [modal name parameters target schedule protocol httpMethod address port path publisher topic confirm? modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 4})
{:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-event-modal :backdrop true})
:modal/page :new-schedule-event}))
:ident (fn [] co/new-schedule-event-ident)
:query [f/form-key :db/id :confirm? :name :parameters :schedule :target :protocol :httpMethod :address :port :path :publisher :topic :user :password
:confirm? :modal/page
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule Event" :validator `f/not-empty?)
(f/text-input :parameters :placeholder "Parameters")
(f/text-input :target :placeholder "Target")
(f/text-input :protocol)
(f/text-input :address :validator `f/not-empty?)
(f/integer-input :port)
(f/text-input :path)
(f/dropdown-input :httpMethod [(f/option :get "GET")
(f/option :post "POST")
(f/option :put "PUT")
(f/option :delete "DELETE")]
:default-value :get)
(f/text-input :publisher)
(f/text-input :topic)
(f/text-input :user)
(f/text-input :password)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule Event"))
(dom/div #js {:className "header"} "Add New Schedule Event")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule Event"))
(schedule-event-table name parameters target schedule protocol httpMethod address port path publisher topic))))
(dom/div {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(co/field-with-label this props :parameters "Parameters" :className "form-control")
(co/field-with-label this props :target "Target" :className "form-control")
(co/field-with-label this props :protocol "Protocol" :className "form-control")
(co/field-with-label this props :httpMethod "HTTP Method" :className "form-control")
(co/field-with-label this props :address "Address" :className "form-control")
(co/field-with-label this props :port "Port" :className "form-control")
(co/field-with-label this props :path "Path" :className "form-control")
(co/field-with-label this props :publisher "Publisher" :className "form-control")
(co/field-with-label this props :topic "Topic" :className "form-control")
(co/field-with-label this props :user "User" :className "form-control")
(co/field-with-label this props :password "<PASSWORD>" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "<KEY>" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-<KEY>" :className "btn-fill" :kind :info
:onClick #(add-new-schedule-event this props)}
"OK")
(b/button {:key "next-<KEY>" :className "btn-fill" :kind :info
:onClick #(prim/transact! this `[(prepare-confirm-add-schedule-event {})])
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-<KEY>" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-event-modal})])}
"Cancel")))))
(defn schedule-table [name start end freq run-once]
(let [if-time-set #(if (:no-default? %) "N/A" (->> % :time ct/from-long (ft/unparse dtp/time-formatter)))]
(dom/div
#js {:className "table-responsive"}
(dom/table
#js {:className "table table-bordered"}
(dom/tbody nil
(t/row "Name" name)
(t/row "Start" (if-time-set start))
(t/row "End" (if-time-set end))
(t/row "Frequency" (if (-> freq str/blank? not) freq "N/A"))
(t/row "Run Once" (str run-once)))))))
(defsc AddScheduleModal [this {:keys [modal confirm? name frequency run-once start-time end-time modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 5})
{:start-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-start
:time (tc/now)
:no-default true
:name "start-time"})
:end-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-end
:time (tc/now)
:no-default true
:name "end-time"})
:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-modal :backdrop true})
:modal/page :new-schedule}))
:ident (fn [] co/new-schedule-ident)
:query [f/form-key :db/id :confirm? :name :frequency :run-once :modal/page
{:start-time (prim/get-query dtp/DateTimePicker)}
{:end-time (prim/get-query dtp/DateTimePicker)}
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule" :validator `f/not-empty?)
(f/text-input :frequency :placeholder "Frequency")
(f/checkbox-input :run-once)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule"))
(dom/div #js {:className "header"} "Add New Schedule")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule"))
(schedule-table name start-time end-time frequency run-once))))
(dom/div #js {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "start-time"} "Start")
(dtp/date-time-picker start-time))
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "end-time"} "End")
(dtp/date-time-picker end-time))
(co/field-with-label this props :frequency "Frequency" :className "form-control")
(co/field-with-label this props :run-once "Run Once" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "back-<KEY>" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-<KEY>" :className "btn-fill" :kind :info
:onClick #(add-new-schedule this props)}
"OK")
(b/button {:key "next-<KEY>" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-<KEY>" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-modal})])}
"Cancel")))))
(defsc ScheduleEventInfo [this
{:keys [name interval target created protocol httpMethod address port path publisher topic] :as props}]
{:ident [:schedule-event :id]
:query [:id :type :name :interval :target :created :protocol :httpMethod :address :port :path :publisher :topic
[:show-schedule-events :singleton]]}
(let [schedule-id (:schedule-id (get props [:show-schedule-events :singleton]))]
(dom/div nil
(dom/div {:className "card"}
(dom/div {:className "fixed-table-toolbar"}
(dom/div {:className "bars pull-right"}
(b/button
{:onClick #(routing/nav-to! this :schedule-event {:id schedule-id})}
(dom/i {:className "glyphicon fa fa-caret-square-o-left"}))))
(dom/div {:className "header"}
(dom/h4 {:className "title"} "Schedule Event"))
(dom/div {:className "table-responsive"}
(dom/table {:className "table table-bordered"}
(dom/tbody nil
(t/row (tr "Name") name)
(t/row (tr "Schedule") interval)
(t/row (tr "Target") target)
(t/row (tr "Created") (co/conv-time created))
(dom/tr nil
(dom/th {:rowSpan "8"} "Address"))
(t/subrow (tr "Protocol") protocol)
(t/subrow (tr "HTTP Method") httpMethod)
(t/subrow (tr "Address") address)
(t/subrow (tr "Port") port)
(t/subrow (tr "Path") path)
(t/subrow (tr "Publisher") publisher)
(t/subrow (tr "Topic") topic))))))))
(deftable ScheduleEventList :show-schedule-events :schedule-event [[:name "<NAME>"]
[:interval "Schedule"]
[:target "Target"]]
[{:onClick #(show-add-schedule-event-modal this) :icon "plus"}
{:onClick #(rt/nav-to! this :schedule) :icon "caret-square-o-left"}]
:modals [{:modal d/DeleteModal :params {:modal-id :dse-modal} :callbacks {:onDelete do-delete-schedule-event}}]
:actions [{:title "View Schedule Event" :action-class :info :symbol "info" :onClick show-schedule-event-info}
{:title "Delete Schedule Event" :action-class :danger :symbol "times"
:onClick (d/mk-show-modal :dse-modal)}])
(defsc ScheduleEvents [this {:keys [id type addressable]}]
{:ident [:schedule-event :id]
:query [:id :type :addressable]})
(deftable ScheduleList :show-schedules :schedule [[:name "Name"] [:start "Start" start-end-time-conv]
[:end "End" start-end-time-conv] [:frequency "Frequency"]
[:runOnce "Run Once"]]
[{:onClick #(show-add-schedule-modal this) :icon "plus"}
{:onClick #(df/refresh! this) :icon "refresh"}]
:query [{:events (prim/get-query ScheduleEvents)}]
:modals [{:modal d/DeleteModal :params {:modal-id :ds-modal} :callbacks {:onDelete do-delete-schedule}}]
:actions [{:title "Show Events" :action-class :info :symbol "cogs" :onClick show-schedule-events}
{:title "Delete Schedule" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :ds-modal)}])
| true |
;;; Copyright (c) 2018
;;; IoTech Ltd
;;; SPDX-License-Identifier: Apache-2.0
(ns org.edgexfoundry.ui.manager.ui.schedules
(:require [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]]
[org.edgexfoundry.ui.manager.ui.dialogs :as d]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.client.localized-dom :as dom]
[fulcro.client.routing :as r]
[fulcro.i18n :refer [tr]]
[fulcro.ui.forms :as f]
[fulcro.ui.form-state :as fs]
[fulcro.ui.bootstrap3 :as b]
[org.edgexfoundry.ui.manager.api.mutations :as mu]
[org.edgexfoundry.ui.manager.ui.routing :as rt]
[org.edgexfoundry.ui.manager.ui.common :as co]
[org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp]
[org.edgexfoundry.ui.manager.ui.devices :as dv]
[org.edgexfoundry.ui.manager.ui.load :as ld]
[org.edgexfoundry.ui.manager.ui.routing :as routing]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.client.data-fetch :as df]
[clojure.set :as set]
[clojure.string :as str]
[cljs-time.coerce :as ct]
[cljs-time.format :as ft]
[cljs-time.core :as tc]))
(defn start-end-time-conv [p t]
(if t
t
"N/A"))
(defn do-delete-schedule [this id props]
(prim/transact! this `[(mu/delete-schedule {:id ~id})
(t/reset-table-page {:id :show-schedules})]))
(defn do-delete-schedule-event [this id props]
(prim/transact! this `[(mu/delete-schedule-event {:id ~id})
(t/reset-table-page {:id :show-schedule-events})]))
(defn set-schedule-events*
[state id]
(let [schedule (-> state :schedule id)
schedule-name (:name schedule)
events (vals (:schedule-event state))
selected-events (filter #(= schedule-name (:interval %)) events)
gen-refs (fn [se] [:schedule-event (:id se)])
content (mapv gen-refs selected-events)]
(-> state
(assoc-in [:show-schedule-events :singleton :content] content)
(assoc-in [:show-schedule-events :singleton :schedule-id] id)
(assoc-in (conj co/new-schedule-event-ident :schedule) schedule))))
(defmutation prepare-schedule-events
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-schedule-events* id))))))
(defmutation load-schedules
[{:keys [id]}]
(action [{:keys [state] :as env}]
(ld/load-action env :q/edgex-schedule-events dv/ScheduleEventListEntry
{:target (conj co/device-list-ident :schedule-events)
:post-mutation `prepare-schedule-events
:post-mutation-params {:id id}}))
(remote [env] (df/remote-load env)))
(defn show-schedule-events [this type id]
(prim/transact! this `[(prepare-schedule-events {:id ~id})])
(rt/nav-to! this :schedule-event {:id id}))
(defn show-schedule-event-info [this type id]
(rt/nav-to! this :schedule-event-info {:id id}))
(declare ScheduleList)
(declare ScheduleEventList)
(defn add-new-schedule-event [comp {:keys [name parameters schedule service target protocol httpMethod address port path publisher topic user password] :as form}]
(let [tmp-id (prim/tempid)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule-event {:tempid ~tmp-id
:name ~name
:parameters ~parameters
:schedule-name ~(:name schedule)
:target ~target
:protocol ~protocol
:httpMethod ~httpMethod
:address ~address
:port ~port
:path ~path
:publisher ~publisher
:topic ~topic
:user ~user
:password PI:PASSWORD:<PASSWORD>END_PI})
(b/hide-modal {:id :add-schedule-event-modal})
(df/fallback {:action ld/reset-error})])))
(defn assoc-options [state field opts default]
(let [path (into co/new-schedule-event-ident [:fulcro.ui.forms/form :elements/by-name field])]
(-> state
(assoc-in (conj path :input/options) opts)
(assoc-in (conj path :input/default-value) default)
(assoc-in (conj co/new-schedule-event-ident field) default))))
(defn set-available-addressables* [state]
(let [mk-id-set (fn [m] (into #{} (map #(-> % :addressable :id) (vals m))))
dsa-ids (mk-id-set (:device-service state))
addrs (vals (:addressable state))
a-ids (into #{} (map :id addrs))
unused-ids (set/difference a-ids dsa-ids)
selected-addr (sort-by :name (filter #(unused-ids (:id %)) addrs))
opts (if (empty? selected-addr)
[(f/option :none "No addressable available")]
(mapv #(f/option (:id %) (:name %)) selected-addr))
default (or (-> selected-addr first :id) :none)]
(assoc-options state :addressable opts default)))
(defn set-schedule-services* [state]
(let [services (-> state :device-service vals)
opts (if (empty? services)
[(f/option :none "No services available")]
(mapv #(f/option (:id %) (:name %)) services))
default (or (-> services first) :none)]
(-> state
(assoc-options :target opts default))))
(defn reset-add-schedule-event* [state]
(-> state
(assoc-in [:new-schedule-event :singleton :confirm?] false)
(assoc-in (conj co/new-schedule-event-ident :name) "")
(assoc-in (conj co/new-schedule-event-ident :parameters) "")))
(defn set-new-schedule-data* [state]
(-> state
(assoc-in (conj co/new-schedule-event-ident :confirm?) true)))
(defmutation prepare-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(set-available-addressables*)
(reset-add-schedule-event*))))))
(defmutation prepare-confirm-add-schedule-event
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
set-new-schedule-data*)))))
(defn show-add-schedule-event-modal [comp]
(prim/transact! comp `[(prepare-add-schedule-event {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-event-ident})
(b/show-modal {:id :add-schedule-event-modal})
:modal-router]))
(def time-formatter1 (ft/formatter "yMMdd"))
(def time-formatter2 (ft/formatter "HHmmss"))
(defn get-time [tp]
(let [time (-> tp :time (ct/from-long))
time-str (str (ft/unparse time-formatter1 time) "T" (ft/unparse time-formatter2 time))]
(if (:no-default? tp) nil time-str)))
(defn add-new-schedule [comp form]
(let [tmp-id (prim/tempid)
{:keys [name start-time end-time frequency run-once]} form
start (get-time start-time)
end (get-time end-time)]
(f/reset-from-entity! comp form)
(prim/transact! comp `[(mu/add-schedule {:tempid ~tmp-id
:name ~name
:start ~start
:end ~end
:frequency ~frequency
:run-once ~run-once})
(b/hide-modal {:id :add-schedule-modal})
:show-schedules])
(df/load comp co/device-list-ident ScheduleList {:fallback `d/show-error})))
(declare AddScheduleModal)
(defn reset-add-schedule* [state]
(let [ref co/new-schedule-ident
now (-> (tc/now) (ct/to-long))]
(-> state
(assoc-in [:date-time-picker :schedule-start :time] now)
(assoc-in [:date-time-picker :schedule-end :time] now)
(assoc-in [:date-time-picker :schedule-start :no-default?] true)
(assoc-in [:date-time-picker :schedule-end :no-default?] true)
(assoc-in [:new-schedule :singleton :confirm?] false)
(assoc-in (conj ref :name) "")
(assoc-in (conj ref :frequency) "")
(assoc-in (conj ref :run-once) false))))
(defmutation prepare-add-schedule
[noargs]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(reset-add-schedule*)
)))))
(defn show-add-schedule-modal [comp]
(prim/transact! comp `[(prepare-add-schedule {})
(r/set-route {:router :root/modal-router :target ~co/new-schedule-ident})
(b/show-modal {:id :add-schedule-modal})
:modal-router]))
(defn schedule-event-table [name parameters target schedule protocol httpMethod address port path publisher topic]
(let [if-avail #(or % "N/A")]
(dom/div :$schedule$container-fluid
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Name"))
(dom/div :$col-xs-8$col-md-9 name))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Parameters"))
(dom/div :$col-xs-8$col-md-9 (if (str/blank? parameters) "N/A" parameters)))
(dom/div :$row$row-no-gutters
(dom/div :$col-xs-4$col-md-3 (tr "Service"))
(dom/div :$col-xs-8$col-md-9 (if-avail target)))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$schedule-title "Schedule")
(dom/div :$col-xs-4$col-md-3 "Name"
(dom/div :$short-div (tr "Start"))
(dom/div :$short-div (tr "End"))
(dom/div :$short-div (tr "Run Once")))
(dom/div :$col-xs-4$col-md-6 (:name schedule)
(dom/div :$short-div (if-avail (:start schedule)))
(dom/div :$short-div (if-avail (:end schedule)))
(dom/div :$short-div (if (nil? (:runOnce schedule)) "false" (-> schedule :runOnce str)))))
(dom/div :$row
(dom/div :$col-xs-4$col-md-3$address-title (tr "Address"))
(dom/div :$col-xs-4$col-md-3 (tr "Protocol")
(dom/div :$short-div (tr "HTTP Method"))
(dom/div :$short-div (tr "Address"))
(dom/div :$short-div (tr "Port"))
(dom/div :$short-div (tr "Path"))
(dom/div :$short-div (tr "Publisher"))
(dom/div :$short-div (tr "Topic")))
(dom/div :$col-xs-4$col-md-6 protocol
(dom/div :$short-div (co/conv-http-method httpMethod))
(dom/div :$short-div address)
(dom/div :$short-div port)
(dom/div :$short-div path)
(dom/div :$short-div publisher)
(dom/div :$short-div topic))))))
(defsc AddScheduleEventModal [this {:keys [modal name parameters target schedule protocol httpMethod address port path publisher topic confirm? modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 4})
{:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-event-modal :backdrop true})
:modal/page :new-schedule-event}))
:ident (fn [] co/new-schedule-event-ident)
:query [f/form-key :db/id :confirm? :name :parameters :schedule :target :protocol :httpMethod :address :port :path :publisher :topic :user :password
:confirm? :modal/page
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule Event" :validator `f/not-empty?)
(f/text-input :parameters :placeholder "Parameters")
(f/text-input :target :placeholder "Target")
(f/text-input :protocol)
(f/text-input :address :validator `f/not-empty?)
(f/integer-input :port)
(f/text-input :path)
(f/dropdown-input :httpMethod [(f/option :get "GET")
(f/option :post "POST")
(f/option :put "PUT")
(f/option :delete "DELETE")]
:default-value :get)
(f/text-input :publisher)
(f/text-input :topic)
(f/text-input :user)
(f/text-input :password)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule Event"))
(dom/div #js {:className "header"} "Add New Schedule Event")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule Event"))
(schedule-event-table name parameters target schedule protocol httpMethod address port path publisher topic))))
(dom/div {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(co/field-with-label this props :parameters "Parameters" :className "form-control")
(co/field-with-label this props :target "Target" :className "form-control")
(co/field-with-label this props :protocol "Protocol" :className "form-control")
(co/field-with-label this props :httpMethod "HTTP Method" :className "form-control")
(co/field-with-label this props :address "Address" :className "form-control")
(co/field-with-label this props :port "Port" :className "form-control")
(co/field-with-label this props :path "Path" :className "form-control")
(co/field-with-label this props :publisher "Publisher" :className "form-control")
(co/field-with-label this props :topic "Topic" :className "form-control")
(co/field-with-label this props :user "User" :className "form-control")
(co/field-with-label this props :password "PI:PASSWORD:<PASSWORD>END_PI" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(add-new-schedule-event this props)}
"OK")
(b/button {:key "next-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(prim/transact! this `[(prepare-confirm-add-schedule-event {})])
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-event-modal})])}
"Cancel")))))
(defn schedule-table [name start end freq run-once]
(let [if-time-set #(if (:no-default? %) "N/A" (->> % :time ct/from-long (ft/unparse dtp/time-formatter)))]
(dom/div
#js {:className "table-responsive"}
(dom/table
#js {:className "table table-bordered"}
(dom/tbody nil
(t/row "Name" name)
(t/row "Start" (if-time-set start))
(t/row "End" (if-time-set end))
(t/row "Frequency" (if (-> freq str/blank? not) freq "N/A"))
(t/row "Run Once" (str run-once)))))))
(defsc AddScheduleModal [this {:keys [modal confirm? name frequency run-once start-time end-time modal/page] :as props}]
{:initial-state (fn [p] (merge (f/build-form this {:db/id 5})
{:start-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-start
:time (tc/now)
:no-default true
:name "start-time"})
:end-time (prim/get-initial-state dtp/DateTimePicker {:id :schedule-end
:time (tc/now)
:no-default true
:name "end-time"})
:confirm? false
:modal (prim/get-initial-state b/Modal {:id :add-schedule-modal :backdrop true})
:modal/page :new-schedule}))
:ident (fn [] co/new-schedule-ident)
:query [f/form-key :db/id :confirm? :name :frequency :run-once :modal/page
{:start-time (prim/get-query dtp/DateTimePicker)}
{:end-time (prim/get-query dtp/DateTimePicker)}
{:modal (prim/get-query b/Modal)}]
:form-fields [(f/id-field :db/id)
(f/text-input :name :placeholder "Name of the Schedule" :validator `f/not-empty?)
(f/text-input :frequency :placeholder "Frequency")
(f/checkbox-input :run-once)]}
(let [valid? (f/valid? (f/validate-fields props))]
(b/ui-modal modal
(b/ui-modal-title nil
(dom/div #js {:key "title"
:style #js {:fontSize "22px"}} "Add New Schedule"))
(dom/div #js {:className "header"} "Add New Schedule")
(b/ui-modal-body nil
(dom/div #js {:className "card"}
(if confirm?
(dom/div #js {:className "container-fluid"}
(dom/div #js {:className "row"}
(dom/div #js {:className "col-md-12"}
(dom/div #js {:className "header"}
(dom/h4 #js {:className "title"} "Schedule"))
(schedule-table name start-time end-time frequency run-once))))
(dom/div #js {:className "content"}
(co/field-with-label this props :name "Name" :className "form-control")
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "start-time"} "Start")
(dtp/date-time-picker start-time))
(dom/div #js {:className "form-group" :style #js {:position "relative"}}
(dom/label #js {:className "control-label" :htmlFor "end-time"} "End")
(dtp/date-time-picker end-time))
(co/field-with-label this props :frequency "Frequency" :className "form-control")
(co/field-with-label this props :run-once "Run Once" :className "form-control")))))
(b/ui-modal-footer nil
(when confirm?
(b/button {:key "back-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)}
"Back"))
(if confirm?
(b/button {:key "ok-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(add-new-schedule this props)}
"OK")
(b/button {:key "next-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :info
:onClick #(m/toggle! this :confirm?)
:disabled (not valid?)}
"Next"))
(b/button {:key "cancel-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :danger
:onClick #(prim/transact!
this `[(b/hide-modal {:id :add-schedule-modal})])}
"Cancel")))))
(defsc ScheduleEventInfo [this
{:keys [name interval target created protocol httpMethod address port path publisher topic] :as props}]
{:ident [:schedule-event :id]
:query [:id :type :name :interval :target :created :protocol :httpMethod :address :port :path :publisher :topic
[:show-schedule-events :singleton]]}
(let [schedule-id (:schedule-id (get props [:show-schedule-events :singleton]))]
(dom/div nil
(dom/div {:className "card"}
(dom/div {:className "fixed-table-toolbar"}
(dom/div {:className "bars pull-right"}
(b/button
{:onClick #(routing/nav-to! this :schedule-event {:id schedule-id})}
(dom/i {:className "glyphicon fa fa-caret-square-o-left"}))))
(dom/div {:className "header"}
(dom/h4 {:className "title"} "Schedule Event"))
(dom/div {:className "table-responsive"}
(dom/table {:className "table table-bordered"}
(dom/tbody nil
(t/row (tr "Name") name)
(t/row (tr "Schedule") interval)
(t/row (tr "Target") target)
(t/row (tr "Created") (co/conv-time created))
(dom/tr nil
(dom/th {:rowSpan "8"} "Address"))
(t/subrow (tr "Protocol") protocol)
(t/subrow (tr "HTTP Method") httpMethod)
(t/subrow (tr "Address") address)
(t/subrow (tr "Port") port)
(t/subrow (tr "Path") path)
(t/subrow (tr "Publisher") publisher)
(t/subrow (tr "Topic") topic))))))))
(deftable ScheduleEventList :show-schedule-events :schedule-event [[:name "PI:NAME:<NAME>END_PI"]
[:interval "Schedule"]
[:target "Target"]]
[{:onClick #(show-add-schedule-event-modal this) :icon "plus"}
{:onClick #(rt/nav-to! this :schedule) :icon "caret-square-o-left"}]
:modals [{:modal d/DeleteModal :params {:modal-id :dse-modal} :callbacks {:onDelete do-delete-schedule-event}}]
:actions [{:title "View Schedule Event" :action-class :info :symbol "info" :onClick show-schedule-event-info}
{:title "Delete Schedule Event" :action-class :danger :symbol "times"
:onClick (d/mk-show-modal :dse-modal)}])
(defsc ScheduleEvents [this {:keys [id type addressable]}]
{:ident [:schedule-event :id]
:query [:id :type :addressable]})
(deftable ScheduleList :show-schedules :schedule [[:name "Name"] [:start "Start" start-end-time-conv]
[:end "End" start-end-time-conv] [:frequency "Frequency"]
[:runOnce "Run Once"]]
[{:onClick #(show-add-schedule-modal this) :icon "plus"}
{:onClick #(df/refresh! this) :icon "refresh"}]
:query [{:events (prim/get-query ScheduleEvents)}]
:modals [{:modal d/DeleteModal :params {:modal-id :ds-modal} :callbacks {:onDelete do-delete-schedule}}]
:actions [{:title "Show Events" :action-class :info :symbol "cogs" :onClick show-schedule-events}
{:title "Delete Schedule" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :ds-modal)}])
|
[
{
"context": "license \"BSD 3-Clause License <https://github.com/FundingCircle/jackdaw/blob/master/LICENSE>\"}\n (:refer-clojure ",
"end": 129,
"score": 0.9963042736053467,
"start": 116,
"tag": "USERNAME",
"value": "FundingCircle"
},
{
"context": " \"fake\")\n (.put \"default.key.serde\" \"jackdaw.serdes.EdnSerde\")\n (.put \"default.value.se",
"end": 993,
"score": 0.6568344235420227,
"start": 992,
"tag": "KEY",
"value": "d"
},
{
"context": "(topology->test-driver topology)))\n\n\n;; FIXME (arrdem 2018-11-24):\n;; This is used by the test suite ",
"end": 3393,
"score": 0.7139238119125366,
"start": 3390,
"tag": "USERNAME",
"value": "dem"
}
] |
src/jackdaw/streams/mock.clj
|
dfbernal/jackdaw
| 0 |
(ns jackdaw.streams.mock
"Mocks for testing kafka streams."
{:license "BSD 3-Clause License <https://github.com/FundingCircle/jackdaw/blob/master/LICENSE>"}
(:refer-clojure :exclude [send])
(:require [jackdaw.streams :as js]
[jackdaw.streams.interop :as interop]
[jackdaw.data :as data])
(:import [org.apache.kafka.streams Topology TopologyTestDriver]
java.util.Properties
org.apache.kafka.common.header.internals.RecordHeaders
[org.apache.kafka.common.serialization Serde Serdes]
(org.apache.kafka.streams.test TestRecord)
(java.util UUID List)))
(set! *warn-on-reflection* false)
(defn topology->test-driver
"Given a kafka streams topology, return a topology test driver for it"
[topology]
(TopologyTestDriver.
^Topology topology
(doto (Properties.)
(.put "application.id" (str (UUID/randomUUID)))
(.put "bootstrap.servers" "fake")
(.put "default.key.serde" "jackdaw.serdes.EdnSerde")
(.put "default.value.serde" "jackdaw.serdes.EdnSerde"))))
(defn streams-builder->test-driver
"Given the jackdaw streams builder, return a builds the described topology
and returns a topology test driver for that topology"
[streams-builder]
(let [topology (.build (js/streams-builder* streams-builder))]
(topology->test-driver topology)))
(defn producer
"Returns a function which can be used to publish data to a topic for the
topology test driver"
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-input-topic (.createInputTopic test-driver
topic-name
(.serializer key-serde)
(.serializer value-serde))]
(fn produce!
([k v]
(.pipeInput test-input-topic (TestRecord. k v)))
([time-ms k v]
(let [record (TestRecord. k v (RecordHeaders.) ^Long time-ms)]
(.pipeRecordList test-input-topic (List/of record)))))))
(defn publish
([test-driver topic-config k v]
((producer test-driver topic-config) k v))
([test-driver topic-config time-ms k v]
((producer test-driver topic-config) time-ms k v)))
(defn consume
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-output-topic (.createOutputTopic test-driver
topic-name
(.deserializer key-serde)
(.deserializer value-serde))]
(when (not (.isEmpty test-output-topic))
(-> test-output-topic
(.readRecord)
(data/datafy)))))
(defn repeatedly-consume
[test-driver topic-config]
(take-while some? (repeatedly (partial consume test-driver topic-config))))
(defn get-keyvals
[test-driver topic-config]
(map #((juxt :key :value) %) (repeatedly-consume test-driver topic-config)))
(defn get-records
[test-driver topic-config]
(repeatedly-consume test-driver topic-config))
(defn build-driver [f]
(let [builder (interop/streams-builder)]
(f builder)
(streams-builder->test-driver builder)))
(defn build-topology-driver [f]
(let [topology (Topology.)]
(f topology)
(topology->test-driver topology)))
;; FIXME (arrdem 2018-11-24):
;; This is used by the test suite but has no bearing on anything else
(defn topic
"Helper to create a topic."
[topic-name]
{:topic-name topic-name
:key-serde (Serdes/Long)
:value-serde (Serdes/Long)})
|
80394
|
(ns jackdaw.streams.mock
"Mocks for testing kafka streams."
{:license "BSD 3-Clause License <https://github.com/FundingCircle/jackdaw/blob/master/LICENSE>"}
(:refer-clojure :exclude [send])
(:require [jackdaw.streams :as js]
[jackdaw.streams.interop :as interop]
[jackdaw.data :as data])
(:import [org.apache.kafka.streams Topology TopologyTestDriver]
java.util.Properties
org.apache.kafka.common.header.internals.RecordHeaders
[org.apache.kafka.common.serialization Serde Serdes]
(org.apache.kafka.streams.test TestRecord)
(java.util UUID List)))
(set! *warn-on-reflection* false)
(defn topology->test-driver
"Given a kafka streams topology, return a topology test driver for it"
[topology]
(TopologyTestDriver.
^Topology topology
(doto (Properties.)
(.put "application.id" (str (UUID/randomUUID)))
(.put "bootstrap.servers" "fake")
(.put "default.key.serde" "jack<KEY>aw.serdes.EdnSerde")
(.put "default.value.serde" "jackdaw.serdes.EdnSerde"))))
(defn streams-builder->test-driver
"Given the jackdaw streams builder, return a builds the described topology
and returns a topology test driver for that topology"
[streams-builder]
(let [topology (.build (js/streams-builder* streams-builder))]
(topology->test-driver topology)))
(defn producer
"Returns a function which can be used to publish data to a topic for the
topology test driver"
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-input-topic (.createInputTopic test-driver
topic-name
(.serializer key-serde)
(.serializer value-serde))]
(fn produce!
([k v]
(.pipeInput test-input-topic (TestRecord. k v)))
([time-ms k v]
(let [record (TestRecord. k v (RecordHeaders.) ^Long time-ms)]
(.pipeRecordList test-input-topic (List/of record)))))))
(defn publish
([test-driver topic-config k v]
((producer test-driver topic-config) k v))
([test-driver topic-config time-ms k v]
((producer test-driver topic-config) time-ms k v)))
(defn consume
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-output-topic (.createOutputTopic test-driver
topic-name
(.deserializer key-serde)
(.deserializer value-serde))]
(when (not (.isEmpty test-output-topic))
(-> test-output-topic
(.readRecord)
(data/datafy)))))
(defn repeatedly-consume
[test-driver topic-config]
(take-while some? (repeatedly (partial consume test-driver topic-config))))
(defn get-keyvals
[test-driver topic-config]
(map #((juxt :key :value) %) (repeatedly-consume test-driver topic-config)))
(defn get-records
[test-driver topic-config]
(repeatedly-consume test-driver topic-config))
(defn build-driver [f]
(let [builder (interop/streams-builder)]
(f builder)
(streams-builder->test-driver builder)))
(defn build-topology-driver [f]
(let [topology (Topology.)]
(f topology)
(topology->test-driver topology)))
;; FIXME (arrdem 2018-11-24):
;; This is used by the test suite but has no bearing on anything else
(defn topic
"Helper to create a topic."
[topic-name]
{:topic-name topic-name
:key-serde (Serdes/Long)
:value-serde (Serdes/Long)})
| true |
(ns jackdaw.streams.mock
"Mocks for testing kafka streams."
{:license "BSD 3-Clause License <https://github.com/FundingCircle/jackdaw/blob/master/LICENSE>"}
(:refer-clojure :exclude [send])
(:require [jackdaw.streams :as js]
[jackdaw.streams.interop :as interop]
[jackdaw.data :as data])
(:import [org.apache.kafka.streams Topology TopologyTestDriver]
java.util.Properties
org.apache.kafka.common.header.internals.RecordHeaders
[org.apache.kafka.common.serialization Serde Serdes]
(org.apache.kafka.streams.test TestRecord)
(java.util UUID List)))
(set! *warn-on-reflection* false)
(defn topology->test-driver
"Given a kafka streams topology, return a topology test driver for it"
[topology]
(TopologyTestDriver.
^Topology topology
(doto (Properties.)
(.put "application.id" (str (UUID/randomUUID)))
(.put "bootstrap.servers" "fake")
(.put "default.key.serde" "jackPI:KEY:<KEY>END_PIaw.serdes.EdnSerde")
(.put "default.value.serde" "jackdaw.serdes.EdnSerde"))))
(defn streams-builder->test-driver
"Given the jackdaw streams builder, return a builds the described topology
and returns a topology test driver for that topology"
[streams-builder]
(let [topology (.build (js/streams-builder* streams-builder))]
(topology->test-driver topology)))
(defn producer
"Returns a function which can be used to publish data to a topic for the
topology test driver"
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-input-topic (.createInputTopic test-driver
topic-name
(.serializer key-serde)
(.serializer value-serde))]
(fn produce!
([k v]
(.pipeInput test-input-topic (TestRecord. k v)))
([time-ms k v]
(let [record (TestRecord. k v (RecordHeaders.) ^Long time-ms)]
(.pipeRecordList test-input-topic (List/of record)))))))
(defn publish
([test-driver topic-config k v]
((producer test-driver topic-config) k v))
([test-driver topic-config time-ms k v]
((producer test-driver topic-config) time-ms k v)))
(defn consume
[test-driver
{:keys [topic-name
^Serde key-serde
^Serde value-serde]}]
(let [test-output-topic (.createOutputTopic test-driver
topic-name
(.deserializer key-serde)
(.deserializer value-serde))]
(when (not (.isEmpty test-output-topic))
(-> test-output-topic
(.readRecord)
(data/datafy)))))
(defn repeatedly-consume
[test-driver topic-config]
(take-while some? (repeatedly (partial consume test-driver topic-config))))
(defn get-keyvals
[test-driver topic-config]
(map #((juxt :key :value) %) (repeatedly-consume test-driver topic-config)))
(defn get-records
[test-driver topic-config]
(repeatedly-consume test-driver topic-config))
(defn build-driver [f]
(let [builder (interop/streams-builder)]
(f builder)
(streams-builder->test-driver builder)))
(defn build-topology-driver [f]
(let [topology (Topology.)]
(f topology)
(topology->test-driver topology)))
;; FIXME (arrdem 2018-11-24):
;; This is used by the test suite but has no bearing on anything else
(defn topic
"Helper to create a topic."
[topic-name]
{:topic-name topic-name
:key-serde (Serdes/Long)
:value-serde (Serdes/Long)})
|
[
{
"context": "f*ck made of clojure.\"\n :url \"https://github.com/p1scescom/crazyfuck\"\n :license {:name \"MIT License\"\n ",
"end": 132,
"score": 0.9995876550674438,
"start": 123,
"tag": "USERNAME",
"value": "p1scescom"
},
{
"context": "ses/MIT\"\n :year 2017\n :key \"mit\"}\n :dependencies [[org.clojure/clojure \"1.8.0\"]]",
"end": 275,
"score": 0.9250697493553162,
"start": 272,
"tag": "KEY",
"value": "mit"
}
] |
project.clj
|
p1scescom/crazyfuck
| 0 |
(defproject crazyfuck "0.1.0-SNAPSHOT"
:description "Crazyf*ck is Brainf*ck made of clojure."
:url "https://github.com/p1scescom/crazyfuck"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2017
:key "mit"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:jvm-opts ["-Xmx1G"]
:main crazyfuck.core )
|
69981
|
(defproject crazyfuck "0.1.0-SNAPSHOT"
:description "Crazyf*ck is Brainf*ck made of clojure."
:url "https://github.com/p1scescom/crazyfuck"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2017
:key "<KEY>"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:jvm-opts ["-Xmx1G"]
:main crazyfuck.core )
| true |
(defproject crazyfuck "0.1.0-SNAPSHOT"
:description "Crazyf*ck is Brainf*ck made of clojure."
:url "https://github.com/p1scescom/crazyfuck"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2017
:key "PI:KEY:<KEY>END_PI"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:jvm-opts ["-Xmx1G"]
:main crazyfuck.core )
|
[
{
"context": "dd some data\n(d/transact! conn [{:db/id -1 :name \"Bob\" :age 30}\n {:db/id -2 :name \"Sa",
"end": 985,
"score": 0.9997835755348206,
"start": 982,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ob\" :age 30}\n {:db/id -2 :name \"Sally\" :age 25}])\n\n;;; Maintain DB history.\n(def histor",
"end": 1038,
"score": 0.9995614290237427,
"start": 1033,
"tag": "NAME",
"value": "Sally"
}
] |
src/cljs/app/core.cljs
|
satrioaw/desa-app
| 0 |
(ns app.core
(:require [reagent.core :as reagent :refer [atom]]
[datascript.core :as d]
[cljs-uuid-utils.core :as uuid]
[app.helper :as h]))
(defn bind
([conn q]
(bind conn q (atom nil)))
([conn q state]
(let [k (uuid/make-random-uuid)]
(reset! state (d/q q @conn))
(d/listen! conn k (fn [tx-report]
(let [novelty (d/q q (:tx-data tx-report))]
(when (not-empty novelty) ;; Only update if query results actually changed
(reset! state (d/q q (:db-after tx-report)))))))
(set! (.-__key state) k)
state)))
(defn unbind
[conn state]
(d/unlisten! conn (.-__key state)))
;;; Creates a DataScript "connection" (really an atom with the current DB value)
(def conn (d/create-conn))
;;; Add some data
(d/transact! conn [{:db/id -1 :name "Bob" :age 30}
{:db/id -2 :name "Sally" :age 25}])
;;; Maintain DB history.
(def history (atom []))
(d/listen! conn :history (fn [tx-report] (swap! history conj tx-report)))
;;; Query to get name and age of peeps in the DB
(def q-peeps '[:find ?n ?a
:where
[?e :name ?n]
[?e :age ?a]])
;; Simple reagent component. Returns a function that performs render
(defn peeps-view
[]
(let [peeps (bind conn q-peeps)
temp (atom {:name "" :age ""})]
(fn []
[:div
[:h2 "Peeps!"]
[:ul
(map (fn [[n a]] [:li [:span (str "Name: " n " Age: " a)]]) @peeps)]
[:div
[:span "Name"][:input {:type "text"
:value (:name @temp)
:on-change #(swap! temp assoc-in [:name] (.. % -target -value))}]]
[:div
[:span "Age"][:input {:type "text"
:value (:age @temp)
:on-change #(swap! temp assoc-in [:age] (.. % -target -value))}]]
[:button
{:onClick (fn []
(d/transact! conn [{:db/id -1 :name (:name @temp) :age (js/parseInt (:age @temp))}])
(reset! temp {:name "" :age ""}))}
"Add Peep"]])))
;;; Query to find peeps whose age is less than 18
(def q-young '[:find ?n
:where
[?e :name ?n]
[?e :age ?a]
[(< ?a 18)]])
;;; Uses reagent/create-class to create a React component with lifecyle functions
(defn younguns-view
[]
(let [y (atom nil)]
(reagent/create-class
{
;; Subscribe to db transactions.
:component-will-mount
(fn [] (bind conn q-young y))
;; Unsubscribe from db transactions.
:component-will-unmount (fn [] (unbind conn y))
:render
(fn [_]
[:div
[:h2 "Young 'uns (under 18)"]
[:ul
(map (fn [[n]] [:li [:span n]]) @y)]])})))
;;; Some non-DB state
(def state (atom {:show-younguns false}))
;;; Uber component, contains/controls stuff and younguns.
(defn uber
[]
[:div
[:div [peeps-view]]
[:div {:style {:margin-top "20px"}}
[:input {:type "checkbox"
:name "younguns"
:onChange #(swap! state assoc-in [:show-younguns] (.. % -target -checked))}
"Show Young'uns"]]
(when (:show-younguns @state)
[:div [younguns-view]])])
(defn ^:export main []
(reagent/render-component (fn [] [uber]) (h/get-elem "app")))
|
12602
|
(ns app.core
(:require [reagent.core :as reagent :refer [atom]]
[datascript.core :as d]
[cljs-uuid-utils.core :as uuid]
[app.helper :as h]))
(defn bind
([conn q]
(bind conn q (atom nil)))
([conn q state]
(let [k (uuid/make-random-uuid)]
(reset! state (d/q q @conn))
(d/listen! conn k (fn [tx-report]
(let [novelty (d/q q (:tx-data tx-report))]
(when (not-empty novelty) ;; Only update if query results actually changed
(reset! state (d/q q (:db-after tx-report)))))))
(set! (.-__key state) k)
state)))
(defn unbind
[conn state]
(d/unlisten! conn (.-__key state)))
;;; Creates a DataScript "connection" (really an atom with the current DB value)
(def conn (d/create-conn))
;;; Add some data
(d/transact! conn [{:db/id -1 :name "<NAME>" :age 30}
{:db/id -2 :name "<NAME>" :age 25}])
;;; Maintain DB history.
(def history (atom []))
(d/listen! conn :history (fn [tx-report] (swap! history conj tx-report)))
;;; Query to get name and age of peeps in the DB
(def q-peeps '[:find ?n ?a
:where
[?e :name ?n]
[?e :age ?a]])
;; Simple reagent component. Returns a function that performs render
(defn peeps-view
[]
(let [peeps (bind conn q-peeps)
temp (atom {:name "" :age ""})]
(fn []
[:div
[:h2 "Peeps!"]
[:ul
(map (fn [[n a]] [:li [:span (str "Name: " n " Age: " a)]]) @peeps)]
[:div
[:span "Name"][:input {:type "text"
:value (:name @temp)
:on-change #(swap! temp assoc-in [:name] (.. % -target -value))}]]
[:div
[:span "Age"][:input {:type "text"
:value (:age @temp)
:on-change #(swap! temp assoc-in [:age] (.. % -target -value))}]]
[:button
{:onClick (fn []
(d/transact! conn [{:db/id -1 :name (:name @temp) :age (js/parseInt (:age @temp))}])
(reset! temp {:name "" :age ""}))}
"Add Peep"]])))
;;; Query to find peeps whose age is less than 18
(def q-young '[:find ?n
:where
[?e :name ?n]
[?e :age ?a]
[(< ?a 18)]])
;;; Uses reagent/create-class to create a React component with lifecyle functions
(defn younguns-view
[]
(let [y (atom nil)]
(reagent/create-class
{
;; Subscribe to db transactions.
:component-will-mount
(fn [] (bind conn q-young y))
;; Unsubscribe from db transactions.
:component-will-unmount (fn [] (unbind conn y))
:render
(fn [_]
[:div
[:h2 "Young 'uns (under 18)"]
[:ul
(map (fn [[n]] [:li [:span n]]) @y)]])})))
;;; Some non-DB state
(def state (atom {:show-younguns false}))
;;; Uber component, contains/controls stuff and younguns.
(defn uber
[]
[:div
[:div [peeps-view]]
[:div {:style {:margin-top "20px"}}
[:input {:type "checkbox"
:name "younguns"
:onChange #(swap! state assoc-in [:show-younguns] (.. % -target -checked))}
"Show Young'uns"]]
(when (:show-younguns @state)
[:div [younguns-view]])])
(defn ^:export main []
(reagent/render-component (fn [] [uber]) (h/get-elem "app")))
| true |
(ns app.core
(:require [reagent.core :as reagent :refer [atom]]
[datascript.core :as d]
[cljs-uuid-utils.core :as uuid]
[app.helper :as h]))
(defn bind
([conn q]
(bind conn q (atom nil)))
([conn q state]
(let [k (uuid/make-random-uuid)]
(reset! state (d/q q @conn))
(d/listen! conn k (fn [tx-report]
(let [novelty (d/q q (:tx-data tx-report))]
(when (not-empty novelty) ;; Only update if query results actually changed
(reset! state (d/q q (:db-after tx-report)))))))
(set! (.-__key state) k)
state)))
(defn unbind
[conn state]
(d/unlisten! conn (.-__key state)))
;;; Creates a DataScript "connection" (really an atom with the current DB value)
(def conn (d/create-conn))
;;; Add some data
(d/transact! conn [{:db/id -1 :name "PI:NAME:<NAME>END_PI" :age 30}
{:db/id -2 :name "PI:NAME:<NAME>END_PI" :age 25}])
;;; Maintain DB history.
(def history (atom []))
(d/listen! conn :history (fn [tx-report] (swap! history conj tx-report)))
;;; Query to get name and age of peeps in the DB
(def q-peeps '[:find ?n ?a
:where
[?e :name ?n]
[?e :age ?a]])
;; Simple reagent component. Returns a function that performs render
(defn peeps-view
[]
(let [peeps (bind conn q-peeps)
temp (atom {:name "" :age ""})]
(fn []
[:div
[:h2 "Peeps!"]
[:ul
(map (fn [[n a]] [:li [:span (str "Name: " n " Age: " a)]]) @peeps)]
[:div
[:span "Name"][:input {:type "text"
:value (:name @temp)
:on-change #(swap! temp assoc-in [:name] (.. % -target -value))}]]
[:div
[:span "Age"][:input {:type "text"
:value (:age @temp)
:on-change #(swap! temp assoc-in [:age] (.. % -target -value))}]]
[:button
{:onClick (fn []
(d/transact! conn [{:db/id -1 :name (:name @temp) :age (js/parseInt (:age @temp))}])
(reset! temp {:name "" :age ""}))}
"Add Peep"]])))
;;; Query to find peeps whose age is less than 18
(def q-young '[:find ?n
:where
[?e :name ?n]
[?e :age ?a]
[(< ?a 18)]])
;;; Uses reagent/create-class to create a React component with lifecyle functions
(defn younguns-view
[]
(let [y (atom nil)]
(reagent/create-class
{
;; Subscribe to db transactions.
:component-will-mount
(fn [] (bind conn q-young y))
;; Unsubscribe from db transactions.
:component-will-unmount (fn [] (unbind conn y))
:render
(fn [_]
[:div
[:h2 "Young 'uns (under 18)"]
[:ul
(map (fn [[n]] [:li [:span n]]) @y)]])})))
;;; Some non-DB state
(def state (atom {:show-younguns false}))
;;; Uber component, contains/controls stuff and younguns.
(defn uber
[]
[:div
[:div [peeps-view]]
[:div {:style {:margin-top "20px"}}
[:input {:type "checkbox"
:name "younguns"
:onChange #(swap! state assoc-in [:show-younguns] (.. % -target -checked))}
"Show Young'uns"]]
(when (:show-younguns @state)
[:div [younguns-view]])])
(defn ^:export main []
(reagent/render-component (fn [] [uber]) (h/get-elem "app")))
|
[
{
"context": "aging \"hash-term\" 1 nil)))\n (is (= '(\"oneres\" \"twores\") (do-twitter-search-with-paging \"hash-term\" 100 ",
"end": 1789,
"score": 0.8979690074920654,
"start": 1783,
"tag": "NAME",
"value": "twores"
},
{
"context": "-with-paging \"hash-term\" 100 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-w",
"end": 1866,
"score": 0.9964510798454285,
"start": 1860,
"tag": "NAME",
"value": "oneres"
},
{
"context": "ing \"hash-term\" 100 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-pagin",
"end": 1875,
"score": 0.9967949986457825,
"start": 1869,
"tag": "NAME",
"value": "twores"
},
{
"context": "-term\" 100 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-paging \"hash-t",
"end": 1884,
"score": 0.9963918924331665,
"start": 1878,
"tag": "NAME",
"value": "oneres"
},
{
"context": "0 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-paging \"hash-term\" 101 ",
"end": 1893,
"score": 0.9908773899078369,
"start": 1887,
"tag": "NAME",
"value": "twores"
},
{
"context": "-with-paging \"hash-term\" 101 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-w",
"end": 1970,
"score": 0.9929442405700684,
"start": 1964,
"tag": "NAME",
"value": "oneres"
},
{
"context": "ing \"hash-term\" 101 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-pagin",
"end": 1979,
"score": 0.9923497438430786,
"start": 1973,
"tag": "NAME",
"value": "twores"
},
{
"context": "-term\" 101 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-paging \"hash-t",
"end": 1988,
"score": 0.9923234581947327,
"start": 1982,
"tag": "NAME",
"value": "oneres"
},
{
"context": "1 nil)))\n (is (= '(\"oneres\" \"twores\" \"oneres\" \"twores\") (do-twitter-search-with-paging \"hash-term\" 200 ",
"end": 1997,
"score": 0.9767715930938721,
"start": 1991,
"tag": "NAME",
"value": "twores"
}
] |
test/twitter_hash_6d/search_test.clj
|
dpavkov/twitter-hash-6d
| 0 |
(ns twitter-hash-6d.search-test
(:require [clojure.test :refer :all]
[twitter-hash-6d.search :refer :all]))
(deftest test-extract-hashes
(is (= [] (extract-hashes []"search-term")))
(is (= [] (extract-hashes [{:entities {}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags []}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags [{:text "search-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}] "search-term")))
(is (= ["other-term" "third-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "third-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "Search-term"}]}}] "search-term"))))
(deftest test-tweets-this-turn
(is (= 54 (tweets-this-turn 54)))
(is (= 0 (tweets-this-turn -1)))
(is (= 100 (tweets-this-turn 107))))
(deftest test-do-twitter-search-with-paging
(with-redefs [do-twitter-search (fn [x y z] {:body {:statuses [{:id 123451234214}]}})
extract-hashes (fn [x y] '("oneres" "twores"))
is-newer-tweet (fn [x y] true)]
(is (= '() (do-twitter-search-with-paging "hash-term" 0 nil)))
(is (= '("oneres" "twores") (do-twitter-search-with-paging "hash-term" 1 nil)))
(is (= '("oneres" "twores") (do-twitter-search-with-paging "hash-term" 100 nil)))
(is (= '("oneres" "twores" "oneres" "twores") (do-twitter-search-with-paging "hash-term" 101 nil)))
(is (= '("oneres" "twores" "oneres" "twores") (do-twitter-search-with-paging "hash-term" 200 nil)))))
(deftest test-next-max-id
(is (= 77 (next-max-id [] 77)))
(is (= nil (next-max-id [] nil)))
(is (= 75 (next-max-id [{:id 76}] 77)))
(is (= 66 (next-max-id [{:id 76} {:id 67}] 77)))
(is (= 44 (next-max-id [{:id 45} {:id 55}] 77))))
(defn- parse-date [date]
(.toInstant (.parse (java.text.SimpleDateFormat. "ddMMyyyy HHmm ZZZZ") date)))
(deftest test-is-newer-tweet
(with-redefs [max-minutes-old 20]
(is (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0409 +0000")))
(is (not (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0410 +0000"))))))
|
75329
|
(ns twitter-hash-6d.search-test
(:require [clojure.test :refer :all]
[twitter-hash-6d.search :refer :all]))
(deftest test-extract-hashes
(is (= [] (extract-hashes []"search-term")))
(is (= [] (extract-hashes [{:entities {}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags []}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags [{:text "search-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}] "search-term")))
(is (= ["other-term" "third-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "third-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "Search-term"}]}}] "search-term"))))
(deftest test-tweets-this-turn
(is (= 54 (tweets-this-turn 54)))
(is (= 0 (tweets-this-turn -1)))
(is (= 100 (tweets-this-turn 107))))
(deftest test-do-twitter-search-with-paging
(with-redefs [do-twitter-search (fn [x y z] {:body {:statuses [{:id 123451234214}]}})
extract-hashes (fn [x y] '("oneres" "twores"))
is-newer-tweet (fn [x y] true)]
(is (= '() (do-twitter-search-with-paging "hash-term" 0 nil)))
(is (= '("oneres" "twores") (do-twitter-search-with-paging "hash-term" 1 nil)))
(is (= '("oneres" "<NAME>") (do-twitter-search-with-paging "hash-term" 100 nil)))
(is (= '("<NAME>" "<NAME>" "<NAME>" "<NAME>") (do-twitter-search-with-paging "hash-term" 101 nil)))
(is (= '("<NAME>" "<NAME>" "<NAME>" "<NAME>") (do-twitter-search-with-paging "hash-term" 200 nil)))))
(deftest test-next-max-id
(is (= 77 (next-max-id [] 77)))
(is (= nil (next-max-id [] nil)))
(is (= 75 (next-max-id [{:id 76}] 77)))
(is (= 66 (next-max-id [{:id 76} {:id 67}] 77)))
(is (= 44 (next-max-id [{:id 45} {:id 55}] 77))))
(defn- parse-date [date]
(.toInstant (.parse (java.text.SimpleDateFormat. "ddMMyyyy HHmm ZZZZ") date)))
(deftest test-is-newer-tweet
(with-redefs [max-minutes-old 20]
(is (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0409 +0000")))
(is (not (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0410 +0000"))))))
| true |
(ns twitter-hash-6d.search-test
(:require [clojure.test :refer :all]
[twitter-hash-6d.search :refer :all]))
(deftest test-extract-hashes
(is (= [] (extract-hashes []"search-term")))
(is (= [] (extract-hashes [{:entities {}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags []}}] "search-term")))
(is (= [] (extract-hashes [{:entities {:hashtags [{:text "search-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}] "search-term")))
(is (= ["other-term" "third-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "third-term"}]}}] "search-term")))
(is (= ["other-term"] (extract-hashes [{:entities {:hashtags [{:text "search-term"}
{:text "other-term"}]}}
{:entities {:hashtags [{:text "Search-term"}]}}] "search-term"))))
(deftest test-tweets-this-turn
(is (= 54 (tweets-this-turn 54)))
(is (= 0 (tweets-this-turn -1)))
(is (= 100 (tweets-this-turn 107))))
(deftest test-do-twitter-search-with-paging
(with-redefs [do-twitter-search (fn [x y z] {:body {:statuses [{:id 123451234214}]}})
extract-hashes (fn [x y] '("oneres" "twores"))
is-newer-tweet (fn [x y] true)]
(is (= '() (do-twitter-search-with-paging "hash-term" 0 nil)))
(is (= '("oneres" "twores") (do-twitter-search-with-paging "hash-term" 1 nil)))
(is (= '("oneres" "PI:NAME:<NAME>END_PI") (do-twitter-search-with-paging "hash-term" 100 nil)))
(is (= '("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (do-twitter-search-with-paging "hash-term" 101 nil)))
(is (= '("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (do-twitter-search-with-paging "hash-term" 200 nil)))))
(deftest test-next-max-id
(is (= 77 (next-max-id [] 77)))
(is (= nil (next-max-id [] nil)))
(is (= 75 (next-max-id [{:id 76}] 77)))
(is (= 66 (next-max-id [{:id 76} {:id 67}] 77)))
(is (= 44 (next-max-id [{:id 45} {:id 55}] 77))))
(defn- parse-date [date]
(.toInstant (.parse (java.text.SimpleDateFormat. "ddMMyyyy HHmm ZZZZ") date)))
(deftest test-is-newer-tweet
(with-redefs [max-minutes-old 20]
(is (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0409 +0000")))
(is (not (is-newer-tweet {:created_at "Fri Oct 23 03:49:28 +0000 2015"} (parse-date "23102015 0410 +0000"))))))
|
[
{
"context": "-----------------------\n;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.\n;;\n;; Th",
"end": 98,
"score": 0.8272398114204407,
"start": 97,
"tag": "NAME",
"value": "o"
},
{
"context": "iakObject]))\n\n(def ^{:private true} default-host \"127.0.0.1\")\n(def ^{:private true} default-port 8087)\n\n(defn",
"end": 1289,
"score": 0.9990221858024597,
"start": 1280,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] |
src/sumo/client.clj
|
michaelklishin/sumo
| 1 |
;; -------------------------------------------------------------------
;; Copyright (c) 2011 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 sumo.client
(:refer-clojure :exclude [get key pr])
(:use [sumo.serializers :only [serialize deserialize]]
[clojure.set :only [union]])
(:import [com.basho.riak.client.builders RiakObjectBuilder]
[com.basho.riak.pbc RiakClient]
[com.basho.riak.client.raw FetchMeta StoreMeta DeleteMeta RawClient]
[com.basho.riak.client.raw.pbc PBClientAdapter]
[com.basho.riak.client IRiakObject]))
(def ^{:private true} default-host "127.0.0.1")
(def ^{:private true} default-port 8087)
(defn- get-as-integer
[key container]
(if-let [i (key container)]
(Integer. i)))
(defn- fetch-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
notfound-ok (:notfound-ok options)
basic-quorum (:basic-quorum options)
head (:head options)]
(FetchMeta. r, pr, notfound-ok,
basic-quorum, head,
nil, nil, nil)))
(defn- store-options
[options]
(let [w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
return-body (:return-body options)]
(StoreMeta. w, dw, pw, return-body,
nil, nil)))
(defn- delete-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
rw (get-as-integer :rw options)
vclock (:vclock options)]
(DeleteMeta. r, pr, w, dw, pw, rw, vclock)))
(defn- riak-indexes-to-map
"Converts a seq of Riak Indexes into a hash of sets. The seq could
define two indexes named 'foo', one binary and one integer, so we
must be careful to add duplicates to the set rather than overriding
the first values."
[indexes]
(let [add-or-new-set (fn [prev val]
(if (nil? prev) val (union prev val)))
add-index (fn [map name val]
(update-in map [name] add-or-new-set val))]
(loop [index-seq indexes index-map {}]
(if (seq index-seq)
(let [index (first index-seq)
index-map (add-index index-map
(keyword (.getName (.getKey index)))
(set (.getValue index)))]
(recur (rest index-seq) index-map))
index-map))))
(defn- riak-object-to-map
"Turn an IRiakObject implementation into
a Clojure map"
[^IRiakObject riak-object]
(-> {}
(assoc :vector-clock (.getBytes (.getVClock riak-object)))
(assoc :content-type (.getContentType riak-object))
(assoc :vtag (.getVtag riak-object))
(assoc :last-modified (.getLastModified riak-object))
(assoc :metadata (into {} (.getMeta riak-object)))
(assoc :value (.getValue riak-object))
(assoc :indexes (riak-indexes-to-map
(concat (seq (.allBinIndexes riak-object))
(seq (.allIntIndexes riak-object)))))))
(defn- ^IRiakObject map-to-riak-object
"Construct a DefaultRiakObject from
a `bucket` `key` and `obj` map"
[bucket key obj]
(let [vclock (:vector-clock obj)
^RiakObjectBuilder riak-object (-> ^RiakObjectBuilder (RiakObjectBuilder/newBuilder bucket key)
(.withValue (:value obj))
(.withContentType (or (:content-type obj)
"application/json"))
(.withUsermeta (:metadata obj {})))]
(doseq [[index-name index-seq] (:indexes obj)]
(doseq [index-value index-seq]
(.addIndex riak-object (name index-name) index-value)))
(if vclock
(.build (.withValue riak-object vclock))
(.build riak-object))))
(defn connect
"Return a connection. With no arguments,
this returns a connection to localhost
at the default protocol buffers port"
([] (connect default-host
default-port))
([^String host ^long port]
(PBClientAdapter.
(RiakClient. host port))))
(defn ping
"Returns true or raises ConnectException"
[^RawClient client]
(let [result (.ping client)]
(if (nil? result) true result)))
(defn get-raw [^RawClient client bucket key & options]
(let [options (or (first options) {})
fetch-meta (fetch-options options)
results (.fetch client ^String bucket ^String key ^FetchMeta fetch-meta)]
(map riak-object-to-map results)))
(defn get [^RawClient client bucket key & options]
"Retrieve a lazy-seq of objects at `bucket` and `key`
Usage looks like:
(def results (sumo.client/get client \"bucket\" \"key\"))
(println (:value (first (results))))"
(let [options (or (first options) {})
results (get-raw client bucket key options)]
(map #(assoc % :value (deserialize %)) results)))
(defn put-raw [^RawClient client bucket key obj & options]
(let [options (or (first options) {})
riak-object (map-to-riak-object bucket key obj)
store-meta (store-options options)
results (.store client ^IRiakObject riak-object ^StoreMeta store-meta)]
(map riak-object-to-map results)))
(defn put [^RawClient client bucket key obj & options]
"Store an object into Riak.
Usage looks like:
(sumo.client/put client \"bucket\" \"key\" {:content-type \"text/plain\" :value \"hello!\"})"
(let [options (or (first options) {})
new-obj (assoc obj :value (serialize obj))
results (put-raw client bucket key new-obj options)]
(map #(assoc % :value (deserialize %)) results)))
(defn delete [^RawClient client bucket key & options]
(let [options (or (first options) {})
delete-meta (delete-options options)]
(.delete client ^String bucket ^String key ^DeleteMeta delete-meta))
true)
|
58327
|
;; -------------------------------------------------------------------
;; Copyright (c) 2011 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 sumo.client
(:refer-clojure :exclude [get key pr])
(:use [sumo.serializers :only [serialize deserialize]]
[clojure.set :only [union]])
(:import [com.basho.riak.client.builders RiakObjectBuilder]
[com.basho.riak.pbc RiakClient]
[com.basho.riak.client.raw FetchMeta StoreMeta DeleteMeta RawClient]
[com.basho.riak.client.raw.pbc PBClientAdapter]
[com.basho.riak.client IRiakObject]))
(def ^{:private true} default-host "127.0.0.1")
(def ^{:private true} default-port 8087)
(defn- get-as-integer
[key container]
(if-let [i (key container)]
(Integer. i)))
(defn- fetch-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
notfound-ok (:notfound-ok options)
basic-quorum (:basic-quorum options)
head (:head options)]
(FetchMeta. r, pr, notfound-ok,
basic-quorum, head,
nil, nil, nil)))
(defn- store-options
[options]
(let [w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
return-body (:return-body options)]
(StoreMeta. w, dw, pw, return-body,
nil, nil)))
(defn- delete-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
rw (get-as-integer :rw options)
vclock (:vclock options)]
(DeleteMeta. r, pr, w, dw, pw, rw, vclock)))
(defn- riak-indexes-to-map
"Converts a seq of Riak Indexes into a hash of sets. The seq could
define two indexes named 'foo', one binary and one integer, so we
must be careful to add duplicates to the set rather than overriding
the first values."
[indexes]
(let [add-or-new-set (fn [prev val]
(if (nil? prev) val (union prev val)))
add-index (fn [map name val]
(update-in map [name] add-or-new-set val))]
(loop [index-seq indexes index-map {}]
(if (seq index-seq)
(let [index (first index-seq)
index-map (add-index index-map
(keyword (.getName (.getKey index)))
(set (.getValue index)))]
(recur (rest index-seq) index-map))
index-map))))
(defn- riak-object-to-map
"Turn an IRiakObject implementation into
a Clojure map"
[^IRiakObject riak-object]
(-> {}
(assoc :vector-clock (.getBytes (.getVClock riak-object)))
(assoc :content-type (.getContentType riak-object))
(assoc :vtag (.getVtag riak-object))
(assoc :last-modified (.getLastModified riak-object))
(assoc :metadata (into {} (.getMeta riak-object)))
(assoc :value (.getValue riak-object))
(assoc :indexes (riak-indexes-to-map
(concat (seq (.allBinIndexes riak-object))
(seq (.allIntIndexes riak-object)))))))
(defn- ^IRiakObject map-to-riak-object
"Construct a DefaultRiakObject from
a `bucket` `key` and `obj` map"
[bucket key obj]
(let [vclock (:vector-clock obj)
^RiakObjectBuilder riak-object (-> ^RiakObjectBuilder (RiakObjectBuilder/newBuilder bucket key)
(.withValue (:value obj))
(.withContentType (or (:content-type obj)
"application/json"))
(.withUsermeta (:metadata obj {})))]
(doseq [[index-name index-seq] (:indexes obj)]
(doseq [index-value index-seq]
(.addIndex riak-object (name index-name) index-value)))
(if vclock
(.build (.withValue riak-object vclock))
(.build riak-object))))
(defn connect
"Return a connection. With no arguments,
this returns a connection to localhost
at the default protocol buffers port"
([] (connect default-host
default-port))
([^String host ^long port]
(PBClientAdapter.
(RiakClient. host port))))
(defn ping
"Returns true or raises ConnectException"
[^RawClient client]
(let [result (.ping client)]
(if (nil? result) true result)))
(defn get-raw [^RawClient client bucket key & options]
(let [options (or (first options) {})
fetch-meta (fetch-options options)
results (.fetch client ^String bucket ^String key ^FetchMeta fetch-meta)]
(map riak-object-to-map results)))
(defn get [^RawClient client bucket key & options]
"Retrieve a lazy-seq of objects at `bucket` and `key`
Usage looks like:
(def results (sumo.client/get client \"bucket\" \"key\"))
(println (:value (first (results))))"
(let [options (or (first options) {})
results (get-raw client bucket key options)]
(map #(assoc % :value (deserialize %)) results)))
(defn put-raw [^RawClient client bucket key obj & options]
(let [options (or (first options) {})
riak-object (map-to-riak-object bucket key obj)
store-meta (store-options options)
results (.store client ^IRiakObject riak-object ^StoreMeta store-meta)]
(map riak-object-to-map results)))
(defn put [^RawClient client bucket key obj & options]
"Store an object into Riak.
Usage looks like:
(sumo.client/put client \"bucket\" \"key\" {:content-type \"text/plain\" :value \"hello!\"})"
(let [options (or (first options) {})
new-obj (assoc obj :value (serialize obj))
results (put-raw client bucket key new-obj options)]
(map #(assoc % :value (deserialize %)) results)))
(defn delete [^RawClient client bucket key & options]
(let [options (or (first options) {})
delete-meta (delete-options options)]
(.delete client ^String bucket ^String key ^DeleteMeta delete-meta))
true)
| true |
;; -------------------------------------------------------------------
;; Copyright (c) 2011 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 sumo.client
(:refer-clojure :exclude [get key pr])
(:use [sumo.serializers :only [serialize deserialize]]
[clojure.set :only [union]])
(:import [com.basho.riak.client.builders RiakObjectBuilder]
[com.basho.riak.pbc RiakClient]
[com.basho.riak.client.raw FetchMeta StoreMeta DeleteMeta RawClient]
[com.basho.riak.client.raw.pbc PBClientAdapter]
[com.basho.riak.client IRiakObject]))
(def ^{:private true} default-host "127.0.0.1")
(def ^{:private true} default-port 8087)
(defn- get-as-integer
[key container]
(if-let [i (key container)]
(Integer. i)))
(defn- fetch-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
notfound-ok (:notfound-ok options)
basic-quorum (:basic-quorum options)
head (:head options)]
(FetchMeta. r, pr, notfound-ok,
basic-quorum, head,
nil, nil, nil)))
(defn- store-options
[options]
(let [w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
return-body (:return-body options)]
(StoreMeta. w, dw, pw, return-body,
nil, nil)))
(defn- delete-options
[options]
(let [r (get-as-integer :r options)
pr (get-as-integer :pr options)
w (get-as-integer :w options)
dw (get-as-integer :dw options)
pw (get-as-integer :pw options)
rw (get-as-integer :rw options)
vclock (:vclock options)]
(DeleteMeta. r, pr, w, dw, pw, rw, vclock)))
(defn- riak-indexes-to-map
"Converts a seq of Riak Indexes into a hash of sets. The seq could
define two indexes named 'foo', one binary and one integer, so we
must be careful to add duplicates to the set rather than overriding
the first values."
[indexes]
(let [add-or-new-set (fn [prev val]
(if (nil? prev) val (union prev val)))
add-index (fn [map name val]
(update-in map [name] add-or-new-set val))]
(loop [index-seq indexes index-map {}]
(if (seq index-seq)
(let [index (first index-seq)
index-map (add-index index-map
(keyword (.getName (.getKey index)))
(set (.getValue index)))]
(recur (rest index-seq) index-map))
index-map))))
(defn- riak-object-to-map
"Turn an IRiakObject implementation into
a Clojure map"
[^IRiakObject riak-object]
(-> {}
(assoc :vector-clock (.getBytes (.getVClock riak-object)))
(assoc :content-type (.getContentType riak-object))
(assoc :vtag (.getVtag riak-object))
(assoc :last-modified (.getLastModified riak-object))
(assoc :metadata (into {} (.getMeta riak-object)))
(assoc :value (.getValue riak-object))
(assoc :indexes (riak-indexes-to-map
(concat (seq (.allBinIndexes riak-object))
(seq (.allIntIndexes riak-object)))))))
(defn- ^IRiakObject map-to-riak-object
"Construct a DefaultRiakObject from
a `bucket` `key` and `obj` map"
[bucket key obj]
(let [vclock (:vector-clock obj)
^RiakObjectBuilder riak-object (-> ^RiakObjectBuilder (RiakObjectBuilder/newBuilder bucket key)
(.withValue (:value obj))
(.withContentType (or (:content-type obj)
"application/json"))
(.withUsermeta (:metadata obj {})))]
(doseq [[index-name index-seq] (:indexes obj)]
(doseq [index-value index-seq]
(.addIndex riak-object (name index-name) index-value)))
(if vclock
(.build (.withValue riak-object vclock))
(.build riak-object))))
(defn connect
"Return a connection. With no arguments,
this returns a connection to localhost
at the default protocol buffers port"
([] (connect default-host
default-port))
([^String host ^long port]
(PBClientAdapter.
(RiakClient. host port))))
(defn ping
"Returns true or raises ConnectException"
[^RawClient client]
(let [result (.ping client)]
(if (nil? result) true result)))
(defn get-raw [^RawClient client bucket key & options]
(let [options (or (first options) {})
fetch-meta (fetch-options options)
results (.fetch client ^String bucket ^String key ^FetchMeta fetch-meta)]
(map riak-object-to-map results)))
(defn get [^RawClient client bucket key & options]
"Retrieve a lazy-seq of objects at `bucket` and `key`
Usage looks like:
(def results (sumo.client/get client \"bucket\" \"key\"))
(println (:value (first (results))))"
(let [options (or (first options) {})
results (get-raw client bucket key options)]
(map #(assoc % :value (deserialize %)) results)))
(defn put-raw [^RawClient client bucket key obj & options]
(let [options (or (first options) {})
riak-object (map-to-riak-object bucket key obj)
store-meta (store-options options)
results (.store client ^IRiakObject riak-object ^StoreMeta store-meta)]
(map riak-object-to-map results)))
(defn put [^RawClient client bucket key obj & options]
"Store an object into Riak.
Usage looks like:
(sumo.client/put client \"bucket\" \"key\" {:content-type \"text/plain\" :value \"hello!\"})"
(let [options (or (first options) {})
new-obj (assoc obj :value (serialize obj))
results (put-raw client bucket key new-obj options)]
(map #(assoc % :value (deserialize %)) results)))
(defn delete [^RawClient client bucket key & options]
(let [options (or (first options) {})
delete-meta (delete-options options)]
(.delete client ^String bucket ^String key ^DeleteMeta delete-meta))
true)
|
[
{
"context": " :password \"PASSWORD\"}\n ",
"end": 1718,
"score": 0.999416172504425,
"start": 1710,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": " :password \"SECRET\"\n ",
"end": 1932,
"score": 0.9994210004806519,
"start": 1926,
"tag": "PASSWORD",
"value": "SECRET"
},
{
"context": " :password \"PASSWORD\"}\n {:co",
"end": 2292,
"score": 0.9993977546691895,
"start": 2284,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": " :password \"SECRET\"\n :val",
"end": 2473,
"score": 0.9994308352470398,
"start": 2467,
"tag": "PASSWORD",
"value": "SECRET"
},
{
"context": " :password \"PASSWORD\"}\n ",
"end": 2846,
"score": 0.9994227886199951,
"start": 2838,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": " :password \"PASSWORD\"}\n {",
"end": 3294,
"score": 0.9994211196899414,
"start": 3286,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] |
test/kintone_client/user_test.clj
|
toyokumo/kintone-clj
| 5 |
(ns kintone-client.user-test
(:require [clojure.core.async :refer [<!! chan put!]]
[clojure.test :refer :all]
[kintone-client.user :as user]
[kintone-client.test-helper :as h]
[kintone-client.types :as t]))
(deftest get-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {}}}
nil)
(<!! (user/get-users h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest add-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:name "first"
:password "PASSWORD"}
{:code "user2"
:name "second"
:password "SECRET"
:valid false
:description ""}]}}}
nil)
(<!! (user/add-users h/fake-conn [{:code "user1"
:name "first"
:password "PASSWORD"}
{:code "user2"
:name "second"
:password "SECRET"
:valid false
:description ""}])))))
(deftest update-user-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:password "PASSWORD"}
{:code "user2"
:name "second"
:valid false
:description ""}]}}}
nil)
(<!! (user/update-users h/fake-conn [{:code "user1"
:password "PASSWORD"}
{:code "user2"
:name "second"
:valid false
:description ""}])))))
(deftest delete-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["user1" "code"]}}}
nil)
(<!! (user/delete-users h/fake-conn ["user1" "code"])))))
(deftest update-user-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-user-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest get-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {}}}
nil)
(<!! (user/get-organizations h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:ids [1 10 20]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:ids [1 10 20]
:offset 2
:size 5}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "foo"]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:codes ["code1" "foo"]
:offset 2
:size 5})))))
(deftest add-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}]}}}
nil)
(<!! (user/add-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}])))))
(deftest update-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}]}}}
nil)
(<!! (user/update-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}])))))
(deftest delete-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "code2"]}}}
nil)
(<!! (user/delete-organizations h/fake-conn ["code1" "code2"])))))
(deftest update-org-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-organization-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest update-user-services
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/services.json"
:req {:params {:users [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}]}}}
nil)
(<!! (user/update-user-services h/fake-conn [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}])))))
(deftest get-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {}}}
nil)
(<!! (user/get-groups h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest get-user-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/organizations.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-organizations h/fake-conn "user1")))))
(deftest get-user-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/groups.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-groups h/fake-conn "user1")))))
(deftest get-organization-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {:offset 10 :size 5})))))
(deftest get-group-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {:offset 10 :size 5})))))
(deftest get-all-users
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))))
(deftest get-all-organizations
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:organizations []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:organizations [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))))
(deftest get-all-groups
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:groups []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:groups [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))))
(deftest get-all-organization-users
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:userTitles []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:userTitles [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count))))))
(deftest get-all-group-users
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count))))))
|
100156
|
(ns kintone-client.user-test
(:require [clojure.core.async :refer [<!! chan put!]]
[clojure.test :refer :all]
[kintone-client.user :as user]
[kintone-client.test-helper :as h]
[kintone-client.types :as t]))
(deftest get-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {}}}
nil)
(<!! (user/get-users h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest add-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:name "first"
:password "<PASSWORD>"}
{:code "user2"
:name "second"
:password "<PASSWORD>"
:valid false
:description ""}]}}}
nil)
(<!! (user/add-users h/fake-conn [{:code "user1"
:name "first"
:password "<PASSWORD>"}
{:code "user2"
:name "second"
:password "<PASSWORD>"
:valid false
:description ""}])))))
(deftest update-user-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:password "<PASSWORD>"}
{:code "user2"
:name "second"
:valid false
:description ""}]}}}
nil)
(<!! (user/update-users h/fake-conn [{:code "user1"
:password "<PASSWORD>"}
{:code "user2"
:name "second"
:valid false
:description ""}])))))
(deftest delete-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["user1" "code"]}}}
nil)
(<!! (user/delete-users h/fake-conn ["user1" "code"])))))
(deftest update-user-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-user-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest get-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {}}}
nil)
(<!! (user/get-organizations h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:ids [1 10 20]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:ids [1 10 20]
:offset 2
:size 5}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "foo"]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:codes ["code1" "foo"]
:offset 2
:size 5})))))
(deftest add-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}]}}}
nil)
(<!! (user/add-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}])))))
(deftest update-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}]}}}
nil)
(<!! (user/update-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}])))))
(deftest delete-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "code2"]}}}
nil)
(<!! (user/delete-organizations h/fake-conn ["code1" "code2"])))))
(deftest update-org-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-organization-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest update-user-services
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/services.json"
:req {:params {:users [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}]}}}
nil)
(<!! (user/update-user-services h/fake-conn [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}])))))
(deftest get-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {}}}
nil)
(<!! (user/get-groups h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest get-user-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/organizations.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-organizations h/fake-conn "user1")))))
(deftest get-user-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/groups.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-groups h/fake-conn "user1")))))
(deftest get-organization-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {:offset 10 :size 5})))))
(deftest get-group-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {:offset 10 :size 5})))))
(deftest get-all-users
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))))
(deftest get-all-organizations
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:organizations []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:organizations [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))))
(deftest get-all-groups
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:groups []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:groups [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))))
(deftest get-all-organization-users
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:userTitles []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:userTitles [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count))))))
(deftest get-all-group-users
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count))))))
| true |
(ns kintone-client.user-test
(:require [clojure.core.async :refer [<!! chan put!]]
[clojure.test :refer :all]
[kintone-client.user :as user]
[kintone-client.test-helper :as h]
[kintone-client.types :as t]))
(deftest get-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {}}}
nil)
(<!! (user/get-users h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-users h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest add-users-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:name "first"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
{:code "user2"
:name "second"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:valid false
:description ""}]}}}
nil)
(<!! (user/add-users h/fake-conn [{:code "user1"
:name "first"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
{:code "user2"
:name "second"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:valid false
:description ""}])))))
(deftest update-user-test
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:users [{:code "user1"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
{:code "user2"
:name "second"
:valid false
:description ""}]}}}
nil)
(<!! (user/update-users h/fake-conn [{:code "user1"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
{:code "user2"
:name "second"
:valid false
:description ""}])))))
(deftest delete-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users.json"
:req {:params {:codes ["user1" "code"]}}}
nil)
(<!! (user/delete-users h/fake-conn ["user1" "code"])))))
(deftest update-user-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-user-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest get-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {}}}
nil)
(<!! (user/get-organizations h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:ids [1 10 20]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:ids [1 10 20]
:offset 2
:size 5}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "foo"]
:offset 2
:size 5}}}
nil)
(<!! (user/get-organizations h/fake-conn {:codes ["code1" "foo"]
:offset 2
:size 5})))))
(deftest add-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}]}}}
nil)
(<!! (user/add-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:name "abc"}])))))
(deftest update-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:organizations [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}]}}}
nil)
(<!! (user/update-organizations h/fake-conn [{:code "org1"
:name "ORG-A"}
{:code "new"
:name "new-organization"
:parentCode "org1"
:description ""}
{:code "ABC"
:description "abc"}])))))
(deftest delete-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations.json"
:req {:params {:codes ["code1" "code2"]}}}
nil)
(<!! (user/delete-organizations h/fake-conn ["code1" "code2"])))))
(deftest update-org-codes
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organizations/codes.json"
:req {:params {:codes [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}]}}}
nil)
(<!! (user/update-organization-codes h/fake-conn [{:currentCode "old"
:newCode "new"}
{:currentCode "code1"
:newCode "code2"}])))))
(deftest update-user-services
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/users/services.json"
:req {:params {:users [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}]}}}
nil)
(<!! (user/update-user-services h/fake-conn [{:code "user1"
:services ["kintone"
"garoon"
"office"
"mailwise"
"secure_access"]}
{:code "user2"
:services []}
{:code "user3"
:services ["kintone"]}])))))
(deftest get-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {}}}
nil)
(<!! (user/get-groups h/fake-conn {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:ids [1 2 3]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:ids [1 2 3]
:offset 2
:size 10}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/groups.json"
:req {:params {:codes ["a" "b"]
:offset 2
:size 10}}}
nil)
(<!! (user/get-groups h/fake-conn {:codes ["a" "b"]
:offset 2
:size 10})))))
(deftest get-user-organizations
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/organizations.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-organizations h/fake-conn "user1")))))
(deftest get-user-groups
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/user/groups.json"
:req {:params {:code "user1"}}}
nil)
(<!! (user/get-user-groups h/fake-conn "user1")))))
(deftest get-organization-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/organization/users.json"
:req {:params {:code "org1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-organization-users h/fake-conn "org1" {:offset 10 :size 5})))))
(deftest get-group-users
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {}))))
(is (= (t/->KintoneResponse {:url "https://test.kintone.com/v1/group/users.json"
:req {:params {:code "group1"
:offset 10
:size 5}}}
nil)
(<!! (user/get-group-users h/fake-conn "group1" {:offset 10 :size 5})))))
(deftest get-all-users
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:users [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:users [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:users [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:users [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-users h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-users
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-users h/fake-conn {}))
:res
:users
count)))))))
(deftest get-all-organizations
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:organizations [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:organizations [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:organizations [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:organizations [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-organizations h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:organizations []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organizations
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:organizations (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:organizations [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organizations h/fake-conn {}))
:res
:organizations
count)))))))
(deftest get-all-groups
(testing "query by user code"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 100))}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:codes (map str (range 101))})))))))
(testing "query by user id"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1} {:id 2}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 100)}))))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse {:groups [{:id 1} {:id 2}]}
nil))
2 (put! c (t/->KintoneResponse {:groups [{:id 3}]}
nil))
3 (put! c (t/->KintoneResponse {:groups [{:id 4}]}
nil)))
c))]
(is (= (t/->KintoneResponse {:groups [{:id 1}
{:id 2}
{:id 3}]} nil)
(<!! (user/get-all-groups h/fake-conn {:ids (range 101)})))))))
(testing "no query"
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:groups []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-groups
(fn [conn {:keys [code]}]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:groups (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:groups [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-groups h/fake-conn {}))
:res
:groups
count)))))))
(deftest get-all-organization-users
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:userTitles []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-organization-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:userTitles (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:userTitles [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-organization-users h/fake-conn "code"))
:res
:userTitles
count))))))
(deftest get-all-group-users
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(case @ncall
1 (put! c (t/->KintoneResponse
{:users (map #(assoc {} :id %) (range 100))}
nil))
2 (put! c (t/->KintoneResponse {:users []}
nil)))
c))]
(is (= 100
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count)))))
(let [ncall (atom 0)]
(with-redefs [user/get-group-users
(fn [conn code opts]
(let [c (chan)]
(swap! ncall inc)
(if (< @ncall 3)
(put! c (t/->KintoneResponse
{:users (map #(assoc {} :id (+ (* 100 @ncall) %))
(range 100))}
nil))
(put! c (t/->KintoneResponse {:users [{:id 1000} {:id 1500}]}
nil)))
c))]
(is (= 202
(-> (<!! (user/get-all-group-users h/fake-conn "code"))
:res
:users
count))))))
|
[
{
"context": "; Copyright (c) 2015 Designed.ly, Marcin Bilski\n; The use and distribution terms for this softwa",
"end": 48,
"score": 0.9997312426567078,
"start": 35,
"tag": "NAME",
"value": "Marcin Bilski"
}
] |
banking-web/resources/public/js/compiled/out/reforms/validation.cljs
|
Divina10/banking
| 0 |
; Copyright (c) 2015 Designed.ly, Marcin Bilski
; The use and distribution terms for this software are covered by the
; Eclipse Public License 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 reforms.validation
"Validation functionality."
(:require [reforms.core :as f]
[reforms.binding.core :as binding]
[clojure.string :as str])
(:refer-clojure :exclude [time]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation
(declare valid?)
(defn find-validation-error
[kork errors]
(when (not-empty errors)
(->>
errors
(filter #((:korks %) kork))
first)))
(defn sequable?
[x]
(try
(seq x)
true
(catch js/Error _ ; Slow.
false)))
(defn present?
[x]
(when (and x
(not (and (string? x) (str/blank? x)))
(not (and (sequable? x) (empty? x))))
true))
(def ^:dynamic *validation-errors* nil)
(defn validating-field
[field-fn & args]
(assert (not-any? #{:validation-error-fn} args) "The validating version uses :validation-error-fn internally.")
(apply field-fn (conj (vec args)
:valid? (fn [korks] (valid? korks *validation-errors*))
:validation-error-fn (fn [korks] (when-let [err (find-validation-error korks *validation-errors*)]
(:error-message err))))))
(defn validating-fields-fn
"Used by [reforms.validation/validating-fields] macro."
[validation-errors & fields]
(binding [*validation-errors* validation-errors]
(doall
(for [field fields]
(field)))))
(defn validation-error
"Returns a validation error for a key sequence.
Arguments:
- korks - key sequence the error refers to
- error-message - string containing the error message"
[korks error-message]
{:korks (into #{} (seq korks))
:error-message error-message})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateless methods
(defn validate
"Validates data and returns a list of errors.
Arguments:
- data - data to validate
- validators - seq of validators to use"
[data & validators]
(-> (keep #(% data) validators)
flatten
distinct
doall))
(defn valid?
"Returns true if there are no errors.
Arguments:
- errors - result of validation
- kork - (optional) match against this key seq"
([errors]
(or (nil? errors) (empty? errors)))
([kork errors]
(nil? (find-validation-error kork errors))))
(def invalid?
"Complement of [[valid?]]"
(complement valid?))
(defn render-errors
"Renders errors as unordered list.
Arguments:
- errors - results of validation"
[errors]
(when (not-empty errors)
[:ul {:class (str "error validation" (when (seq errors) " validation-failed"))}
(for [failure errors]
[:li (:error-message failure)])]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Validators
(defn equal
"Equality validator.
Example:
(equal [:user :password1] [:user :password2] \"Passwords do not match\"]"
[korks1 korks2 error-message]
(fn [data]
(let [lhs (or (get-in data korks1) "")
rhs (or (get-in data korks2) "")]
(when-not (= lhs rhs)
(validation-error [korks2] ; Show error only next to the second control.
error-message)))))
(defn present
"Presence validator.
Example:
(present [:user :login] \"Enter the login\"]"
[korks error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (present? x)
(validation-error [korks] error-message)))))
(defn matches
"Regex validator.
Example:
(matches [:user :email] #\"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$\" \"Invalid email address\"]"
[korks re error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (re-matches re x)
(validation-error [korks] error-message)))))
(defn is-true
"Predicate-based validator.
Example:
(is-true [:user :email] #(nil? (find-by-email %)) \"Email already exists\"]"
[korks f error-message]
(fn [data]
(when-not (f (get-in data korks))
(validation-error [korks] error-message))))
(defn force-error
"Generates an error. Useful for errors not coming from data but from external sources such as Ajax or RPC.
Example:
(force-error [:server-error] \"Problem connecting to the REST API server\")"
[korks error-message]
(fn [_]
(validation-error [korks] error-message)))
(defn no-error
"Generates a 'no error' placeholder."
[]
(fn [_]
nil))
(defn all
"Groups validators using 'and' boolean logic."
[& validators]
(fn [data]
(apply validate data validators)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateful methods
(defn validate!
"Validates data and saves the result. **A stateful method.**
Arguments:
- cursor - the data to validate
- ui-state-cursor - this is where validation result will be stored
- validators - a seq of validators"
[cursor ui-state-cursor & validators]
(let [validation-errors (apply validate (binding/deref cursor) validators)]
(binding/reset! ui-state-cursor [:validation-errors] validation-errors)
(valid? validation-errors)))
(defn validation-errors
"Returns validation errors saved by [[validate!]] into ui-state-cursor."
[ui-state-cursor]
(binding/get-in ui-state-cursor [:validation-errors]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Form helpers
(defn html5-input
"Wrapper for [[reforms.core/html5-input]] adding support for validation."
[& args]
(apply validating-field f/html5-input args))
(defn password
"Wrapper for [[reforms.core/password]] adding support for validation."
[& args]
(apply validating-field f/password args))
(defn text
"Wrapper for [[reforms.core/text]] adding support for validation."
[& args]
(apply validating-field f/text args))
(defn textarea
"Wrapper for [[reforms.core/textarea]] adding support for validation."
[& args]
(apply validating-field f/textarea args))
(defn checkbox
"Wrapper for [[reforms.core/checkbox]] adding support for validation."
[& args]
(apply validating-field f/checkbox args))
(defn select
"Wrapper for [[reforms.core/select]] adding support for validation."
[& args]
(apply validating-field f/select args))
(defn button
"Wrapper for [[reforms.core/button]] adding support for validation."
[& args]
(apply validating-field f/button args))
(defn button-primary
"Wrapper for [[reforms.core/button-primary]] adding support for validation."
[& args]
(apply validating-field f/button-primary args))
(defn button-default
"Wrapper for [[reforms.core/button-default]] adding support for validation."
[& args]
(apply validating-field f/button-default args))
(defn datetime
"Wrapper for [[reforms.core/datetime]] adding support for validation."
[& args]
(apply validating-field f/datetime args))
(defn datetime-local
"Wrapper for [[reforms.core/datetime-local]] adding support for validation."
[& args]
(apply validating-field f/datetime-local args))
(defn date
"Wrapper for [[reforms.core/date]] adding support for validation."
[& args]
(apply validating-field f/date args))
(defn month
"Wrapper for [[reforms.core/month]] adding support for validation."
[& args]
(apply validating-field f/month args))
(defn time
"Wrapper for [[reforms.core/time]] adding support for validation."
[& args]
(apply validating-field f/time args))
(defn week
"Wrapper for [[reforms.core/week]] adding support for validation."
[& args]
(apply validating-field f/week args))
(defn number
"Wrapper for [[reforms.core/number]] adding support for validation."
[& args]
(apply validating-field f/number args))
(defn email
"Wrapper for [[reforms.core/email]] adding support for validation."
[& args]
(apply validating-field f/email args))
(defn url
"Wrapper for [[reforms.core/url]] adding support for validation."
[& args]
(apply validating-field f/url args))
(defn search
"Wrapper for [[reforms.core/search]] adding support for validation."
[& args]
(apply validating-field f/search args))
(defn tel
"Wrapper for [[reforms.core/tel]] adding support for validation."
[& args]
(apply validating-field f/tel args))
(defn color
"Wrapper for [[reforms.core/color]] adding support for validation."
[& args]
(apply validating-field f/color args))
(defn error-alert
"Renders errors for specified key seqs.
Example:
(error-alert [:user :name] [:my-custom-error])"
[& korks]
(render-errors (keep (fn [kork]
(when-let [err (find-validation-error kork *validation-errors*)]
err)) korks)))
|
120606
|
; Copyright (c) 2015 Designed.ly, <NAME>
; The use and distribution terms for this software are covered by the
; Eclipse Public License 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 reforms.validation
"Validation functionality."
(:require [reforms.core :as f]
[reforms.binding.core :as binding]
[clojure.string :as str])
(:refer-clojure :exclude [time]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation
(declare valid?)
(defn find-validation-error
[kork errors]
(when (not-empty errors)
(->>
errors
(filter #((:korks %) kork))
first)))
(defn sequable?
[x]
(try
(seq x)
true
(catch js/Error _ ; Slow.
false)))
(defn present?
[x]
(when (and x
(not (and (string? x) (str/blank? x)))
(not (and (sequable? x) (empty? x))))
true))
(def ^:dynamic *validation-errors* nil)
(defn validating-field
[field-fn & args]
(assert (not-any? #{:validation-error-fn} args) "The validating version uses :validation-error-fn internally.")
(apply field-fn (conj (vec args)
:valid? (fn [korks] (valid? korks *validation-errors*))
:validation-error-fn (fn [korks] (when-let [err (find-validation-error korks *validation-errors*)]
(:error-message err))))))
(defn validating-fields-fn
"Used by [reforms.validation/validating-fields] macro."
[validation-errors & fields]
(binding [*validation-errors* validation-errors]
(doall
(for [field fields]
(field)))))
(defn validation-error
"Returns a validation error for a key sequence.
Arguments:
- korks - key sequence the error refers to
- error-message - string containing the error message"
[korks error-message]
{:korks (into #{} (seq korks))
:error-message error-message})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateless methods
(defn validate
"Validates data and returns a list of errors.
Arguments:
- data - data to validate
- validators - seq of validators to use"
[data & validators]
(-> (keep #(% data) validators)
flatten
distinct
doall))
(defn valid?
"Returns true if there are no errors.
Arguments:
- errors - result of validation
- kork - (optional) match against this key seq"
([errors]
(or (nil? errors) (empty? errors)))
([kork errors]
(nil? (find-validation-error kork errors))))
(def invalid?
"Complement of [[valid?]]"
(complement valid?))
(defn render-errors
"Renders errors as unordered list.
Arguments:
- errors - results of validation"
[errors]
(when (not-empty errors)
[:ul {:class (str "error validation" (when (seq errors) " validation-failed"))}
(for [failure errors]
[:li (:error-message failure)])]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Validators
(defn equal
"Equality validator.
Example:
(equal [:user :password1] [:user :password2] \"Passwords do not match\"]"
[korks1 korks2 error-message]
(fn [data]
(let [lhs (or (get-in data korks1) "")
rhs (or (get-in data korks2) "")]
(when-not (= lhs rhs)
(validation-error [korks2] ; Show error only next to the second control.
error-message)))))
(defn present
"Presence validator.
Example:
(present [:user :login] \"Enter the login\"]"
[korks error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (present? x)
(validation-error [korks] error-message)))))
(defn matches
"Regex validator.
Example:
(matches [:user :email] #\"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$\" \"Invalid email address\"]"
[korks re error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (re-matches re x)
(validation-error [korks] error-message)))))
(defn is-true
"Predicate-based validator.
Example:
(is-true [:user :email] #(nil? (find-by-email %)) \"Email already exists\"]"
[korks f error-message]
(fn [data]
(when-not (f (get-in data korks))
(validation-error [korks] error-message))))
(defn force-error
"Generates an error. Useful for errors not coming from data but from external sources such as Ajax or RPC.
Example:
(force-error [:server-error] \"Problem connecting to the REST API server\")"
[korks error-message]
(fn [_]
(validation-error [korks] error-message)))
(defn no-error
"Generates a 'no error' placeholder."
[]
(fn [_]
nil))
(defn all
"Groups validators using 'and' boolean logic."
[& validators]
(fn [data]
(apply validate data validators)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateful methods
(defn validate!
"Validates data and saves the result. **A stateful method.**
Arguments:
- cursor - the data to validate
- ui-state-cursor - this is where validation result will be stored
- validators - a seq of validators"
[cursor ui-state-cursor & validators]
(let [validation-errors (apply validate (binding/deref cursor) validators)]
(binding/reset! ui-state-cursor [:validation-errors] validation-errors)
(valid? validation-errors)))
(defn validation-errors
"Returns validation errors saved by [[validate!]] into ui-state-cursor."
[ui-state-cursor]
(binding/get-in ui-state-cursor [:validation-errors]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Form helpers
(defn html5-input
"Wrapper for [[reforms.core/html5-input]] adding support for validation."
[& args]
(apply validating-field f/html5-input args))
(defn password
"Wrapper for [[reforms.core/password]] adding support for validation."
[& args]
(apply validating-field f/password args))
(defn text
"Wrapper for [[reforms.core/text]] adding support for validation."
[& args]
(apply validating-field f/text args))
(defn textarea
"Wrapper for [[reforms.core/textarea]] adding support for validation."
[& args]
(apply validating-field f/textarea args))
(defn checkbox
"Wrapper for [[reforms.core/checkbox]] adding support for validation."
[& args]
(apply validating-field f/checkbox args))
(defn select
"Wrapper for [[reforms.core/select]] adding support for validation."
[& args]
(apply validating-field f/select args))
(defn button
"Wrapper for [[reforms.core/button]] adding support for validation."
[& args]
(apply validating-field f/button args))
(defn button-primary
"Wrapper for [[reforms.core/button-primary]] adding support for validation."
[& args]
(apply validating-field f/button-primary args))
(defn button-default
"Wrapper for [[reforms.core/button-default]] adding support for validation."
[& args]
(apply validating-field f/button-default args))
(defn datetime
"Wrapper for [[reforms.core/datetime]] adding support for validation."
[& args]
(apply validating-field f/datetime args))
(defn datetime-local
"Wrapper for [[reforms.core/datetime-local]] adding support for validation."
[& args]
(apply validating-field f/datetime-local args))
(defn date
"Wrapper for [[reforms.core/date]] adding support for validation."
[& args]
(apply validating-field f/date args))
(defn month
"Wrapper for [[reforms.core/month]] adding support for validation."
[& args]
(apply validating-field f/month args))
(defn time
"Wrapper for [[reforms.core/time]] adding support for validation."
[& args]
(apply validating-field f/time args))
(defn week
"Wrapper for [[reforms.core/week]] adding support for validation."
[& args]
(apply validating-field f/week args))
(defn number
"Wrapper for [[reforms.core/number]] adding support for validation."
[& args]
(apply validating-field f/number args))
(defn email
"Wrapper for [[reforms.core/email]] adding support for validation."
[& args]
(apply validating-field f/email args))
(defn url
"Wrapper for [[reforms.core/url]] adding support for validation."
[& args]
(apply validating-field f/url args))
(defn search
"Wrapper for [[reforms.core/search]] adding support for validation."
[& args]
(apply validating-field f/search args))
(defn tel
"Wrapper for [[reforms.core/tel]] adding support for validation."
[& args]
(apply validating-field f/tel args))
(defn color
"Wrapper for [[reforms.core/color]] adding support for validation."
[& args]
(apply validating-field f/color args))
(defn error-alert
"Renders errors for specified key seqs.
Example:
(error-alert [:user :name] [:my-custom-error])"
[& korks]
(render-errors (keep (fn [kork]
(when-let [err (find-validation-error kork *validation-errors*)]
err)) korks)))
| true |
; Copyright (c) 2015 Designed.ly, PI:NAME:<NAME>END_PI
; The use and distribution terms for this software are covered by the
; Eclipse Public License 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 reforms.validation
"Validation functionality."
(:require [reforms.core :as f]
[reforms.binding.core :as binding]
[clojure.string :as str])
(:refer-clojure :exclude [time]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation
(declare valid?)
(defn find-validation-error
[kork errors]
(when (not-empty errors)
(->>
errors
(filter #((:korks %) kork))
first)))
(defn sequable?
[x]
(try
(seq x)
true
(catch js/Error _ ; Slow.
false)))
(defn present?
[x]
(when (and x
(not (and (string? x) (str/blank? x)))
(not (and (sequable? x) (empty? x))))
true))
(def ^:dynamic *validation-errors* nil)
(defn validating-field
[field-fn & args]
(assert (not-any? #{:validation-error-fn} args) "The validating version uses :validation-error-fn internally.")
(apply field-fn (conj (vec args)
:valid? (fn [korks] (valid? korks *validation-errors*))
:validation-error-fn (fn [korks] (when-let [err (find-validation-error korks *validation-errors*)]
(:error-message err))))))
(defn validating-fields-fn
"Used by [reforms.validation/validating-fields] macro."
[validation-errors & fields]
(binding [*validation-errors* validation-errors]
(doall
(for [field fields]
(field)))))
(defn validation-error
"Returns a validation error for a key sequence.
Arguments:
- korks - key sequence the error refers to
- error-message - string containing the error message"
[korks error-message]
{:korks (into #{} (seq korks))
:error-message error-message})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateless methods
(defn validate
"Validates data and returns a list of errors.
Arguments:
- data - data to validate
- validators - seq of validators to use"
[data & validators]
(-> (keep #(% data) validators)
flatten
distinct
doall))
(defn valid?
"Returns true if there are no errors.
Arguments:
- errors - result of validation
- kork - (optional) match against this key seq"
([errors]
(or (nil? errors) (empty? errors)))
([kork errors]
(nil? (find-validation-error kork errors))))
(def invalid?
"Complement of [[valid?]]"
(complement valid?))
(defn render-errors
"Renders errors as unordered list.
Arguments:
- errors - results of validation"
[errors]
(when (not-empty errors)
[:ul {:class (str "error validation" (when (seq errors) " validation-failed"))}
(for [failure errors]
[:li (:error-message failure)])]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Validators
(defn equal
"Equality validator.
Example:
(equal [:user :password1] [:user :password2] \"Passwords do not match\"]"
[korks1 korks2 error-message]
(fn [data]
(let [lhs (or (get-in data korks1) "")
rhs (or (get-in data korks2) "")]
(when-not (= lhs rhs)
(validation-error [korks2] ; Show error only next to the second control.
error-message)))))
(defn present
"Presence validator.
Example:
(present [:user :login] \"Enter the login\"]"
[korks error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (present? x)
(validation-error [korks] error-message)))))
(defn matches
"Regex validator.
Example:
(matches [:user :email] #\"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$\" \"Invalid email address\"]"
[korks re error-message]
(fn [data]
(let [x (get-in data korks)]
(when-not (re-matches re x)
(validation-error [korks] error-message)))))
(defn is-true
"Predicate-based validator.
Example:
(is-true [:user :email] #(nil? (find-by-email %)) \"Email already exists\"]"
[korks f error-message]
(fn [data]
(when-not (f (get-in data korks))
(validation-error [korks] error-message))))
(defn force-error
"Generates an error. Useful for errors not coming from data but from external sources such as Ajax or RPC.
Example:
(force-error [:server-error] \"Problem connecting to the REST API server\")"
[korks error-message]
(fn [_]
(validation-error [korks] error-message)))
(defn no-error
"Generates a 'no error' placeholder."
[]
(fn [_]
nil))
(defn all
"Groups validators using 'and' boolean logic."
[& validators]
(fn [data]
(apply validate data validators)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stateful methods
(defn validate!
"Validates data and saves the result. **A stateful method.**
Arguments:
- cursor - the data to validate
- ui-state-cursor - this is where validation result will be stored
- validators - a seq of validators"
[cursor ui-state-cursor & validators]
(let [validation-errors (apply validate (binding/deref cursor) validators)]
(binding/reset! ui-state-cursor [:validation-errors] validation-errors)
(valid? validation-errors)))
(defn validation-errors
"Returns validation errors saved by [[validate!]] into ui-state-cursor."
[ui-state-cursor]
(binding/get-in ui-state-cursor [:validation-errors]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Form helpers
(defn html5-input
"Wrapper for [[reforms.core/html5-input]] adding support for validation."
[& args]
(apply validating-field f/html5-input args))
(defn password
"Wrapper for [[reforms.core/password]] adding support for validation."
[& args]
(apply validating-field f/password args))
(defn text
"Wrapper for [[reforms.core/text]] adding support for validation."
[& args]
(apply validating-field f/text args))
(defn textarea
"Wrapper for [[reforms.core/textarea]] adding support for validation."
[& args]
(apply validating-field f/textarea args))
(defn checkbox
"Wrapper for [[reforms.core/checkbox]] adding support for validation."
[& args]
(apply validating-field f/checkbox args))
(defn select
"Wrapper for [[reforms.core/select]] adding support for validation."
[& args]
(apply validating-field f/select args))
(defn button
"Wrapper for [[reforms.core/button]] adding support for validation."
[& args]
(apply validating-field f/button args))
(defn button-primary
"Wrapper for [[reforms.core/button-primary]] adding support for validation."
[& args]
(apply validating-field f/button-primary args))
(defn button-default
"Wrapper for [[reforms.core/button-default]] adding support for validation."
[& args]
(apply validating-field f/button-default args))
(defn datetime
"Wrapper for [[reforms.core/datetime]] adding support for validation."
[& args]
(apply validating-field f/datetime args))
(defn datetime-local
"Wrapper for [[reforms.core/datetime-local]] adding support for validation."
[& args]
(apply validating-field f/datetime-local args))
(defn date
"Wrapper for [[reforms.core/date]] adding support for validation."
[& args]
(apply validating-field f/date args))
(defn month
"Wrapper for [[reforms.core/month]] adding support for validation."
[& args]
(apply validating-field f/month args))
(defn time
"Wrapper for [[reforms.core/time]] adding support for validation."
[& args]
(apply validating-field f/time args))
(defn week
"Wrapper for [[reforms.core/week]] adding support for validation."
[& args]
(apply validating-field f/week args))
(defn number
"Wrapper for [[reforms.core/number]] adding support for validation."
[& args]
(apply validating-field f/number args))
(defn email
"Wrapper for [[reforms.core/email]] adding support for validation."
[& args]
(apply validating-field f/email args))
(defn url
"Wrapper for [[reforms.core/url]] adding support for validation."
[& args]
(apply validating-field f/url args))
(defn search
"Wrapper for [[reforms.core/search]] adding support for validation."
[& args]
(apply validating-field f/search args))
(defn tel
"Wrapper for [[reforms.core/tel]] adding support for validation."
[& args]
(apply validating-field f/tel args))
(defn color
"Wrapper for [[reforms.core/color]] adding support for validation."
[& args]
(apply validating-field f/color args))
(defn error-alert
"Renders errors for specified key seqs.
Example:
(error-alert [:user :name] [:my-custom-error])"
[& korks]
(render-errors (keep (fn [kork]
(when-let [err (find-validation-error kork *validation-errors*)]
err)) korks)))
|
[
{
"context": " port\n :user user\n :password pass})\n",
"end": 403,
"score": 0.9977789521217346,
"start": 399,
"tag": "PASSWORD",
"value": "pass"
}
] |
test/jdbc/melt/common.clj
|
reifying/melt
| 0 |
(ns jdbc.melt.common)
(def host (System/getenv "MELT_DB_HOST"))
(def port (or (System/getenv "MELT_DB_PORT") "1433"))
(def user (System/getenv "MELT_DB_USER"))
(def pass (System/getenv "MELT_DB_PASS"))
(def dbname (System/getenv "MELT_DB_NAME"))
(def db {:dbtype "jtds"
:dbname dbname
:host host
:port port
:user user
:password pass})
|
119186
|
(ns jdbc.melt.common)
(def host (System/getenv "MELT_DB_HOST"))
(def port (or (System/getenv "MELT_DB_PORT") "1433"))
(def user (System/getenv "MELT_DB_USER"))
(def pass (System/getenv "MELT_DB_PASS"))
(def dbname (System/getenv "MELT_DB_NAME"))
(def db {:dbtype "jtds"
:dbname dbname
:host host
:port port
:user user
:password <PASSWORD>})
| true |
(ns jdbc.melt.common)
(def host (System/getenv "MELT_DB_HOST"))
(def port (or (System/getenv "MELT_DB_PORT") "1433"))
(def user (System/getenv "MELT_DB_USER"))
(def pass (System/getenv "MELT_DB_PASS"))
(def dbname (System/getenv "MELT_DB_NAME"))
(def db {:dbtype "jtds"
:dbname dbname
:host host
:port port
:user user
:password PI:PASSWORD:<PASSWORD>END_PI})
|
[
{
"context": "s the user to choose a game to play.\"\n {:author \"Daniel Solano Gómez\"}\n (:gen-class :main no\n :extends a",
"end": 1741,
"score": 0.9997812509536743,
"start": 1722,
"tag": "NAME",
"value": "Daniel Solano Gómez"
}
] |
jvm-lang/clojure/src/clojure/decafbot/clojure/GameChooserActivity.clj
|
sattvik/decafbot
| 0 |
; Copyright © 2011 Sattvik Software & Technology Resources, Ltd. Co.
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice,
; this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
; 3. Neither the name of Sattvik Software & Technology Resources, Ltd. Co. nor
; the names of its contributors may be used to endorse or promote products
; derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(ns decafbot.clojure.GameChooserActivity
"Activity that allows the user to choose a game to play."
{:author "Daniel Solano Gómez"}
(:gen-class :main no
:extends android.app.Activity
:exposes-methods {onCreate superOnCreate
onDestroy superOnDestroy})
(:require [decafbot.clojure.talker :as talker])
(:use decafbot.clojure.utils)
(:import android.view.View$OnClickListener
[decafbot.clojure GlobalThermonuclearWarActivity
GuessTheNumberActivity
R$id R$layout R$string]))
(def talker (atom nil))
(defn- confirm-war
[activity]
(let [start-activity (partial start-activity activity)]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/chooser_confirm_nuke
:negative-button [R$string/later
#(start-activity GlobalThermonuclearWarActivity)]
:positive-button [android.R$string/yes
#(start-activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/chooser_confirm_nuke))))
(defn- handle-click
[selected activity]
(condp = selected
R$id/game_guess_the_number
(start-activity activity GuessTheNumberActivity)
R$id/game_global_thermonuclear_war
(confirm-war activity)))
(defn -onCreate
[this bundle]
(doto this
(.superOnCreate bundle)
(.setContentView R$layout/game_chooser))
(reset! talker (talker/init this))
(when (nil? bundle)
(talker/say @talker (.getString this R$string/greetings)))
(let [button (.findViewById this R$id/choose_button)
radio-group (.findViewById this R$id/game_chooser_list)]
(.setOnClickListener button
(reify View$OnClickListener
(onClick [_ _]
(handle-click (.getCheckedRadioButtonId radio-group)
this))))))
(defn -onDestroy
[this]
(when @talker
(talker/shutdown @talker)
(reset! talker nil))
(.superOnDestroy this))
|
41039
|
; Copyright © 2011 Sattvik Software & Technology Resources, Ltd. Co.
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice,
; this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
; 3. Neither the name of Sattvik Software & Technology Resources, Ltd. Co. nor
; the names of its contributors may be used to endorse or promote products
; derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(ns decafbot.clojure.GameChooserActivity
"Activity that allows the user to choose a game to play."
{:author "<NAME>"}
(:gen-class :main no
:extends android.app.Activity
:exposes-methods {onCreate superOnCreate
onDestroy superOnDestroy})
(:require [decafbot.clojure.talker :as talker])
(:use decafbot.clojure.utils)
(:import android.view.View$OnClickListener
[decafbot.clojure GlobalThermonuclearWarActivity
GuessTheNumberActivity
R$id R$layout R$string]))
(def talker (atom nil))
(defn- confirm-war
[activity]
(let [start-activity (partial start-activity activity)]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/chooser_confirm_nuke
:negative-button [R$string/later
#(start-activity GlobalThermonuclearWarActivity)]
:positive-button [android.R$string/yes
#(start-activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/chooser_confirm_nuke))))
(defn- handle-click
[selected activity]
(condp = selected
R$id/game_guess_the_number
(start-activity activity GuessTheNumberActivity)
R$id/game_global_thermonuclear_war
(confirm-war activity)))
(defn -onCreate
[this bundle]
(doto this
(.superOnCreate bundle)
(.setContentView R$layout/game_chooser))
(reset! talker (talker/init this))
(when (nil? bundle)
(talker/say @talker (.getString this R$string/greetings)))
(let [button (.findViewById this R$id/choose_button)
radio-group (.findViewById this R$id/game_chooser_list)]
(.setOnClickListener button
(reify View$OnClickListener
(onClick [_ _]
(handle-click (.getCheckedRadioButtonId radio-group)
this))))))
(defn -onDestroy
[this]
(when @talker
(talker/shutdown @talker)
(reset! talker nil))
(.superOnDestroy this))
| true |
; Copyright © 2011 Sattvik Software & Technology Resources, Ltd. Co.
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice,
; this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
; 3. Neither the name of Sattvik Software & Technology Resources, Ltd. Co. nor
; the names of its contributors may be used to endorse or promote products
; derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(ns decafbot.clojure.GameChooserActivity
"Activity that allows the user to choose a game to play."
{:author "PI:NAME:<NAME>END_PI"}
(:gen-class :main no
:extends android.app.Activity
:exposes-methods {onCreate superOnCreate
onDestroy superOnDestroy})
(:require [decafbot.clojure.talker :as talker])
(:use decafbot.clojure.utils)
(:import android.view.View$OnClickListener
[decafbot.clojure GlobalThermonuclearWarActivity
GuessTheNumberActivity
R$id R$layout R$string]))
(def talker (atom nil))
(defn- confirm-war
[activity]
(let [start-activity (partial start-activity activity)]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/chooser_confirm_nuke
:negative-button [R$string/later
#(start-activity GlobalThermonuclearWarActivity)]
:positive-button [android.R$string/yes
#(start-activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/chooser_confirm_nuke))))
(defn- handle-click
[selected activity]
(condp = selected
R$id/game_guess_the_number
(start-activity activity GuessTheNumberActivity)
R$id/game_global_thermonuclear_war
(confirm-war activity)))
(defn -onCreate
[this bundle]
(doto this
(.superOnCreate bundle)
(.setContentView R$layout/game_chooser))
(reset! talker (talker/init this))
(when (nil? bundle)
(talker/say @talker (.getString this R$string/greetings)))
(let [button (.findViewById this R$id/choose_button)
radio-group (.findViewById this R$id/game_chooser_list)]
(.setOnClickListener button
(reify View$OnClickListener
(onClick [_ _]
(handle-click (.getCheckedRadioButtonId radio-group)
this))))))
(defn -onDestroy
[this]
(when @talker
(talker/shutdown @talker)
(reset! talker nil))
(.superOnDestroy this))
|
[
{
"context": "sername :env/nexus_jenkins_username\n :password :env/nexus_jenkins_password\n :sign-releases false})\n\n(def tk-version \"1.1.1",
"end": 329,
"score": 0.8697314262390137,
"start": 303,
"tag": "PASSWORD",
"value": "env/nexus_jenkins_password"
}
] |
project.clj
|
shrug/puppetdb
| 0 |
(def pdb-version "3.1.0-SNAPSHOT")
(def pe-pdb-version "0.1.0-SNAPSHOT")
(defn deploy-info
"Generate deployment information from the URL supplied and the username and
password for Nexus supplied as environment variables."
[url]
{:url url
:username :env/nexus_jenkins_username
:password :env/nexus_jenkins_password
:sign-releases false})
(def tk-version "1.1.1")
(def tk-jetty9-version "1.3.1")
(def ks-version "1.1.0")
(defproject puppetlabs/puppetdb pdb-version
:description "Puppet-integrated catalog and fact storage"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:url "https://docs.puppetlabs.com/puppetdb/"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:dependencies [[org.clojure/clojure "1.7.0-RC2"]
[cheshire "5.4.0"]
[org.clojure/core.match "0.2.2"]
[org.clojure/math.combinatorics "0.0.4"]
[org.clojure/math.numeric-tower "0.0.4"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.10"]
[puppetlabs/tools.namespace "0.2.4.1"]
[clj-stacktrace "0.2.8"]
[metrics-clojure "0.7.0" :exclusions [org.clojure/clojure org.slf4j/slf4j-api]]
[clj-time "0.9.0"]
[org.clojure/java.jmx "0.3.1"]
;; Filesystem utilities
[me.raynes/fs "1.4.5"]
;; Version information
[trptcolin/versioneer "0.1.0"]
;; Job scheduling
[overtone/at-at "1.2.0"]
;; Nicer exception handling with try+/throw+
[slingshot "0.12.2"]
;; Database connectivity
[com.jolbox/bonecp "0.7.1.RELEASE" :exclusions [org.slf4j/slf4j-api]]
[org.clojure/java.jdbc "0.1.1"]
[org.hsqldb/hsqldb "2.2.8"]
[org.postgresql/postgresql "9.2-1003-jdbc4"]
;; MQ connectivity
[org.apache.activemq/activemq-broker "5.11.1"]
[org.apache.activemq/activemq-kahadb-store "5.11.1"]
[org.apache.activemq/activemq-pool "5.11.1"]
;; bridge to allow some spring/activemq stuff to log over slf4j
[org.slf4j/jcl-over-slf4j "1.7.10"]
;; WebAPI support libraries.
[net.cgrand/moustache "1.1.0" :exclusions [ring/ring-core org.clojure/clojure]]
[compojure "1.3.3"]
[clj-http "1.0.1"]
[ring/ring-core "1.3.2" :exclusions [javax.servlet/servlet-api]]
[org.apache.commons/commons-compress "1.8"]
[puppetlabs/kitchensink ~ks-version]
[puppetlabs/trapperkeeper ~tk-version]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version]
[prismatic/schema "0.4.1"]
[org.clojure/tools.macro "0.1.5"]
[com.novemberain/pantomime "2.1.0"]
[fast-zip-visit "1.0.2"]
[robert/hooke "1.3.0"]
[honeysql "0.5.2"]
[org.clojure/data.xml "0.0.8"]]
:jvm-opts ["-XX:MaxPermSize=128M"]
;;The below test-selectors is basically using the PUPPETDB_DBTYPE
;;environment variable to be the test selector. The selector below
;;will always run a test, unless it has a meta value for that
;;dbtype, and that value is falsey, such as
;;(deftest ^{:postgres false} my-test-name...)
:test-selectors {:default (fn [test-var-meta]
(let [dbtype (keyword (or (System/getenv "PUPPETDB_DBTYPE")
"hsqldb"))]
(get test-var-meta dbtype true)))}
:repositories [["releases" "http://nexus.delivery.puppetlabs.net/content/repositories/releases/"]
["snapshots" "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/"]]
:plugins [[lein-release "1.0.5"]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:uberjar-name "puppetdb.jar"
:lein-ezbake {:vars {:user "puppetdb"
:group "puppetdb"
:build-type "foss"
:main-namespace "puppetlabs.puppetdb.main"}
:config-dir "ext/config/foss"
}
:deploy-repositories [["releases" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/releases/")]
["snapshots" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/")]]
;; By declaring a classifier here and a corresponding profile below we'll get an additional jar
;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then
;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility
;; code that we have.
:classifiers [["test" :testutils]]
:profiles {:dev {:resource-paths ["test-resources"],
:dependencies [[ring-mock "0.1.5"]
[puppetlabs/trapperkeeper ~tk-version :classifier "test"]
[puppetlabs/kitchensink ~ks-version :classifier "test"]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version :classifier "test"]
[org.flatland/ordered "1.5.2"]
[org.clojure/test.check "0.5.9"]]}
:ezbake {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]]
:name "puppetdb"
:plugins [[puppetlabs/lein-ezbake "0.3.10-SNAPSHOT"
:exclusions [org.clojure/clojure]]]}
:pe {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]
[puppetlabs/pe-puppetdb-extensions ~pe-pdb-version]]
:lein-ezbake {:vars {:user "pe-puppetdb"
:group "pe-puppetdb"
:build-type "pe"}
:config-dir "ext/config/pe"}
:version ~pdb-version
:name "pe-puppetdb"}
:testutils {:source-paths ^:replace ["test"]}
:ci {:plugins [[lein-pprint "1.1.1"]]}}
:jar-exclusions [#"leiningen/"]
:resource-paths ["resources" "puppet/lib" "resources/puppetlabs/puppetdb" "resources/ext/docs"]
:main ^:skip-aot puppetlabs.puppetdb.core)
|
98790
|
(def pdb-version "3.1.0-SNAPSHOT")
(def pe-pdb-version "0.1.0-SNAPSHOT")
(defn deploy-info
"Generate deployment information from the URL supplied and the username and
password for Nexus supplied as environment variables."
[url]
{:url url
:username :env/nexus_jenkins_username
:password :<PASSWORD>
:sign-releases false})
(def tk-version "1.1.1")
(def tk-jetty9-version "1.3.1")
(def ks-version "1.1.0")
(defproject puppetlabs/puppetdb pdb-version
:description "Puppet-integrated catalog and fact storage"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:url "https://docs.puppetlabs.com/puppetdb/"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:dependencies [[org.clojure/clojure "1.7.0-RC2"]
[cheshire "5.4.0"]
[org.clojure/core.match "0.2.2"]
[org.clojure/math.combinatorics "0.0.4"]
[org.clojure/math.numeric-tower "0.0.4"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.10"]
[puppetlabs/tools.namespace "0.2.4.1"]
[clj-stacktrace "0.2.8"]
[metrics-clojure "0.7.0" :exclusions [org.clojure/clojure org.slf4j/slf4j-api]]
[clj-time "0.9.0"]
[org.clojure/java.jmx "0.3.1"]
;; Filesystem utilities
[me.raynes/fs "1.4.5"]
;; Version information
[trptcolin/versioneer "0.1.0"]
;; Job scheduling
[overtone/at-at "1.2.0"]
;; Nicer exception handling with try+/throw+
[slingshot "0.12.2"]
;; Database connectivity
[com.jolbox/bonecp "0.7.1.RELEASE" :exclusions [org.slf4j/slf4j-api]]
[org.clojure/java.jdbc "0.1.1"]
[org.hsqldb/hsqldb "2.2.8"]
[org.postgresql/postgresql "9.2-1003-jdbc4"]
;; MQ connectivity
[org.apache.activemq/activemq-broker "5.11.1"]
[org.apache.activemq/activemq-kahadb-store "5.11.1"]
[org.apache.activemq/activemq-pool "5.11.1"]
;; bridge to allow some spring/activemq stuff to log over slf4j
[org.slf4j/jcl-over-slf4j "1.7.10"]
;; WebAPI support libraries.
[net.cgrand/moustache "1.1.0" :exclusions [ring/ring-core org.clojure/clojure]]
[compojure "1.3.3"]
[clj-http "1.0.1"]
[ring/ring-core "1.3.2" :exclusions [javax.servlet/servlet-api]]
[org.apache.commons/commons-compress "1.8"]
[puppetlabs/kitchensink ~ks-version]
[puppetlabs/trapperkeeper ~tk-version]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version]
[prismatic/schema "0.4.1"]
[org.clojure/tools.macro "0.1.5"]
[com.novemberain/pantomime "2.1.0"]
[fast-zip-visit "1.0.2"]
[robert/hooke "1.3.0"]
[honeysql "0.5.2"]
[org.clojure/data.xml "0.0.8"]]
:jvm-opts ["-XX:MaxPermSize=128M"]
;;The below test-selectors is basically using the PUPPETDB_DBTYPE
;;environment variable to be the test selector. The selector below
;;will always run a test, unless it has a meta value for that
;;dbtype, and that value is falsey, such as
;;(deftest ^{:postgres false} my-test-name...)
:test-selectors {:default (fn [test-var-meta]
(let [dbtype (keyword (or (System/getenv "PUPPETDB_DBTYPE")
"hsqldb"))]
(get test-var-meta dbtype true)))}
:repositories [["releases" "http://nexus.delivery.puppetlabs.net/content/repositories/releases/"]
["snapshots" "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/"]]
:plugins [[lein-release "1.0.5"]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:uberjar-name "puppetdb.jar"
:lein-ezbake {:vars {:user "puppetdb"
:group "puppetdb"
:build-type "foss"
:main-namespace "puppetlabs.puppetdb.main"}
:config-dir "ext/config/foss"
}
:deploy-repositories [["releases" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/releases/")]
["snapshots" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/")]]
;; By declaring a classifier here and a corresponding profile below we'll get an additional jar
;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then
;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility
;; code that we have.
:classifiers [["test" :testutils]]
:profiles {:dev {:resource-paths ["test-resources"],
:dependencies [[ring-mock "0.1.5"]
[puppetlabs/trapperkeeper ~tk-version :classifier "test"]
[puppetlabs/kitchensink ~ks-version :classifier "test"]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version :classifier "test"]
[org.flatland/ordered "1.5.2"]
[org.clojure/test.check "0.5.9"]]}
:ezbake {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]]
:name "puppetdb"
:plugins [[puppetlabs/lein-ezbake "0.3.10-SNAPSHOT"
:exclusions [org.clojure/clojure]]]}
:pe {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]
[puppetlabs/pe-puppetdb-extensions ~pe-pdb-version]]
:lein-ezbake {:vars {:user "pe-puppetdb"
:group "pe-puppetdb"
:build-type "pe"}
:config-dir "ext/config/pe"}
:version ~pdb-version
:name "pe-puppetdb"}
:testutils {:source-paths ^:replace ["test"]}
:ci {:plugins [[lein-pprint "1.1.1"]]}}
:jar-exclusions [#"leiningen/"]
:resource-paths ["resources" "puppet/lib" "resources/puppetlabs/puppetdb" "resources/ext/docs"]
:main ^:skip-aot puppetlabs.puppetdb.core)
| true |
(def pdb-version "3.1.0-SNAPSHOT")
(def pe-pdb-version "0.1.0-SNAPSHOT")
(defn deploy-info
"Generate deployment information from the URL supplied and the username and
password for Nexus supplied as environment variables."
[url]
{:url url
:username :env/nexus_jenkins_username
:password :PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false})
(def tk-version "1.1.1")
(def tk-jetty9-version "1.3.1")
(def ks-version "1.1.0")
(defproject puppetlabs/puppetdb pdb-version
:description "Puppet-integrated catalog and fact storage"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:url "https://docs.puppetlabs.com/puppetdb/"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:dependencies [[org.clojure/clojure "1.7.0-RC2"]
[cheshire "5.4.0"]
[org.clojure/core.match "0.2.2"]
[org.clojure/math.combinatorics "0.0.4"]
[org.clojure/math.numeric-tower "0.0.4"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/tools.nrepl "0.2.10"]
[puppetlabs/tools.namespace "0.2.4.1"]
[clj-stacktrace "0.2.8"]
[metrics-clojure "0.7.0" :exclusions [org.clojure/clojure org.slf4j/slf4j-api]]
[clj-time "0.9.0"]
[org.clojure/java.jmx "0.3.1"]
;; Filesystem utilities
[me.raynes/fs "1.4.5"]
;; Version information
[trptcolin/versioneer "0.1.0"]
;; Job scheduling
[overtone/at-at "1.2.0"]
;; Nicer exception handling with try+/throw+
[slingshot "0.12.2"]
;; Database connectivity
[com.jolbox/bonecp "0.7.1.RELEASE" :exclusions [org.slf4j/slf4j-api]]
[org.clojure/java.jdbc "0.1.1"]
[org.hsqldb/hsqldb "2.2.8"]
[org.postgresql/postgresql "9.2-1003-jdbc4"]
;; MQ connectivity
[org.apache.activemq/activemq-broker "5.11.1"]
[org.apache.activemq/activemq-kahadb-store "5.11.1"]
[org.apache.activemq/activemq-pool "5.11.1"]
;; bridge to allow some spring/activemq stuff to log over slf4j
[org.slf4j/jcl-over-slf4j "1.7.10"]
;; WebAPI support libraries.
[net.cgrand/moustache "1.1.0" :exclusions [ring/ring-core org.clojure/clojure]]
[compojure "1.3.3"]
[clj-http "1.0.1"]
[ring/ring-core "1.3.2" :exclusions [javax.servlet/servlet-api]]
[org.apache.commons/commons-compress "1.8"]
[puppetlabs/kitchensink ~ks-version]
[puppetlabs/trapperkeeper ~tk-version]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version]
[prismatic/schema "0.4.1"]
[org.clojure/tools.macro "0.1.5"]
[com.novemberain/pantomime "2.1.0"]
[fast-zip-visit "1.0.2"]
[robert/hooke "1.3.0"]
[honeysql "0.5.2"]
[org.clojure/data.xml "0.0.8"]]
:jvm-opts ["-XX:MaxPermSize=128M"]
;;The below test-selectors is basically using the PUPPETDB_DBTYPE
;;environment variable to be the test selector. The selector below
;;will always run a test, unless it has a meta value for that
;;dbtype, and that value is falsey, such as
;;(deftest ^{:postgres false} my-test-name...)
:test-selectors {:default (fn [test-var-meta]
(let [dbtype (keyword (or (System/getenv "PUPPETDB_DBTYPE")
"hsqldb"))]
(get test-var-meta dbtype true)))}
:repositories [["releases" "http://nexus.delivery.puppetlabs.net/content/repositories/releases/"]
["snapshots" "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/"]]
:plugins [[lein-release "1.0.5"]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:uberjar-name "puppetdb.jar"
:lein-ezbake {:vars {:user "puppetdb"
:group "puppetdb"
:build-type "foss"
:main-namespace "puppetlabs.puppetdb.main"}
:config-dir "ext/config/foss"
}
:deploy-repositories [["releases" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/releases/")]
["snapshots" ~(deploy-info "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/")]]
;; By declaring a classifier here and a corresponding profile below we'll get an additional jar
;; during `lein jar` that has all the code in the test/ directory. Downstream projects can then
;; depend on this test jar using a :classifier in their :dependencies to reuse the test utility
;; code that we have.
:classifiers [["test" :testutils]]
:profiles {:dev {:resource-paths ["test-resources"],
:dependencies [[ring-mock "0.1.5"]
[puppetlabs/trapperkeeper ~tk-version :classifier "test"]
[puppetlabs/kitchensink ~ks-version :classifier "test"]
[puppetlabs/trapperkeeper-webserver-jetty9 ~tk-jetty9-version :classifier "test"]
[org.flatland/ordered "1.5.2"]
[org.clojure/test.check "0.5.9"]]}
:ezbake {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]]
:name "puppetdb"
:plugins [[puppetlabs/lein-ezbake "0.3.10-SNAPSHOT"
:exclusions [org.clojure/clojure]]]}
:pe {:dependencies ^:replace [[puppetlabs/puppetdb ~pdb-version]
[org.clojure/tools.nrepl "0.2.3"]
[puppetlabs/pe-puppetdb-extensions ~pe-pdb-version]]
:lein-ezbake {:vars {:user "pe-puppetdb"
:group "pe-puppetdb"
:build-type "pe"}
:config-dir "ext/config/pe"}
:version ~pdb-version
:name "pe-puppetdb"}
:testutils {:source-paths ^:replace ["test"]}
:ci {:plugins [[lein-pprint "1.1.1"]]}}
:jar-exclusions [#"leiningen/"]
:resource-paths ["resources" "puppet/lib" "resources/puppetlabs/puppetdb" "resources/ext/docs"]
:main ^:skip-aot puppetlabs.puppetdb.core)
|
[
{
"context": "params \"user\")\n password (get params \"password\")\n session (session session-store req",
"end": 3026,
"score": 0.9901927709579468,
"start": 3018,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " {:name \"password\" :label \"Password\" :password? true :placeholder \"password\"}]})\n ",
"end": 4932,
"score": 0.8129881024360657,
"start": 4924,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "\" :label \"Password\" :password? true :placeholder \"password\"}]})\n (s/validate new-login-schema)\n ",
"end": 4972,
"score": 0.9867386221885681,
"start": 4964,
"tag": "PASSWORD",
"value": "password"
}
] |
src/cylon/authentication/login.clj
|
michaelklishin/cylon
| 1 |
;; Copyright © 2014, JUXT LTD. All Rights Reserved.
(ns cylon.authentication.login
(:require
[clojure.tools.logging :refer :all]
[cylon.authentication.protocols :refer (AuthenticationInteraction)]
[cylon.password :refer (verify-password)]
[cylon.password.protocols :refer (PasswordVerifier)]
[cylon.session :refer (session assoc-session-data! respond-with-new-session!)]
[cylon.session.protocols :refer (SessionStore)]
[cylon.util :refer (as-query-string uri-with-qs Request)]
[modular.bidi :refer (WebService path-for)]
[ring.util.response :refer (redirect redirect-after-post)]
[ring.middleware.params :refer (params-request)]
[plumbing.core :refer (<-)]
[com.stuartsierra.component :refer (Lifecycle using)]
[schema.core :as s])
(:import (java.net URLEncoder))
)
(defprotocol LoginFormRenderer
(render-login-form [_ req model]))
(def field-schema
{:name s/Str
:label s/Str
(s/optional-key :placeholder) s/Str
(s/optional-key :password?) s/Bool})
(def new-login-schema {:fields [field-schema]})
(s/defn render-login-form+ :- s/Str
[component :- (s/protocol LoginFormRenderer)
req :- Request
model :- {:form {:method s/Keyword
:action s/Str
(s/optional-key :signup-uri) s/Str
(s/optional-key :post-login-redirect) s/Str
:fields [field-schema]}}]
(render-login-form component req model))
(defrecord Login [session-store renderer password-verifier fields]
Lifecycle
(start [component]
(s/validate
(merge new-login-schema
{:session-store (s/protocol SessionStore)
:renderer (s/protocol LoginFormRenderer)
:password-verifier (s/protocol PasswordVerifier)
}) component))
(stop [component] component)
AuthenticationInteraction
(initiate-authentication-interaction [this req]
(if-let [p (path-for req ::login-form)]
(let [loc (str p (as-query-string {"post_login_redirect" (URLEncoder/encode (uri-with-qs req))}))]
(debugf "Redirecting to %s" loc)
(redirect loc))
(throw (ex-info "No path to login form" {}))))
(get-outcome [this req]
(session session-store req))
WebService
(request-handlers [this]
{::login-form
(fn [req]
(let [qparams (-> req params-request :query-params)
response
{:status 200
:body (render-login-form+
renderer req
{:form {:method :post
:action (path-for req ::process-login-attempt)
:signup-uri (path-for req :cylon.signup.signup/GET-signup-form)
:post-login-redirect (get qparams "post_login_redirect")
:fields fields}})}]
response))
::process-login-attempt
(fn [req]
(let [params (-> req params-request :form-params)
uid (get params "user")
password (get params "password")
session (session session-store req)
post-login-redirect (get params "post_login_redirect")]
(debugf "Form params posted to login form are %s" params)
(if (and uid (not-empty uid)
(verify-password password-verifier (.trim uid) password))
;; Login successful!
(do
(debugf "Login successful!")
(respond-with-new-session!
session-store req
{:cylon/subject-identifier uid}
(if post-login-redirect
(redirect-after-post post-login-redirect)
{:status 200 :body "Login successful"})))
;; Login failed!
(do
(debugf "Login failed!")
;; TODO I think the best thing to do here is to create a
;; session anyway - we have been posted after all. We can
;; store in the session things like number of failed
;; attempts (to attempt to prevent brute-force hacking
;; attempts by limiting the number of sessions that can be
;; used by each remote IP address). If we do this, then the
;; post_login_redirect must be ascertained from the
;; query-params, and then from the session.
(redirect-after-post
(str (path-for req ::login-form)
;; We must be careful to add back the query string
(when post-login-redirect
(str "?post_login_redirect=" (URLEncoder/encode post-login-redirect)))))))))})
(routes [this]
["" {"/login" {:get ::login-form
:post ::process-login-attempt}}])
(uri-context [this] ""))
(defn new-login [& {:as opts}]
(->> opts
(merge {:fields [{:name "user" :label "User" :placeholder "id or email"}
{:name "password" :label "Password" :password? true :placeholder "password"}]})
(s/validate new-login-schema)
map->Login
(<- (using [:password-verifier :session-store :renderer]))))
|
90044
|
;; Copyright © 2014, JUXT LTD. All Rights Reserved.
(ns cylon.authentication.login
(:require
[clojure.tools.logging :refer :all]
[cylon.authentication.protocols :refer (AuthenticationInteraction)]
[cylon.password :refer (verify-password)]
[cylon.password.protocols :refer (PasswordVerifier)]
[cylon.session :refer (session assoc-session-data! respond-with-new-session!)]
[cylon.session.protocols :refer (SessionStore)]
[cylon.util :refer (as-query-string uri-with-qs Request)]
[modular.bidi :refer (WebService path-for)]
[ring.util.response :refer (redirect redirect-after-post)]
[ring.middleware.params :refer (params-request)]
[plumbing.core :refer (<-)]
[com.stuartsierra.component :refer (Lifecycle using)]
[schema.core :as s])
(:import (java.net URLEncoder))
)
(defprotocol LoginFormRenderer
(render-login-form [_ req model]))
(def field-schema
{:name s/Str
:label s/Str
(s/optional-key :placeholder) s/Str
(s/optional-key :password?) s/Bool})
(def new-login-schema {:fields [field-schema]})
(s/defn render-login-form+ :- s/Str
[component :- (s/protocol LoginFormRenderer)
req :- Request
model :- {:form {:method s/Keyword
:action s/Str
(s/optional-key :signup-uri) s/Str
(s/optional-key :post-login-redirect) s/Str
:fields [field-schema]}}]
(render-login-form component req model))
(defrecord Login [session-store renderer password-verifier fields]
Lifecycle
(start [component]
(s/validate
(merge new-login-schema
{:session-store (s/protocol SessionStore)
:renderer (s/protocol LoginFormRenderer)
:password-verifier (s/protocol PasswordVerifier)
}) component))
(stop [component] component)
AuthenticationInteraction
(initiate-authentication-interaction [this req]
(if-let [p (path-for req ::login-form)]
(let [loc (str p (as-query-string {"post_login_redirect" (URLEncoder/encode (uri-with-qs req))}))]
(debugf "Redirecting to %s" loc)
(redirect loc))
(throw (ex-info "No path to login form" {}))))
(get-outcome [this req]
(session session-store req))
WebService
(request-handlers [this]
{::login-form
(fn [req]
(let [qparams (-> req params-request :query-params)
response
{:status 200
:body (render-login-form+
renderer req
{:form {:method :post
:action (path-for req ::process-login-attempt)
:signup-uri (path-for req :cylon.signup.signup/GET-signup-form)
:post-login-redirect (get qparams "post_login_redirect")
:fields fields}})}]
response))
::process-login-attempt
(fn [req]
(let [params (-> req params-request :form-params)
uid (get params "user")
password (get params "<PASSWORD>")
session (session session-store req)
post-login-redirect (get params "post_login_redirect")]
(debugf "Form params posted to login form are %s" params)
(if (and uid (not-empty uid)
(verify-password password-verifier (.trim uid) password))
;; Login successful!
(do
(debugf "Login successful!")
(respond-with-new-session!
session-store req
{:cylon/subject-identifier uid}
(if post-login-redirect
(redirect-after-post post-login-redirect)
{:status 200 :body "Login successful"})))
;; Login failed!
(do
(debugf "Login failed!")
;; TODO I think the best thing to do here is to create a
;; session anyway - we have been posted after all. We can
;; store in the session things like number of failed
;; attempts (to attempt to prevent brute-force hacking
;; attempts by limiting the number of sessions that can be
;; used by each remote IP address). If we do this, then the
;; post_login_redirect must be ascertained from the
;; query-params, and then from the session.
(redirect-after-post
(str (path-for req ::login-form)
;; We must be careful to add back the query string
(when post-login-redirect
(str "?post_login_redirect=" (URLEncoder/encode post-login-redirect)))))))))})
(routes [this]
["" {"/login" {:get ::login-form
:post ::process-login-attempt}}])
(uri-context [this] ""))
(defn new-login [& {:as opts}]
(->> opts
(merge {:fields [{:name "user" :label "User" :placeholder "id or email"}
{:name "password" :label "<PASSWORD>" :password? true :placeholder "<PASSWORD>"}]})
(s/validate new-login-schema)
map->Login
(<- (using [:password-verifier :session-store :renderer]))))
| true |
;; Copyright © 2014, JUXT LTD. All Rights Reserved.
(ns cylon.authentication.login
(:require
[clojure.tools.logging :refer :all]
[cylon.authentication.protocols :refer (AuthenticationInteraction)]
[cylon.password :refer (verify-password)]
[cylon.password.protocols :refer (PasswordVerifier)]
[cylon.session :refer (session assoc-session-data! respond-with-new-session!)]
[cylon.session.protocols :refer (SessionStore)]
[cylon.util :refer (as-query-string uri-with-qs Request)]
[modular.bidi :refer (WebService path-for)]
[ring.util.response :refer (redirect redirect-after-post)]
[ring.middleware.params :refer (params-request)]
[plumbing.core :refer (<-)]
[com.stuartsierra.component :refer (Lifecycle using)]
[schema.core :as s])
(:import (java.net URLEncoder))
)
(defprotocol LoginFormRenderer
(render-login-form [_ req model]))
(def field-schema
{:name s/Str
:label s/Str
(s/optional-key :placeholder) s/Str
(s/optional-key :password?) s/Bool})
(def new-login-schema {:fields [field-schema]})
(s/defn render-login-form+ :- s/Str
[component :- (s/protocol LoginFormRenderer)
req :- Request
model :- {:form {:method s/Keyword
:action s/Str
(s/optional-key :signup-uri) s/Str
(s/optional-key :post-login-redirect) s/Str
:fields [field-schema]}}]
(render-login-form component req model))
(defrecord Login [session-store renderer password-verifier fields]
Lifecycle
(start [component]
(s/validate
(merge new-login-schema
{:session-store (s/protocol SessionStore)
:renderer (s/protocol LoginFormRenderer)
:password-verifier (s/protocol PasswordVerifier)
}) component))
(stop [component] component)
AuthenticationInteraction
(initiate-authentication-interaction [this req]
(if-let [p (path-for req ::login-form)]
(let [loc (str p (as-query-string {"post_login_redirect" (URLEncoder/encode (uri-with-qs req))}))]
(debugf "Redirecting to %s" loc)
(redirect loc))
(throw (ex-info "No path to login form" {}))))
(get-outcome [this req]
(session session-store req))
WebService
(request-handlers [this]
{::login-form
(fn [req]
(let [qparams (-> req params-request :query-params)
response
{:status 200
:body (render-login-form+
renderer req
{:form {:method :post
:action (path-for req ::process-login-attempt)
:signup-uri (path-for req :cylon.signup.signup/GET-signup-form)
:post-login-redirect (get qparams "post_login_redirect")
:fields fields}})}]
response))
::process-login-attempt
(fn [req]
(let [params (-> req params-request :form-params)
uid (get params "user")
password (get params "PI:PASSWORD:<PASSWORD>END_PI")
session (session session-store req)
post-login-redirect (get params "post_login_redirect")]
(debugf "Form params posted to login form are %s" params)
(if (and uid (not-empty uid)
(verify-password password-verifier (.trim uid) password))
;; Login successful!
(do
(debugf "Login successful!")
(respond-with-new-session!
session-store req
{:cylon/subject-identifier uid}
(if post-login-redirect
(redirect-after-post post-login-redirect)
{:status 200 :body "Login successful"})))
;; Login failed!
(do
(debugf "Login failed!")
;; TODO I think the best thing to do here is to create a
;; session anyway - we have been posted after all. We can
;; store in the session things like number of failed
;; attempts (to attempt to prevent brute-force hacking
;; attempts by limiting the number of sessions that can be
;; used by each remote IP address). If we do this, then the
;; post_login_redirect must be ascertained from the
;; query-params, and then from the session.
(redirect-after-post
(str (path-for req ::login-form)
;; We must be careful to add back the query string
(when post-login-redirect
(str "?post_login_redirect=" (URLEncoder/encode post-login-redirect)))))))))})
(routes [this]
["" {"/login" {:get ::login-form
:post ::process-login-attempt}}])
(uri-context [this] ""))
(defn new-login [& {:as opts}]
(->> opts
(merge {:fields [{:name "user" :label "User" :placeholder "id or email"}
{:name "password" :label "PI:PASSWORD:<PASSWORD>END_PI" :password? true :placeholder "PI:PASSWORD:<PASSWORD>END_PI"}]})
(s/validate new-login-schema)
map->Login
(<- (using [:password-verifier :session-store :renderer]))))
|
[
{
"context": "eys [firstname lastname] :as person} {:firstname \"John\" :lastname \"Smith\"}\n{:keys [:firstname :lastname",
"end": 530,
"score": 0.9861246943473816,
"start": 526,
"tag": "NAME",
"value": "John"
},
{
"context": "s [:firstname :lastname] :as person} {:firstname \"John\" :lastname \"Smith\"}\n{:strs [firstname lastname] ",
"end": 611,
"score": 0.9959458112716675,
"start": 607,
"tag": "NAME",
"value": "John"
},
{
"context": "tname] :as person} {:firstname \"John\" :lastname \"Smith\"}\n{:strs [firstname lastname] :as person} {\"first",
"end": 630,
"score": 0.6889041662216187,
"start": 625,
"tag": "NAME",
"value": "Smith"
},
{
"context": "rs [firstname lastname] :as person} {\"firstname\" \"John\" \"lastname\" \"Smith\"}\n{:syms [firstname lastname] ",
"end": 691,
"score": 0.9724926948547363,
"start": 687,
"tag": "NAME",
"value": "John"
},
{
"context": "yms [firstname lastname] :as person} {'firstname \"John\" 'lastname \"Smith\"}\n;; firstname = John, lastnam",
"end": 770,
"score": 0.9930405616760254,
"start": 766,
"tag": "NAME",
"value": "John"
},
{
"context": "irstname \"John\" 'lastname \"Smith\"}\n;; firstname = John, lastname = Smith, person = {:firstname \"John\" :l",
"end": 811,
"score": 0.9740085005760193,
"start": 807,
"tag": "NAME",
"value": "John"
},
{
"context": "e = John, lastname = Smith, person = {:firstname \"John\" :lastname \"Smith\"}\n\n;; maps destructuring with d",
"end": 857,
"score": 0.9904587268829346,
"start": 853,
"tag": "NAME",
"value": "John"
},
{
"context": "me family-name :lastname :as person} {:firstname \"John\" :lastname \"Smith\"}\n;; name = John, family-name ",
"end": 1001,
"score": 0.9911641478538513,
"start": 997,
"tag": "NAME",
"value": "John"
},
{
"context": "} {:firstname \"John\" :lastname \"Smith\"}\n;; name = John, family-name = Smith, person = {:firstname \"John\"",
"end": 1037,
"score": 0.906242847442627,
"start": 1033,
"tag": "NAME",
"value": "John"
},
{
"context": " John, family-name = Smith, person = {:firstname \"John\" :lastname \"Smith\"}\n\n;; default values\n{:keys [fi",
"end": 1086,
"score": 0.9889519810676575,
"start": 1082,
"tag": "NAME",
"value": "John"
},
{
"context": "rstname \"Jane\" :lastname \"Bloggs\"}} {:firstname \"John\"}\n;; firstname = John, lastname = Bloggs, person ",
"end": 1227,
"score": 0.9848998785018921,
"start": 1223,
"tag": "NAME",
"value": "John"
},
{
"context": "name \"Bloggs\"}} {:firstname \"John\"}\n;; firstname = John, lastname = Bloggs, person = {:firstname \"John\"}\n",
"end": 1249,
"score": 0.7705963253974915,
"start": 1245,
"tag": "NAME",
"value": "John"
},
{
"context": " = John, lastname = Bloggs, person = {:firstname \"John\"}\n\n;; nested destructuring\n[[x1 y1] [x2 y2] [_ _ ",
"end": 1296,
"score": 0.9803370833396912,
"start": 1292,
"tag": "NAME",
"value": "John"
},
{
"context": "tname]\n {:keys [phone]} :contact} {:firstname \"John\" :lastname \"Smith\" :contact {:phone \"0987654321\"}",
"end": 1490,
"score": 0.9931342005729675,
"start": 1486,
"tag": "NAME",
"value": "John"
},
{
"context": "th\" :contact {:phone \"0987654321\"}}\n;; firstname = John, lastname = Smith, phone = 0987654321\n\n;; namespa",
"end": 1561,
"score": 0.9998434782028198,
"start": 1557,
"tag": "NAME",
"value": "John"
},
{
"context": "one \"0987654321\"}}\n;; firstname = John, lastname = Smith, phone = 0987654321\n\n;; namespaced keys in maps a",
"end": 1579,
"score": 0.9968885779380798,
"start": 1574,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ct/lastname] :as person} {:contact/firstname \"John\" :contact/lastname \"Smith\"}\n{:keys [:contact/firs",
"end": 1722,
"score": 0.99980229139328,
"start": 1718,
"tag": "NAME",
"value": "John"
},
{
"context": " {:contact/firstname \"John\" :contact/lastname \"Smith\"}\n{:keys [:contact/firstname :contact/lastname] :",
"end": 1748,
"score": 0.9996669292449951,
"start": 1743,
"tag": "NAME",
"value": "Smith"
},
{
"context": "tact/lastname] :as person} {:contact/firstname \"John\" :contact/lastname \"Smith\"}\n{:keys [::firstname :",
"end": 1836,
"score": 0.9997901320457458,
"start": 1832,
"tag": "NAME",
"value": "John"
},
{
"context": "} {:contact/firstname \"John\" :contact/lastname \"Smith\"}\n{:keys [::firstname ::lastname] :as person} ",
"end": 1862,
"score": 0.9996502995491028,
"start": 1857,
"tag": "NAME",
"value": "Smith"
},
{
"context": "stname] :as person} {::firstname \"John\" ::lastname \"Smith\"}\n{:syms [contact/first",
"end": 1943,
"score": 0.9997966885566711,
"start": 1939,
"tag": "NAME",
"value": "John"
},
{
"context": " {::firstname \"John\" ::lastname \"Smith\"}\n{:syms [contact/firstname contact/lastname] :as",
"end": 1969,
"score": 0.9973811507225037,
"start": 1964,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ct/lastname] :as person} {'contact/firstname \"John\" 'contact/lastname \"Smith\"}\n;; firstname = John, ",
"end": 2057,
"score": 0.9998055100440979,
"start": 2053,
"tag": "NAME",
"value": "John"
},
{
"context": " {'contact/firstname \"John\" 'contact/lastname \"Smith\"}\n;; firstname = John, lastname = Smith, person =",
"end": 2083,
"score": 0.9995503425598145,
"start": 2078,
"tag": "NAME",
"value": "Smith"
},
{
"context": "e \"John\" 'contact/lastname \"Smith\"}\n;; firstname = John, lastname = Smith, person = {:firstname \"John\" :l",
"end": 2105,
"score": 0.9998465776443481,
"start": 2101,
"tag": "NAME",
"value": "John"
},
{
"context": "/lastname \"Smith\"}\n;; firstname = John, lastname = Smith, person = {:firstname \"John\" :lastname \"Smith\"}\n",
"end": 2123,
"score": 0.9956313371658325,
"start": 2118,
"tag": "NAME",
"value": "Smith"
},
{
"context": "e = John, lastname = Smith, person = {:firstname \"John\" :lastname \"Smith\"}\n",
"end": 2151,
"score": 0.9997574687004089,
"start": 2147,
"tag": "NAME",
"value": "John"
},
{
"context": "e = Smith, person = {:firstname \"John\" :lastname \"Smith\"}\n",
"end": 2169,
"score": 0.9995107650756836,
"start": 2164,
"tag": "NAME",
"value": "Smith"
}
] |
clojure/avulsos/the_complete_guide_to_clojure_destructuring.clj
|
micalevisk/x-de-cada-dia
| 0 |
;; Clojure destructuring cheatsheet.
;; all the following destructuring forms can be used in any of the
;; Clojure's `let` derived bindings such as function's parameters,
;; `let`, `loop`, `binding`, `for`, `doseq`, etc.
;; list, vectors and sequences
[zero _ _ three & four-and-more :as numbers] (range)
{one 1 two 2} [:a :b :c :d :e :f :g]
;; zero = 0, three = 3, four-and-more = (4 5 6 7 ...),
;; numbers = (0 1 2 3 4 5 6 7 ...)
;; one = :b, two = :c
;; maps and sets
{:keys [firstname lastname] :as person} {:firstname "John" :lastname "Smith"}
{:keys [:firstname :lastname] :as person} {:firstname "John" :lastname "Smith"}
{:strs [firstname lastname] :as person} {"firstname" "John" "lastname" "Smith"}
{:syms [firstname lastname] :as person} {'firstname "John" 'lastname "Smith"}
;; firstname = John, lastname = Smith, person = {:firstname "John" :lastname "Smith"}
;; maps destructuring with different local vars names
{name :firstname family-name :lastname :as person} {:firstname "John" :lastname "Smith"}
;; name = John, family-name = Smith, person = {:firstname "John" :lastname "Smith"}
;; default values
{:keys [firstname lastname] :as person
:or {firstname "Jane" :lastname "Bloggs"}} {:firstname "John"}
;; firstname = John, lastname = Bloggs, person = {:firstname "John"}
;; nested destructuring
[[x1 y1] [x2 y2] [_ _ z]] [[2 3] [5 6] [9 8 7]]
;; x1 = 2, y1 = 3, x2 = 5, y2 = 6, z = 7
{:keys [firstname lastname]
{:keys [phone]} :contact} {:firstname "John" :lastname "Smith" :contact {:phone "0987654321"}}
;; firstname = John, lastname = Smith, phone = 0987654321
;; namespaced keys in maps and sets
{:keys [contact/firstname contact/lastname] :as person} {:contact/firstname "John" :contact/lastname "Smith"}
{:keys [:contact/firstname :contact/lastname] :as person} {:contact/firstname "John" :contact/lastname "Smith"}
{:keys [::firstname ::lastname] :as person} {::firstname "John" ::lastname "Smith"}
{:syms [contact/firstname contact/lastname] :as person} {'contact/firstname "John" 'contact/lastname "Smith"}
;; firstname = John, lastname = Smith, person = {:firstname "John" :lastname "Smith"}
|
35723
|
;; Clojure destructuring cheatsheet.
;; all the following destructuring forms can be used in any of the
;; Clojure's `let` derived bindings such as function's parameters,
;; `let`, `loop`, `binding`, `for`, `doseq`, etc.
;; list, vectors and sequences
[zero _ _ three & four-and-more :as numbers] (range)
{one 1 two 2} [:a :b :c :d :e :f :g]
;; zero = 0, three = 3, four-and-more = (4 5 6 7 ...),
;; numbers = (0 1 2 3 4 5 6 7 ...)
;; one = :b, two = :c
;; maps and sets
{:keys [firstname lastname] :as person} {:firstname "<NAME>" :lastname "Smith"}
{:keys [:firstname :lastname] :as person} {:firstname "<NAME>" :lastname "<NAME>"}
{:strs [firstname lastname] :as person} {"firstname" "<NAME>" "lastname" "Smith"}
{:syms [firstname lastname] :as person} {'firstname "<NAME>" 'lastname "Smith"}
;; firstname = <NAME>, lastname = Smith, person = {:firstname "<NAME>" :lastname "Smith"}
;; maps destructuring with different local vars names
{name :firstname family-name :lastname :as person} {:firstname "<NAME>" :lastname "Smith"}
;; name = <NAME>, family-name = Smith, person = {:firstname "<NAME>" :lastname "Smith"}
;; default values
{:keys [firstname lastname] :as person
:or {firstname "Jane" :lastname "Bloggs"}} {:firstname "<NAME>"}
;; firstname = <NAME>, lastname = Bloggs, person = {:firstname "<NAME>"}
;; nested destructuring
[[x1 y1] [x2 y2] [_ _ z]] [[2 3] [5 6] [9 8 7]]
;; x1 = 2, y1 = 3, x2 = 5, y2 = 6, z = 7
{:keys [firstname lastname]
{:keys [phone]} :contact} {:firstname "<NAME>" :lastname "Smith" :contact {:phone "0987654321"}}
;; firstname = <NAME>, lastname = <NAME>, phone = 0987654321
;; namespaced keys in maps and sets
{:keys [contact/firstname contact/lastname] :as person} {:contact/firstname "<NAME>" :contact/lastname "<NAME>"}
{:keys [:contact/firstname :contact/lastname] :as person} {:contact/firstname "<NAME>" :contact/lastname "<NAME>"}
{:keys [::firstname ::lastname] :as person} {::firstname "<NAME>" ::lastname "<NAME>"}
{:syms [contact/firstname contact/lastname] :as person} {'contact/firstname "<NAME>" 'contact/lastname "<NAME>"}
;; firstname = <NAME>, lastname = <NAME>, person = {:firstname "<NAME>" :lastname "<NAME>"}
| true |
;; Clojure destructuring cheatsheet.
;; all the following destructuring forms can be used in any of the
;; Clojure's `let` derived bindings such as function's parameters,
;; `let`, `loop`, `binding`, `for`, `doseq`, etc.
;; list, vectors and sequences
[zero _ _ three & four-and-more :as numbers] (range)
{one 1 two 2} [:a :b :c :d :e :f :g]
;; zero = 0, three = 3, four-and-more = (4 5 6 7 ...),
;; numbers = (0 1 2 3 4 5 6 7 ...)
;; one = :b, two = :c
;; maps and sets
{:keys [firstname lastname] :as person} {:firstname "PI:NAME:<NAME>END_PI" :lastname "Smith"}
{:keys [:firstname :lastname] :as person} {:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"}
{:strs [firstname lastname] :as person} {"firstname" "PI:NAME:<NAME>END_PI" "lastname" "Smith"}
{:syms [firstname lastname] :as person} {'firstname "PI:NAME:<NAME>END_PI" 'lastname "Smith"}
;; firstname = PI:NAME:<NAME>END_PI, lastname = Smith, person = {:firstname "PI:NAME:<NAME>END_PI" :lastname "Smith"}
;; maps destructuring with different local vars names
{name :firstname family-name :lastname :as person} {:firstname "PI:NAME:<NAME>END_PI" :lastname "Smith"}
;; name = PI:NAME:<NAME>END_PI, family-name = Smith, person = {:firstname "PI:NAME:<NAME>END_PI" :lastname "Smith"}
;; default values
{:keys [firstname lastname] :as person
:or {firstname "Jane" :lastname "Bloggs"}} {:firstname "PI:NAME:<NAME>END_PI"}
;; firstname = PI:NAME:<NAME>END_PI, lastname = Bloggs, person = {:firstname "PI:NAME:<NAME>END_PI"}
;; nested destructuring
[[x1 y1] [x2 y2] [_ _ z]] [[2 3] [5 6] [9 8 7]]
;; x1 = 2, y1 = 3, x2 = 5, y2 = 6, z = 7
{:keys [firstname lastname]
{:keys [phone]} :contact} {:firstname "PI:NAME:<NAME>END_PI" :lastname "Smith" :contact {:phone "0987654321"}}
;; firstname = PI:NAME:<NAME>END_PI, lastname = PI:NAME:<NAME>END_PI, phone = 0987654321
;; namespaced keys in maps and sets
{:keys [contact/firstname contact/lastname] :as person} {:contact/firstname "PI:NAME:<NAME>END_PI" :contact/lastname "PI:NAME:<NAME>END_PI"}
{:keys [:contact/firstname :contact/lastname] :as person} {:contact/firstname "PI:NAME:<NAME>END_PI" :contact/lastname "PI:NAME:<NAME>END_PI"}
{:keys [::firstname ::lastname] :as person} {::firstname "PI:NAME:<NAME>END_PI" ::lastname "PI:NAME:<NAME>END_PI"}
{:syms [contact/firstname contact/lastname] :as person} {'contact/firstname "PI:NAME:<NAME>END_PI" 'contact/lastname "PI:NAME:<NAME>END_PI"}
;; firstname = PI:NAME:<NAME>END_PI, lastname = PI:NAME:<NAME>END_PI, person = {:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI"}
|
[
{
"context": "flatten set)))))\n\n(deftest test-part-*\n (let [s \"Alice would gain 54 happiness units by sitting next to ",
"end": 1041,
"score": 0.9910392165184021,
"start": 1036,
"tag": "NAME",
"value": "Alice"
},
{
"context": "e would gain 54 happiness units by sitting next to Bob.\n Alice would lose 79 happiness units b",
"end": 1094,
"score": 0.9833163619041443,
"start": 1091,
"tag": "NAME",
"value": "Bob"
},
{
"context": "happiness units by sitting next to Bob.\n Alice would lose 79 happiness units by sitting next to ",
"end": 1112,
"score": 0.9797934293746948,
"start": 1107,
"tag": "NAME",
"value": "Alice"
},
{
"context": "e would lose 79 happiness units by sitting next to Carol.\n Alice would lose 2 happiness units by",
"end": 1167,
"score": 0.960362434387207,
"start": 1162,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ppiness units by sitting next to Carol.\n Alice would lose 2 happiness units by sitting next to D",
"end": 1185,
"score": 0.970652163028717,
"start": 1180,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ce would lose 2 happiness units by sitting next to David.\n Bob would gain 83 happiness units by ",
"end": 1239,
"score": 0.9912012815475464,
"start": 1234,
"tag": "NAME",
"value": "David"
},
{
"context": "ppiness units by sitting next to David.\n Bob would gain 83 happiness units by sitting next to ",
"end": 1255,
"score": 0.9754927158355713,
"start": 1252,
"tag": "NAME",
"value": "Bob"
},
{
"context": "b would gain 83 happiness units by sitting next to Alice.\n Bob would lose 7 happiness units by s",
"end": 1310,
"score": 0.9702397584915161,
"start": 1305,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ppiness units by sitting next to Alice.\n Bob would lose 7 happiness units by sitting next to C",
"end": 1326,
"score": 0.9336010813713074,
"start": 1323,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ob would lose 7 happiness units by sitting next to Carol.\n Bob would lose 63 happiness units by ",
"end": 1380,
"score": 0.9570180177688599,
"start": 1375,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ppiness units by sitting next to Carol.\n Bob would lose 63 happiness units by sitting next to ",
"end": 1396,
"score": 0.8896661400794983,
"start": 1393,
"tag": "NAME",
"value": "Bob"
},
{
"context": "b would lose 63 happiness units by sitting next to David.\n Carol would lose 62 happiness units b",
"end": 1451,
"score": 0.9815961718559265,
"start": 1446,
"tag": "NAME",
"value": "David"
},
{
"context": "ppiness units by sitting next to David.\n Carol would lose 62 happiness units by sitting next to ",
"end": 1469,
"score": 0.9326823353767395,
"start": 1464,
"tag": "NAME",
"value": "Carol"
},
{
"context": "l would lose 62 happiness units by sitting next to Alice.\n Carol would gain 60 happiness units b",
"end": 1524,
"score": 0.9720885157585144,
"start": 1519,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ppiness units by sitting next to Alice.\n Carol would gain 60 happiness units by sitting next t",
"end": 1540,
"score": 0.8843293190002441,
"start": 1537,
"tag": "NAME",
"value": "Car"
},
{
"context": "l would gain 60 happiness units by sitting next to Bob.\n Carol would gain 55 happiness units b",
"end": 1595,
"score": 0.9346100091934204,
"start": 1592,
"tag": "NAME",
"value": "Bob"
},
{
"context": "happiness units by sitting next to Bob.\n Carol would gain 55 happiness units by sitting next t",
"end": 1611,
"score": 0.9220525026321411,
"start": 1608,
"tag": "NAME",
"value": "Car"
},
{
"context": "l would gain 55 happiness units by sitting next to David.\n David would gain 46 happiness units b",
"end": 1668,
"score": 0.9854045510292053,
"start": 1663,
"tag": "NAME",
"value": "David"
},
{
"context": "ppiness units by sitting next to David.\n David would gain 46 happiness units by sitting next to ",
"end": 1686,
"score": 0.9522145986557007,
"start": 1681,
"tag": "NAME",
"value": "David"
},
{
"context": "d would gain 46 happiness units by sitting next to Alice.\n David would lose 7 happiness units by",
"end": 1741,
"score": 0.9997610449790955,
"start": 1736,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ppiness units by sitting next to Alice.\n David would lose 7 happiness units by sitting next to B",
"end": 1759,
"score": 0.9996860027313232,
"start": 1754,
"tag": "NAME",
"value": "David"
},
{
"context": "id would lose 7 happiness units by sitting next to Bob.\n David would gain 41 happiness units b",
"end": 1811,
"score": 0.9996863603591919,
"start": 1808,
"tag": "NAME",
"value": "Bob"
},
{
"context": "happiness units by sitting next to Bob.\n David would gain 41 happiness units by sitting next to ",
"end": 1829,
"score": 0.999681830406189,
"start": 1824,
"tag": "NAME",
"value": "David"
},
{
"context": "d would gain 41 happiness units by sitting next to Carol.\"]\n (is (= 330 (part-* (parse s))))))\n",
"end": 1884,
"score": 0.9994997978210449,
"start": 1879,
"tag": "NAME",
"value": "Carol"
}
] |
src/aoc/2015/13.clj
|
callum-oakley/advent-of-code
| 2 |
(ns aoc.2015.13
(:require
[clojure.math.combinatorics :as comb]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(reduce #(let [[_ a b c d]
(re-matches #"\s*(\w+) would (gain|lose) (\d+) .* (\w+)." %2)]
(assoc %1 [a d] (({"gain" + "lose" -} b) (read-string c))))
{}
(str/split-lines s)))
(defn part-* [happiness]
(let [guests (-> happiness keys flatten set)]
(->> (comb/permutations (rest guests))
(map #(->> (concat [(first guests)] % [(first guests)])
(partition 2 1)
(map (fn [[a b]] (+ (happiness [a b]) (happiness [b a]))))
(apply +)))
(apply max))))
(defn part-1 []
(-> "input/2015/13" slurp parse part-*))
(defn part-2 []
(let [happiness (-> "input/2015/13" slurp parse)]
(part-* (reduce #(assoc %1 [:me %2] 0 [%2 :me] 0)
happiness
(-> happiness keys flatten set)))))
(deftest test-part-*
(let [s "Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol."]
(is (= 330 (part-* (parse s))))))
|
107175
|
(ns aoc.2015.13
(:require
[clojure.math.combinatorics :as comb]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(reduce #(let [[_ a b c d]
(re-matches #"\s*(\w+) would (gain|lose) (\d+) .* (\w+)." %2)]
(assoc %1 [a d] (({"gain" + "lose" -} b) (read-string c))))
{}
(str/split-lines s)))
(defn part-* [happiness]
(let [guests (-> happiness keys flatten set)]
(->> (comb/permutations (rest guests))
(map #(->> (concat [(first guests)] % [(first guests)])
(partition 2 1)
(map (fn [[a b]] (+ (happiness [a b]) (happiness [b a]))))
(apply +)))
(apply max))))
(defn part-1 []
(-> "input/2015/13" slurp parse part-*))
(defn part-2 []
(let [happiness (-> "input/2015/13" slurp parse)]
(part-* (reduce #(assoc %1 [:me %2] 0 [%2 :me] 0)
happiness
(-> happiness keys flatten set)))))
(deftest test-part-*
(let [s "<NAME> would gain 54 happiness units by sitting next to <NAME>.
<NAME> would lose 79 happiness units by sitting next to <NAME>.
<NAME> would lose 2 happiness units by sitting next to <NAME>.
<NAME> would gain 83 happiness units by sitting next to <NAME>.
<NAME> would lose 7 happiness units by sitting next to <NAME>.
<NAME> would lose 63 happiness units by sitting next to <NAME>.
<NAME> would lose 62 happiness units by sitting next to <NAME>.
<NAME>ol would gain 60 happiness units by sitting next to <NAME>.
<NAME>ol would gain 55 happiness units by sitting next to <NAME>.
<NAME> would gain 46 happiness units by sitting next to <NAME>.
<NAME> would lose 7 happiness units by sitting next to <NAME>.
<NAME> would gain 41 happiness units by sitting next to <NAME>."]
(is (= 330 (part-* (parse s))))))
| true |
(ns aoc.2015.13
(:require
[clojure.math.combinatorics :as comb]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(reduce #(let [[_ a b c d]
(re-matches #"\s*(\w+) would (gain|lose) (\d+) .* (\w+)." %2)]
(assoc %1 [a d] (({"gain" + "lose" -} b) (read-string c))))
{}
(str/split-lines s)))
(defn part-* [happiness]
(let [guests (-> happiness keys flatten set)]
(->> (comb/permutations (rest guests))
(map #(->> (concat [(first guests)] % [(first guests)])
(partition 2 1)
(map (fn [[a b]] (+ (happiness [a b]) (happiness [b a]))))
(apply +)))
(apply max))))
(defn part-1 []
(-> "input/2015/13" slurp parse part-*))
(defn part-2 []
(let [happiness (-> "input/2015/13" slurp parse)]
(part-* (reduce #(assoc %1 [:me %2] 0 [%2 :me] 0)
happiness
(-> happiness keys flatten set)))))
(deftest test-part-*
(let [s "PI:NAME:<NAME>END_PI would gain 54 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 79 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 2 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would gain 83 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 7 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 63 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 62 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PIol would gain 60 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PIol would gain 55 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would gain 46 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would lose 7 happiness units by sitting next to PI:NAME:<NAME>END_PI.
PI:NAME:<NAME>END_PI would gain 41 happiness units by sitting next to PI:NAME:<NAME>END_PI."]
(is (= 330 (part-* (parse s))))))
|
[
{
"context": "structures\n (:gen-class))\n\n; map\n{:name {:first \"John\" :middle \"Jacob\" :last \"Jingleheimerschmidt\"}}\n\n;",
"end": 72,
"score": 0.9998321533203125,
"start": 68,
"tag": "NAME",
"value": "John"
},
{
"context": "gen-class))\n\n; map\n{:name {:first \"John\" :middle \"Jacob\" :last \"Jingleheimerschmidt\"}}\n\n;vector\n(get [\"a\"",
"end": 88,
"score": 0.9998123645782471,
"start": 83,
"tag": "NAME",
"value": "Jacob"
},
{
"context": " map\n{:name {:first \"John\" :middle \"Jacob\" :last \"Jingleheimerschmidt\"}}\n\n;vector\n(get [\"a\" {:name \"Pugsley Winterbotto",
"end": 116,
"score": 0.9998217821121216,
"start": 97,
"tag": "NAME",
"value": "Jingleheimerschmidt"
},
{
"context": "Jingleheimerschmidt\"}}\n\n;vector\n(get [\"a\" {:name \"Pugsley Winterbottom\"} \"c\"] 1)\n\n(def vectortest [\"a\" {:name \"Pugsley W",
"end": 167,
"score": 0.999832034111023,
"start": 147,
"tag": "NAME",
"value": "Pugsley Winterbottom"
},
{
"context": "terbottom\"} \"c\"] 1)\n\n(def vectortest [\"a\" {:name \"Pugsley Winterbottom\"} \"c\"])\n\n(vectortest 1)\n\n(defn vtest\n [x]\n (vec",
"end": 228,
"score": 0.9998263120651245,
"start": 208,
"tag": "NAME",
"value": "Pugsley Winterbottom"
}
] |
clojure-noob/src/clojure_noob/structures.clj
|
christianzach/chz-clojure
| 0 |
(ns clojure-noob.structures
(:gen-class))
; map
{:name {:first "John" :middle "Jacob" :last "Jingleheimerschmidt"}}
;vector
(get ["a" {:name "Pugsley Winterbottom"} "c"] 1)
(def vectortest ["a" {:name "Pugsley Winterbottom"} "c"])
(vectortest 1)
(defn vtest
[x]
(vectortest x))
(vtest 1)
;list
'(1 2 3 4)
(def listtest '(1 2 3 4) )
(defn getlist []
(nth listtest 1))
(getlist)
;set
;
(hash-set 1 1 2 2)
|
98845
|
(ns clojure-noob.structures
(:gen-class))
; map
{:name {:first "<NAME>" :middle "<NAME>" :last "<NAME>"}}
;vector
(get ["a" {:name "<NAME>"} "c"] 1)
(def vectortest ["a" {:name "<NAME>"} "c"])
(vectortest 1)
(defn vtest
[x]
(vectortest x))
(vtest 1)
;list
'(1 2 3 4)
(def listtest '(1 2 3 4) )
(defn getlist []
(nth listtest 1))
(getlist)
;set
;
(hash-set 1 1 2 2)
| true |
(ns clojure-noob.structures
(:gen-class))
; map
{:name {:first "PI:NAME:<NAME>END_PI" :middle "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}}
;vector
(get ["a" {:name "PI:NAME:<NAME>END_PI"} "c"] 1)
(def vectortest ["a" {:name "PI:NAME:<NAME>END_PI"} "c"])
(vectortest 1)
(defn vtest
[x]
(vectortest x))
(vtest 1)
;list
'(1 2 3 4)
(def listtest '(1 2 3 4) )
(defn getlist []
(nth listtest 1))
(getlist)
;set
;
(hash-set 1 1 2 2)
|
[
{
"context": "e another Dockerfile.\"\n :url \"https://github.com/into-docker/into-docker\"\n :license {:name \"MIT License\"\n ",
"end": 121,
"score": 0.9586073756217957,
"start": 110,
"tag": "USERNAME",
"value": "into-docker"
},
{
"context": "ses/MIT\"\n :year 2020\n :key \"mit\"}\n :dependencies [[org.clojure/clojure \"1.10.2\"]",
"end": 266,
"score": 0.9684665203094482,
"start": 263,
"tag": "KEY",
"value": "mit"
}
] |
project.clj
|
r0man/into-docker
| 0 |
(defproject into "1.0.1-SNAPSHOT"
:description "Never write another Dockerfile."
:url "https://github.com/into-docker/into-docker"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2020
:key "mit"}
:dependencies [[org.clojure/clojure "1.10.2"]
[org.clojure/tools.cli "1.0.194"]
[org.clojure/tools.logging "1.1.0"]
;; components
[lispyclouds/clj-docker-client "1.0.2"]
[unixsocket-http "1.0.8"]
;; utilities
[org.apache.commons/commons-compress "1.20"]
[commons-lang "2.6"]
[potemkin "0.4.5"]
;; logging
[jansi-clj "0.1.1"]
[ch.qos.logback/logback-classic "1.2.3"]
;; cleanup dependency chain
[riddley "0.2.0"]
[org.jetbrains.kotlin/kotlin-stdlib-common "1.4.30"]]
:exclusions [org.clojure/clojure]
:java-source-paths ["src"]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
:plugins [[lein-cljfmt "0.6.7"]]
:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]
[org.clojure/java.classpath "1.0.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]
:uberjar
{:global-vars {*assert* false}
:jvm-opts ["-Dclojure.compiler.direct-linking=true"
"-Dclojure.spec.skip-macros=true"]
:main into.main
:aot :all}}
:cljfmt {:indents {prop/for-all [[:block 1]]
defcomponent [[:block 2] [:inner 1]]}}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
|
88703
|
(defproject into "1.0.1-SNAPSHOT"
:description "Never write another Dockerfile."
:url "https://github.com/into-docker/into-docker"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2020
:key "<KEY>"}
:dependencies [[org.clojure/clojure "1.10.2"]
[org.clojure/tools.cli "1.0.194"]
[org.clojure/tools.logging "1.1.0"]
;; components
[lispyclouds/clj-docker-client "1.0.2"]
[unixsocket-http "1.0.8"]
;; utilities
[org.apache.commons/commons-compress "1.20"]
[commons-lang "2.6"]
[potemkin "0.4.5"]
;; logging
[jansi-clj "0.1.1"]
[ch.qos.logback/logback-classic "1.2.3"]
;; cleanup dependency chain
[riddley "0.2.0"]
[org.jetbrains.kotlin/kotlin-stdlib-common "1.4.30"]]
:exclusions [org.clojure/clojure]
:java-source-paths ["src"]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
:plugins [[lein-cljfmt "0.6.7"]]
:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]
[org.clojure/java.classpath "1.0.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]
:uberjar
{:global-vars {*assert* false}
:jvm-opts ["-Dclojure.compiler.direct-linking=true"
"-Dclojure.spec.skip-macros=true"]
:main into.main
:aot :all}}
:cljfmt {:indents {prop/for-all [[:block 1]]
defcomponent [[:block 2] [:inner 1]]}}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
| true |
(defproject into "1.0.1-SNAPSHOT"
:description "Never write another Dockerfile."
:url "https://github.com/into-docker/into-docker"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:year 2020
:key "PI:KEY:<KEY>END_PI"}
:dependencies [[org.clojure/clojure "1.10.2"]
[org.clojure/tools.cli "1.0.194"]
[org.clojure/tools.logging "1.1.0"]
;; components
[lispyclouds/clj-docker-client "1.0.2"]
[unixsocket-http "1.0.8"]
;; utilities
[org.apache.commons/commons-compress "1.20"]
[commons-lang "2.6"]
[potemkin "0.4.5"]
;; logging
[jansi-clj "0.1.1"]
[ch.qos.logback/logback-classic "1.2.3"]
;; cleanup dependency chain
[riddley "0.2.0"]
[org.jetbrains.kotlin/kotlin-stdlib-common "1.4.30"]]
:exclusions [org.clojure/clojure]
:java-source-paths ["src"]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
:plugins [[lein-cljfmt "0.6.7"]]
:global-vars {*warn-on-reflection* true}}
:kaocha
{:dependencies [[lambdaisland/kaocha "1.0.732"
:exclusions [org.clojure/spec.alpha]]
[lambdaisland/kaocha-cloverage "1.0.75"]
[org.clojure/java.classpath "1.0.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]
:uberjar
{:global-vars {*assert* false}
:jvm-opts ["-Dclojure.compiler.direct-linking=true"
"-Dclojure.spec.skip-macros=true"]
:main into.main
:aot :all}}
:cljfmt {:indents {prop/for-all [[:block 1]]
defcomponent [[:block 2] [:inner 1]]}}
:aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"]
"ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner"
"--reporter" "documentation"
"--plugin" "cloverage"
"--codecov"
"--no-cov-html"]}
:pedantic? :abort)
|
[
{
"context": ";; Copyright 2014 (c) Diego Souza <[email protected]>\n;;\n;; Licensed under the Apache",
"end": 33,
"score": 0.9998750686645508,
"start": 22,
"tag": "NAME",
"value": "Diego Souza"
},
{
"context": ";; Copyright 2014 (c) Diego Souza <[email protected]>\n;;\n;; Licensed under the Apache License, Version",
"end": 50,
"score": 0.9999011158943176,
"start": 35,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/blackbox/src/leela/version.clj
|
locaweb/leela
| 22 |
;; Copyright 2014 (c) Diego Souza <[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.
;;
;; [DO NOT EDIT, AUTOMATICALLY GENERATED BY (./src/scripts/version.sh /home/dsouza/dev/locaweb/leela/src/blackbox/src/leela/version.clj)]
(ns leela.version)
(def major 6)
(def minor 3)
(def patch 0)
(def version "6.3.0")
|
52206
|
;; Copyright 2014 (c) <NAME> <<EMAIL>>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; [DO NOT EDIT, AUTOMATICALLY GENERATED BY (./src/scripts/version.sh /home/dsouza/dev/locaweb/leela/src/blackbox/src/leela/version.clj)]
(ns leela.version)
(def major 6)
(def minor 3)
(def patch 0)
(def version "6.3.0")
| true |
;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; [DO NOT EDIT, AUTOMATICALLY GENERATED BY (./src/scripts/version.sh /home/dsouza/dev/locaweb/leela/src/blackbox/src/leela/version.clj)]
(ns leela.version)
(def major 6)
(def minor 3)
(def patch 0)
(def version "6.3.0")
|
[
{
"context": "t [pacientes {}\n guilherme {:id 15, :nome \"Guilherme\" :nascimento \"18/9/1981\"}\n daniela {:id 20",
"end": 451,
"score": 0.9997850060462952,
"start": 442,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "ento \"18/9/1981\"}\n daniela {:id 20, :nome \"Daniela\" :nascimento \"18/9/1984\"}\n paulo {:nome \"P",
"end": 517,
"score": 0.9997556805610657,
"start": 510,
"tag": "NAME",
"value": "Daniela"
},
{
"context": "a\" :nascimento \"18/9/1984\"}\n paulo {:nome \"Paulo\" :nascimento \"18/10/1983\"}\n ]\n (pprint ",
"end": 571,
"score": 0.9997730851173401,
"start": 566,
"tag": "NAME",
"value": "Paulo"
},
{
"context": "deal para interopilidade\n(println (->Paciente 15 \"Guilherme\" \"18/9/1981\"))\n(pprint (->Paciente 15 \"Guilherme\"",
"end": 1047,
"score": 0.9997470378875732,
"start": 1038,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "\"Guilherme\" \"18/9/1981\"))\n(pprint (->Paciente 15 \"Guilherme\" \"18/9/1981\"))\n(pprint (Paciente. 15 \"Guilherme\" ",
"end": 1096,
"score": 0.999762237071991,
"start": 1087,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": " \"Guilherme\" \"18/9/1981\"))\n(pprint (Paciente. 15 \"Guilherme\" \"18/9/1981\")) \". instancia a classe java, espera",
"end": 1144,
"score": 0.9997957944869995,
"start": 1135,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "um construtor\"\n(pprint (Paciente. 15 \"18/9/1981\" \"Guilherme\"))\n(pprint (Paciente. \"Guilherme\" 15 \"18/9/1981\")",
"end": 1257,
"score": 0.9997028112411499,
"start": 1248,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": " 15 \"18/9/1981\" \"Guilherme\"))\n(pprint (Paciente. \"Guilherme\" 15 \"18/9/1981\"))\n(pprint (Paciente. 15 \"18/9/198",
"end": 1290,
"score": 0.9997767210006714,
"start": 1281,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": " \"18/9/1981\"))\n(pprint (Paciente. 15 \"18/9/1981\" \"Guilherme\"))\n(pprint (map->Paciente {:id 15, :nome \"Guilher",
"end": 1353,
"score": 0.999687671661377,
"start": 1344,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "ilherme\"))\n(pprint (map->Paciente {:id 15, :nome \"Guilherme\" :nascimento \"18/9/1981\"}))\n\n(let [guilherme (->P",
"end": 1405,
"score": 0.9997923970222473,
"start": 1396,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "o \"18/9/1981\"}))\n\n(let [guilherme (->Paciente 15 \"Guilherme\" \"18/9/1981\")]\n (println (:id guilherme))\n (pri",
"end": 1476,
"score": 0.999732255935669,
"start": 1467,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "lação\n )\n\n(pprint (map->Paciente {:id 15, :nome \"Guilherme\" :nascimento \"18/9/1981\" :rg \"2222\"}))\n(pprint (P",
"end": 1778,
"score": 0.9997838735580444,
"start": 1769,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "\"18/9/1981\" :rg \"2222\"}))\n(pprint (Paciente. nil \"Guilherme\" \"18/9/1981\")) ;não permite vazio pois",
"end": 1851,
"score": 0.9997129440307617,
"start": 1842,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "il ou o id de fato\n(pprint (map->Paciente {:nome \"Guilherme\" :nascimento \"18/9/1981\" :rg \"2222\"}))\n\n(pprint (",
"end": 1988,
"score": 0.9997681379318237,
"start": 1979,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "81\" :rg \"2222\"}))\n\n(pprint (assoc (Paciente. nil \"Guilherme\" \"18/9/1981\") :id 38))\n(pprint (class (assoc (Pac",
"end": 2069,
"score": 0.9995254278182983,
"start": 2060,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "\") :id 38))\n(pprint (class (assoc (Paciente. nil \"Guilherme\" \"18/9/1981\") :id 38)))\n\n\n(pprint (= (->Paciente ",
"end": 2140,
"score": 0.9994800090789795,
"start": 2131,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "8/9/1981\") :id 38)))\n\n\n(pprint (= (->Paciente 15 \"Guilherme\" \"18/9/1981\") (->Paciente 15 \"Guilherme\" \"18/9/19",
"end": 2203,
"score": 0.9997748136520386,
"start": 2194,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "iente 15 \"Guilherme\" \"18/9/1981\") (->Paciente 15 \"Guilherme\" \"18/9/1981\")))\n(pprint (= (->Paciente 153 \"Guilh",
"end": 2243,
"score": 0.9996703267097473,
"start": 2234,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "herme\" \"18/9/1981\")))\n(pprint (= (->Paciente 153 \"Guilherme\" \"18/9/1981\") (->Paciente 15 \"Guilherme\" \"18/9/19",
"end": 2297,
"score": 0.9997250437736511,
"start": 2288,
"tag": "NAME",
"value": "Guilherme"
},
{
"context": "ente 153 \"Guilherme\" \"18/9/1981\") (->Paciente 15 \"Guilherme\" \"18/9/1981\")))\n\n\n\n\n\n\n\n\n\n\n\n\n",
"end": 2337,
"score": 0.9995660185813904,
"start": 2328,
"tag": "NAME",
"value": "Guilherme"
}
] |
curso4/src/hospital/aula1.clj
|
Caporiccii/Clojure-Class
| 0 |
(ns hospital.aula1
(:use clojure.pprint))
(defn adiciona-paciente
"os pacientes são um mapa"
[pacientes paciente]
(if-let [id (:id paciente)]
(assoc pacientes id paciente)
(throw (ex-info "Paciente não possui id" {:paciente paciente}))))
;if-let já executa caso o let seja verdadeiro, caso não ele retorna a
; exception ou outro tratamento
(defn testa-uso-pacientes []
(let [pacientes {}
guilherme {:id 15, :nome "Guilherme" :nascimento "18/9/1981"}
daniela {:id 20, :nome "Daniela" :nascimento "18/9/1984"}
paulo {:nome "Paulo" :nascimento "18/10/1983"}
]
(pprint (adiciona-paciente pacientes guilherme))
(pprint (adiciona-paciente pacientes daniela))
(pprint (adiciona-paciente pacientes paulo))
))
;(testa-uso-pacientes)
(defrecord Paciente [id nome nascimento]) "interopabilidade, poder trampar com oo quando preciso e agregar simbolos"
; ^String posso forçar para o cluje que seja uma string apenas
;defrecord é ideal para interopilidade
(println (->Paciente 15 "Guilherme" "18/9/1981"))
(pprint (->Paciente 15 "Guilherme" "18/9/1981"))
(pprint (Paciente. 15 "Guilherme" "18/9/1981")) ". instancia a classe java, esperando um construtor"
(pprint (Paciente. 15 "18/9/1981" "Guilherme"))
(pprint (Paciente. "Guilherme" 15 "18/9/1981"))
(pprint (Paciente. 15 "18/9/1981" "Guilherme"))
(pprint (map->Paciente {:id 15, :nome "Guilherme" :nascimento "18/9/1981"}))
(let [guilherme (->Paciente 15 "Guilherme" "18/9/1981")]
(println (:id guilherme))
(println (vals guilherme))
(println (record? guilherme))
(println (.nome guilherme)) ; chama o campo nome do java, teoricamente mais rapido. bind em tempo de compilação
)
(pprint (map->Paciente {:id 15, :nome "Guilherme" :nascimento "18/9/1981" :rg "2222"}))
(pprint (Paciente. nil "Guilherme" "18/9/1981")) ;não permite vazio pois já reclama da aridade, só nil ou o id de fato
(pprint (map->Paciente {:nome "Guilherme" :nascimento "18/9/1981" :rg "2222"}))
(pprint (assoc (Paciente. nil "Guilherme" "18/9/1981") :id 38))
(pprint (class (assoc (Paciente. nil "Guilherme" "18/9/1981") :id 38)))
(pprint (= (->Paciente 15 "Guilherme" "18/9/1981") (->Paciente 15 "Guilherme" "18/9/1981")))
(pprint (= (->Paciente 153 "Guilherme" "18/9/1981") (->Paciente 15 "Guilherme" "18/9/1981")))
|
68540
|
(ns hospital.aula1
(:use clojure.pprint))
(defn adiciona-paciente
"os pacientes são um mapa"
[pacientes paciente]
(if-let [id (:id paciente)]
(assoc pacientes id paciente)
(throw (ex-info "Paciente não possui id" {:paciente paciente}))))
;if-let já executa caso o let seja verdadeiro, caso não ele retorna a
; exception ou outro tratamento
(defn testa-uso-pacientes []
(let [pacientes {}
guilherme {:id 15, :nome "<NAME>" :nascimento "18/9/1981"}
daniela {:id 20, :nome "<NAME>" :nascimento "18/9/1984"}
paulo {:nome "<NAME>" :nascimento "18/10/1983"}
]
(pprint (adiciona-paciente pacientes guilherme))
(pprint (adiciona-paciente pacientes daniela))
(pprint (adiciona-paciente pacientes paulo))
))
;(testa-uso-pacientes)
(defrecord Paciente [id nome nascimento]) "interopabilidade, poder trampar com oo quando preciso e agregar simbolos"
; ^String posso forçar para o cluje que seja uma string apenas
;defrecord é ideal para interopilidade
(println (->Paciente 15 "<NAME>" "18/9/1981"))
(pprint (->Paciente 15 "<NAME>" "18/9/1981"))
(pprint (Paciente. 15 "<NAME>" "18/9/1981")) ". instancia a classe java, esperando um construtor"
(pprint (Paciente. 15 "18/9/1981" "<NAME>"))
(pprint (Paciente. "<NAME>" 15 "18/9/1981"))
(pprint (Paciente. 15 "18/9/1981" "<NAME>"))
(pprint (map->Paciente {:id 15, :nome "<NAME>" :nascimento "18/9/1981"}))
(let [guilherme (->Paciente 15 "<NAME>" "18/9/1981")]
(println (:id guilherme))
(println (vals guilherme))
(println (record? guilherme))
(println (.nome guilherme)) ; chama o campo nome do java, teoricamente mais rapido. bind em tempo de compilação
)
(pprint (map->Paciente {:id 15, :nome "<NAME>" :nascimento "18/9/1981" :rg "2222"}))
(pprint (Paciente. nil "<NAME>" "18/9/1981")) ;não permite vazio pois já reclama da aridade, só nil ou o id de fato
(pprint (map->Paciente {:nome "<NAME>" :nascimento "18/9/1981" :rg "2222"}))
(pprint (assoc (Paciente. nil "<NAME>" "18/9/1981") :id 38))
(pprint (class (assoc (Paciente. nil "<NAME>" "18/9/1981") :id 38)))
(pprint (= (->Paciente 15 "<NAME>" "18/9/1981") (->Paciente 15 "<NAME>" "18/9/1981")))
(pprint (= (->Paciente 153 "<NAME>" "18/9/1981") (->Paciente 15 "<NAME>" "18/9/1981")))
| true |
(ns hospital.aula1
(:use clojure.pprint))
(defn adiciona-paciente
"os pacientes são um mapa"
[pacientes paciente]
(if-let [id (:id paciente)]
(assoc pacientes id paciente)
(throw (ex-info "Paciente não possui id" {:paciente paciente}))))
;if-let já executa caso o let seja verdadeiro, caso não ele retorna a
; exception ou outro tratamento
(defn testa-uso-pacientes []
(let [pacientes {}
guilherme {:id 15, :nome "PI:NAME:<NAME>END_PI" :nascimento "18/9/1981"}
daniela {:id 20, :nome "PI:NAME:<NAME>END_PI" :nascimento "18/9/1984"}
paulo {:nome "PI:NAME:<NAME>END_PI" :nascimento "18/10/1983"}
]
(pprint (adiciona-paciente pacientes guilherme))
(pprint (adiciona-paciente pacientes daniela))
(pprint (adiciona-paciente pacientes paulo))
))
;(testa-uso-pacientes)
(defrecord Paciente [id nome nascimento]) "interopabilidade, poder trampar com oo quando preciso e agregar simbolos"
; ^String posso forçar para o cluje que seja uma string apenas
;defrecord é ideal para interopilidade
(println (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981"))
(pprint (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981"))
(pprint (Paciente. 15 "PI:NAME:<NAME>END_PI" "18/9/1981")) ". instancia a classe java, esperando um construtor"
(pprint (Paciente. 15 "18/9/1981" "PI:NAME:<NAME>END_PI"))
(pprint (Paciente. "PI:NAME:<NAME>END_PI" 15 "18/9/1981"))
(pprint (Paciente. 15 "18/9/1981" "PI:NAME:<NAME>END_PI"))
(pprint (map->Paciente {:id 15, :nome "PI:NAME:<NAME>END_PI" :nascimento "18/9/1981"}))
(let [guilherme (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981")]
(println (:id guilherme))
(println (vals guilherme))
(println (record? guilherme))
(println (.nome guilherme)) ; chama o campo nome do java, teoricamente mais rapido. bind em tempo de compilação
)
(pprint (map->Paciente {:id 15, :nome "PI:NAME:<NAME>END_PI" :nascimento "18/9/1981" :rg "2222"}))
(pprint (Paciente. nil "PI:NAME:<NAME>END_PI" "18/9/1981")) ;não permite vazio pois já reclama da aridade, só nil ou o id de fato
(pprint (map->Paciente {:nome "PI:NAME:<NAME>END_PI" :nascimento "18/9/1981" :rg "2222"}))
(pprint (assoc (Paciente. nil "PI:NAME:<NAME>END_PI" "18/9/1981") :id 38))
(pprint (class (assoc (Paciente. nil "PI:NAME:<NAME>END_PI" "18/9/1981") :id 38)))
(pprint (= (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981") (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981")))
(pprint (= (->Paciente 153 "PI:NAME:<NAME>END_PI" "18/9/1981") (->Paciente 15 "PI:NAME:<NAME>END_PI" "18/9/1981")))
|
[
{
"context": "; Copyright 2016 David O'Meara\n;\n; Licensed under the Apache License, Version 2.",
"end": 30,
"score": 0.9998533129692078,
"start": 17,
"tag": "NAME",
"value": "David O'Meara"
}
] |
src-cljs/ui/utils.cljs
|
davidomeara/fnedit
| 0 |
; Copyright 2016 David O'Meara
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns ui.utils
(:require [clojure.set :as set]))
(defn toggle [s v]
(if (contains? s v)
(disj s v)
(set/union s #{v})))
|
74898
|
; Copyright 2016 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns ui.utils
(:require [clojure.set :as set]))
(defn toggle [s v]
(if (contains? s v)
(disj s v)
(set/union s #{v})))
| true |
; Copyright 2016 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns ui.utils
(:require [clojure.set :as set]))
(defn toggle [s v]
(if (contains? s v)
(disj s v)
(set/union s #{v})))
|
[
{
"context": "e-auth]))\n\n(defonce firebase-app-info\n {:apiKey \"AIzaSyDrq5xXw3h9hNJfFmH2x1cprsQ165PYe28\"\n :authDomain \"rolling-rules.firebaseapp.com\"\n ",
"end": 270,
"score": 0.9997547268867493,
"start": 231,
"tag": "KEY",
"value": "AIzaSyDrq5xXw3h9hNJfFmH2x1cprsQ165PYe28"
},
{
"context": "se/email-sign-in {:email temp-email :password temp-password}\n :db (dissoc db :firebase/temp-email :fireb",
"end": 2902,
"score": 0.6276857852935791,
"start": 2894,
"tag": "PASSWORD",
"value": "password"
}
] |
src/rolling_rules/firebase.cljs
|
jahenderson777/rolling-rules
| 0 |
(ns rolling-rules.firebase
(:require [clojure.string :as str]
[xframe.core.alpha :as xf]
["firebase" :as firebase]
["firebase/auth" :as firebase-auth]))
(defonce firebase-app-info
{:apiKey "AIzaSyDrq5xXw3h9hNJfFmH2x1cprsQ165PYe28"
:authDomain "rolling-rules.firebaseapp.com"
:databaseURL "https://rolling-rules.firebaseio.com"
:projectId "rolling-rules"
:storageBucket "rolling-rules.appspot.com"
:messagingSenderId "725862460631"
:appId "1:725862460631:web:35f5e63a6a79565c8e5492"})
(defn- user [firebase-user]
(when firebase-user
{:uid (.-uid firebase-user)
:provider-data (.-providerData firebase-user)
:display-name (.-displayName firebase-user)
:photo-url (.-photoURL firebase-user)
:email (or (.-email firebase-user)
(let [provider-data (.-providerData firebase-user)]
(when-not (empty? provider-data)
(-> provider-data first .-email))))}))
(defn- default-error-handler [error]
(println "Error: " error))
(defn- set-user [firebase-user]
(println "called set-user")
(xf/dispatch [:set [:firebase/user] (user firebase-user)]))
(defn init []
(defonce _init
(do
(firebase/initializeApp (clj->js firebase-app-info))
(.. firebase auth (onAuthStateChanged set-user default-error-handler))
(let [RecaptchaVerifier (.. firebase -auth -RecaptchaVerifier)
recaptcha (RecaptchaVerifier.
"Phone"
(clj->js {:size "invisible"
:callback #(xf/dispatch [:set [:firebase/captcha-msg] "Welcome Human"])}))]
(xf/dispatch [:set [:firebase/recaptcha-verifier] recaptcha])))))
(defn email-create-user [_ [_ {:keys [email password]}]]
(.. firebase auth (createUserWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-create-user email-create-user)
(xf/reg-event-fx
:firebase/email-create-user
(fn [db _]
(let [{:firebase/keys [temp-email temp-password temp-password-confirm]} db]
{:firebase/email-create-user {:email temp-email :password temp-password}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn email-sign-in [_ [_ {:keys [email password]}]]
(.. firebase auth (signInWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-sign-in email-sign-in)
(xf/reg-event-fx
:firebase/email-sign-in
(fn [db _]
(let [{:firebase/keys [temp-email temp-password]} db]
{:firebase/email-sign-in {:email temp-email :password temp-password}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn sign-out [_ _]
(.. firebase auth (signOut)
(catch default-error-handler)))
(xf/reg-fx :firebase/sign-out sign-out)
(xf/reg-event-fx :firebase/sign-out (fn [_ _] {:firebase/sign-out true}))
(defn phone-sign-in [{:firebase/keys [temp-phone recaptcha-verifier] :as db} _]
(let [phone-number (str/replace-first temp-phone #"^[0]+" "+44")]
(if recaptcha-verifier
(.. firebase auth
(signInWithPhoneNumber phone-number recaptcha-verifier)
(then (fn [confirmation]
(xf/dispatch [:set [:firebase/sms-sent] true])
(xf/dispatch [:set [:firebase/recaptcha-confirmation-result] confirmation])))
(catch default-error-handler))
(.warn js/console "Initialise reCaptcha first"))))
(xf/reg-fx :firebase/phone-sign-in phone-sign-in)
(xf/reg-event-fx :firebase/phone-sign-in (fn [_ _] {:firebase/phone-sign-in true}))
(defn phone-confirm-code [{:firebase/keys [recaptcha-confirmation-result temp-sms-code] :as db} _]
(if [recaptcha-confirmation-result]
(.. recaptcha-confirmation-result
(confirm temp-sms-code)
(then set-user)
(catch default-error-handler))
(.warn js/console "reCaptcha confirmation missing")))
(xf/reg-fx :firebase/phone-confirm-code phone-confirm-code)
(xf/reg-event-fx :firebase/phone-confirm-code (fn [_ _] {:firebase/phone-confirm-code true}))
(defn send-password-reset-email [_ [_ {:keys [email on-complete]}]]
(.. firebase auth
(sendPasswordResetEmail email)
(then on-complete)
(catch default-error-handler)))
(xf/reg-fx :firebase/send-password-reset-email send-password-reset-email)
(xf/reg-event-fx
:firebase/send-password-reset-email
(fn [db _]
(let [{:firebase/keys [temp-email]} db]
{:firebase/send-password-reset-email {:email temp-email
:on-complete #(js/alert "Password reset email sent")}})))
(comment
(.doc (.firestore firebase)
(str/join "/" (clj->js path)))
(.. firebase firestore
(doc (str/join "/" (clj->js path)))
(onSnapshot)))
(defn collection-on-snapshot [path f]
(.. firebase firestore
(collection (str/join "/" path))
(onSnapshot (fn [querySnapshot]
(f (for [doc (js->clj (.-docs querySnapshot))]
(js->clj (.data doc))))))))
|
77782
|
(ns rolling-rules.firebase
(:require [clojure.string :as str]
[xframe.core.alpha :as xf]
["firebase" :as firebase]
["firebase/auth" :as firebase-auth]))
(defonce firebase-app-info
{:apiKey "<KEY>"
:authDomain "rolling-rules.firebaseapp.com"
:databaseURL "https://rolling-rules.firebaseio.com"
:projectId "rolling-rules"
:storageBucket "rolling-rules.appspot.com"
:messagingSenderId "725862460631"
:appId "1:725862460631:web:35f5e63a6a79565c8e5492"})
(defn- user [firebase-user]
(when firebase-user
{:uid (.-uid firebase-user)
:provider-data (.-providerData firebase-user)
:display-name (.-displayName firebase-user)
:photo-url (.-photoURL firebase-user)
:email (or (.-email firebase-user)
(let [provider-data (.-providerData firebase-user)]
(when-not (empty? provider-data)
(-> provider-data first .-email))))}))
(defn- default-error-handler [error]
(println "Error: " error))
(defn- set-user [firebase-user]
(println "called set-user")
(xf/dispatch [:set [:firebase/user] (user firebase-user)]))
(defn init []
(defonce _init
(do
(firebase/initializeApp (clj->js firebase-app-info))
(.. firebase auth (onAuthStateChanged set-user default-error-handler))
(let [RecaptchaVerifier (.. firebase -auth -RecaptchaVerifier)
recaptcha (RecaptchaVerifier.
"Phone"
(clj->js {:size "invisible"
:callback #(xf/dispatch [:set [:firebase/captcha-msg] "Welcome Human"])}))]
(xf/dispatch [:set [:firebase/recaptcha-verifier] recaptcha])))))
(defn email-create-user [_ [_ {:keys [email password]}]]
(.. firebase auth (createUserWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-create-user email-create-user)
(xf/reg-event-fx
:firebase/email-create-user
(fn [db _]
(let [{:firebase/keys [temp-email temp-password temp-password-confirm]} db]
{:firebase/email-create-user {:email temp-email :password temp-password}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn email-sign-in [_ [_ {:keys [email password]}]]
(.. firebase auth (signInWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-sign-in email-sign-in)
(xf/reg-event-fx
:firebase/email-sign-in
(fn [db _]
(let [{:firebase/keys [temp-email temp-password]} db]
{:firebase/email-sign-in {:email temp-email :password temp-<PASSWORD>}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn sign-out [_ _]
(.. firebase auth (signOut)
(catch default-error-handler)))
(xf/reg-fx :firebase/sign-out sign-out)
(xf/reg-event-fx :firebase/sign-out (fn [_ _] {:firebase/sign-out true}))
(defn phone-sign-in [{:firebase/keys [temp-phone recaptcha-verifier] :as db} _]
(let [phone-number (str/replace-first temp-phone #"^[0]+" "+44")]
(if recaptcha-verifier
(.. firebase auth
(signInWithPhoneNumber phone-number recaptcha-verifier)
(then (fn [confirmation]
(xf/dispatch [:set [:firebase/sms-sent] true])
(xf/dispatch [:set [:firebase/recaptcha-confirmation-result] confirmation])))
(catch default-error-handler))
(.warn js/console "Initialise reCaptcha first"))))
(xf/reg-fx :firebase/phone-sign-in phone-sign-in)
(xf/reg-event-fx :firebase/phone-sign-in (fn [_ _] {:firebase/phone-sign-in true}))
(defn phone-confirm-code [{:firebase/keys [recaptcha-confirmation-result temp-sms-code] :as db} _]
(if [recaptcha-confirmation-result]
(.. recaptcha-confirmation-result
(confirm temp-sms-code)
(then set-user)
(catch default-error-handler))
(.warn js/console "reCaptcha confirmation missing")))
(xf/reg-fx :firebase/phone-confirm-code phone-confirm-code)
(xf/reg-event-fx :firebase/phone-confirm-code (fn [_ _] {:firebase/phone-confirm-code true}))
(defn send-password-reset-email [_ [_ {:keys [email on-complete]}]]
(.. firebase auth
(sendPasswordResetEmail email)
(then on-complete)
(catch default-error-handler)))
(xf/reg-fx :firebase/send-password-reset-email send-password-reset-email)
(xf/reg-event-fx
:firebase/send-password-reset-email
(fn [db _]
(let [{:firebase/keys [temp-email]} db]
{:firebase/send-password-reset-email {:email temp-email
:on-complete #(js/alert "Password reset email sent")}})))
(comment
(.doc (.firestore firebase)
(str/join "/" (clj->js path)))
(.. firebase firestore
(doc (str/join "/" (clj->js path)))
(onSnapshot)))
(defn collection-on-snapshot [path f]
(.. firebase firestore
(collection (str/join "/" path))
(onSnapshot (fn [querySnapshot]
(f (for [doc (js->clj (.-docs querySnapshot))]
(js->clj (.data doc))))))))
| true |
(ns rolling-rules.firebase
(:require [clojure.string :as str]
[xframe.core.alpha :as xf]
["firebase" :as firebase]
["firebase/auth" :as firebase-auth]))
(defonce firebase-app-info
{:apiKey "PI:KEY:<KEY>END_PI"
:authDomain "rolling-rules.firebaseapp.com"
:databaseURL "https://rolling-rules.firebaseio.com"
:projectId "rolling-rules"
:storageBucket "rolling-rules.appspot.com"
:messagingSenderId "725862460631"
:appId "1:725862460631:web:35f5e63a6a79565c8e5492"})
(defn- user [firebase-user]
(when firebase-user
{:uid (.-uid firebase-user)
:provider-data (.-providerData firebase-user)
:display-name (.-displayName firebase-user)
:photo-url (.-photoURL firebase-user)
:email (or (.-email firebase-user)
(let [provider-data (.-providerData firebase-user)]
(when-not (empty? provider-data)
(-> provider-data first .-email))))}))
(defn- default-error-handler [error]
(println "Error: " error))
(defn- set-user [firebase-user]
(println "called set-user")
(xf/dispatch [:set [:firebase/user] (user firebase-user)]))
(defn init []
(defonce _init
(do
(firebase/initializeApp (clj->js firebase-app-info))
(.. firebase auth (onAuthStateChanged set-user default-error-handler))
(let [RecaptchaVerifier (.. firebase -auth -RecaptchaVerifier)
recaptcha (RecaptchaVerifier.
"Phone"
(clj->js {:size "invisible"
:callback #(xf/dispatch [:set [:firebase/captcha-msg] "Welcome Human"])}))]
(xf/dispatch [:set [:firebase/recaptcha-verifier] recaptcha])))))
(defn email-create-user [_ [_ {:keys [email password]}]]
(.. firebase auth (createUserWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-create-user email-create-user)
(xf/reg-event-fx
:firebase/email-create-user
(fn [db _]
(let [{:firebase/keys [temp-email temp-password temp-password-confirm]} db]
{:firebase/email-create-user {:email temp-email :password temp-password}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn email-sign-in [_ [_ {:keys [email password]}]]
(.. firebase auth (signInWithEmailAndPassword email password)
(then (fn [user-credential]
(set-user (.-user user-credential))))
(catch default-error-handler)))
(xf/reg-fx :firebase/email-sign-in email-sign-in)
(xf/reg-event-fx
:firebase/email-sign-in
(fn [db _]
(let [{:firebase/keys [temp-email temp-password]} db]
{:firebase/email-sign-in {:email temp-email :password temp-PI:PASSWORD:<PASSWORD>END_PI}
:db (dissoc db :firebase/temp-email :firebase/temp-password :firebase/temp-password-confirm :firebase/temp-name)})))
(defn sign-out [_ _]
(.. firebase auth (signOut)
(catch default-error-handler)))
(xf/reg-fx :firebase/sign-out sign-out)
(xf/reg-event-fx :firebase/sign-out (fn [_ _] {:firebase/sign-out true}))
(defn phone-sign-in [{:firebase/keys [temp-phone recaptcha-verifier] :as db} _]
(let [phone-number (str/replace-first temp-phone #"^[0]+" "+44")]
(if recaptcha-verifier
(.. firebase auth
(signInWithPhoneNumber phone-number recaptcha-verifier)
(then (fn [confirmation]
(xf/dispatch [:set [:firebase/sms-sent] true])
(xf/dispatch [:set [:firebase/recaptcha-confirmation-result] confirmation])))
(catch default-error-handler))
(.warn js/console "Initialise reCaptcha first"))))
(xf/reg-fx :firebase/phone-sign-in phone-sign-in)
(xf/reg-event-fx :firebase/phone-sign-in (fn [_ _] {:firebase/phone-sign-in true}))
(defn phone-confirm-code [{:firebase/keys [recaptcha-confirmation-result temp-sms-code] :as db} _]
(if [recaptcha-confirmation-result]
(.. recaptcha-confirmation-result
(confirm temp-sms-code)
(then set-user)
(catch default-error-handler))
(.warn js/console "reCaptcha confirmation missing")))
(xf/reg-fx :firebase/phone-confirm-code phone-confirm-code)
(xf/reg-event-fx :firebase/phone-confirm-code (fn [_ _] {:firebase/phone-confirm-code true}))
(defn send-password-reset-email [_ [_ {:keys [email on-complete]}]]
(.. firebase auth
(sendPasswordResetEmail email)
(then on-complete)
(catch default-error-handler)))
(xf/reg-fx :firebase/send-password-reset-email send-password-reset-email)
(xf/reg-event-fx
:firebase/send-password-reset-email
(fn [db _]
(let [{:firebase/keys [temp-email]} db]
{:firebase/send-password-reset-email {:email temp-email
:on-complete #(js/alert "Password reset email sent")}})))
(comment
(.doc (.firestore firebase)
(str/join "/" (clj->js path)))
(.. firebase firestore
(doc (str/join "/" (clj->js path)))
(onSnapshot)))
(defn collection-on-snapshot [path f]
(.. firebase firestore
(collection (str/join "/" path))
(onSnapshot (fn [querySnapshot]
(f (for [doc (js->clj (.-docs querySnapshot))]
(js->clj (.data doc))))))))
|
[
{
"context": " an Event from an Action\"\n (let [source-token \"SOURCE_TOKEN\"\n subject-url \"https://blog.com/1234\"\n ",
"end": 438,
"score": 0.7631062865257263,
"start": 426,
"tag": "KEY",
"value": "SOURCE_TOKEN"
},
{
"context": "license field if present\"\n (let [source-token \"SOURCE_TOKEN\"\n subject-url \"https://blog.com/1234\"\n ",
"end": 2176,
"score": 0.8258965611457825,
"start": 2164,
"tag": "KEY",
"value": "SOURCE_TOKEN"
},
{
"context": "nse field if not present\"\n (let [source-token \"SOURCE_TOKEN\"\n subject-url \"https://blog.com/1234\"\n ",
"end": 3250,
"score": 0.8496798872947693,
"start": 3238,
"tag": "KEY",
"value": "SOURCE_TOKEN"
}
] |
test/event_data_percolator/action_test.clj
|
CrossRef/event-data-percolator
| 2 |
(ns event-data-percolator.action-test
"Tests for action"
(:require [clojure.test :refer :all]
[clj-time.core :as clj-time]
[org.httpkit.fake :as fake]
[event-data-percolator.action :as action]
[event-data-percolator.test-util :as util]))
(deftest ^:unit create-event-from-match
(testing "create-event-from-match can build an Event from an Action"
(let [source-token "SOURCE_TOKEN"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:obj_id result) object-doi) "Match URL should be output as obj_id")
(is (= (:source_token result) source-token) "Source token should be taken from Evidence Record")
(is (= (:occurred_at result) "2016-02-05") "Occurred at should be taken from the Action")
(is (= (:subj_id result) subject-url) "Subject URL should be taken from the Action")
(is (:id result) "ID is assigned")
(is (:action result) "Action is assigned")
(is (= (-> result :subj :pid) subject-url) "Subject URL should be taken from the Action")
(is (= (-> result :obj :pid) object-doi) "The match DOI should be included as the obj metadata PID ")
(is (= (-> result :obj :url) object-url) "The match input URL should be included as the obj metadata PID")
(is (= (:relation_type_id result) "cites") "Relation type id is taken from the Action")))
(testing "create-event-from-match adds license field if present"
(let [source-token "SOURCE_TOKEN"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]
:license "https://creativecommons.org/publicdomain/zero/1.0/"}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:license result) "https://creativecommons.org/publicdomain/zero/1.0/") "License field present")))
(testing "create-event-from-match does not add license field if not present"
(let [source-token "SOURCE_TOKEN"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (not (contains? result :license)) "License field not present (not just nil)"))))
; This behaviour allows consumers to tell the difference between DOIs that were matched from an input URL (e.g. landing page)
; and those that were referenced directly with the DOI.
(deftest ^:unit create-event-from-match-subj-urls
(let [; A match where there was an input-url
match1 {:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}
; A match where there wasn't.
match2 {:match "https://dx.doi.org/10.5555/12345678"}
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:pages [{:actions [input-action]}]}
result1 (action/create-event-from-match evidence-record input-action match1)
result2 (action/create-event-from-match evidence-record input-action match2)]
(testing "create-event-from-match will take the input URL as the event URL from the match where there is one"
(is (= (-> result1 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result1 :obj :url) "http://psychoceramics.labs.crossref.org/12345")))
(testing "create-event-from-match will take the DOI URL as the event URL from the match where there is no input url"
(is (= (-> result2 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result2 :obj :url) "https://dx.doi.org/10.5555/12345678")))))
(deftest ^:unit create-events-for-action
(testing "When there are are extra Events but there was no match, no Events should be emitted."
(let [extra-events [{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; no matches
:matches []
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (empty? (:events result-action)) "No Events should have been emitted.")))
(testing "When there are are extra Events and there was at least one match, those Extra Events should be emitted, with the requisite fields."
(let [extra-events [; These Events have minimal fields.
{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 3) "Three Events should have been emitted, one from the match and two from the extras.")
; compare with out :id field, that's random.
(is (= (set (map #(dissoc % :id) (:events result-action)))
#{{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}
; Emitted ones have :id, :evidence_record, :action, :source_id added
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}}))))
(testing "When there are are no extra Events but there were matches, an Event should be created for each match"
(let [input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
; no extra events
:extra-events []}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 1) "One Events should have been emitted, from the match.")
(is (= (map #(dissoc % :id) (:events result-action))
[{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}])))))
(deftest ^:unit dedupe-by-val-substring
(testing "dedupe-by-val-substring removes all matches that are a substring of any other in the group."
(is (= (action/dedupe-by-val-substring [{:value "1"} {:value "1234"} {:value "12"} {:value "oops"}])
[{:value "1234"} {:value "oops"}])
"Substrings should be removed. Non-dupes should be untouched")))
(deftest ^:unit dedupe-matches
(testing "When there are duplicate matches that represent the same thing match-candidates should de-duplicate them.
See event-data-percolator.observation-types.html-test/html-with-duplicates for when this might occur."
(let [input-action {:matches [; This should be removed because the matched DOI is a duplicate of another one and the value is a substring of another.
{:type :plain-doi :value "10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be removed because the matche DOI is a duplicate of another one, as is the value, and :doi-urls are prioritised.
{:type :landing-page-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be retained because its' the only one left of the duplicates and it's prioritised.
{:type :doi-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This has the same matched DOI, but is different in that it came from a landing page. Should be retained.
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
; And something that's not a duplicate, so should be retained.
{:type :doi-url :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
expected-result {:matches [{:type :doi-url, :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
{:type :doi-url, :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
result (action/dedupe-matches util/mock-context util/mock-evidence-record input-action)]
(is (= result expected-result)))))
(deftest ^:unit canonical-url-for-action
(testing "Can detect the first canonical url in any input observation."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect the first canonical fron any type."
; Could be from :content-url or :html
(let [input-action {:processed-observations
[{:type :doesnt-matter :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect multiple found canonical URLs if they are identical."
; We don't expect this ever to happen.
; But if it does, and they are identical, that's fine because there's no ambiguity.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Ignores duplicate different found canonical URLs if they are not identical."
; We don't expect this ever to happen.
; But it if does, that's ambiguous, so return nothing.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/no-I-am"}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when nil found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url nil}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when none found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url}]}]
(is (= (action/canonical-url-for-action input-action) nil)))))
(deftest ^:unit final-url-for-action
(testing "final-url-for-action can retrieve the final-url from the first observation's :final-url value"
(let [input-action {:processed-observations
[{:input-url "http://example.com" :final-url "http://sandwiches.com"}]}]
(is (= (action/final-url-for-action input-action) "http://sandwiches.com")))))
(deftest ^:unit best-subj-url-for-action
(testing "best-subj-url-for-action should choose canonical URL as first choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :canonical-url "http://alpha.com/canonical"}]
:final-url "http://beta.com/xyz"
:url "http://gamma.com/abcdefg"})
"http://alpha.com/canonical")))
(testing "best-subj-url-for-action should choose final-url as second choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz?utm_keyword=sandwiches"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
"Cursory check to ensure that tracking params are removed when using the 'final' url.")
(testing "best-subj-url-for-action should choose action URL as third choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg"})
"http://gamma.com/abcdefg"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches"})
"http://gamma.com/abcdefg")
"Cursory check to ensure that tracking params are removed when using the action URL")
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches&colour=indigo"})
"http://gamma.com/abcdefg?colour=indigo")
"Cursory check to ensure that tracking params are removed when using the action URL")))
(deftest ^:unit best-subj-url-for-action-events
(testing "`events` should use the 'best' URL for both subj_id and subj.pid, i.e. return value of `best-subj-url-for-action`"
(with-redefs [event-data-percolator.action/best-subj-url-for-action
(fn [action] "http://returned.com/this-is-the-best-url")]
; We're mocking out the return value of best-subj-url-for-action, so it doesn't use this content.
(let [input-action {:url "https://example.com/the-action-url"
:occurred-at "2016-02-05"
:relation-type-id "cites"
:matches
[{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:processed-observations
[{:type :content-url
:canonical-url "http://returned.com/this-is-the-best-url"
:final-url "http://example.com/the-final-url"
:url "http://example.com/the-observation-url"}]}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)
first-event (-> result-action :events first)]
(is (= (:subj_id first-event)
(-> first-event :subj :pid)
"http://returned.com/this-is-the-best-url")
"Best URL should be use for both fields")
(is (= (-> first-event :subj :url)
"https://example.com/the-action-url")
"Action URL should be used for the subj.url")))))
|
83056
|
(ns event-data-percolator.action-test
"Tests for action"
(:require [clojure.test :refer :all]
[clj-time.core :as clj-time]
[org.httpkit.fake :as fake]
[event-data-percolator.action :as action]
[event-data-percolator.test-util :as util]))
(deftest ^:unit create-event-from-match
(testing "create-event-from-match can build an Event from an Action"
(let [source-token "<KEY>"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:obj_id result) object-doi) "Match URL should be output as obj_id")
(is (= (:source_token result) source-token) "Source token should be taken from Evidence Record")
(is (= (:occurred_at result) "2016-02-05") "Occurred at should be taken from the Action")
(is (= (:subj_id result) subject-url) "Subject URL should be taken from the Action")
(is (:id result) "ID is assigned")
(is (:action result) "Action is assigned")
(is (= (-> result :subj :pid) subject-url) "Subject URL should be taken from the Action")
(is (= (-> result :obj :pid) object-doi) "The match DOI should be included as the obj metadata PID ")
(is (= (-> result :obj :url) object-url) "The match input URL should be included as the obj metadata PID")
(is (= (:relation_type_id result) "cites") "Relation type id is taken from the Action")))
(testing "create-event-from-match adds license field if present"
(let [source-token "<KEY>"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]
:license "https://creativecommons.org/publicdomain/zero/1.0/"}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:license result) "https://creativecommons.org/publicdomain/zero/1.0/") "License field present")))
(testing "create-event-from-match does not add license field if not present"
(let [source-token "<KEY>"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (not (contains? result :license)) "License field not present (not just nil)"))))
; This behaviour allows consumers to tell the difference between DOIs that were matched from an input URL (e.g. landing page)
; and those that were referenced directly with the DOI.
(deftest ^:unit create-event-from-match-subj-urls
(let [; A match where there was an input-url
match1 {:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}
; A match where there wasn't.
match2 {:match "https://dx.doi.org/10.5555/12345678"}
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:pages [{:actions [input-action]}]}
result1 (action/create-event-from-match evidence-record input-action match1)
result2 (action/create-event-from-match evidence-record input-action match2)]
(testing "create-event-from-match will take the input URL as the event URL from the match where there is one"
(is (= (-> result1 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result1 :obj :url) "http://psychoceramics.labs.crossref.org/12345")))
(testing "create-event-from-match will take the DOI URL as the event URL from the match where there is no input url"
(is (= (-> result2 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result2 :obj :url) "https://dx.doi.org/10.5555/12345678")))))
(deftest ^:unit create-events-for-action
(testing "When there are are extra Events but there was no match, no Events should be emitted."
(let [extra-events [{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; no matches
:matches []
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (empty? (:events result-action)) "No Events should have been emitted.")))
(testing "When there are are extra Events and there was at least one match, those Extra Events should be emitted, with the requisite fields."
(let [extra-events [; These Events have minimal fields.
{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 3) "Three Events should have been emitted, one from the match and two from the extras.")
; compare with out :id field, that's random.
(is (= (set (map #(dissoc % :id) (:events result-action)))
#{{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}
; Emitted ones have :id, :evidence_record, :action, :source_id added
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}}))))
(testing "When there are are no extra Events but there were matches, an Event should be created for each match"
(let [input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
; no extra events
:extra-events []}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 1) "One Events should have been emitted, from the match.")
(is (= (map #(dissoc % :id) (:events result-action))
[{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}])))))
(deftest ^:unit dedupe-by-val-substring
(testing "dedupe-by-val-substring removes all matches that are a substring of any other in the group."
(is (= (action/dedupe-by-val-substring [{:value "1"} {:value "1234"} {:value "12"} {:value "oops"}])
[{:value "1234"} {:value "oops"}])
"Substrings should be removed. Non-dupes should be untouched")))
(deftest ^:unit dedupe-matches
(testing "When there are duplicate matches that represent the same thing match-candidates should de-duplicate them.
See event-data-percolator.observation-types.html-test/html-with-duplicates for when this might occur."
(let [input-action {:matches [; This should be removed because the matched DOI is a duplicate of another one and the value is a substring of another.
{:type :plain-doi :value "10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be removed because the matche DOI is a duplicate of another one, as is the value, and :doi-urls are prioritised.
{:type :landing-page-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be retained because its' the only one left of the duplicates and it's prioritised.
{:type :doi-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This has the same matched DOI, but is different in that it came from a landing page. Should be retained.
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
; And something that's not a duplicate, so should be retained.
{:type :doi-url :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
expected-result {:matches [{:type :doi-url, :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
{:type :doi-url, :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
result (action/dedupe-matches util/mock-context util/mock-evidence-record input-action)]
(is (= result expected-result)))))
(deftest ^:unit canonical-url-for-action
(testing "Can detect the first canonical url in any input observation."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect the first canonical fron any type."
; Could be from :content-url or :html
(let [input-action {:processed-observations
[{:type :doesnt-matter :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect multiple found canonical URLs if they are identical."
; We don't expect this ever to happen.
; But if it does, and they are identical, that's fine because there's no ambiguity.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Ignores duplicate different found canonical URLs if they are not identical."
; We don't expect this ever to happen.
; But it if does, that's ambiguous, so return nothing.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/no-I-am"}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when nil found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url nil}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when none found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url}]}]
(is (= (action/canonical-url-for-action input-action) nil)))))
(deftest ^:unit final-url-for-action
(testing "final-url-for-action can retrieve the final-url from the first observation's :final-url value"
(let [input-action {:processed-observations
[{:input-url "http://example.com" :final-url "http://sandwiches.com"}]}]
(is (= (action/final-url-for-action input-action) "http://sandwiches.com")))))
(deftest ^:unit best-subj-url-for-action
(testing "best-subj-url-for-action should choose canonical URL as first choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :canonical-url "http://alpha.com/canonical"}]
:final-url "http://beta.com/xyz"
:url "http://gamma.com/abcdefg"})
"http://alpha.com/canonical")))
(testing "best-subj-url-for-action should choose final-url as second choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz?utm_keyword=sandwiches"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
"Cursory check to ensure that tracking params are removed when using the 'final' url.")
(testing "best-subj-url-for-action should choose action URL as third choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg"})
"http://gamma.com/abcdefg"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches"})
"http://gamma.com/abcdefg")
"Cursory check to ensure that tracking params are removed when using the action URL")
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches&colour=indigo"})
"http://gamma.com/abcdefg?colour=indigo")
"Cursory check to ensure that tracking params are removed when using the action URL")))
(deftest ^:unit best-subj-url-for-action-events
(testing "`events` should use the 'best' URL for both subj_id and subj.pid, i.e. return value of `best-subj-url-for-action`"
(with-redefs [event-data-percolator.action/best-subj-url-for-action
(fn [action] "http://returned.com/this-is-the-best-url")]
; We're mocking out the return value of best-subj-url-for-action, so it doesn't use this content.
(let [input-action {:url "https://example.com/the-action-url"
:occurred-at "2016-02-05"
:relation-type-id "cites"
:matches
[{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:processed-observations
[{:type :content-url
:canonical-url "http://returned.com/this-is-the-best-url"
:final-url "http://example.com/the-final-url"
:url "http://example.com/the-observation-url"}]}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)
first-event (-> result-action :events first)]
(is (= (:subj_id first-event)
(-> first-event :subj :pid)
"http://returned.com/this-is-the-best-url")
"Best URL should be use for both fields")
(is (= (-> first-event :subj :url)
"https://example.com/the-action-url")
"Action URL should be used for the subj.url")))))
| true |
(ns event-data-percolator.action-test
"Tests for action"
(:require [clojure.test :refer :all]
[clj-time.core :as clj-time]
[org.httpkit.fake :as fake]
[event-data-percolator.action :as action]
[event-data-percolator.test-util :as util]))
(deftest ^:unit create-event-from-match
(testing "create-event-from-match can build an Event from an Action"
(let [source-token "PI:KEY:<KEY>END_PI"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:obj_id result) object-doi) "Match URL should be output as obj_id")
(is (= (:source_token result) source-token) "Source token should be taken from Evidence Record")
(is (= (:occurred_at result) "2016-02-05") "Occurred at should be taken from the Action")
(is (= (:subj_id result) subject-url) "Subject URL should be taken from the Action")
(is (:id result) "ID is assigned")
(is (:action result) "Action is assigned")
(is (= (-> result :subj :pid) subject-url) "Subject URL should be taken from the Action")
(is (= (-> result :obj :pid) object-doi) "The match DOI should be included as the obj metadata PID ")
(is (= (-> result :obj :url) object-url) "The match input URL should be included as the obj metadata PID")
(is (= (:relation_type_id result) "cites") "Relation type id is taken from the Action")))
(testing "create-event-from-match adds license field if present"
(let [source-token "PI:KEY:<KEY>END_PI"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]
:license "https://creativecommons.org/publicdomain/zero/1.0/"}
result (action/create-event-from-match evidence-record input-action match)]
(is (= (:license result) "https://creativecommons.org/publicdomain/zero/1.0/") "License field present")))
(testing "create-event-from-match does not add license field if not present"
(let [source-token "PI:KEY:<KEY>END_PI"
subject-url "https://blog.com/1234"
source-id "SOURCE_ID"
object-url "http://psychoceramics.labs.crossref.org/12345"
object-doi "https://dx.doi.org/10.5555/12345678"
match {:type :landing-page-url :value object-url :match object-doi}
input-action {:url subject-url
:occurred-at "2016-02-05"
:relation-type-id "cites"
:processed-observations [{:match match}]}
evidence-record {:source-token source-token
:source-id source-id
:pages [{:actions [input-action]}]}
result (action/create-event-from-match evidence-record input-action match)]
(is (not (contains? result :license)) "License field not present (not just nil)"))))
; This behaviour allows consumers to tell the difference between DOIs that were matched from an input URL (e.g. landing page)
; and those that were referenced directly with the DOI.
(deftest ^:unit create-event-from-match-subj-urls
(let [; A match where there was an input-url
match1 {:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}
; A match where there wasn't.
match2 {:match "https://dx.doi.org/10.5555/12345678"}
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:pages [{:actions [input-action]}]}
result1 (action/create-event-from-match evidence-record input-action match1)
result2 (action/create-event-from-match evidence-record input-action match2)]
(testing "create-event-from-match will take the input URL as the event URL from the match where there is one"
(is (= (-> result1 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result1 :obj :url) "http://psychoceramics.labs.crossref.org/12345")))
(testing "create-event-from-match will take the DOI URL as the event URL from the match where there is no input url"
(is (= (-> result2 :obj :pid) "https://dx.doi.org/10.5555/12345678"))
(is (= (-> result2 :obj :url) "https://dx.doi.org/10.5555/12345678")))))
(deftest ^:unit create-events-for-action
(testing "When there are are extra Events but there was no match, no Events should be emitted."
(let [extra-events [{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; no matches
:matches []
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (empty? (:events result-action)) "No Events should have been emitted.")))
(testing "When there are are extra Events and there was at least one match, those Extra Events should be emitted, with the requisite fields."
(let [extra-events [; These Events have minimal fields.
{:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}]
input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:extra-events extra-events}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 3) "Three Events should have been emitted, one from the match and two from the extras.")
; compare with out :id field, that's random.
(is (= (set (map #(dissoc % :id) (:events result-action)))
#{{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}
; Emitted ones have :id, :evidence_record, :action, :source_id added
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/1",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/1/version/2",
:relation_type_id "is_version_of"}
{:license "http://example.com/license"
:evidence_record "http://example.com/evidence/123456",
:source_token "SOURCE_TOKEN",
:source_id "SOURCE_ID",
:action "add",
:obj_id "https://example.com/2",
:occurred_at "2017-04-01T00:33:21Z",
:subj_id "https://example.com/2/version/2",
:relation_type_id "is_version_of"}}))))
(testing "When there are are no extra Events but there were matches, an Event should be created for each match"
(let [input-action {:url "https://blog.com/1234"
:occurred-at "2016-02-05"
:relation-type-id "cites"
; one match
:matches [{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
; no extra events
:extra-events []}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)]
(is (= (count (:events result-action)) 1) "One Events should have been emitted, from the match.")
(is (= (map #(dissoc % :id) (:events result-action))
[{:license "http://example.com/license"
:obj_id "https://dx.doi.org/10.5555/12345678",
:source_token "SOURCE_TOKEN",
:occurred_at "2016-02-05",
:subj_id "https://blog.com/1234",
:action "add",
:subj {:pid "https://blog.com/1234"
:url "https://blog.com/1234"},
:source_id "SOURCE_ID",
:obj
{:pid "https://dx.doi.org/10.5555/12345678",
:url "http://psychoceramics.labs.crossref.org/12345"},
:evidence_record "http://example.com/evidence/123456",
:relation_type_id "cites"}])))))
(deftest ^:unit dedupe-by-val-substring
(testing "dedupe-by-val-substring removes all matches that are a substring of any other in the group."
(is (= (action/dedupe-by-val-substring [{:value "1"} {:value "1234"} {:value "12"} {:value "oops"}])
[{:value "1234"} {:value "oops"}])
"Substrings should be removed. Non-dupes should be untouched")))
(deftest ^:unit dedupe-matches
(testing "When there are duplicate matches that represent the same thing match-candidates should de-duplicate them.
See event-data-percolator.observation-types.html-test/html-with-duplicates for when this might occur."
(let [input-action {:matches [; This should be removed because the matched DOI is a duplicate of another one and the value is a substring of another.
{:type :plain-doi :value "10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be removed because the matche DOI is a duplicate of another one, as is the value, and :doi-urls are prioritised.
{:type :landing-page-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This should be retained because its' the only one left of the duplicates and it's prioritised.
{:type :doi-url :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
; This has the same matched DOI, but is different in that it came from a landing page. Should be retained.
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
; And something that's not a duplicate, so should be retained.
{:type :doi-url :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
expected-result {:matches [{:type :doi-url, :value "https://doi.org/10.5555/12345678" :match "https://doi.org/10.5555/12345678"}
{:type :landing-page-url :value "https://www.example.com/article/123456789" :match "https://doi.org/10.5555/12345678"}
{:type :doi-url, :value "https://doi.org/10.6666/24242424" :match "https://doi.org/10.6666/24242424"}]}
result (action/dedupe-matches util/mock-context util/mock-evidence-record input-action)]
(is (= result expected-result)))))
(deftest ^:unit canonical-url-for-action
(testing "Can detect the first canonical url in any input observation."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect the first canonical fron any type."
; Could be from :content-url or :html
(let [input-action {:processed-observations
[{:type :doesnt-matter :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Can detect multiple found canonical URLs if they are identical."
; We don't expect this ever to happen.
; But if it does, and they are identical, that's fine because there's no ambiguity.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/canonical"}]}]
(is (= (action/canonical-url-for-action input-action) "http://example.com/canonical"))))
(testing "Ignores duplicate different found canonical URLs if they are not identical."
; We don't expect this ever to happen.
; But it if does, that's ambiguous, so return nothing.
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url "http://example.com/canonical"}
{:type :irrelevant :further :irrelevancies}
{:type :content-url :canonical-url "http://example.com/no-I-am"}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when nil found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url :canonical-url nil}]}]
(is (= (action/canonical-url-for-action input-action) nil))))
(testing "Returns nil when none found."
(let [input-action {:processed-observations
[{:type :irrelevant :nothing :else}
{:type :content-url}]}]
(is (= (action/canonical-url-for-action input-action) nil)))))
(deftest ^:unit final-url-for-action
(testing "final-url-for-action can retrieve the final-url from the first observation's :final-url value"
(let [input-action {:processed-observations
[{:input-url "http://example.com" :final-url "http://sandwiches.com"}]}]
(is (= (action/final-url-for-action input-action) "http://sandwiches.com")))))
(deftest ^:unit best-subj-url-for-action
(testing "best-subj-url-for-action should choose canonical URL as first choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :canonical-url "http://alpha.com/canonical"}]
:final-url "http://beta.com/xyz"
:url "http://gamma.com/abcdefg"})
"http://alpha.com/canonical")))
(testing "best-subj-url-for-action should choose final-url as second choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[{:type :content-url :final-url "http://beta.com/xyz?utm_keyword=sandwiches"}]
:url "http://gamma.com/abcdefg"})
"http://beta.com/xyz"))
"Cursory check to ensure that tracking params are removed when using the 'final' url.")
(testing "best-subj-url-for-action should choose action URL as third choice."
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg"})
"http://gamma.com/abcdefg"))
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches"})
"http://gamma.com/abcdefg")
"Cursory check to ensure that tracking params are removed when using the action URL")
(is (= (action/best-subj-url-for-action
{:processed-observations
[]
:url "http://gamma.com/abcdefg?utm_keyword=sandwiches&colour=indigo"})
"http://gamma.com/abcdefg?colour=indigo")
"Cursory check to ensure that tracking params are removed when using the action URL")))
(deftest ^:unit best-subj-url-for-action-events
(testing "`events` should use the 'best' URL for both subj_id and subj.pid, i.e. return value of `best-subj-url-for-action`"
(with-redefs [event-data-percolator.action/best-subj-url-for-action
(fn [action] "http://returned.com/this-is-the-best-url")]
; We're mocking out the return value of best-subj-url-for-action, so it doesn't use this content.
(let [input-action {:url "https://example.com/the-action-url"
:occurred-at "2016-02-05"
:relation-type-id "cites"
:matches
[{:value "http://psychoceramics.labs.crossref.org/12345"
:type :landing-page-url
:match "https://dx.doi.org/10.5555/12345678"}]
:processed-observations
[{:type :content-url
:canonical-url "http://returned.com/this-is-the-best-url"
:final-url "http://example.com/the-final-url"
:url "http://example.com/the-observation-url"}]}
evidence-record {:source-token "SOURCE_TOKEN"
:source-id "SOURCE_ID"
:license "http://example.com/license"
:url "http://example.com/evidence/123456"
:pages [{:actions [input-action]}]}
result-action (action/create-events-for-action util/mock-context evidence-record input-action)
first-event (-> result-action :events first)]
(is (= (:subj_id first-event)
(-> first-event :subj :pid)
"http://returned.com/this-is-the-best-url")
"Best URL should be use for both fields")
(is (= (-> first-event :subj :url)
"https://example.com/the-action-url")
"Action URL should be used for the subj.url")))))
|
[
{
"context": "nstrument and studio abstractions.\"\n :author \"Jeff Rose\"}\n overtone.studio.mixer\n (:use [clojure.core.i",
"end": 87,
"score": 0.9998677968978882,
"start": 78,
"tag": "NAME",
"value": "Jeff Rose"
}
] |
src/overtone/studio/mixer.clj
|
rosejn/overtone
| 4 |
(ns
^{:doc "Higher level instrument and studio abstractions."
:author "Jeff Rose"}
overtone.studio.mixer
(:use [clojure.core.incubator :only [dissoc-in]]
[overtone.music rhythm pitch]
[overtone.libs event deps]
[overtone.util lib]
[overtone.sc.machinery defaults synthdef]
[overtone.sc.machinery.ugen fn-gen defaults sc-ugen]
[overtone.sc.machinery.server comms]
[overtone.sc server synth ugens envelope node bus]
[overtone.sc.util :only [id-mapper]]
[overtone.music rhythm time])
(:require [overtone.studio fx]
[overtone.util.log :as log]))
; An instrument abstracts the more basic concept of a synthesizer used by
; SuperCollider. Every instance of an instrument will be placed in the same
; group, so if you later call (kill my-inst) it will be able to stop all the
; instances of that group. (Likewise for controlling them...)
(defonce instruments* (ref {}))
(defonce inst-group* (ref nil))
(def MIXER-BOOT-DEPS [:server-ready :studio-setup-completed])
(def DEFAULT-VOLUME 1.0)
(def DEFAULT-PAN 0.0)
(defn mixer-booted? []
(deps-satisfied? MIXER-BOOT-DEPS))
(defn wait-until-mixer-booted
"Makes the current thread sleep until the mixer completed its boot process."
[]
(wait-until-deps-satisfied MIXER-BOOT-DEPS))
(defn boot-mixer
"Boots the server and waits until the studio mixer has complete set up"
[]
(when-not (mixer-booted?)
(boot-server)
(wait-until-mixer-booted)))
(defn setup-studio []
(log/info (str "Creating studio group at head of: " (root-group)))
(let [root (root-group)
g (with-server-sync #(group :head root))
r (group :tail root)
insts-with-groups (map-vals #(assoc % :group (group :tail g))
@instruments*)]
(dosync
(ref-set inst-group* g)
(ref-set instruments* insts-with-groups))
(satisfy-deps :studio-setup-completed)))
(on-deps :server-ready ::setup-studio setup-studio)
;; Clear and re-create the instrument groups after a reset
;; TODO: re-create the instrument groups
(defn reset-inst-groups
"Frees all synth notes for each of the current instruments"
[event-info]
(doseq [[name inst] @instruments*]
(group-clear (:instance-group inst))))
(on-sync-event :reset reset-inst-groups ::reset-instruments)
; Add instruments to the session when defined
(defn add-instrument [inst]
(let [i-name (:name inst)]
(dosync (alter instruments* assoc i-name inst))
i-name))
(defn remove-instrument [i-name]
(dosync (alter instruments* dissoc (name i-name)))
(event :inst-removed :inst-name i-name))
(defn clear-instruments []
(dosync (ref-set instruments* {})))
|
67795
|
(ns
^{:doc "Higher level instrument and studio abstractions."
:author "<NAME>"}
overtone.studio.mixer
(:use [clojure.core.incubator :only [dissoc-in]]
[overtone.music rhythm pitch]
[overtone.libs event deps]
[overtone.util lib]
[overtone.sc.machinery defaults synthdef]
[overtone.sc.machinery.ugen fn-gen defaults sc-ugen]
[overtone.sc.machinery.server comms]
[overtone.sc server synth ugens envelope node bus]
[overtone.sc.util :only [id-mapper]]
[overtone.music rhythm time])
(:require [overtone.studio fx]
[overtone.util.log :as log]))
; An instrument abstracts the more basic concept of a synthesizer used by
; SuperCollider. Every instance of an instrument will be placed in the same
; group, so if you later call (kill my-inst) it will be able to stop all the
; instances of that group. (Likewise for controlling them...)
(defonce instruments* (ref {}))
(defonce inst-group* (ref nil))
(def MIXER-BOOT-DEPS [:server-ready :studio-setup-completed])
(def DEFAULT-VOLUME 1.0)
(def DEFAULT-PAN 0.0)
(defn mixer-booted? []
(deps-satisfied? MIXER-BOOT-DEPS))
(defn wait-until-mixer-booted
"Makes the current thread sleep until the mixer completed its boot process."
[]
(wait-until-deps-satisfied MIXER-BOOT-DEPS))
(defn boot-mixer
"Boots the server and waits until the studio mixer has complete set up"
[]
(when-not (mixer-booted?)
(boot-server)
(wait-until-mixer-booted)))
(defn setup-studio []
(log/info (str "Creating studio group at head of: " (root-group)))
(let [root (root-group)
g (with-server-sync #(group :head root))
r (group :tail root)
insts-with-groups (map-vals #(assoc % :group (group :tail g))
@instruments*)]
(dosync
(ref-set inst-group* g)
(ref-set instruments* insts-with-groups))
(satisfy-deps :studio-setup-completed)))
(on-deps :server-ready ::setup-studio setup-studio)
;; Clear and re-create the instrument groups after a reset
;; TODO: re-create the instrument groups
(defn reset-inst-groups
"Frees all synth notes for each of the current instruments"
[event-info]
(doseq [[name inst] @instruments*]
(group-clear (:instance-group inst))))
(on-sync-event :reset reset-inst-groups ::reset-instruments)
; Add instruments to the session when defined
(defn add-instrument [inst]
(let [i-name (:name inst)]
(dosync (alter instruments* assoc i-name inst))
i-name))
(defn remove-instrument [i-name]
(dosync (alter instruments* dissoc (name i-name)))
(event :inst-removed :inst-name i-name))
(defn clear-instruments []
(dosync (ref-set instruments* {})))
| true |
(ns
^{:doc "Higher level instrument and studio abstractions."
:author "PI:NAME:<NAME>END_PI"}
overtone.studio.mixer
(:use [clojure.core.incubator :only [dissoc-in]]
[overtone.music rhythm pitch]
[overtone.libs event deps]
[overtone.util lib]
[overtone.sc.machinery defaults synthdef]
[overtone.sc.machinery.ugen fn-gen defaults sc-ugen]
[overtone.sc.machinery.server comms]
[overtone.sc server synth ugens envelope node bus]
[overtone.sc.util :only [id-mapper]]
[overtone.music rhythm time])
(:require [overtone.studio fx]
[overtone.util.log :as log]))
; An instrument abstracts the more basic concept of a synthesizer used by
; SuperCollider. Every instance of an instrument will be placed in the same
; group, so if you later call (kill my-inst) it will be able to stop all the
; instances of that group. (Likewise for controlling them...)
(defonce instruments* (ref {}))
(defonce inst-group* (ref nil))
(def MIXER-BOOT-DEPS [:server-ready :studio-setup-completed])
(def DEFAULT-VOLUME 1.0)
(def DEFAULT-PAN 0.0)
(defn mixer-booted? []
(deps-satisfied? MIXER-BOOT-DEPS))
(defn wait-until-mixer-booted
"Makes the current thread sleep until the mixer completed its boot process."
[]
(wait-until-deps-satisfied MIXER-BOOT-DEPS))
(defn boot-mixer
"Boots the server and waits until the studio mixer has complete set up"
[]
(when-not (mixer-booted?)
(boot-server)
(wait-until-mixer-booted)))
(defn setup-studio []
(log/info (str "Creating studio group at head of: " (root-group)))
(let [root (root-group)
g (with-server-sync #(group :head root))
r (group :tail root)
insts-with-groups (map-vals #(assoc % :group (group :tail g))
@instruments*)]
(dosync
(ref-set inst-group* g)
(ref-set instruments* insts-with-groups))
(satisfy-deps :studio-setup-completed)))
(on-deps :server-ready ::setup-studio setup-studio)
;; Clear and re-create the instrument groups after a reset
;; TODO: re-create the instrument groups
(defn reset-inst-groups
"Frees all synth notes for each of the current instruments"
[event-info]
(doseq [[name inst] @instruments*]
(group-clear (:instance-group inst))))
(on-sync-event :reset reset-inst-groups ::reset-instruments)
; Add instruments to the session when defined
(defn add-instrument [inst]
(let [i-name (:name inst)]
(dosync (alter instruments* assoc i-name inst))
i-name))
(defn remove-instrument [i-name]
(dosync (alter instruments* dissoc (name i-name)))
(event :inst-removed :inst-name i-name))
(defn clear-instruments []
(dosync (ref-set instruments* {})))
|
[
{
"context": "file is part of esri-api.\n;;;;\n;;;; Copyright 2020 Alexander Dorn\n;;;;\n;;;; Licensed under the Apache License, Vers",
"end": 75,
"score": 0.9998602867126465,
"start": 61,
"tag": "NAME",
"value": "Alexander Dorn"
}
] |
src/esri_api/core.clj
|
e-user/esri-api
| 0 |
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 Alexander Dorn
;;;;
;;;; 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 esri_api.core
"Core namespace"
(:gen-class)
(:require [esri_api.server :as server]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[com.stuartsierra.component :as component]))
;;; CLI boilerplate, super boring.
(defn usage [options-summary]
(format
"Esri ArcGIS open data API
USAGE:
esri-api [options]
OPTIONS:
%s"
options-summary))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-h" "--help"]])
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args cli-options)]
(cond (options :help)
(do (println (usage summary))
(System/exit 0))
errors
(do (println (string/join \newline errors))
(System/exit 1))
(not= 0 (count arguments))
(do (println (usage options))
(System/exit 1))
:default (component/start
(server/system {:port (options :port)})))))
|
117895
|
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 <NAME>
;;;;
;;;; Licensed under the Apache License, Version 2.0 (the "License");
;;;; you may not use this file except in compliance with the License.
;;;; You may obtain a copy of the License at
;;;;
;;;; http://www.apache.org/licenses/LICENSE-2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing, software
;;;; distributed under the License is distributed on an "AS IS" BASIS,
;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the License for the specific language governing permissions and
;;;; limitations under the License.
(ns esri_api.core
"Core namespace"
(:gen-class)
(:require [esri_api.server :as server]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[com.stuartsierra.component :as component]))
;;; CLI boilerplate, super boring.
(defn usage [options-summary]
(format
"Esri ArcGIS open data API
USAGE:
esri-api [options]
OPTIONS:
%s"
options-summary))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-h" "--help"]])
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args cli-options)]
(cond (options :help)
(do (println (usage summary))
(System/exit 0))
errors
(do (println (string/join \newline errors))
(System/exit 1))
(not= 0 (count arguments))
(do (println (usage options))
(System/exit 1))
:default (component/start
(server/system {:port (options :port)})))))
| true |
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 PI:NAME:<NAME>END_PI
;;;;
;;;; Licensed under the Apache License, Version 2.0 (the "License");
;;;; you may not use this file except in compliance with the License.
;;;; You may obtain a copy of the License at
;;;;
;;;; http://www.apache.org/licenses/LICENSE-2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing, software
;;;; distributed under the License is distributed on an "AS IS" BASIS,
;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the License for the specific language governing permissions and
;;;; limitations under the License.
(ns esri_api.core
"Core namespace"
(:gen-class)
(:require [esri_api.server :as server]
[clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[com.stuartsierra.component :as component]))
;;; CLI boilerplate, super boring.
(defn usage [options-summary]
(format
"Esri ArcGIS open data API
USAGE:
esri-api [options]
OPTIONS:
%s"
options-summary))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-h" "--help"]])
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args cli-options)]
(cond (options :help)
(do (println (usage summary))
(System/exit 0))
errors
(do (println (string/join \newline errors))
(System/exit 1))
(not= 0 (count arguments))
(do (println (usage options))
(System/exit 1))
:default (component/start
(server/system {:port (options :port)})))))
|
[
{
"context": "in (time/t -2 1900)\n :max (time/t -2 2100)}\n\n \"hetkel\"\n \"praegu\"\n \"praegusel hetkel\"\n \"just nüüd\"\n ",
"end": 189,
"score": 0.9428743720054626,
"start": 183,
"tag": "NAME",
"value": "hetkel"
},
{
"context": "-2 1900)\n :max (time/t -2 2100)}\n\n \"hetkel\"\n \"praegu\"\n \"praegusel hetkel\"\n \"just nüüd\"\n (datetime 2",
"end": 200,
"score": 0.9715246558189392,
"start": 194,
"tag": "NAME",
"value": "praegu"
},
{
"context": " :max (time/t -2 2100)}\n\n \"hetkel\"\n \"praegu\"\n \"praegusel hetkel\"\n \"just nüüd\"\n (datetime 2013 2 12 4 30 00)\n \n",
"end": 221,
"score": 0.9880948066711426,
"start": 205,
"tag": "NAME",
"value": "praegusel hetkel"
},
{
"context": " \"just nüüd\"\n (datetime 2013 2 12 4 30 00)\n \n \"täna\"\n (datetime 2013 2 12)\n\n \"eile\"\n (datetime 201",
"end": 278,
"score": 0.8884006142616272,
"start": 274,
"tag": "NAME",
"value": "täna"
},
{
"context": "2 4 30 00)\n \n \"täna\"\n (datetime 2013 2 12)\n\n \"eile\"\n (datetime 2013 2 11)\n\n \"homme\"\n (datetime 20",
"end": 311,
"score": 0.9653973579406738,
"start": 307,
"tag": "NAME",
"value": "eile"
},
{
"context": "e 2013 2 12)\n\n \"eile\"\n (datetime 2013 2 11)\n\n \"homme\"\n (datetime 2013 2 13)\n \n \"esmaspäev\"\n \"esmas",
"end": 345,
"score": 0.9274803996086121,
"start": 340,
"tag": "NAME",
"value": "homme"
},
{
"context": "013 2 11)\n\n \"homme\"\n (datetime 2013 2 13)\n \n \"esmaspäev\"\n \"esmaspäeval\"\n \"esmasp.\"\n \"sellel esmaspäeva",
"end": 385,
"score": 0.9074867963790894,
"start": 376,
"tag": "NAME",
"value": "esmaspäev"
},
{
"context": "homme\"\n (datetime 2013 2 13)\n \n \"esmaspäev\"\n \"esmaspäeval\"\n \"esmasp.\"\n \"sellel esmaspäeval\"\n \"see esmasp",
"end": 401,
"score": 0.7997051477432251,
"start": 390,
"tag": "NAME",
"value": "esmaspäeval"
},
{
"context": "aspäev\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"Esmaspäev, 18. veebruar\"\n \"Esm, 18. veebruaril\"\n (datetim",
"end": 507,
"score": 0.9821321368217468,
"start": 498,
"tag": "NAME",
"value": "Esmaspäev"
},
{
"context": "8 :day-of-week 1)\n\n \"Esmaspäev, 18. veebruar\"\n \"Esm, 18. veebruaril\"\n (datetime 2013 2 18 :day-of-we",
"end": 529,
"score": 0.98209547996521,
"start": 526,
"tag": "NAME",
"value": "Esm"
},
{
"context": "me 2013 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"teisipäev\"\n \"teisipäeval\"\n \"teisip.\"\n (datetime 201",
"end": 610,
"score": 0.6080113649368286,
"start": 606,
"tag": "NAME",
"value": "teis"
},
{
"context": "3 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"teisipäev\"\n \"teisipäeval\"\n \"teisip.\"\n (datetime 2013 2 1",
"end": 615,
"score": 0.6418148279190063,
"start": 612,
"tag": "NAME",
"value": "äev"
},
{
"context": "day-of-week 1 :day 18 :month 2)\n\n \"teisipäev\"\n \"teisipäeval\"\n \"teisip.\"\n (datetime 2013 2 19)\n\n \"ko",
"end": 624,
"score": 0.6380250453948975,
"start": 620,
"tag": "NAME",
"value": "teis"
},
{
"context": "-week 1 :day 18 :month 2)\n\n \"teisipäev\"\n \"teisipäeval\"\n \"teisip.\"\n (datetime 2013 2 19)\n\n \"kolma",
"end": 627,
"score": 0.5608199238777161,
"start": 626,
"tag": "NAME",
"value": "ä"
},
{
"context": "lmapäeval\"\n \"kolmap.\"\n (datetime 2013 2 20)\n\n \"neljapäev\"\n \"neljapäeval\"\n \"neljap.\"\n (datetime 2013 2 1",
"end": 747,
"score": 0.724761426448822,
"start": 738,
"tag": "NAME",
"value": "neljapäev"
},
{
"context": ".\"\n (datetime 2013 2 20)\n\n \"neljapäev\"\n \"neljapäeval\"\n \"neljap.\"\n (datetime 2013 2 14)\n\n \"reede",
"end": 759,
"score": 0.5128543376922607,
"start": 758,
"tag": "NAME",
"value": "ä"
},
{
"context": "ljapäeval\"\n \"neljap.\"\n (datetime 2013 2 14)\n\n \"reede\"\n \"reedel\"\n (datetime 2013 2 15)\n\n \"laupäev\"\n ",
"end": 809,
"score": 0.8595151305198669,
"start": 804,
"tag": "NAME",
"value": "reede"
},
{
"context": "\n \"neljap.\"\n (datetime 2013 2 14)\n\n \"reede\"\n \"reedel\"\n (datetime 2013 2 15)\n\n \"laupäev\"\n \"laupäeval",
"end": 820,
"score": 0.8122802376747131,
"start": 814,
"tag": "NAME",
"value": "reedel"
}
] |
resources/languages/et/corpus/_time.clj
|
irvingflores/duckling
| 922 |
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"hetkel"
"praegu"
"praegusel hetkel"
"just nüüd"
(datetime 2013 2 12 4 30 00)
"täna"
(datetime 2013 2 12)
"eile"
(datetime 2013 2 11)
"homme"
(datetime 2013 2 13)
"esmaspäev"
"esmaspäeval"
"esmasp."
"sellel esmaspäeval"
"see esmaspäev"
(datetime 2013 2 18 :day-of-week 1)
"Esmaspäev, 18. veebruar"
"Esm, 18. veebruaril"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"teisipäev"
"teisipäeval"
"teisip."
(datetime 2013 2 19)
"kolmapäev"
"kolmapäeval"
"kolmap."
(datetime 2013 2 20)
"neljapäev"
"neljapäeval"
"neljap."
(datetime 2013 2 14)
"reede"
"reedel"
(datetime 2013 2 15)
"laupäev"
"laupäeval"
"laup."
(datetime 2013 2 16)
"pühapäev"
"pühapäeval"
"pühap."
(datetime 2013 2 17)
"1. märtsil"
"esimesel märtsil"
(datetime 2013 3 1 :day 1 :month 3)
"3. märtsil"
(datetime 2013 3 3 :day 3 :month 3)
"3. märts 2015"
"3. märtsil 2015. a"
"3. märtsil 2015"
"3. III 2015"
"03.03.2015"
"3.3.2015"
"3.3.15"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"15."
"viieteistkümnendal"
"15ndal"
(datetime 2013 2 15 :day 15)
"15. veebruar"
"15. veebruaril"
"15ndal veebruaril"
"viieteistkümnes veebruar"
"viieteistkümnendal veebruaril"
"15.2"
"15.02"
"15. II"
(datetime 2013 2 15 :day 15 :month 2)
"Aug 8"
(datetime 2013 8 8 :day 8 :month 8)
"Oktoober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31.10.1974"
"31.10.74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14. aprill 2015"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"järgmine teisipäev" ; when today is Tuesday, "mardi prochain" is a week from now
"järgmisel teisipäeval"
(datetime 2013 2 19 :day-of-week 2)
"järgmise nädala reede"
"järgmise nädala reedel"
(datetime 2013 2 22 :day-of-week 2)
"järgmine märts"
"järgmisel märtsil"
(datetime 2013 3)
"ülejärgmine märts"
"ülejärgmisel märtsil"
(datetime 2014 3)
"Sunday, Feb 10"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Wed, Feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"Monday, Feb 18"
"Mon, February 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"this week"
"coming week"
(datetime 2013 2 11 :grain :week)
"last week"
(datetime 2013 2 4 :grain :week)
"next week"
(datetime 2013 2 18 :grain :week)
"last month"
(datetime 2013 1)
"next month"
(datetime 2013 3)
"this quarter"
(datetime 2013 1 1 :grain :quarter)
"next quarter"
(datetime 2013 4 1 :grain :quarter)
"third quarter"
(datetime 2013 7 1 :grain :quarter)
"4th quarter 2018"
(datetime 2018 10 1 :grain :quarter)
"last year"
(datetime 2012)
"this year"
(datetime 2013)
"next year"
(datetime 2014)
"last sunday"
"sunday from last week"
"last week's sunday"
(datetime 2013 2 10 :day-of-week 7)
"last tuesday"
(datetime 2013 2 5 :day-of-week 2)
"next tuesday" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"next wednesday" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"wednesday of next week"
"wednesday next week"
"wednesday after next"
(datetime 2013 2 20 :day-of-week 3)
"friday after next"
(datetime 2013 2 22 :day-of-week 5)
"monday of this week"
(datetime 2013 2 11 :day-of-week 1)
"tuesday of this week"
(datetime 2013 2 12 :day-of-week 2)
"wednesday of this week"
(datetime 2013 2 13 :day-of-week 3)
"the day after tomorrow"
(datetime 2013 2 14)
"the day before yesterday"
(datetime 2013 2 10)
"last Monday of March"
(datetime 2013 3 25 :day-of-week 1)
"last Sunday of March 2014"
(datetime 2014 3 30 :day-of-week 7)
"third day of october"
(datetime 2013 10 3)
"first week of october 2014"
(datetime 2014 10 6 :grain :week)
"last day of october 2015"
(datetime 2015 10 31)
"last week of september 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"first tuesday of october"
(datetime 2013 10 1)
"third tuesday of september 2014"
(datetime 2014 9 16)
"first wednesday of october 2014"
(datetime 2014 10 1)
"second wednesday of october 2014"
(datetime 2014 10 8)
;; nth after
"third tuesday after christmas 2014"
(datetime 2015 1 13)
;; Hours
"at 3am"
"at 3 AM"
"3 oclock am"
"at three am"
(datetime 2013 2 13 3)
"3:18am"
"3:18a"
(datetime 2013 2 12 3 18)
"at 3pm"
"@ 3pm"
"3PM"
"3pm"
"3 oclock pm"
"3 o'clock in the afternoon"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"3ish pm"
"3pm approximately"
"at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm :precision "approximate")
"tomorrow 5pm sharp"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm :precision "exact")
"at 15 past 3pm"
"a quarter past 3pm"
"3:15 in the afternon"
"15:15"
"3:15pm"
"3:15PM"
"3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"at 20 past 3pm"
"3:20 in the afternoon"
"3:20 in afternoon"
"twenty after 3pm"
"3:20p"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"at half past three pm"
"half past 3 pm"
"15:30"
"3:30pm"
"3:30PM"
"330 p.m."
"3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
"half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"a quarter to noon"
"11:45am"
"15 to noon" ; Ambiguous with interval
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"8 tonight"
"eight tonight"
"8 this evening"
(datetime 2013 2 12 20)
;; Mixing date and time
"at 7:30 PM on Fri, Sep 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"at 9am on Saturday"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fri, Jul 18, 2014 07:00 PM"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
; ;; Involving periods
"in a sec"
"one second from now"
(datetime 2013 2 12 4 30 1)
"in a minute"
"in one minute"
(datetime 2013 2 12 4 31 0)
"in 2 minutes"
"in 2 more minutes"
"2 minutes from now"
(datetime 2013 2 12 4 32 0)
"in 60 minutes"
(datetime 2013 2 12 5 30 0)
"in half an hour"
(datetime 2013 2 12 5 0 0)
"in 2.5 hours"
"in 2 and an half hours"
(datetime 2013 2 12 7 0 0)
"in one hour"
(datetime 2013 2 12 5 30)
"in a couple hours"
"in a couple of hours"
(datetime 2013 2 12 6 30)
"in a few hours"
"in few hours"
(datetime 2013 2 12 7 30)
"in 24 hours"
(datetime 2013 2 13 4 30)
"in a day"
"a day from now"
(datetime 2013 2 13 4)
"3 years from today"
(datetime 2016 2)
"in 7 days"
(datetime 2013 2 19 4)
"in 1 week"
"in a week"
(datetime 2013 2 19)
"in about half an hour"
(datetime 2013 2 12 5 0 0 :precision "approximate")
"7 days ago"
(datetime 2013 2 5 4)
"14 days ago"
"a fortnight ago"
(datetime 2013 1 29 4)
"a week ago"
"one week ago"
"1 week ago"
(datetime 2013 2 5)
"three weeks ago"
(datetime 2013 1 22)
"three months ago"
(datetime 2012 11 12)
"two years ago"
(datetime 2011 2)
"7 days hence"
(datetime 2013 2 19 4)
"14 days hence"
"a fortnight hence"
(datetime 2013 2 26 4)
"a week hence"
"one week hence"
"1 week hence"
(datetime 2013 2 19)
"three weeks hence"
(datetime 2013 3 5)
"three months hence"
(datetime 2013 5 12)
"two years hence"
(datetime 2015 2)
"one year after christmas"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"this summer"
(datetime-interval [2013 6 21] [2013 9 24])
"this winter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"xmas"
"christmas"
"christmas day"
(datetime 2013 12 25)
"new year's eve"
"new years eve"
(datetime 2013 12 31)
"new year's day"
"new years day"
(datetime 2014 1 1)
"valentine's day"
"valentine day"
(datetime 2013 2 14)
"memorial day"
(datetime 2013 5 27)
"Mother's Day"
(datetime 2013 5 12)
"Father's Day"
(datetime 2013 6 16)
"memorial day week-end"
(datetime-interval [2013 5 24 18] [2013 5 28 0])
"independence day"
"4th of July"
"4 of july"
(datetime 2013 7 4)
"labor day"
(datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"thanksgiving day"
"thanksgiving"
(datetime 2013 11 28)
; Part of day (morning, afternoon...)
"this evening"
"today evening"
"tonight"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"tomorrow evening"
;"Wednesday evening"
"tomorrow night"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"yesterday evening"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"this week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"monday morning"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"february the 15th in the morning"
"15 of february in the morning"
"morning of the 15th of february"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"last 2 seconds"
"last two seconds"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"next 3 seconds"
"next three seconds"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"last 2 minutes"
"last two minutes"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"next 3 minutes"
"next three minutes"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"last 1 hour"
"last one hour"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"next 3 hours"
"next three hours"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"last 2 days"
"last two days"
"past 2 days"
(datetime-interval [2013 2 10] [2013 2 12])
"next 3 days"
"next three days"
(datetime-interval [2013 2 13] [2013 2 16])
"next few days"
(datetime-interval [2013 2 13] [2013 2 16])
"last 2 weeks"
"last two weeks"
"past 2 weeks"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"next 3 weeks"
"next three weeks"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"last 2 months"
"last two months"
(datetime-interval [2012 12] [2013 02])
"next 3 months"
"next three months"
(datetime-interval [2013 3] [2013 6])
"last 2 years"
"last two years"
(datetime-interval [2011] [2013])
"next 3 years"
"next three years"
(datetime-interval [2014] [2017])
; Explicit intervals
"July 13-15"
"July 13 to 15"
"July 13 thru 15"
"July 13 through 15"
"July 13 - July 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Aug 8 - Aug 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"from 9:30 - 11:00 on Thursday"
"between 9:30 and 11:00 on thursday"
"9:30 - 11:00 on Thursday"
"later than 9:30 but before 11:00 on Thursday"
"Thursday from 9:30 to 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Thursday from 9a to 11a"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"1:30 PM on Sat, Sep 21"
(datetime 2013 9 21 13 30)
"within 2 weeks"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"until 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by EOD"
(datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
"by EOM"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"by the end of next month"
(datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
; Timezones
"4pm CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"Thursday 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
)
|
55476
|
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"<NAME>"
"<NAME>"
"<NAME>"
"just nüüd"
(datetime 2013 2 12 4 30 00)
"<NAME>"
(datetime 2013 2 12)
"<NAME>"
(datetime 2013 2 11)
"<NAME>"
(datetime 2013 2 13)
"<NAME>"
"<NAME>"
"esmasp."
"sellel esmaspäeval"
"see esmaspäev"
(datetime 2013 2 18 :day-of-week 1)
"<NAME>, 18. veebruar"
"<NAME>, 18. veebruaril"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"<NAME>ip<NAME>"
"<NAME>ip<NAME>eval"
"teisip."
(datetime 2013 2 19)
"kolmapäev"
"kolmapäeval"
"kolmap."
(datetime 2013 2 20)
"<NAME>"
"neljap<NAME>eval"
"neljap."
(datetime 2013 2 14)
"<NAME>"
"<NAME>"
(datetime 2013 2 15)
"laupäev"
"laupäeval"
"laup."
(datetime 2013 2 16)
"pühapäev"
"pühapäeval"
"pühap."
(datetime 2013 2 17)
"1. märtsil"
"esimesel märtsil"
(datetime 2013 3 1 :day 1 :month 3)
"3. märtsil"
(datetime 2013 3 3 :day 3 :month 3)
"3. märts 2015"
"3. märtsil 2015. a"
"3. märtsil 2015"
"3. III 2015"
"03.03.2015"
"3.3.2015"
"3.3.15"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"15."
"viieteistkümnendal"
"15ndal"
(datetime 2013 2 15 :day 15)
"15. veebruar"
"15. veebruaril"
"15ndal veebruaril"
"viieteistkümnes veebruar"
"viieteistkümnendal veebruaril"
"15.2"
"15.02"
"15. II"
(datetime 2013 2 15 :day 15 :month 2)
"Aug 8"
(datetime 2013 8 8 :day 8 :month 8)
"Oktoober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31.10.1974"
"31.10.74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14. aprill 2015"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"järgmine teisipäev" ; when today is Tuesday, "mardi prochain" is a week from now
"järgmisel teisipäeval"
(datetime 2013 2 19 :day-of-week 2)
"järgmise nädala reede"
"järgmise nädala reedel"
(datetime 2013 2 22 :day-of-week 2)
"järgmine märts"
"järgmisel märtsil"
(datetime 2013 3)
"ülejärgmine märts"
"ülejärgmisel märtsil"
(datetime 2014 3)
"Sunday, Feb 10"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Wed, Feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"Monday, Feb 18"
"Mon, February 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"this week"
"coming week"
(datetime 2013 2 11 :grain :week)
"last week"
(datetime 2013 2 4 :grain :week)
"next week"
(datetime 2013 2 18 :grain :week)
"last month"
(datetime 2013 1)
"next month"
(datetime 2013 3)
"this quarter"
(datetime 2013 1 1 :grain :quarter)
"next quarter"
(datetime 2013 4 1 :grain :quarter)
"third quarter"
(datetime 2013 7 1 :grain :quarter)
"4th quarter 2018"
(datetime 2018 10 1 :grain :quarter)
"last year"
(datetime 2012)
"this year"
(datetime 2013)
"next year"
(datetime 2014)
"last sunday"
"sunday from last week"
"last week's sunday"
(datetime 2013 2 10 :day-of-week 7)
"last tuesday"
(datetime 2013 2 5 :day-of-week 2)
"next tuesday" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"next wednesday" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"wednesday of next week"
"wednesday next week"
"wednesday after next"
(datetime 2013 2 20 :day-of-week 3)
"friday after next"
(datetime 2013 2 22 :day-of-week 5)
"monday of this week"
(datetime 2013 2 11 :day-of-week 1)
"tuesday of this week"
(datetime 2013 2 12 :day-of-week 2)
"wednesday of this week"
(datetime 2013 2 13 :day-of-week 3)
"the day after tomorrow"
(datetime 2013 2 14)
"the day before yesterday"
(datetime 2013 2 10)
"last Monday of March"
(datetime 2013 3 25 :day-of-week 1)
"last Sunday of March 2014"
(datetime 2014 3 30 :day-of-week 7)
"third day of october"
(datetime 2013 10 3)
"first week of october 2014"
(datetime 2014 10 6 :grain :week)
"last day of october 2015"
(datetime 2015 10 31)
"last week of september 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"first tuesday of october"
(datetime 2013 10 1)
"third tuesday of september 2014"
(datetime 2014 9 16)
"first wednesday of october 2014"
(datetime 2014 10 1)
"second wednesday of october 2014"
(datetime 2014 10 8)
;; nth after
"third tuesday after christmas 2014"
(datetime 2015 1 13)
;; Hours
"at 3am"
"at 3 AM"
"3 oclock am"
"at three am"
(datetime 2013 2 13 3)
"3:18am"
"3:18a"
(datetime 2013 2 12 3 18)
"at 3pm"
"@ 3pm"
"3PM"
"3pm"
"3 oclock pm"
"3 o'clock in the afternoon"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"3ish pm"
"3pm approximately"
"at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm :precision "approximate")
"tomorrow 5pm sharp"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm :precision "exact")
"at 15 past 3pm"
"a quarter past 3pm"
"3:15 in the afternon"
"15:15"
"3:15pm"
"3:15PM"
"3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"at 20 past 3pm"
"3:20 in the afternoon"
"3:20 in afternoon"
"twenty after 3pm"
"3:20p"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"at half past three pm"
"half past 3 pm"
"15:30"
"3:30pm"
"3:30PM"
"330 p.m."
"3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
"half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"a quarter to noon"
"11:45am"
"15 to noon" ; Ambiguous with interval
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"8 tonight"
"eight tonight"
"8 this evening"
(datetime 2013 2 12 20)
;; Mixing date and time
"at 7:30 PM on Fri, Sep 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"at 9am on Saturday"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fri, Jul 18, 2014 07:00 PM"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
; ;; Involving periods
"in a sec"
"one second from now"
(datetime 2013 2 12 4 30 1)
"in a minute"
"in one minute"
(datetime 2013 2 12 4 31 0)
"in 2 minutes"
"in 2 more minutes"
"2 minutes from now"
(datetime 2013 2 12 4 32 0)
"in 60 minutes"
(datetime 2013 2 12 5 30 0)
"in half an hour"
(datetime 2013 2 12 5 0 0)
"in 2.5 hours"
"in 2 and an half hours"
(datetime 2013 2 12 7 0 0)
"in one hour"
(datetime 2013 2 12 5 30)
"in a couple hours"
"in a couple of hours"
(datetime 2013 2 12 6 30)
"in a few hours"
"in few hours"
(datetime 2013 2 12 7 30)
"in 24 hours"
(datetime 2013 2 13 4 30)
"in a day"
"a day from now"
(datetime 2013 2 13 4)
"3 years from today"
(datetime 2016 2)
"in 7 days"
(datetime 2013 2 19 4)
"in 1 week"
"in a week"
(datetime 2013 2 19)
"in about half an hour"
(datetime 2013 2 12 5 0 0 :precision "approximate")
"7 days ago"
(datetime 2013 2 5 4)
"14 days ago"
"a fortnight ago"
(datetime 2013 1 29 4)
"a week ago"
"one week ago"
"1 week ago"
(datetime 2013 2 5)
"three weeks ago"
(datetime 2013 1 22)
"three months ago"
(datetime 2012 11 12)
"two years ago"
(datetime 2011 2)
"7 days hence"
(datetime 2013 2 19 4)
"14 days hence"
"a fortnight hence"
(datetime 2013 2 26 4)
"a week hence"
"one week hence"
"1 week hence"
(datetime 2013 2 19)
"three weeks hence"
(datetime 2013 3 5)
"three months hence"
(datetime 2013 5 12)
"two years hence"
(datetime 2015 2)
"one year after christmas"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"this summer"
(datetime-interval [2013 6 21] [2013 9 24])
"this winter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"xmas"
"christmas"
"christmas day"
(datetime 2013 12 25)
"new year's eve"
"new years eve"
(datetime 2013 12 31)
"new year's day"
"new years day"
(datetime 2014 1 1)
"valentine's day"
"valentine day"
(datetime 2013 2 14)
"memorial day"
(datetime 2013 5 27)
"Mother's Day"
(datetime 2013 5 12)
"Father's Day"
(datetime 2013 6 16)
"memorial day week-end"
(datetime-interval [2013 5 24 18] [2013 5 28 0])
"independence day"
"4th of July"
"4 of july"
(datetime 2013 7 4)
"labor day"
(datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"thanksgiving day"
"thanksgiving"
(datetime 2013 11 28)
; Part of day (morning, afternoon...)
"this evening"
"today evening"
"tonight"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"tomorrow evening"
;"Wednesday evening"
"tomorrow night"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"yesterday evening"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"this week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"monday morning"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"february the 15th in the morning"
"15 of february in the morning"
"morning of the 15th of february"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"last 2 seconds"
"last two seconds"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"next 3 seconds"
"next three seconds"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"last 2 minutes"
"last two minutes"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"next 3 minutes"
"next three minutes"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"last 1 hour"
"last one hour"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"next 3 hours"
"next three hours"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"last 2 days"
"last two days"
"past 2 days"
(datetime-interval [2013 2 10] [2013 2 12])
"next 3 days"
"next three days"
(datetime-interval [2013 2 13] [2013 2 16])
"next few days"
(datetime-interval [2013 2 13] [2013 2 16])
"last 2 weeks"
"last two weeks"
"past 2 weeks"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"next 3 weeks"
"next three weeks"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"last 2 months"
"last two months"
(datetime-interval [2012 12] [2013 02])
"next 3 months"
"next three months"
(datetime-interval [2013 3] [2013 6])
"last 2 years"
"last two years"
(datetime-interval [2011] [2013])
"next 3 years"
"next three years"
(datetime-interval [2014] [2017])
; Explicit intervals
"July 13-15"
"July 13 to 15"
"July 13 thru 15"
"July 13 through 15"
"July 13 - July 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Aug 8 - Aug 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"from 9:30 - 11:00 on Thursday"
"between 9:30 and 11:00 on thursday"
"9:30 - 11:00 on Thursday"
"later than 9:30 but before 11:00 on Thursday"
"Thursday from 9:30 to 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Thursday from 9a to 11a"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"1:30 PM on Sat, Sep 21"
(datetime 2013 9 21 13 30)
"within 2 weeks"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"until 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by EOD"
(datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
"by EOM"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"by the end of next month"
(datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
; Timezones
"4pm CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"Thursday 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
)
| true |
(
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"just nüüd"
(datetime 2013 2 12 4 30 00)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 12)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 11)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 13)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"esmasp."
"sellel esmaspäeval"
"see esmaspäev"
(datetime 2013 2 18 :day-of-week 1)
"PI:NAME:<NAME>END_PI, 18. veebruar"
"PI:NAME:<NAME>END_PI, 18. veebruaril"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"PI:NAME:<NAME>END_PIipPI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PIipPI:NAME:<NAME>END_PIeval"
"teisip."
(datetime 2013 2 19)
"kolmapäev"
"kolmapäeval"
"kolmap."
(datetime 2013 2 20)
"PI:NAME:<NAME>END_PI"
"neljapPI:NAME:<NAME>END_PIeval"
"neljap."
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 15)
"laupäev"
"laupäeval"
"laup."
(datetime 2013 2 16)
"pühapäev"
"pühapäeval"
"pühap."
(datetime 2013 2 17)
"1. märtsil"
"esimesel märtsil"
(datetime 2013 3 1 :day 1 :month 3)
"3. märtsil"
(datetime 2013 3 3 :day 3 :month 3)
"3. märts 2015"
"3. märtsil 2015. a"
"3. märtsil 2015"
"3. III 2015"
"03.03.2015"
"3.3.2015"
"3.3.15"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"15."
"viieteistkümnendal"
"15ndal"
(datetime 2013 2 15 :day 15)
"15. veebruar"
"15. veebruaril"
"15ndal veebruaril"
"viieteistkümnes veebruar"
"viieteistkümnendal veebruaril"
"15.2"
"15.02"
"15. II"
(datetime 2013 2 15 :day 15 :month 2)
"Aug 8"
(datetime 2013 8 8 :day 8 :month 8)
"Oktoober 2014"
(datetime 2014 10 :year 2014 :month 10)
"31.10.1974"
"31.10.74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14. aprill 2015"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"järgmine teisipäev" ; when today is Tuesday, "mardi prochain" is a week from now
"järgmisel teisipäeval"
(datetime 2013 2 19 :day-of-week 2)
"järgmise nädala reede"
"järgmise nädala reedel"
(datetime 2013 2 22 :day-of-week 2)
"järgmine märts"
"järgmisel märtsil"
(datetime 2013 3)
"ülejärgmine märts"
"ülejärgmisel märtsil"
(datetime 2014 3)
"Sunday, Feb 10"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Wed, Feb13"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"Monday, Feb 18"
"Mon, February 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
; ;; Cycles
"this week"
"coming week"
(datetime 2013 2 11 :grain :week)
"last week"
(datetime 2013 2 4 :grain :week)
"next week"
(datetime 2013 2 18 :grain :week)
"last month"
(datetime 2013 1)
"next month"
(datetime 2013 3)
"this quarter"
(datetime 2013 1 1 :grain :quarter)
"next quarter"
(datetime 2013 4 1 :grain :quarter)
"third quarter"
(datetime 2013 7 1 :grain :quarter)
"4th quarter 2018"
(datetime 2018 10 1 :grain :quarter)
"last year"
(datetime 2012)
"this year"
(datetime 2013)
"next year"
(datetime 2014)
"last sunday"
"sunday from last week"
"last week's sunday"
(datetime 2013 2 10 :day-of-week 7)
"last tuesday"
(datetime 2013 2 5 :day-of-week 2)
"next tuesday" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"next wednesday" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
"wednesday of next week"
"wednesday next week"
"wednesday after next"
(datetime 2013 2 20 :day-of-week 3)
"friday after next"
(datetime 2013 2 22 :day-of-week 5)
"monday of this week"
(datetime 2013 2 11 :day-of-week 1)
"tuesday of this week"
(datetime 2013 2 12 :day-of-week 2)
"wednesday of this week"
(datetime 2013 2 13 :day-of-week 3)
"the day after tomorrow"
(datetime 2013 2 14)
"the day before yesterday"
(datetime 2013 2 10)
"last Monday of March"
(datetime 2013 3 25 :day-of-week 1)
"last Sunday of March 2014"
(datetime 2014 3 30 :day-of-week 7)
"third day of october"
(datetime 2013 10 3)
"first week of october 2014"
(datetime 2014 10 6 :grain :week)
"last day of october 2015"
(datetime 2015 10 31)
"last week of september 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"first tuesday of october"
(datetime 2013 10 1)
"third tuesday of september 2014"
(datetime 2014 9 16)
"first wednesday of october 2014"
(datetime 2014 10 1)
"second wednesday of october 2014"
(datetime 2014 10 8)
;; nth after
"third tuesday after christmas 2014"
(datetime 2015 1 13)
;; Hours
"at 3am"
"at 3 AM"
"3 oclock am"
"at three am"
(datetime 2013 2 13 3)
"3:18am"
"3:18a"
(datetime 2013 2 12 3 18)
"at 3pm"
"@ 3pm"
"3PM"
"3pm"
"3 oclock pm"
"3 o'clock in the afternoon"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"3ish pm"
"3pm approximately"
"at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm :precision "approximate")
"tomorrow 5pm sharp"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm :precision "exact")
"at 15 past 3pm"
"a quarter past 3pm"
"3:15 in the afternon"
"15:15"
"3:15pm"
"3:15PM"
"3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"at 20 past 3pm"
"3:20 in the afternoon"
"3:20 in afternoon"
"twenty after 3pm"
"3:20p"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
"at half past three pm"
"half past 3 pm"
"15:30"
"3:30pm"
"3:30PM"
"330 p.m."
"3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
"half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"a quarter to noon"
"11:45am"
"15 to noon" ; Ambiguous with interval
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"8 tonight"
"eight tonight"
"8 this evening"
(datetime 2013 2 12 20)
;; Mixing date and time
"at 7:30 PM on Fri, Sep 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"at 9am on Saturday"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Fri, Jul 18, 2014 07:00 PM"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
; ;; Involving periods
"in a sec"
"one second from now"
(datetime 2013 2 12 4 30 1)
"in a minute"
"in one minute"
(datetime 2013 2 12 4 31 0)
"in 2 minutes"
"in 2 more minutes"
"2 minutes from now"
(datetime 2013 2 12 4 32 0)
"in 60 minutes"
(datetime 2013 2 12 5 30 0)
"in half an hour"
(datetime 2013 2 12 5 0 0)
"in 2.5 hours"
"in 2 and an half hours"
(datetime 2013 2 12 7 0 0)
"in one hour"
(datetime 2013 2 12 5 30)
"in a couple hours"
"in a couple of hours"
(datetime 2013 2 12 6 30)
"in a few hours"
"in few hours"
(datetime 2013 2 12 7 30)
"in 24 hours"
(datetime 2013 2 13 4 30)
"in a day"
"a day from now"
(datetime 2013 2 13 4)
"3 years from today"
(datetime 2016 2)
"in 7 days"
(datetime 2013 2 19 4)
"in 1 week"
"in a week"
(datetime 2013 2 19)
"in about half an hour"
(datetime 2013 2 12 5 0 0 :precision "approximate")
"7 days ago"
(datetime 2013 2 5 4)
"14 days ago"
"a fortnight ago"
(datetime 2013 1 29 4)
"a week ago"
"one week ago"
"1 week ago"
(datetime 2013 2 5)
"three weeks ago"
(datetime 2013 1 22)
"three months ago"
(datetime 2012 11 12)
"two years ago"
(datetime 2011 2)
"7 days hence"
(datetime 2013 2 19 4)
"14 days hence"
"a fortnight hence"
(datetime 2013 2 26 4)
"a week hence"
"one week hence"
"1 week hence"
(datetime 2013 2 19)
"three weeks hence"
(datetime 2013 3 5)
"three months hence"
(datetime 2013 5 12)
"two years hence"
(datetime 2015 2)
"one year after christmas"
(datetime 2013 12) ; resolves as after last Xmas...
; Seasons
"this summer"
(datetime-interval [2013 6 21] [2013 9 24])
"this winter"
(datetime-interval [2012 12 21] [2013 3 21])
; US holidays (http://www.timeanddate.com/holidays/us/)
"xmas"
"christmas"
"christmas day"
(datetime 2013 12 25)
"new year's eve"
"new years eve"
(datetime 2013 12 31)
"new year's day"
"new years day"
(datetime 2014 1 1)
"valentine's day"
"valentine day"
(datetime 2013 2 14)
"memorial day"
(datetime 2013 5 27)
"Mother's Day"
(datetime 2013 5 12)
"Father's Day"
(datetime 2013 6 16)
"memorial day week-end"
(datetime-interval [2013 5 24 18] [2013 5 28 0])
"independence day"
"4th of July"
"4 of july"
(datetime 2013 7 4)
"labor day"
(datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"thanksgiving day"
"thanksgiving"
(datetime 2013 11 28)
; Part of day (morning, afternoon...)
"this evening"
"today evening"
"tonight"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"tomorrow evening"
;"Wednesday evening"
"tomorrow night"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"yesterday evening"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"this week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"monday morning"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"february the 15th in the morning"
"15 of february in the morning"
"morning of the 15th of february"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"last 2 seconds"
"last two seconds"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"next 3 seconds"
"next three seconds"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"last 2 minutes"
"last two minutes"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"next 3 minutes"
"next three minutes"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"last 1 hour"
"last one hour"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"next 3 hours"
"next three hours"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"last 2 days"
"last two days"
"past 2 days"
(datetime-interval [2013 2 10] [2013 2 12])
"next 3 days"
"next three days"
(datetime-interval [2013 2 13] [2013 2 16])
"next few days"
(datetime-interval [2013 2 13] [2013 2 16])
"last 2 weeks"
"last two weeks"
"past 2 weeks"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"next 3 weeks"
"next three weeks"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"last 2 months"
"last two months"
(datetime-interval [2012 12] [2013 02])
"next 3 months"
"next three months"
(datetime-interval [2013 3] [2013 6])
"last 2 years"
"last two years"
(datetime-interval [2011] [2013])
"next 3 years"
"next three years"
(datetime-interval [2014] [2017])
; Explicit intervals
"July 13-15"
"July 13 to 15"
"July 13 thru 15"
"July 13 through 15"
"July 13 - July 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Aug 8 - Aug 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"from 9:30 - 11:00 on Thursday"
"between 9:30 and 11:00 on thursday"
"9:30 - 11:00 on Thursday"
"later than 9:30 but before 11:00 on Thursday"
"Thursday from 9:30 to 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Thursday from 9a to 11a"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"1:30 PM on Sat, Sep 21"
(datetime 2013 9 21 13 30)
"within 2 weeks"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"until 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by 2:00pm"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
"by EOD"
(datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
"by EOM"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"by the end of next month"
(datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
; Timezones
"4pm CET"
(datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
"Thursday 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
)
|
[
{
"context": "d b values in the set [0, 255].\n Based on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n ",
"end": 25039,
"score": 0.6748352646827698,
"start": 25024,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "ed on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n * h (number) - The hue, in th",
"end": 25070,
"score": 0.9994984269142151,
"start": 25060,
"tag": "USERNAME",
"value": "mjijackson"
},
{
"context": "d b values in the set [0, 255].\n Based on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n ",
"end": 26130,
"score": 0.9312500953674316,
"start": 26115,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "ed on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n * h (number) - The hue, in th",
"end": 26161,
"score": 0.9994660019874573,
"start": 26151,
"tag": "USERNAME",
"value": "mjijackson"
},
{
"context": "Converts a hue to an RGB color.\n Based on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n ",
"end": 28281,
"score": 0.7735118269920349,
"start": 28266,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "ed on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n * p (number) - No description",
"end": 28312,
"score": 0.9994950294494629,
"start": 28302,
"tag": "USERNAME",
"value": "mjijackson"
},
{
"context": "s h, s and l in the set [0, 1].\n Based on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n ",
"end": 32878,
"score": 0.9969687461853027,
"start": 32863,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "ed on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n * r (number) - The red color ",
"end": 32909,
"score": 0.9996103644371033,
"start": 32899,
"tag": "USERNAME",
"value": "mjijackson"
},
{
"context": "s h, s and v in the set [0, 1].\n Based on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n ",
"end": 34016,
"score": 0.9978277087211609,
"start": 34001,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "ed on code by Michael Jackson (https://github.com/mjijackson)\n\n Parameters:\n * r (number) - The red color ",
"end": 34047,
"score": 0.9996237754821777,
"start": 34037,
"tag": "USERNAME",
"value": "mjijackson"
}
] |
src/phzr/color.cljs
|
dparis/phzr
| 120 |
(ns phzr.color
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn blend-add-
"Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAdd js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-average-
"Takes the average of the source and backdrop colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAverage js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-burn-
"Darkens the backdrop color to reflect the source color.
Painting with white produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-dodge-
"Brightens the backdrop color to reflect the source color.
Painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-darken-
"Selects the darker of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDarken js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-difference-
"Subtracts the darker of the two constituent colors from the lighter.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDifference js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-exclusion-
"Produces an effect similar to that of the Difference mode, but lower in contrast.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendExclusion js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-glow-
"Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendGlow js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-light-
"Multiplies or screens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied;
this is useful for adding shadows to a scene.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-mix-
"Runs blendVividLight on the source and backdrop colors.
If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
This changes all pixels to primary additive colors (red, green, or blue), white, or black.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardMix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-lighten-
"Selects the lighter of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLighten js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-burn-
"An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-dodge-
"An alias for blendAdd, it simply sums the values of the two colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-light-
"This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-multiply-
"Multiplies the backdrop and source color values.
The result color is always at least as dark as either of the two constituent
colors. Multiplying any color with black produces black;
multiplying with white leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendMultiply js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-negation-
"Negation blend mode.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNegation js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-normal-
"Blends the source color, ignoring the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNormal js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-overlay-
"Multiplies or screens the colors, depending on the backdrop color.
Source colors overlay the backdrop while preserving its highlights and shadows.
The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendOverlay js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-phoenix-
"Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPhoenix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-pin-light-
"If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPinLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-reflect-
"Reflect blend mode. This mode is useful when adding shining objects or light zones to images.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendReflect js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-screen-
"Multiplies the complements of the backdrop and source color values, then complements the result.
The result color is always at least as light as either of the two constituent colors.
Screening any color with white produces white; screening with black leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendScreen js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-soft-light-
"Darkens or lightens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
The effect is similar to shining a diffused spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSoftLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-subtract-
"Combines the source and backdrop colors and returns their value minus 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSubtract js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-vivid-light-
"This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom
layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendVividLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn component-to-hex-
"Return a string containing a hex representation of the given color component.
Parameters:
* color (number) - The color channel to get the hex value for, must be a value between 0 and 255.
Returns: string - A string of length 2 characters, i.e. 255 = ff, 100 = 64."
([color]
(phaser->clj
(.componentToHex js/Phaser.Color
(clj->phaser color)))))
(defn create-color-
"A utility function to create a lightweight 'color' object with the default components.
Any components that are not specified will default to zero.
This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
Parameters:
* r (number) {optional} - The red color component, in the range 0 - 255.
* g (number) {optional} - The green color component, in the range 0 - 255.
* b (number) {optional} - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 1.
* h (number) {optional} - The hue, in the range 0 - 1.
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: object - The resulting object with r, g, b, a properties and h, s, l and v."
([]
(phaser->clj
(.createColor js/Phaser.Color)))
([r]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r))))
([r g]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g))))
([r g b]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a h]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h))))
([r g b a h s]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s))))
([r g b a h s l]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([r g b a h s l v]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser v)))))
(defn from-rgba-
"A utility to convert an integer in 0xRRGGBBAA format to a color object.
This does not rely on endianness.
Parameters:
* rgba (number) - An RGBA hex
* out (object) {optional} - The object to use, optional.
Returns: object - A color object."
([rgba]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)))))
(defn get-alpha-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlpha js/Phaser.Color
(clj->phaser color)))))
(defn get-alpha-float-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlphaFloat js/Phaser.Color
(clj->phaser color)))))
(defn get-blue-
"Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue)."
([color]
(phaser->clj
(.getBlue js/Phaser.Color
(clj->phaser color)))))
(defn get-color-
"Given 3 color values this will return an integer representation of it.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xRRGGBB)."
([r g b]
(phaser->clj
(.getColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-color-32-
"Given an alpha and 3 color values this will return an integer representation of it.
Parameters:
* a (number) - The alpha color component, in the range 0 - 255.
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([a r g b]
(phaser->clj
(.getColor32 js/Phaser.Color
(clj->phaser a)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-green-
"Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green)."
([color]
(phaser->clj
(.getGreen js/Phaser.Color
(clj->phaser color)))))
(defn get-random-color-
"Returns a random color value between black and white
Set the min value to start each channel from the given offset.
Set the max value to restrict the maximum color used per channel.
Parameters:
* min (number) - The lowest value to use for the color.
* max (number) - The highest value to use for the color.
* alpha (number) - The alpha value of the returning color (default 255 = fully opaque).
Returns: number - 32-bit color value with alpha."
([min max alpha]
(phaser->clj
(.getRandomColor js/Phaser.Color
(clj->phaser min)
(clj->phaser max)
(clj->phaser alpha)))))
(defn get-red-
"Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red)."
([color]
(phaser->clj
(.getRed js/Phaser.Color
(clj->phaser color)))))
(defn get-rgb-
"Return the component parts of a color as an Object with the properties alpha, red, green, blue.
Alpha will only be set if it exist in the given color (0xAARRGGBB)
Parameters:
* color (number) - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
Returns: object - An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given."
([color]
(phaser->clj
(.getRGB js/Phaser.Color
(clj->phaser color)))))
(defn get-web-rgb-
"Returns a CSS friendly string value from the given color.
Parameters:
* color (number | Object) - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
Returns: string - A string in the format: 'rgba(r,g,b,a)'"
([color]
(phaser->clj
(.getWebRGB js/Phaser.Color
(clj->phaser color)))))
(defn hex-to-color-
"Converts a hex string into a Phaser Color object.
The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional '#' or '0x', or be unprefixed.
An alpha channel is _not_ supported.
Parameters:
* hex (string) - The color string in a hex format.
* out (object) {optional} - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([hex]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex))))
([hex out]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex)
(clj->phaser out)))))
(defn hex-to-rgb-
"Converts a hex string into an integer color value.
Parameters:
* hex (string) - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
Returns: number - The rgb color value in the format 0xAARRGGBB."
([hex]
(phaser->clj
(.hexToRGB js/Phaser.Color
(clj->phaser hex)))))
(defn hs-lto-rgb-
"Converts an HSL (hue, saturation and lightness) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by Michael Jackson (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* l (number) - The lightness, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s l]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([h s l out]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser out)))))
(defn hs-vto-rgb-
"Converts an HSV (hue, saturation and value) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by Michael Jackson (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* v (number) - The value, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s v]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v))))
([h s v out]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v)
(clj->phaser out)))))
(defn hsl-color-wheel-
"Get HSL color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSL color wheel."
([]
(phaser->clj
(.HSLColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s))))
([s l]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser l)))))
(defn hsv-color-wheel-
"Get HSV color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSV color wheel."
([]
(phaser->clj
(.HSVColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s))))
([s v]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser v)))))
(defn hue-to-color-
"Converts a hue to an RGB color.
Based on code by Michael Jackson (https://github.com/mjijackson)
Parameters:
* p (number) - No description
* q (number) - No description
* t (number) - No description
Returns: number - The color component value."
([p q t]
(phaser->clj
(.hueToColor js/Phaser.Color
(clj->phaser p)
(clj->phaser q)
(clj->phaser t)))))
(defn interpolate-color-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color-1 (number) - The first color value.
* color-2 (number) - The second color value.
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* alpha (number) - The alpha of the returned color.
Returns: number - The interpolated color value."
([color-1 color-2 steps current-step alpha]
(phaser->clj
(.interpolateColor js/Phaser.Color
(clj->phaser color-1)
(clj->phaser color-2)
(clj->phaser steps)
(clj->phaser current-step)
(clj->phaser alpha)))))
(defn interpolate-color-with-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color (number) - The first color value.
* r (number) - The red color value, between 0 and 0xFF (255).
* g (number) - The green color value, between 0 and 0xFF (255).
* b (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([color r g b steps current-step]
(phaser->clj
(.interpolateColorWithRGB js/Phaser.Color
(clj->phaser color)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn interpolate-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* r-1 (number) - The red color value, between 0 and 0xFF (255).
* g-1 (number) - The green color value, between 0 and 0xFF (255).
* b-1 (number) - The blue color value, between 0 and 0xFF (255).
* r-2 (number) - The red color value, between 0 and 0xFF (255).
* g-2 (number) - The green color value, between 0 and 0xFF (255).
* b-2 (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([r-1 g-1 b-1 r-2 g-2 b-2 steps current-step]
(phaser->clj
(.interpolateRGB js/Phaser.Color
(clj->phaser r-1)
(clj->phaser g-1)
(clj->phaser b-1)
(clj->phaser r-2)
(clj->phaser g-2)
(clj->phaser b-2)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn pack-pixel-
"Packs the r, g, b, a components into a single integer, for use with Int32Array.
If device is little endian then ABGR order is used. Otherwise RGBA order is used.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - The packed color as uint32"
([r g b a]
(phaser->clj
(.packPixel js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn rg-bto-hsl-
"Converts an RGB color value to HSL (hue, saturation and lightness).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
Based on code by Michael Jackson (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and lightness values set in the h, s and l properties."
([r g b]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-hsv-
"Converts an RGB color value to HSV (hue, saturation and value).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
Based on code by Michael Jackson (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and value set in the h, s and v properties."
([r g b]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-string-
"Converts the given color values into a string.
If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 255.
* prefix (string) {optional} - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
Returns: string - A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`."
([r g b]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a prefix]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser prefix)))))
(defn to-rgba-
"A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - A RGBA-packed 32 bit integer"
([r g b a]
(phaser->clj
(.toRGBA js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn unpack-pixel-
"Unpacks the r, g, b, a components into the specified color object, or a new
object, for use with Int32Array. If little endian, then ABGR order is used when
unpacking, otherwise, RGBA order is used. The resulting color object has the
`r, g, b, a` properties which are unrelated to endianness.
Note that the integer is assumed to be packed in the correct endianness. On little-endian
the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
Parameters:
* rgba (number) - The integer, packed in endian order by packPixel.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
* hsl (boolean) {optional} - Also convert the rgb values into hsl?
* hsv (boolean) {optional} - Also convert the rgb values into hsv?
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([rgba]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out))))
([rgba out hsl]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl))))
([rgba out hsl hsv]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl)
(clj->phaser hsv)))))
(defn update-color-
"Takes a color object and updates the rgba property.
Parameters:
* out (object) - The color object to update.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([out]
(phaser->clj
(.updateColor js/Phaser.Color
(clj->phaser out)))))
(defn value-to-color-
"Converts a value - a 'hex' string, a 'CSS 'web' string', or a number - into red, green, blue, and alpha components.
The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
An alpha channel is _not_ supported when specifying a hex string.
Parameters:
* value (string | number) - The color expressed as a recognized string format or a packed integer.
* out (object) {optional} - The object to use for the output. If not provided a new object will be created.
Returns: object - The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties."
([value]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value))))
([value out]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value)
(clj->phaser out)))))
(defn web-to-color-
"Converts a CSS 'web' string into a Phaser Color object.
The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
Parameters:
* web (string) - The color string in CSS 'web' format.
* out (object) {optional} - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
Returns: object - An object with the red, green, blue and alpha values set in the r, g, b and a properties."
([web]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web))))
([web out]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web)
(clj->phaser out)))))
|
37118
|
(ns phzr.color
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn blend-add-
"Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAdd js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-average-
"Takes the average of the source and backdrop colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAverage js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-burn-
"Darkens the backdrop color to reflect the source color.
Painting with white produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-dodge-
"Brightens the backdrop color to reflect the source color.
Painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-darken-
"Selects the darker of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDarken js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-difference-
"Subtracts the darker of the two constituent colors from the lighter.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDifference js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-exclusion-
"Produces an effect similar to that of the Difference mode, but lower in contrast.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendExclusion js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-glow-
"Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendGlow js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-light-
"Multiplies or screens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied;
this is useful for adding shadows to a scene.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-mix-
"Runs blendVividLight on the source and backdrop colors.
If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
This changes all pixels to primary additive colors (red, green, or blue), white, or black.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardMix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-lighten-
"Selects the lighter of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLighten js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-burn-
"An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-dodge-
"An alias for blendAdd, it simply sums the values of the two colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-light-
"This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-multiply-
"Multiplies the backdrop and source color values.
The result color is always at least as dark as either of the two constituent
colors. Multiplying any color with black produces black;
multiplying with white leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendMultiply js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-negation-
"Negation blend mode.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNegation js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-normal-
"Blends the source color, ignoring the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNormal js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-overlay-
"Multiplies or screens the colors, depending on the backdrop color.
Source colors overlay the backdrop while preserving its highlights and shadows.
The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendOverlay js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-phoenix-
"Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPhoenix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-pin-light-
"If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPinLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-reflect-
"Reflect blend mode. This mode is useful when adding shining objects or light zones to images.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendReflect js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-screen-
"Multiplies the complements of the backdrop and source color values, then complements the result.
The result color is always at least as light as either of the two constituent colors.
Screening any color with white produces white; screening with black leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendScreen js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-soft-light-
"Darkens or lightens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
The effect is similar to shining a diffused spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSoftLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-subtract-
"Combines the source and backdrop colors and returns their value minus 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSubtract js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-vivid-light-
"This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom
layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendVividLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn component-to-hex-
"Return a string containing a hex representation of the given color component.
Parameters:
* color (number) - The color channel to get the hex value for, must be a value between 0 and 255.
Returns: string - A string of length 2 characters, i.e. 255 = ff, 100 = 64."
([color]
(phaser->clj
(.componentToHex js/Phaser.Color
(clj->phaser color)))))
(defn create-color-
"A utility function to create a lightweight 'color' object with the default components.
Any components that are not specified will default to zero.
This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
Parameters:
* r (number) {optional} - The red color component, in the range 0 - 255.
* g (number) {optional} - The green color component, in the range 0 - 255.
* b (number) {optional} - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 1.
* h (number) {optional} - The hue, in the range 0 - 1.
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: object - The resulting object with r, g, b, a properties and h, s, l and v."
([]
(phaser->clj
(.createColor js/Phaser.Color)))
([r]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r))))
([r g]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g))))
([r g b]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a h]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h))))
([r g b a h s]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s))))
([r g b a h s l]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([r g b a h s l v]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser v)))))
(defn from-rgba-
"A utility to convert an integer in 0xRRGGBBAA format to a color object.
This does not rely on endianness.
Parameters:
* rgba (number) - An RGBA hex
* out (object) {optional} - The object to use, optional.
Returns: object - A color object."
([rgba]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)))))
(defn get-alpha-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlpha js/Phaser.Color
(clj->phaser color)))))
(defn get-alpha-float-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlphaFloat js/Phaser.Color
(clj->phaser color)))))
(defn get-blue-
"Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue)."
([color]
(phaser->clj
(.getBlue js/Phaser.Color
(clj->phaser color)))))
(defn get-color-
"Given 3 color values this will return an integer representation of it.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xRRGGBB)."
([r g b]
(phaser->clj
(.getColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-color-32-
"Given an alpha and 3 color values this will return an integer representation of it.
Parameters:
* a (number) - The alpha color component, in the range 0 - 255.
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([a r g b]
(phaser->clj
(.getColor32 js/Phaser.Color
(clj->phaser a)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-green-
"Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green)."
([color]
(phaser->clj
(.getGreen js/Phaser.Color
(clj->phaser color)))))
(defn get-random-color-
"Returns a random color value between black and white
Set the min value to start each channel from the given offset.
Set the max value to restrict the maximum color used per channel.
Parameters:
* min (number) - The lowest value to use for the color.
* max (number) - The highest value to use for the color.
* alpha (number) - The alpha value of the returning color (default 255 = fully opaque).
Returns: number - 32-bit color value with alpha."
([min max alpha]
(phaser->clj
(.getRandomColor js/Phaser.Color
(clj->phaser min)
(clj->phaser max)
(clj->phaser alpha)))))
(defn get-red-
"Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red)."
([color]
(phaser->clj
(.getRed js/Phaser.Color
(clj->phaser color)))))
(defn get-rgb-
"Return the component parts of a color as an Object with the properties alpha, red, green, blue.
Alpha will only be set if it exist in the given color (0xAARRGGBB)
Parameters:
* color (number) - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
Returns: object - An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given."
([color]
(phaser->clj
(.getRGB js/Phaser.Color
(clj->phaser color)))))
(defn get-web-rgb-
"Returns a CSS friendly string value from the given color.
Parameters:
* color (number | Object) - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
Returns: string - A string in the format: 'rgba(r,g,b,a)'"
([color]
(phaser->clj
(.getWebRGB js/Phaser.Color
(clj->phaser color)))))
(defn hex-to-color-
"Converts a hex string into a Phaser Color object.
The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional '#' or '0x', or be unprefixed.
An alpha channel is _not_ supported.
Parameters:
* hex (string) - The color string in a hex format.
* out (object) {optional} - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([hex]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex))))
([hex out]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex)
(clj->phaser out)))))
(defn hex-to-rgb-
"Converts a hex string into an integer color value.
Parameters:
* hex (string) - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
Returns: number - The rgb color value in the format 0xAARRGGBB."
([hex]
(phaser->clj
(.hexToRGB js/Phaser.Color
(clj->phaser hex)))))
(defn hs-lto-rgb-
"Converts an HSL (hue, saturation and lightness) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by <NAME> (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* l (number) - The lightness, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s l]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([h s l out]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser out)))))
(defn hs-vto-rgb-
"Converts an HSV (hue, saturation and value) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by <NAME> (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* v (number) - The value, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s v]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v))))
([h s v out]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v)
(clj->phaser out)))))
(defn hsl-color-wheel-
"Get HSL color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSL color wheel."
([]
(phaser->clj
(.HSLColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s))))
([s l]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser l)))))
(defn hsv-color-wheel-
"Get HSV color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSV color wheel."
([]
(phaser->clj
(.HSVColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s))))
([s v]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser v)))))
(defn hue-to-color-
"Converts a hue to an RGB color.
Based on code by <NAME> (https://github.com/mjijackson)
Parameters:
* p (number) - No description
* q (number) - No description
* t (number) - No description
Returns: number - The color component value."
([p q t]
(phaser->clj
(.hueToColor js/Phaser.Color
(clj->phaser p)
(clj->phaser q)
(clj->phaser t)))))
(defn interpolate-color-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color-1 (number) - The first color value.
* color-2 (number) - The second color value.
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* alpha (number) - The alpha of the returned color.
Returns: number - The interpolated color value."
([color-1 color-2 steps current-step alpha]
(phaser->clj
(.interpolateColor js/Phaser.Color
(clj->phaser color-1)
(clj->phaser color-2)
(clj->phaser steps)
(clj->phaser current-step)
(clj->phaser alpha)))))
(defn interpolate-color-with-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color (number) - The first color value.
* r (number) - The red color value, between 0 and 0xFF (255).
* g (number) - The green color value, between 0 and 0xFF (255).
* b (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([color r g b steps current-step]
(phaser->clj
(.interpolateColorWithRGB js/Phaser.Color
(clj->phaser color)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn interpolate-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* r-1 (number) - The red color value, between 0 and 0xFF (255).
* g-1 (number) - The green color value, between 0 and 0xFF (255).
* b-1 (number) - The blue color value, between 0 and 0xFF (255).
* r-2 (number) - The red color value, between 0 and 0xFF (255).
* g-2 (number) - The green color value, between 0 and 0xFF (255).
* b-2 (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([r-1 g-1 b-1 r-2 g-2 b-2 steps current-step]
(phaser->clj
(.interpolateRGB js/Phaser.Color
(clj->phaser r-1)
(clj->phaser g-1)
(clj->phaser b-1)
(clj->phaser r-2)
(clj->phaser g-2)
(clj->phaser b-2)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn pack-pixel-
"Packs the r, g, b, a components into a single integer, for use with Int32Array.
If device is little endian then ABGR order is used. Otherwise RGBA order is used.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - The packed color as uint32"
([r g b a]
(phaser->clj
(.packPixel js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn rg-bto-hsl-
"Converts an RGB color value to HSL (hue, saturation and lightness).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
Based on code by <NAME> (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and lightness values set in the h, s and l properties."
([r g b]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-hsv-
"Converts an RGB color value to HSV (hue, saturation and value).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
Based on code by <NAME> (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and value set in the h, s and v properties."
([r g b]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-string-
"Converts the given color values into a string.
If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 255.
* prefix (string) {optional} - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
Returns: string - A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`."
([r g b]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a prefix]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser prefix)))))
(defn to-rgba-
"A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - A RGBA-packed 32 bit integer"
([r g b a]
(phaser->clj
(.toRGBA js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn unpack-pixel-
"Unpacks the r, g, b, a components into the specified color object, or a new
object, for use with Int32Array. If little endian, then ABGR order is used when
unpacking, otherwise, RGBA order is used. The resulting color object has the
`r, g, b, a` properties which are unrelated to endianness.
Note that the integer is assumed to be packed in the correct endianness. On little-endian
the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
Parameters:
* rgba (number) - The integer, packed in endian order by packPixel.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
* hsl (boolean) {optional} - Also convert the rgb values into hsl?
* hsv (boolean) {optional} - Also convert the rgb values into hsv?
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([rgba]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out))))
([rgba out hsl]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl))))
([rgba out hsl hsv]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl)
(clj->phaser hsv)))))
(defn update-color-
"Takes a color object and updates the rgba property.
Parameters:
* out (object) - The color object to update.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([out]
(phaser->clj
(.updateColor js/Phaser.Color
(clj->phaser out)))))
(defn value-to-color-
"Converts a value - a 'hex' string, a 'CSS 'web' string', or a number - into red, green, blue, and alpha components.
The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
An alpha channel is _not_ supported when specifying a hex string.
Parameters:
* value (string | number) - The color expressed as a recognized string format or a packed integer.
* out (object) {optional} - The object to use for the output. If not provided a new object will be created.
Returns: object - The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties."
([value]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value))))
([value out]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value)
(clj->phaser out)))))
(defn web-to-color-
"Converts a CSS 'web' string into a Phaser Color object.
The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
Parameters:
* web (string) - The color string in CSS 'web' format.
* out (object) {optional} - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
Returns: object - An object with the red, green, blue and alpha values set in the r, g, b and a properties."
([web]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web))))
([web out]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web)
(clj->phaser out)))))
| true |
(ns phzr.color
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn blend-add-
"Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAdd js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-average-
"Takes the average of the source and backdrop colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendAverage js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-burn-
"Darkens the backdrop color to reflect the source color.
Painting with white produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-color-dodge-
"Brightens the backdrop color to reflect the source color.
Painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendColorDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-darken-
"Selects the darker of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDarken js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-difference-
"Subtracts the darker of the two constituent colors from the lighter.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendDifference js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-exclusion-
"Produces an effect similar to that of the Difference mode, but lower in contrast.
Painting with white inverts the backdrop color; painting with black produces no change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendExclusion js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-glow-
"Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendGlow js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-light-
"Multiplies or screens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied;
this is useful for adding shadows to a scene.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-hard-mix-
"Runs blendVividLight on the source and backdrop colors.
If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
This changes all pixels to primary additive colors (red, green, or blue), white, or black.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendHardMix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-lighten-
"Selects the lighter of the backdrop and source colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLighten js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-burn-
"An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearBurn js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-dodge-
"An alias for blendAdd, it simply sums the values of the two colors.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearDodge js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-linear-light-
"This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendLinearLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-multiply-
"Multiplies the backdrop and source color values.
The result color is always at least as dark as either of the two constituent
colors. Multiplying any color with black produces black;
multiplying with white leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendMultiply js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-negation-
"Negation blend mode.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNegation js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-normal-
"Blends the source color, ignoring the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendNormal js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-overlay-
"Multiplies or screens the colors, depending on the backdrop color.
Source colors overlay the backdrop while preserving its highlights and shadows.
The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendOverlay js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-phoenix-
"Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPhoenix js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-pin-light-
"If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendPinLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-reflect-
"Reflect blend mode. This mode is useful when adding shining objects or light zones to images.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendReflect js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-screen-
"Multiplies the complements of the backdrop and source color values, then complements the result.
The result color is always at least as light as either of the two constituent colors.
Screening any color with white produces white; screening with black leaves the original color unchanged.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendScreen js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-soft-light-
"Darkens or lightens the colors, depending on the source color value.
If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged;
this is useful for adding highlights to a scene.
If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in.
The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
if it is equal to 0.5, the backdrop is unchanged.
Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
The effect is similar to shining a diffused spotlight on the backdrop.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSoftLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-subtract-
"Combines the source and backdrop colors and returns their value minus 255.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendSubtract js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn blend-vivid-light-
"This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom
layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
Parameters:
* a (integer) - The source color to blend, in the range 1 to 255.
* b (integer) - The backdrop color to blend, in the range 1 to 255.
Returns: integer - The blended color value, in the range 1 to 255."
([a b]
(phaser->clj
(.blendVividLight js/Phaser.Color
(clj->phaser a)
(clj->phaser b)))))
(defn component-to-hex-
"Return a string containing a hex representation of the given color component.
Parameters:
* color (number) - The color channel to get the hex value for, must be a value between 0 and 255.
Returns: string - A string of length 2 characters, i.e. 255 = ff, 100 = 64."
([color]
(phaser->clj
(.componentToHex js/Phaser.Color
(clj->phaser color)))))
(defn create-color-
"A utility function to create a lightweight 'color' object with the default components.
Any components that are not specified will default to zero.
This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
Parameters:
* r (number) {optional} - The red color component, in the range 0 - 255.
* g (number) {optional} - The green color component, in the range 0 - 255.
* b (number) {optional} - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 1.
* h (number) {optional} - The hue, in the range 0 - 1.
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: object - The resulting object with r, g, b, a properties and h, s, l and v."
([]
(phaser->clj
(.createColor js/Phaser.Color)))
([r]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r))))
([r g]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g))))
([r g b]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a h]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h))))
([r g b a h s]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s))))
([r g b a h s l]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([r g b a h s l v]
(phaser->clj
(.createColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser v)))))
(defn from-rgba-
"A utility to convert an integer in 0xRRGGBBAA format to a color object.
This does not rely on endianness.
Parameters:
* rgba (number) - An RGBA hex
* out (object) {optional} - The object to use, optional.
Returns: object - A color object."
([rgba]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.fromRGBA js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)))))
(defn get-alpha-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlpha js/Phaser.Color
(clj->phaser color)))))
(defn get-alpha-float-
"Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent))."
([color]
(phaser->clj
(.getAlphaFloat js/Phaser.Color
(clj->phaser color)))))
(defn get-blue-
"Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue)."
([color]
(phaser->clj
(.getBlue js/Phaser.Color
(clj->phaser color)))))
(defn get-color-
"Given 3 color values this will return an integer representation of it.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xRRGGBB)."
([r g b]
(phaser->clj
(.getColor js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-color-32-
"Given an alpha and 3 color values this will return an integer representation of it.
Parameters:
* a (number) - The alpha color component, in the range 0 - 255.
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([a r g b]
(phaser->clj
(.getColor32 js/Phaser.Color
(clj->phaser a)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)))))
(defn get-green-
"Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green)."
([color]
(phaser->clj
(.getGreen js/Phaser.Color
(clj->phaser color)))))
(defn get-random-color-
"Returns a random color value between black and white
Set the min value to start each channel from the given offset.
Set the max value to restrict the maximum color used per channel.
Parameters:
* min (number) - The lowest value to use for the color.
* max (number) - The highest value to use for the color.
* alpha (number) - The alpha value of the returning color (default 255 = fully opaque).
Returns: number - 32-bit color value with alpha."
([min max alpha]
(phaser->clj
(.getRandomColor js/Phaser.Color
(clj->phaser min)
(clj->phaser max)
(clj->phaser alpha)))))
(defn get-red-
"Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
Parameters:
* color (number) - In the format 0xAARRGGBB.
Returns: number - The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red)."
([color]
(phaser->clj
(.getRed js/Phaser.Color
(clj->phaser color)))))
(defn get-rgb-
"Return the component parts of a color as an Object with the properties alpha, red, green, blue.
Alpha will only be set if it exist in the given color (0xAARRGGBB)
Parameters:
* color (number) - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
Returns: object - An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given."
([color]
(phaser->clj
(.getRGB js/Phaser.Color
(clj->phaser color)))))
(defn get-web-rgb-
"Returns a CSS friendly string value from the given color.
Parameters:
* color (number | Object) - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
Returns: string - A string in the format: 'rgba(r,g,b,a)'"
([color]
(phaser->clj
(.getWebRGB js/Phaser.Color
(clj->phaser color)))))
(defn hex-to-color-
"Converts a hex string into a Phaser Color object.
The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional '#' or '0x', or be unprefixed.
An alpha channel is _not_ supported.
Parameters:
* hex (string) - The color string in a hex format.
* out (object) {optional} - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([hex]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex))))
([hex out]
(phaser->clj
(.hexToColor js/Phaser.Color
(clj->phaser hex)
(clj->phaser out)))))
(defn hex-to-rgb-
"Converts a hex string into an integer color value.
Parameters:
* hex (string) - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
Returns: number - The rgb color value in the format 0xAARRGGBB."
([hex]
(phaser->clj
(.hexToRGB js/Phaser.Color
(clj->phaser hex)))))
(defn hs-lto-rgb-
"Converts an HSL (hue, saturation and lightness) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by PI:NAME:<NAME>END_PI (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* l (number) - The lightness, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s l]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l))))
([h s l out]
(phaser->clj
(.HSLtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser l)
(clj->phaser out)))))
(defn hs-vto-rgb-
"Converts an HSV (hue, saturation and value) color value to RGB.
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
Based on code by PI:NAME:<NAME>END_PI (https://github.com/mjijackson)
Parameters:
* h (number) - The hue, in the range 0 - 1.
* s (number) - The saturation, in the range 0 - 1.
* v (number) - The value, in the range 0 - 1.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([h s v]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v))))
([h s v out]
(phaser->clj
(.HSVtoRGB js/Phaser.Color
(clj->phaser h)
(clj->phaser s)
(clj->phaser v)
(clj->phaser out)))))
(defn hsl-color-wheel-
"Get HSL color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* l (number) {optional} - The lightness, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSL color wheel."
([]
(phaser->clj
(.HSLColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s))))
([s l]
(phaser->clj
(.HSLColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser l)))))
(defn hsv-color-wheel-
"Get HSV color wheel values in an array which will be 360 elements in size.
Parameters:
* s (number) {optional} - The saturation, in the range 0 - 1.
* v (number) {optional} - The value, in the range 0 - 1.
Returns: array - An array containing 360 elements corresponding to the HSV color wheel."
([]
(phaser->clj
(.HSVColorWheel js/Phaser.Color)))
([s]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s))))
([s v]
(phaser->clj
(.HSVColorWheel js/Phaser.Color
(clj->phaser s)
(clj->phaser v)))))
(defn hue-to-color-
"Converts a hue to an RGB color.
Based on code by PI:NAME:<NAME>END_PI (https://github.com/mjijackson)
Parameters:
* p (number) - No description
* q (number) - No description
* t (number) - No description
Returns: number - The color component value."
([p q t]
(phaser->clj
(.hueToColor js/Phaser.Color
(clj->phaser p)
(clj->phaser q)
(clj->phaser t)))))
(defn interpolate-color-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color-1 (number) - The first color value.
* color-2 (number) - The second color value.
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* alpha (number) - The alpha of the returned color.
Returns: number - The interpolated color value."
([color-1 color-2 steps current-step alpha]
(phaser->clj
(.interpolateColor js/Phaser.Color
(clj->phaser color-1)
(clj->phaser color-2)
(clj->phaser steps)
(clj->phaser current-step)
(clj->phaser alpha)))))
(defn interpolate-color-with-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* color (number) - The first color value.
* r (number) - The red color value, between 0 and 0xFF (255).
* g (number) - The green color value, between 0 and 0xFF (255).
* b (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([color r g b steps current-step]
(phaser->clj
(.interpolateColorWithRGB js/Phaser.Color
(clj->phaser color)
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn interpolate-rgb-
"Interpolates the two given colours based on the supplied step and currentStep properties.
Parameters:
* r-1 (number) - The red color value, between 0 and 0xFF (255).
* g-1 (number) - The green color value, between 0 and 0xFF (255).
* b-1 (number) - The blue color value, between 0 and 0xFF (255).
* r-2 (number) - The red color value, between 0 and 0xFF (255).
* g-2 (number) - The green color value, between 0 and 0xFF (255).
* b-2 (number) - The blue color value, between 0 and 0xFF (255).
* steps (number) - The number of steps to run the interpolation over.
* current-step (number) - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
Returns: number - The interpolated color value."
([r-1 g-1 b-1 r-2 g-2 b-2 steps current-step]
(phaser->clj
(.interpolateRGB js/Phaser.Color
(clj->phaser r-1)
(clj->phaser g-1)
(clj->phaser b-1)
(clj->phaser r-2)
(clj->phaser g-2)
(clj->phaser b-2)
(clj->phaser steps)
(clj->phaser current-step)))))
(defn pack-pixel-
"Packs the r, g, b, a components into a single integer, for use with Int32Array.
If device is little endian then ABGR order is used. Otherwise RGBA order is used.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - The packed color as uint32"
([r g b a]
(phaser->clj
(.packPixel js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn rg-bto-hsl-
"Converts an RGB color value to HSL (hue, saturation and lightness).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
Based on code by PI:NAME:<NAME>END_PI (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and lightness values set in the h, s and l properties."
([r g b]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSL js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-hsv-
"Converts an RGB color value to HSV (hue, saturation and value).
Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
Based on code by PI:NAME:<NAME>END_PI (https://github.com/mjijackson)
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* out (object) {optional} - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
Returns: object - An object with the hue, saturation and value set in the h, s and v properties."
([r g b]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b out]
(phaser->clj
(.RGBtoHSV js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser out)))))
(defn rg-bto-string-
"Converts the given color values into a string.
If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) {optional} - The alpha color component, in the range 0 - 255.
* prefix (string) {optional} - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
Returns: string - A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`."
([r g b]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b))))
([r g b a]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a))))
([r g b a prefix]
(phaser->clj
(.RGBtoString js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)
(clj->phaser prefix)))))
(defn to-rgba-
"A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
Parameters:
* r (number) - The red color component, in the range 0 - 255.
* g (number) - The green color component, in the range 0 - 255.
* b (number) - The blue color component, in the range 0 - 255.
* a (number) - The alpha color component, in the range 0 - 255.
Returns: number - A RGBA-packed 32 bit integer"
([r g b a]
(phaser->clj
(.toRGBA js/Phaser.Color
(clj->phaser r)
(clj->phaser g)
(clj->phaser b)
(clj->phaser a)))))
(defn unpack-pixel-
"Unpacks the r, g, b, a components into the specified color object, or a new
object, for use with Int32Array. If little endian, then ABGR order is used when
unpacking, otherwise, RGBA order is used. The resulting color object has the
`r, g, b, a` properties which are unrelated to endianness.
Note that the integer is assumed to be packed in the correct endianness. On little-endian
the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
Parameters:
* rgba (number) - The integer, packed in endian order by packPixel.
* out (object) {optional} - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
* hsl (boolean) {optional} - Also convert the rgb values into hsl?
* hsv (boolean) {optional} - Also convert the rgb values into hsv?
Returns: object - An object with the red, green and blue values set in the r, g and b properties."
([rgba]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba))))
([rgba out]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out))))
([rgba out hsl]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl))))
([rgba out hsl hsv]
(phaser->clj
(.unpackPixel js/Phaser.Color
(clj->phaser rgba)
(clj->phaser out)
(clj->phaser hsl)
(clj->phaser hsv)))))
(defn update-color-
"Takes a color object and updates the rgba property.
Parameters:
* out (object) - The color object to update.
Returns: number - A native color value integer (format: 0xAARRGGBB)."
([out]
(phaser->clj
(.updateColor js/Phaser.Color
(clj->phaser out)))))
(defn value-to-color-
"Converts a value - a 'hex' string, a 'CSS 'web' string', or a number - into red, green, blue, and alpha components.
The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
An alpha channel is _not_ supported when specifying a hex string.
Parameters:
* value (string | number) - The color expressed as a recognized string format or a packed integer.
* out (object) {optional} - The object to use for the output. If not provided a new object will be created.
Returns: object - The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties."
([value]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value))))
([value out]
(phaser->clj
(.valueToColor js/Phaser.Color
(clj->phaser value)
(clj->phaser out)))))
(defn web-to-color-
"Converts a CSS 'web' string into a Phaser Color object.
The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
Parameters:
* web (string) - The color string in CSS 'web' format.
* out (object) {optional} - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
Returns: object - An object with the red, green, blue and alpha values set in the r, g, b and a properties."
([web]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web))))
([web out]
(phaser->clj
(.webToColor js/Phaser.Color
(clj->phaser web)
(clj->phaser out)))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998130202293396,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998209476470947,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] |
editor/test/editor/geom_test.clj
|
cmarincia/defold
| 0 |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.geom-test
(:require [clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test :refer :all]
[editor.types :as types]
[editor.geom :as geom]
[schema.test])
(:import [com.defold.util Geometry]
[javax.vecmath Point3d]))
(use-fixtures :once schema.test/validate-schemas)
(def gen-float (gen/fmap (fn [[dec frac]]
(float (+ (float dec) (/ (rem (float frac) 10000.0) 10000.0))))
(gen/tuple gen/int (gen/resize 10000 gen/int))))
(defspec to-short-uv-works
(prop/for-all [fuv gen-float]
(= (Geometry/toShortUV fuv) (geom/to-short-uv fuv))))
(deftest to-short-uv-problem-cases
(testing "Avoid Clojure's off-by-one cases"
(are [f-uv s-uv] (= s-uv (Geometry/toShortUV f-uv) (geom/to-short-uv f-uv))
0 0
1.3785 24804
6.3785 24799
-9.456 -29875
-21.0141 -903)))
(def gen-point (gen/fmap (fn [[x y z]] (Point3d. x y z))
(gen/tuple gen/int gen/int gen/int)))
(def gen-aabb (gen/fmap (fn [vs]
(let [[[x0 x1] [y0 y1] [z0 z1]] (map sort (partition 2 vs))]
(types/->AABB (Point3d. x0 y0 z0)
(Point3d. x1 y1 z1))))
(gen/tuple gen/int gen/int gen/int
gen/int gen/int gen/int)))
(defspec aabb-union-reflexive
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(= (geom/aabb-union aabb1 aabb2)
(geom/aabb-union aabb2 aabb1))))
(defspec aabb-union-non-degenerate
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(let [u (geom/aabb-union aabb1 aabb2)]
(and (<= (.. u min x) (.. u max x))
(<= (.. u min y) (.. u max y))
(<= (.. u min z) (.. u max z))))))
(deftest aabb-union-null []
(let [aabb (types/->AABB (Point3d. 0 0 0) (Point3d. 10 10 10))]
(is (= aabb (geom/aabb-union aabb geom/null-aabb)))
(is (= aabb (geom/aabb-union geom/null-aabb aabb)))
(is (= aabb (geom/aabb-union aabb aabb)))
(is (= geom/null-aabb (geom/aabb-union geom/null-aabb geom/null-aabb)))
(is (geom/null-aabb? (geom/aabb-union geom/null-aabb geom/null-aabb)))))
(defspec aabb-incorporates-points
(prop/for-all [pointlist (gen/vector gen-point)]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)]
(every? #(geom/aabb-contains? aabb %) pointlist))))
(defmacro reduce-field
[f field coll]
`(reduce ~f (map #(~field %) ~coll)))
(defspec aabb-incorporates-minimally
(prop/for-all [pointlist (gen/such-that #(< 0 (count %)) (gen/vector gen-point))]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)
max-v (Point3d. (reduce-field max .x pointlist)
(reduce-field max .y pointlist)
(reduce-field max .z pointlist))
min-v (Point3d. (reduce-field min .x pointlist)
(reduce-field min .y pointlist)
(reduce-field min .z pointlist))]
(and
(= max-v (.max aabb))
(= min-v (.min aabb))))))
|
50433
|
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.geom-test
(:require [clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test :refer :all]
[editor.types :as types]
[editor.geom :as geom]
[schema.test])
(:import [com.defold.util Geometry]
[javax.vecmath Point3d]))
(use-fixtures :once schema.test/validate-schemas)
(def gen-float (gen/fmap (fn [[dec frac]]
(float (+ (float dec) (/ (rem (float frac) 10000.0) 10000.0))))
(gen/tuple gen/int (gen/resize 10000 gen/int))))
(defspec to-short-uv-works
(prop/for-all [fuv gen-float]
(= (Geometry/toShortUV fuv) (geom/to-short-uv fuv))))
(deftest to-short-uv-problem-cases
(testing "Avoid Clojure's off-by-one cases"
(are [f-uv s-uv] (= s-uv (Geometry/toShortUV f-uv) (geom/to-short-uv f-uv))
0 0
1.3785 24804
6.3785 24799
-9.456 -29875
-21.0141 -903)))
(def gen-point (gen/fmap (fn [[x y z]] (Point3d. x y z))
(gen/tuple gen/int gen/int gen/int)))
(def gen-aabb (gen/fmap (fn [vs]
(let [[[x0 x1] [y0 y1] [z0 z1]] (map sort (partition 2 vs))]
(types/->AABB (Point3d. x0 y0 z0)
(Point3d. x1 y1 z1))))
(gen/tuple gen/int gen/int gen/int
gen/int gen/int gen/int)))
(defspec aabb-union-reflexive
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(= (geom/aabb-union aabb1 aabb2)
(geom/aabb-union aabb2 aabb1))))
(defspec aabb-union-non-degenerate
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(let [u (geom/aabb-union aabb1 aabb2)]
(and (<= (.. u min x) (.. u max x))
(<= (.. u min y) (.. u max y))
(<= (.. u min z) (.. u max z))))))
(deftest aabb-union-null []
(let [aabb (types/->AABB (Point3d. 0 0 0) (Point3d. 10 10 10))]
(is (= aabb (geom/aabb-union aabb geom/null-aabb)))
(is (= aabb (geom/aabb-union geom/null-aabb aabb)))
(is (= aabb (geom/aabb-union aabb aabb)))
(is (= geom/null-aabb (geom/aabb-union geom/null-aabb geom/null-aabb)))
(is (geom/null-aabb? (geom/aabb-union geom/null-aabb geom/null-aabb)))))
(defspec aabb-incorporates-points
(prop/for-all [pointlist (gen/vector gen-point)]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)]
(every? #(geom/aabb-contains? aabb %) pointlist))))
(defmacro reduce-field
[f field coll]
`(reduce ~f (map #(~field %) ~coll)))
(defspec aabb-incorporates-minimally
(prop/for-all [pointlist (gen/such-that #(< 0 (count %)) (gen/vector gen-point))]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)
max-v (Point3d. (reduce-field max .x pointlist)
(reduce-field max .y pointlist)
(reduce-field max .z pointlist))
min-v (Point3d. (reduce-field min .x pointlist)
(reduce-field min .y pointlist)
(reduce-field min .z pointlist))]
(and
(= max-v (.max aabb))
(= min-v (.min aabb))))))
| true |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.geom-test
(:require [clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test :refer :all]
[editor.types :as types]
[editor.geom :as geom]
[schema.test])
(:import [com.defold.util Geometry]
[javax.vecmath Point3d]))
(use-fixtures :once schema.test/validate-schemas)
(def gen-float (gen/fmap (fn [[dec frac]]
(float (+ (float dec) (/ (rem (float frac) 10000.0) 10000.0))))
(gen/tuple gen/int (gen/resize 10000 gen/int))))
(defspec to-short-uv-works
(prop/for-all [fuv gen-float]
(= (Geometry/toShortUV fuv) (geom/to-short-uv fuv))))
(deftest to-short-uv-problem-cases
(testing "Avoid Clojure's off-by-one cases"
(are [f-uv s-uv] (= s-uv (Geometry/toShortUV f-uv) (geom/to-short-uv f-uv))
0 0
1.3785 24804
6.3785 24799
-9.456 -29875
-21.0141 -903)))
(def gen-point (gen/fmap (fn [[x y z]] (Point3d. x y z))
(gen/tuple gen/int gen/int gen/int)))
(def gen-aabb (gen/fmap (fn [vs]
(let [[[x0 x1] [y0 y1] [z0 z1]] (map sort (partition 2 vs))]
(types/->AABB (Point3d. x0 y0 z0)
(Point3d. x1 y1 z1))))
(gen/tuple gen/int gen/int gen/int
gen/int gen/int gen/int)))
(defspec aabb-union-reflexive
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(= (geom/aabb-union aabb1 aabb2)
(geom/aabb-union aabb2 aabb1))))
(defspec aabb-union-non-degenerate
(prop/for-all [aabb1 gen-aabb
aabb2 gen-aabb]
(let [u (geom/aabb-union aabb1 aabb2)]
(and (<= (.. u min x) (.. u max x))
(<= (.. u min y) (.. u max y))
(<= (.. u min z) (.. u max z))))))
(deftest aabb-union-null []
(let [aabb (types/->AABB (Point3d. 0 0 0) (Point3d. 10 10 10))]
(is (= aabb (geom/aabb-union aabb geom/null-aabb)))
(is (= aabb (geom/aabb-union geom/null-aabb aabb)))
(is (= aabb (geom/aabb-union aabb aabb)))
(is (= geom/null-aabb (geom/aabb-union geom/null-aabb geom/null-aabb)))
(is (geom/null-aabb? (geom/aabb-union geom/null-aabb geom/null-aabb)))))
(defspec aabb-incorporates-points
(prop/for-all [pointlist (gen/vector gen-point)]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)]
(every? #(geom/aabb-contains? aabb %) pointlist))))
(defmacro reduce-field
[f field coll]
`(reduce ~f (map #(~field %) ~coll)))
(defspec aabb-incorporates-minimally
(prop/for-all [pointlist (gen/such-that #(< 0 (count %)) (gen/vector gen-point))]
(let [aabb (reduce geom/aabb-incorporate geom/null-aabb pointlist)
max-v (Point3d. (reduce-field max .x pointlist)
(reduce-field max .y pointlist)
(reduce-field max .z pointlist))
min-v (Point3d. (reduce-field min .x pointlist)
(reduce-field min .y pointlist)
(reduce-field min .z pointlist))]
(and
(= max-v (.max aabb))
(= min-v (.min aabb))))))
|
[
{
"context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 28,
"score": 0.9530190825462341,
"start": 25,
"tag": "NAME",
"value": "Net"
}
] |
src/test/clojure/pigpen/functional/code_test.clj
|
magomimmo/PigPen
| 1 |
;;
;;
;; Copyright 2013 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.functional.code-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig/map (fn [x] (+ (test-fn x) y z))))))
(deftest test-closure
(let [data (pig/return [1 2 3])
command (test-param 37 data)]
(test-diff
(pig/dump command)
'[80 83 88])))
(deftest test-for
(is (= (pig/dump
(apply pig/concat
(for [x [1 2 3]]
(->>
(pig/return [1 2 3])
(pig/map (fn [y] (+ x y)))))))
[4 3 2 5 4 3 6 5 4])))
|
17330
|
;;
;;
;; Copyright 2013 <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.functional.code-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig/map (fn [x] (+ (test-fn x) y z))))))
(deftest test-closure
(let [data (pig/return [1 2 3])
command (test-param 37 data)]
(test-diff
(pig/dump command)
'[80 83 88])))
(deftest test-for
(is (= (pig/dump
(apply pig/concat
(for [x [1 2 3]]
(->>
(pig/return [1 2 3])
(pig/map (fn [y] (+ x y)))))))
[4 3 2 5 4 3 6 5 4])))
| true |
;;
;;
;; Copyright 2013 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.functional.code-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(defn test-fn [x]
(* x x))
(defn test-param [y data]
(let [z 42]
(->> data
(pig/map (fn [x] (+ (test-fn x) y z))))))
(deftest test-closure
(let [data (pig/return [1 2 3])
command (test-param 37 data)]
(test-diff
(pig/dump command)
'[80 83 88])))
(deftest test-for
(is (= (pig/dump
(apply pig/concat
(for [x [1 2 3]]
(->>
(pig/return [1 2 3])
(pig/map (fn [y] (+ x y)))))))
[4 3 2 5 4 3 6 5 4])))
|
[
{
"context": "rohost.com\")\n(def endpoint \"flows\")\n(def api-key \"a1b2c3\")\n\n(fact \"get-textit-data calls parse-http with t",
"end": 274,
"score": 0.9994967579841614,
"start": 268,
"tag": "KEY",
"value": "a1b2c3"
}
] |
test/clj/milia/api/apps_test.clj
|
onaio/milia
| 9 |
(ns milia.api.apps-test
(:require [midje.sweet :refer :all]
[milia.api.apps :refer :all]
[milia.api.http :refer [parse-http]]))
(def server "rapidpro-ona")
(def custom-server "http://myrapidprohost.com")
(def endpoint "flows")
(def api-key "a1b2c3")
(fact "get-textit-data calls parse-http with the correct parameters"
(get-textit-data api-key endpoint server) => :api-response
(provided
(make-textit-url server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
(fact "get-textit-data calls parse-http with the correct host url"
(get-textit-data api-key endpoint custom-server) => :api-response
(provided
(make-textit-url custom-server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
|
46821
|
(ns milia.api.apps-test
(:require [midje.sweet :refer :all]
[milia.api.apps :refer :all]
[milia.api.http :refer [parse-http]]))
(def server "rapidpro-ona")
(def custom-server "http://myrapidprohost.com")
(def endpoint "flows")
(def api-key "<KEY>")
(fact "get-textit-data calls parse-http with the correct parameters"
(get-textit-data api-key endpoint server) => :api-response
(provided
(make-textit-url server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
(fact "get-textit-data calls parse-http with the correct host url"
(get-textit-data api-key endpoint custom-server) => :api-response
(provided
(make-textit-url custom-server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
| true |
(ns milia.api.apps-test
(:require [midje.sweet :refer :all]
[milia.api.apps :refer :all]
[milia.api.http :refer [parse-http]]))
(def server "rapidpro-ona")
(def custom-server "http://myrapidprohost.com")
(def endpoint "flows")
(def api-key "PI:KEY:<KEY>END_PI")
(fact "get-textit-data calls parse-http with the correct parameters"
(get-textit-data api-key endpoint server) => :api-response
(provided
(make-textit-url server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
(fact "get-textit-data calls parse-http with the correct host url"
(get-textit-data api-key endpoint custom-server) => :api-response
(provided
(make-textit-url custom-server (str endpoint ".json")) => :url
(parse-http :get :url :http-options {:auth-token api-key}
:as-map? true
:raw-response? true
:suppress-4xx-exceptions? true) => :api-response))
|
[
{
"context": "using reservoirs as described by\n Efraimidis and Spirakis.\n http://utopia.duth.gr/~pefraimi/researc",
"end": 251,
"score": 0.5752099752426147,
"start": 249,
"tag": "NAME",
"value": "Sp"
}
] |
src/bigml/sampling/reservoir/efraimidis.clj
|
bigmlcom/sampling
| 66 |
;; Copyright 2013 BigML
;; Licensed under the Apache License, Version 2.0
;; http://www.apache.org/licenses/LICENSE-2.0
(ns bigml.sampling.reservoir.efraimidis
"Provides weighted random sampling using reservoirs as described by
Efraimidis and Spirakis.
http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf"
(:require (bigml.sampling [random :as random]
[util :as util])
(clojure.data [finger-tree :as tree]))
(:import (bigml.sampling.reservoir.mergeable MergeableReservoir)))
(def ^:private compare-k
#(compare (:k %1) (:k %2)))
(defn- calc-r [rnd & [floor]]
(let [r (random/next-double! rnd)]
(if floor
(+ floor (* r (- 1 floor)))
r)))
(defn- calc-k [item r weigh]
(if weigh
(let [w (weigh item)]
(if (zero? w)
0
(Math/pow r (/ 1 w))))
r))
(defn- calc-x [reservoir r]
(/ (Math/log r)
(Math/log (:k (first reservoir)))))
(defprotocol ^:private CountedSetReservoir
(getCountedSet [a]))
(deftype Reservoir [reservoir res-size seed gen weigh r wt jmp mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (seq (map :item reservoir)))
(cons [_ i]
(let [reservoir-count (count reservoir)
next-wt (+ wt (if weigh (weigh i) 1))]
(cond (= reservoir-count (dec res-size))
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
(< reservoir-count res-size)
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh nil 0 0 mdata))
(> next-wt jmp)
(let [rnd (random/create :seed seed :generator gen)
current-thresh (:k (first reservoir))
low-r (Math/pow current-thresh (if weigh (weigh i) 1))
lthr (Math/pow current-thresh next-wt)
hthr (Math/pow current-thresh wt)
r2 (/ (- r lthr)
(- hthr lthr))
r3 (+ low-r (* r2 (- 1 low-r)))
k (calc-k i r3 weigh)
reservoir (conj (next reservoir) {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
:else
(Reservoir. reservoir res-size seed gen weigh r next-wt jmp mdata))))
(empty [_] (Reservoir. (tree/counted-sorted-set-by compare-k)
res-size seed gen weigh nil 0 0 mdata))
(equiv
[_ i]
(and (instance? Reservoir i)
(= (into [] reservoir)
(into [] (.reservoir ^Reservoir i)))
(= res-size (.res-size ^Reservoir i))
(= seed (.seed ^Reservoir i))
(= gen (.gen ^Reservoir i))
(= weigh (.weigh ^Reservoir i))))
clojure.lang.ISeq
(first [_] (:item (first reservoir)))
(more [_] (Reservoir. (rest reservoir) res-size seed gen weigh nil 0 0 mdata))
(next [_] (if-let [r (next reservoir)]
(Reservoir. r res-size seed gen weigh nil 0 0 mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [reservoir (into reservoir (.reservoir ^Reservoir i))]
(Reservoir. (->> (nthnext reservoir (max (- (count reservoir) res-size) 0))
(into (empty reservoir)))
res-size seed gen weigh r
(+ wt (.wt ^Reservoir i))
(+ jmp (.jmp ^Reservoir i))
mdata)))
CountedSetReservoir
(getCountedSet [_] reservoir)
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (:item (first @r))]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (map :item reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(Reservoir. reservoir res-size seed gen weigh r wt jmp mdata)))
(defn- init-replacement-reservoir [res-size seed gen weigh]
(let [rnd (random/create :seed seed :generator gen)]
(vec (repeatedly res-size
#(Reservoir. [] 1 (random/next-double! rnd) gen weigh
nil 0 0 nil)))))
(deftype ReplacementReservoir [reservoir res-size seed gen weigh mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (remove nil? (mapcat seq reservoir)))
(cons [_ i]
(ReplacementReservoir. (mapv #(conj % i) reservoir)
res-size seed gen weigh mdata))
(empty [_]
(ReplacementReservoir. (init-replacement-reservoir res-size seed gen weigh)
res-size seed gen weigh mdata))
(equiv [_ i]
(and (instance? ReplacementReservoir i)
(= reservoir (.reservoir ^ReplacementReservoir i))
(= res-size (.res-size ^ReplacementReservoir i))
(= seed (.seed ^ReplacementReservoir i))
(= gen (.gen ^ReplacementReservoir i))
(= weigh (.weigh ^ReplacementReservoir i))))
clojure.lang.ISeq
(first [_] (ffirst reservoir))
(more [_] (ReplacementReservoir. (rest reservoir) res-size seed gen weigh mdata))
(next [_] (when-let [r (next reservoir)]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [r (->> (concat reservoir (.reservoir ^ReplacementReservoir i))
(sort-by #(:k (first (.getCountedSet ^Reservoir %))) >)
(take res-size)
(vec))]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (ffirst @r)]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (mapcat seq reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(ReplacementReservoir. reservoir res-size seed gen weigh mdata)))
(defn create
"Creates a sample reservoir given the reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[size & {:keys [seed replace generator weigh]}]
(let [weigh (util/validated-weigh weigh)]
(if replace
(ReplacementReservoir. (init-replacement-reservoir size seed generator weigh)
size seed generator weigh nil)
(Reservoir. (tree/counted-sorted-set-by compare-k)
size seed generator weigh nil 0 0 nil))))
(defn sample
"Returns a reservoir sample for a collection given a reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[coll size & opts]
(into (apply create size opts) coll))
|
1045
|
;; Copyright 2013 BigML
;; Licensed under the Apache License, Version 2.0
;; http://www.apache.org/licenses/LICENSE-2.0
(ns bigml.sampling.reservoir.efraimidis
"Provides weighted random sampling using reservoirs as described by
Efraimidis and <NAME>irakis.
http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf"
(:require (bigml.sampling [random :as random]
[util :as util])
(clojure.data [finger-tree :as tree]))
(:import (bigml.sampling.reservoir.mergeable MergeableReservoir)))
(def ^:private compare-k
#(compare (:k %1) (:k %2)))
(defn- calc-r [rnd & [floor]]
(let [r (random/next-double! rnd)]
(if floor
(+ floor (* r (- 1 floor)))
r)))
(defn- calc-k [item r weigh]
(if weigh
(let [w (weigh item)]
(if (zero? w)
0
(Math/pow r (/ 1 w))))
r))
(defn- calc-x [reservoir r]
(/ (Math/log r)
(Math/log (:k (first reservoir)))))
(defprotocol ^:private CountedSetReservoir
(getCountedSet [a]))
(deftype Reservoir [reservoir res-size seed gen weigh r wt jmp mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (seq (map :item reservoir)))
(cons [_ i]
(let [reservoir-count (count reservoir)
next-wt (+ wt (if weigh (weigh i) 1))]
(cond (= reservoir-count (dec res-size))
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
(< reservoir-count res-size)
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh nil 0 0 mdata))
(> next-wt jmp)
(let [rnd (random/create :seed seed :generator gen)
current-thresh (:k (first reservoir))
low-r (Math/pow current-thresh (if weigh (weigh i) 1))
lthr (Math/pow current-thresh next-wt)
hthr (Math/pow current-thresh wt)
r2 (/ (- r lthr)
(- hthr lthr))
r3 (+ low-r (* r2 (- 1 low-r)))
k (calc-k i r3 weigh)
reservoir (conj (next reservoir) {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
:else
(Reservoir. reservoir res-size seed gen weigh r next-wt jmp mdata))))
(empty [_] (Reservoir. (tree/counted-sorted-set-by compare-k)
res-size seed gen weigh nil 0 0 mdata))
(equiv
[_ i]
(and (instance? Reservoir i)
(= (into [] reservoir)
(into [] (.reservoir ^Reservoir i)))
(= res-size (.res-size ^Reservoir i))
(= seed (.seed ^Reservoir i))
(= gen (.gen ^Reservoir i))
(= weigh (.weigh ^Reservoir i))))
clojure.lang.ISeq
(first [_] (:item (first reservoir)))
(more [_] (Reservoir. (rest reservoir) res-size seed gen weigh nil 0 0 mdata))
(next [_] (if-let [r (next reservoir)]
(Reservoir. r res-size seed gen weigh nil 0 0 mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [reservoir (into reservoir (.reservoir ^Reservoir i))]
(Reservoir. (->> (nthnext reservoir (max (- (count reservoir) res-size) 0))
(into (empty reservoir)))
res-size seed gen weigh r
(+ wt (.wt ^Reservoir i))
(+ jmp (.jmp ^Reservoir i))
mdata)))
CountedSetReservoir
(getCountedSet [_] reservoir)
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (:item (first @r))]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (map :item reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(Reservoir. reservoir res-size seed gen weigh r wt jmp mdata)))
(defn- init-replacement-reservoir [res-size seed gen weigh]
(let [rnd (random/create :seed seed :generator gen)]
(vec (repeatedly res-size
#(Reservoir. [] 1 (random/next-double! rnd) gen weigh
nil 0 0 nil)))))
(deftype ReplacementReservoir [reservoir res-size seed gen weigh mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (remove nil? (mapcat seq reservoir)))
(cons [_ i]
(ReplacementReservoir. (mapv #(conj % i) reservoir)
res-size seed gen weigh mdata))
(empty [_]
(ReplacementReservoir. (init-replacement-reservoir res-size seed gen weigh)
res-size seed gen weigh mdata))
(equiv [_ i]
(and (instance? ReplacementReservoir i)
(= reservoir (.reservoir ^ReplacementReservoir i))
(= res-size (.res-size ^ReplacementReservoir i))
(= seed (.seed ^ReplacementReservoir i))
(= gen (.gen ^ReplacementReservoir i))
(= weigh (.weigh ^ReplacementReservoir i))))
clojure.lang.ISeq
(first [_] (ffirst reservoir))
(more [_] (ReplacementReservoir. (rest reservoir) res-size seed gen weigh mdata))
(next [_] (when-let [r (next reservoir)]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [r (->> (concat reservoir (.reservoir ^ReplacementReservoir i))
(sort-by #(:k (first (.getCountedSet ^Reservoir %))) >)
(take res-size)
(vec))]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (ffirst @r)]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (mapcat seq reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(ReplacementReservoir. reservoir res-size seed gen weigh mdata)))
(defn create
"Creates a sample reservoir given the reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[size & {:keys [seed replace generator weigh]}]
(let [weigh (util/validated-weigh weigh)]
(if replace
(ReplacementReservoir. (init-replacement-reservoir size seed generator weigh)
size seed generator weigh nil)
(Reservoir. (tree/counted-sorted-set-by compare-k)
size seed generator weigh nil 0 0 nil))))
(defn sample
"Returns a reservoir sample for a collection given a reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[coll size & opts]
(into (apply create size opts) coll))
| true |
;; Copyright 2013 BigML
;; Licensed under the Apache License, Version 2.0
;; http://www.apache.org/licenses/LICENSE-2.0
(ns bigml.sampling.reservoir.efraimidis
"Provides weighted random sampling using reservoirs as described by
Efraimidis and PI:NAME:<NAME>END_PIirakis.
http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf"
(:require (bigml.sampling [random :as random]
[util :as util])
(clojure.data [finger-tree :as tree]))
(:import (bigml.sampling.reservoir.mergeable MergeableReservoir)))
(def ^:private compare-k
#(compare (:k %1) (:k %2)))
(defn- calc-r [rnd & [floor]]
(let [r (random/next-double! rnd)]
(if floor
(+ floor (* r (- 1 floor)))
r)))
(defn- calc-k [item r weigh]
(if weigh
(let [w (weigh item)]
(if (zero? w)
0
(Math/pow r (/ 1 w))))
r))
(defn- calc-x [reservoir r]
(/ (Math/log r)
(Math/log (:k (first reservoir)))))
(defprotocol ^:private CountedSetReservoir
(getCountedSet [a]))
(deftype Reservoir [reservoir res-size seed gen weigh r wt jmp mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (seq (map :item reservoir)))
(cons [_ i]
(let [reservoir-count (count reservoir)
next-wt (+ wt (if weigh (weigh i) 1))]
(cond (= reservoir-count (dec res-size))
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
(< reservoir-count res-size)
(let [rnd (random/create :seed seed :generator gen)
k (calc-k i (random/next-double! rnd) weigh)
reservoir (conj reservoir {:item i :k k})
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh nil 0 0 mdata))
(> next-wt jmp)
(let [rnd (random/create :seed seed :generator gen)
current-thresh (:k (first reservoir))
low-r (Math/pow current-thresh (if weigh (weigh i) 1))
lthr (Math/pow current-thresh next-wt)
hthr (Math/pow current-thresh wt)
r2 (/ (- r lthr)
(- hthr lthr))
r3 (+ low-r (* r2 (- 1 low-r)))
k (calc-k i r3 weigh)
reservoir (conj (next reservoir) {:item i :k k})
r (random/next-double! rnd)
x (calc-x reservoir r)
seed (random/next-long! rnd)]
(Reservoir. reservoir res-size seed gen weigh r 0 x mdata))
:else
(Reservoir. reservoir res-size seed gen weigh r next-wt jmp mdata))))
(empty [_] (Reservoir. (tree/counted-sorted-set-by compare-k)
res-size seed gen weigh nil 0 0 mdata))
(equiv
[_ i]
(and (instance? Reservoir i)
(= (into [] reservoir)
(into [] (.reservoir ^Reservoir i)))
(= res-size (.res-size ^Reservoir i))
(= seed (.seed ^Reservoir i))
(= gen (.gen ^Reservoir i))
(= weigh (.weigh ^Reservoir i))))
clojure.lang.ISeq
(first [_] (:item (first reservoir)))
(more [_] (Reservoir. (rest reservoir) res-size seed gen weigh nil 0 0 mdata))
(next [_] (if-let [r (next reservoir)]
(Reservoir. r res-size seed gen weigh nil 0 0 mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [reservoir (into reservoir (.reservoir ^Reservoir i))]
(Reservoir. (->> (nthnext reservoir (max (- (count reservoir) res-size) 0))
(into (empty reservoir)))
res-size seed gen weigh r
(+ wt (.wt ^Reservoir i))
(+ jmp (.jmp ^Reservoir i))
mdata)))
CountedSetReservoir
(getCountedSet [_] reservoir)
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (:item (first @r))]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (map :item reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(Reservoir. reservoir res-size seed gen weigh r wt jmp mdata)))
(defn- init-replacement-reservoir [res-size seed gen weigh]
(let [rnd (random/create :seed seed :generator gen)]
(vec (repeatedly res-size
#(Reservoir. [] 1 (random/next-double! rnd) gen weigh
nil 0 0 nil)))))
(deftype ReplacementReservoir [reservoir res-size seed gen weigh mdata]
clojure.lang.IPersistentCollection
(count [_] (count reservoir))
(seq [_] (remove nil? (mapcat seq reservoir)))
(cons [_ i]
(ReplacementReservoir. (mapv #(conj % i) reservoir)
res-size seed gen weigh mdata))
(empty [_]
(ReplacementReservoir. (init-replacement-reservoir res-size seed gen weigh)
res-size seed gen weigh mdata))
(equiv [_ i]
(and (instance? ReplacementReservoir i)
(= reservoir (.reservoir ^ReplacementReservoir i))
(= res-size (.res-size ^ReplacementReservoir i))
(= seed (.seed ^ReplacementReservoir i))
(= gen (.gen ^ReplacementReservoir i))
(= weigh (.weigh ^ReplacementReservoir i))))
clojure.lang.ISeq
(first [_] (ffirst reservoir))
(more [_] (ReplacementReservoir. (rest reservoir) res-size seed gen weigh mdata))
(next [_] (when-let [r (next reservoir)]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
MergeableReservoir
(mergeReservoir [_ i]
(let [r (->> (concat reservoir (.reservoir ^ReplacementReservoir i))
(sort-by #(:k (first (.getCountedSet ^Reservoir %))) >)
(take res-size)
(vec))]
(ReplacementReservoir. r res-size seed gen weigh mdata)))
java.util.List
(iterator [_]
(let [r (atom reservoir)]
(reify java.util.Iterator
(next [_] (let [i (ffirst @r)]
(swap! r next)
i))
(hasNext [_] (boolean (seq @r))))))
(toArray [_] (to-array (mapcat seq reservoir)))
clojure.lang.IObj
(meta [_] mdata)
(withMeta [_ mdata]
(ReplacementReservoir. reservoir res-size seed gen weigh mdata)))
(defn create
"Creates a sample reservoir given the reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[size & {:keys [seed replace generator weigh]}]
(let [weigh (util/validated-weigh weigh)]
(if replace
(ReplacementReservoir. (init-replacement-reservoir size seed generator weigh)
size seed generator weigh nil)
(Reservoir. (tree/counted-sorted-set-by compare-k)
size seed generator weigh nil 0 0 nil))))
(defn sample
"Returns a reservoir sample for a collection given a reservoir size.
Options:
:replace - True to sample with replacement, defaults to false.
:seed - A seed for the random number generator, defaults to nil.
:generator - The random number generator to be used, options
are :lcg (linear congruential) or :twister (Marsenne
twister), default is :lcg.
:weigh - A function that returns a non-negative weight for an
item. When nil, no sampling weights are applied.
Defaults to nil."
[coll size & opts]
(into (apply create size opts) coll))
|
[
{
"context": " :password (str user \"Pass0\")}])\n\n (if group-concept-ids\n (do\n (d",
"end": 2500,
"score": 0.9846205711364746,
"start": 2495,
"tag": "PASSWORD",
"value": "Pass0"
}
] |
mock-echo-app/src/cmr/mock_echo/client/echo_util.clj
|
daniel-zamora/Common-Metadata-Repository
| 0 |
(ns cmr.mock-echo.client.echo-util
"Contains helper functions for working with the echo mock"
(:require
[clojure.set :as set]
[clojure.string :as string]
[cmr.common-app.api.launchpad-token-validation :as lt-validation]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.util :as util]
[cmr.mock-echo.client.mock-echo-client :as echo-client]
[cmr.mock-echo.client.mock-urs-client :as urs-client]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as config]
[cmr.transmit.echo.conversion :as c]
[cmr.transmit.echo.tokens :as tokens]))
(defn reset
"Resets the mock echo."
[context]
(echo-client/reset context))
(defn create-providers
"Creates the providers in the mock echo."
[context provider-guid-id-map]
(echo-client/create-providers context provider-guid-id-map))
(defn get-or-create-group
"Gets a group or creates it if it does not exist"
([context group-name]
(get-or-create-group context group-name (config/echo-system-token)))
([context group-name token]
(let [existing-group (-> (ac/search-for-groups context
{:name group-name}
{:raw? true :token token})
(get-in [:body :items])
(first))
;; Return the existing group if it exists, otherwise create a new one
group (or existing-group (:body (ac/create-group context
{:name group-name
:description group-name}
{:raw? true :token token})))]
(:concept_id group))))
(defn add-user-to-group
"Adds the user to an access-control group"
[context group-concept-id user-name token]
(ac/add-members context group-concept-id [user-name] {:raw? true :token token}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Token related
(defn login-guest
"Logs in as a guest and returns the token"
[context]
(tokens/login-guest context))
(defn login
"Logs in as the specified user and returns the token. No password needed because mock echo
doesn't enforce passwords. Group guids can be optionally specified. The logged in user will
be in the given groups."
([context user]
(login context user nil))
([context user group-concept-ids]
(urs-client/create-users context [{:username user
:password (str user "Pass0")}])
(if group-concept-ids
(do
(doseq [group-concept-id group-concept-ids]
(add-user-to-group context group-concept-id user (config/echo-system-token)))
(echo-client/login-with-group-access context user "password" group-concept-ids))
(tokens/login context user "password"))))
(defn logout
"Logs out the specified token."
[context token]
(tokens/logout context token))
(def LAUNCHPAD_TOKEN_PADDING
"Padding to make a regular token into launchpad token
(i.e. make it longer than max length of URS token)."
(string/join (repeat lt-validation/URS_TOKEN_MAX_LENGTH "Z")))
(defn login-with-launchpad-token
"Logs in as the specified user and returns the launchpad token.
This is a wrapper around the login function and just pad the returned URS token to
the length of a launchpad token."
([context user]
(login-with-launchpad-token context user nil))
([context user group-concept-ids]
(let [token (login context user group-concept-ids)]
(str token LAUNCHPAD_TOKEN_PADDING))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ACL related
;; Ingest management AKA admin granters
(def ingest-management-acl
"An ACL for managing access to ingest management functions."
"INGEST_MANAGEMENT_ACL")
;; subscription management acl
(def subscription-management
"An ACL for managing access to subscription functions."
"SUBSCRIPTION_MANAGEMENT")
(def tag-acl
"An ACL for managing access to tag modification functions."
"TAG_GROUP")
(defn coll-id
"Creates an ACL collection identifier"
([entry-titles]
(coll-id entry-titles nil))
([entry-titles access-value-filter]
(coll-id entry-titles access-value-filter nil))
([entry-titles access-value-filter temporal]
(util/remove-nil-keys
{:entry_titles entry-titles
:access_value access-value-filter
:temporal temporal})))
(defn gran-id
"Creates an ACL granule identifier"
([access-value-filter]
(gran-id access-value-filter nil))
([access-value-filter temporal]
(util/remove-nil-keys
{:access_value access-value-filter
:temporal temporal})))
(defn catalog-item-id
"Creates a catalog item identity"
([provider-guid]
(catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(util/remove-nil-keys
{:provider_id provider-guid
:collection_identifier coll-identifier
:granule_identifier gran-identifier})))
(defn coll-catalog-item-id
"Creates a collection applicable catalog item identity"
([provider-guid]
(coll-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(coll-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:collection_applicable true)))
(defn gran-catalog-item-id
"Creates a granule applicable catalog item identity"
([provider-guid]
(gran-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(gran-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:granule_applicable true)))
(defn- cmr-catalog-identity->echo
"Converts a cmr catalog-item-identity into the format used by mock-echo"
[identity]
(let [{:keys [name provider_id collection_applicable granule_applicable]} identity
coll-access-value (-> (get-in identity [:collection_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
gran-access-value (-> (get-in identity [:granule_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
coll-temporal (-> (get-in identity [:collection_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
gran-temporal (-> (get-in identity [:granule_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
entry-titles (get-in identity [:collection_identifier :entry_titles])]
(-> {:name name
:provider-guid provider_id
:collection-applicable collection_applicable
:granule-applicable granule_applicable
:collection-identifier (util/remove-nil-keys
{:entry-titles entry-titles
:access-value coll-access-value
:temporal (if coll-temporal (assoc coll-temporal :temporal-field :acquisition))})
:granule-identifier (util/remove-nil-keys
{:access-value gran-access-value
:temporal (if gran-temporal (assoc gran-temporal :temporal-field :acquisition))})}
util/remove-nil-keys)))
(defn grant
"Creates an ACL in mock echo with the id, access control entries, identities"
[context group-permissions object-identity-type object-identity]
(let [cmr-acl (if (= object-identity-type :catalog_item_identity)
(util/map-keys->snake_case {:group_permissions group-permissions
object-identity-type (util/remove-nil-keys (merge {:name (str (java.util.UUID/randomUUID))}
object-identity))})
{:group_permissions group-permissions
object-identity-type object-identity})
echo-identity (if (= object-identity-type :catalog_item_identity) (cmr-catalog-identity->echo object-identity) object-identity)
;;attempt to create ACL. If it already exists, then get the existing ACL and update.
cmr-response (ac/create-acl context cmr-acl {:raw? true :token (config/echo-system-token)})
cmr-response (if (= 409 (:status cmr-response))
(let [existing-concept-id (->> (get-in cmr-response [:body :errors])
first
(re-find #"\[([\w\d-]+)\]")
second)
existing-concept (:body
(ac/get-acl context
existing-concept-id
{:raw? true
:token (config/echo-system-token)}))
updated-concept (assoc existing-concept
:group_permissions
(into (:group_permissions existing-concept)
group-permissions))]
(assoc
(ac/update-acl context
existing-concept-id
updated-concept
{:raw? true
:token (config/echo-system-token)})
:acl updated-concept))
cmr-response)
group-permissions (or (get-in cmr-response [:acl :group_permissions]) group-permissions)
echo-acl (-> {:aces (map #(clojure.set/rename-keys % {:user_type :user-type :group_id :group-guid}) group-permissions)
object-identity-type (clojure.set/rename-keys echo-identity {:provider_id :provider-guid :collection_identifier :collection-identifier})
:id (get-in cmr-response [:body :concept_id])}
(set/rename-keys {:system_identity :system-object-identity :provider_identity :provider-object-identity :catalog_item_identity :catalog-item-identity}))
;; Dont save to ECHO if CMR create fails
echo-acl-response (if (< (:status cmr-response) 300)
(echo-client/create-acl context echo-acl)
(info "Failed to ingest ACL to access-control: " cmr-response))]
(get-in cmr-response [:body :concept_id])))
(defn ungrant
"Removes the acl"
[context acl]
(ac/delete-acl context acl {:raw? true :token (config/echo-system-token)})
(echo-client/delete-acl context acl))
(defn get-acls-by-type-and-target
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context type target]
(get-acls-by-type-and-target context type target {}))
([context type target options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type type :target target :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-provider-group-acls
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context]
(get-provider-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "PROVIDER" "GROUP" options)))
(defn get-system-group-acls
"Get the GROUP ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-system-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "SYSTEM" "GROUP" options)))
(defn get-catalog-item-acls
"Get the CATALOG_ITEM ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-catalog-item-acls context {}))
([context options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type "catalog_item" :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-admin-group
"Gets the system administrator group"
[context]
(->> (ac/search-for-groups context {:legacy_guid (config/administrators-group-legacy-guid) :token (config/echo-system-token)})
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %)))
(first)))
(def guest-read-ace
"A CMR style access control entry granting guests read access."
{:permissions [:read]
:user_type :guest})
(def registered-user-read-ace
"A CMR style access control entry granting registered users read access."
{:permissions [:read]
:user_type :registered})
(def guest-read-write-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :create]
:user_type :guest})
(def guest-read-update-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :update]
:user_type :guest})
(def registered-user-read-write-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :create]
:user_type :registered})
(def registered-user-read-update-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :update]
:user_type :registered})
(defn group-ace
"A CMR style access control entry granting users in a specific group read access."
[group-guid permissions]
{:permissions permissions
:group_id group-guid})
(defn grant-all-ingest
"Creates an ACL in mock echo granting guests and registered users access to ingest for the given
provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :guest}
{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-registered-ingest
"Creates an ACL in mock echo granting registered users access to ingest for the given provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-groups-ingest
"Creates an ACL in mock echo granting the specified groups access to ingest for the given provider."
[context provider-guid group-guids]
(grant context
(vec (for [guid group-guids]
(group-ace guid [:update :read])))
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-all-tag
"Creates an ACL in mock echo granting registered users ability to tag anything"
[context]
(grant context
[{:permissions [:create :update :delete]
:user_type :registered}
{:permissions [:create :update :delete]
:user_type :guest}]
:system_identity
{:target tag-acl}))
(defn grant-all-variable
"Creates an ACL in mock echo granting registered users ability to do all
variable related operations"
[context]
(grant context
[{:permissions [:read :update]
:user_type :registered}
{:permissions [:read :update]
:user_type :guest}]
:system_identity
{:target ingest-management-acl}))
(def grant-all-service
"Creates an ACL in mock echo granting registered users ability to do all
service related operations"
grant-all-variable)
(def grant-all-tool
"Creates an ACL in mock echo granting registered users ability to do all
tool related operations"
grant-all-variable)
(def grant-all-subscription-ima
"Creates an ingest-management-acl in mock echo granting guest and registered users ability to do all
subscription related operations"
grant-all-variable)
(defn grant-all-subscription-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting guest and registered users ability to do all
subscription related operations"
[context provider-guid guest-permissions registered-permissions]
(grant context
[{:permissions guest-permissions
:user_type :guest}
{:permissions registered-permissions
:user_type :registered}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-all-subscription-group-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting group ability to do all
subscription related operations"
[context provider-guid group-id group-permissions]
(grant context
[{:permissions group-permissions
:group_id group-id}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-create-read-groups
"Creates an ACL in mock echo granting registered users and guests ability to create and read
groups. If a provider id is provided this it permits it for the given provider. If not provided
then it is at the system level."
([context]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:system_identity
{:target "GROUP"}))
([context provider-guid]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:provider_identity
{:target "GROUP"
:provider_id provider-guid})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Grant functions for Catalog Item ACLS
(defn grant-all
"Creates an ACL in mock echo granting guests and registered users access to catalog items
identified by the catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-guest
"Creates an ACL in mock echo granting guests access to catalog items identified by the
catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-registered-users
"Creates an ACL in mock echo granting all registered users access to catalog items identified by
the catalog-item-identity"
[context catalog-item-identity]
(grant context [registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-group
"Creates an ACL in mock echo granting users in the group access to catalog items identified by
the catalog-item-identity"
[context group-guid catalog-item-identity]
(grant context [(group-ace group-guid [:read])] :catalog_item_identity catalog-item-identity))
(defn grant-group-admin
"Creates an ACL in mock echo granting users in the group the given
permissions for system ingest management. If no permissions are provided the
group is given read and update permission.
Note that not all services have all permissions. In some cases, a service
allows for concepts to be created, but doesn't actually have a :create
permission enabled. In such circumstances, the group getting admin
permissions will need to be granted :update."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:read :update]))]
:system_identity
{:target ingest-management-acl}))
(defn grant-all-admin
"Creates an ACL in mock echo granting all users read and update for system ingest management."
[context]
(grant context [guest-read-update-ace registered-user-read-update-ace]
:system_identity
{:target ingest-management-acl}))
(defn grant-group-provider-admin
"Creates an ACL in mock echo granting users in the group the given permissions to ingest for the
given provider. If no permissions are provided the group is given update and delete permissions."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:update :read]))]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-group-tag
"Creates an ACL in mock echo granting users in the group the given permissions to modify tags. If
no permissions are provided the group is given create, update, and delete permissions."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq permission-types)
[:create :update :delete]))]
:system_identity
{:target tag-acl}))
(defn grant-system-group-permissions-to-group
"Grants system-level access control group management permissions to given group."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:system_identity
{:target "GROUP"}))
(defn grant-system-group-permissions-to-admin-group
"Grants system-level access-control group management permissions for the admin group"
[context & permission-types]
(apply grant-system-group-permissions-to-group
context (:concept_id (get-admin-group context)) permission-types))
(defn grant-group-instance-permissions-to-group
[context group-guid target-group-guid & permission-types]
(grant context [(group-ace group-guid (seq permission-types))]
:single_instance_object_identity
{:target "GROUP_MANAGEMENT"
:target_guid target-group-guid}))
(defn grant-system-group-permissions-to-all
"Grants all users all permissions for system level access control group management."
[context]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:system_identity
{:target "GROUP"}))
(defn grant-provider-group-permissions-to-group
"Grants provider-level access-control group management permissions for specified group-guid and provider-guid."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-provider-group-permissions-to-admin-group
"Grants provider-level access-control group management permissions for the admin group"
[context provider-guid & permission-types]
(apply grant-provider-group-permissions-to-group
context (:concept_id (get-admin-group context)) provider-guid permission-types))
(defn grant-provider-group-permissions-to-all
"Grants provider-level access-control group management to all users for all providers."
[context provider-guid]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-permitted?
"Check if a given grant id is in the list of provided ACLs."
[grant-id acls]
(contains?
(into
#{}
(map :guid acls))
grant-id))
(defn group-permitted?
"Check if a given group id is in the list of provided ACLs."
[group-id acls]
(contains?
(reduce
#(into %1 (map :group-guid %2))
#{}
(map :aces acls))
group-id))
(defn permitted?
"Check if a the ACLs for the given token include the given grant and group IDs."
[token grant-id group-id acls]
(and (grant-permitted? grant-id acls)
(group-permitted? group-id acls)))
(defn not-permitted?
[& args]
(not (apply permitted? args)))
|
731
|
(ns cmr.mock-echo.client.echo-util
"Contains helper functions for working with the echo mock"
(:require
[clojure.set :as set]
[clojure.string :as string]
[cmr.common-app.api.launchpad-token-validation :as lt-validation]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.util :as util]
[cmr.mock-echo.client.mock-echo-client :as echo-client]
[cmr.mock-echo.client.mock-urs-client :as urs-client]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as config]
[cmr.transmit.echo.conversion :as c]
[cmr.transmit.echo.tokens :as tokens]))
(defn reset
"Resets the mock echo."
[context]
(echo-client/reset context))
(defn create-providers
"Creates the providers in the mock echo."
[context provider-guid-id-map]
(echo-client/create-providers context provider-guid-id-map))
(defn get-or-create-group
"Gets a group or creates it if it does not exist"
([context group-name]
(get-or-create-group context group-name (config/echo-system-token)))
([context group-name token]
(let [existing-group (-> (ac/search-for-groups context
{:name group-name}
{:raw? true :token token})
(get-in [:body :items])
(first))
;; Return the existing group if it exists, otherwise create a new one
group (or existing-group (:body (ac/create-group context
{:name group-name
:description group-name}
{:raw? true :token token})))]
(:concept_id group))))
(defn add-user-to-group
"Adds the user to an access-control group"
[context group-concept-id user-name token]
(ac/add-members context group-concept-id [user-name] {:raw? true :token token}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Token related
(defn login-guest
"Logs in as a guest and returns the token"
[context]
(tokens/login-guest context))
(defn login
"Logs in as the specified user and returns the token. No password needed because mock echo
doesn't enforce passwords. Group guids can be optionally specified. The logged in user will
be in the given groups."
([context user]
(login context user nil))
([context user group-concept-ids]
(urs-client/create-users context [{:username user
:password (str user "<PASSWORD>")}])
(if group-concept-ids
(do
(doseq [group-concept-id group-concept-ids]
(add-user-to-group context group-concept-id user (config/echo-system-token)))
(echo-client/login-with-group-access context user "password" group-concept-ids))
(tokens/login context user "password"))))
(defn logout
"Logs out the specified token."
[context token]
(tokens/logout context token))
(def LAUNCHPAD_TOKEN_PADDING
"Padding to make a regular token into launchpad token
(i.e. make it longer than max length of URS token)."
(string/join (repeat lt-validation/URS_TOKEN_MAX_LENGTH "Z")))
(defn login-with-launchpad-token
"Logs in as the specified user and returns the launchpad token.
This is a wrapper around the login function and just pad the returned URS token to
the length of a launchpad token."
([context user]
(login-with-launchpad-token context user nil))
([context user group-concept-ids]
(let [token (login context user group-concept-ids)]
(str token LAUNCHPAD_TOKEN_PADDING))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ACL related
;; Ingest management AKA admin granters
(def ingest-management-acl
"An ACL for managing access to ingest management functions."
"INGEST_MANAGEMENT_ACL")
;; subscription management acl
(def subscription-management
"An ACL for managing access to subscription functions."
"SUBSCRIPTION_MANAGEMENT")
(def tag-acl
"An ACL for managing access to tag modification functions."
"TAG_GROUP")
(defn coll-id
"Creates an ACL collection identifier"
([entry-titles]
(coll-id entry-titles nil))
([entry-titles access-value-filter]
(coll-id entry-titles access-value-filter nil))
([entry-titles access-value-filter temporal]
(util/remove-nil-keys
{:entry_titles entry-titles
:access_value access-value-filter
:temporal temporal})))
(defn gran-id
"Creates an ACL granule identifier"
([access-value-filter]
(gran-id access-value-filter nil))
([access-value-filter temporal]
(util/remove-nil-keys
{:access_value access-value-filter
:temporal temporal})))
(defn catalog-item-id
"Creates a catalog item identity"
([provider-guid]
(catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(util/remove-nil-keys
{:provider_id provider-guid
:collection_identifier coll-identifier
:granule_identifier gran-identifier})))
(defn coll-catalog-item-id
"Creates a collection applicable catalog item identity"
([provider-guid]
(coll-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(coll-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:collection_applicable true)))
(defn gran-catalog-item-id
"Creates a granule applicable catalog item identity"
([provider-guid]
(gran-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(gran-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:granule_applicable true)))
(defn- cmr-catalog-identity->echo
"Converts a cmr catalog-item-identity into the format used by mock-echo"
[identity]
(let [{:keys [name provider_id collection_applicable granule_applicable]} identity
coll-access-value (-> (get-in identity [:collection_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
gran-access-value (-> (get-in identity [:granule_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
coll-temporal (-> (get-in identity [:collection_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
gran-temporal (-> (get-in identity [:granule_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
entry-titles (get-in identity [:collection_identifier :entry_titles])]
(-> {:name name
:provider-guid provider_id
:collection-applicable collection_applicable
:granule-applicable granule_applicable
:collection-identifier (util/remove-nil-keys
{:entry-titles entry-titles
:access-value coll-access-value
:temporal (if coll-temporal (assoc coll-temporal :temporal-field :acquisition))})
:granule-identifier (util/remove-nil-keys
{:access-value gran-access-value
:temporal (if gran-temporal (assoc gran-temporal :temporal-field :acquisition))})}
util/remove-nil-keys)))
(defn grant
"Creates an ACL in mock echo with the id, access control entries, identities"
[context group-permissions object-identity-type object-identity]
(let [cmr-acl (if (= object-identity-type :catalog_item_identity)
(util/map-keys->snake_case {:group_permissions group-permissions
object-identity-type (util/remove-nil-keys (merge {:name (str (java.util.UUID/randomUUID))}
object-identity))})
{:group_permissions group-permissions
object-identity-type object-identity})
echo-identity (if (= object-identity-type :catalog_item_identity) (cmr-catalog-identity->echo object-identity) object-identity)
;;attempt to create ACL. If it already exists, then get the existing ACL and update.
cmr-response (ac/create-acl context cmr-acl {:raw? true :token (config/echo-system-token)})
cmr-response (if (= 409 (:status cmr-response))
(let [existing-concept-id (->> (get-in cmr-response [:body :errors])
first
(re-find #"\[([\w\d-]+)\]")
second)
existing-concept (:body
(ac/get-acl context
existing-concept-id
{:raw? true
:token (config/echo-system-token)}))
updated-concept (assoc existing-concept
:group_permissions
(into (:group_permissions existing-concept)
group-permissions))]
(assoc
(ac/update-acl context
existing-concept-id
updated-concept
{:raw? true
:token (config/echo-system-token)})
:acl updated-concept))
cmr-response)
group-permissions (or (get-in cmr-response [:acl :group_permissions]) group-permissions)
echo-acl (-> {:aces (map #(clojure.set/rename-keys % {:user_type :user-type :group_id :group-guid}) group-permissions)
object-identity-type (clojure.set/rename-keys echo-identity {:provider_id :provider-guid :collection_identifier :collection-identifier})
:id (get-in cmr-response [:body :concept_id])}
(set/rename-keys {:system_identity :system-object-identity :provider_identity :provider-object-identity :catalog_item_identity :catalog-item-identity}))
;; Dont save to ECHO if CMR create fails
echo-acl-response (if (< (:status cmr-response) 300)
(echo-client/create-acl context echo-acl)
(info "Failed to ingest ACL to access-control: " cmr-response))]
(get-in cmr-response [:body :concept_id])))
(defn ungrant
"Removes the acl"
[context acl]
(ac/delete-acl context acl {:raw? true :token (config/echo-system-token)})
(echo-client/delete-acl context acl))
(defn get-acls-by-type-and-target
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context type target]
(get-acls-by-type-and-target context type target {}))
([context type target options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type type :target target :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-provider-group-acls
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context]
(get-provider-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "PROVIDER" "GROUP" options)))
(defn get-system-group-acls
"Get the GROUP ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-system-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "SYSTEM" "GROUP" options)))
(defn get-catalog-item-acls
"Get the CATALOG_ITEM ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-catalog-item-acls context {}))
([context options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type "catalog_item" :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-admin-group
"Gets the system administrator group"
[context]
(->> (ac/search-for-groups context {:legacy_guid (config/administrators-group-legacy-guid) :token (config/echo-system-token)})
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %)))
(first)))
(def guest-read-ace
"A CMR style access control entry granting guests read access."
{:permissions [:read]
:user_type :guest})
(def registered-user-read-ace
"A CMR style access control entry granting registered users read access."
{:permissions [:read]
:user_type :registered})
(def guest-read-write-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :create]
:user_type :guest})
(def guest-read-update-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :update]
:user_type :guest})
(def registered-user-read-write-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :create]
:user_type :registered})
(def registered-user-read-update-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :update]
:user_type :registered})
(defn group-ace
"A CMR style access control entry granting users in a specific group read access."
[group-guid permissions]
{:permissions permissions
:group_id group-guid})
(defn grant-all-ingest
"Creates an ACL in mock echo granting guests and registered users access to ingest for the given
provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :guest}
{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-registered-ingest
"Creates an ACL in mock echo granting registered users access to ingest for the given provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-groups-ingest
"Creates an ACL in mock echo granting the specified groups access to ingest for the given provider."
[context provider-guid group-guids]
(grant context
(vec (for [guid group-guids]
(group-ace guid [:update :read])))
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-all-tag
"Creates an ACL in mock echo granting registered users ability to tag anything"
[context]
(grant context
[{:permissions [:create :update :delete]
:user_type :registered}
{:permissions [:create :update :delete]
:user_type :guest}]
:system_identity
{:target tag-acl}))
(defn grant-all-variable
"Creates an ACL in mock echo granting registered users ability to do all
variable related operations"
[context]
(grant context
[{:permissions [:read :update]
:user_type :registered}
{:permissions [:read :update]
:user_type :guest}]
:system_identity
{:target ingest-management-acl}))
(def grant-all-service
"Creates an ACL in mock echo granting registered users ability to do all
service related operations"
grant-all-variable)
(def grant-all-tool
"Creates an ACL in mock echo granting registered users ability to do all
tool related operations"
grant-all-variable)
(def grant-all-subscription-ima
"Creates an ingest-management-acl in mock echo granting guest and registered users ability to do all
subscription related operations"
grant-all-variable)
(defn grant-all-subscription-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting guest and registered users ability to do all
subscription related operations"
[context provider-guid guest-permissions registered-permissions]
(grant context
[{:permissions guest-permissions
:user_type :guest}
{:permissions registered-permissions
:user_type :registered}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-all-subscription-group-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting group ability to do all
subscription related operations"
[context provider-guid group-id group-permissions]
(grant context
[{:permissions group-permissions
:group_id group-id}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-create-read-groups
"Creates an ACL in mock echo granting registered users and guests ability to create and read
groups. If a provider id is provided this it permits it for the given provider. If not provided
then it is at the system level."
([context]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:system_identity
{:target "GROUP"}))
([context provider-guid]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:provider_identity
{:target "GROUP"
:provider_id provider-guid})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Grant functions for Catalog Item ACLS
(defn grant-all
"Creates an ACL in mock echo granting guests and registered users access to catalog items
identified by the catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-guest
"Creates an ACL in mock echo granting guests access to catalog items identified by the
catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-registered-users
"Creates an ACL in mock echo granting all registered users access to catalog items identified by
the catalog-item-identity"
[context catalog-item-identity]
(grant context [registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-group
"Creates an ACL in mock echo granting users in the group access to catalog items identified by
the catalog-item-identity"
[context group-guid catalog-item-identity]
(grant context [(group-ace group-guid [:read])] :catalog_item_identity catalog-item-identity))
(defn grant-group-admin
"Creates an ACL in mock echo granting users in the group the given
permissions for system ingest management. If no permissions are provided the
group is given read and update permission.
Note that not all services have all permissions. In some cases, a service
allows for concepts to be created, but doesn't actually have a :create
permission enabled. In such circumstances, the group getting admin
permissions will need to be granted :update."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:read :update]))]
:system_identity
{:target ingest-management-acl}))
(defn grant-all-admin
"Creates an ACL in mock echo granting all users read and update for system ingest management."
[context]
(grant context [guest-read-update-ace registered-user-read-update-ace]
:system_identity
{:target ingest-management-acl}))
(defn grant-group-provider-admin
"Creates an ACL in mock echo granting users in the group the given permissions to ingest for the
given provider. If no permissions are provided the group is given update and delete permissions."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:update :read]))]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-group-tag
"Creates an ACL in mock echo granting users in the group the given permissions to modify tags. If
no permissions are provided the group is given create, update, and delete permissions."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq permission-types)
[:create :update :delete]))]
:system_identity
{:target tag-acl}))
(defn grant-system-group-permissions-to-group
"Grants system-level access control group management permissions to given group."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:system_identity
{:target "GROUP"}))
(defn grant-system-group-permissions-to-admin-group
"Grants system-level access-control group management permissions for the admin group"
[context & permission-types]
(apply grant-system-group-permissions-to-group
context (:concept_id (get-admin-group context)) permission-types))
(defn grant-group-instance-permissions-to-group
[context group-guid target-group-guid & permission-types]
(grant context [(group-ace group-guid (seq permission-types))]
:single_instance_object_identity
{:target "GROUP_MANAGEMENT"
:target_guid target-group-guid}))
(defn grant-system-group-permissions-to-all
"Grants all users all permissions for system level access control group management."
[context]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:system_identity
{:target "GROUP"}))
(defn grant-provider-group-permissions-to-group
"Grants provider-level access-control group management permissions for specified group-guid and provider-guid."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-provider-group-permissions-to-admin-group
"Grants provider-level access-control group management permissions for the admin group"
[context provider-guid & permission-types]
(apply grant-provider-group-permissions-to-group
context (:concept_id (get-admin-group context)) provider-guid permission-types))
(defn grant-provider-group-permissions-to-all
"Grants provider-level access-control group management to all users for all providers."
[context provider-guid]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-permitted?
"Check if a given grant id is in the list of provided ACLs."
[grant-id acls]
(contains?
(into
#{}
(map :guid acls))
grant-id))
(defn group-permitted?
"Check if a given group id is in the list of provided ACLs."
[group-id acls]
(contains?
(reduce
#(into %1 (map :group-guid %2))
#{}
(map :aces acls))
group-id))
(defn permitted?
"Check if a the ACLs for the given token include the given grant and group IDs."
[token grant-id group-id acls]
(and (grant-permitted? grant-id acls)
(group-permitted? group-id acls)))
(defn not-permitted?
[& args]
(not (apply permitted? args)))
| true |
(ns cmr.mock-echo.client.echo-util
"Contains helper functions for working with the echo mock"
(:require
[clojure.set :as set]
[clojure.string :as string]
[cmr.common-app.api.launchpad-token-validation :as lt-validation]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.util :as util]
[cmr.mock-echo.client.mock-echo-client :as echo-client]
[cmr.mock-echo.client.mock-urs-client :as urs-client]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as config]
[cmr.transmit.echo.conversion :as c]
[cmr.transmit.echo.tokens :as tokens]))
(defn reset
"Resets the mock echo."
[context]
(echo-client/reset context))
(defn create-providers
"Creates the providers in the mock echo."
[context provider-guid-id-map]
(echo-client/create-providers context provider-guid-id-map))
(defn get-or-create-group
"Gets a group or creates it if it does not exist"
([context group-name]
(get-or-create-group context group-name (config/echo-system-token)))
([context group-name token]
(let [existing-group (-> (ac/search-for-groups context
{:name group-name}
{:raw? true :token token})
(get-in [:body :items])
(first))
;; Return the existing group if it exists, otherwise create a new one
group (or existing-group (:body (ac/create-group context
{:name group-name
:description group-name}
{:raw? true :token token})))]
(:concept_id group))))
(defn add-user-to-group
"Adds the user to an access-control group"
[context group-concept-id user-name token]
(ac/add-members context group-concept-id [user-name] {:raw? true :token token}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Token related
(defn login-guest
"Logs in as a guest and returns the token"
[context]
(tokens/login-guest context))
(defn login
"Logs in as the specified user and returns the token. No password needed because mock echo
doesn't enforce passwords. Group guids can be optionally specified. The logged in user will
be in the given groups."
([context user]
(login context user nil))
([context user group-concept-ids]
(urs-client/create-users context [{:username user
:password (str user "PI:PASSWORD:<PASSWORD>END_PI")}])
(if group-concept-ids
(do
(doseq [group-concept-id group-concept-ids]
(add-user-to-group context group-concept-id user (config/echo-system-token)))
(echo-client/login-with-group-access context user "password" group-concept-ids))
(tokens/login context user "password"))))
(defn logout
"Logs out the specified token."
[context token]
(tokens/logout context token))
(def LAUNCHPAD_TOKEN_PADDING
"Padding to make a regular token into launchpad token
(i.e. make it longer than max length of URS token)."
(string/join (repeat lt-validation/URS_TOKEN_MAX_LENGTH "Z")))
(defn login-with-launchpad-token
"Logs in as the specified user and returns the launchpad token.
This is a wrapper around the login function and just pad the returned URS token to
the length of a launchpad token."
([context user]
(login-with-launchpad-token context user nil))
([context user group-concept-ids]
(let [token (login context user group-concept-ids)]
(str token LAUNCHPAD_TOKEN_PADDING))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ACL related
;; Ingest management AKA admin granters
(def ingest-management-acl
"An ACL for managing access to ingest management functions."
"INGEST_MANAGEMENT_ACL")
;; subscription management acl
(def subscription-management
"An ACL for managing access to subscription functions."
"SUBSCRIPTION_MANAGEMENT")
(def tag-acl
"An ACL for managing access to tag modification functions."
"TAG_GROUP")
(defn coll-id
"Creates an ACL collection identifier"
([entry-titles]
(coll-id entry-titles nil))
([entry-titles access-value-filter]
(coll-id entry-titles access-value-filter nil))
([entry-titles access-value-filter temporal]
(util/remove-nil-keys
{:entry_titles entry-titles
:access_value access-value-filter
:temporal temporal})))
(defn gran-id
"Creates an ACL granule identifier"
([access-value-filter]
(gran-id access-value-filter nil))
([access-value-filter temporal]
(util/remove-nil-keys
{:access_value access-value-filter
:temporal temporal})))
(defn catalog-item-id
"Creates a catalog item identity"
([provider-guid]
(catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(util/remove-nil-keys
{:provider_id provider-guid
:collection_identifier coll-identifier
:granule_identifier gran-identifier})))
(defn coll-catalog-item-id
"Creates a collection applicable catalog item identity"
([provider-guid]
(coll-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(coll-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:collection_applicable true)))
(defn gran-catalog-item-id
"Creates a granule applicable catalog item identity"
([provider-guid]
(gran-catalog-item-id provider-guid nil))
([provider-guid coll-identifier]
(gran-catalog-item-id provider-guid coll-identifier nil))
([provider-guid coll-identifier gran-identifier]
(assoc (catalog-item-id provider-guid coll-identifier gran-identifier)
:granule_applicable true)))
(defn- cmr-catalog-identity->echo
"Converts a cmr catalog-item-identity into the format used by mock-echo"
[identity]
(let [{:keys [name provider_id collection_applicable granule_applicable]} identity
coll-access-value (-> (get-in identity [:collection_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
gran-access-value (-> (get-in identity [:granule_identifier :access_value])
(clojure.set/rename-keys {:include_undefined_value :include-undefined}))
coll-temporal (-> (get-in identity [:collection_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
gran-temporal (-> (get-in identity [:granule_identifier :temporal])
(clojure.set/rename-keys {:stop-date :end-date}))
entry-titles (get-in identity [:collection_identifier :entry_titles])]
(-> {:name name
:provider-guid provider_id
:collection-applicable collection_applicable
:granule-applicable granule_applicable
:collection-identifier (util/remove-nil-keys
{:entry-titles entry-titles
:access-value coll-access-value
:temporal (if coll-temporal (assoc coll-temporal :temporal-field :acquisition))})
:granule-identifier (util/remove-nil-keys
{:access-value gran-access-value
:temporal (if gran-temporal (assoc gran-temporal :temporal-field :acquisition))})}
util/remove-nil-keys)))
(defn grant
"Creates an ACL in mock echo with the id, access control entries, identities"
[context group-permissions object-identity-type object-identity]
(let [cmr-acl (if (= object-identity-type :catalog_item_identity)
(util/map-keys->snake_case {:group_permissions group-permissions
object-identity-type (util/remove-nil-keys (merge {:name (str (java.util.UUID/randomUUID))}
object-identity))})
{:group_permissions group-permissions
object-identity-type object-identity})
echo-identity (if (= object-identity-type :catalog_item_identity) (cmr-catalog-identity->echo object-identity) object-identity)
;;attempt to create ACL. If it already exists, then get the existing ACL and update.
cmr-response (ac/create-acl context cmr-acl {:raw? true :token (config/echo-system-token)})
cmr-response (if (= 409 (:status cmr-response))
(let [existing-concept-id (->> (get-in cmr-response [:body :errors])
first
(re-find #"\[([\w\d-]+)\]")
second)
existing-concept (:body
(ac/get-acl context
existing-concept-id
{:raw? true
:token (config/echo-system-token)}))
updated-concept (assoc existing-concept
:group_permissions
(into (:group_permissions existing-concept)
group-permissions))]
(assoc
(ac/update-acl context
existing-concept-id
updated-concept
{:raw? true
:token (config/echo-system-token)})
:acl updated-concept))
cmr-response)
group-permissions (or (get-in cmr-response [:acl :group_permissions]) group-permissions)
echo-acl (-> {:aces (map #(clojure.set/rename-keys % {:user_type :user-type :group_id :group-guid}) group-permissions)
object-identity-type (clojure.set/rename-keys echo-identity {:provider_id :provider-guid :collection_identifier :collection-identifier})
:id (get-in cmr-response [:body :concept_id])}
(set/rename-keys {:system_identity :system-object-identity :provider_identity :provider-object-identity :catalog_item_identity :catalog-item-identity}))
;; Dont save to ECHO if CMR create fails
echo-acl-response (if (< (:status cmr-response) 300)
(echo-client/create-acl context echo-acl)
(info "Failed to ingest ACL to access-control: " cmr-response))]
(get-in cmr-response [:body :concept_id])))
(defn ungrant
"Removes the acl"
[context acl]
(ac/delete-acl context acl {:raw? true :token (config/echo-system-token)})
(echo-client/delete-acl context acl))
(defn get-acls-by-type-and-target
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context type target]
(get-acls-by-type-and-target context type target {}))
([context type target options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type type :target target :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-provider-group-acls
"Get the GROUP ACLs set up for providers in fixtures. Return in format used for test assertions"
([context]
(get-provider-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "PROVIDER" "GROUP" options)))
(defn get-system-group-acls
"Get the GROUP ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-system-group-acls context {}))
([context options]
(get-acls-by-type-and-target context "SYSTEM" "GROUP" options)))
(defn get-catalog-item-acls
"Get the CATALOG_ITEM ACLs set up for system in fixtures. Return in format used for test assertions"
([context]
(get-catalog-item-acls context {}))
([context options]
(->> (ac/search-for-acls (assoc context :token (config/echo-system-token)) (merge {:identity_type "catalog_item" :include_full_acl true} options))
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %))))))
(defn get-admin-group
"Gets the system administrator group"
[context]
(->> (ac/search-for-groups context {:legacy_guid (config/administrators-group-legacy-guid) :token (config/echo-system-token)})
:items
(map #(assoc (:acl %) :revision_id (:revision_id %) :concept_id (:concept_id %)))
(first)))
(def guest-read-ace
"A CMR style access control entry granting guests read access."
{:permissions [:read]
:user_type :guest})
(def registered-user-read-ace
"A CMR style access control entry granting registered users read access."
{:permissions [:read]
:user_type :registered})
(def guest-read-write-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :create]
:user_type :guest})
(def guest-read-update-ace
"A CMR style access control entry granting guests create and read access."
{:permissions [:read :update]
:user_type :guest})
(def registered-user-read-write-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :create]
:user_type :registered})
(def registered-user-read-update-ace
"A CMR style access control entry granting registered users create and read access."
{:permissions [:read :update]
:user_type :registered})
(defn group-ace
"A CMR style access control entry granting users in a specific group read access."
[group-guid permissions]
{:permissions permissions
:group_id group-guid})
(defn grant-all-ingest
"Creates an ACL in mock echo granting guests and registered users access to ingest for the given
provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :guest}
{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-registered-ingest
"Creates an ACL in mock echo granting registered users access to ingest for the given provider."
[context provider-guid]
(grant context
[{:permissions [:update :read]
:user_type :registered}]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-groups-ingest
"Creates an ACL in mock echo granting the specified groups access to ingest for the given provider."
[context provider-guid group-guids]
(grant context
(vec (for [guid group-guids]
(group-ace guid [:update :read])))
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-all-tag
"Creates an ACL in mock echo granting registered users ability to tag anything"
[context]
(grant context
[{:permissions [:create :update :delete]
:user_type :registered}
{:permissions [:create :update :delete]
:user_type :guest}]
:system_identity
{:target tag-acl}))
(defn grant-all-variable
"Creates an ACL in mock echo granting registered users ability to do all
variable related operations"
[context]
(grant context
[{:permissions [:read :update]
:user_type :registered}
{:permissions [:read :update]
:user_type :guest}]
:system_identity
{:target ingest-management-acl}))
(def grant-all-service
"Creates an ACL in mock echo granting registered users ability to do all
service related operations"
grant-all-variable)
(def grant-all-tool
"Creates an ACL in mock echo granting registered users ability to do all
tool related operations"
grant-all-variable)
(def grant-all-subscription-ima
"Creates an ingest-management-acl in mock echo granting guest and registered users ability to do all
subscription related operations"
grant-all-variable)
(defn grant-all-subscription-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting guest and registered users ability to do all
subscription related operations"
[context provider-guid guest-permissions registered-permissions]
(grant context
[{:permissions guest-permissions
:user_type :guest}
{:permissions registered-permissions
:user_type :registered}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-all-subscription-group-sm
"Creates a SUBSCRIPTION_MANAGEMENT acl in mock echo granting group ability to do all
subscription related operations"
[context provider-guid group-id group-permissions]
(grant context
[{:permissions group-permissions
:group_id group-id}]
:provider_identity
{:target subscription-management
:provider_id provider-guid}))
(defn grant-create-read-groups
"Creates an ACL in mock echo granting registered users and guests ability to create and read
groups. If a provider id is provided this it permits it for the given provider. If not provided
then it is at the system level."
([context]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:system_identity
{:target "GROUP"}))
([context provider-guid]
(grant context
[{:permissions [:create :read] :user_type :registered}
{:permissions [:create :read] :user_type :guest}]
:provider_identity
{:target "GROUP"
:provider_id provider-guid})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Grant functions for Catalog Item ACLS
(defn grant-all
"Creates an ACL in mock echo granting guests and registered users access to catalog items
identified by the catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-guest
"Creates an ACL in mock echo granting guests access to catalog items identified by the
catalog-item-identity"
[context catalog-item-identity]
(grant context [guest-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-registered-users
"Creates an ACL in mock echo granting all registered users access to catalog items identified by
the catalog-item-identity"
[context catalog-item-identity]
(grant context [registered-user-read-ace] :catalog_item_identity catalog-item-identity))
(defn grant-group
"Creates an ACL in mock echo granting users in the group access to catalog items identified by
the catalog-item-identity"
[context group-guid catalog-item-identity]
(grant context [(group-ace group-guid [:read])] :catalog_item_identity catalog-item-identity))
(defn grant-group-admin
"Creates an ACL in mock echo granting users in the group the given
permissions for system ingest management. If no permissions are provided the
group is given read and update permission.
Note that not all services have all permissions. In some cases, a service
allows for concepts to be created, but doesn't actually have a :create
permission enabled. In such circumstances, the group getting admin
permissions will need to be granted :update."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:read :update]))]
:system_identity
{:target ingest-management-acl}))
(defn grant-all-admin
"Creates an ACL in mock echo granting all users read and update for system ingest management."
[context]
(grant context [guest-read-update-ace registered-user-read-update-ace]
:system_identity
{:target ingest-management-acl}))
(defn grant-group-provider-admin
"Creates an ACL in mock echo granting users in the group the given permissions to ingest for the
given provider. If no permissions are provided the group is given update and delete permissions."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:delete} permission-types))
[:update :read]))]
:provider_identity
{:target ingest-management-acl
:provider_id provider-guid}))
(defn grant-group-tag
"Creates an ACL in mock echo granting users in the group the given permissions to modify tags. If
no permissions are provided the group is given create, update, and delete permissions."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq permission-types)
[:create :update :delete]))]
:system_identity
{:target tag-acl}))
(defn grant-system-group-permissions-to-group
"Grants system-level access control group management permissions to given group."
[context group-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:system_identity
{:target "GROUP"}))
(defn grant-system-group-permissions-to-admin-group
"Grants system-level access-control group management permissions for the admin group"
[context & permission-types]
(apply grant-system-group-permissions-to-group
context (:concept_id (get-admin-group context)) permission-types))
(defn grant-group-instance-permissions-to-group
[context group-guid target-group-guid & permission-types]
(grant context [(group-ace group-guid (seq permission-types))]
:single_instance_object_identity
{:target "GROUP_MANAGEMENT"
:target_guid target-group-guid}))
(defn grant-system-group-permissions-to-all
"Grants all users all permissions for system level access control group management."
[context]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:system_identity
{:target "GROUP"}))
(defn grant-provider-group-permissions-to-group
"Grants provider-level access-control group management permissions for specified group-guid and provider-guid."
[context group-guid provider-guid & permission-types]
(grant context [(group-ace group-guid (or (seq (remove #{:update} permission-types))
[:create :read]))]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-provider-group-permissions-to-admin-group
"Grants provider-level access-control group management permissions for the admin group"
[context provider-guid & permission-types]
(apply grant-provider-group-permissions-to-group
context (:concept_id (get-admin-group context)) provider-guid permission-types))
(defn grant-provider-group-permissions-to-all
"Grants provider-level access-control group management to all users for all providers."
[context provider-guid]
(grant context [guest-read-write-ace registered-user-read-write-ace]
:provider_identity
{:target "GROUP"
:provider_id provider-guid}))
(defn grant-permitted?
"Check if a given grant id is in the list of provided ACLs."
[grant-id acls]
(contains?
(into
#{}
(map :guid acls))
grant-id))
(defn group-permitted?
"Check if a given group id is in the list of provided ACLs."
[group-id acls]
(contains?
(reduce
#(into %1 (map :group-guid %2))
#{}
(map :aces acls))
group-id))
(defn permitted?
"Check if a the ACLs for the given token include the given grant and group IDs."
[token grant-id group-id acls]
(and (grant-permitted? grant-id acls)
(group-permitted? group-id acls)))
(defn not-permitted?
[& args]
(not (apply permitted? args)))
|
[
{
"context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The",
"end": 45,
"score": 0.9998509287834167,
"start": 27,
"tag": "NAME",
"value": "Michael S. Klishin"
},
{
"context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The use and dist",
"end": 58,
"score": 0.9998106956481934,
"start": 47,
"tag": "NAME",
"value": "Alex Petrov"
}
] |
src/clojure/pantomime/internal.clj
|
dthadi3/pantomime
| 119 |
;; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team
;;
;; 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 pantomime.internal)
;; clojure.java.io has these as private, so we had to copy them. MK.
(def ^{:doc "Type object for a Java primitive byte array."}
byte-array-type (class (make-array Byte/TYPE 0)))
(def ^{:doc "Type object for a Java primitive char array."}
char-array-type (class (make-array Character/TYPE 0)))
|
53411
|
;; Copyright (c) 2011-2014 <NAME>, <NAME>, and the ClojureWerkz Team
;;
;; 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 pantomime.internal)
;; clojure.java.io has these as private, so we had to copy them. MK.
(def ^{:doc "Type object for a Java primitive byte array."}
byte-array-type (class (make-array Byte/TYPE 0)))
(def ^{:doc "Type object for a Java primitive char array."}
char-array-type (class (make-array Character/TYPE 0)))
| true |
;; Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and the ClojureWerkz Team
;;
;; 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 pantomime.internal)
;; clojure.java.io has these as private, so we had to copy them. MK.
(def ^{:doc "Type object for a Java primitive byte array."}
byte-array-type (class (make-array Byte/TYPE 0)))
(def ^{:doc "Type object for a Java primitive char array."}
char-array-type (class (make-array Character/TYPE 0)))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; Copyright (c) 2008, J. Bester\n;; All rights reserved.\n;;\n;; Redistribution and ",
"end": 441,
"score": 0.9998762607574463,
"start": 432,
"tag": "NAME",
"value": "J. Bester"
}
] |
src/cljext/option.clj
|
jbester/cljext
| 9 |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : option.clj
;; Function : Optional value library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 38c5cc66480ac6dc3b36f70eb51641df89a5ad05 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, J. Bester
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY
;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.option
(:refer-clojure)
)
(defstruct option
:has-value :value)
(defn none
"Create an option with no value"
([]
(struct-map option :has-value false)))
(defn value
"Create an option with a value"
([val]
(struct-map option :has-value true :value val)))
(defn value-of
"Retrieve the value of an option"
([opt]
(:value opt)))
(defn none?
"Predicate to test if an option has no value"
([opt]
(not (:has-value opt))))
(defn has-value?
"Predicate to test if an option has value"
([opt]
(:has-value opt)))
|
9169
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : option.clj
;; Function : Optional value library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 38c5cc66480ac6dc3b36f70eb51641df89a5ad05 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, <NAME>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY
;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.option
(:refer-clojure)
)
(defstruct option
:has-value :value)
(defn none
"Create an option with no value"
([]
(struct-map option :has-value false)))
(defn value
"Create an option with a value"
([val]
(struct-map option :has-value true :value val)))
(defn value-of
"Retrieve the value of an option"
([opt]
(:value opt)))
(defn none?
"Predicate to test if an option has no value"
([opt]
(not (:has-value opt))))
(defn has-value?
"Predicate to test if an option has value"
([opt]
(:has-value opt)))
| true |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : option.clj
;; Function : Optional value library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 38c5cc66480ac6dc3b36f70eb51641df89a5ad05 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, PI:NAME:<NAME>END_PI
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY
;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.option
(:refer-clojure)
)
(defstruct option
:has-value :value)
(defn none
"Create an option with no value"
([]
(struct-map option :has-value false)))
(defn value
"Create an option with a value"
([val]
(struct-map option :has-value true :value val)))
(defn value-of
"Retrieve the value of an option"
([opt]
(:value opt)))
(defn none?
"Predicate to test if an option has no value"
([opt]
(not (:has-value opt))))
(defn has-value?
"Predicate to test if an option has value"
([opt]
(:has-value opt)))
|
[
{
"context": " :username (:username credentials)\n :password (:",
"end": 2372,
"score": 0.5371686816215515,
"start": 2361,
"tag": "USERNAME",
"value": "credentials"
},
{
"context": ")\n :password (:password credentials)}\n :content-type",
"end": 2430,
"score": 0.7527105212211609,
"start": 2422,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :password (:password credentials)}\n :content-type \"applicatio",
"end": 2442,
"score": 0.9973646402359009,
"start": 2431,
"tag": "PASSWORD",
"value": "credentials"
},
{
"context": "d limit time :after :comment :user))\n\n\n(defn user-trophies\n [credentials username]\n (-> (http-get credenti",
"end": 10942,
"score": 0.9752531051635742,
"start": 10934,
"tag": "USERNAME",
"value": "trophies"
}
] |
src/creddit/client.clj
|
OliverAndrews/creddit
| 0 |
(ns creddit.client
(:require [clj-http.client :as client]
[clojure.string :as string]
[cheshire.core :refer :all]
[slingshot.slingshot :refer :all]))
(defn- parse-response
[response]
(if-let [coll (or (get-in response [:data :children])
(get-in response [:data :trophies]))]
(map :data coll)
(:data response)))
(defn- valid-limit? [limit]
(if (and (integer? limit)
(<= 1 limit)
(>= 100 limit))
limit
(throw
(ex-info "Invalid limit - Must be an integer between 1 & 100."
{:causes :invalid-limit}))))
(defn- valid-time? [time]
(if (and (keyword? time)
(contains? #{:hour :day :week :month :year :all} time))
time
(throw
(ex-info "Invalid time - Must be one of the following: :hour, :day, :week, :month, :year, :all."
{:causes :invalid-time}))))
(defn- valid-top-level-kind? [topLevelKind]
(if (and (keyword? topLevelKind) (contains? #{:user :subreddit} topLevelKind))
topLevelKind
(throw
(ex-info "Invalid top level kind - Must be one of the following: :user, :subreddit."))))
(defn- valid-direction? [direction]
(if (and (keyword? direction) (contains? #{:before :after} direction))
direction
(throw
(ex-info "Invalid direction - Must be one of the following: :before, :after."))))
(defn- valid-entity? [entity]
(if (and (keyword? entity) (contains? #{:comment :submission} entity))
entity
(throw
(ex-info "Invalid entity - Must be one of the following: :comment, :submission."))))
(defn- item-code [entityKind]
(case entityKind
:comment "t1_"
:submission "t3_"))
(defn- before-or-after [direction entityId entityKind]
(case direction
:before (str "&before=" (item-code entityKind) entityId)
:after (str "&after=" (item-code entityKind) entityId)))
(defn get-access-token-with-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "password"
:device_id (str (java.util.UUID/randomUUID))
:username (:username credentials)
:password (:password credentials)}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token-without-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "client_credentials"
:device_id (str (java.util.UUID/randomUUID))}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token
[credentials]
(if (:username credentials) (get-access-token-with-user credentials) (get-access-token-without-user credentials)))
(defn- http-get [credentials url]
(-> (client/get url
{:basic-auth [(:access-token credentials)]
:headers {"User-Agent" "creddit"}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
(defn- parse-top-level [topLevelKind]
(case topLevelKind
:user (name topLevelKind)
:subreddit "r"))
(defn- parse-entity-kind [entityKind]
(case entityKind
:comment "/comments"
:submission "/submitted"))
(defn- get-entities-window
[credentials slug entityId limit time direction entityKind topLevelKind]
(if (and (valid-limit? limit) (valid-time? time) (valid-entity? entityKind) (valid-top-level-kind? topLevelKind) (valid-direction? direction))
(-> (http-get credentials (str "https://www.reddit.com/" (parse-top-level topLevelKind) "/" slug (parse-entity-kind entityKind) "/.json?limit=" limit "&t=" (name time) (before-or-after direction entityId entityKind)))
(parse-response))))
(defn frontpage
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn controversial
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn new
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn rising
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn top
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-controversial
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-new
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-rising
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-top
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-comments
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/comments/.json?limit=" limit))
(parse-response))))
(defn subreddit-comments-before
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :before :comment :subreddit))
(defn subreddit-comments-after
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :after :comment :subreddit))
(defn subreddit-search
[credentials subreddit query limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/search/.json?q=" query "&limit=" limit))
(parse-response))))
(defn subreddit-about
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/.json"))
(parse-response)))
(defn subreddit-moderators
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/moderators/.json"))
:data
:children))
(defn subreddits
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/.json?limit=" limit))
(parse-response))))
(defn subreddits-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/new/.json?limit=" limit))
(parse-response))))
(defn subreddits-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/popular/.json?limit=" limit))
(parse-response))))
(defn subreddits-gold
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/gold/.json?limit=" limit))
(parse-response))))
(defn subreddits-default
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/default/.json?limit=" limit))
(parse-response))))
(defn subreddits-search
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/search/.json?q=" subreddit "&limit=" limit))
(parse-response))))
(defn user
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/about/.json"))
(parse-response)))
(defn user-posts
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/submitted/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-comments
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/comments/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-posts-after
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :after :submission :user))
(defn user-posts-before
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :before :submission :user))
(defn user-comments-before
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :before :comment :user))
(defn user-comments-after
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :after :comment :user))
(defn user-trophies
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/trophies/.json"))
(parse-response)))
(defn users
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/.json?limit=" limit))
(parse-response))))
(defn users-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/new/.json?limit=" limit))
(parse-response))))
(defn users-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/popular/.json?limit=" limit))
(parse-response))))
(defn listing
[credentials names]
(-> (http-get credentials (str "https://www.reddit.com/by_id/" (string/join "," names) "/.json"))
(parse-response)))
; other functions use credentials directly, unsure why mine needs to get them from the client with get-in...
(defn submit
[credentials subreddit kind title content]
(-> (client/post "https://oauth.reddit.com/api/submit"
{:headers {:User-Agent "creddit"
:Authorization (str "bearer " (get-in credentials [:credentials :access-token]))}
:form-params {:sr subreddit
:kind kind
:title title
(cond
(= kind "self") :text
(= kind "link") :url) content}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
|
94179
|
(ns creddit.client
(:require [clj-http.client :as client]
[clojure.string :as string]
[cheshire.core :refer :all]
[slingshot.slingshot :refer :all]))
(defn- parse-response
[response]
(if-let [coll (or (get-in response [:data :children])
(get-in response [:data :trophies]))]
(map :data coll)
(:data response)))
(defn- valid-limit? [limit]
(if (and (integer? limit)
(<= 1 limit)
(>= 100 limit))
limit
(throw
(ex-info "Invalid limit - Must be an integer between 1 & 100."
{:causes :invalid-limit}))))
(defn- valid-time? [time]
(if (and (keyword? time)
(contains? #{:hour :day :week :month :year :all} time))
time
(throw
(ex-info "Invalid time - Must be one of the following: :hour, :day, :week, :month, :year, :all."
{:causes :invalid-time}))))
(defn- valid-top-level-kind? [topLevelKind]
(if (and (keyword? topLevelKind) (contains? #{:user :subreddit} topLevelKind))
topLevelKind
(throw
(ex-info "Invalid top level kind - Must be one of the following: :user, :subreddit."))))
(defn- valid-direction? [direction]
(if (and (keyword? direction) (contains? #{:before :after} direction))
direction
(throw
(ex-info "Invalid direction - Must be one of the following: :before, :after."))))
(defn- valid-entity? [entity]
(if (and (keyword? entity) (contains? #{:comment :submission} entity))
entity
(throw
(ex-info "Invalid entity - Must be one of the following: :comment, :submission."))))
(defn- item-code [entityKind]
(case entityKind
:comment "t1_"
:submission "t3_"))
(defn- before-or-after [direction entityId entityKind]
(case direction
:before (str "&before=" (item-code entityKind) entityId)
:after (str "&after=" (item-code entityKind) entityId)))
(defn get-access-token-with-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "password"
:device_id (str (java.util.UUID/randomUUID))
:username (:username credentials)
:password (:<PASSWORD> <PASSWORD>)}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token-without-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "client_credentials"
:device_id (str (java.util.UUID/randomUUID))}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token
[credentials]
(if (:username credentials) (get-access-token-with-user credentials) (get-access-token-without-user credentials)))
(defn- http-get [credentials url]
(-> (client/get url
{:basic-auth [(:access-token credentials)]
:headers {"User-Agent" "creddit"}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
(defn- parse-top-level [topLevelKind]
(case topLevelKind
:user (name topLevelKind)
:subreddit "r"))
(defn- parse-entity-kind [entityKind]
(case entityKind
:comment "/comments"
:submission "/submitted"))
(defn- get-entities-window
[credentials slug entityId limit time direction entityKind topLevelKind]
(if (and (valid-limit? limit) (valid-time? time) (valid-entity? entityKind) (valid-top-level-kind? topLevelKind) (valid-direction? direction))
(-> (http-get credentials (str "https://www.reddit.com/" (parse-top-level topLevelKind) "/" slug (parse-entity-kind entityKind) "/.json?limit=" limit "&t=" (name time) (before-or-after direction entityId entityKind)))
(parse-response))))
(defn frontpage
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn controversial
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn new
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn rising
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn top
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-controversial
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-new
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-rising
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-top
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-comments
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/comments/.json?limit=" limit))
(parse-response))))
(defn subreddit-comments-before
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :before :comment :subreddit))
(defn subreddit-comments-after
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :after :comment :subreddit))
(defn subreddit-search
[credentials subreddit query limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/search/.json?q=" query "&limit=" limit))
(parse-response))))
(defn subreddit-about
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/.json"))
(parse-response)))
(defn subreddit-moderators
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/moderators/.json"))
:data
:children))
(defn subreddits
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/.json?limit=" limit))
(parse-response))))
(defn subreddits-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/new/.json?limit=" limit))
(parse-response))))
(defn subreddits-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/popular/.json?limit=" limit))
(parse-response))))
(defn subreddits-gold
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/gold/.json?limit=" limit))
(parse-response))))
(defn subreddits-default
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/default/.json?limit=" limit))
(parse-response))))
(defn subreddits-search
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/search/.json?q=" subreddit "&limit=" limit))
(parse-response))))
(defn user
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/about/.json"))
(parse-response)))
(defn user-posts
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/submitted/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-comments
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/comments/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-posts-after
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :after :submission :user))
(defn user-posts-before
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :before :submission :user))
(defn user-comments-before
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :before :comment :user))
(defn user-comments-after
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :after :comment :user))
(defn user-trophies
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/trophies/.json"))
(parse-response)))
(defn users
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/.json?limit=" limit))
(parse-response))))
(defn users-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/new/.json?limit=" limit))
(parse-response))))
(defn users-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/popular/.json?limit=" limit))
(parse-response))))
(defn listing
[credentials names]
(-> (http-get credentials (str "https://www.reddit.com/by_id/" (string/join "," names) "/.json"))
(parse-response)))
; other functions use credentials directly, unsure why mine needs to get them from the client with get-in...
(defn submit
[credentials subreddit kind title content]
(-> (client/post "https://oauth.reddit.com/api/submit"
{:headers {:User-Agent "creddit"
:Authorization (str "bearer " (get-in credentials [:credentials :access-token]))}
:form-params {:sr subreddit
:kind kind
:title title
(cond
(= kind "self") :text
(= kind "link") :url) content}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
| true |
(ns creddit.client
(:require [clj-http.client :as client]
[clojure.string :as string]
[cheshire.core :refer :all]
[slingshot.slingshot :refer :all]))
(defn- parse-response
[response]
(if-let [coll (or (get-in response [:data :children])
(get-in response [:data :trophies]))]
(map :data coll)
(:data response)))
(defn- valid-limit? [limit]
(if (and (integer? limit)
(<= 1 limit)
(>= 100 limit))
limit
(throw
(ex-info "Invalid limit - Must be an integer between 1 & 100."
{:causes :invalid-limit}))))
(defn- valid-time? [time]
(if (and (keyword? time)
(contains? #{:hour :day :week :month :year :all} time))
time
(throw
(ex-info "Invalid time - Must be one of the following: :hour, :day, :week, :month, :year, :all."
{:causes :invalid-time}))))
(defn- valid-top-level-kind? [topLevelKind]
(if (and (keyword? topLevelKind) (contains? #{:user :subreddit} topLevelKind))
topLevelKind
(throw
(ex-info "Invalid top level kind - Must be one of the following: :user, :subreddit."))))
(defn- valid-direction? [direction]
(if (and (keyword? direction) (contains? #{:before :after} direction))
direction
(throw
(ex-info "Invalid direction - Must be one of the following: :before, :after."))))
(defn- valid-entity? [entity]
(if (and (keyword? entity) (contains? #{:comment :submission} entity))
entity
(throw
(ex-info "Invalid entity - Must be one of the following: :comment, :submission."))))
(defn- item-code [entityKind]
(case entityKind
:comment "t1_"
:submission "t3_"))
(defn- before-or-after [direction entityId entityKind]
(case direction
:before (str "&before=" (item-code entityKind) entityId)
:after (str "&after=" (item-code entityKind) entityId)))
(defn get-access-token-with-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "password"
:device_id (str (java.util.UUID/randomUUID))
:username (:username credentials)
:password (:PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI)}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token-without-user
[credentials]
(try+
(-> (client/post "https://www.reddit.com/api/v1/access_token"
{:basic-auth [(:user-client credentials) (:user-secret credentials)]
:headers {"User-Agent" "creddit"}
:form-params {:grant_type "client_credentials"
:device_id (str (java.util.UUID/randomUUID))}
:content-type "application/x-www-form-urlencoded"
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body))
(catch [:status 401] {}
(throw
(ex-info "Unauthorised, please check your credentials are correct."
{:causes :unauthorised})))))
(defn get-access-token
[credentials]
(if (:username credentials) (get-access-token-with-user credentials) (get-access-token-without-user credentials)))
(defn- http-get [credentials url]
(-> (client/get url
{:basic-auth [(:access-token credentials)]
:headers {"User-Agent" "creddit"}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
(defn- parse-top-level [topLevelKind]
(case topLevelKind
:user (name topLevelKind)
:subreddit "r"))
(defn- parse-entity-kind [entityKind]
(case entityKind
:comment "/comments"
:submission "/submitted"))
(defn- get-entities-window
[credentials slug entityId limit time direction entityKind topLevelKind]
(if (and (valid-limit? limit) (valid-time? time) (valid-entity? entityKind) (valid-top-level-kind? topLevelKind) (valid-direction? direction))
(-> (http-get credentials (str "https://www.reddit.com/" (parse-top-level topLevelKind) "/" slug (parse-entity-kind entityKind) "/.json?limit=" limit "&t=" (name time) (before-or-after direction entityId entityKind)))
(parse-response))))
(defn frontpage
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn controversial
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn new
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn rising
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn top
[credentials limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-controversial
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/controversial/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-new
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/new/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-rising
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/rising/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-top
[credentials subreddit limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/top/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn subreddit-comments
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/comments/.json?limit=" limit))
(parse-response))))
(defn subreddit-comments-before
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :before :comment :subreddit))
(defn subreddit-comments-after
[credentials subreddit commentId limit time]
(get-entities-window credentials subreddit commentId limit time :after :comment :subreddit))
(defn subreddit-search
[credentials subreddit query limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/search/.json?q=" query "&limit=" limit))
(parse-response))))
(defn subreddit-about
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/.json"))
(parse-response)))
(defn subreddit-moderators
[credentials subreddit]
(-> (http-get credentials (str "https://www.reddit.com/r/" subreddit "/about/moderators/.json"))
:data
:children))
(defn subreddits
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/.json?limit=" limit))
(parse-response))))
(defn subreddits-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/new/.json?limit=" limit))
(parse-response))))
(defn subreddits-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/popular/.json?limit=" limit))
(parse-response))))
(defn subreddits-gold
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/gold/.json?limit=" limit))
(parse-response))))
(defn subreddits-default
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/default/.json?limit=" limit))
(parse-response))))
(defn subreddits-search
[credentials subreddit limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/subreddits/search/.json?q=" subreddit "&limit=" limit))
(parse-response))))
(defn user
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/about/.json"))
(parse-response)))
(defn user-posts
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/submitted/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-comments
[credentials username limit time]
(if (and (valid-limit? limit) (valid-time? time))
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/comments/.json?limit=" limit "&t=" (name time)))
(parse-response))))
(defn user-posts-after
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :after :submission :user))
(defn user-posts-before
[credentials username postId limit time]
(get-entities-window credentials username postId limit time :before :submission :user))
(defn user-comments-before
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :before :comment :user))
(defn user-comments-after
[credentials username commentId limit time]
(get-entities-window credentials username commentId limit time :after :comment :user))
(defn user-trophies
[credentials username]
(-> (http-get credentials (str "https://www.reddit.com/user/" username "/trophies/.json"))
(parse-response)))
(defn users
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/.json?limit=" limit))
(parse-response))))
(defn users-new
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/new/.json?limit=" limit))
(parse-response))))
(defn users-popular
[credentials limit]
(if (valid-limit? limit)
(-> (http-get credentials (str "https://www.reddit.com/users/popular/.json?limit=" limit))
(parse-response))))
(defn listing
[credentials names]
(-> (http-get credentials (str "https://www.reddit.com/by_id/" (string/join "," names) "/.json"))
(parse-response)))
; other functions use credentials directly, unsure why mine needs to get them from the client with get-in...
(defn submit
[credentials subreddit kind title content]
(-> (client/post "https://oauth.reddit.com/api/submit"
{:headers {:User-Agent "creddit"
:Authorization (str "bearer " (get-in credentials [:credentials :access-token]))}
:form-params {:sr subreddit
:kind kind
:title title
(cond
(= kind "self") :text
(= kind "link") :url) content}
:socket-timeout 10000
:conn-timeout 10000
:as :json})
(get :body)))
|
[
{
"context": " (is (nil? (usercore/load-user-by-email db-spec \"[email protected]\")))\n (is (nil? (usercore/load-user-by-username",
"end": 4089,
"score": 0.9999263286590576,
"start": 4070,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "is (nil? (usercore/load-user-by-username db-spec \"smithk\")))\n (let [user {\"user/name\" \"Karen Smith\"\n ",
"end": 4155,
"score": 0.9652503728866577,
"start": 4149,
"tag": "USERNAME",
"value": "smithk"
},
{
"context": " db-spec \"smithk\")))\n (let [user {\"user/name\" \"Karen Smith\"\n \"user/email\" \"[email protected]",
"end": 4200,
"score": 0.9989325404167175,
"start": 4189,
"tag": "NAME",
"value": "Karen Smith"
},
{
"context": "name\" \"Karen Smith\"\n \"user/email\" \"[email protected]\"\n \"user/username\" \"smithk\"\n ",
"end": 4251,
"score": 0.9999263882637024,
"start": 4232,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]\"\n \"user/username\" \"smithk\"\n \"user/password\" \"insecure\"}\n ",
"end": 4292,
"score": 0.9993979930877686,
"start": 4286,
"tag": "USERNAME",
"value": "smithk"
},
{
"context": "ername\" \"smithk\"\n \"user/password\" \"insecure\"}\n req (-> (rtucore/req-w-std-hdrs rumet",
"end": 4335,
"score": 0.9987332224845886,
"start": 4327,
"tag": "PASSWORD",
"value": "insecure"
}
] |
test/pe_fp_rest/resource/vehicle/vehicles_res_test.clj
|
evanspa/pe-gasjot-rest
| 0 |
(ns pe-fp-rest.resource.vehicle.vehicles-res-test
(:require [clojure.test :refer :all]
[clojure.data.json :as json]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clojure.tools.logging :as log]
[clojure.pprint :refer (pprint)]
[compojure.core :refer [defroutes ANY]]
[ring.middleware.cookies :refer [wrap-cookies]]
[compojure.handler :as handler]
[ring.mock.request :as mock]
[pe-fp-rest.resource.vehicle.vehicles-res :as vehsres]
[pe-fp-rest.resource.vehicle.version.vehicles-res-v001]
[pe-fp-rest.resource.vehicle.vehicle-res :as vehres]
[pe-fp-rest.resource.vehicle.version.vehicle-res-v001]
[pe-fp-rest.meta :as meta]
[pe-user-core.ddl :as uddl]
[pe-fp-core.ddl :as fpddl]
[pe-fp-core.validation :as fpval]
[pe-jdbc-utils.core :as jcore]
[pe-fp-core.core :as fpcore]
[pe-rest-testutils.core :as rtucore]
[pe-core-utils.core :as ucore]
[pe-rest-utils.core :as rucore]
[pe-rest-utils.meta :as rumeta]
[pe-user-core.core :as usercore]
[pe-user-rest.meta :as usermeta]
[pe-fp-rest.test-utils :refer [fpmt-subtype-prefix
fp-auth-scheme
fp-auth-scheme-param-name
base-url
fphdr-auth-token
fphdr-error-mask
fphdr-establish-session
entity-uri-prefix
users-uri-template
vehicles-uri-template
vehicle-uri-template
db-spec
fixture-maker
users-route
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email]]))
(defroutes routes
users-route
(ANY vehicles-uri-template
[user-id]
(vehsres/vehicles-res db-spec
fpmt-subtype-prefix
fphdr-auth-token
fphdr-error-mask
fp-auth-scheme
fp-auth-scheme-param-name
base-url
entity-uri-prefix
(Long. user-id)
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Middleware-decorated app
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def app
(-> routes
(handler/api)
(wrap-cookies)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fixtures
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-fixtures :each (fixture-maker))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest integration-tests-1
(testing "Successful creation of user, app txn logs and vehicles."
(is (nil? (usercore/load-user-by-email db-spec "[email protected]")))
(is (nil? (usercore/load-user-by-username db-spec "smithk")))
(let [user {"user/name" "Karen Smith"
"user/email" "[email protected]"
"user/username" "smithk"
"user/password" "insecure"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
users-uri-template)
(rtucore/header fphdr-establish-session "true")
(mock/body (json/write-str user))
(mock/content-type (rucore/content-type rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"json"
"UTF-8")))
resp (app req)]
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
user-location-str (get hdrs "location")
resp-user-id-str (rtucore/last-url-part user-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-user (rucore/read-res pct resp-body-stream charset)
auth-token (get hdrs fphdr-auth-token)
[loaded-user-id loaded-user-ent] (usercore/load-user-by-authtoken db-spec
(Long. resp-user-id-str)
auth-token)]
;; Create 1st vehicle
(is (empty? (fpcore/vehicles-for-user db-spec loaded-user-id)))
(let [vehicle {"fpvehicle/name" "300Z"
"fpvehicle/default-octane" 93
"fpvehicle/fuel-capacity" 19.1}
vehicles-uri (str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles)
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
vehicles-uri)
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created 300Z vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "300Z" (get resp-veh "fpvehicle/name")))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (not (nil? (get resp-veh "fpvehicle/updated-at"))))
(is (= 93 (get resp-veh "fpvehicle/default-octane")))
(is (= 19.1 (get resp-veh "fpvehicle/fuel-capacity")))
(let [loaded-vehicles (fpcore/vehicles-for-user db-spec loaded-user-id)]
(is (= 1 (count loaded-vehicles)))
(let [[[loaded-veh-300z-id loaded-veh-300z]] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-300z-id))
(is (= "300Z" (:fpvehicle/name loaded-veh-300z)))
(is (= 93 (:fpvehicle/default-octane loaded-veh-300z)))
(is (= 19.1M (:fpvehicle/fuel-capacity loaded-veh-300z)))
;; Create 2nd vehicle
(let [vehicle {"fpvehicle/name" "Mazda CX-9"
"fpvehicle/default-octane" 87}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created mazda vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "Mazda CX-9" (get resp-veh "fpvehicle/name")))
(is (= 87 (get resp-veh "fpvehicle/default-octane")))
(let [loaded-vehicles (sort-by #(:fpvehicle/date-added (second %))
#(compare %2 %1)
(vec (fpcore/vehicles-for-user db-spec loaded-user-id)))]
(is (= 2 (count loaded-vehicles)))
(let [[[loaded-veh-mazda-id loaded-veh-mazda] _] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-mazda-id))
(is (= "Mazda CX-9" (:fpvehicle/name loaded-veh-mazda)))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (= 87 (:fpvehicle/default-octane loaded-veh-mazda)))))))))
;; Try to create a 3rd vehicle with a non-unique name
(let [vehicle {"fpvehicle/name" "Mazda CX-9"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 422 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(log/debug "hdrs: " hdrs)
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str))
(let [error-mask-str (get hdrs fphdr-error-mask)]
(is (nil? (get hdrs fphdr-auth-token)))
(is (not (nil? error-mask-str)))
(let [error-mask (Long/parseLong error-mask-str)]
(is (pos? (bit-and error-mask fpval/sv-any-issues)))
(is (pos? (bit-and error-mask fpval/sv-vehicle-already-exists)))
(is (zero? (bit-and error-mask fpval/sv-name-not-provided))))))))
;; try to create a vehicle that will cause a logout
(let [vehicle {"fpvehicle/name" "log-me-out"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str)))))
;; Now Try to create a vehicle with a fine name (but should
;; stil fail because we're no longer authenticated)
(let [vehicle {"fpvehicle/name" "Mazda CX-9 Grand Touring Edition"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (nil? user-location-str)))))))))))))))
|
64075
|
(ns pe-fp-rest.resource.vehicle.vehicles-res-test
(:require [clojure.test :refer :all]
[clojure.data.json :as json]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clojure.tools.logging :as log]
[clojure.pprint :refer (pprint)]
[compojure.core :refer [defroutes ANY]]
[ring.middleware.cookies :refer [wrap-cookies]]
[compojure.handler :as handler]
[ring.mock.request :as mock]
[pe-fp-rest.resource.vehicle.vehicles-res :as vehsres]
[pe-fp-rest.resource.vehicle.version.vehicles-res-v001]
[pe-fp-rest.resource.vehicle.vehicle-res :as vehres]
[pe-fp-rest.resource.vehicle.version.vehicle-res-v001]
[pe-fp-rest.meta :as meta]
[pe-user-core.ddl :as uddl]
[pe-fp-core.ddl :as fpddl]
[pe-fp-core.validation :as fpval]
[pe-jdbc-utils.core :as jcore]
[pe-fp-core.core :as fpcore]
[pe-rest-testutils.core :as rtucore]
[pe-core-utils.core :as ucore]
[pe-rest-utils.core :as rucore]
[pe-rest-utils.meta :as rumeta]
[pe-user-core.core :as usercore]
[pe-user-rest.meta :as usermeta]
[pe-fp-rest.test-utils :refer [fpmt-subtype-prefix
fp-auth-scheme
fp-auth-scheme-param-name
base-url
fphdr-auth-token
fphdr-error-mask
fphdr-establish-session
entity-uri-prefix
users-uri-template
vehicles-uri-template
vehicle-uri-template
db-spec
fixture-maker
users-route
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email]]))
(defroutes routes
users-route
(ANY vehicles-uri-template
[user-id]
(vehsres/vehicles-res db-spec
fpmt-subtype-prefix
fphdr-auth-token
fphdr-error-mask
fp-auth-scheme
fp-auth-scheme-param-name
base-url
entity-uri-prefix
(Long. user-id)
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Middleware-decorated app
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def app
(-> routes
(handler/api)
(wrap-cookies)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fixtures
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-fixtures :each (fixture-maker))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest integration-tests-1
(testing "Successful creation of user, app txn logs and vehicles."
(is (nil? (usercore/load-user-by-email db-spec "<EMAIL>")))
(is (nil? (usercore/load-user-by-username db-spec "smithk")))
(let [user {"user/name" "<NAME>"
"user/email" "<EMAIL>"
"user/username" "smithk"
"user/password" "<PASSWORD>"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
users-uri-template)
(rtucore/header fphdr-establish-session "true")
(mock/body (json/write-str user))
(mock/content-type (rucore/content-type rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"json"
"UTF-8")))
resp (app req)]
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
user-location-str (get hdrs "location")
resp-user-id-str (rtucore/last-url-part user-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-user (rucore/read-res pct resp-body-stream charset)
auth-token (get hdrs fphdr-auth-token)
[loaded-user-id loaded-user-ent] (usercore/load-user-by-authtoken db-spec
(Long. resp-user-id-str)
auth-token)]
;; Create 1st vehicle
(is (empty? (fpcore/vehicles-for-user db-spec loaded-user-id)))
(let [vehicle {"fpvehicle/name" "300Z"
"fpvehicle/default-octane" 93
"fpvehicle/fuel-capacity" 19.1}
vehicles-uri (str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles)
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
vehicles-uri)
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created 300Z vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "300Z" (get resp-veh "fpvehicle/name")))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (not (nil? (get resp-veh "fpvehicle/updated-at"))))
(is (= 93 (get resp-veh "fpvehicle/default-octane")))
(is (= 19.1 (get resp-veh "fpvehicle/fuel-capacity")))
(let [loaded-vehicles (fpcore/vehicles-for-user db-spec loaded-user-id)]
(is (= 1 (count loaded-vehicles)))
(let [[[loaded-veh-300z-id loaded-veh-300z]] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-300z-id))
(is (= "300Z" (:fpvehicle/name loaded-veh-300z)))
(is (= 93 (:fpvehicle/default-octane loaded-veh-300z)))
(is (= 19.1M (:fpvehicle/fuel-capacity loaded-veh-300z)))
;; Create 2nd vehicle
(let [vehicle {"fpvehicle/name" "Mazda CX-9"
"fpvehicle/default-octane" 87}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created mazda vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "Mazda CX-9" (get resp-veh "fpvehicle/name")))
(is (= 87 (get resp-veh "fpvehicle/default-octane")))
(let [loaded-vehicles (sort-by #(:fpvehicle/date-added (second %))
#(compare %2 %1)
(vec (fpcore/vehicles-for-user db-spec loaded-user-id)))]
(is (= 2 (count loaded-vehicles)))
(let [[[loaded-veh-mazda-id loaded-veh-mazda] _] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-mazda-id))
(is (= "Mazda CX-9" (:fpvehicle/name loaded-veh-mazda)))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (= 87 (:fpvehicle/default-octane loaded-veh-mazda)))))))))
;; Try to create a 3rd vehicle with a non-unique name
(let [vehicle {"fpvehicle/name" "Mazda CX-9"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 422 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(log/debug "hdrs: " hdrs)
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str))
(let [error-mask-str (get hdrs fphdr-error-mask)]
(is (nil? (get hdrs fphdr-auth-token)))
(is (not (nil? error-mask-str)))
(let [error-mask (Long/parseLong error-mask-str)]
(is (pos? (bit-and error-mask fpval/sv-any-issues)))
(is (pos? (bit-and error-mask fpval/sv-vehicle-already-exists)))
(is (zero? (bit-and error-mask fpval/sv-name-not-provided))))))))
;; try to create a vehicle that will cause a logout
(let [vehicle {"fpvehicle/name" "log-me-out"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str)))))
;; Now Try to create a vehicle with a fine name (but should
;; stil fail because we're no longer authenticated)
(let [vehicle {"fpvehicle/name" "Mazda CX-9 Grand Touring Edition"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (nil? user-location-str)))))))))))))))
| true |
(ns pe-fp-rest.resource.vehicle.vehicles-res-test
(:require [clojure.test :refer :all]
[clojure.data.json :as json]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clojure.tools.logging :as log]
[clojure.pprint :refer (pprint)]
[compojure.core :refer [defroutes ANY]]
[ring.middleware.cookies :refer [wrap-cookies]]
[compojure.handler :as handler]
[ring.mock.request :as mock]
[pe-fp-rest.resource.vehicle.vehicles-res :as vehsres]
[pe-fp-rest.resource.vehicle.version.vehicles-res-v001]
[pe-fp-rest.resource.vehicle.vehicle-res :as vehres]
[pe-fp-rest.resource.vehicle.version.vehicle-res-v001]
[pe-fp-rest.meta :as meta]
[pe-user-core.ddl :as uddl]
[pe-fp-core.ddl :as fpddl]
[pe-fp-core.validation :as fpval]
[pe-jdbc-utils.core :as jcore]
[pe-fp-core.core :as fpcore]
[pe-rest-testutils.core :as rtucore]
[pe-core-utils.core :as ucore]
[pe-rest-utils.core :as rucore]
[pe-rest-utils.meta :as rumeta]
[pe-user-core.core :as usercore]
[pe-user-rest.meta :as usermeta]
[pe-fp-rest.test-utils :refer [fpmt-subtype-prefix
fp-auth-scheme
fp-auth-scheme-param-name
base-url
fphdr-auth-token
fphdr-error-mask
fphdr-establish-session
entity-uri-prefix
users-uri-template
vehicles-uri-template
vehicle-uri-template
db-spec
fixture-maker
users-route
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email]]))
(defroutes routes
users-route
(ANY vehicles-uri-template
[user-id]
(vehsres/vehicles-res db-spec
fpmt-subtype-prefix
fphdr-auth-token
fphdr-error-mask
fp-auth-scheme
fp-auth-scheme-param-name
base-url
entity-uri-prefix
(Long. user-id)
empty-embedded-resources-fn
empty-links-fn
err-notification-mustache-template
err-subject
err-from-email
err-to-email)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Middleware-decorated app
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def app
(-> routes
(handler/api)
(wrap-cookies)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fixtures
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-fixtures :each (fixture-maker))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest integration-tests-1
(testing "Successful creation of user, app txn logs and vehicles."
(is (nil? (usercore/load-user-by-email db-spec "PI:EMAIL:<EMAIL>END_PI")))
(is (nil? (usercore/load-user-by-username db-spec "smithk")))
(let [user {"user/name" "PI:NAME:<NAME>END_PI"
"user/email" "PI:EMAIL:<EMAIL>END_PI"
"user/username" "smithk"
"user/password" "PI:PASSWORD:<PASSWORD>END_PI"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
users-uri-template)
(rtucore/header fphdr-establish-session "true")
(mock/body (json/write-str user))
(mock/content-type (rucore/content-type rumeta/mt-type
(usermeta/mt-subtype-user fpmt-subtype-prefix)
usermeta/v001
"json"
"UTF-8")))
resp (app req)]
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
user-location-str (get hdrs "location")
resp-user-id-str (rtucore/last-url-part user-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-user (rucore/read-res pct resp-body-stream charset)
auth-token (get hdrs fphdr-auth-token)
[loaded-user-id loaded-user-ent] (usercore/load-user-by-authtoken db-spec
(Long. resp-user-id-str)
auth-token)]
;; Create 1st vehicle
(is (empty? (fpcore/vehicles-for-user db-spec loaded-user-id)))
(let [vehicle {"fpvehicle/name" "300Z"
"fpvehicle/default-octane" 93
"fpvehicle/fuel-capacity" 19.1}
vehicles-uri (str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles)
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
vehicles-uri)
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created 300Z vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "300Z" (get resp-veh "fpvehicle/name")))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (not (nil? (get resp-veh "fpvehicle/updated-at"))))
(is (= 93 (get resp-veh "fpvehicle/default-octane")))
(is (= 19.1 (get resp-veh "fpvehicle/fuel-capacity")))
(let [loaded-vehicles (fpcore/vehicles-for-user db-spec loaded-user-id)]
(is (= 1 (count loaded-vehicles)))
(let [[[loaded-veh-300z-id loaded-veh-300z]] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-300z-id))
(is (= "300Z" (:fpvehicle/name loaded-veh-300z)))
(is (= 93 (:fpvehicle/default-octane loaded-veh-300z)))
(is (= 19.1M (:fpvehicle/fuel-capacity loaded-veh-300z)))
;; Create 2nd vehicle
(let [vehicle {"fpvehicle/name" "Mazda CX-9"
"fpvehicle/default-octane" 87}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 201 (:status resp))))
(testing "headers and body of created mazda vehicle"
(let [hdrs (:headers resp)
resp-body-stream (:body resp)
veh-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (not (nil? resp-body-stream)))
(is (not (nil? veh-location-str)))
(let [resp-veh-id-str (rtucore/last-url-part veh-location-str)
pct (rucore/parse-media-type (get hdrs "Content-Type"))
charset (get rumeta/char-sets (:charset pct))
resp-veh (rucore/read-res pct resp-body-stream charset)]
(is (not (nil? resp-veh-id-str)))
(is (not (nil? resp-veh)))
(is (= "Mazda CX-9" (get resp-veh "fpvehicle/name")))
(is (= 87 (get resp-veh "fpvehicle/default-octane")))
(let [loaded-vehicles (sort-by #(:fpvehicle/date-added (second %))
#(compare %2 %1)
(vec (fpcore/vehicles-for-user db-spec loaded-user-id)))]
(is (= 2 (count loaded-vehicles)))
(let [[[loaded-veh-mazda-id loaded-veh-mazda] _] loaded-vehicles]
(is (= (Long/parseLong resp-veh-id-str) loaded-veh-mazda-id))
(is (= "Mazda CX-9" (:fpvehicle/name loaded-veh-mazda)))
(is (not (nil? (get resp-veh "fpvehicle/created-at"))))
(is (= 87 (:fpvehicle/default-octane loaded-veh-mazda)))))))))
;; Try to create a 3rd vehicle with a non-unique name
(let [vehicle {"fpvehicle/name" "Mazda CX-9"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 422 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(log/debug "hdrs: " hdrs)
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str))
(let [error-mask-str (get hdrs fphdr-error-mask)]
(is (nil? (get hdrs fphdr-auth-token)))
(is (not (nil? error-mask-str)))
(let [error-mask (Long/parseLong error-mask-str)]
(is (pos? (bit-and error-mask fpval/sv-any-issues)))
(is (pos? (bit-and error-mask fpval/sv-vehicle-already-exists)))
(is (zero? (bit-and error-mask fpval/sv-name-not-provided))))))))
;; try to create a vehicle that will cause a logout
(let [vehicle {"fpvehicle/name" "log-me-out"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (= "Accept, Accept-Charset, Accept-Language" (get hdrs "Vary")))
(is (nil? user-location-str)))))
;; Now Try to create a vehicle with a fine name (but should
;; stil fail because we're no longer authenticated)
(let [vehicle {"fpvehicle/name" "Mazda CX-9 Grand Touring Edition"}
req (-> (rtucore/req-w-std-hdrs rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"UTF-8;q=1,ISO-8859-1;q=0"
"json"
"en-US"
:post
(str base-url
entity-uri-prefix
usermeta/pathcomp-users
"/"
resp-user-id-str
"/"
meta/pathcomp-vehicles))
(mock/body (json/write-str vehicle))
(mock/content-type (rucore/content-type rumeta/mt-type
(meta/mt-subtype-vehicle fpmt-subtype-prefix)
meta/v001
"json"
"UTF-8"))
(rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme
fp-auth-scheme-param-name
auth-token)))
resp (app req)]
(testing "status code" (is (= 401 (:status resp))))
(testing "headers and body of created user"
(let [hdrs (:headers resp)
user-location-str (get hdrs "location")]
(is (nil? user-location-str)))))))))))))))
|
[
{
"context": " :selected_dates []\n :name (:name user)\n :email (:email user)\n :phon",
"end": 3911,
"score": 0.6434166431427002,
"start": 3907,
"tag": "NAME",
"value": "user"
},
{
"context": "ter_link {:href \"https://www.flaticon.com/authors/spovv\"} \"Lähde joillekin ikoneille\"]]])\n\n(defn logout-l",
"end": 16656,
"score": 0.9291183352470398,
"start": 16651,
"tag": "USERNAME",
"value": "spovv"
},
{
"context": "{:href \"https://www.flaticon.com/authors/spovv\"} \"Lähde joillekin ikoneille\"]]])\n\n(defn logout-link []\n [:div.logout_header\n",
"end": 16685,
"score": 0.9996135234832764,
"start": 16660,
"tag": "NAME",
"value": "Lähde joillekin ikoneille"
}
] |
src/cljs/m_cal/core.cljs
|
jaittola/m-cal
| 0 |
(ns m-cal.core
(:require [reagent.core :as reagent]
[clojure.string :as string]
[cljs-time.core :as time]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[m-cal.utils :as u]
[m-cal.login :as login]
[m-cal.token-utils :as t]
[cemerick.url :refer (url url-encode)]
[cljsjs.babel-polyfill])
(:require-macros [cljs.core.async.macros :refer [go]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vars
(def min-input-len 5)
(def email-validation-regex #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])")
(def phone-number-validation-regex #"^((\+([0-9] *){1,3})|0)([0-9] *){6,15}$")
(defonce app-state
(reagent/atom {:user-token nil
:required_days 2
:buffer_days_for_cancel 2
:today-iso nil
:today nil
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_private_id nil
:user_public_id nil
:first_date nil
:last_date nil
:booked_dates []
:error_status nil
:success_status nil
:request_in_progress false}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities for maintaining the state and input validation
(defn set-error-status [new-status]
(swap! app-state assoc :error_status new-status :success_status nil))
(defn set-success-status [new-status]
(swap! app-state assoc :error_status nil :success_status new-status))
(defn clear-statuses []
(swap! app-state assoc :error_status nil :success_status nil))
(defn update-state-from-text-input [field on-change-event]
(swap! app-state assoc field (-> on-change-event .-target .-value)))
(defn make-selection-date [date & [is-cancellable]]
(let [cancellable (if (some? is-cancellable)
is-cancellable
true)]
{:date date
:is-cancellable cancellable}))
(defn add-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (conj (:selected_dates state) new-date)
(distinct)
(assoc state :selected_dates)))
(make-selection-date date)))
(defn remove-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (filter #(not (= date (:date %))) (:selected_dates state))
(assoc state :selected_dates)))
date))
(defn set-booked-dates [new-dates]
(swap! app-state assoc :booked_dates new-dates))
(defn clear-user []
(swap! app-state assoc
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_public_id nil)
(t/clear-user-token app-state))
(defn clear-user-private-id []
(swap! app-state assoc
:user_private_id nil))
(defn add-cancellation-status [selected-dates]
(let [dates (or selected-dates [])
today (:today @app-state)
buffer-days (:buffer_days_for_cancel @app-state)]
(map (fn [d]
(->> (u/is-days-after-today? today d buffer-days)
(make-selection-date d)))
dates)))
(defn set-user [user selected_dates]
(let [selected-dates-with-cancellation (add-cancellation-status selected_dates)]
(swap! app-state assoc
:selected_dates []
:name (:name user)
:email (:email user)
:phone (:phone user)
:yacht_name (:yacht_name user)
:user_private_id (:secret_id user)
:user_public_id (:id user)
:selected_dates selected-dates-with-cancellation)))
(defn set-selected-dates [selected_dates]
(swap! app-state assoc
:selected_dates (add-cancellation-status selected_dates)))
(defn set-user-private-id [private_id]
(swap! app-state assoc
:user_private_id private_id))
(defn clear-selected-days []
(set-selected-dates nil))
(defn set-request-in-progress [in-progress]
(swap! app-state assoc
:request_in_progress in-progress))
(defn set-calendar-config [config]
(swap! app-state assoc
:first_date (:first_date config)
:last_date (:last_date config)
:required_days (or (:required_days config) 2)
:buffer_days_for_cancel (:buffer_days_for_cancel config)
:today-iso (:today config)
:today (u/parse-ymd (:today config))))
(defn clear-user-token-and-cookie []
(t/clear-cookie)
(clear-user)
(clear-statuses)
(set-booked-dates []))
(defn simple-input-validation [value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else :good)))
(defn re-input-validation [field-validation-regex value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else (if (re-matches field-validation-regex value)
:good
:bad))))
(defn email-input-validation [value]
(re-input-validation email-validation-regex value))
(defn phone-input-validation [value]
(re-input-validation phone-number-validation-regex value))
(defn all-input-validates [ratom]
(and (every? #(= :good %)
[(simple-input-validation (:name @ratom))
(simple-input-validation (:yacht_name @ratom))
(email-input-validation (:email @ratom))
(phone-input-validation (:phone @ratom))])
(>= (count (:selected_dates @ratom)) (:required_days @ratom))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HTTP calls to the booking API
(defn auth-header [ratom]
{"X-Auth-Token" (t/get-user-token ratom)})
(defn load-bookings [ratom]
(go (let [private-id (:user_private_id @ratom)
request-uri (if private-id
(str "/bookings/api/1/bookings/" private-id)
"/bookings/api/1/bookings")
response (<! (http/get request-uri
{:headers (auth-header ratom)}))
status-ok (= (:status response) 200)
status-unauthorised (= (:status response) 401)
body (:body response)
bookings (when status-ok
(:all_bookings body))
config (when status-ok
(:calendar_config body))
user (when status-ok
(:user body))
selected_dates (when status-ok
(:selected_dates body))]
(if status-unauthorised
(clear-user-token-and-cookie)
(if bookings
(set-booked-dates bookings)
(do
(set-booked-dates [])
(set-error-status "Varaustietojen lataaminen epäonnistui. Yritä myöhemmin uudelleen"))))
(when config
(set-calendar-config config))
(when (and selected_dates user)
(set-user user selected_dates)))))
(defn save-bookings [ratom]
(go (do
(set-request-in-progress true)
(let [private-id (:user_private_id @ratom)
body {
:headers (auth-header ratom)
:json-params {:name (:name @ratom)
:email (:email @ratom)
:phone (:phone @ratom)
:yacht_name (:yacht_name @ratom)
:selected_dates (map
#(:date %)
(:selected_dates @ratom))}}
request (if private-id
(http/put (str "/bookings/api/1/bookings/" private-id) body)
(http/post "/bookings/api/1/bookings" body))
response (<! request)
status (:status response)
body (:body response)
bookings (:all_bookings body)
user (:user body)
selected_dates (:selected_dates body)]
(set-request-in-progress false)
(when bookings
(set-booked-dates bookings))
(case status
200 (do
(set-user user selected_dates)
(set-success-status "Varauksesi on talletettu. Järjestelmä lähettää varausvahvistuksen antamaasi sähköpostiosoitteeseen. Varausvahvistuksessa on linkki, jota voit käyttää varaustesi muokkaamiseen."))
409 (do
(set-selected-dates selected_dates)
(set-error-status "Joku muu ehti valita samat päivät kuin sinä. Valitse uudet päivät."))
401 (clear-user-token-and-cookie)
(do
(set-error-status "Varauksien tallettaminen epäonnistui. Yritä myöhemmin uudelleen.")))))))
(defn set-uri-to-root []
(js/window.history.replaceState {} "Merenkävijät" "/"))
(defn logout []
(let [token (t/get-user-token app-state)]
(clear-user-private-id)
(clear-user-token-and-cookie)
(set-uri-to-root)
(when token
(login/perform-logout-request token))))
(defn successful-login [token]
(t/set-user-token-and-cookie app-state token)
(load-bookings app-state))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Page
(defn input-class-name [validator-function value]
(case (validator-function value)
:empty "contact_input"
:bad "contact_input_bad"
:good "contact_input"))
(defn instructions []
[:div.instruction_area
[:h3 "Huomioitavaa"]
[:ul
[:li "Kaikilla Särkällä veneitä pitävillä on velvollisuus toimia "
"yövartijana Särkällä kahtena yönä purjehduskauden aikana."]
[:li "Varatun vartiovuoron laiminlyönnistä laskutetaan voimassa "
"olevan hinnaston mukainen maksu."]
[:li "Vuorovarauksia on voi muuttaa ennenn varattua vartiovuoroa. "
"Vuoroa ei kuitenkaan voi vaihtaa enää kahta päivää "
"ennen varattua päivää. Muutoksia juuri ennen vartiovuoroa "
"on syytä välttää, jottei Särkkä jää ilman vartijaa. "
"Toimiva vartiointi Särkällä on kaikkien veneenomistajien "
"etujen mukaista ja estää mm. myrskyvahinkoja."]]
[:h3 "Toimi näin"]
[:ol
[:li.instruction "Syötä nimesi, veneesi nimi ja yhteystietosi "
"allaoleviin kenttiin. Yhteystietoja ei julkaista varauslistassa."]
[:li.instruction "Valitse kaksi vapaata vartiovuoroa."]
[:li.instruction "Paina \"Varaa valitsemasi vuorot\" -nappia."]
[:li.instruction "Varausjärjestelmä lähettää sähköpostitse vahvistuksen "
"varauksestasi. Sähköpostiviestissä on WWW-linkki, jota voit käyttää "
"varauksiesi muokkaamiseen." ]
]]
)
(defn contact_entry [ratom]
[:div
[:div.contact_entry
[:div.contact_title "Nimesi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:name @ratom))
:value (:name @ratom)
:on-change #(update-state-from-text-input :name %)}]
]
[:div.contact_entry
[:div.contact_title "Veneesi nimi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:yacht_name @ratom))
:value (:yacht_name @ratom)
:on-change #(update-state-from-text-input :yacht_name %)}]
]
[:div.contact_entry
[:div.contact_title "Puhelinnumerosi:"]
[:input {:type "tel"
:maxLength 25
:class (input-class-name phone-input-validation (:phone @ratom))
:value (:phone @ratom)
:on-change #(update-state-from-text-input :phone %)}]
]
[:div.contact_entry
[:div.contact_title "Sähköpostiosoitteesi:"]
[:input {:type "email"
:class (input-class-name email-input-validation (:email @ratom))
:value (:email @ratom)
:on-change #(update-state-from-text-input :email %)}]
]
])
(defn selected_day [day]
(if day
(let [date (:date day)]
[:div.selected_day
[:div.selected_day_date (u/format-date date)]
(when (:is-cancellable day)
[:input.booking_cancel_button
{:type "image"
:on-click #(remove-date-selection date)
:src "images/red-trash.png"}])])
[:div.selected_day [u/blank-element]]))
(defn selection_area [ratom]
(let [days (->>
(:selected_dates @ratom)
(sort #(< (:date %1) (:date %2)))
(vec))]
[:div.selected_days_area
[:div.contact_title.selected_days_title "Valitsemasi vartiovuorot:"]
[:div.selected_days_selections
(->> (range (:required_days @ratom))
(map (fn [dayidx]
(let [day (get days dayidx)]
^{:key (str "day-" dayidx)}
[selected_day day]))))]]))
(defn selection_button_area [ratom]
(let [updating (some? (:user_private_id @ratom))]
[:div.select_button_container
[:button.selection {:disabled (or
(:request_in_progress @ratom)
(not (all-input-validates ratom)))
:on-click #(save-bookings ratom)}
(if updating
"Tallenna muutokset"
"Varaa valitsemasi vuorot")]
(when updating
[:button.selection {:disabled (:request_in_progress @ratom)
:on-click #(load-bookings ratom)}
"Peruuta muutokset"])]))
(defn booking-details [booking]
[:div (:name booking) [:br] (:yacht_name booking)])
(defn my-details-for-booking [ratom]
[:div (:name @ratom) [:br] (:yacht_name @ratom)])
(defn day-details-chosen-cancellable []
[:input.booking_checkbox
{:type "image"
:src "images/blue-checkmark.png"}])
(defn day-details-bookable []
[:div.booking_checkbox])
(defn day-details-free-but-not-bookable []
[:div.booking_checkbox_appear_disabled
{:disabled true}])
(defn calendar-cell-booked-for-me [ratom]
[:div.calendar-booked-content-cell
[day-details-chosen-cancellable]
[my-details-for-booking ratom]])
(defn is-in-future? [isoday isotoday]
(>= isoday isotoday))
(defn my-booking-for-day [day]
(let [isoday (:isoformat day)]
(->>
(:selected_dates @app-state)
(filter #(== (:date %) isoday))
(first))))
(defn has-required-bookings? []
(>= (count (:selected_dates @app-state)) (:required_days @app-state)))
(defn booking-or-free [today-iso daydata ratom] ""
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(cond
(and my-booking is-cancellable) [calendar-cell-booked-for-me ratom]
(and my-booking (not is-cancellable)) [booking-details booking]
(and booking (not (= (:user_id booking) (:user_public_id @ratom)))) [booking-details booking]
(and (nil? booking) (not day-is-in-future)) u/blank-element
(has-required-bookings?) [day-details-free-but-not-bookable]
:else [day-details-bookable])))
(defn cell-click-handler [daydata today-iso]
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(when day-is-in-future
(cond
is-cancellable (remove-date-selection isoday)
(and (not (has-required-bookings?))
(or (nil? booking)
(= (:user_id booking) (:user_public_id @app-state)))) (add-date-selection isoday)))))
(defn render-booking-calendar [ratom]
(let [bookings (:booked_dates @ratom)
first-date (:first_date @ratom)
last-date (:last_date @ratom)]
[u/render-calendar ratom first-date last-date bookings booking-or-free cell-click-handler]))
(defn footer []
[:div.footer
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/"} "Merenkävijät ry"]]
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/tietosuojaseloste.html"} "Tietosuojaseloste"]]
[:div.footer_element
[:a.footer_link {:href "https://www.flaticon.com/authors/spovv"} "Lähde joillekin ikoneille"]]])
(defn logout-link []
[:div.logout_header
[:div.push_right]
[:div.logout_link
[:div.link_like {:on-click #(logout)}
"Kirjaudu ulos"]]])
(defn page [ratom]
(if (t/get-user-token ratom)
[:div
[logout-link]
[:h1 "Merenkävijät ry"]
[:h2 "Särkän vartiovuorojen varaukset"]
[instructions]
[contact_entry ratom]
[selection_area ratom]
[selection_button_area ratom]
[u/success_status_area ratom]
[u/error_status_area ratom]
[render-booking-calendar ratom]
[footer]]
[:div
[login/login-form-for-default-user successful-login]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
(defn dev-setup []
(when ^boolean js/goog.DEBUG
(enable-console-print!)
(println "dev mode")
))
(defn reload []
(let [location-url (url (-> js/window .-location .-href))
user (get (:query location-url) "user")]
(when user
(set-user-private-id user)))
(load-bookings app-state)
(reagent/render [page app-state]
(.getElementById js/document "app")))
(defn ^:export main []
(dev-setup)
(t/set-user-token-from-cookie app-state)
(reload))
|
1702
|
(ns m-cal.core
(:require [reagent.core :as reagent]
[clojure.string :as string]
[cljs-time.core :as time]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[m-cal.utils :as u]
[m-cal.login :as login]
[m-cal.token-utils :as t]
[cemerick.url :refer (url url-encode)]
[cljsjs.babel-polyfill])
(:require-macros [cljs.core.async.macros :refer [go]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vars
(def min-input-len 5)
(def email-validation-regex #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])")
(def phone-number-validation-regex #"^((\+([0-9] *){1,3})|0)([0-9] *){6,15}$")
(defonce app-state
(reagent/atom {:user-token nil
:required_days 2
:buffer_days_for_cancel 2
:today-iso nil
:today nil
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_private_id nil
:user_public_id nil
:first_date nil
:last_date nil
:booked_dates []
:error_status nil
:success_status nil
:request_in_progress false}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities for maintaining the state and input validation
(defn set-error-status [new-status]
(swap! app-state assoc :error_status new-status :success_status nil))
(defn set-success-status [new-status]
(swap! app-state assoc :error_status nil :success_status new-status))
(defn clear-statuses []
(swap! app-state assoc :error_status nil :success_status nil))
(defn update-state-from-text-input [field on-change-event]
(swap! app-state assoc field (-> on-change-event .-target .-value)))
(defn make-selection-date [date & [is-cancellable]]
(let [cancellable (if (some? is-cancellable)
is-cancellable
true)]
{:date date
:is-cancellable cancellable}))
(defn add-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (conj (:selected_dates state) new-date)
(distinct)
(assoc state :selected_dates)))
(make-selection-date date)))
(defn remove-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (filter #(not (= date (:date %))) (:selected_dates state))
(assoc state :selected_dates)))
date))
(defn set-booked-dates [new-dates]
(swap! app-state assoc :booked_dates new-dates))
(defn clear-user []
(swap! app-state assoc
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_public_id nil)
(t/clear-user-token app-state))
(defn clear-user-private-id []
(swap! app-state assoc
:user_private_id nil))
(defn add-cancellation-status [selected-dates]
(let [dates (or selected-dates [])
today (:today @app-state)
buffer-days (:buffer_days_for_cancel @app-state)]
(map (fn [d]
(->> (u/is-days-after-today? today d buffer-days)
(make-selection-date d)))
dates)))
(defn set-user [user selected_dates]
(let [selected-dates-with-cancellation (add-cancellation-status selected_dates)]
(swap! app-state assoc
:selected_dates []
:name (:name <NAME>)
:email (:email user)
:phone (:phone user)
:yacht_name (:yacht_name user)
:user_private_id (:secret_id user)
:user_public_id (:id user)
:selected_dates selected-dates-with-cancellation)))
(defn set-selected-dates [selected_dates]
(swap! app-state assoc
:selected_dates (add-cancellation-status selected_dates)))
(defn set-user-private-id [private_id]
(swap! app-state assoc
:user_private_id private_id))
(defn clear-selected-days []
(set-selected-dates nil))
(defn set-request-in-progress [in-progress]
(swap! app-state assoc
:request_in_progress in-progress))
(defn set-calendar-config [config]
(swap! app-state assoc
:first_date (:first_date config)
:last_date (:last_date config)
:required_days (or (:required_days config) 2)
:buffer_days_for_cancel (:buffer_days_for_cancel config)
:today-iso (:today config)
:today (u/parse-ymd (:today config))))
(defn clear-user-token-and-cookie []
(t/clear-cookie)
(clear-user)
(clear-statuses)
(set-booked-dates []))
(defn simple-input-validation [value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else :good)))
(defn re-input-validation [field-validation-regex value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else (if (re-matches field-validation-regex value)
:good
:bad))))
(defn email-input-validation [value]
(re-input-validation email-validation-regex value))
(defn phone-input-validation [value]
(re-input-validation phone-number-validation-regex value))
(defn all-input-validates [ratom]
(and (every? #(= :good %)
[(simple-input-validation (:name @ratom))
(simple-input-validation (:yacht_name @ratom))
(email-input-validation (:email @ratom))
(phone-input-validation (:phone @ratom))])
(>= (count (:selected_dates @ratom)) (:required_days @ratom))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HTTP calls to the booking API
(defn auth-header [ratom]
{"X-Auth-Token" (t/get-user-token ratom)})
(defn load-bookings [ratom]
(go (let [private-id (:user_private_id @ratom)
request-uri (if private-id
(str "/bookings/api/1/bookings/" private-id)
"/bookings/api/1/bookings")
response (<! (http/get request-uri
{:headers (auth-header ratom)}))
status-ok (= (:status response) 200)
status-unauthorised (= (:status response) 401)
body (:body response)
bookings (when status-ok
(:all_bookings body))
config (when status-ok
(:calendar_config body))
user (when status-ok
(:user body))
selected_dates (when status-ok
(:selected_dates body))]
(if status-unauthorised
(clear-user-token-and-cookie)
(if bookings
(set-booked-dates bookings)
(do
(set-booked-dates [])
(set-error-status "Varaustietojen lataaminen epäonnistui. Yritä myöhemmin uudelleen"))))
(when config
(set-calendar-config config))
(when (and selected_dates user)
(set-user user selected_dates)))))
(defn save-bookings [ratom]
(go (do
(set-request-in-progress true)
(let [private-id (:user_private_id @ratom)
body {
:headers (auth-header ratom)
:json-params {:name (:name @ratom)
:email (:email @ratom)
:phone (:phone @ratom)
:yacht_name (:yacht_name @ratom)
:selected_dates (map
#(:date %)
(:selected_dates @ratom))}}
request (if private-id
(http/put (str "/bookings/api/1/bookings/" private-id) body)
(http/post "/bookings/api/1/bookings" body))
response (<! request)
status (:status response)
body (:body response)
bookings (:all_bookings body)
user (:user body)
selected_dates (:selected_dates body)]
(set-request-in-progress false)
(when bookings
(set-booked-dates bookings))
(case status
200 (do
(set-user user selected_dates)
(set-success-status "Varauksesi on talletettu. Järjestelmä lähettää varausvahvistuksen antamaasi sähköpostiosoitteeseen. Varausvahvistuksessa on linkki, jota voit käyttää varaustesi muokkaamiseen."))
409 (do
(set-selected-dates selected_dates)
(set-error-status "Joku muu ehti valita samat päivät kuin sinä. Valitse uudet päivät."))
401 (clear-user-token-and-cookie)
(do
(set-error-status "Varauksien tallettaminen epäonnistui. Yritä myöhemmin uudelleen.")))))))
(defn set-uri-to-root []
(js/window.history.replaceState {} "Merenkävijät" "/"))
(defn logout []
(let [token (t/get-user-token app-state)]
(clear-user-private-id)
(clear-user-token-and-cookie)
(set-uri-to-root)
(when token
(login/perform-logout-request token))))
(defn successful-login [token]
(t/set-user-token-and-cookie app-state token)
(load-bookings app-state))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Page
(defn input-class-name [validator-function value]
(case (validator-function value)
:empty "contact_input"
:bad "contact_input_bad"
:good "contact_input"))
(defn instructions []
[:div.instruction_area
[:h3 "Huomioitavaa"]
[:ul
[:li "Kaikilla Särkällä veneitä pitävillä on velvollisuus toimia "
"yövartijana Särkällä kahtena yönä purjehduskauden aikana."]
[:li "Varatun vartiovuoron laiminlyönnistä laskutetaan voimassa "
"olevan hinnaston mukainen maksu."]
[:li "Vuorovarauksia on voi muuttaa ennenn varattua vartiovuoroa. "
"Vuoroa ei kuitenkaan voi vaihtaa enää kahta päivää "
"ennen varattua päivää. Muutoksia juuri ennen vartiovuoroa "
"on syytä välttää, jottei Särkkä jää ilman vartijaa. "
"Toimiva vartiointi Särkällä on kaikkien veneenomistajien "
"etujen mukaista ja estää mm. myrskyvahinkoja."]]
[:h3 "Toimi näin"]
[:ol
[:li.instruction "Syötä nimesi, veneesi nimi ja yhteystietosi "
"allaoleviin kenttiin. Yhteystietoja ei julkaista varauslistassa."]
[:li.instruction "Valitse kaksi vapaata vartiovuoroa."]
[:li.instruction "Paina \"Varaa valitsemasi vuorot\" -nappia."]
[:li.instruction "Varausjärjestelmä lähettää sähköpostitse vahvistuksen "
"varauksestasi. Sähköpostiviestissä on WWW-linkki, jota voit käyttää "
"varauksiesi muokkaamiseen." ]
]]
)
(defn contact_entry [ratom]
[:div
[:div.contact_entry
[:div.contact_title "Nimesi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:name @ratom))
:value (:name @ratom)
:on-change #(update-state-from-text-input :name %)}]
]
[:div.contact_entry
[:div.contact_title "Veneesi nimi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:yacht_name @ratom))
:value (:yacht_name @ratom)
:on-change #(update-state-from-text-input :yacht_name %)}]
]
[:div.contact_entry
[:div.contact_title "Puhelinnumerosi:"]
[:input {:type "tel"
:maxLength 25
:class (input-class-name phone-input-validation (:phone @ratom))
:value (:phone @ratom)
:on-change #(update-state-from-text-input :phone %)}]
]
[:div.contact_entry
[:div.contact_title "Sähköpostiosoitteesi:"]
[:input {:type "email"
:class (input-class-name email-input-validation (:email @ratom))
:value (:email @ratom)
:on-change #(update-state-from-text-input :email %)}]
]
])
(defn selected_day [day]
(if day
(let [date (:date day)]
[:div.selected_day
[:div.selected_day_date (u/format-date date)]
(when (:is-cancellable day)
[:input.booking_cancel_button
{:type "image"
:on-click #(remove-date-selection date)
:src "images/red-trash.png"}])])
[:div.selected_day [u/blank-element]]))
(defn selection_area [ratom]
(let [days (->>
(:selected_dates @ratom)
(sort #(< (:date %1) (:date %2)))
(vec))]
[:div.selected_days_area
[:div.contact_title.selected_days_title "Valitsemasi vartiovuorot:"]
[:div.selected_days_selections
(->> (range (:required_days @ratom))
(map (fn [dayidx]
(let [day (get days dayidx)]
^{:key (str "day-" dayidx)}
[selected_day day]))))]]))
(defn selection_button_area [ratom]
(let [updating (some? (:user_private_id @ratom))]
[:div.select_button_container
[:button.selection {:disabled (or
(:request_in_progress @ratom)
(not (all-input-validates ratom)))
:on-click #(save-bookings ratom)}
(if updating
"Tallenna muutokset"
"Varaa valitsemasi vuorot")]
(when updating
[:button.selection {:disabled (:request_in_progress @ratom)
:on-click #(load-bookings ratom)}
"Peruuta muutokset"])]))
(defn booking-details [booking]
[:div (:name booking) [:br] (:yacht_name booking)])
(defn my-details-for-booking [ratom]
[:div (:name @ratom) [:br] (:yacht_name @ratom)])
(defn day-details-chosen-cancellable []
[:input.booking_checkbox
{:type "image"
:src "images/blue-checkmark.png"}])
(defn day-details-bookable []
[:div.booking_checkbox])
(defn day-details-free-but-not-bookable []
[:div.booking_checkbox_appear_disabled
{:disabled true}])
(defn calendar-cell-booked-for-me [ratom]
[:div.calendar-booked-content-cell
[day-details-chosen-cancellable]
[my-details-for-booking ratom]])
(defn is-in-future? [isoday isotoday]
(>= isoday isotoday))
(defn my-booking-for-day [day]
(let [isoday (:isoformat day)]
(->>
(:selected_dates @app-state)
(filter #(== (:date %) isoday))
(first))))
(defn has-required-bookings? []
(>= (count (:selected_dates @app-state)) (:required_days @app-state)))
(defn booking-or-free [today-iso daydata ratom] ""
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(cond
(and my-booking is-cancellable) [calendar-cell-booked-for-me ratom]
(and my-booking (not is-cancellable)) [booking-details booking]
(and booking (not (= (:user_id booking) (:user_public_id @ratom)))) [booking-details booking]
(and (nil? booking) (not day-is-in-future)) u/blank-element
(has-required-bookings?) [day-details-free-but-not-bookable]
:else [day-details-bookable])))
(defn cell-click-handler [daydata today-iso]
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(when day-is-in-future
(cond
is-cancellable (remove-date-selection isoday)
(and (not (has-required-bookings?))
(or (nil? booking)
(= (:user_id booking) (:user_public_id @app-state)))) (add-date-selection isoday)))))
(defn render-booking-calendar [ratom]
(let [bookings (:booked_dates @ratom)
first-date (:first_date @ratom)
last-date (:last_date @ratom)]
[u/render-calendar ratom first-date last-date bookings booking-or-free cell-click-handler]))
(defn footer []
[:div.footer
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/"} "Merenkävijät ry"]]
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/tietosuojaseloste.html"} "Tietosuojaseloste"]]
[:div.footer_element
[:a.footer_link {:href "https://www.flaticon.com/authors/spovv"} "<NAME>"]]])
(defn logout-link []
[:div.logout_header
[:div.push_right]
[:div.logout_link
[:div.link_like {:on-click #(logout)}
"Kirjaudu ulos"]]])
(defn page [ratom]
(if (t/get-user-token ratom)
[:div
[logout-link]
[:h1 "Merenkävijät ry"]
[:h2 "Särkän vartiovuorojen varaukset"]
[instructions]
[contact_entry ratom]
[selection_area ratom]
[selection_button_area ratom]
[u/success_status_area ratom]
[u/error_status_area ratom]
[render-booking-calendar ratom]
[footer]]
[:div
[login/login-form-for-default-user successful-login]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
(defn dev-setup []
(when ^boolean js/goog.DEBUG
(enable-console-print!)
(println "dev mode")
))
(defn reload []
(let [location-url (url (-> js/window .-location .-href))
user (get (:query location-url) "user")]
(when user
(set-user-private-id user)))
(load-bookings app-state)
(reagent/render [page app-state]
(.getElementById js/document "app")))
(defn ^:export main []
(dev-setup)
(t/set-user-token-from-cookie app-state)
(reload))
| true |
(ns m-cal.core
(:require [reagent.core :as reagent]
[clojure.string :as string]
[cljs-time.core :as time]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[m-cal.utils :as u]
[m-cal.login :as login]
[m-cal.token-utils :as t]
[cemerick.url :refer (url url-encode)]
[cljsjs.babel-polyfill])
(:require-macros [cljs.core.async.macros :refer [go]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vars
(def min-input-len 5)
(def email-validation-regex #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])")
(def phone-number-validation-regex #"^((\+([0-9] *){1,3})|0)([0-9] *){6,15}$")
(defonce app-state
(reagent/atom {:user-token nil
:required_days 2
:buffer_days_for_cancel 2
:today-iso nil
:today nil
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_private_id nil
:user_public_id nil
:first_date nil
:last_date nil
:booked_dates []
:error_status nil
:success_status nil
:request_in_progress false}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities for maintaining the state and input validation
(defn set-error-status [new-status]
(swap! app-state assoc :error_status new-status :success_status nil))
(defn set-success-status [new-status]
(swap! app-state assoc :error_status nil :success_status new-status))
(defn clear-statuses []
(swap! app-state assoc :error_status nil :success_status nil))
(defn update-state-from-text-input [field on-change-event]
(swap! app-state assoc field (-> on-change-event .-target .-value)))
(defn make-selection-date [date & [is-cancellable]]
(let [cancellable (if (some? is-cancellable)
is-cancellable
true)]
{:date date
:is-cancellable cancellable}))
(defn add-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (conj (:selected_dates state) new-date)
(distinct)
(assoc state :selected_dates)))
(make-selection-date date)))
(defn remove-date-selection [date]
(clear-statuses)
(swap! app-state (fn [state new-date]
(->> (filter #(not (= date (:date %))) (:selected_dates state))
(assoc state :selected_dates)))
date))
(defn set-booked-dates [new-dates]
(swap! app-state assoc :booked_dates new-dates))
(defn clear-user []
(swap! app-state assoc
:selected_dates []
:name ""
:email ""
:phone ""
:yacht_name ""
:user_public_id nil)
(t/clear-user-token app-state))
(defn clear-user-private-id []
(swap! app-state assoc
:user_private_id nil))
(defn add-cancellation-status [selected-dates]
(let [dates (or selected-dates [])
today (:today @app-state)
buffer-days (:buffer_days_for_cancel @app-state)]
(map (fn [d]
(->> (u/is-days-after-today? today d buffer-days)
(make-selection-date d)))
dates)))
(defn set-user [user selected_dates]
(let [selected-dates-with-cancellation (add-cancellation-status selected_dates)]
(swap! app-state assoc
:selected_dates []
:name (:name PI:NAME:<NAME>END_PI)
:email (:email user)
:phone (:phone user)
:yacht_name (:yacht_name user)
:user_private_id (:secret_id user)
:user_public_id (:id user)
:selected_dates selected-dates-with-cancellation)))
(defn set-selected-dates [selected_dates]
(swap! app-state assoc
:selected_dates (add-cancellation-status selected_dates)))
(defn set-user-private-id [private_id]
(swap! app-state assoc
:user_private_id private_id))
(defn clear-selected-days []
(set-selected-dates nil))
(defn set-request-in-progress [in-progress]
(swap! app-state assoc
:request_in_progress in-progress))
(defn set-calendar-config [config]
(swap! app-state assoc
:first_date (:first_date config)
:last_date (:last_date config)
:required_days (or (:required_days config) 2)
:buffer_days_for_cancel (:buffer_days_for_cancel config)
:today-iso (:today config)
:today (u/parse-ymd (:today config))))
(defn clear-user-token-and-cookie []
(t/clear-cookie)
(clear-user)
(clear-statuses)
(set-booked-dates []))
(defn simple-input-validation [value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else :good)))
(defn re-input-validation [field-validation-regex value]
(let [string-len (count value)]
(cond
(== string-len 0) :empty
(< string-len min-input-len) :bad
:else (if (re-matches field-validation-regex value)
:good
:bad))))
(defn email-input-validation [value]
(re-input-validation email-validation-regex value))
(defn phone-input-validation [value]
(re-input-validation phone-number-validation-regex value))
(defn all-input-validates [ratom]
(and (every? #(= :good %)
[(simple-input-validation (:name @ratom))
(simple-input-validation (:yacht_name @ratom))
(email-input-validation (:email @ratom))
(phone-input-validation (:phone @ratom))])
(>= (count (:selected_dates @ratom)) (:required_days @ratom))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HTTP calls to the booking API
(defn auth-header [ratom]
{"X-Auth-Token" (t/get-user-token ratom)})
(defn load-bookings [ratom]
(go (let [private-id (:user_private_id @ratom)
request-uri (if private-id
(str "/bookings/api/1/bookings/" private-id)
"/bookings/api/1/bookings")
response (<! (http/get request-uri
{:headers (auth-header ratom)}))
status-ok (= (:status response) 200)
status-unauthorised (= (:status response) 401)
body (:body response)
bookings (when status-ok
(:all_bookings body))
config (when status-ok
(:calendar_config body))
user (when status-ok
(:user body))
selected_dates (when status-ok
(:selected_dates body))]
(if status-unauthorised
(clear-user-token-and-cookie)
(if bookings
(set-booked-dates bookings)
(do
(set-booked-dates [])
(set-error-status "Varaustietojen lataaminen epäonnistui. Yritä myöhemmin uudelleen"))))
(when config
(set-calendar-config config))
(when (and selected_dates user)
(set-user user selected_dates)))))
(defn save-bookings [ratom]
(go (do
(set-request-in-progress true)
(let [private-id (:user_private_id @ratom)
body {
:headers (auth-header ratom)
:json-params {:name (:name @ratom)
:email (:email @ratom)
:phone (:phone @ratom)
:yacht_name (:yacht_name @ratom)
:selected_dates (map
#(:date %)
(:selected_dates @ratom))}}
request (if private-id
(http/put (str "/bookings/api/1/bookings/" private-id) body)
(http/post "/bookings/api/1/bookings" body))
response (<! request)
status (:status response)
body (:body response)
bookings (:all_bookings body)
user (:user body)
selected_dates (:selected_dates body)]
(set-request-in-progress false)
(when bookings
(set-booked-dates bookings))
(case status
200 (do
(set-user user selected_dates)
(set-success-status "Varauksesi on talletettu. Järjestelmä lähettää varausvahvistuksen antamaasi sähköpostiosoitteeseen. Varausvahvistuksessa on linkki, jota voit käyttää varaustesi muokkaamiseen."))
409 (do
(set-selected-dates selected_dates)
(set-error-status "Joku muu ehti valita samat päivät kuin sinä. Valitse uudet päivät."))
401 (clear-user-token-and-cookie)
(do
(set-error-status "Varauksien tallettaminen epäonnistui. Yritä myöhemmin uudelleen.")))))))
(defn set-uri-to-root []
(js/window.history.replaceState {} "Merenkävijät" "/"))
(defn logout []
(let [token (t/get-user-token app-state)]
(clear-user-private-id)
(clear-user-token-and-cookie)
(set-uri-to-root)
(when token
(login/perform-logout-request token))))
(defn successful-login [token]
(t/set-user-token-and-cookie app-state token)
(load-bookings app-state))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Page
(defn input-class-name [validator-function value]
(case (validator-function value)
:empty "contact_input"
:bad "contact_input_bad"
:good "contact_input"))
(defn instructions []
[:div.instruction_area
[:h3 "Huomioitavaa"]
[:ul
[:li "Kaikilla Särkällä veneitä pitävillä on velvollisuus toimia "
"yövartijana Särkällä kahtena yönä purjehduskauden aikana."]
[:li "Varatun vartiovuoron laiminlyönnistä laskutetaan voimassa "
"olevan hinnaston mukainen maksu."]
[:li "Vuorovarauksia on voi muuttaa ennenn varattua vartiovuoroa. "
"Vuoroa ei kuitenkaan voi vaihtaa enää kahta päivää "
"ennen varattua päivää. Muutoksia juuri ennen vartiovuoroa "
"on syytä välttää, jottei Särkkä jää ilman vartijaa. "
"Toimiva vartiointi Särkällä on kaikkien veneenomistajien "
"etujen mukaista ja estää mm. myrskyvahinkoja."]]
[:h3 "Toimi näin"]
[:ol
[:li.instruction "Syötä nimesi, veneesi nimi ja yhteystietosi "
"allaoleviin kenttiin. Yhteystietoja ei julkaista varauslistassa."]
[:li.instruction "Valitse kaksi vapaata vartiovuoroa."]
[:li.instruction "Paina \"Varaa valitsemasi vuorot\" -nappia."]
[:li.instruction "Varausjärjestelmä lähettää sähköpostitse vahvistuksen "
"varauksestasi. Sähköpostiviestissä on WWW-linkki, jota voit käyttää "
"varauksiesi muokkaamiseen." ]
]]
)
(defn contact_entry [ratom]
[:div
[:div.contact_entry
[:div.contact_title "Nimesi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:name @ratom))
:value (:name @ratom)
:on-change #(update-state-from-text-input :name %)}]
]
[:div.contact_entry
[:div.contact_title "Veneesi nimi:"]
[:input {:type "text"
:class (input-class-name simple-input-validation (:yacht_name @ratom))
:value (:yacht_name @ratom)
:on-change #(update-state-from-text-input :yacht_name %)}]
]
[:div.contact_entry
[:div.contact_title "Puhelinnumerosi:"]
[:input {:type "tel"
:maxLength 25
:class (input-class-name phone-input-validation (:phone @ratom))
:value (:phone @ratom)
:on-change #(update-state-from-text-input :phone %)}]
]
[:div.contact_entry
[:div.contact_title "Sähköpostiosoitteesi:"]
[:input {:type "email"
:class (input-class-name email-input-validation (:email @ratom))
:value (:email @ratom)
:on-change #(update-state-from-text-input :email %)}]
]
])
(defn selected_day [day]
(if day
(let [date (:date day)]
[:div.selected_day
[:div.selected_day_date (u/format-date date)]
(when (:is-cancellable day)
[:input.booking_cancel_button
{:type "image"
:on-click #(remove-date-selection date)
:src "images/red-trash.png"}])])
[:div.selected_day [u/blank-element]]))
(defn selection_area [ratom]
(let [days (->>
(:selected_dates @ratom)
(sort #(< (:date %1) (:date %2)))
(vec))]
[:div.selected_days_area
[:div.contact_title.selected_days_title "Valitsemasi vartiovuorot:"]
[:div.selected_days_selections
(->> (range (:required_days @ratom))
(map (fn [dayidx]
(let [day (get days dayidx)]
^{:key (str "day-" dayidx)}
[selected_day day]))))]]))
(defn selection_button_area [ratom]
(let [updating (some? (:user_private_id @ratom))]
[:div.select_button_container
[:button.selection {:disabled (or
(:request_in_progress @ratom)
(not (all-input-validates ratom)))
:on-click #(save-bookings ratom)}
(if updating
"Tallenna muutokset"
"Varaa valitsemasi vuorot")]
(when updating
[:button.selection {:disabled (:request_in_progress @ratom)
:on-click #(load-bookings ratom)}
"Peruuta muutokset"])]))
(defn booking-details [booking]
[:div (:name booking) [:br] (:yacht_name booking)])
(defn my-details-for-booking [ratom]
[:div (:name @ratom) [:br] (:yacht_name @ratom)])
(defn day-details-chosen-cancellable []
[:input.booking_checkbox
{:type "image"
:src "images/blue-checkmark.png"}])
(defn day-details-bookable []
[:div.booking_checkbox])
(defn day-details-free-but-not-bookable []
[:div.booking_checkbox_appear_disabled
{:disabled true}])
(defn calendar-cell-booked-for-me [ratom]
[:div.calendar-booked-content-cell
[day-details-chosen-cancellable]
[my-details-for-booking ratom]])
(defn is-in-future? [isoday isotoday]
(>= isoday isotoday))
(defn my-booking-for-day [day]
(let [isoday (:isoformat day)]
(->>
(:selected_dates @app-state)
(filter #(== (:date %) isoday))
(first))))
(defn has-required-bookings? []
(>= (count (:selected_dates @app-state)) (:required_days @app-state)))
(defn booking-or-free [today-iso daydata ratom] ""
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(cond
(and my-booking is-cancellable) [calendar-cell-booked-for-me ratom]
(and my-booking (not is-cancellable)) [booking-details booking]
(and booking (not (= (:user_id booking) (:user_public_id @ratom)))) [booking-details booking]
(and (nil? booking) (not day-is-in-future)) u/blank-element
(has-required-bookings?) [day-details-free-but-not-bookable]
:else [day-details-bookable])))
(defn cell-click-handler [daydata today-iso]
(let [booking (:booking daydata)
day (:day daydata)
isoday (:isoformat day)
day-is-in-future (is-in-future? isoday today-iso)
my-booking (my-booking-for-day day)
is-cancellable (:is-cancellable my-booking)]
(when day-is-in-future
(cond
is-cancellable (remove-date-selection isoday)
(and (not (has-required-bookings?))
(or (nil? booking)
(= (:user_id booking) (:user_public_id @app-state)))) (add-date-selection isoday)))))
(defn render-booking-calendar [ratom]
(let [bookings (:booked_dates @ratom)
first-date (:first_date @ratom)
last-date (:last_date @ratom)]
[u/render-calendar ratom first-date last-date bookings booking-or-free cell-click-handler]))
(defn footer []
[:div.footer
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/"} "Merenkävijät ry"]]
[:div.footer_element
[:a.footer_link {:href "http://www.merenkavijat.fi/tietosuojaseloste.html"} "Tietosuojaseloste"]]
[:div.footer_element
[:a.footer_link {:href "https://www.flaticon.com/authors/spovv"} "PI:NAME:<NAME>END_PI"]]])
(defn logout-link []
[:div.logout_header
[:div.push_right]
[:div.logout_link
[:div.link_like {:on-click #(logout)}
"Kirjaudu ulos"]]])
(defn page [ratom]
(if (t/get-user-token ratom)
[:div
[logout-link]
[:h1 "Merenkävijät ry"]
[:h2 "Särkän vartiovuorojen varaukset"]
[instructions]
[contact_entry ratom]
[selection_area ratom]
[selection_button_area ratom]
[u/success_status_area ratom]
[u/error_status_area ratom]
[render-booking-calendar ratom]
[footer]]
[:div
[login/login-form-for-default-user successful-login]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
(defn dev-setup []
(when ^boolean js/goog.DEBUG
(enable-console-print!)
(println "dev mode")
))
(defn reload []
(let [location-url (url (-> js/window .-location .-href))
user (get (:query location-url) "user")]
(when user
(set-user-private-id user)))
(load-bookings app-state)
(reagent/render [page app-state]
(.getElementById js/document "app")))
(defn ^:export main []
(dev-setup)
(t/set-user-token-from-cookie app-state)
(reload))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-02-1",
"end": 88,
"score": 0.5292940735816956,
"start": 87,
"tag": "EMAIL",
"value": "w"
}
] |
src/main/clojure/zana/data/enum.clj
|
wahpenayo/zana
| 2 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:date "2018-02-12"
:doc "Syntatic sugar for categorical 'enum' type definition.
Note: one per namespace; some names (eg 'singleton') are reserved.
Best practice is one enum and a small number of related functions
in the namespace." }
zana.data.enum
(:require [clojure.string :as s]
[zana.commons.core :as cc]))
;;------------------------------------------------------------------------------
;; A marker interface
;; TODO: defprotocol instead?
;; TODO: values method, etc?
;; conflict with java.lang.Enum
(definterface Enumb
(readResolve []))
(defn ^:no-doc enum? [x]
(or (instance? zana.data.enum.Enumb x)
(cc/descendant? Enumb x)))
;;------------------------------------------------------------------------------
;; camelCase to lisp-case
(defn- skewer ^String [s] (s/lower-case (s/join "-" (s/split s #"(?=[A-Z])"))))
(defn- safe ^String [^String s]
(s/replace (str s) #"[^A-Za-z0-9\_\+\-\*\!\?]{1}" ""))
(defn- safe-keyword ^clojure.lang.Keyword [s]
(if (instance? clojure.lang.Keyword s) s (keyword (safe s))))
(defn- namespace-symbol [ename]
(symbol (str (namespace-munge *ns*) "." ename)))
(defn- accessor-name [ename] (symbol (str "." ename)))
(defn- access [ename field arg]
`(~(accessor-name field) ~(with-meta arg {:tag ename})))
(defn- constructor [ename] (symbol (str ename ".")))
;;------------------------------------------------------------------------------
;; TODO: binary IO
;; TODO: JSON IO
;; TODO: tsv parsing, with and without header
;; TODO: faster if values are Keywords rather than Strings?
(defmacro ^:no-doc ordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
rank (gensym "rank")
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
writer (with-meta (gensym "w") {:tag 'java.io.Writer})
this-str (with-meta `(str ~this) {:tag 'String})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~(with-meta rank {:tag 'int}) ~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this]
(unchecked-add-int
(hash ~label)
(unchecked-multiply-int
(int 31)
~rank)))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(== ~rank ~(access ename rank that))
(= ~label ~(access ename label that)))))
clojure.lang.Named
(getName [~this] (name ~label))
Comparable
(compareTo [~this ~that] (- ~rank ~(access ename rank that))))
(def ~singletons
(into
{}
(map-indexed
(fn [~rank ~label] [~label (~(constructor cname) ~rank ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v))
;; Don't show the enum name in default printing
(defmethod clojure.core/print-method ~cname [~this ~writer]
(.write ~writer ~this-str)))))
;;------------------------------------------------------------------------------
(defmacro ^:no-doc unordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this] (hash ~label))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(= ~label ~(access ename label that)))))
clojure.lang.Named (getName [~this] (name ~label)))
(refer-clojure :exclude [~'get])
(def ~singletons
(into {} (map (fn [~label] [~label (~(constructor cname) ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v)))))
;;------------------------------------------------------------------------------
|
7142
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL>ahpenayo at gmail dot com"
:date "2018-02-12"
:doc "Syntatic sugar for categorical 'enum' type definition.
Note: one per namespace; some names (eg 'singleton') are reserved.
Best practice is one enum and a small number of related functions
in the namespace." }
zana.data.enum
(:require [clojure.string :as s]
[zana.commons.core :as cc]))
;;------------------------------------------------------------------------------
;; A marker interface
;; TODO: defprotocol instead?
;; TODO: values method, etc?
;; conflict with java.lang.Enum
(definterface Enumb
(readResolve []))
(defn ^:no-doc enum? [x]
(or (instance? zana.data.enum.Enumb x)
(cc/descendant? Enumb x)))
;;------------------------------------------------------------------------------
;; camelCase to lisp-case
(defn- skewer ^String [s] (s/lower-case (s/join "-" (s/split s #"(?=[A-Z])"))))
(defn- safe ^String [^String s]
(s/replace (str s) #"[^A-Za-z0-9\_\+\-\*\!\?]{1}" ""))
(defn- safe-keyword ^clojure.lang.Keyword [s]
(if (instance? clojure.lang.Keyword s) s (keyword (safe s))))
(defn- namespace-symbol [ename]
(symbol (str (namespace-munge *ns*) "." ename)))
(defn- accessor-name [ename] (symbol (str "." ename)))
(defn- access [ename field arg]
`(~(accessor-name field) ~(with-meta arg {:tag ename})))
(defn- constructor [ename] (symbol (str ename ".")))
;;------------------------------------------------------------------------------
;; TODO: binary IO
;; TODO: JSON IO
;; TODO: tsv parsing, with and without header
;; TODO: faster if values are Keywords rather than Strings?
(defmacro ^:no-doc ordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
rank (gensym "rank")
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
writer (with-meta (gensym "w") {:tag 'java.io.Writer})
this-str (with-meta `(str ~this) {:tag 'String})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~(with-meta rank {:tag 'int}) ~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this]
(unchecked-add-int
(hash ~label)
(unchecked-multiply-int
(int 31)
~rank)))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(== ~rank ~(access ename rank that))
(= ~label ~(access ename label that)))))
clojure.lang.Named
(getName [~this] (name ~label))
Comparable
(compareTo [~this ~that] (- ~rank ~(access ename rank that))))
(def ~singletons
(into
{}
(map-indexed
(fn [~rank ~label] [~label (~(constructor cname) ~rank ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v))
;; Don't show the enum name in default printing
(defmethod clojure.core/print-method ~cname [~this ~writer]
(.write ~writer ~this-str)))))
;;------------------------------------------------------------------------------
(defmacro ^:no-doc unordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this] (hash ~label))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(= ~label ~(access ename label that)))))
clojure.lang.Named (getName [~this] (name ~label)))
(refer-clojure :exclude [~'get])
(def ~singletons
(into {} (map (fn [~label] [~label (~(constructor cname) ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v)))))
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PIahpenayo at gmail dot com"
:date "2018-02-12"
:doc "Syntatic sugar for categorical 'enum' type definition.
Note: one per namespace; some names (eg 'singleton') are reserved.
Best practice is one enum and a small number of related functions
in the namespace." }
zana.data.enum
(:require [clojure.string :as s]
[zana.commons.core :as cc]))
;;------------------------------------------------------------------------------
;; A marker interface
;; TODO: defprotocol instead?
;; TODO: values method, etc?
;; conflict with java.lang.Enum
(definterface Enumb
(readResolve []))
(defn ^:no-doc enum? [x]
(or (instance? zana.data.enum.Enumb x)
(cc/descendant? Enumb x)))
;;------------------------------------------------------------------------------
;; camelCase to lisp-case
(defn- skewer ^String [s] (s/lower-case (s/join "-" (s/split s #"(?=[A-Z])"))))
(defn- safe ^String [^String s]
(s/replace (str s) #"[^A-Za-z0-9\_\+\-\*\!\?]{1}" ""))
(defn- safe-keyword ^clojure.lang.Keyword [s]
(if (instance? clojure.lang.Keyword s) s (keyword (safe s))))
(defn- namespace-symbol [ename]
(symbol (str (namespace-munge *ns*) "." ename)))
(defn- accessor-name [ename] (symbol (str "." ename)))
(defn- access [ename field arg]
`(~(accessor-name field) ~(with-meta arg {:tag ename})))
(defn- constructor [ename] (symbol (str ename ".")))
;;------------------------------------------------------------------------------
;; TODO: binary IO
;; TODO: JSON IO
;; TODO: tsv parsing, with and without header
;; TODO: faster if values are Keywords rather than Strings?
(defmacro ^:no-doc ordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
rank (gensym "rank")
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
writer (with-meta (gensym "w") {:tag 'java.io.Writer})
this-str (with-meta `(str ~this) {:tag 'String})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~(with-meta rank {:tag 'int}) ~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this]
(unchecked-add-int
(hash ~label)
(unchecked-multiply-int
(int 31)
~rank)))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(== ~rank ~(access ename rank that))
(= ~label ~(access ename label that)))))
clojure.lang.Named
(getName [~this] (name ~label))
Comparable
(compareTo [~this ~that] (- ~rank ~(access ename rank that))))
(def ~singletons
(into
{}
(map-indexed
(fn [~rank ~label] [~label (~(constructor cname) ~rank ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v))
;; Don't show the enum name in default printing
(defmethod clojure.core/print-method ~cname [~this ~writer]
(.write ~writer ~this-str)))))
;;------------------------------------------------------------------------------
(defmacro ^:no-doc unordered [ename [& values]]
(let [cname (namespace-symbol ename)
label (with-meta (gensym "label") {:tag String})
this (gensym "this")
that (gensym "that")
hinted-that (with-meta that {:tag cname})
singletons (symbol "singletons")
lookup (symbol "singleton")
k (gensym "k")
v (gensym "v")]
`(let []
(declare ~lookup)
(deftype ~ename [~label]
Enumb
(readResolve [~this] (~lookup ~label))
java.io.Serializable
Object
(toString [~this] (name ~label))
(hashCode [~this] (hash ~label))
(equals [~this ~that]
(or (identical? ~this ~that)
(and (instance? ~ename ~that)
(= ~label ~(access ename label that)))))
clojure.lang.Named (getName [~this] (name ~label)))
(refer-clojure :exclude [~'get])
(def ~singletons
(into {} (map (fn [~label] [~label (~(constructor cname) ~label)])
[~@values])))
(defn ~lookup [~k]
(let [~v (~singletons ~k)]
(assert ~v (str ~(str "no " ename " for ") ~k))
~v)))))
;;------------------------------------------------------------------------------
|
[
{
"context": ";;; window regex pattern.\n\"Touhou Hisoutensoku ver\"\n\n;;; new config section\n[:end ; new A ke",
"end": 46,
"score": 0.8485988974571228,
"start": 27,
"tag": "NAME",
"value": "Touhou Hisoutensoku"
},
{
"context": " ; heavy artillery\n (first-match\n [key-7] fns-421b [key-8] fns-22b [key-9] fns-623b\n [key-4] fns-4",
"end": 946,
"score": 0.8597782850265503,
"start": 940,
"tag": "KEY",
"value": "ns-421"
},
{
"context": "lery\n (first-match\n [key-7] fns-421b [key-8] fns-22b [key-9] fns-623b\n [key-4] fns-421c [key-d] fns-",
"end": 962,
"score": 0.6616536378860474,
"start": 960,
"tag": "KEY",
"value": "22"
},
{
"context": "ch\n [key-7] fns-421b [key-8] fns-22b [key-9] fns-623b\n [key-4] fns-421c [key-d] fns-22b [key-6] fns-6",
"end": 979,
"score": 0.6867720484733582,
"start": 976,
"tag": "KEY",
"value": "623"
},
{
"context": "-421b [key-8] fns-22b [key-9] fns-623b\n [key-4] fns-421c [key-d] fns-22b [key-6] fns-623c\n [key-1] fns-4",
"end": 998,
"score": 0.8838950991630554,
"start": 992,
"tag": "KEY",
"value": "ns-421"
},
{
"context": "-22b [key-9] fns-623b\n [key-4] fns-421c [key-d] fns-22b [key-6] fns-623c\n [key-1] fns-421b [key-2] fns-",
"end": 1014,
"score": 0.748602569103241,
"start": 1009,
"tag": "KEY",
"value": "ns-22"
},
{
"context": "-623b\n [key-4] fns-421c [key-d] fns-22b [key-6] fns-623c\n [key-1] fns-421b [key-2] fns-22c [key-3] fns-6",
"end": 1031,
"score": 0.7122417092323303,
"start": 1025,
"tag": "KEY",
"value": "ns-623"
},
{
"context": "-421c [key-d] fns-22b [key-6] fns-623c\n [key-1] fns-421b [key-2] fns-22c [key-3] fns-623b\n [] fns-22b)\n ",
"end": 1050,
"score": 0.7893996238708496,
"start": 1044,
"tag": "KEY",
"value": "ns-421"
},
{
"context": "-22b [key-6] fns-623c\n [key-1] fns-421b [key-2] fns-22c [key-3] fns-623b\n [] fns-22b)\n [key-c key-a]\n (",
"end": 1066,
"score": 0.6494410037994385,
"start": 1061,
"tag": "KEY",
"value": "ns-22"
},
{
"context": "3c\n [key-1] fns-421b [key-2] fns-22c [key-3] fns-623b\n [] fns-22b)\n [key-c key-a]\n (first-match\n [ke",
"end": 1083,
"score": 0.6811214089393616,
"start": 1080,
"tag": "KEY",
"value": "623"
},
{
"context": "y-old-c])))\n [key-b key-a]\n (first-match\n [key-1] fns-421b\n [key-3] fns-623b\n [] (fns :key-hold #(press-re",
"end": 1266,
"score": 0.8036922216415405,
"start": 1258,
"tag": "KEY",
"value": "fns-421b"
},
{
"context": " key-a]\n (first-match\n [key-1] fns-421b\n [key-3] fns-623b\n [] (fns :key-hold #(press-release 2 [key-old-b",
"end": 1284,
"score": 0.6759485602378845,
"start": 1277,
"tag": "KEY",
"value": "fns-623"
},
{
"context": "me key as for B bullets\n (first-match\n ;; [key-7] fns-421c [key-9] fns-623c\n [key-1] fns",
"end": 1435,
"score": 0.8892478942871094,
"start": 1427,
"tag": "KEY",
"value": "fns-421c"
},
{
"context": "h\n ;; [key-7] fns-421c [key-9] fns-623c\n [key-1] fns-214b [key-3] fns",
"end": 1471,
"score": 0.8341005444526672,
"start": 1463,
"tag": "KEY",
"value": "fns-623c"
},
{
"context": "421c [key-9] fns-623c\n [key-1] fns-214b [key-3] fns-236b)\n [key-c] ",
"end": 1490,
"score": 0.9007129073143005,
"start": 1482,
"tag": "KEY",
"value": "fns-214b"
},
{
"context": "623c\n [key-1] fns-214b [key-3] fns-236b)\n [key-c] ; same key as f",
"end": 1526,
"score": 0.7989825010299683,
"start": 1518,
"tag": "KEY",
"value": "fns-236b"
},
{
"context": "me key as for C bullets\n (first-match\n ;; [key-7] fns-421b [key-9] fns-623b\n [key-1] fns",
"end": 1624,
"score": 0.9650010466575623,
"start": 1616,
"tag": "KEY",
"value": "fns-421b"
},
{
"context": "h\n ;; [key-7] fns-421b [key-9] fns-623b\n [key-1] fns-214c [key-3] fns",
"end": 1660,
"score": 0.9252429008483887,
"start": 1652,
"tag": "KEY",
"value": "fns-623b"
},
{
"context": "421b [key-9] fns-623b\n [key-1] fns-214c [key-3] fns-236c)\n []\n (all-ma",
"end": 1679,
"score": 0.9651699662208557,
"start": 1671,
"tag": "KEY",
"value": "fns-214c"
},
{
"context": "623b\n [key-1] fns-214c [key-3] fns-236c)\n []\n (all-matches\n []\n (binding [*reset* false",
"end": 1715,
"score": 0.846045196056366,
"start": 1707,
"tag": "KEY",
"value": "fns-236c"
}
] |
target/clj-hisoutensoku-config.clj
|
NeedMoreDesu/clj-hisoutensoku
| 1 |
;;; window regex pattern.
"Touhou Hisoutensoku ver"
;;; new config section
[:end ; new A key
:+ ; new B key
:return ; new C key
:numpad5 ; new D key
:numpad1
:numpad2
:numpad3
:numpad4
;; there is no numpad5 direction
:numpad6
:numpad7
:numpad8
:numpad9
:home ; power-system key
:* ; card choose
:- ; card use
]
;;; old config section
;; must match your character config in soku
;; beware, arrow keys don't work. Blame java.awt.robot class for that
[:z ; old A key
:x ; old B key
:c ; old C key
:v ; old D key
:b ; old card choose
:n ; old card use
:s ; old 2 key
:d ; old 6 key
:w ; old 8 key
:a ; old 4 key
]
;;; key-replacement section
(first-match
[key-1 key-6] ;; 1+6 == 66
fns-66
[key-9 key-4] ;; 3+4 == 66
fns-66
[key-3 key-4] ;; 3+4 == 44
fns-44
[key-7 key-6] ;; 7+6 == 44
fns-44
[key-power] ; heavy artillery
(first-match
[key-7] fns-421b [key-8] fns-22b [key-9] fns-623b
[key-4] fns-421c [key-d] fns-22b [key-6] fns-623c
[key-1] fns-421b [key-2] fns-22c [key-3] fns-623b
[] fns-22b)
[key-c key-a]
(first-match
[key-1] fns-421c
[key-3] fns-623c
[] (fns :key-hold #(press-release 2 [key-old-c])))
[key-b key-a]
(first-match
[key-1] fns-421b
[key-3] fns-623b
[] (fns :key-hold #(press-release 2 [key-old-b])))
[key-b] ; same key as for B bullets
(first-match
;; [key-7] fns-421c [key-9] fns-623c
[key-1] fns-214b [key-3] fns-236b)
[key-c] ; same key as for C bullets
(first-match
;; [key-7] fns-421b [key-9] fns-623b
[key-1] fns-214c [key-3] fns-236c)
[]
(all-matches
[]
(binding [*reset* false] ; reset crashes blocks
(all-matches ; Uses guarded version of key-sequence.
;; [key-old-2 [key-2 key-3]] means s key won't be
;; keyuped while either numpad2 or numpad3 is pressed
;; Also, [key-old-2 [[[key-2] [key-3]] key-4]] means
;; that even if key-2 is down, if key-3 is down, we
;; will do keyup
[key-1] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-2] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]])
[key-3] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-4] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-6] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-7] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-8] (key-sequence [[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-9] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-d] (key-sequence [key-old-d])))
[]
(first-match
[key-a] (tk-cancel-tree key-old-a)
[key-b] (tk-cancel-tree key-old-b)
[key-c] (tk-cancel-tree key-old-c)
[key-card-choose] (key-sequence [key-old-card-choose])
[key-card-use] (key-sequence [key-old-card-use])
[key-3 key-9] (triangle fn29 [key-old-2 key-old-6])
[key-2 key-9] (triangle fn29 [key-old-2])
[key-1 key-9] (triangle fn29 [key-old-2 key-old-4])
[key-3 key-8] (triangle fn28 [key-old-2 key-old-6])
[key-2 key-8] (triangle fn28 [key-old-2])
[key-1 key-8] (triangle fn28 [key-old-2 key-old-4])
[key-3 key-7] (triangle fn27 [key-old-2 key-old-6])
[key-2 key-7] (triangle fn27 [key-old-2])
[key-1 key-7] (triangle fn27 [key-old-2 key-old-4]))))
|
349
|
;;; window regex pattern.
"<NAME> ver"
;;; new config section
[:end ; new A key
:+ ; new B key
:return ; new C key
:numpad5 ; new D key
:numpad1
:numpad2
:numpad3
:numpad4
;; there is no numpad5 direction
:numpad6
:numpad7
:numpad8
:numpad9
:home ; power-system key
:* ; card choose
:- ; card use
]
;;; old config section
;; must match your character config in soku
;; beware, arrow keys don't work. Blame java.awt.robot class for that
[:z ; old A key
:x ; old B key
:c ; old C key
:v ; old D key
:b ; old card choose
:n ; old card use
:s ; old 2 key
:d ; old 6 key
:w ; old 8 key
:a ; old 4 key
]
;;; key-replacement section
(first-match
[key-1 key-6] ;; 1+6 == 66
fns-66
[key-9 key-4] ;; 3+4 == 66
fns-66
[key-3 key-4] ;; 3+4 == 44
fns-44
[key-7 key-6] ;; 7+6 == 44
fns-44
[key-power] ; heavy artillery
(first-match
[key-7] f<KEY>b [key-8] fns-<KEY>b [key-9] fns-<KEY>b
[key-4] f<KEY>c [key-d] f<KEY>b [key-6] f<KEY>c
[key-1] f<KEY>b [key-2] f<KEY>c [key-3] fns-<KEY>b
[] fns-22b)
[key-c key-a]
(first-match
[key-1] fns-421c
[key-3] fns-623c
[] (fns :key-hold #(press-release 2 [key-old-c])))
[key-b key-a]
(first-match
[key-1] <KEY>
[key-3] <KEY>b
[] (fns :key-hold #(press-release 2 [key-old-b])))
[key-b] ; same key as for B bullets
(first-match
;; [key-7] <KEY> [key-9] <KEY>
[key-1] <KEY> [key-3] <KEY>)
[key-c] ; same key as for C bullets
(first-match
;; [key-7] <KEY> [key-9] <KEY>
[key-1] <KEY> [key-3] <KEY>)
[]
(all-matches
[]
(binding [*reset* false] ; reset crashes blocks
(all-matches ; Uses guarded version of key-sequence.
;; [key-old-2 [key-2 key-3]] means s key won't be
;; keyuped while either numpad2 or numpad3 is pressed
;; Also, [key-old-2 [[[key-2] [key-3]] key-4]] means
;; that even if key-2 is down, if key-3 is down, we
;; will do keyup
[key-1] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-2] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]])
[key-3] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-4] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-6] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-7] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-8] (key-sequence [[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-9] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-d] (key-sequence [key-old-d])))
[]
(first-match
[key-a] (tk-cancel-tree key-old-a)
[key-b] (tk-cancel-tree key-old-b)
[key-c] (tk-cancel-tree key-old-c)
[key-card-choose] (key-sequence [key-old-card-choose])
[key-card-use] (key-sequence [key-old-card-use])
[key-3 key-9] (triangle fn29 [key-old-2 key-old-6])
[key-2 key-9] (triangle fn29 [key-old-2])
[key-1 key-9] (triangle fn29 [key-old-2 key-old-4])
[key-3 key-8] (triangle fn28 [key-old-2 key-old-6])
[key-2 key-8] (triangle fn28 [key-old-2])
[key-1 key-8] (triangle fn28 [key-old-2 key-old-4])
[key-3 key-7] (triangle fn27 [key-old-2 key-old-6])
[key-2 key-7] (triangle fn27 [key-old-2])
[key-1 key-7] (triangle fn27 [key-old-2 key-old-4]))))
| true |
;;; window regex pattern.
"PI:NAME:<NAME>END_PI ver"
;;; new config section
[:end ; new A key
:+ ; new B key
:return ; new C key
:numpad5 ; new D key
:numpad1
:numpad2
:numpad3
:numpad4
;; there is no numpad5 direction
:numpad6
:numpad7
:numpad8
:numpad9
:home ; power-system key
:* ; card choose
:- ; card use
]
;;; old config section
;; must match your character config in soku
;; beware, arrow keys don't work. Blame java.awt.robot class for that
[:z ; old A key
:x ; old B key
:c ; old C key
:v ; old D key
:b ; old card choose
:n ; old card use
:s ; old 2 key
:d ; old 6 key
:w ; old 8 key
:a ; old 4 key
]
;;; key-replacement section
(first-match
[key-1 key-6] ;; 1+6 == 66
fns-66
[key-9 key-4] ;; 3+4 == 66
fns-66
[key-3 key-4] ;; 3+4 == 44
fns-44
[key-7 key-6] ;; 7+6 == 44
fns-44
[key-power] ; heavy artillery
(first-match
[key-7] fPI:KEY:<KEY>END_PIb [key-8] fns-PI:KEY:<KEY>END_PIb [key-9] fns-PI:KEY:<KEY>END_PIb
[key-4] fPI:KEY:<KEY>END_PIc [key-d] fPI:KEY:<KEY>END_PIb [key-6] fPI:KEY:<KEY>END_PIc
[key-1] fPI:KEY:<KEY>END_PIb [key-2] fPI:KEY:<KEY>END_PIc [key-3] fns-PI:KEY:<KEY>END_PIb
[] fns-22b)
[key-c key-a]
(first-match
[key-1] fns-421c
[key-3] fns-623c
[] (fns :key-hold #(press-release 2 [key-old-c])))
[key-b key-a]
(first-match
[key-1] PI:KEY:<KEY>END_PI
[key-3] PI:KEY:<KEY>END_PIb
[] (fns :key-hold #(press-release 2 [key-old-b])))
[key-b] ; same key as for B bullets
(first-match
;; [key-7] PI:KEY:<KEY>END_PI [key-9] PI:KEY:<KEY>END_PI
[key-1] PI:KEY:<KEY>END_PI [key-3] PI:KEY:<KEY>END_PI)
[key-c] ; same key as for C bullets
(first-match
;; [key-7] PI:KEY:<KEY>END_PI [key-9] PI:KEY:<KEY>END_PI
[key-1] PI:KEY:<KEY>END_PI [key-3] PI:KEY:<KEY>END_PI)
[]
(all-matches
[]
(binding [*reset* false] ; reset crashes blocks
(all-matches ; Uses guarded version of key-sequence.
;; [key-old-2 [key-2 key-3]] means s key won't be
;; keyuped while either numpad2 or numpad3 is pressed
;; Also, [key-old-2 [[[key-2] [key-3]] key-4]] means
;; that even if key-2 is down, if key-3 is down, we
;; will do keyup
[key-1] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-2] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]])
[key-3] (key-sequence [[key-old-2
[[[key-1] [key-6]]
key-2
[[key-3] [key-4]]]]
[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-4] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]])
[key-6] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]])
[key-7] (key-sequence [[key-old-4
[[[key-1] [key-6]]
[[key-4] [key-9 key-3]]
[[key-7] [key-6]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-8] (key-sequence [[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-9] (key-sequence [[key-old-6
[[[key-3] [key-4]]
[[key-6] [key-7 key-1]]
[[key-9] [key-4]]]]
[key-old-8
[[[key-7] [key-6]]
key-8
[[key-9] [key-4]]]]])
[key-d] (key-sequence [key-old-d])))
[]
(first-match
[key-a] (tk-cancel-tree key-old-a)
[key-b] (tk-cancel-tree key-old-b)
[key-c] (tk-cancel-tree key-old-c)
[key-card-choose] (key-sequence [key-old-card-choose])
[key-card-use] (key-sequence [key-old-card-use])
[key-3 key-9] (triangle fn29 [key-old-2 key-old-6])
[key-2 key-9] (triangle fn29 [key-old-2])
[key-1 key-9] (triangle fn29 [key-old-2 key-old-4])
[key-3 key-8] (triangle fn28 [key-old-2 key-old-6])
[key-2 key-8] (triangle fn28 [key-old-2])
[key-1 key-8] (triangle fn28 [key-old-2 key-old-4])
[key-3 key-7] (triangle fn27 [key-old-2 key-old-6])
[key-2 key-7] (triangle fn27 [key-old-2])
[key-1 key-7] (triangle fn27 [key-old-2 key-old-4]))))
|
[
{
"context": "fault_for_currency true\n :bank_name \"Wells Fargo\"\n :last4 \"1234\"\n :country ",
"end": 3758,
"score": 0.9993299245834351,
"start": 3747,
"tag": "NAME",
"value": "Wells Fargo"
},
{
"context": "nabled true\n :legal_entity {:first_name \"Test\"\n :last_name \"User\"\n ",
"end": 4106,
"score": 0.9996750354766846,
"start": 4102,
"tag": "NAME",
"value": "Test"
},
{
"context": "t_name \"Test\"\n :last_name \"User\"\n :dob {:day 10\n ",
"end": 4148,
"score": 0.9997178912162781,
"start": 4144,
"tag": "NAME",
"value": "User"
},
{
"context": "(date/current-secs)\n :ip \"192.168.0.1\"}})\n\n(defn add-account-verifications [account]\n ",
"end": 4727,
"score": 0.9996589422225952,
"start": 4716,
"tag": "IP_ADDRESS",
"value": "192.168.0.1"
}
] |
src/eponai/server/external/stripe/stub.cljc
|
eponai/sulolive
| 181 |
(ns eponai.server.external.stripe.stub
(:require [eponai.common.format.date :as date]))
(def country-specs
{"CA" {:id "CA"
:default_currency "cad"
:supported_bank_account_currencies {"cad" ["CA"]
"usd" ["US" "CA"]}
:supported_payment_currencies ["cad" "usd"]
:verification_fields {:individual {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}
:company {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.business_name",
"legal_entity.business_tax_id",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}}}})
(defn default-bank-account [account-id]
{:id account-id
:currency "CAD"
:default_for_currency true
:bank_name "Wells Fargo"
:last4 "1234"
:country "CA"})
(defn default-account [id]
{:id id
:country "ca"
:payout_schedule {:delay_days 7
:interval "daily"}
:details_submitted true
:charges_enabled true
:payouts_enabled true
:legal_entity {:first_name "Test"
:last_name "User"
:dob {:day 10
:month 10
:year 1970}
:type "individual"
:address {:line1 "939 Homer St"
:city "Vancouver"
:postal_code "V6B 2W6"
:state "BC"}}
:external_accounts {:data [(default-bank-account id)]}
:tos_acceptance {:date (date/current-secs)
:ip "192.168.0.1"}})
(defn add-account-verifications [account]
(let [{:keys [external_accounts legal_entity tos_acceptance]} account
{:keys [first_name last_name dob address type]} legal_entity
fields-needed (cond-> []
(nil? tos_acceptance)
(conj "tos_acceptance.date" "tos_acceptance.ip")
(empty? external_accounts)
(conj "external_account")
(nil? first_name)
(conj "legal_entity.first_name")
(nil? last_name)
(conj "legal_entity.last_name")
(nil? dob)
(conj "legal_entity.dob.day" "legal_entity.dob.month" "legal_entity.dob.year")
(nil? type)
(conj "legal_entity.type")
(nil? address)
(conj "legal_entity.address.city" "legal_entity.address.line1" "legal_entity.address.postal_code" "legal_entity.address.state"))]
(assoc account :verification {:fields_needed fields-needed}
:details_submitted (some? legal_entity))))
|
84791
|
(ns eponai.server.external.stripe.stub
(:require [eponai.common.format.date :as date]))
(def country-specs
{"CA" {:id "CA"
:default_currency "cad"
:supported_bank_account_currencies {"cad" ["CA"]
"usd" ["US" "CA"]}
:supported_payment_currencies ["cad" "usd"]
:verification_fields {:individual {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}
:company {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.business_name",
"legal_entity.business_tax_id",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}}}})
(defn default-bank-account [account-id]
{:id account-id
:currency "CAD"
:default_for_currency true
:bank_name "<NAME>"
:last4 "1234"
:country "CA"})
(defn default-account [id]
{:id id
:country "ca"
:payout_schedule {:delay_days 7
:interval "daily"}
:details_submitted true
:charges_enabled true
:payouts_enabled true
:legal_entity {:first_name "<NAME>"
:last_name "<NAME>"
:dob {:day 10
:month 10
:year 1970}
:type "individual"
:address {:line1 "939 Homer St"
:city "Vancouver"
:postal_code "V6B 2W6"
:state "BC"}}
:external_accounts {:data [(default-bank-account id)]}
:tos_acceptance {:date (date/current-secs)
:ip "192.168.0.1"}})
(defn add-account-verifications [account]
(let [{:keys [external_accounts legal_entity tos_acceptance]} account
{:keys [first_name last_name dob address type]} legal_entity
fields-needed (cond-> []
(nil? tos_acceptance)
(conj "tos_acceptance.date" "tos_acceptance.ip")
(empty? external_accounts)
(conj "external_account")
(nil? first_name)
(conj "legal_entity.first_name")
(nil? last_name)
(conj "legal_entity.last_name")
(nil? dob)
(conj "legal_entity.dob.day" "legal_entity.dob.month" "legal_entity.dob.year")
(nil? type)
(conj "legal_entity.type")
(nil? address)
(conj "legal_entity.address.city" "legal_entity.address.line1" "legal_entity.address.postal_code" "legal_entity.address.state"))]
(assoc account :verification {:fields_needed fields-needed}
:details_submitted (some? legal_entity))))
| true |
(ns eponai.server.external.stripe.stub
(:require [eponai.common.format.date :as date]))
(def country-specs
{"CA" {:id "CA"
:default_currency "cad"
:supported_bank_account_currencies {"cad" ["CA"]
"usd" ["US" "CA"]}
:supported_payment_currencies ["cad" "usd"]
:verification_fields {:individual {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}
:company {:minimum #{"external_account",
"legal_entity.address.city",
"legal_entity.address.line1",
"legal_entity.address.postal_code",
"legal_entity.address.state",
"legal_entity.business_name",
"legal_entity.business_tax_id",
"legal_entity.dob.day",
"legal_entity.dob.month",
"legal_entity.dob.year",
"legal_entity.first_name",
"legal_entity.last_name",
"legal_entity.personal_id_number",
"legal_entity.type",
"tos_acceptance.date",
"tos_acceptance.ip"}
:additional #{"legal_entity.verification.document"}}}}})
(defn default-bank-account [account-id]
{:id account-id
:currency "CAD"
:default_for_currency true
:bank_name "PI:NAME:<NAME>END_PI"
:last4 "1234"
:country "CA"})
(defn default-account [id]
{:id id
:country "ca"
:payout_schedule {:delay_days 7
:interval "daily"}
:details_submitted true
:charges_enabled true
:payouts_enabled true
:legal_entity {:first_name "PI:NAME:<NAME>END_PI"
:last_name "PI:NAME:<NAME>END_PI"
:dob {:day 10
:month 10
:year 1970}
:type "individual"
:address {:line1 "939 Homer St"
:city "Vancouver"
:postal_code "V6B 2W6"
:state "BC"}}
:external_accounts {:data [(default-bank-account id)]}
:tos_acceptance {:date (date/current-secs)
:ip "192.168.0.1"}})
(defn add-account-verifications [account]
(let [{:keys [external_accounts legal_entity tos_acceptance]} account
{:keys [first_name last_name dob address type]} legal_entity
fields-needed (cond-> []
(nil? tos_acceptance)
(conj "tos_acceptance.date" "tos_acceptance.ip")
(empty? external_accounts)
(conj "external_account")
(nil? first_name)
(conj "legal_entity.first_name")
(nil? last_name)
(conj "legal_entity.last_name")
(nil? dob)
(conj "legal_entity.dob.day" "legal_entity.dob.month" "legal_entity.dob.year")
(nil? type)
(conj "legal_entity.type")
(nil? address)
(conj "legal_entity.address.city" "legal_entity.address.line1" "legal_entity.address.postal_code" "legal_entity.address.state"))]
(assoc account :verification {:fields_needed fields-needed}
:details_submitted (some? legal_entity))))
|
[
{
"context": "etions {:completions\n {:people [\"Rich Hickey\" \"Alan Turing\"]}})\n\n(defn mount-root []\n (dispat",
"end": 414,
"score": 0.9998744130134583,
"start": 403,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "etions\n {:people [\"Rich Hickey\" \"Alan Turing\"]}})\n\n(defn mount-root []\n (dispatch-sync [:init",
"end": 428,
"score": 0.9998791813850403,
"start": 417,
"tag": "NAME",
"value": "Alan Turing"
}
] |
data/train/clojure/802c2af8751846a7cf7052d85990cecea9a15a44core.cljs
|
harshp8l/deep-learning-lang-detection
| 84 |
(ns auto-mention.core
(:require [auto-mention.handlers]
[auto-mention.subscriptions]
[auto-mention.views :as views]
[reagent.core :as r]
[re-frame.core :refer [dispatch-sync
dispatch
subscribe]]))
(enable-console-print!)
(def completions {:completions
{:people ["Rich Hickey" "Alan Turing"]}})
(defn mount-root []
(dispatch-sync [:initialize completions])
(r/render [views/container] (.getElementById js/document "app")))
|
104929
|
(ns auto-mention.core
(:require [auto-mention.handlers]
[auto-mention.subscriptions]
[auto-mention.views :as views]
[reagent.core :as r]
[re-frame.core :refer [dispatch-sync
dispatch
subscribe]]))
(enable-console-print!)
(def completions {:completions
{:people ["<NAME>" "<NAME>"]}})
(defn mount-root []
(dispatch-sync [:initialize completions])
(r/render [views/container] (.getElementById js/document "app")))
| true |
(ns auto-mention.core
(:require [auto-mention.handlers]
[auto-mention.subscriptions]
[auto-mention.views :as views]
[reagent.core :as r]
[re-frame.core :refer [dispatch-sync
dispatch
subscribe]]))
(enable-console-print!)
(def completions {:completions
{:people ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}})
(defn mount-root []
(dispatch-sync [:initialize completions])
(r/render [views/container] (.getElementById js/document "app")))
|
[
{
"context": "andy list (not sequence) util fns\"\n :author \"Sam Aaron\"}\n overtone.algo.lists)\n\n(defn rotate\n \"Treat a",
"end": 76,
"score": 0.9998877644538879,
"start": 67,
"tag": "NAME",
"value": "Sam Aaron"
}
] |
src/overtone/algo/lists.clj
|
ABaldwinHunter/overtone
| 3,870 |
(ns
^{:doc "Handy list (not sequence) util fns"
:author "Sam Aaron"}
overtone.algo.lists)
(defn rotate
"Treat a list/vector as a circular data structure and rotate it by n
places:
(rotate 0 [1 2 3 4]) ;=> [1 2 3 4]
(rotate 2 [1 2 3 4]) ;=> [3 4 1 2]
(rotate -1 [1 2 3 4]) ;=> [4 1 2 3]
Note, coll should be countable."
[n coll]
(let [size (count coll)
offset (mod n size)
s (cycle coll)
s (drop offset s)]
(into [] (take size s))))
(defn fill
"Create a new vector with the specified size containing either part of
list ls, or ls repeated until size elements have been placed into result
vector.
(fill 5 [1]) ;=> [1 1 1 1 1]
(fill 6 [1 2 3] ;=> [1 2 3 1 2 3]
(fill 7 [5 6] ;=> [5 6 5 6 5 6 5]
(fill 3 [1 2 3 4] ;=> [1 2 3]
Note, coll should be non-empty and countable."
[size coll]
(assert (not (empty? coll)) "coll should not be empty")
(let [cnt (count coll )]
(if (>= cnt size)
(into [] (take size coll))
(let [rem (mod size cnt)
num (int (/ size cnt))]
(into [] (concat (apply concat (repeat num coll))
(take rem coll)))))))
|
50183
|
(ns
^{:doc "Handy list (not sequence) util fns"
:author "<NAME>"}
overtone.algo.lists)
(defn rotate
"Treat a list/vector as a circular data structure and rotate it by n
places:
(rotate 0 [1 2 3 4]) ;=> [1 2 3 4]
(rotate 2 [1 2 3 4]) ;=> [3 4 1 2]
(rotate -1 [1 2 3 4]) ;=> [4 1 2 3]
Note, coll should be countable."
[n coll]
(let [size (count coll)
offset (mod n size)
s (cycle coll)
s (drop offset s)]
(into [] (take size s))))
(defn fill
"Create a new vector with the specified size containing either part of
list ls, or ls repeated until size elements have been placed into result
vector.
(fill 5 [1]) ;=> [1 1 1 1 1]
(fill 6 [1 2 3] ;=> [1 2 3 1 2 3]
(fill 7 [5 6] ;=> [5 6 5 6 5 6 5]
(fill 3 [1 2 3 4] ;=> [1 2 3]
Note, coll should be non-empty and countable."
[size coll]
(assert (not (empty? coll)) "coll should not be empty")
(let [cnt (count coll )]
(if (>= cnt size)
(into [] (take size coll))
(let [rem (mod size cnt)
num (int (/ size cnt))]
(into [] (concat (apply concat (repeat num coll))
(take rem coll)))))))
| true |
(ns
^{:doc "Handy list (not sequence) util fns"
:author "PI:NAME:<NAME>END_PI"}
overtone.algo.lists)
(defn rotate
"Treat a list/vector as a circular data structure and rotate it by n
places:
(rotate 0 [1 2 3 4]) ;=> [1 2 3 4]
(rotate 2 [1 2 3 4]) ;=> [3 4 1 2]
(rotate -1 [1 2 3 4]) ;=> [4 1 2 3]
Note, coll should be countable."
[n coll]
(let [size (count coll)
offset (mod n size)
s (cycle coll)
s (drop offset s)]
(into [] (take size s))))
(defn fill
"Create a new vector with the specified size containing either part of
list ls, or ls repeated until size elements have been placed into result
vector.
(fill 5 [1]) ;=> [1 1 1 1 1]
(fill 6 [1 2 3] ;=> [1 2 3 1 2 3]
(fill 7 [5 6] ;=> [5 6 5 6 5 6 5]
(fill 3 [1 2 3 4] ;=> [1 2 3]
Note, coll should be non-empty and countable."
[size coll]
(assert (not (empty? coll)) "coll should not be empty")
(let [cnt (count coll )]
(if (>= cnt size)
(into [] (take size coll))
(let [rem (mod size cnt)
num (int (/ size cnt))]
(into [] (concat (apply concat (repeat num coll))
(take rem coll)))))))
|
[
{
"context": " \"it finds valid/invalid adddresses\"\n (is (= [\"[email protected]\"\n nil\n nil\n nil\n",
"end": 258,
"score": 0.9998327493667603,
"start": 242,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " nil\n nil\n nil\n \"[email protected]\"\n \"[email protected]\"\n ",
"end": 348,
"score": 0.9997371435165405,
"start": 321,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " \"[email protected]\"\n \"[email protected]\"\n nil\n \"ok_lolling-1+cool-l",
"end": 388,
"score": 0.9991647005081177,
"start": 363,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]\"\n nil\n \"[email protected]\"]\n (mapv #(re-matches validation/email-",
"end": 462,
"score": 0.9822169542312622,
"start": 419,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "es validation/email-pattern %)\n [\"[email protected]\"\n \"@example.com\"\n ",
"end": 558,
"score": 0.9997817277908325,
"start": 542,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " \"@example.com\"\n \"ok@example.\"\n \"foo\"\n \"ok.lol",
"end": 622,
"score": 0.9990863800048828,
"start": 612,
"tag": "EMAIL",
"value": "ok@example"
},
{
"context": "mple.\"\n \"foo\"\n \"[email protected]\"\n \"[email protected]\"\n ",
"end": 695,
"score": 0.9997705221176147,
"start": 668,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " \"[email protected]\"\n \"[email protected]\"\n \"ok_lolling-1+cool-label_ok@th",
"end": 741,
"score": 0.9987221956253052,
"start": 716,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "_lolling-1+cool-label_ok@then\"\n \"[email protected]\"])))))\n",
"end": 857,
"score": 0.9987136125564575,
"start": 814,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
test/utility_belt/validation_test.clj
|
nomnom-insights/nomnom.utility-belt
| 1 |
(ns utility-belt.validation-test
(:require
[clojure.test :refer [is deftest testing]]
[utility-belt.validation :as validation]))
(deftest email-validation-and-extraction
(testing "it finds valid/invalid adddresses"
(is (= ["[email protected]"
nil
nil
nil
"[email protected]"
"[email protected]"
nil
"[email protected]"]
(mapv #(re-matches validation/email-pattern %)
["[email protected]"
"@example.com"
"ok@example."
"foo"
"[email protected]"
"[email protected]"
"ok_lolling-1+cool-label_ok@then"
"[email protected]"])))))
|
124117
|
(ns utility-belt.validation-test
(:require
[clojure.test :refer [is deftest testing]]
[utility-belt.validation :as validation]))
(deftest email-validation-and-extraction
(testing "it finds valid/invalid adddresses"
(is (= ["<EMAIL>"
nil
nil
nil
"<EMAIL>"
"<EMAIL>"
nil
"<EMAIL>"]
(mapv #(re-matches validation/email-pattern %)
["<EMAIL>"
"@example.com"
"<EMAIL>."
"foo"
"<EMAIL>"
"<EMAIL>"
"ok_lolling-1+cool-label_ok@then"
"<EMAIL>"])))))
| true |
(ns utility-belt.validation-test
(:require
[clojure.test :refer [is deftest testing]]
[utility-belt.validation :as validation]))
(deftest email-validation-and-extraction
(testing "it finds valid/invalid adddresses"
(is (= ["PI:EMAIL:<EMAIL>END_PI"
nil
nil
nil
"PI:EMAIL:<EMAIL>END_PI"
"PI:EMAIL:<EMAIL>END_PI"
nil
"PI:EMAIL:<EMAIL>END_PI"]
(mapv #(re-matches validation/email-pattern %)
["PI:EMAIL:<EMAIL>END_PI"
"@example.com"
"PI:EMAIL:<EMAIL>END_PI."
"foo"
"PI:EMAIL:<EMAIL>END_PI"
"PI:EMAIL:<EMAIL>END_PI"
"ok_lolling-1+cool-label_ok@then"
"PI:EMAIL:<EMAIL>END_PI"])))))
|
[
{
"context": ";\n; Copyright 2020 AppsFlyer\n;\n; Licensed under the Apache License, Versi",
"end": 23,
"score": 0.5448635220527649,
"start": 19,
"tag": "NAME",
"value": "Apps"
},
{
"context": ";\n; Copyright 2020 AppsFlyer\n;\n; Licensed under the Apache License, Version 2.",
"end": 28,
"score": 0.7477027773857117,
"start": 23,
"tag": "USERNAME",
"value": "Flyer"
}
] |
src/test/clojure/com/appsflyer/donkey/core_test.clj
|
yaronel/donkey-1
| 274 |
;
; Copyright 2020 AppsFlyer
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
;
(ns com.appsflyer.donkey.core-test
(:require [clojure.test :refer [deftest testing is]]
[com.appsflyer.donkey.core :refer [create-donkey
create-server
create-client
destroy]]
[com.appsflyer.donkey.server :refer [start-sync stop-sync]]
[com.appsflyer.donkey.client :refer [request]]
[com.appsflyer.donkey.request :refer [submit]]
[com.appsflyer.donkey.test-helper :as helper])
(:import (com.appsflyer.donkey.core Donkey)
(java.net ConnectException)))
(deftest test-create-donkey
(testing "it should create a Donkey instance"
(is (instance? Donkey (create-donkey)))))
(deftest test-destroy-donkey
(testing "it should release all resources associated with the Donkey instance"
(let [make-client #(create-client % {:default-port helper/DEFAULT-PORT})
call-server #(-> % (request {:method :get}) submit)
donkey (create-donkey)
server (create-server donkey {:port helper/DEFAULT-PORT
:routes [{:handler (fn [_, res _] (res {:status 200 :body "hello world"}))}]})
client (make-client donkey)]
(start-sync server)
(is (= 200 (-> client call-server deref :status)))
@(destroy donkey)
;; Check that the client was closed
(is (thrown? IllegalStateException @(call-server client)))
;; Create a new client and verify that the server is unreachable
(is (= ConnectException (->
(create-donkey)
make-client
call-server
deref
ex-cause
ex-cause
type))))))
|
33061
|
;
; Copyright 2020 <NAME>Flyer
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
;
(ns com.appsflyer.donkey.core-test
(:require [clojure.test :refer [deftest testing is]]
[com.appsflyer.donkey.core :refer [create-donkey
create-server
create-client
destroy]]
[com.appsflyer.donkey.server :refer [start-sync stop-sync]]
[com.appsflyer.donkey.client :refer [request]]
[com.appsflyer.donkey.request :refer [submit]]
[com.appsflyer.donkey.test-helper :as helper])
(:import (com.appsflyer.donkey.core Donkey)
(java.net ConnectException)))
(deftest test-create-donkey
(testing "it should create a Donkey instance"
(is (instance? Donkey (create-donkey)))))
(deftest test-destroy-donkey
(testing "it should release all resources associated with the Donkey instance"
(let [make-client #(create-client % {:default-port helper/DEFAULT-PORT})
call-server #(-> % (request {:method :get}) submit)
donkey (create-donkey)
server (create-server donkey {:port helper/DEFAULT-PORT
:routes [{:handler (fn [_, res _] (res {:status 200 :body "hello world"}))}]})
client (make-client donkey)]
(start-sync server)
(is (= 200 (-> client call-server deref :status)))
@(destroy donkey)
;; Check that the client was closed
(is (thrown? IllegalStateException @(call-server client)))
;; Create a new client and verify that the server is unreachable
(is (= ConnectException (->
(create-donkey)
make-client
call-server
deref
ex-cause
ex-cause
type))))))
| true |
;
; Copyright 2020 PI:NAME:<NAME>END_PIFlyer
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
;
(ns com.appsflyer.donkey.core-test
(:require [clojure.test :refer [deftest testing is]]
[com.appsflyer.donkey.core :refer [create-donkey
create-server
create-client
destroy]]
[com.appsflyer.donkey.server :refer [start-sync stop-sync]]
[com.appsflyer.donkey.client :refer [request]]
[com.appsflyer.donkey.request :refer [submit]]
[com.appsflyer.donkey.test-helper :as helper])
(:import (com.appsflyer.donkey.core Donkey)
(java.net ConnectException)))
(deftest test-create-donkey
(testing "it should create a Donkey instance"
(is (instance? Donkey (create-donkey)))))
(deftest test-destroy-donkey
(testing "it should release all resources associated with the Donkey instance"
(let [make-client #(create-client % {:default-port helper/DEFAULT-PORT})
call-server #(-> % (request {:method :get}) submit)
donkey (create-donkey)
server (create-server donkey {:port helper/DEFAULT-PORT
:routes [{:handler (fn [_, res _] (res {:status 200 :body "hello world"}))}]})
client (make-client donkey)]
(start-sync server)
(is (= 200 (-> client call-server deref :status)))
@(destroy donkey)
;; Check that the client was closed
(is (thrown? IllegalStateException @(call-server client)))
;; Create a new client and verify that the server is unreachable
(is (= ConnectException (->
(create-donkey)
make-client
call-server
deref
ex-cause
ex-cause
type))))))
|
[
{
"context": "(def family [\n \"Homer Simpson\"\n \"Marge Simpson\"\n ",
"end": 44,
"score": 0.9997331500053406,
"start": 31,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "\n \"Homer Simpson\"\n \"Marge Simpson\"\n \"Bart Simpson\"\n \"",
"end": 76,
"score": 0.9997925162315369,
"start": 63,
"tag": "NAME",
"value": "Marge Simpson"
},
{
"context": "\n \"Marge Simpson\"\n \"Bart Simpson\"\n \"Lisa Simpson\"\n \"",
"end": 107,
"score": 0.9997683763504028,
"start": 95,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "\"\n \"Bart Simpson\"\n \"Lisa Simpson\"\n \"Maggie Simpson\"])\n\n(def abc \"ab",
"end": 138,
"score": 0.9997498989105225,
"start": 126,
"tag": "NAME",
"value": "Lisa Simpson"
},
{
"context": "\"\n \"Lisa Simpson\"\n \"Maggie Simpson\"])\n\n(def abc \"abcdefghijklmnopqrstuvxyz\")\n\n(defn ",
"end": 171,
"score": 0.9997749328613281,
"start": 157,
"tag": "NAME",
"value": "Maggie Simpson"
}
] |
barp.cljs
|
MaxBittker/barpsminson
| 0 |
(def family [
"Homer Simpson"
"Marge Simpson"
"Bart Simpson"
"Lisa Simpson"
"Maggie Simpson"])
(def abc "abcdefghijklmnopqrstuvxyz")
(defn substitute [input i n]
(str
(subs input 0 i)
n
(subs input (inc i))))
(defn mutate [input]
(let [mutated
(substitute
input
(rand-int (count input))
(rand-nth abc))]
(if (zero? (count (filter (partial = " ") mutated)))
(recur input)
mutated)))
(defn mutations [name]
(take 10 (iterate mutate name)))
(println (map mutations family))
|
93780
|
(def family [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"])
(def abc "abcdefghijklmnopqrstuvxyz")
(defn substitute [input i n]
(str
(subs input 0 i)
n
(subs input (inc i))))
(defn mutate [input]
(let [mutated
(substitute
input
(rand-int (count input))
(rand-nth abc))]
(if (zero? (count (filter (partial = " ") mutated)))
(recur input)
mutated)))
(defn mutations [name]
(take 10 (iterate mutate name)))
(println (map mutations family))
| true |
(def family [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"])
(def abc "abcdefghijklmnopqrstuvxyz")
(defn substitute [input i n]
(str
(subs input 0 i)
n
(subs input (inc i))))
(defn mutate [input]
(let [mutated
(substitute
input
(rand-int (count input))
(rand-nth abc))]
(if (zero? (count (filter (partial = " ") mutated)))
(recur input)
mutated)))
(defn mutations [name]
(take 10 (iterate mutate name)))
(println (map mutations family))
|
[
{
"context": "ntln (shuffle \n [\"Hi\", \"Hello\", \"Howdy\", \"Greetings\", \n \"Hey\", \"G'da",
"end": 116,
"score": 0.5605360865592957,
"start": 113,
"tag": "NAME",
"value": "How"
}
] |
sharing/src/sharing/sharing.clj
|
joseph-brennan/Concitive-AI
| 0 |
(ns sharing.sharing
(:gen-class))
(defn -main []
(run! println (shuffle
["Hi", "Hello", "Howdy", "Greetings",
"Hey", "G'day", "Good day", "How are you",
"What's up", "How goes it", "How do you do",
"Hi there"])))
|
15409
|
(ns sharing.sharing
(:gen-class))
(defn -main []
(run! println (shuffle
["Hi", "Hello", "<NAME>dy", "Greetings",
"Hey", "G'day", "Good day", "How are you",
"What's up", "How goes it", "How do you do",
"Hi there"])))
| true |
(ns sharing.sharing
(:gen-class))
(defn -main []
(run! println (shuffle
["Hi", "Hello", "PI:NAME:<NAME>END_PIdy", "Greetings",
"Hey", "G'day", "Good day", "How are you",
"What's up", "How goes it", "How do you do",
"Hi there"])))
|
[
{
"context": ";; Copyright (c) Zachary Tellman. All rights reserved.\n;; The use and distributi",
"end": 34,
"score": 0.9997984766960144,
"start": 19,
"tag": "NAME",
"value": "Zachary Tellman"
}
] |
data/clojure/d7d2e4ad81078a953698f5e78ed52c74_data.clj
|
maxim5/code-inspector
| 5 |
;; Copyright (c) Zachary Tellman. 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 penumbra.data)
(defprotocol Data
(acquire! [d] "Increments the reference count.")
(release! [d] "Decrements the reference count")
(destroy! [d] "Destroys and releases all related resources.")
(refcount [d] "Returns the reference count.")
(refcount! [d count] "Sets the reference count.")
(permanent? [d] "Returns whether the data is permanent.")
(permanent! [d flag] "Sets whether data is permanent.")
(unwrap [d] "Returns the the contained data.")
(overwrite! [d bounds data] [d data] "Overwrites contained data.")
(sizeof [d] "Memory, in bytes, used by data.")
(mimic [d] [d dim] "Returns an equivalent data container.")
(signature [d] "Returns a data signature, where equivalent signatures implies equivalent containers.")
(matches? [a sig] "Returns true if the signature of 'a' is compatible with sig (this is not necessarily bidirectional)")
(params [t] "The parameters used to create the data"))
(defn unwrap! [d]
(let [v (unwrap d)]
(release! d)
v))
(defmacro with-acquired [d & body]
`(do
(acquire! d)
~@body
(release! d)))
(defn available? [d]
(and (<= (refcount d) 0)
(not (permanent? d))))
;;;
(defprotocol DataCache
(max-count! [c count])
(max-size! [c size])
(locate! [c sig])
(add! [c d])
(stats [c])
(remove! [c d])
(clear! [c]))
(defn create-cache
([]
(create-cache 0 0))
([max-count max-size]
(let [max-count (ref max-count)
max-size (ref max-size)
cache (ref #{})
total-size (ref 0)
total-count (ref 0)]
(reify
DataCache
(max-count!
[_ count]
(dosync (ref-set max-count count)))
(max-size!
[_ size]
(dosync (ref-set max-size size)))
(locate!
[_ sig]
(dosync
(let [match (some #(when (and (available? %) (matches? % sig)) %) @cache)]
(when match
(refcount! match 1))
match)))
(add!
[_ data]
(dosync
(let [max-count @max-count
max-size @max-size]
(when (or
(and (pos? max-size) (>= @total-size max-size))
(and (pos? max-count) (>= @total-count max-count)))
(let [[available not-available] (partition available? @cache)]
(doseq [d available]
(destroy! d))
(ref-set cache not-available)
(alter total-size #(- % (apply + (map sizeof available))))
(alter total-count #(- % (count available)))))
(alter cache #(conj % data))
(alter total-count inc)
(alter total-size #(+ % (sizeof data))))))
(stats
[_]
{:size (/ @total-size 10e6)
:count @total-count})
(remove!
[_ data]
(dosync
(alter cache #(disj % data))
(alter total-count dec)
(alter total-size #(- % (sizeof data)))))
(clear!
[_]
(dosync
(doseq [d @cache]
(destroy! d))))))))
;;;
|
106368
|
;; Copyright (c) <NAME>. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns penumbra.data)
(defprotocol Data
(acquire! [d] "Increments the reference count.")
(release! [d] "Decrements the reference count")
(destroy! [d] "Destroys and releases all related resources.")
(refcount [d] "Returns the reference count.")
(refcount! [d count] "Sets the reference count.")
(permanent? [d] "Returns whether the data is permanent.")
(permanent! [d flag] "Sets whether data is permanent.")
(unwrap [d] "Returns the the contained data.")
(overwrite! [d bounds data] [d data] "Overwrites contained data.")
(sizeof [d] "Memory, in bytes, used by data.")
(mimic [d] [d dim] "Returns an equivalent data container.")
(signature [d] "Returns a data signature, where equivalent signatures implies equivalent containers.")
(matches? [a sig] "Returns true if the signature of 'a' is compatible with sig (this is not necessarily bidirectional)")
(params [t] "The parameters used to create the data"))
(defn unwrap! [d]
(let [v (unwrap d)]
(release! d)
v))
(defmacro with-acquired [d & body]
`(do
(acquire! d)
~@body
(release! d)))
(defn available? [d]
(and (<= (refcount d) 0)
(not (permanent? d))))
;;;
(defprotocol DataCache
(max-count! [c count])
(max-size! [c size])
(locate! [c sig])
(add! [c d])
(stats [c])
(remove! [c d])
(clear! [c]))
(defn create-cache
([]
(create-cache 0 0))
([max-count max-size]
(let [max-count (ref max-count)
max-size (ref max-size)
cache (ref #{})
total-size (ref 0)
total-count (ref 0)]
(reify
DataCache
(max-count!
[_ count]
(dosync (ref-set max-count count)))
(max-size!
[_ size]
(dosync (ref-set max-size size)))
(locate!
[_ sig]
(dosync
(let [match (some #(when (and (available? %) (matches? % sig)) %) @cache)]
(when match
(refcount! match 1))
match)))
(add!
[_ data]
(dosync
(let [max-count @max-count
max-size @max-size]
(when (or
(and (pos? max-size) (>= @total-size max-size))
(and (pos? max-count) (>= @total-count max-count)))
(let [[available not-available] (partition available? @cache)]
(doseq [d available]
(destroy! d))
(ref-set cache not-available)
(alter total-size #(- % (apply + (map sizeof available))))
(alter total-count #(- % (count available)))))
(alter cache #(conj % data))
(alter total-count inc)
(alter total-size #(+ % (sizeof data))))))
(stats
[_]
{:size (/ @total-size 10e6)
:count @total-count})
(remove!
[_ data]
(dosync
(alter cache #(disj % data))
(alter total-count dec)
(alter total-size #(- % (sizeof data)))))
(clear!
[_]
(dosync
(doseq [d @cache]
(destroy! d))))))))
;;;
| true |
;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns penumbra.data)
(defprotocol Data
(acquire! [d] "Increments the reference count.")
(release! [d] "Decrements the reference count")
(destroy! [d] "Destroys and releases all related resources.")
(refcount [d] "Returns the reference count.")
(refcount! [d count] "Sets the reference count.")
(permanent? [d] "Returns whether the data is permanent.")
(permanent! [d flag] "Sets whether data is permanent.")
(unwrap [d] "Returns the the contained data.")
(overwrite! [d bounds data] [d data] "Overwrites contained data.")
(sizeof [d] "Memory, in bytes, used by data.")
(mimic [d] [d dim] "Returns an equivalent data container.")
(signature [d] "Returns a data signature, where equivalent signatures implies equivalent containers.")
(matches? [a sig] "Returns true if the signature of 'a' is compatible with sig (this is not necessarily bidirectional)")
(params [t] "The parameters used to create the data"))
(defn unwrap! [d]
(let [v (unwrap d)]
(release! d)
v))
(defmacro with-acquired [d & body]
`(do
(acquire! d)
~@body
(release! d)))
(defn available? [d]
(and (<= (refcount d) 0)
(not (permanent? d))))
;;;
(defprotocol DataCache
(max-count! [c count])
(max-size! [c size])
(locate! [c sig])
(add! [c d])
(stats [c])
(remove! [c d])
(clear! [c]))
(defn create-cache
([]
(create-cache 0 0))
([max-count max-size]
(let [max-count (ref max-count)
max-size (ref max-size)
cache (ref #{})
total-size (ref 0)
total-count (ref 0)]
(reify
DataCache
(max-count!
[_ count]
(dosync (ref-set max-count count)))
(max-size!
[_ size]
(dosync (ref-set max-size size)))
(locate!
[_ sig]
(dosync
(let [match (some #(when (and (available? %) (matches? % sig)) %) @cache)]
(when match
(refcount! match 1))
match)))
(add!
[_ data]
(dosync
(let [max-count @max-count
max-size @max-size]
(when (or
(and (pos? max-size) (>= @total-size max-size))
(and (pos? max-count) (>= @total-count max-count)))
(let [[available not-available] (partition available? @cache)]
(doseq [d available]
(destroy! d))
(ref-set cache not-available)
(alter total-size #(- % (apply + (map sizeof available))))
(alter total-count #(- % (count available)))))
(alter cache #(conj % data))
(alter total-count inc)
(alter total-size #(+ % (sizeof data))))))
(stats
[_]
{:size (/ @total-size 10e6)
:count @total-count})
(remove!
[_ data]
(dosync
(alter cache #(disj % data))
(alter total-count dec)
(alter total-size #(- % (sizeof data)))))
(clear!
[_]
(dosync
(doseq [d @cache]
(destroy! d))))))))
;;;
|
[
{
"context": ";; Created by Iyanu Adelekan\n(ns euler.core\n (:gen-class))\n\n(defn sum-multipl",
"end": 28,
"score": 0.9998918771743774,
"start": 14,
"tag": "NAME",
"value": "Iyanu Adelekan"
}
] |
problems/problem1.clj
|
SeunAdelekan/ProjectEuler
| 1 |
;; Created by Iyanu Adelekan
(ns euler.core
(:gen-class))
(defn sum-multiples
"Finds the sum of multiples of two numeric vars
x and y that are less than var ceil."
[x y ceil]
(def multiple-sum 0)
(def current-val 0)
(while (< current-val ceil)
(do
(if
(or
(zero?
(rem current-val x))
(zero?
(rem current-val y)))
(def multiple-sum
(+ multiple-sum current-val)))
(def current-val
(inc current-val))))
(println multiple-sum))
(defn -main
[& args]
(sum-multiples 3 5 1000))
|
59590
|
;; Created by <NAME>
(ns euler.core
(:gen-class))
(defn sum-multiples
"Finds the sum of multiples of two numeric vars
x and y that are less than var ceil."
[x y ceil]
(def multiple-sum 0)
(def current-val 0)
(while (< current-val ceil)
(do
(if
(or
(zero?
(rem current-val x))
(zero?
(rem current-val y)))
(def multiple-sum
(+ multiple-sum current-val)))
(def current-val
(inc current-val))))
(println multiple-sum))
(defn -main
[& args]
(sum-multiples 3 5 1000))
| true |
;; Created by PI:NAME:<NAME>END_PI
(ns euler.core
(:gen-class))
(defn sum-multiples
"Finds the sum of multiples of two numeric vars
x and y that are less than var ceil."
[x y ceil]
(def multiple-sum 0)
(def current-val 0)
(while (< current-val ceil)
(do
(if
(or
(zero?
(rem current-val x))
(zero?
(rem current-val y)))
(def multiple-sum
(+ multiple-sum current-val)))
(def current-val
(inc current-val))))
(println multiple-sum))
(defn -main
[& args]
(sum-multiples 3 5 1000))
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.basal.str\n\n",
"end": 597,
"score": 0.9998527765274048,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] |
src/test/clojure/czlab/test/basal/str.clj
|
llnek/xlib
| 0 |
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.test.basal.str
(:require [clojure.test :as ct]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.core
:refer [ensure?? ensure-thrown??] :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/deftest test-str
(ensure?? "char-array??"
(let [z (c/char-array?? "")
a (c/char-array?? "abcde")]
(and (empty? z)
(= "e" (last a))
(= "a" (first a)))))
(ensure?? "fmt" (= "a09z" (c/fmt "%s%02d%s" "a" 9 "z")))
(ensure?? "sbf<>" (= "abc" (str (c/sbf<> "a" "b" "c"))))
(ensure?? "sbf<>" (= "a" (str (c/sbf<> "a"))))
(ensure?? "sbf-join" (= "a,a"
(-> (c/sbf-join (c/sbf<>) "," "a")
(c/sbf-join "," "a")
(str))))
(ensure?? "sbf+" (= "abc" (str (c/sbf+ (c/sbf<>) "a" "b" "c"))))
(ensure?? "nichts?" (and (c/nichts? "")
(c/nichts? nil)
(c/nichts? 4)))
(ensure?? "hgl?" (and (c/hgl? "a") (not (c/hgl? ""))))
(ensure?? "stror" (= "a" (c/stror nil "a")))
(ensure?? "stror*" (= "a" (c/stror* nil nil nil nil "a")))
(ensure?? "lcase" (= "aaa" (c/lcase "AAA")))
(ensure?? "ucase" (= "AAA" (c/ucase "aaa")))
(ensure?? "triml" (= "abc" (c/triml "123673abc" "123456789")))
(ensure?? "trimr" (= "abc" (c/trimr "abc123456789" "123456789")))
(ensure?? "includes?" (c/includes? "ab cd" \space))
(ensure?? "embeds?" (and (c/includes? "ab cd" "cd")
(not (c/includes? "ab cd" "ecd"))))
(ensure?? "has-no-case?" (c/has-no-case? "ab cd" "AB"))
(ensure?? "index-any" (and (== 5 (c/index-any "hello joe" "793 Z"))
(neg? (c/index-any "hello joe" "793"))))
(ensure?? "count-str" (and (== 3 (c/count-str "abagabrabt" "ab"))
(zero? (c/count-str "abagabrabt" "AA"))))
(ensure?? "count-char" (and (== 4 (c/count-char "abagabrabt" \a))
(zero? (c/count-char "abagabrabt" \space))))
(ensure?? "sname" (and (= "a" (c/sname :a))
(= "a" (c/sname "a"))
(= "" (c/sname nil))))
(ensure?? "nsb" (and (= "a" (c/nsb :a))
(= "a" (c/nsb "a"))
(= "" (c/nsb nil))))
(ensure?? "kw->str" (= "czlab.test.basal.str/a" (c/kw->str ::a)))
(ensure?? "x->kw" (= :tmp/abc (c/x->kw "tmp" "/" "abc")))
(ensure?? "nsn" (and (= "a" (c/nsn "a"))
(= "(null)" (c/nsn nil))))
(ensure?? "match-char?" (and (c/match-char? \d #{\a \b \d})
(not (c/match-char? \e #{\a \b \d}))))
(ensure?? "strim" (and (= "" (c/strim nil))
(= "a" (c/strim " a "))))
(ensure?? "strim-any" (and (= " ab123" (c/strim-any " ab123ab" "ab"))
(= "123" (c/strim-any " ab123ab " "ab" true))))
(ensure?? "splunk" (= ["1234" "5678" "9"]
(c/splunk "123456789" 4)))
(ensure?? "hasic-any?"
(and (c/hasic-any? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "has-any?"
(and (c/has-any? "hello good morning" ["OO" "in"])
(not (c/has-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "hasic-all?"
(and (c/hasic-all? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-all? "hello good morning" ["he" "yy"]))))
(ensure?? "has-all?"
(and (c/has-all? "hello gOOd morning" ["OO" "in"])
(not (c/has-all? "Hello good morning" ["he" "oo"]))))
(ensure?? "ewic-any?"
(and (c/ewic-any? "hello good morning" ["he" "OO" "NG"])
(not (c/ewic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "ew-any?"
(and (c/ew-any? "hello good morning" ["OO" "ing"])
(not (c/ew-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "swic-any?"
(and (c/swic-any? "hello good morning" ["OO" "HE"])
(not (c/swic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "sw-any?"
(and (c/sw-any? "hello good morning" ["OO" "hell"])
(not (c/sw-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "eqic?" (c/eqic? "AbcDE" "abcde"))
(ensure?? "eqic-any?"
(and (c/eqic-any? "hello" ["OO" "HellO"])
(not (c/eqic-any? "hello" ["xx" "yy"]))))
(ensure?? "eq-any?"
(and (c/eq-any? "hello" ["OO" "hello"])
(not (c/eq-any? "hello" ["xx" "yy"]))))
(ensure?? "wrapped?"
(and (c/wrapped? "hello" "h" "o")
(not (c/wrapped? "hello" "x" "y"))))
(ensure?? "rights" (and (= "joe" (c/rights "hello joe" 3))
(= "" (c/rights nil 3))
(= "" (c/rights "aaa" 0))
(= "hello joe" (c/rights "hello joe" 30))))
(ensure?? "lefts" (and (= "he" (c/lefts "hello joe" 2))
(= "" (c/lefts nil 3))
(= "" (c/lefts "aaa" 0))
(= "hello joe" (c/lefts "hello joe" 30))))
(ensure?? "drop-head" (and (= "lo joe" (c/drop-head "hello joe" 3))
(= "" (c/drop-head nil 3))
(= "aaa" (c/drop-head "aaa" 0))
(= "" (c/drop-head "hello joe" 30))))
(ensure?? "drop-tail" (and (= "hello " (c/drop-tail "hello joe" 3))
(= "" (c/drop-tail nil 3))
(= "aaa" (c/drop-tail "aaa" 0))
(= "" (c/drop-tail "hello joe" 30))))
(ensure?? "matches?" (c/matches? "abc55jjK8K" "[a-z0-9]+K[0-9]+K"))
(ensure?? "sreduce<>"
(= "123"
(c/sreduce<> #(c/sbf+ %1 %2) [1 2 3])))
(ensure?? "split"
(= '("abc" "K" "K")
(c/split "abc55jjK8K" "(\\d|jj)")))
(ensure?? "split-str"
(and (= ["a" "b" "c"]
(c/split-str "/a/b/c/" "/"))
(= ["/" "a" "/" "b" "/" "c" "/"]
(c/split-str "/a/b/c/" "/" true))))
(ensure?? "shuffle" (let [s "abcdefg"
z (u/shuffle s)]
(and (count s)
(count z)
(not= s z))))
(ensure?? "esc-xml" (= (c/esc-xml "<abc\"'&>")
"<abc"'&>"))
(ensure?? "test-end" (== 1 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ct/deftest
^:test-str basal-test-str
(ct/is (c/clj-test?? test-str)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
9887
|
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.test.basal.str
(:require [clojure.test :as ct]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.core
:refer [ensure?? ensure-thrown??] :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/deftest test-str
(ensure?? "char-array??"
(let [z (c/char-array?? "")
a (c/char-array?? "abcde")]
(and (empty? z)
(= "e" (last a))
(= "a" (first a)))))
(ensure?? "fmt" (= "a09z" (c/fmt "%s%02d%s" "a" 9 "z")))
(ensure?? "sbf<>" (= "abc" (str (c/sbf<> "a" "b" "c"))))
(ensure?? "sbf<>" (= "a" (str (c/sbf<> "a"))))
(ensure?? "sbf-join" (= "a,a"
(-> (c/sbf-join (c/sbf<>) "," "a")
(c/sbf-join "," "a")
(str))))
(ensure?? "sbf+" (= "abc" (str (c/sbf+ (c/sbf<>) "a" "b" "c"))))
(ensure?? "nichts?" (and (c/nichts? "")
(c/nichts? nil)
(c/nichts? 4)))
(ensure?? "hgl?" (and (c/hgl? "a") (not (c/hgl? ""))))
(ensure?? "stror" (= "a" (c/stror nil "a")))
(ensure?? "stror*" (= "a" (c/stror* nil nil nil nil "a")))
(ensure?? "lcase" (= "aaa" (c/lcase "AAA")))
(ensure?? "ucase" (= "AAA" (c/ucase "aaa")))
(ensure?? "triml" (= "abc" (c/triml "123673abc" "123456789")))
(ensure?? "trimr" (= "abc" (c/trimr "abc123456789" "123456789")))
(ensure?? "includes?" (c/includes? "ab cd" \space))
(ensure?? "embeds?" (and (c/includes? "ab cd" "cd")
(not (c/includes? "ab cd" "ecd"))))
(ensure?? "has-no-case?" (c/has-no-case? "ab cd" "AB"))
(ensure?? "index-any" (and (== 5 (c/index-any "hello joe" "793 Z"))
(neg? (c/index-any "hello joe" "793"))))
(ensure?? "count-str" (and (== 3 (c/count-str "abagabrabt" "ab"))
(zero? (c/count-str "abagabrabt" "AA"))))
(ensure?? "count-char" (and (== 4 (c/count-char "abagabrabt" \a))
(zero? (c/count-char "abagabrabt" \space))))
(ensure?? "sname" (and (= "a" (c/sname :a))
(= "a" (c/sname "a"))
(= "" (c/sname nil))))
(ensure?? "nsb" (and (= "a" (c/nsb :a))
(= "a" (c/nsb "a"))
(= "" (c/nsb nil))))
(ensure?? "kw->str" (= "czlab.test.basal.str/a" (c/kw->str ::a)))
(ensure?? "x->kw" (= :tmp/abc (c/x->kw "tmp" "/" "abc")))
(ensure?? "nsn" (and (= "a" (c/nsn "a"))
(= "(null)" (c/nsn nil))))
(ensure?? "match-char?" (and (c/match-char? \d #{\a \b \d})
(not (c/match-char? \e #{\a \b \d}))))
(ensure?? "strim" (and (= "" (c/strim nil))
(= "a" (c/strim " a "))))
(ensure?? "strim-any" (and (= " ab123" (c/strim-any " ab123ab" "ab"))
(= "123" (c/strim-any " ab123ab " "ab" true))))
(ensure?? "splunk" (= ["1234" "5678" "9"]
(c/splunk "123456789" 4)))
(ensure?? "hasic-any?"
(and (c/hasic-any? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "has-any?"
(and (c/has-any? "hello good morning" ["OO" "in"])
(not (c/has-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "hasic-all?"
(and (c/hasic-all? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-all? "hello good morning" ["he" "yy"]))))
(ensure?? "has-all?"
(and (c/has-all? "hello gOOd morning" ["OO" "in"])
(not (c/has-all? "Hello good morning" ["he" "oo"]))))
(ensure?? "ewic-any?"
(and (c/ewic-any? "hello good morning" ["he" "OO" "NG"])
(not (c/ewic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "ew-any?"
(and (c/ew-any? "hello good morning" ["OO" "ing"])
(not (c/ew-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "swic-any?"
(and (c/swic-any? "hello good morning" ["OO" "HE"])
(not (c/swic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "sw-any?"
(and (c/sw-any? "hello good morning" ["OO" "hell"])
(not (c/sw-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "eqic?" (c/eqic? "AbcDE" "abcde"))
(ensure?? "eqic-any?"
(and (c/eqic-any? "hello" ["OO" "HellO"])
(not (c/eqic-any? "hello" ["xx" "yy"]))))
(ensure?? "eq-any?"
(and (c/eq-any? "hello" ["OO" "hello"])
(not (c/eq-any? "hello" ["xx" "yy"]))))
(ensure?? "wrapped?"
(and (c/wrapped? "hello" "h" "o")
(not (c/wrapped? "hello" "x" "y"))))
(ensure?? "rights" (and (= "joe" (c/rights "hello joe" 3))
(= "" (c/rights nil 3))
(= "" (c/rights "aaa" 0))
(= "hello joe" (c/rights "hello joe" 30))))
(ensure?? "lefts" (and (= "he" (c/lefts "hello joe" 2))
(= "" (c/lefts nil 3))
(= "" (c/lefts "aaa" 0))
(= "hello joe" (c/lefts "hello joe" 30))))
(ensure?? "drop-head" (and (= "lo joe" (c/drop-head "hello joe" 3))
(= "" (c/drop-head nil 3))
(= "aaa" (c/drop-head "aaa" 0))
(= "" (c/drop-head "hello joe" 30))))
(ensure?? "drop-tail" (and (= "hello " (c/drop-tail "hello joe" 3))
(= "" (c/drop-tail nil 3))
(= "aaa" (c/drop-tail "aaa" 0))
(= "" (c/drop-tail "hello joe" 30))))
(ensure?? "matches?" (c/matches? "abc55jjK8K" "[a-z0-9]+K[0-9]+K"))
(ensure?? "sreduce<>"
(= "123"
(c/sreduce<> #(c/sbf+ %1 %2) [1 2 3])))
(ensure?? "split"
(= '("abc" "K" "K")
(c/split "abc55jjK8K" "(\\d|jj)")))
(ensure?? "split-str"
(and (= ["a" "b" "c"]
(c/split-str "/a/b/c/" "/"))
(= ["/" "a" "/" "b" "/" "c" "/"]
(c/split-str "/a/b/c/" "/" true))))
(ensure?? "shuffle" (let [s "abcdefg"
z (u/shuffle s)]
(and (count s)
(count z)
(not= s z))))
(ensure?? "esc-xml" (= (c/esc-xml "<abc\"'&>")
"<abc"'&>"))
(ensure?? "test-end" (== 1 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ct/deftest
^:test-str basal-test-str
(ct/is (c/clj-test?? test-str)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true |
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.test.basal.str
(:require [clojure.test :as ct]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.core
:refer [ensure?? ensure-thrown??] :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/deftest test-str
(ensure?? "char-array??"
(let [z (c/char-array?? "")
a (c/char-array?? "abcde")]
(and (empty? z)
(= "e" (last a))
(= "a" (first a)))))
(ensure?? "fmt" (= "a09z" (c/fmt "%s%02d%s" "a" 9 "z")))
(ensure?? "sbf<>" (= "abc" (str (c/sbf<> "a" "b" "c"))))
(ensure?? "sbf<>" (= "a" (str (c/sbf<> "a"))))
(ensure?? "sbf-join" (= "a,a"
(-> (c/sbf-join (c/sbf<>) "," "a")
(c/sbf-join "," "a")
(str))))
(ensure?? "sbf+" (= "abc" (str (c/sbf+ (c/sbf<>) "a" "b" "c"))))
(ensure?? "nichts?" (and (c/nichts? "")
(c/nichts? nil)
(c/nichts? 4)))
(ensure?? "hgl?" (and (c/hgl? "a") (not (c/hgl? ""))))
(ensure?? "stror" (= "a" (c/stror nil "a")))
(ensure?? "stror*" (= "a" (c/stror* nil nil nil nil "a")))
(ensure?? "lcase" (= "aaa" (c/lcase "AAA")))
(ensure?? "ucase" (= "AAA" (c/ucase "aaa")))
(ensure?? "triml" (= "abc" (c/triml "123673abc" "123456789")))
(ensure?? "trimr" (= "abc" (c/trimr "abc123456789" "123456789")))
(ensure?? "includes?" (c/includes? "ab cd" \space))
(ensure?? "embeds?" (and (c/includes? "ab cd" "cd")
(not (c/includes? "ab cd" "ecd"))))
(ensure?? "has-no-case?" (c/has-no-case? "ab cd" "AB"))
(ensure?? "index-any" (and (== 5 (c/index-any "hello joe" "793 Z"))
(neg? (c/index-any "hello joe" "793"))))
(ensure?? "count-str" (and (== 3 (c/count-str "abagabrabt" "ab"))
(zero? (c/count-str "abagabrabt" "AA"))))
(ensure?? "count-char" (and (== 4 (c/count-char "abagabrabt" \a))
(zero? (c/count-char "abagabrabt" \space))))
(ensure?? "sname" (and (= "a" (c/sname :a))
(= "a" (c/sname "a"))
(= "" (c/sname nil))))
(ensure?? "nsb" (and (= "a" (c/nsb :a))
(= "a" (c/nsb "a"))
(= "" (c/nsb nil))))
(ensure?? "kw->str" (= "czlab.test.basal.str/a" (c/kw->str ::a)))
(ensure?? "x->kw" (= :tmp/abc (c/x->kw "tmp" "/" "abc")))
(ensure?? "nsn" (and (= "a" (c/nsn "a"))
(= "(null)" (c/nsn nil))))
(ensure?? "match-char?" (and (c/match-char? \d #{\a \b \d})
(not (c/match-char? \e #{\a \b \d}))))
(ensure?? "strim" (and (= "" (c/strim nil))
(= "a" (c/strim " a "))))
(ensure?? "strim-any" (and (= " ab123" (c/strim-any " ab123ab" "ab"))
(= "123" (c/strim-any " ab123ab " "ab" true))))
(ensure?? "splunk" (= ["1234" "5678" "9"]
(c/splunk "123456789" 4)))
(ensure?? "hasic-any?"
(and (c/hasic-any? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "has-any?"
(and (c/has-any? "hello good morning" ["OO" "in"])
(not (c/has-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "hasic-all?"
(and (c/hasic-all? "hello good morning" ["he" "OO" "in"])
(not (c/hasic-all? "hello good morning" ["he" "yy"]))))
(ensure?? "has-all?"
(and (c/has-all? "hello gOOd morning" ["OO" "in"])
(not (c/has-all? "Hello good morning" ["he" "oo"]))))
(ensure?? "ewic-any?"
(and (c/ewic-any? "hello good morning" ["he" "OO" "NG"])
(not (c/ewic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "ew-any?"
(and (c/ew-any? "hello good morning" ["OO" "ing"])
(not (c/ew-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "swic-any?"
(and (c/swic-any? "hello good morning" ["OO" "HE"])
(not (c/swic-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "sw-any?"
(and (c/sw-any? "hello good morning" ["OO" "hell"])
(not (c/sw-any? "hello good morning" ["xx" "yy"]))))
(ensure?? "eqic?" (c/eqic? "AbcDE" "abcde"))
(ensure?? "eqic-any?"
(and (c/eqic-any? "hello" ["OO" "HellO"])
(not (c/eqic-any? "hello" ["xx" "yy"]))))
(ensure?? "eq-any?"
(and (c/eq-any? "hello" ["OO" "hello"])
(not (c/eq-any? "hello" ["xx" "yy"]))))
(ensure?? "wrapped?"
(and (c/wrapped? "hello" "h" "o")
(not (c/wrapped? "hello" "x" "y"))))
(ensure?? "rights" (and (= "joe" (c/rights "hello joe" 3))
(= "" (c/rights nil 3))
(= "" (c/rights "aaa" 0))
(= "hello joe" (c/rights "hello joe" 30))))
(ensure?? "lefts" (and (= "he" (c/lefts "hello joe" 2))
(= "" (c/lefts nil 3))
(= "" (c/lefts "aaa" 0))
(= "hello joe" (c/lefts "hello joe" 30))))
(ensure?? "drop-head" (and (= "lo joe" (c/drop-head "hello joe" 3))
(= "" (c/drop-head nil 3))
(= "aaa" (c/drop-head "aaa" 0))
(= "" (c/drop-head "hello joe" 30))))
(ensure?? "drop-tail" (and (= "hello " (c/drop-tail "hello joe" 3))
(= "" (c/drop-tail nil 3))
(= "aaa" (c/drop-tail "aaa" 0))
(= "" (c/drop-tail "hello joe" 30))))
(ensure?? "matches?" (c/matches? "abc55jjK8K" "[a-z0-9]+K[0-9]+K"))
(ensure?? "sreduce<>"
(= "123"
(c/sreduce<> #(c/sbf+ %1 %2) [1 2 3])))
(ensure?? "split"
(= '("abc" "K" "K")
(c/split "abc55jjK8K" "(\\d|jj)")))
(ensure?? "split-str"
(and (= ["a" "b" "c"]
(c/split-str "/a/b/c/" "/"))
(= ["/" "a" "/" "b" "/" "c" "/"]
(c/split-str "/a/b/c/" "/" true))))
(ensure?? "shuffle" (let [s "abcdefg"
z (u/shuffle s)]
(and (count s)
(count z)
(not= s z))))
(ensure?? "esc-xml" (= (c/esc-xml "<abc\"'&>")
"<abc"'&>"))
(ensure?? "test-end" (== 1 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ct/deftest
^:test-str basal-test-str
(ct/is (c/clj-test?? test-str)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": ";;\n;;\n;; Copyright 2014-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 33,
"score": 0.9545367956161499,
"start": 30,
"tag": "NAME",
"value": "Net"
}
] |
pigpen-avro/src/main/clojure/pigpen/avro.clj
|
ombagus/Netflix
| 327 |
;;
;;
;; Copyright 2014-2015 Netflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.avro
"*** ALPHA - Subject to change ***
Functions for reading avro data.
See: http://avro.apache.org/
Note: These are currently only supported by the local, rx, and pig platforms
" (:require [pigpen.raw :as raw]
[pigpen.avro.core :as avro-core])
(:import [org.apache.avro Schema]))
(set! *warn-on-reflection* true)
;; These namespaces need to be loaded to register multimethods. They are loaded
;; in a try/catch becasue not all of them are always available.
(def ^:private known-impls
['pigpen.local.avro
'pigpen.pig.avro])
(doseq [ns known-impls]
(try
(require ns)
(println (str "Loaded " ns))
(catch Exception e
#_(prn e))))
(defn load-avro
"*** ALPHA - Subject to change ***
Loads data from an avro file. Returns data as maps with keyword keys
corresponding to avro field names. Fields with avro type 'map' will be maps with
string keys.
Example:
(pig-avro/load-avro \"input.avro\" (slurp \"schemafile.json\"))
(pig-avro/load-avro \"input.avro\"
\"{\\\"namespace\\\": \\\"example.avro\\\",
\\\"type\\\": \\\"record\\\",
\\\"name\\\": \\\"foo\\\",
\\\"fields\\\": [{\\\"name\\\": \\\"wurdz\\\",
\\\"type\\\": \\\"string\\\"},
{\\\"name\\\": \\\"bar\\\",
\\\"type\\\": \\\"int\\\"}]}\")
Notes:
* Avro schemas are defined on the project's website: http://avro.apache.org/docs/1.7.7/spec.html#schemas
* load-avro takes the schema as a string
* Make sure a piggybank.jar (http://mvnrepository.com/artifact/org.apache.pig/piggybank/0.14.0)
compatible with your version of hadoop is on $PIG_CLASSPATH. For hadoop v2,
see http://stackoverflow.com/a/21753749. Amazon's elastic mapreduce comes
with a compatible piggybank.jar already on the classpath.
"
{:added "0.2.13"}
([location schema]
(let [^Schema parsed-schema (avro-core/parse-schema schema)
fields (map symbol (avro-core/field-names parsed-schema))]
(->>
(raw/load$ location :avro fields {:schema parsed-schema})
(raw/bind$
'[pigpen.avro.core]
'(pigpen.runtime/map->bind (comp
pigpen.avro.core/dotted-keys->nested-map
(pigpen.runtime/args->map pigpen.runtime/native->clojure)))
{:args (clojure.core/mapcat (juxt str identity) fields)
:field-type-in :native})))))
|
62359
|
;;
;;
;; Copyright 2014-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.avro
"*** ALPHA - Subject to change ***
Functions for reading avro data.
See: http://avro.apache.org/
Note: These are currently only supported by the local, rx, and pig platforms
" (:require [pigpen.raw :as raw]
[pigpen.avro.core :as avro-core])
(:import [org.apache.avro Schema]))
(set! *warn-on-reflection* true)
;; These namespaces need to be loaded to register multimethods. They are loaded
;; in a try/catch becasue not all of them are always available.
(def ^:private known-impls
['pigpen.local.avro
'pigpen.pig.avro])
(doseq [ns known-impls]
(try
(require ns)
(println (str "Loaded " ns))
(catch Exception e
#_(prn e))))
(defn load-avro
"*** ALPHA - Subject to change ***
Loads data from an avro file. Returns data as maps with keyword keys
corresponding to avro field names. Fields with avro type 'map' will be maps with
string keys.
Example:
(pig-avro/load-avro \"input.avro\" (slurp \"schemafile.json\"))
(pig-avro/load-avro \"input.avro\"
\"{\\\"namespace\\\": \\\"example.avro\\\",
\\\"type\\\": \\\"record\\\",
\\\"name\\\": \\\"foo\\\",
\\\"fields\\\": [{\\\"name\\\": \\\"wurdz\\\",
\\\"type\\\": \\\"string\\\"},
{\\\"name\\\": \\\"bar\\\",
\\\"type\\\": \\\"int\\\"}]}\")
Notes:
* Avro schemas are defined on the project's website: http://avro.apache.org/docs/1.7.7/spec.html#schemas
* load-avro takes the schema as a string
* Make sure a piggybank.jar (http://mvnrepository.com/artifact/org.apache.pig/piggybank/0.14.0)
compatible with your version of hadoop is on $PIG_CLASSPATH. For hadoop v2,
see http://stackoverflow.com/a/21753749. Amazon's elastic mapreduce comes
with a compatible piggybank.jar already on the classpath.
"
{:added "0.2.13"}
([location schema]
(let [^Schema parsed-schema (avro-core/parse-schema schema)
fields (map symbol (avro-core/field-names parsed-schema))]
(->>
(raw/load$ location :avro fields {:schema parsed-schema})
(raw/bind$
'[pigpen.avro.core]
'(pigpen.runtime/map->bind (comp
pigpen.avro.core/dotted-keys->nested-map
(pigpen.runtime/args->map pigpen.runtime/native->clojure)))
{:args (clojure.core/mapcat (juxt str identity) fields)
:field-type-in :native})))))
| true |
;;
;;
;; Copyright 2014-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.avro
"*** ALPHA - Subject to change ***
Functions for reading avro data.
See: http://avro.apache.org/
Note: These are currently only supported by the local, rx, and pig platforms
" (:require [pigpen.raw :as raw]
[pigpen.avro.core :as avro-core])
(:import [org.apache.avro Schema]))
(set! *warn-on-reflection* true)
;; These namespaces need to be loaded to register multimethods. They are loaded
;; in a try/catch becasue not all of them are always available.
(def ^:private known-impls
['pigpen.local.avro
'pigpen.pig.avro])
(doseq [ns known-impls]
(try
(require ns)
(println (str "Loaded " ns))
(catch Exception e
#_(prn e))))
(defn load-avro
"*** ALPHA - Subject to change ***
Loads data from an avro file. Returns data as maps with keyword keys
corresponding to avro field names. Fields with avro type 'map' will be maps with
string keys.
Example:
(pig-avro/load-avro \"input.avro\" (slurp \"schemafile.json\"))
(pig-avro/load-avro \"input.avro\"
\"{\\\"namespace\\\": \\\"example.avro\\\",
\\\"type\\\": \\\"record\\\",
\\\"name\\\": \\\"foo\\\",
\\\"fields\\\": [{\\\"name\\\": \\\"wurdz\\\",
\\\"type\\\": \\\"string\\\"},
{\\\"name\\\": \\\"bar\\\",
\\\"type\\\": \\\"int\\\"}]}\")
Notes:
* Avro schemas are defined on the project's website: http://avro.apache.org/docs/1.7.7/spec.html#schemas
* load-avro takes the schema as a string
* Make sure a piggybank.jar (http://mvnrepository.com/artifact/org.apache.pig/piggybank/0.14.0)
compatible with your version of hadoop is on $PIG_CLASSPATH. For hadoop v2,
see http://stackoverflow.com/a/21753749. Amazon's elastic mapreduce comes
with a compatible piggybank.jar already on the classpath.
"
{:added "0.2.13"}
([location schema]
(let [^Schema parsed-schema (avro-core/parse-schema schema)
fields (map symbol (avro-core/field-names parsed-schema))]
(->>
(raw/load$ location :avro fields {:schema parsed-schema})
(raw/bind$
'[pigpen.avro.core]
'(pigpen.runtime/map->bind (comp
pigpen.avro.core/dotted-keys->nested-map
(pigpen.runtime/args->map pigpen.runtime/native->clojure)))
{:args (clojure.core/mapcat (juxt str identity) fields)
:field-type-in :native})))))
|
[
{
"context": "----------------------------------\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;;\n;; Source: http://snowball.t",
"end": 223,
"score": 0.9998716711997986,
"start": 207,
"tag": "NAME",
"value": "PLIQUE Guillaume"
},
{
"context": "---------------\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;;\n;; Source: http://snowball.tartarus.org/alg",
"end": 238,
"score": 0.9963300824165344,
"start": 225,
"tag": "USERNAME",
"value": "Yomguithereal"
},
{
"context": "orithm for the English language\n;; designed by Julie Beth Lovins in 1968.\n;;\n;; Note: A vast majority of the alg",
"end": 435,
"score": 0.9996877908706665,
"start": 418,
"tag": "NAME",
"value": "Julie Beth Lovins"
}
] |
src/clj_fuzzy/lovins.cljc
|
sooheon/clj-fuzzy
| 0 |
;; -----------------------------------------------------------------------------
;; clj-fuzzy Lovins Stemming
;; -----------------------------------------------------------------------------
;;
;; Author: PLIQUE Guillaume (Yomguithereal)
;;
;; Source: http://snowball.tartarus.org/algorithms/lovins/stemmer.html
;;
;; Description: One of the oldest stemming algorithm for the English language
;; designed by Julie Beth Lovins in 1968.
;;
;; Note: A vast majority of the algorithm can be improved codewise.
;;
(ns clj-fuzzy.lovins
(:require [clojure.string])
(:use [clj-fuzzy.helpers :only [re-test?
batch-replace]]))
;; Endings
(def ^:private endings
'(#"alistically$" :B #"arizability$" :A #"izationally$" :B
#"antialness$" :A #"arisations$" :A #"arizations$" :A #"entialness$" :A
#"allically$" :C #"antaneous$" :A #"antiality$" :A #"arisation$" :A
#"arization$" :A #"ationally$" :B #"ativeness$" :A #"eableness$" :E
#"entations$" :A #"entiality$" :A #"entialize$" :A #"entiation$" :A
#"ionalness$" :A #"istically$" :A #"itousness$" :A #"izability$" :A
#"izational$" :A
#"ableness$" :A #"arizable$" :A #"entation$" :A #"entially$" :A
#"eousness$" :A #"ibleness$" :A #"icalness$" :A #"ionalism$" :A
#"ionality$" :A #"ionalize$" :A #"iousness$" :A #"izations$" :A
#"lessness$" :A
#"ability$" :A #"aically$" :A #"alistic$" :B #"alities$" :A
#"ariness$" :E #"aristic$" :A #"arizing$" :A #"ateness$" :A
#"atingly$" :A #"ational$" :B #"atively$" :A #"ativism$" :A
#"elihood$" :E #"encible$" :A #"entally$" :A #"entials$" :A
#"entiate$" :A #"entness$" :A #"fulness$" :A #"ibility$" :A
#"icalism$" :A #"icalist$" :A #"icality$" :A #"icalize$" :A
#"ication$" :G #"icianry$" :A #"ination$" :A #"ingness$" :A
#"ionally$" :A #"isation$" :A #"ishness$" :A #"istical$" :A
#"iteness$" :A #"iveness$" :A #"ivistic$" :A #"ivities$" :A
#"ization$" :F #"izement$" :A #"oidally$" :A #"ousness$" :A
#"aceous$" :A #"acious$" :B #"action$" :G #"alness$" :A
#"ancial$" :A #"ancies$" :A #"ancing$" :B #"ariser$" :A
#"arized$" :A #"arizer$" :A #"atable$" :A #"ations$" :B
#"atives$" :A #"eature$" :Z #"efully$" :A #"encies$" :A
#"encing$" :A #"ential$" :A #"enting$" :C #"entist$" :A
#"eously$" :A #"ialist$" :A #"iality$" :A #"ialize$" :A
#"ically$" :A #"icance$" :A #"icians$" :A #"icists$" :A
#"ifully$" :A #"ionals$" :A #"ionate$" :D #"ioning$" :A
#"ionist$" :A #"iously$" :A #"istics$" :A #"izable$" :E
#"lessly$" :A #"nesses$" :A #"oidism$" :A
#"acies$" :A #"acity$" :A #"aging$" :B #"aical$" :A
#"alist$" :A #"alism$" :B #"ality$" :A #"alize$" :A
#"allic$" :BB #"anced$" :B #"ances$" :B #"antic$" :C
#"arial$" :A #"aries$" :A #"arily$" :A #"arity$" :B
#"arize$" :A #"aroid$" :A #"ately$" :A #"ating$" :I
#"ation$" :B #"ative$" :A #"ators$" :A #"atory$" :A
#"ature$" :E #"early$" :Y #"ehood$" :A #"eless$" :A
#"elity$" :A #"ement$" :A #"enced$" :A #"ences$" :A
#"eness$" :E #"ening$" :E #"ental$" :A #"ented$" :C
#"ently$" :A #"fully$" :A #"ially$" :A #"icant$" :A
#"ician$" :A #"icide$" :A #"icism$" :A #"icist$" :A
#"icity$" :A #"idine$" :I #"iedly$" :A #"ihood$" :A
#"inate$" :A #"iness$" :A #"ingly$" :B #"inism$" :J
#"inity$" :CC #"ional$" :A #"ioned$" :A #"ished$" :A
#"istic$" :A #"ities$" :A #"itous$" :A #"ively$" :A
#"ivity$" :A #"izers$" :F #"izing$" :F #"oidal$" :A
#"oides$" :A #"otide$" :A #"ously$" :A
#"able$" :A #"ably$" :A #"ages$" :B #"ally$" :B
#"ance$" :B #"ancy$" :B #"ants$" :B #"aric$" :A
#"arly$" :K #"ated$" :I #"ates$" :A #"atic$" :B
#"ator$" :A #"ealy$" :Y #"edly$" :E #"eful$" :A
#"eity$" :A #"ence$" :A #"ency$" :A #"ened$" :E
#"enly$" :E #"eous$" :A #"hood$" :A #"ials$" :A
#"ians$" :A #"ible$" :A #"ibly$" :A #"ical$" :A
#"ides$" :L #"iers$" :A #"iful$" :A #"ines$" :M
#"ings$" :N #"ions$" :B #"ious$" :A #"isms$" :B
#"ists$" :A #"itic$" :H #"ized$" :F #"izer$" :F
#"less$" :A #"lily$" :A #"ness$" :A #"ogen$" :A
#"ward$" :A #"wise$" :A #"ying$" :B #"yish$" :A
#"acy$" :A #"age$" :B #"aic$" :A #"als$" :BB
#"ant$" :B #"ars$" :O #"ary$" :F #"ata$" :A
#"ate$" :A #"eal$" :Y #"ear$" :Y #"ely$" :E
#"ene$" :E #"ent$" :C #"ery$" :E #"ese$" :A
#"ful$" :A #"ial$" :A #"ian$" :A #"ics$" :A
#"ide$" :L #"ied$" :A #"ier$" :A #"ies$" :P
#"ily$" :A #"ine$" :M #"ing$" :N #"ion$" :Q
#"ish$" :C #"ism$" :B #"ist$" :A #"ite$" :AA
#"ity$" :A #"ium$" :A #"ive$" :A #"ize$" :F
#"oid$" :A #"one$" :R #"ous$" :A
#"ae$" :A #"al$" :BB #"ar$" :X #"as$" :B
#"ed$" :E #"en$" :F #"es$" :E #"ia$" :A
#"ic$" :A #"is$" :A #"ly$" :B #"on$" :S
#"or$" :T #"um$" :U #"us$" :V #"yl$" :R
#"s'" :A #"'s$" :A
#"a$" :A #"e$" :A #"i$" :A #"o$" :A
#"s$" :W #"y$" :B))
;; Conditions
(def ^:private conditions
{:A (fn [stem] true)
:B (fn [stem] (> (count stem) 2))
:C (fn [stem] (> (count stem) 3))
:D (fn [stem] (> (count stem) 4))
:E (fn [stem] (not (re-test? #"e$" stem)))
:F (fn [stem] (and ((conditions :B) stem) (conditions :E stem)))
:G (fn [stem] (and ((conditions :B) stem) (re-test? #"f$" stem)))
:H (fn [stem] (re-test? #"(t|ll)$" stem))
:I (fn [stem] (not (re-test? #"[oe]$" stem)))
:J (fn [stem] (not (re-test? #"[ae]$" stem)))
:K (fn [stem] (and ((conditions :B) stem) (re-test? #"(l|i|(u\we))$" stem)))
:L (fn [stem] (not (re-test? #"(u|x|([^o]s))$" stem)))
:M (fn [stem] (not (re-test? #"[acem]$" stem)))
:N (fn [stem] (if (re-test? #"s\w{2}$" stem) ((conditions :C) stem) ((conditions :B) stem)))
:O (fn [stem] (re-test? #"[li]$" stem))
:P (fn [stem] (not (re-test? #"c$" stem)))
:Q (fn [stem] (and ((conditions :B) stem) (not (re-test? #"[ln]$" stem))))
:R (fn [stem] (re-test? #"[nr]$" stem))
:S (fn [stem] (re-test? #"(dr|[^t]t)$" stem))
:T (fn [stem] (re-test? #"(s|[^o]t)$" stem))
:U (fn [stem] (re-test? #"[lmnr]$" stem))
:V (fn [stem] (re-test? #"c$" stem))
:W (fn [stem] (not (re-test? #"[su]$" stem)))
:X (fn [stem] (re-test? #"(l|i|u\we)$" stem))
:Y (fn [stem] (re-test? #"in$" stem))
:Z (fn [stem] (not (re-test? #"f$" stem)))
:AA (fn [stem] (re-test? #"([dflt]|ph|th|er|or|es)$" stem))
:BB (fn [stem] (and ((conditions :B) stem) (not (re-test? #"(met|ryst)" stem))))
:CC (fn [stem] (re-test? #"l$" stem))})
;; Transformations
(defn- dedouble
"Drop double occurences of certain letters in the given [stem]."
[stem]
(clojure.string/replace stem #"([bdglmnprst])\1{1,}$" "$1"))
(def ^:private transformations
'(#"iev$" "ief"
#"uct$" "uc"
#"umpt$" "um"
#"rpt$" "rb"
#"urs$" "ur"
#"istr$" "ister"
#"metr$" "meter"
#"olv$" "olut"
#"([^aoi])ul$" "$1l"
#"bex$" "bic"
#"dex$" "dic"
#"pex$" "pic"
#"tex$" "tic"
#"ax$" "ac"
#"ex$" "ec"
#"ix$" "ic"
#"lux$" "luc"
#"uad$" "uas"
#"vad$" "vas"
#"cid$" "cis"
#"lid$" "lis"
#"erid$" "eris"
#"pand$" "pans"
#"([^s])end$" "$1ens"
#"ond$" "ons"
#"lud$" "lus"
#"rud$" "rus"
#"([^pt])her$" "$1hes"
#"mit$" "mis"
#"([^m])ent$" "$1ens"
#"ert$" "ers"
#"([^n])et$" "$1es"
#"(yt|yz)$" "ys"))
;; Helpers
(defn- clean
"Clean a [word] of characters unsupported by the stemmer"
[word]
(clojure.string/replace word #"[^a-zA-Z']" ""))
;; Main functions
(defn- prep-word
"Prepare a [word] for its passage through the stemmer."
[word]
(clean (clojure.string/lower-case word)))
(defn- test-suffix-fn
[word]
(fn [ending]
(let [match (first ending)
condition (second ending)
stem (clojure.string/replace word match "")]
(when (and (< (count stem) (count word))
(> (count stem) 1)
((conditions condition) stem))
stem))))
(defn- drop-suffix
"Drop the longest suffix we can find in the given [word]."
[word]
(if-let [stem (some (test-suffix-fn word) (partition 2 endings))]
stem
word))
(defn apply-transformations
"Apply the algorithm's transformations to the given [stem]."
[stem]
(if-let [[match replacement] (some #(when (re-test? (first %) stem) %) (partition 2 transformations))]
(clojure.string/replace stem match replacement)
stem))
(defn stem
"Stem the given [word] according to the algorithm."
[word]
(-> (prep-word word)
(drop-suffix)
(dedouble)
(apply-transformations)))
|
26530
|
;; -----------------------------------------------------------------------------
;; clj-fuzzy Lovins Stemming
;; -----------------------------------------------------------------------------
;;
;; Author: <NAME> (Yomguithereal)
;;
;; Source: http://snowball.tartarus.org/algorithms/lovins/stemmer.html
;;
;; Description: One of the oldest stemming algorithm for the English language
;; designed by <NAME> in 1968.
;;
;; Note: A vast majority of the algorithm can be improved codewise.
;;
(ns clj-fuzzy.lovins
(:require [clojure.string])
(:use [clj-fuzzy.helpers :only [re-test?
batch-replace]]))
;; Endings
(def ^:private endings
'(#"alistically$" :B #"arizability$" :A #"izationally$" :B
#"antialness$" :A #"arisations$" :A #"arizations$" :A #"entialness$" :A
#"allically$" :C #"antaneous$" :A #"antiality$" :A #"arisation$" :A
#"arization$" :A #"ationally$" :B #"ativeness$" :A #"eableness$" :E
#"entations$" :A #"entiality$" :A #"entialize$" :A #"entiation$" :A
#"ionalness$" :A #"istically$" :A #"itousness$" :A #"izability$" :A
#"izational$" :A
#"ableness$" :A #"arizable$" :A #"entation$" :A #"entially$" :A
#"eousness$" :A #"ibleness$" :A #"icalness$" :A #"ionalism$" :A
#"ionality$" :A #"ionalize$" :A #"iousness$" :A #"izations$" :A
#"lessness$" :A
#"ability$" :A #"aically$" :A #"alistic$" :B #"alities$" :A
#"ariness$" :E #"aristic$" :A #"arizing$" :A #"ateness$" :A
#"atingly$" :A #"ational$" :B #"atively$" :A #"ativism$" :A
#"elihood$" :E #"encible$" :A #"entally$" :A #"entials$" :A
#"entiate$" :A #"entness$" :A #"fulness$" :A #"ibility$" :A
#"icalism$" :A #"icalist$" :A #"icality$" :A #"icalize$" :A
#"ication$" :G #"icianry$" :A #"ination$" :A #"ingness$" :A
#"ionally$" :A #"isation$" :A #"ishness$" :A #"istical$" :A
#"iteness$" :A #"iveness$" :A #"ivistic$" :A #"ivities$" :A
#"ization$" :F #"izement$" :A #"oidally$" :A #"ousness$" :A
#"aceous$" :A #"acious$" :B #"action$" :G #"alness$" :A
#"ancial$" :A #"ancies$" :A #"ancing$" :B #"ariser$" :A
#"arized$" :A #"arizer$" :A #"atable$" :A #"ations$" :B
#"atives$" :A #"eature$" :Z #"efully$" :A #"encies$" :A
#"encing$" :A #"ential$" :A #"enting$" :C #"entist$" :A
#"eously$" :A #"ialist$" :A #"iality$" :A #"ialize$" :A
#"ically$" :A #"icance$" :A #"icians$" :A #"icists$" :A
#"ifully$" :A #"ionals$" :A #"ionate$" :D #"ioning$" :A
#"ionist$" :A #"iously$" :A #"istics$" :A #"izable$" :E
#"lessly$" :A #"nesses$" :A #"oidism$" :A
#"acies$" :A #"acity$" :A #"aging$" :B #"aical$" :A
#"alist$" :A #"alism$" :B #"ality$" :A #"alize$" :A
#"allic$" :BB #"anced$" :B #"ances$" :B #"antic$" :C
#"arial$" :A #"aries$" :A #"arily$" :A #"arity$" :B
#"arize$" :A #"aroid$" :A #"ately$" :A #"ating$" :I
#"ation$" :B #"ative$" :A #"ators$" :A #"atory$" :A
#"ature$" :E #"early$" :Y #"ehood$" :A #"eless$" :A
#"elity$" :A #"ement$" :A #"enced$" :A #"ences$" :A
#"eness$" :E #"ening$" :E #"ental$" :A #"ented$" :C
#"ently$" :A #"fully$" :A #"ially$" :A #"icant$" :A
#"ician$" :A #"icide$" :A #"icism$" :A #"icist$" :A
#"icity$" :A #"idine$" :I #"iedly$" :A #"ihood$" :A
#"inate$" :A #"iness$" :A #"ingly$" :B #"inism$" :J
#"inity$" :CC #"ional$" :A #"ioned$" :A #"ished$" :A
#"istic$" :A #"ities$" :A #"itous$" :A #"ively$" :A
#"ivity$" :A #"izers$" :F #"izing$" :F #"oidal$" :A
#"oides$" :A #"otide$" :A #"ously$" :A
#"able$" :A #"ably$" :A #"ages$" :B #"ally$" :B
#"ance$" :B #"ancy$" :B #"ants$" :B #"aric$" :A
#"arly$" :K #"ated$" :I #"ates$" :A #"atic$" :B
#"ator$" :A #"ealy$" :Y #"edly$" :E #"eful$" :A
#"eity$" :A #"ence$" :A #"ency$" :A #"ened$" :E
#"enly$" :E #"eous$" :A #"hood$" :A #"ials$" :A
#"ians$" :A #"ible$" :A #"ibly$" :A #"ical$" :A
#"ides$" :L #"iers$" :A #"iful$" :A #"ines$" :M
#"ings$" :N #"ions$" :B #"ious$" :A #"isms$" :B
#"ists$" :A #"itic$" :H #"ized$" :F #"izer$" :F
#"less$" :A #"lily$" :A #"ness$" :A #"ogen$" :A
#"ward$" :A #"wise$" :A #"ying$" :B #"yish$" :A
#"acy$" :A #"age$" :B #"aic$" :A #"als$" :BB
#"ant$" :B #"ars$" :O #"ary$" :F #"ata$" :A
#"ate$" :A #"eal$" :Y #"ear$" :Y #"ely$" :E
#"ene$" :E #"ent$" :C #"ery$" :E #"ese$" :A
#"ful$" :A #"ial$" :A #"ian$" :A #"ics$" :A
#"ide$" :L #"ied$" :A #"ier$" :A #"ies$" :P
#"ily$" :A #"ine$" :M #"ing$" :N #"ion$" :Q
#"ish$" :C #"ism$" :B #"ist$" :A #"ite$" :AA
#"ity$" :A #"ium$" :A #"ive$" :A #"ize$" :F
#"oid$" :A #"one$" :R #"ous$" :A
#"ae$" :A #"al$" :BB #"ar$" :X #"as$" :B
#"ed$" :E #"en$" :F #"es$" :E #"ia$" :A
#"ic$" :A #"is$" :A #"ly$" :B #"on$" :S
#"or$" :T #"um$" :U #"us$" :V #"yl$" :R
#"s'" :A #"'s$" :A
#"a$" :A #"e$" :A #"i$" :A #"o$" :A
#"s$" :W #"y$" :B))
;; Conditions
(def ^:private conditions
{:A (fn [stem] true)
:B (fn [stem] (> (count stem) 2))
:C (fn [stem] (> (count stem) 3))
:D (fn [stem] (> (count stem) 4))
:E (fn [stem] (not (re-test? #"e$" stem)))
:F (fn [stem] (and ((conditions :B) stem) (conditions :E stem)))
:G (fn [stem] (and ((conditions :B) stem) (re-test? #"f$" stem)))
:H (fn [stem] (re-test? #"(t|ll)$" stem))
:I (fn [stem] (not (re-test? #"[oe]$" stem)))
:J (fn [stem] (not (re-test? #"[ae]$" stem)))
:K (fn [stem] (and ((conditions :B) stem) (re-test? #"(l|i|(u\we))$" stem)))
:L (fn [stem] (not (re-test? #"(u|x|([^o]s))$" stem)))
:M (fn [stem] (not (re-test? #"[acem]$" stem)))
:N (fn [stem] (if (re-test? #"s\w{2}$" stem) ((conditions :C) stem) ((conditions :B) stem)))
:O (fn [stem] (re-test? #"[li]$" stem))
:P (fn [stem] (not (re-test? #"c$" stem)))
:Q (fn [stem] (and ((conditions :B) stem) (not (re-test? #"[ln]$" stem))))
:R (fn [stem] (re-test? #"[nr]$" stem))
:S (fn [stem] (re-test? #"(dr|[^t]t)$" stem))
:T (fn [stem] (re-test? #"(s|[^o]t)$" stem))
:U (fn [stem] (re-test? #"[lmnr]$" stem))
:V (fn [stem] (re-test? #"c$" stem))
:W (fn [stem] (not (re-test? #"[su]$" stem)))
:X (fn [stem] (re-test? #"(l|i|u\we)$" stem))
:Y (fn [stem] (re-test? #"in$" stem))
:Z (fn [stem] (not (re-test? #"f$" stem)))
:AA (fn [stem] (re-test? #"([dflt]|ph|th|er|or|es)$" stem))
:BB (fn [stem] (and ((conditions :B) stem) (not (re-test? #"(met|ryst)" stem))))
:CC (fn [stem] (re-test? #"l$" stem))})
;; Transformations
(defn- dedouble
"Drop double occurences of certain letters in the given [stem]."
[stem]
(clojure.string/replace stem #"([bdglmnprst])\1{1,}$" "$1"))
(def ^:private transformations
'(#"iev$" "ief"
#"uct$" "uc"
#"umpt$" "um"
#"rpt$" "rb"
#"urs$" "ur"
#"istr$" "ister"
#"metr$" "meter"
#"olv$" "olut"
#"([^aoi])ul$" "$1l"
#"bex$" "bic"
#"dex$" "dic"
#"pex$" "pic"
#"tex$" "tic"
#"ax$" "ac"
#"ex$" "ec"
#"ix$" "ic"
#"lux$" "luc"
#"uad$" "uas"
#"vad$" "vas"
#"cid$" "cis"
#"lid$" "lis"
#"erid$" "eris"
#"pand$" "pans"
#"([^s])end$" "$1ens"
#"ond$" "ons"
#"lud$" "lus"
#"rud$" "rus"
#"([^pt])her$" "$1hes"
#"mit$" "mis"
#"([^m])ent$" "$1ens"
#"ert$" "ers"
#"([^n])et$" "$1es"
#"(yt|yz)$" "ys"))
;; Helpers
(defn- clean
"Clean a [word] of characters unsupported by the stemmer"
[word]
(clojure.string/replace word #"[^a-zA-Z']" ""))
;; Main functions
(defn- prep-word
"Prepare a [word] for its passage through the stemmer."
[word]
(clean (clojure.string/lower-case word)))
(defn- test-suffix-fn
[word]
(fn [ending]
(let [match (first ending)
condition (second ending)
stem (clojure.string/replace word match "")]
(when (and (< (count stem) (count word))
(> (count stem) 1)
((conditions condition) stem))
stem))))
(defn- drop-suffix
"Drop the longest suffix we can find in the given [word]."
[word]
(if-let [stem (some (test-suffix-fn word) (partition 2 endings))]
stem
word))
(defn apply-transformations
"Apply the algorithm's transformations to the given [stem]."
[stem]
(if-let [[match replacement] (some #(when (re-test? (first %) stem) %) (partition 2 transformations))]
(clojure.string/replace stem match replacement)
stem))
(defn stem
"Stem the given [word] according to the algorithm."
[word]
(-> (prep-word word)
(drop-suffix)
(dedouble)
(apply-transformations)))
| true |
;; -----------------------------------------------------------------------------
;; clj-fuzzy Lovins Stemming
;; -----------------------------------------------------------------------------
;;
;; Author: PI:NAME:<NAME>END_PI (Yomguithereal)
;;
;; Source: http://snowball.tartarus.org/algorithms/lovins/stemmer.html
;;
;; Description: One of the oldest stemming algorithm for the English language
;; designed by PI:NAME:<NAME>END_PI in 1968.
;;
;; Note: A vast majority of the algorithm can be improved codewise.
;;
(ns clj-fuzzy.lovins
(:require [clojure.string])
(:use [clj-fuzzy.helpers :only [re-test?
batch-replace]]))
;; Endings
(def ^:private endings
'(#"alistically$" :B #"arizability$" :A #"izationally$" :B
#"antialness$" :A #"arisations$" :A #"arizations$" :A #"entialness$" :A
#"allically$" :C #"antaneous$" :A #"antiality$" :A #"arisation$" :A
#"arization$" :A #"ationally$" :B #"ativeness$" :A #"eableness$" :E
#"entations$" :A #"entiality$" :A #"entialize$" :A #"entiation$" :A
#"ionalness$" :A #"istically$" :A #"itousness$" :A #"izability$" :A
#"izational$" :A
#"ableness$" :A #"arizable$" :A #"entation$" :A #"entially$" :A
#"eousness$" :A #"ibleness$" :A #"icalness$" :A #"ionalism$" :A
#"ionality$" :A #"ionalize$" :A #"iousness$" :A #"izations$" :A
#"lessness$" :A
#"ability$" :A #"aically$" :A #"alistic$" :B #"alities$" :A
#"ariness$" :E #"aristic$" :A #"arizing$" :A #"ateness$" :A
#"atingly$" :A #"ational$" :B #"atively$" :A #"ativism$" :A
#"elihood$" :E #"encible$" :A #"entally$" :A #"entials$" :A
#"entiate$" :A #"entness$" :A #"fulness$" :A #"ibility$" :A
#"icalism$" :A #"icalist$" :A #"icality$" :A #"icalize$" :A
#"ication$" :G #"icianry$" :A #"ination$" :A #"ingness$" :A
#"ionally$" :A #"isation$" :A #"ishness$" :A #"istical$" :A
#"iteness$" :A #"iveness$" :A #"ivistic$" :A #"ivities$" :A
#"ization$" :F #"izement$" :A #"oidally$" :A #"ousness$" :A
#"aceous$" :A #"acious$" :B #"action$" :G #"alness$" :A
#"ancial$" :A #"ancies$" :A #"ancing$" :B #"ariser$" :A
#"arized$" :A #"arizer$" :A #"atable$" :A #"ations$" :B
#"atives$" :A #"eature$" :Z #"efully$" :A #"encies$" :A
#"encing$" :A #"ential$" :A #"enting$" :C #"entist$" :A
#"eously$" :A #"ialist$" :A #"iality$" :A #"ialize$" :A
#"ically$" :A #"icance$" :A #"icians$" :A #"icists$" :A
#"ifully$" :A #"ionals$" :A #"ionate$" :D #"ioning$" :A
#"ionist$" :A #"iously$" :A #"istics$" :A #"izable$" :E
#"lessly$" :A #"nesses$" :A #"oidism$" :A
#"acies$" :A #"acity$" :A #"aging$" :B #"aical$" :A
#"alist$" :A #"alism$" :B #"ality$" :A #"alize$" :A
#"allic$" :BB #"anced$" :B #"ances$" :B #"antic$" :C
#"arial$" :A #"aries$" :A #"arily$" :A #"arity$" :B
#"arize$" :A #"aroid$" :A #"ately$" :A #"ating$" :I
#"ation$" :B #"ative$" :A #"ators$" :A #"atory$" :A
#"ature$" :E #"early$" :Y #"ehood$" :A #"eless$" :A
#"elity$" :A #"ement$" :A #"enced$" :A #"ences$" :A
#"eness$" :E #"ening$" :E #"ental$" :A #"ented$" :C
#"ently$" :A #"fully$" :A #"ially$" :A #"icant$" :A
#"ician$" :A #"icide$" :A #"icism$" :A #"icist$" :A
#"icity$" :A #"idine$" :I #"iedly$" :A #"ihood$" :A
#"inate$" :A #"iness$" :A #"ingly$" :B #"inism$" :J
#"inity$" :CC #"ional$" :A #"ioned$" :A #"ished$" :A
#"istic$" :A #"ities$" :A #"itous$" :A #"ively$" :A
#"ivity$" :A #"izers$" :F #"izing$" :F #"oidal$" :A
#"oides$" :A #"otide$" :A #"ously$" :A
#"able$" :A #"ably$" :A #"ages$" :B #"ally$" :B
#"ance$" :B #"ancy$" :B #"ants$" :B #"aric$" :A
#"arly$" :K #"ated$" :I #"ates$" :A #"atic$" :B
#"ator$" :A #"ealy$" :Y #"edly$" :E #"eful$" :A
#"eity$" :A #"ence$" :A #"ency$" :A #"ened$" :E
#"enly$" :E #"eous$" :A #"hood$" :A #"ials$" :A
#"ians$" :A #"ible$" :A #"ibly$" :A #"ical$" :A
#"ides$" :L #"iers$" :A #"iful$" :A #"ines$" :M
#"ings$" :N #"ions$" :B #"ious$" :A #"isms$" :B
#"ists$" :A #"itic$" :H #"ized$" :F #"izer$" :F
#"less$" :A #"lily$" :A #"ness$" :A #"ogen$" :A
#"ward$" :A #"wise$" :A #"ying$" :B #"yish$" :A
#"acy$" :A #"age$" :B #"aic$" :A #"als$" :BB
#"ant$" :B #"ars$" :O #"ary$" :F #"ata$" :A
#"ate$" :A #"eal$" :Y #"ear$" :Y #"ely$" :E
#"ene$" :E #"ent$" :C #"ery$" :E #"ese$" :A
#"ful$" :A #"ial$" :A #"ian$" :A #"ics$" :A
#"ide$" :L #"ied$" :A #"ier$" :A #"ies$" :P
#"ily$" :A #"ine$" :M #"ing$" :N #"ion$" :Q
#"ish$" :C #"ism$" :B #"ist$" :A #"ite$" :AA
#"ity$" :A #"ium$" :A #"ive$" :A #"ize$" :F
#"oid$" :A #"one$" :R #"ous$" :A
#"ae$" :A #"al$" :BB #"ar$" :X #"as$" :B
#"ed$" :E #"en$" :F #"es$" :E #"ia$" :A
#"ic$" :A #"is$" :A #"ly$" :B #"on$" :S
#"or$" :T #"um$" :U #"us$" :V #"yl$" :R
#"s'" :A #"'s$" :A
#"a$" :A #"e$" :A #"i$" :A #"o$" :A
#"s$" :W #"y$" :B))
;; Conditions
(def ^:private conditions
{:A (fn [stem] true)
:B (fn [stem] (> (count stem) 2))
:C (fn [stem] (> (count stem) 3))
:D (fn [stem] (> (count stem) 4))
:E (fn [stem] (not (re-test? #"e$" stem)))
:F (fn [stem] (and ((conditions :B) stem) (conditions :E stem)))
:G (fn [stem] (and ((conditions :B) stem) (re-test? #"f$" stem)))
:H (fn [stem] (re-test? #"(t|ll)$" stem))
:I (fn [stem] (not (re-test? #"[oe]$" stem)))
:J (fn [stem] (not (re-test? #"[ae]$" stem)))
:K (fn [stem] (and ((conditions :B) stem) (re-test? #"(l|i|(u\we))$" stem)))
:L (fn [stem] (not (re-test? #"(u|x|([^o]s))$" stem)))
:M (fn [stem] (not (re-test? #"[acem]$" stem)))
:N (fn [stem] (if (re-test? #"s\w{2}$" stem) ((conditions :C) stem) ((conditions :B) stem)))
:O (fn [stem] (re-test? #"[li]$" stem))
:P (fn [stem] (not (re-test? #"c$" stem)))
:Q (fn [stem] (and ((conditions :B) stem) (not (re-test? #"[ln]$" stem))))
:R (fn [stem] (re-test? #"[nr]$" stem))
:S (fn [stem] (re-test? #"(dr|[^t]t)$" stem))
:T (fn [stem] (re-test? #"(s|[^o]t)$" stem))
:U (fn [stem] (re-test? #"[lmnr]$" stem))
:V (fn [stem] (re-test? #"c$" stem))
:W (fn [stem] (not (re-test? #"[su]$" stem)))
:X (fn [stem] (re-test? #"(l|i|u\we)$" stem))
:Y (fn [stem] (re-test? #"in$" stem))
:Z (fn [stem] (not (re-test? #"f$" stem)))
:AA (fn [stem] (re-test? #"([dflt]|ph|th|er|or|es)$" stem))
:BB (fn [stem] (and ((conditions :B) stem) (not (re-test? #"(met|ryst)" stem))))
:CC (fn [stem] (re-test? #"l$" stem))})
;; Transformations
(defn- dedouble
"Drop double occurences of certain letters in the given [stem]."
[stem]
(clojure.string/replace stem #"([bdglmnprst])\1{1,}$" "$1"))
(def ^:private transformations
'(#"iev$" "ief"
#"uct$" "uc"
#"umpt$" "um"
#"rpt$" "rb"
#"urs$" "ur"
#"istr$" "ister"
#"metr$" "meter"
#"olv$" "olut"
#"([^aoi])ul$" "$1l"
#"bex$" "bic"
#"dex$" "dic"
#"pex$" "pic"
#"tex$" "tic"
#"ax$" "ac"
#"ex$" "ec"
#"ix$" "ic"
#"lux$" "luc"
#"uad$" "uas"
#"vad$" "vas"
#"cid$" "cis"
#"lid$" "lis"
#"erid$" "eris"
#"pand$" "pans"
#"([^s])end$" "$1ens"
#"ond$" "ons"
#"lud$" "lus"
#"rud$" "rus"
#"([^pt])her$" "$1hes"
#"mit$" "mis"
#"([^m])ent$" "$1ens"
#"ert$" "ers"
#"([^n])et$" "$1es"
#"(yt|yz)$" "ys"))
;; Helpers
(defn- clean
"Clean a [word] of characters unsupported by the stemmer"
[word]
(clojure.string/replace word #"[^a-zA-Z']" ""))
;; Main functions
(defn- prep-word
"Prepare a [word] for its passage through the stemmer."
[word]
(clean (clojure.string/lower-case word)))
(defn- test-suffix-fn
[word]
(fn [ending]
(let [match (first ending)
condition (second ending)
stem (clojure.string/replace word match "")]
(when (and (< (count stem) (count word))
(> (count stem) 1)
((conditions condition) stem))
stem))))
(defn- drop-suffix
"Drop the longest suffix we can find in the given [word]."
[word]
(if-let [stem (some (test-suffix-fn word) (partition 2 endings))]
stem
word))
(defn apply-transformations
"Apply the algorithm's transformations to the given [stem]."
[stem]
(if-let [[match replacement] (some #(when (re-test? (first %) stem) %) (partition 2 transformations))]
(clojure.string/replace stem match replacement)
stem))
(defn stem
"Stem the given [word] according to the algorithm."
[word]
(-> (prep-word word)
(drop-suffix)
(dedouble)
(apply-transformations)))
|
[
{
"context": "et! *warn-on-reflection* true)\n\n\n(def window-key :chat)\n\n\n(def chat-window-width 1600)\n(def chat-window-",
"end": 354,
"score": 0.6885027289390564,
"start": 350,
"tag": "KEY",
"value": "chat"
}
] |
src/clj/skylobby/fx/chat.clj
|
badosu/skylobby
| 7 |
(ns skylobby.fx.chat
(:require
[cljfx.api :as fx]
skylobby.fx
[skylobby.fx.channels :as fx.channels]
[skylobby.fx.font-icon :as font-icon]
[skylobby.fx.main-tabs :as fx.main-tabs]
[skylobby.fx.user :as fx.user]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def window-key :chat)
(def chat-window-width 1600)
(def chat-window-height 1000)
(defn chat-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
window-states (fx/sub-val context :window-states)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
show (boolean (fx/sub-val context :show-chat-window))]
{:fx/type fx/ext-on-instance-lifecycle
:on-created (partial skylobby.fx/add-maximized-listener window-key)
:desc
{:fx/type :stage
:showing show
:title (str u/app-name " Chat " server-key)
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-chat-window}
:maximized (get-in window-states [window-key :maximized] false)
:x (skylobby.fx/fitx screen-bounds (get-in window-states [window-key :x]))
:y (skylobby.fx/fity screen-bounds (get-in window-states [window-key :y]))
:width (skylobby.fx/fitwidth screen-bounds (get-in window-states [window-key :width]) chat-window-width)
:height (skylobby.fx/fitheight screen-bounds (get-in window-states [window-key :height]) chat-window-height)
:on-width-changed (partial skylobby.fx/window-changed window-key :width)
:on-height-changed (partial skylobby.fx/window-changed window-key :height)
:on-x-changed (partial skylobby.fx/window-changed window-key :x)
:on-y-changed (partial skylobby.fx/window-changed window-key :y)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show
(let [
join-channel-name (fx/sub-val context :join-channel-name)
channels (fx/sub-val context get-in [:by-server server-key :channels])
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
users-view {:fx/type fx.user/users-view
:server-key server-key
:v-box/vgrow :always}]
{:fx/type :split-pane
:divider-positions [0.70 0.9]
:items
[{:fx/type fx.main-tabs/my-channels-view
:server-key server-key}
users-view
{:fx/type :v-box
:children
[{:fx/type :label
:text (str "Channels (" (->> channels vals u/non-battle-channels count) ")")}
{:fx/type fx.channels/channels-table
:v-box/vgrow :always
:server-key server-key}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :button
:text ""
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}
:graphic
{:fx/type font-icon/lifecycle
:icon-literal "mdi-plus:20:white"}}
{:fx/type :text-field
:text join-channel-name
:prompt-text "New Channel"
:on-text-changed {:event/type :spring-lobby/assoc-in
:path [:by-server server-key :join-channel-name]}
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}}]}]}]})
{:fx/type :pane
:pref-width chat-window-width
:pref-height chat-window-height})}}}))
(defn chat-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :chat-window
(chat-window-impl state))))
|
65807
|
(ns skylobby.fx.chat
(:require
[cljfx.api :as fx]
skylobby.fx
[skylobby.fx.channels :as fx.channels]
[skylobby.fx.font-icon :as font-icon]
[skylobby.fx.main-tabs :as fx.main-tabs]
[skylobby.fx.user :as fx.user]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def window-key :<KEY>)
(def chat-window-width 1600)
(def chat-window-height 1000)
(defn chat-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
window-states (fx/sub-val context :window-states)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
show (boolean (fx/sub-val context :show-chat-window))]
{:fx/type fx/ext-on-instance-lifecycle
:on-created (partial skylobby.fx/add-maximized-listener window-key)
:desc
{:fx/type :stage
:showing show
:title (str u/app-name " Chat " server-key)
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-chat-window}
:maximized (get-in window-states [window-key :maximized] false)
:x (skylobby.fx/fitx screen-bounds (get-in window-states [window-key :x]))
:y (skylobby.fx/fity screen-bounds (get-in window-states [window-key :y]))
:width (skylobby.fx/fitwidth screen-bounds (get-in window-states [window-key :width]) chat-window-width)
:height (skylobby.fx/fitheight screen-bounds (get-in window-states [window-key :height]) chat-window-height)
:on-width-changed (partial skylobby.fx/window-changed window-key :width)
:on-height-changed (partial skylobby.fx/window-changed window-key :height)
:on-x-changed (partial skylobby.fx/window-changed window-key :x)
:on-y-changed (partial skylobby.fx/window-changed window-key :y)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show
(let [
join-channel-name (fx/sub-val context :join-channel-name)
channels (fx/sub-val context get-in [:by-server server-key :channels])
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
users-view {:fx/type fx.user/users-view
:server-key server-key
:v-box/vgrow :always}]
{:fx/type :split-pane
:divider-positions [0.70 0.9]
:items
[{:fx/type fx.main-tabs/my-channels-view
:server-key server-key}
users-view
{:fx/type :v-box
:children
[{:fx/type :label
:text (str "Channels (" (->> channels vals u/non-battle-channels count) ")")}
{:fx/type fx.channels/channels-table
:v-box/vgrow :always
:server-key server-key}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :button
:text ""
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}
:graphic
{:fx/type font-icon/lifecycle
:icon-literal "mdi-plus:20:white"}}
{:fx/type :text-field
:text join-channel-name
:prompt-text "New Channel"
:on-text-changed {:event/type :spring-lobby/assoc-in
:path [:by-server server-key :join-channel-name]}
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}}]}]}]})
{:fx/type :pane
:pref-width chat-window-width
:pref-height chat-window-height})}}}))
(defn chat-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :chat-window
(chat-window-impl state))))
| true |
(ns skylobby.fx.chat
(:require
[cljfx.api :as fx]
skylobby.fx
[skylobby.fx.channels :as fx.channels]
[skylobby.fx.font-icon :as font-icon]
[skylobby.fx.main-tabs :as fx.main-tabs]
[skylobby.fx.user :as fx.user]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def window-key :PI:KEY:<KEY>END_PI)
(def chat-window-width 1600)
(def chat-window-height 1000)
(defn chat-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
window-states (fx/sub-val context :window-states)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
show (boolean (fx/sub-val context :show-chat-window))]
{:fx/type fx/ext-on-instance-lifecycle
:on-created (partial skylobby.fx/add-maximized-listener window-key)
:desc
{:fx/type :stage
:showing show
:title (str u/app-name " Chat " server-key)
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-chat-window}
:maximized (get-in window-states [window-key :maximized] false)
:x (skylobby.fx/fitx screen-bounds (get-in window-states [window-key :x]))
:y (skylobby.fx/fity screen-bounds (get-in window-states [window-key :y]))
:width (skylobby.fx/fitwidth screen-bounds (get-in window-states [window-key :width]) chat-window-width)
:height (skylobby.fx/fitheight screen-bounds (get-in window-states [window-key :height]) chat-window-height)
:on-width-changed (partial skylobby.fx/window-changed window-key :width)
:on-height-changed (partial skylobby.fx/window-changed window-key :height)
:on-x-changed (partial skylobby.fx/window-changed window-key :x)
:on-y-changed (partial skylobby.fx/window-changed window-key :y)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show
(let [
join-channel-name (fx/sub-val context :join-channel-name)
channels (fx/sub-val context get-in [:by-server server-key :channels])
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
users-view {:fx/type fx.user/users-view
:server-key server-key
:v-box/vgrow :always}]
{:fx/type :split-pane
:divider-positions [0.70 0.9]
:items
[{:fx/type fx.main-tabs/my-channels-view
:server-key server-key}
users-view
{:fx/type :v-box
:children
[{:fx/type :label
:text (str "Channels (" (->> channels vals u/non-battle-channels count) ")")}
{:fx/type fx.channels/channels-table
:v-box/vgrow :always
:server-key server-key}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :button
:text ""
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}
:graphic
{:fx/type font-icon/lifecycle
:icon-literal "mdi-plus:20:white"}}
{:fx/type :text-field
:text join-channel-name
:prompt-text "New Channel"
:on-text-changed {:event/type :spring-lobby/assoc-in
:path [:by-server server-key :join-channel-name]}
:on-action {:event/type :spring-lobby/join-channel
:channel-name join-channel-name
:client-data client-data}}]}]}]})
{:fx/type :pane
:pref-width chat-window-width
:pref-height chat-window-height})}}}))
(defn chat-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :chat-window
(chat-window-impl state))))
|
[
{
"context": "name/Password\"\n :username \"username\"\n :password \"password\"\n ",
"end": 1111,
"score": 0.9995664954185486,
"start": 1103,
"tag": "USERNAME",
"value": "username"
},
{
"context": " \"username\"\n :password \"password\"\n :acl st/resource-ac",
"end": 1156,
"score": 0.9994140863418579,
"start": 1148,
"tag": "PASSWORD",
"value": "password"
}
] |
cimi/test/com/sixsq/slipstream/ssclj/resources/session_template_internal_lifecycle_test.clj
|
slipstream/cimi-mf2c
| 0 |
(ns com.sixsq.slipstream.ssclj.resources.session-template-internal-lifecycle-test
(:require
[clojure.test :refer :all]
[peridot.core :refer :all]
[com.sixsq.slipstream.ssclj.resources.session-template :as st]
[com.sixsq.slipstream.ssclj.resources.session-template-internal :as internal]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.resources.session-template-lifecycle-test-utils :as stu]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[clojure.data.json :as json]))
(use-fixtures :each ltu/with-test-server-fixture)
(def base-uri (str p/service-context (u/de-camelcase st/resource-name)))
(def valid-template {:method internal/authn-method
:instance internal/authn-method
:name "Internal"
:description "Internal Authentication via Username/Password"
:username "username"
:password "password"
:acl st/resource-acl})
(defn check-existing-session-template [base-uri valid-template]
(let [method (:method valid-template)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "root ADMIN USER ANON")
session-anon (header session authn-info-header "unknown ANON")]
;; should be an existing template already
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-template))
(ltu/body->edn)
(ltu/is-status 409))
;; session template should be visible via query as well
;; should have one with the correct method name
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (= 1 (count (filter #(= method (:method %)) entries)))))
;; do full lifecycle for an internal session template
(let [uri (str (u/de-camelcase st/resource-name) "/" method)
abs-uri (str p/service-context uri)]
;; delete the template
(-> session-admin
(request abs-uri :request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; verify that the template is gone
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 404))
;; session template should not be there anymore
(ltu/refresh-es-indices)
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (zero? (count (filter #(= method (:method %)) entries))))))))
(deftest lifecycle
(check-existing-session-template base-uri valid-template)
(stu/session-template-lifecycle base-uri valid-template))
|
111942
|
(ns com.sixsq.slipstream.ssclj.resources.session-template-internal-lifecycle-test
(:require
[clojure.test :refer :all]
[peridot.core :refer :all]
[com.sixsq.slipstream.ssclj.resources.session-template :as st]
[com.sixsq.slipstream.ssclj.resources.session-template-internal :as internal]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.resources.session-template-lifecycle-test-utils :as stu]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[clojure.data.json :as json]))
(use-fixtures :each ltu/with-test-server-fixture)
(def base-uri (str p/service-context (u/de-camelcase st/resource-name)))
(def valid-template {:method internal/authn-method
:instance internal/authn-method
:name "Internal"
:description "Internal Authentication via Username/Password"
:username "username"
:password "<PASSWORD>"
:acl st/resource-acl})
(defn check-existing-session-template [base-uri valid-template]
(let [method (:method valid-template)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "root ADMIN USER ANON")
session-anon (header session authn-info-header "unknown ANON")]
;; should be an existing template already
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-template))
(ltu/body->edn)
(ltu/is-status 409))
;; session template should be visible via query as well
;; should have one with the correct method name
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (= 1 (count (filter #(= method (:method %)) entries)))))
;; do full lifecycle for an internal session template
(let [uri (str (u/de-camelcase st/resource-name) "/" method)
abs-uri (str p/service-context uri)]
;; delete the template
(-> session-admin
(request abs-uri :request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; verify that the template is gone
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 404))
;; session template should not be there anymore
(ltu/refresh-es-indices)
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (zero? (count (filter #(= method (:method %)) entries))))))))
(deftest lifecycle
(check-existing-session-template base-uri valid-template)
(stu/session-template-lifecycle base-uri valid-template))
| true |
(ns com.sixsq.slipstream.ssclj.resources.session-template-internal-lifecycle-test
(:require
[clojure.test :refer :all]
[peridot.core :refer :all]
[com.sixsq.slipstream.ssclj.resources.session-template :as st]
[com.sixsq.slipstream.ssclj.resources.session-template-internal :as internal]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.resources.session-template-lifecycle-test-utils :as stu]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[clojure.data.json :as json]))
(use-fixtures :each ltu/with-test-server-fixture)
(def base-uri (str p/service-context (u/de-camelcase st/resource-name)))
(def valid-template {:method internal/authn-method
:instance internal/authn-method
:name "Internal"
:description "Internal Authentication via Username/Password"
:username "username"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:acl st/resource-acl})
(defn check-existing-session-template [base-uri valid-template]
(let [method (:method valid-template)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "root ADMIN USER ANON")
session-anon (header session authn-info-header "unknown ANON")]
;; should be an existing template already
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-template))
(ltu/body->edn)
(ltu/is-status 409))
;; session template should be visible via query as well
;; should have one with the correct method name
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (= 1 (count (filter #(= method (:method %)) entries)))))
;; do full lifecycle for an internal session template
(let [uri (str (u/de-camelcase st/resource-name) "/" method)
abs-uri (str p/service-context uri)]
;; delete the template
(-> session-admin
(request abs-uri :request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; verify that the template is gone
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 404))
;; session template should not be there anymore
(ltu/refresh-es-indices)
(let [entries (-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-resource-uri st/collection-uri)
(ltu/entries :sessionTemplates))]
(is (zero? (count (filter #(= method (:method %)) entries))))))))
(deftest lifecycle
(check-existing-session-template base-uri valid-template)
(stu/session-template-lifecycle base-uri valid-template))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(ns\n #^{:author \"Konrad Hinsen\"\n :skip-wiki true\n :doc \"Examples for dat",
"end": 369,
"score": 0.9998677968978882,
"start": 356,
"tag": "NAME",
"value": "Konrad Hinsen"
}
] |
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/types/examples.clj
|
allertonm/Couverjure
| 3 |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Application examples for data types
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "Konrad Hinsen"
:skip-wiki true
:doc "Examples for data type definitions"}
clojure.contrib.types.examples
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types
:only (deftype defadt match)])
(:require [clojure.contrib.generic.collection :as gc])
(:require [clojure.contrib.generic.functor :as gf]))
;
; Multisets implemented as maps to integers
;
; The most basic type definition. A more elaborate version could add
; a constructor that verifies that its argument is a map with integer values.
(deftype ::multiset multiset
"Multiset (demo implementation)")
; Some set operations generalized to multisets
; Note that the multiset constructor is nowhere called explicitly, as the
; map operations all preserve the metadata.
(defmethod gc/conj ::multiset
([ms x]
(assoc ms x (inc (get ms x 0))))
([ms x & xs]
(reduce gc/conj (gc/conj ms x) xs)))
(defmulti union (fn [& sets] (type (first sets))))
(defmethod union clojure.lang.IPersistentSet
[& sets]
(apply clojure.set/union sets))
; Note: a production-quality implementation should accept standard sets
; and perhaps other collections for its second argument.
(defmethod union ::multiset
([ms] ms)
([ms1 ms2]
(letfn [(add-item [ms [item n]]
(assoc ms item (+ n (get ms item 0))))]
(reduce add-item ms1 ms2)))
([ms1 ms2 & mss]
(reduce union (union ms1 ms2) mss)))
; Let's use it:
(gc/conj #{} :a :a :b :c)
(gc/conj (multiset {}) :a :a :b :c)
(union #{:a :b} #{:b :c})
(union (multiset {:a 1 :b 1}) (multiset {:b 1 :c 2}))
;
; A simple tree structure defined as an algebraic data type
;
(defadt ::tree
empty-tree
(leaf value)
(node left-tree right-tree))
(def a-tree (node (leaf :a)
(node (leaf :b)
(leaf :c))))
(defn depth
[t]
(match t
empty-tree 0
(leaf _) 1
(node l r) (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Algebraic data types with multimethods: fmap on a tree
(defmethod gf/fmap ::tree
[f t]
(match t
empty-tree empty-tree
(leaf v) (leaf (f v))
(node l r) (node (gf/fmap f l) (gf/fmap f r))))
(gf/fmap str a-tree)
;
; Nonsense examples to illustrate all the features of match
; for type constructors.
;
(defadt ::foo
(bar a b c))
(defn foo-to-int
[a-foo]
(match a-foo
(bar x x x) x
(bar 0 x y) (+ x y)
(bar 1 2 3) -1
(bar a b 1) (* a b)
:else 42))
(foo-to-int (bar 0 0 0)) ; 0
(foo-to-int (bar 0 5 6)) ; 11
(foo-to-int (bar 1 2 3)) ; -1
(foo-to-int (bar 3 3 1)) ; 9
(foo-to-int (bar 0 3 1)) ; 4
(foo-to-int (bar 10 20 30)) ; 42
;
; Match can also be used for lists, vectors, and maps. Note that since
; algebraic data types are represented as maps, they can be matched
; either with their type constructor and positional arguments, or
; with a map template.
;
; Tree depth once again with map templates
(defn depth
[t]
(match t
empty-tree 0
{:value _} 1
{:left-tree l :right-tree r} (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Match for lists, vectors, and maps:
(for [x ['(1 2 3)
[1 2 3]
{:x 1 :y 2 :z 3}
'(1 1 1)
[2 1 2]
{:x 1 :y 1 :z 2}]]
(match x
'(a a a) 'list-of-three-equal-values
'(a b c) 'list
[a a a] 'vector-of-three-equal-values
[a b a] 'vector-of-three-with-first-and-last-equal
[a b c] 'vector
{:x a :y z} 'map-with-x-equal-y
{} 'any-map))
|
91314
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Application examples for data types
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "<NAME>"
:skip-wiki true
:doc "Examples for data type definitions"}
clojure.contrib.types.examples
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types
:only (deftype defadt match)])
(:require [clojure.contrib.generic.collection :as gc])
(:require [clojure.contrib.generic.functor :as gf]))
;
; Multisets implemented as maps to integers
;
; The most basic type definition. A more elaborate version could add
; a constructor that verifies that its argument is a map with integer values.
(deftype ::multiset multiset
"Multiset (demo implementation)")
; Some set operations generalized to multisets
; Note that the multiset constructor is nowhere called explicitly, as the
; map operations all preserve the metadata.
(defmethod gc/conj ::multiset
([ms x]
(assoc ms x (inc (get ms x 0))))
([ms x & xs]
(reduce gc/conj (gc/conj ms x) xs)))
(defmulti union (fn [& sets] (type (first sets))))
(defmethod union clojure.lang.IPersistentSet
[& sets]
(apply clojure.set/union sets))
; Note: a production-quality implementation should accept standard sets
; and perhaps other collections for its second argument.
(defmethod union ::multiset
([ms] ms)
([ms1 ms2]
(letfn [(add-item [ms [item n]]
(assoc ms item (+ n (get ms item 0))))]
(reduce add-item ms1 ms2)))
([ms1 ms2 & mss]
(reduce union (union ms1 ms2) mss)))
; Let's use it:
(gc/conj #{} :a :a :b :c)
(gc/conj (multiset {}) :a :a :b :c)
(union #{:a :b} #{:b :c})
(union (multiset {:a 1 :b 1}) (multiset {:b 1 :c 2}))
;
; A simple tree structure defined as an algebraic data type
;
(defadt ::tree
empty-tree
(leaf value)
(node left-tree right-tree))
(def a-tree (node (leaf :a)
(node (leaf :b)
(leaf :c))))
(defn depth
[t]
(match t
empty-tree 0
(leaf _) 1
(node l r) (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Algebraic data types with multimethods: fmap on a tree
(defmethod gf/fmap ::tree
[f t]
(match t
empty-tree empty-tree
(leaf v) (leaf (f v))
(node l r) (node (gf/fmap f l) (gf/fmap f r))))
(gf/fmap str a-tree)
;
; Nonsense examples to illustrate all the features of match
; for type constructors.
;
(defadt ::foo
(bar a b c))
(defn foo-to-int
[a-foo]
(match a-foo
(bar x x x) x
(bar 0 x y) (+ x y)
(bar 1 2 3) -1
(bar a b 1) (* a b)
:else 42))
(foo-to-int (bar 0 0 0)) ; 0
(foo-to-int (bar 0 5 6)) ; 11
(foo-to-int (bar 1 2 3)) ; -1
(foo-to-int (bar 3 3 1)) ; 9
(foo-to-int (bar 0 3 1)) ; 4
(foo-to-int (bar 10 20 30)) ; 42
;
; Match can also be used for lists, vectors, and maps. Note that since
; algebraic data types are represented as maps, they can be matched
; either with their type constructor and positional arguments, or
; with a map template.
;
; Tree depth once again with map templates
(defn depth
[t]
(match t
empty-tree 0
{:value _} 1
{:left-tree l :right-tree r} (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Match for lists, vectors, and maps:
(for [x ['(1 2 3)
[1 2 3]
{:x 1 :y 2 :z 3}
'(1 1 1)
[2 1 2]
{:x 1 :y 1 :z 2}]]
(match x
'(a a a) 'list-of-three-equal-values
'(a b c) 'list
[a a a] 'vector-of-three-equal-values
[a b a] 'vector-of-three-with-first-and-last-equal
[a b c] 'vector
{:x a :y z} 'map-with-x-equal-y
{} 'any-map))
| true |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Application examples for data types
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns
#^{:author "PI:NAME:<NAME>END_PI"
:skip-wiki true
:doc "Examples for data type definitions"}
clojure.contrib.types.examples
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types
:only (deftype defadt match)])
(:require [clojure.contrib.generic.collection :as gc])
(:require [clojure.contrib.generic.functor :as gf]))
;
; Multisets implemented as maps to integers
;
; The most basic type definition. A more elaborate version could add
; a constructor that verifies that its argument is a map with integer values.
(deftype ::multiset multiset
"Multiset (demo implementation)")
; Some set operations generalized to multisets
; Note that the multiset constructor is nowhere called explicitly, as the
; map operations all preserve the metadata.
(defmethod gc/conj ::multiset
([ms x]
(assoc ms x (inc (get ms x 0))))
([ms x & xs]
(reduce gc/conj (gc/conj ms x) xs)))
(defmulti union (fn [& sets] (type (first sets))))
(defmethod union clojure.lang.IPersistentSet
[& sets]
(apply clojure.set/union sets))
; Note: a production-quality implementation should accept standard sets
; and perhaps other collections for its second argument.
(defmethod union ::multiset
([ms] ms)
([ms1 ms2]
(letfn [(add-item [ms [item n]]
(assoc ms item (+ n (get ms item 0))))]
(reduce add-item ms1 ms2)))
([ms1 ms2 & mss]
(reduce union (union ms1 ms2) mss)))
; Let's use it:
(gc/conj #{} :a :a :b :c)
(gc/conj (multiset {}) :a :a :b :c)
(union #{:a :b} #{:b :c})
(union (multiset {:a 1 :b 1}) (multiset {:b 1 :c 2}))
;
; A simple tree structure defined as an algebraic data type
;
(defadt ::tree
empty-tree
(leaf value)
(node left-tree right-tree))
(def a-tree (node (leaf :a)
(node (leaf :b)
(leaf :c))))
(defn depth
[t]
(match t
empty-tree 0
(leaf _) 1
(node l r) (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Algebraic data types with multimethods: fmap on a tree
(defmethod gf/fmap ::tree
[f t]
(match t
empty-tree empty-tree
(leaf v) (leaf (f v))
(node l r) (node (gf/fmap f l) (gf/fmap f r))))
(gf/fmap str a-tree)
;
; Nonsense examples to illustrate all the features of match
; for type constructors.
;
(defadt ::foo
(bar a b c))
(defn foo-to-int
[a-foo]
(match a-foo
(bar x x x) x
(bar 0 x y) (+ x y)
(bar 1 2 3) -1
(bar a b 1) (* a b)
:else 42))
(foo-to-int (bar 0 0 0)) ; 0
(foo-to-int (bar 0 5 6)) ; 11
(foo-to-int (bar 1 2 3)) ; -1
(foo-to-int (bar 3 3 1)) ; 9
(foo-to-int (bar 0 3 1)) ; 4
(foo-to-int (bar 10 20 30)) ; 42
;
; Match can also be used for lists, vectors, and maps. Note that since
; algebraic data types are represented as maps, they can be matched
; either with their type constructor and positional arguments, or
; with a map template.
;
; Tree depth once again with map templates
(defn depth
[t]
(match t
empty-tree 0
{:value _} 1
{:left-tree l :right-tree r} (inc (max (depth l) (depth r)))))
(depth empty-tree)
(depth (leaf 42))
(depth a-tree)
; Match for lists, vectors, and maps:
(for [x ['(1 2 3)
[1 2 3]
{:x 1 :y 2 :z 3}
'(1 1 1)
[2 1 2]
{:x 1 :y 1 :z 2}]]
(match x
'(a a a) 'list-of-three-equal-values
'(a b c) 'list
[a a a] 'vector-of-three-equal-values
[a b a] 'vector-of-three-with-first-and-last-equal
[a b c] 'vector
{:x a :y z} 'map-with-x-equal-y
{} 'any-map))
|
[
{
"context": "e-lines\n;; (:new Conversation c)\n;; (:new Person Steve)\n;; (Steve :in c)\n;; (Steve :says \"Hello\")\n;; ",
"end": 4774,
"score": 0.9989859461784363,
"start": 4769,
"tag": "NAME",
"value": "Steve"
},
{
"context": ":new Conversation c)\n;; (:new Person Steve)\n;; (Steve :in c)\n;; (Steve :says \"Hello\")\n;; (Steve :says",
"end": 4786,
"score": 0.8238162994384766,
"start": 4781,
"tag": "NAME",
"value": "Steve"
},
{
"context": "c)\n;; (:new Person Steve)\n;; (Steve :in c)\n;; (Steve :says \"Hello\")\n;; (Steve :says \"I hate this plac",
"end": 4804,
"score": 0.9104045629501343,
"start": 4799,
"tag": "NAME",
"value": "Steve"
},
{
"context": "\n;; (Steve :in c)\n;; (Steve :says \"Hello\")\n;; (Steve :says \"I hate this place!\")\n;; (Steve :quits)\n;;",
"end": 4830,
"score": 0.8975164890289307,
"start": 4825,
"tag": "NAME",
"value": "Steve"
},
{
"context": "llo\")\n;; (Steve :says \"I hate this place!\")\n;; (Steve :quits)\n;; (c))\n\n",
"end": 4869,
"score": 0.888149082660675,
"start": 4864,
"tag": "NAME",
"value": "Steve"
}
] |
src/spec_examples/dsl_example.clj
|
MrDallOca/spec-examples
| 47 |
(ns spec-examples.dsl-example
(:require [clojure.spec :as s]
[clojure.string :as str])
(:import [clojure.lang Keyword Symbol]))
(definterface IConversation
(getParticipants [])
(setParticipants [n])
(updateParticipants [f])
(getLines [])
(setLines [n])
(updateLines [f]))
(definterface IPerson
(getName [])
(getConversation [])
(setConversation [c]))
(deftype Conversation [^:volatile-mutable participants
^:volatile-mutable lines]
Object
(toString [this]
(str {:participants participants
:lines lines }))
IConversation
(getParticipants [this]
participants)
(setParticipants [this n]
(set! participants n))
(updateParticipants [this f]
(set! participants (f participants)))
(getLines [this]
lines)
(setLines [this n]
(set! lines n))
(updateLines [this f]
(set! lines (f lines))))
(deftype Person [name
^:volatile-mutable conv]
Object
(toString [this]
(str name))
IPerson
(getName [this]
name)
(getConversation [this]
conv)
(setConversation [this c]
(set! conv c)))
(defmethod print-method Conversation [x writer]
(.write writer (.toString x)))
(defmethod print-method Person [x writer]
(.write writer (str \" x \")))
(defmethod print-dup Conversation [x w]
(print-ctor x (fn [o w] (print-dup (str x) w))
w))
(defmethod print-dup Person [x w]
(print-ctor x (fn [o w] (print-dup ((str \" x \")) w))
w))
(defn conversation []
(Conversation. #{} []))
(defn person [name]
(Person. name nil))
(defmacro handle-get
[obj-sym field-sym]
(let [getter (str ".get" (-> field-sym str str/capitalize))]
(read-string (str "(" getter " " obj-sym ")"))))
(defn handle-return [x] x)
(defn add-participant
[who conversation]
(.updateParticipants conversation #(conj % who))
(.setConversation who conversation))
(defn say-something
[who what]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(.updateLines c #(conj % (str who "> "what))))))
(defn quit-conversation
[who]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(do (.updateParticipants c #(disj % who))
(.setConversation who nil)))))
(defn print-conversation
[conversation])
(def constructors-map
{'Conversation (fn [_] (conversation))
'Person #(person (str %))})
(defn construct-thing [constructor-s args]
`(apply ~(constructors-map constructor-s) '~args))
(def infix-map
{:joins `add-participant
:says `say-something
:quits `quit-conversation})
(def prefix-map
{:print `print
:print-line `println
:get `handle-get
:return `handle-return})
(def new-k :new)
;; SPEC
(s/def ::infix-keyword (s/and keyword? (set (keys infix-map))))
(s/def ::prefix-keyword (s/and keyword? (set (keys prefix-map))))
(s/def ::new-keyword (s/and keyword? #(= % new-k)))
(s/def ::constructor (s/and symbol? (set (keys constructors-map))))
(s/def ::args (s/* any?))
(s/def ::constructor-line (s/spec (s/cat :new-k ::new-keyword
:constructor ::constructor
:obj-symbol symbol?
:args ::args)))
(s/def ::infix-line (s/spec (s/cat :subject symbol?
:keyword ::infix-keyword
:args ::args)))
(s/def ::prefix-line (s/spec (s/cat :keyword ::prefix-keyword
:args ::args)))
(s/def ::line (s/alt :infix-line ::infix-line
:prefix-line ::prefix-line))
(s/def ::lines-seq (s/cat :constructor-lines (s/* ::constructor-line)
:body-lines (s/+ ::line)))
(s/fdef parse-nosence-lines :args ::lines-seq)
;; END OF SPEC
(defmulti parse-nosence
"Core function for parsing the nosencelang"
(fn [& args] (map class (take 1 args))))
(defmethod parse-nosence
[Symbol]
sym-k-args
[s1 k & args]
`(~(k infix-map) ~s1 ~@args))
(defmethod parse-nosence
[Keyword]
k-args
[k & args]
`(~(k prefix-map) ~@args))
(defmethod parse-nosence :default [x] x)
(defn bindings-from-new [lists]
(->> (for [[k constructor sym & args] lists
:when (= k new-k)]
`(~sym ~(construct-thing constructor (conj args sym))))
(apply concat)
(into [])))
(defn parse-nosence-lines-helper [lines]
(let [bindings (bindings-from-new lines)
lines (remove #(= new-k (first %)) lines)]
`(let ~bindings
~@(for [l lines]
(apply parse-nosence l)))))
(defmacro parse-nosence-lines
[& lines]
(parse-nosence-lines-helper lines))
;; (parse-nosence-lines
;; (:new Conversation c)
;; (:new Person Steve)
;; (Steve :in c)
;; (Steve :says "Hello")
;; (Steve :says "I hate this place!")
;; (Steve :quits)
;; (c))
|
43956
|
(ns spec-examples.dsl-example
(:require [clojure.spec :as s]
[clojure.string :as str])
(:import [clojure.lang Keyword Symbol]))
(definterface IConversation
(getParticipants [])
(setParticipants [n])
(updateParticipants [f])
(getLines [])
(setLines [n])
(updateLines [f]))
(definterface IPerson
(getName [])
(getConversation [])
(setConversation [c]))
(deftype Conversation [^:volatile-mutable participants
^:volatile-mutable lines]
Object
(toString [this]
(str {:participants participants
:lines lines }))
IConversation
(getParticipants [this]
participants)
(setParticipants [this n]
(set! participants n))
(updateParticipants [this f]
(set! participants (f participants)))
(getLines [this]
lines)
(setLines [this n]
(set! lines n))
(updateLines [this f]
(set! lines (f lines))))
(deftype Person [name
^:volatile-mutable conv]
Object
(toString [this]
(str name))
IPerson
(getName [this]
name)
(getConversation [this]
conv)
(setConversation [this c]
(set! conv c)))
(defmethod print-method Conversation [x writer]
(.write writer (.toString x)))
(defmethod print-method Person [x writer]
(.write writer (str \" x \")))
(defmethod print-dup Conversation [x w]
(print-ctor x (fn [o w] (print-dup (str x) w))
w))
(defmethod print-dup Person [x w]
(print-ctor x (fn [o w] (print-dup ((str \" x \")) w))
w))
(defn conversation []
(Conversation. #{} []))
(defn person [name]
(Person. name nil))
(defmacro handle-get
[obj-sym field-sym]
(let [getter (str ".get" (-> field-sym str str/capitalize))]
(read-string (str "(" getter " " obj-sym ")"))))
(defn handle-return [x] x)
(defn add-participant
[who conversation]
(.updateParticipants conversation #(conj % who))
(.setConversation who conversation))
(defn say-something
[who what]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(.updateLines c #(conj % (str who "> "what))))))
(defn quit-conversation
[who]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(do (.updateParticipants c #(disj % who))
(.setConversation who nil)))))
(defn print-conversation
[conversation])
(def constructors-map
{'Conversation (fn [_] (conversation))
'Person #(person (str %))})
(defn construct-thing [constructor-s args]
`(apply ~(constructors-map constructor-s) '~args))
(def infix-map
{:joins `add-participant
:says `say-something
:quits `quit-conversation})
(def prefix-map
{:print `print
:print-line `println
:get `handle-get
:return `handle-return})
(def new-k :new)
;; SPEC
(s/def ::infix-keyword (s/and keyword? (set (keys infix-map))))
(s/def ::prefix-keyword (s/and keyword? (set (keys prefix-map))))
(s/def ::new-keyword (s/and keyword? #(= % new-k)))
(s/def ::constructor (s/and symbol? (set (keys constructors-map))))
(s/def ::args (s/* any?))
(s/def ::constructor-line (s/spec (s/cat :new-k ::new-keyword
:constructor ::constructor
:obj-symbol symbol?
:args ::args)))
(s/def ::infix-line (s/spec (s/cat :subject symbol?
:keyword ::infix-keyword
:args ::args)))
(s/def ::prefix-line (s/spec (s/cat :keyword ::prefix-keyword
:args ::args)))
(s/def ::line (s/alt :infix-line ::infix-line
:prefix-line ::prefix-line))
(s/def ::lines-seq (s/cat :constructor-lines (s/* ::constructor-line)
:body-lines (s/+ ::line)))
(s/fdef parse-nosence-lines :args ::lines-seq)
;; END OF SPEC
(defmulti parse-nosence
"Core function for parsing the nosencelang"
(fn [& args] (map class (take 1 args))))
(defmethod parse-nosence
[Symbol]
sym-k-args
[s1 k & args]
`(~(k infix-map) ~s1 ~@args))
(defmethod parse-nosence
[Keyword]
k-args
[k & args]
`(~(k prefix-map) ~@args))
(defmethod parse-nosence :default [x] x)
(defn bindings-from-new [lists]
(->> (for [[k constructor sym & args] lists
:when (= k new-k)]
`(~sym ~(construct-thing constructor (conj args sym))))
(apply concat)
(into [])))
(defn parse-nosence-lines-helper [lines]
(let [bindings (bindings-from-new lines)
lines (remove #(= new-k (first %)) lines)]
`(let ~bindings
~@(for [l lines]
(apply parse-nosence l)))))
(defmacro parse-nosence-lines
[& lines]
(parse-nosence-lines-helper lines))
;; (parse-nosence-lines
;; (:new Conversation c)
;; (:new Person <NAME>)
;; (<NAME> :in c)
;; (<NAME> :says "Hello")
;; (<NAME> :says "I hate this place!")
;; (<NAME> :quits)
;; (c))
| true |
(ns spec-examples.dsl-example
(:require [clojure.spec :as s]
[clojure.string :as str])
(:import [clojure.lang Keyword Symbol]))
(definterface IConversation
(getParticipants [])
(setParticipants [n])
(updateParticipants [f])
(getLines [])
(setLines [n])
(updateLines [f]))
(definterface IPerson
(getName [])
(getConversation [])
(setConversation [c]))
(deftype Conversation [^:volatile-mutable participants
^:volatile-mutable lines]
Object
(toString [this]
(str {:participants participants
:lines lines }))
IConversation
(getParticipants [this]
participants)
(setParticipants [this n]
(set! participants n))
(updateParticipants [this f]
(set! participants (f participants)))
(getLines [this]
lines)
(setLines [this n]
(set! lines n))
(updateLines [this f]
(set! lines (f lines))))
(deftype Person [name
^:volatile-mutable conv]
Object
(toString [this]
(str name))
IPerson
(getName [this]
name)
(getConversation [this]
conv)
(setConversation [this c]
(set! conv c)))
(defmethod print-method Conversation [x writer]
(.write writer (.toString x)))
(defmethod print-method Person [x writer]
(.write writer (str \" x \")))
(defmethod print-dup Conversation [x w]
(print-ctor x (fn [o w] (print-dup (str x) w))
w))
(defmethod print-dup Person [x w]
(print-ctor x (fn [o w] (print-dup ((str \" x \")) w))
w))
(defn conversation []
(Conversation. #{} []))
(defn person [name]
(Person. name nil))
(defmacro handle-get
[obj-sym field-sym]
(let [getter (str ".get" (-> field-sym str str/capitalize))]
(read-string (str "(" getter " " obj-sym ")"))))
(defn handle-return [x] x)
(defn add-participant
[who conversation]
(.updateParticipants conversation #(conj % who))
(.setConversation who conversation))
(defn say-something
[who what]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(.updateLines c #(conj % (str who "> "what))))))
(defn quit-conversation
[who]
(let [c (.getConversation who)]
(if (some #{who} (.getParticipants c))
(do (.updateParticipants c #(disj % who))
(.setConversation who nil)))))
(defn print-conversation
[conversation])
(def constructors-map
{'Conversation (fn [_] (conversation))
'Person #(person (str %))})
(defn construct-thing [constructor-s args]
`(apply ~(constructors-map constructor-s) '~args))
(def infix-map
{:joins `add-participant
:says `say-something
:quits `quit-conversation})
(def prefix-map
{:print `print
:print-line `println
:get `handle-get
:return `handle-return})
(def new-k :new)
;; SPEC
(s/def ::infix-keyword (s/and keyword? (set (keys infix-map))))
(s/def ::prefix-keyword (s/and keyword? (set (keys prefix-map))))
(s/def ::new-keyword (s/and keyword? #(= % new-k)))
(s/def ::constructor (s/and symbol? (set (keys constructors-map))))
(s/def ::args (s/* any?))
(s/def ::constructor-line (s/spec (s/cat :new-k ::new-keyword
:constructor ::constructor
:obj-symbol symbol?
:args ::args)))
(s/def ::infix-line (s/spec (s/cat :subject symbol?
:keyword ::infix-keyword
:args ::args)))
(s/def ::prefix-line (s/spec (s/cat :keyword ::prefix-keyword
:args ::args)))
(s/def ::line (s/alt :infix-line ::infix-line
:prefix-line ::prefix-line))
(s/def ::lines-seq (s/cat :constructor-lines (s/* ::constructor-line)
:body-lines (s/+ ::line)))
(s/fdef parse-nosence-lines :args ::lines-seq)
;; END OF SPEC
(defmulti parse-nosence
"Core function for parsing the nosencelang"
(fn [& args] (map class (take 1 args))))
(defmethod parse-nosence
[Symbol]
sym-k-args
[s1 k & args]
`(~(k infix-map) ~s1 ~@args))
(defmethod parse-nosence
[Keyword]
k-args
[k & args]
`(~(k prefix-map) ~@args))
(defmethod parse-nosence :default [x] x)
(defn bindings-from-new [lists]
(->> (for [[k constructor sym & args] lists
:when (= k new-k)]
`(~sym ~(construct-thing constructor (conj args sym))))
(apply concat)
(into [])))
(defn parse-nosence-lines-helper [lines]
(let [bindings (bindings-from-new lines)
lines (remove #(= new-k (first %)) lines)]
`(let ~bindings
~@(for [l lines]
(apply parse-nosence l)))))
(defmacro parse-nosence-lines
[& lines]
(parse-nosence-lines-helper lines))
;; (parse-nosence-lines
;; (:new Conversation c)
;; (:new Person PI:NAME:<NAME>END_PI)
;; (PI:NAME:<NAME>END_PI :in c)
;; (PI:NAME:<NAME>END_PI :says "Hello")
;; (PI:NAME:<NAME>END_PI :says "I hate this place!")
;; (PI:NAME:<NAME>END_PI :quits)
;; (c))
|
[
{
"context": "file is part of esri-api.\n;;;;\n;;;; Copyright 2020 Alexander Dorn\n;;;;\n;;;; Licensed under the Apache License, Vers",
"end": 75,
"score": 0.9998611211776733,
"start": 61,
"tag": "NAME",
"value": "Alexander Dorn"
}
] |
src/esri_api/data.clj
|
e-user/esri-api
| 0 |
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 Alexander Dorn
;;;;
;;;; 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 esri_api.data
"Data import and transformation"
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[java-time :refer [local-date-time]])
(:import [java.util Date]))
;;; Here, we are mostly concerned with importy raw CSV, transforming the input
;;; into native hash maps and tranforming relevant time stamps into
;;; corresponding Java objects we can use later.
(defn import-csv
"Import CSV resource"
([res]
(with-open [r (io/reader (io/resource res))]
(doall (csv/read-csv r))))
([] (import-csv "Adressen__Berlin.csv")))
(defn parse-date
"Parse date-time strings of the format `2008-01-28T00:00:00`"
[s]
(local-date-time (java-time.format/formatter :iso-local-date-time) s))
(defn csv-data->maps
"Transform raw CSV to hash maps
Also transform select data fields."
[csv-data]
(map (fn [keys vals]
(-> (zipmap keys vals)
(update :STR_DATUM (fn [v] (and v (parse-date v))))))
(->> (first csv-data)
(map keyword)
repeat)
(rest csv-data)))
(def csv
"Future of imported and transformed CSV data set"
(future (csv-data->maps (import-csv))))
|
109372
|
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 <NAME>
;;;;
;;;; Licensed under the Apache License, Version 2.0 (the "License");
;;;; you may not use this file except in compliance with the License.
;;;; You may obtain a copy of the License at
;;;;
;;;; http://www.apache.org/licenses/LICENSE-2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing, software
;;;; distributed under the License is distributed on an "AS IS" BASIS,
;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the License for the specific language governing permissions and
;;;; limitations under the License.
(ns esri_api.data
"Data import and transformation"
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[java-time :refer [local-date-time]])
(:import [java.util Date]))
;;; Here, we are mostly concerned with importy raw CSV, transforming the input
;;; into native hash maps and tranforming relevant time stamps into
;;; corresponding Java objects we can use later.
(defn import-csv
"Import CSV resource"
([res]
(with-open [r (io/reader (io/resource res))]
(doall (csv/read-csv r))))
([] (import-csv "Adressen__Berlin.csv")))
(defn parse-date
"Parse date-time strings of the format `2008-01-28T00:00:00`"
[s]
(local-date-time (java-time.format/formatter :iso-local-date-time) s))
(defn csv-data->maps
"Transform raw CSV to hash maps
Also transform select data fields."
[csv-data]
(map (fn [keys vals]
(-> (zipmap keys vals)
(update :STR_DATUM (fn [v] (and v (parse-date v))))))
(->> (first csv-data)
(map keyword)
repeat)
(rest csv-data)))
(def csv
"Future of imported and transformed CSV data set"
(future (csv-data->maps (import-csv))))
| true |
;;;; This file is part of esri-api.
;;;;
;;;; Copyright 2020 PI:NAME:<NAME>END_PI
;;;;
;;;; Licensed under the Apache License, Version 2.0 (the "License");
;;;; you may not use this file except in compliance with the License.
;;;; You may obtain a copy of the License at
;;;;
;;;; http://www.apache.org/licenses/LICENSE-2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing, software
;;;; distributed under the License is distributed on an "AS IS" BASIS,
;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the License for the specific language governing permissions and
;;;; limitations under the License.
(ns esri_api.data
"Data import and transformation"
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[java-time :refer [local-date-time]])
(:import [java.util Date]))
;;; Here, we are mostly concerned with importy raw CSV, transforming the input
;;; into native hash maps and tranforming relevant time stamps into
;;; corresponding Java objects we can use later.
(defn import-csv
"Import CSV resource"
([res]
(with-open [r (io/reader (io/resource res))]
(doall (csv/read-csv r))))
([] (import-csv "Adressen__Berlin.csv")))
(defn parse-date
"Parse date-time strings of the format `2008-01-28T00:00:00`"
[s]
(local-date-time (java-time.format/formatter :iso-local-date-time) s))
(defn csv-data->maps
"Transform raw CSV to hash maps
Also transform select data fields."
[csv-data]
(map (fn [keys vals]
(-> (zipmap keys vals)
(update :STR_DATUM (fn [v] (and v (parse-date v))))))
(->> (first csv-data)
(map keyword)
repeat)
(rest csv-data)))
(def csv
"Future of imported and transformed CSV data set"
(future (csv-data->maps (import-csv))))
|
[
{
"context": "]}]\n [[:button.btn.btn-sm.btn-default\n {:key (lib/get-unique-key)\n :onClick (fn [_]\n (lib/st",
"end": 4334,
"score": 0.6332843899726868,
"start": 4319,
"tag": "KEY",
"value": "lib/get-unique-"
},
{
"context": "on.btn.btn-sm.btn-default {:onClick #(auth/login \"Walter\" \"iamatestuser2016\")}\n \"Login as Wa",
"end": 5014,
"score": 0.6907758712768555,
"start": 5013,
"tag": "USERNAME",
"value": "W"
},
{
"context": "n-sm.btn-default {:onClick #(auth/login \"Walter\" \"iamatestuser2016\")}\n \"Login as Walter\"]]))))\n(def connect",
"end": 5038,
"score": 0.998059093952179,
"start": 5022,
"tag": "USERNAME",
"value": "iamatestuser2016"
}
] |
src/discuss/components/options.cljs
|
hhucn/discuss
| 4 |
(ns discuss.components.options
(:require [om.next :as om :refer-macros [defui]]
[cljs.spec.alpha :as s]
[sablono.core :refer-macros [html]]
[goog.string :refer [format]]
[goog.string.format]
[discuss.utils.bootstrap :as bs]
[discuss.translations :as translations :refer [translate] :rename {translate t}]
[discuss.communication.auth :as auth]
[discuss.utils.common :as lib]
[discuss.utils.views :as vlib]
[discuss.communication.connectivity :as comcon]
[discuss.config :as config]))
(declare HostDBAS HostEDEN ConnectivityStatus ConnectionBrowser Options)
(defn- language-button
"Create button to set language."
[[lang-keyword lang-verbose]]
(bs/button-default-sm #(lib/language-next! lang-keyword) lang-verbose))
;; -----------------------------------------------------------------------------
;; Set hosts
(defn- set-host-config [this title current-host default-host set-host reset-host delete-host]
(let [content (or (get (om/get-state this) :content) "")]
[:div
[:h5 title]
[:div.input-group
[:span.input-group-addon (t :options :new-route)]
[:input.form-control {:onChange #(om/update-state! this assoc :content (.. % -target -value))
:value (or content "")
:placeholder default-host}]]
[:div.input-group
[:span.input-group-addon (t :options :current)]
[:input.form-control {:value (or (current-host) "")
:disabled true}]]
[:div.input-group
[:span.input-group-addon (t :options :default)]
[:input.form-control {:value (or default-host "")
:disabled true}]]
[:button.btn.btn-sm.btn-default {:onClick #(set-host content)}
(t :options :save) " " title]
[:div.pull-right
[:button.btn.btn-sm.btn-warning
{:onClick delete-host
:style {:marginRight "0.5em"}}
(t :options :delete)]
[:button.btn.btn-sm.btn-warning
{:onClick reset-host}
(t :options :reset)]]]))
(s/fdef set-host-config
:args (s/cat :this any? :title string? :current-host string?
:default-host string? :set-host fn? :reset-host fn?))
(defui HostDBAS
static om/IQuery
(query [this]
`[:host/dbas :layout/lang])
Object
(render [this]
(html
(set-host-config this "D-BAS API" lib/host-dbas config/host-dbas lib/host-dbas! lib/host-dbas-reset! #(lib/host-dbas! nil)))))
(def host-dbas (om/factory HostDBAS))
(defui HostEDEN
static om/IQuery
(query [this]
`[:host/eden :layout/lang])
Object
(render [this]
(html
(set-host-config this "EDEN Search" lib/host-eden config/host-eden lib/host-eden! lib/host-eden-reset! #(lib/host-eden! nil)))))
(def host-eden (om/factory HostEDEN))
;; -----------------------------------------------------------------------------
;; Connectivity Information
(defn- connection-icon [status service host]
(let [[class icon msg]
(cond
(empty? host) ["" "fa-minus-square-o" "not configured"]
(true? status) ["text-success" "fa-circle" "connected"]
(false? status) ["text-danger" "fa-circle-o" "disconnected"]
:else ["text-warning" "fa-dot-circle-o" "connecting..."])]
[:div
[:span {:className class
:style {:padding-right "0.5em"}} (vlib/fa-icon icon)]
[:span (format "%s %s" service msg)]]))
(defui ConnectivityStatus
static om/IQuery
(query [this]
[:host/dbas-is-up? :host/eden-is-up?
:host/dbas :host/eden])
Object
(render [this]
(let [{:keys [host/dbas-is-up? host/eden-is-up? host/dbas host/eden]} (om/props this)]
(html [:div
[:h5 "Status"]
(connection-icon dbas-is-up? "D-BAS" dbas)
(connection-icon eden-is-up? "EDEN" eden)
[:br]
[:button.btn.btn-sm.btn-default {:onClick comcon/check-connectivity-of-hosts}
(t :options :reconnect)]]))))
(def connectivity-status (om/factory ConnectivityStatus))
;; -----------------------------------------------------------------------------
;; Demo Settings
(defn- build-connections [{:keys [name dbas eden]}]
[[:button.btn.btn-sm.btn-default
{:key (lib/get-unique-key)
:onClick (fn [_]
(lib/store-multiple-values-to-app-state!
[['host/dbas dbas]
['host/eden eden]])
(auth/logout))}
"Connect to " name]
" "])
(defui ConnectionBrowser
static om/IQuery
(query [this]
`[:layout/lang])
Object
(render [this]
(let [{:keys []} (om/props this)]
(html
[:div.text-center
(map build-connections config/demo-servers)
[:br] [:br]
[:button.btn.btn-sm.btn-default {:onClick #(lib/save-current-and-change-view! :options)}
"Custom Settings"] " "
[:button.btn.btn-sm.btn-default {:onClick #(auth/login "Walter" "iamatestuser2016")}
"Login as Walter"]]))))
(def connection-browser (om/factory ConnectionBrowser))
;; -----------------------------------------------------------------------------
;; Combine options
(defui Options
static om/IQuery
(query [this]
`[:layout/lang :discuss/experimental?
{:host/dbas ~(om/get-query HostDBAS)}
{:host/eden ~(om/get-query HostEDEN)}])
Object
(render [this]
(let [{:keys [discuss/experimental?]} (om/props this)]
(html
[:div
[:div (vlib/view-header (t :options :heading))
[:div.row
[:div.col-md-3 (vlib/fa-icon "fa-flag") (t :options :lang :space)]
[:div.col-md-9 (interpose " " (mapv language-button translations/available))]]]
(when experimental?
[:div
[:br]
[:hr]
[:h4.text-center "Connection Browser"]
(connection-browser (om/props this))
[:br]
[:hr]
[:h4.text-center "Connectivity"]
(connectivity-status (om/props this))
[:br]
[:hr]
[:h4.text-center (t :options :routes)]
(host-dbas (om/props this))
[:hr]
(host-eden (om/props this))])]))))
(def options (om/factory Options))
|
4848
|
(ns discuss.components.options
(:require [om.next :as om :refer-macros [defui]]
[cljs.spec.alpha :as s]
[sablono.core :refer-macros [html]]
[goog.string :refer [format]]
[goog.string.format]
[discuss.utils.bootstrap :as bs]
[discuss.translations :as translations :refer [translate] :rename {translate t}]
[discuss.communication.auth :as auth]
[discuss.utils.common :as lib]
[discuss.utils.views :as vlib]
[discuss.communication.connectivity :as comcon]
[discuss.config :as config]))
(declare HostDBAS HostEDEN ConnectivityStatus ConnectionBrowser Options)
(defn- language-button
"Create button to set language."
[[lang-keyword lang-verbose]]
(bs/button-default-sm #(lib/language-next! lang-keyword) lang-verbose))
;; -----------------------------------------------------------------------------
;; Set hosts
(defn- set-host-config [this title current-host default-host set-host reset-host delete-host]
(let [content (or (get (om/get-state this) :content) "")]
[:div
[:h5 title]
[:div.input-group
[:span.input-group-addon (t :options :new-route)]
[:input.form-control {:onChange #(om/update-state! this assoc :content (.. % -target -value))
:value (or content "")
:placeholder default-host}]]
[:div.input-group
[:span.input-group-addon (t :options :current)]
[:input.form-control {:value (or (current-host) "")
:disabled true}]]
[:div.input-group
[:span.input-group-addon (t :options :default)]
[:input.form-control {:value (or default-host "")
:disabled true}]]
[:button.btn.btn-sm.btn-default {:onClick #(set-host content)}
(t :options :save) " " title]
[:div.pull-right
[:button.btn.btn-sm.btn-warning
{:onClick delete-host
:style {:marginRight "0.5em"}}
(t :options :delete)]
[:button.btn.btn-sm.btn-warning
{:onClick reset-host}
(t :options :reset)]]]))
(s/fdef set-host-config
:args (s/cat :this any? :title string? :current-host string?
:default-host string? :set-host fn? :reset-host fn?))
(defui HostDBAS
static om/IQuery
(query [this]
`[:host/dbas :layout/lang])
Object
(render [this]
(html
(set-host-config this "D-BAS API" lib/host-dbas config/host-dbas lib/host-dbas! lib/host-dbas-reset! #(lib/host-dbas! nil)))))
(def host-dbas (om/factory HostDBAS))
(defui HostEDEN
static om/IQuery
(query [this]
`[:host/eden :layout/lang])
Object
(render [this]
(html
(set-host-config this "EDEN Search" lib/host-eden config/host-eden lib/host-eden! lib/host-eden-reset! #(lib/host-eden! nil)))))
(def host-eden (om/factory HostEDEN))
;; -----------------------------------------------------------------------------
;; Connectivity Information
(defn- connection-icon [status service host]
(let [[class icon msg]
(cond
(empty? host) ["" "fa-minus-square-o" "not configured"]
(true? status) ["text-success" "fa-circle" "connected"]
(false? status) ["text-danger" "fa-circle-o" "disconnected"]
:else ["text-warning" "fa-dot-circle-o" "connecting..."])]
[:div
[:span {:className class
:style {:padding-right "0.5em"}} (vlib/fa-icon icon)]
[:span (format "%s %s" service msg)]]))
(defui ConnectivityStatus
static om/IQuery
(query [this]
[:host/dbas-is-up? :host/eden-is-up?
:host/dbas :host/eden])
Object
(render [this]
(let [{:keys [host/dbas-is-up? host/eden-is-up? host/dbas host/eden]} (om/props this)]
(html [:div
[:h5 "Status"]
(connection-icon dbas-is-up? "D-BAS" dbas)
(connection-icon eden-is-up? "EDEN" eden)
[:br]
[:button.btn.btn-sm.btn-default {:onClick comcon/check-connectivity-of-hosts}
(t :options :reconnect)]]))))
(def connectivity-status (om/factory ConnectivityStatus))
;; -----------------------------------------------------------------------------
;; Demo Settings
(defn- build-connections [{:keys [name dbas eden]}]
[[:button.btn.btn-sm.btn-default
{:key (<KEY>key)
:onClick (fn [_]
(lib/store-multiple-values-to-app-state!
[['host/dbas dbas]
['host/eden eden]])
(auth/logout))}
"Connect to " name]
" "])
(defui ConnectionBrowser
static om/IQuery
(query [this]
`[:layout/lang])
Object
(render [this]
(let [{:keys []} (om/props this)]
(html
[:div.text-center
(map build-connections config/demo-servers)
[:br] [:br]
[:button.btn.btn-sm.btn-default {:onClick #(lib/save-current-and-change-view! :options)}
"Custom Settings"] " "
[:button.btn.btn-sm.btn-default {:onClick #(auth/login "Walter" "iamatestuser2016")}
"Login as Walter"]]))))
(def connection-browser (om/factory ConnectionBrowser))
;; -----------------------------------------------------------------------------
;; Combine options
(defui Options
static om/IQuery
(query [this]
`[:layout/lang :discuss/experimental?
{:host/dbas ~(om/get-query HostDBAS)}
{:host/eden ~(om/get-query HostEDEN)}])
Object
(render [this]
(let [{:keys [discuss/experimental?]} (om/props this)]
(html
[:div
[:div (vlib/view-header (t :options :heading))
[:div.row
[:div.col-md-3 (vlib/fa-icon "fa-flag") (t :options :lang :space)]
[:div.col-md-9 (interpose " " (mapv language-button translations/available))]]]
(when experimental?
[:div
[:br]
[:hr]
[:h4.text-center "Connection Browser"]
(connection-browser (om/props this))
[:br]
[:hr]
[:h4.text-center "Connectivity"]
(connectivity-status (om/props this))
[:br]
[:hr]
[:h4.text-center (t :options :routes)]
(host-dbas (om/props this))
[:hr]
(host-eden (om/props this))])]))))
(def options (om/factory Options))
| true |
(ns discuss.components.options
(:require [om.next :as om :refer-macros [defui]]
[cljs.spec.alpha :as s]
[sablono.core :refer-macros [html]]
[goog.string :refer [format]]
[goog.string.format]
[discuss.utils.bootstrap :as bs]
[discuss.translations :as translations :refer [translate] :rename {translate t}]
[discuss.communication.auth :as auth]
[discuss.utils.common :as lib]
[discuss.utils.views :as vlib]
[discuss.communication.connectivity :as comcon]
[discuss.config :as config]))
(declare HostDBAS HostEDEN ConnectivityStatus ConnectionBrowser Options)
(defn- language-button
"Create button to set language."
[[lang-keyword lang-verbose]]
(bs/button-default-sm #(lib/language-next! lang-keyword) lang-verbose))
;; -----------------------------------------------------------------------------
;; Set hosts
(defn- set-host-config [this title current-host default-host set-host reset-host delete-host]
(let [content (or (get (om/get-state this) :content) "")]
[:div
[:h5 title]
[:div.input-group
[:span.input-group-addon (t :options :new-route)]
[:input.form-control {:onChange #(om/update-state! this assoc :content (.. % -target -value))
:value (or content "")
:placeholder default-host}]]
[:div.input-group
[:span.input-group-addon (t :options :current)]
[:input.form-control {:value (or (current-host) "")
:disabled true}]]
[:div.input-group
[:span.input-group-addon (t :options :default)]
[:input.form-control {:value (or default-host "")
:disabled true}]]
[:button.btn.btn-sm.btn-default {:onClick #(set-host content)}
(t :options :save) " " title]
[:div.pull-right
[:button.btn.btn-sm.btn-warning
{:onClick delete-host
:style {:marginRight "0.5em"}}
(t :options :delete)]
[:button.btn.btn-sm.btn-warning
{:onClick reset-host}
(t :options :reset)]]]))
(s/fdef set-host-config
:args (s/cat :this any? :title string? :current-host string?
:default-host string? :set-host fn? :reset-host fn?))
(defui HostDBAS
static om/IQuery
(query [this]
`[:host/dbas :layout/lang])
Object
(render [this]
(html
(set-host-config this "D-BAS API" lib/host-dbas config/host-dbas lib/host-dbas! lib/host-dbas-reset! #(lib/host-dbas! nil)))))
(def host-dbas (om/factory HostDBAS))
(defui HostEDEN
static om/IQuery
(query [this]
`[:host/eden :layout/lang])
Object
(render [this]
(html
(set-host-config this "EDEN Search" lib/host-eden config/host-eden lib/host-eden! lib/host-eden-reset! #(lib/host-eden! nil)))))
(def host-eden (om/factory HostEDEN))
;; -----------------------------------------------------------------------------
;; Connectivity Information
(defn- connection-icon [status service host]
(let [[class icon msg]
(cond
(empty? host) ["" "fa-minus-square-o" "not configured"]
(true? status) ["text-success" "fa-circle" "connected"]
(false? status) ["text-danger" "fa-circle-o" "disconnected"]
:else ["text-warning" "fa-dot-circle-o" "connecting..."])]
[:div
[:span {:className class
:style {:padding-right "0.5em"}} (vlib/fa-icon icon)]
[:span (format "%s %s" service msg)]]))
(defui ConnectivityStatus
static om/IQuery
(query [this]
[:host/dbas-is-up? :host/eden-is-up?
:host/dbas :host/eden])
Object
(render [this]
(let [{:keys [host/dbas-is-up? host/eden-is-up? host/dbas host/eden]} (om/props this)]
(html [:div
[:h5 "Status"]
(connection-icon dbas-is-up? "D-BAS" dbas)
(connection-icon eden-is-up? "EDEN" eden)
[:br]
[:button.btn.btn-sm.btn-default {:onClick comcon/check-connectivity-of-hosts}
(t :options :reconnect)]]))))
(def connectivity-status (om/factory ConnectivityStatus))
;; -----------------------------------------------------------------------------
;; Demo Settings
(defn- build-connections [{:keys [name dbas eden]}]
[[:button.btn.btn-sm.btn-default
{:key (PI:KEY:<KEY>END_PIkey)
:onClick (fn [_]
(lib/store-multiple-values-to-app-state!
[['host/dbas dbas]
['host/eden eden]])
(auth/logout))}
"Connect to " name]
" "])
(defui ConnectionBrowser
static om/IQuery
(query [this]
`[:layout/lang])
Object
(render [this]
(let [{:keys []} (om/props this)]
(html
[:div.text-center
(map build-connections config/demo-servers)
[:br] [:br]
[:button.btn.btn-sm.btn-default {:onClick #(lib/save-current-and-change-view! :options)}
"Custom Settings"] " "
[:button.btn.btn-sm.btn-default {:onClick #(auth/login "Walter" "iamatestuser2016")}
"Login as Walter"]]))))
(def connection-browser (om/factory ConnectionBrowser))
;; -----------------------------------------------------------------------------
;; Combine options
(defui Options
static om/IQuery
(query [this]
`[:layout/lang :discuss/experimental?
{:host/dbas ~(om/get-query HostDBAS)}
{:host/eden ~(om/get-query HostEDEN)}])
Object
(render [this]
(let [{:keys [discuss/experimental?]} (om/props this)]
(html
[:div
[:div (vlib/view-header (t :options :heading))
[:div.row
[:div.col-md-3 (vlib/fa-icon "fa-flag") (t :options :lang :space)]
[:div.col-md-9 (interpose " " (mapv language-button translations/available))]]]
(when experimental?
[:div
[:br]
[:hr]
[:h4.text-center "Connection Browser"]
(connection-browser (om/props this))
[:br]
[:hr]
[:h4.text-center "Connectivity"]
(connectivity-status (om/props this))
[:br]
[:hr]
[:h4.text-center (t :options :routes)]
(host-dbas (om/props this))
[:hr]
(host-eden (om/props this))])]))))
(def options (om/factory Options))
|
[
{
"context": "service\n {:id \"namer\"}}\n :subject\n {:name \"Herman Melville\"\n :id \"42bf351c-f9ec-40af-84ad-e976fec7f4bd\"}\n",
"end": 990,
"score": 0.9987367987632751,
"start": 975,
"tag": "NAME",
"value": "Herman Melville"
},
{
"context": "-40af-84ad-e976fec7f4bd\"}\n :objects\n [{:name \"Herman Aldrich\"\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177caac32\"\n",
"end": 1078,
"score": 0.9998849630355835,
"start": 1064,
"tag": "NAME",
"value": "Herman Aldrich"
},
{
"context": "-084177caac32\"\n :type \"a Herman\"}\n {:name \"Herman Miller\",\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177caac33\"",
"end": 1176,
"score": 0.9998812675476074,
"start": 1163,
"tag": "NAME",
"value": "Herman Miller"
},
{
"context": "084177caac33\",\n :type \"a Herman\"}\n {:name \"Herman Stump\",\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177caac34\"",
"end": 1275,
"score": 0.9998855590820312,
"start": 1263,
"tag": "NAME",
"value": "Herman Stump"
},
{
"context": "084177caac34\",\n :type \"a Herman\"}\n {:name \"Herman W. Hellman\",\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177caac35\"",
"end": 1379,
"score": 0.9998754858970642,
"start": 1362,
"tag": "NAME",
"value": "Herman W. Hellman"
},
{
"context": "service\n {:id \"namer\"}}\n :subject\n {:name \"Herman Melville\"\n :id \"42bf351c-f9ec-40af-84ad-e976fec7f4bd\"}\n",
"end": 1585,
"score": 0.9998219013214111,
"start": 1570,
"tag": "NAME",
"value": "Herman Melville"
},
{
"context": "-f9ec-40af-84ad-e976fec7f4bd\"}\n :object {:name \"Herman Aldrich\"\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177c",
"end": 1668,
"score": 0.9998863339424133,
"start": 1654,
"tag": "NAME",
"value": "Herman Aldrich"
},
{
"context": "service\n {:id \"namer\"}}\n :subject\n {:name \"Herman Melville\"\n :id \"42bf351c-f9ec-40af-84ad-e976fec7f4bd\"}\n",
"end": 1863,
"score": 0.9998452067375183,
"start": 1848,
"tag": "NAME",
"value": "Herman Melville"
},
{
"context": "ec-40af-84ad-e976fec7f4bd\"}\n :object\n {:name \"Herman Aldrich\"\n :id \"2d5d4e0b-5353-4bbd-9c4c-084177caac32\"\n ",
"end": 1949,
"score": 0.9998825192451477,
"start": 1935,
"tag": "NAME",
"value": "Herman Aldrich"
},
{
"context": "service\n {:id \"namer\"}}\n :subject\n {:name \"Herman Melville\"\n :id \"42bf351c-f9ec-40af-84ad-e976fec7f4bd\"}\n",
"end": 2137,
"score": 0.9998663663864136,
"start": 2122,
"tag": "NAME",
"value": "Herman Melville"
},
{
"context": "9ec-40af-84ad-e976fec7f4bd\"}\n :objects [{:name \"Herman Aldrich\"\n :id \"2d5d4e0b-5353-4bbd-9c4c-08417",
"end": 2222,
"score": 0.9998809099197388,
"start": 2208,
"tag": "NAME",
"value": "Herman Aldrich"
}
] |
test/puppetlabs/rbac_client/services/test_activity.clj
|
mollykmcglone/clj-rbac-client
| 0 |
(ns puppetlabs.rbac-client.services.test-activity
(:require [cheshire.core :as json]
[clojure.test :refer [deftest testing is]]
[puppetlabs.rbac-client.protocols.activity :as act]
[puppetlabs.rbac-client.services.activity :refer [remote-activity-reporter]]
[puppetlabs.rbac-client.testutils.config :as cfg]
[puppetlabs.rbac-client.testutils.http :as http]
[puppetlabs.trapperkeeper.app :as tk-app]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]
[puppetlabs.trapperkeeper.testutils.webserver :refer [with-test-webserver-and-config]]))
(def ^:private configs
(let [server-cfg (cfg/jetty-ssl-config)]
{:server server-cfg
:client (cfg/rbac-client-config server-cfg)}))
(defn- wrap-test-handler-middleware
[handler]
(http/wrap-test-handler-mw handler))
(def v2-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "Herman Melville"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects
[{:name "Herman Aldrich"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}
{:name "Herman Miller",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac33",
:type "a Herman"}
{:name "Herman Stump",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac34",
:type "a Herman"}
{:name "Herman W. Hellman",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac35",
:type "a Herman"}]
:ip-address "an ip address"})
(def v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "Herman Melville"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object {:name "Herman Aldrich"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "Herman Melville"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object
{:name "Herman Aldrich"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-upgraded-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "Herman Melville"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects [{:name "Herman Aldrich"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}]})
(deftest test-activity
(with-app-with-config tk-app [remote-activity-reporter] (:client configs)
(let [consumer-svc (tk-app/get-service tk-app :ActivityReportingService)
handler (wrap-test-handler-middleware
(fn [req]
(if (= "/activity-api/v2/events" (:uri req))
(let [parsed-body (json/parse-string (:body req) true)]
(is (or (= v2-bundle parsed-body) (= expected-v1-upgraded-bundle parsed-body)))
;; provide a payload for testability. Actual service doesn't guarantee providing return results
(http/json-200-resp {:success true :actual (:body req)}))
(is false))))
v1-handler (wrap-test-handler-middleware
(fn [req]
(case (:uri req)
"/activity-api/v2/events" (http/json-resp 404 {:success false})
"/activity-api/v1/events" (http/json-200-resp {:success true :actual (:body req)}))))]
(testing "v2 endpoint supported with passthrough"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= v2-bundle (json/parse-string (get-in result [:body :actual]) true))))))
(testing "upgrades to v2 payload when v1 payload is submitted"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v1-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-upgraded-bundle (json/parse-string (get-in result [:body :actual]) true))))))
;; note that after this test is done, if any more tests are added,
;; the client will have stored that the v2 endpoint isn't available internally, and
;; will use the v1 endpoint. If this is undesirable, a new "with-app-with-config" should be created.
(testing "downgrades to v1 endpoint when v2 is a 404"
(with-test-webserver-and-config v1-handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-bundle (json/parse-string (get-in result [:body :actual]) true)))))))))
|
11413
|
(ns puppetlabs.rbac-client.services.test-activity
(:require [cheshire.core :as json]
[clojure.test :refer [deftest testing is]]
[puppetlabs.rbac-client.protocols.activity :as act]
[puppetlabs.rbac-client.services.activity :refer [remote-activity-reporter]]
[puppetlabs.rbac-client.testutils.config :as cfg]
[puppetlabs.rbac-client.testutils.http :as http]
[puppetlabs.trapperkeeper.app :as tk-app]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]
[puppetlabs.trapperkeeper.testutils.webserver :refer [with-test-webserver-and-config]]))
(def ^:private configs
(let [server-cfg (cfg/jetty-ssl-config)]
{:server server-cfg
:client (cfg/rbac-client-config server-cfg)}))
(defn- wrap-test-handler-middleware
[handler]
(http/wrap-test-handler-mw handler))
(def v2-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "<NAME>"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects
[{:name "<NAME>"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}
{:name "<NAME>",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac33",
:type "a Herman"}
{:name "<NAME>",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac34",
:type "a Herman"}
{:name "<NAME>",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac35",
:type "a Herman"}]
:ip-address "an ip address"})
(def v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "<NAME>"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object {:name "<NAME>"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "<NAME>"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object
{:name "<NAME>"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-upgraded-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "<NAME>"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects [{:name "<NAME>"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}]})
(deftest test-activity
(with-app-with-config tk-app [remote-activity-reporter] (:client configs)
(let [consumer-svc (tk-app/get-service tk-app :ActivityReportingService)
handler (wrap-test-handler-middleware
(fn [req]
(if (= "/activity-api/v2/events" (:uri req))
(let [parsed-body (json/parse-string (:body req) true)]
(is (or (= v2-bundle parsed-body) (= expected-v1-upgraded-bundle parsed-body)))
;; provide a payload for testability. Actual service doesn't guarantee providing return results
(http/json-200-resp {:success true :actual (:body req)}))
(is false))))
v1-handler (wrap-test-handler-middleware
(fn [req]
(case (:uri req)
"/activity-api/v2/events" (http/json-resp 404 {:success false})
"/activity-api/v1/events" (http/json-200-resp {:success true :actual (:body req)}))))]
(testing "v2 endpoint supported with passthrough"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= v2-bundle (json/parse-string (get-in result [:body :actual]) true))))))
(testing "upgrades to v2 payload when v1 payload is submitted"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v1-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-upgraded-bundle (json/parse-string (get-in result [:body :actual]) true))))))
;; note that after this test is done, if any more tests are added,
;; the client will have stored that the v2 endpoint isn't available internally, and
;; will use the v1 endpoint. If this is undesirable, a new "with-app-with-config" should be created.
(testing "downgrades to v1 endpoint when v2 is a 404"
(with-test-webserver-and-config v1-handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-bundle (json/parse-string (get-in result [:body :actual]) true)))))))))
| true |
(ns puppetlabs.rbac-client.services.test-activity
(:require [cheshire.core :as json]
[clojure.test :refer [deftest testing is]]
[puppetlabs.rbac-client.protocols.activity :as act]
[puppetlabs.rbac-client.services.activity :refer [remote-activity-reporter]]
[puppetlabs.rbac-client.testutils.config :as cfg]
[puppetlabs.rbac-client.testutils.http :as http]
[puppetlabs.trapperkeeper.app :as tk-app]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]
[puppetlabs.trapperkeeper.testutils.webserver :refer [with-test-webserver-and-config]]))
(def ^:private configs
(let [server-cfg (cfg/jetty-ssl-config)]
{:server server-cfg
:client (cfg/rbac-client-config server-cfg)}))
(defn- wrap-test-handler-middleware
[handler]
(http/wrap-test-handler-mw handler))
(def v2-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "PI:NAME:<NAME>END_PI"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects
[{:name "PI:NAME:<NAME>END_PI"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}
{:name "PI:NAME:<NAME>END_PI",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac33",
:type "a Herman"}
{:name "PI:NAME:<NAME>END_PI",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac34",
:type "a Herman"}
{:name "PI:NAME:<NAME>END_PI",
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac35",
:type "a Herman"}]
:ip-address "an ip address"})
(def v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "PI:NAME:<NAME>END_PI"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object {:name "PI:NAME:<NAME>END_PI"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "PI:NAME:<NAME>END_PI"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:object
{:name "PI:NAME:<NAME>END_PI"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}})
(def expected-v1-upgraded-bundle
{:commit
{:service
{:id "namer"}}
:subject
{:name "PI:NAME:<NAME>END_PI"
:id "42bf351c-f9ec-40af-84ad-e976fec7f4bd"}
:objects [{:name "PI:NAME:<NAME>END_PI"
:id "2d5d4e0b-5353-4bbd-9c4c-084177caac32"
:type "a Herman"}]})
(deftest test-activity
(with-app-with-config tk-app [remote-activity-reporter] (:client configs)
(let [consumer-svc (tk-app/get-service tk-app :ActivityReportingService)
handler (wrap-test-handler-middleware
(fn [req]
(if (= "/activity-api/v2/events" (:uri req))
(let [parsed-body (json/parse-string (:body req) true)]
(is (or (= v2-bundle parsed-body) (= expected-v1-upgraded-bundle parsed-body)))
;; provide a payload for testability. Actual service doesn't guarantee providing return results
(http/json-200-resp {:success true :actual (:body req)}))
(is false))))
v1-handler (wrap-test-handler-middleware
(fn [req]
(case (:uri req)
"/activity-api/v2/events" (http/json-resp 404 {:success false})
"/activity-api/v1/events" (http/json-200-resp {:success true :actual (:body req)}))))]
(testing "v2 endpoint supported with passthrough"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= v2-bundle (json/parse-string (get-in result [:body :actual]) true))))))
(testing "upgrades to v2 payload when v1 payload is submitted"
(with-test-webserver-and-config handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v1-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-upgraded-bundle (json/parse-string (get-in result [:body :actual]) true))))))
;; note that after this test is done, if any more tests are added,
;; the client will have stored that the v2 endpoint isn't available internally, and
;; will use the v1 endpoint. If this is undesirable, a new "with-app-with-config" should be created.
(testing "downgrades to v1 endpoint when v2 is a 404"
(with-test-webserver-and-config v1-handler _ (:server configs)
(let [result (act/report-activity! consumer-svc v2-bundle)]
(is (= 200 (:status result)))
(is (= true (get-in result [:body :success])))
(is (= expected-v1-bundle (json/parse-string (get-in result [:body :actual]) true)))))))))
|
[
{
"context": "eftest service-translations-test\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [data (-> (req",
"end": 299,
"score": 0.998637855052948,
"start": 297,
"tag": "KEY",
"value": "42"
},
{
"context": "ations-test\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [data (-> (request :get \"/api/translat",
"end": 323,
"score": 0.9989316463470459,
"start": 318,
"tag": "USERNAME",
"value": "alice"
}
] |
test/clj/rems/api/test_public.clj
|
juholehtonen/rems
| 0 |
(ns ^:integration rems.api.test-public
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.handler :refer :all]
[ring.mock.request :refer :all]))
(use-fixtures
:once
api-fixture)
(deftest service-translations-test
(let [api-key "42"
user-id "alice"]
(let [data (-> (request :get "/api/translations")
(authenticate api-key user-id)
handler
read-body)
languages (keys data)]
(is (= [:en :fi] (sort languages))))))
(deftest test-config-api-smoke
(let [config (-> (request :get "/api/config")
handler
read-ok-body)]
(is (true? (:dev config)))))
|
116175
|
(ns ^:integration rems.api.test-public
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.handler :refer :all]
[ring.mock.request :refer :all]))
(use-fixtures
:once
api-fixture)
(deftest service-translations-test
(let [api-key "<KEY>"
user-id "alice"]
(let [data (-> (request :get "/api/translations")
(authenticate api-key user-id)
handler
read-body)
languages (keys data)]
(is (= [:en :fi] (sort languages))))))
(deftest test-config-api-smoke
(let [config (-> (request :get "/api/config")
handler
read-ok-body)]
(is (true? (:dev config)))))
| true |
(ns ^:integration rems.api.test-public
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.handler :refer :all]
[ring.mock.request :refer :all]))
(use-fixtures
:once
api-fixture)
(deftest service-translations-test
(let [api-key "PI:KEY:<KEY>END_PI"
user-id "alice"]
(let [data (-> (request :get "/api/translations")
(authenticate api-key user-id)
handler
read-body)
languages (keys data)]
(is (= [:en :fi] (sort languages))))))
(deftest test-config-api-smoke
(let [config (-> (request :get "/api/config")
handler
read-ok-body)]
(is (true? (:dev config)))))
|
[
{
"context": "itors. I'm using\n;; [vim-iced](https://github.com/liquidz/vim-iced).\n\n\n;; ## Introduction\n;;\n;; This is jus",
"end": 696,
"score": 0.9988332986831665,
"start": 689,
"tag": "USERNAME",
"value": "liquidz"
},
{
"context": " the result of an API call):\n\n(map :name [{:name \"Yannick\"} {:name \"Luke\"} {:name \"Leia\"}])\n\n;; Maps themse",
"end": 6923,
"score": 0.999847948551178,
"start": 6916,
"tag": "NAME",
"value": "Yannick"
},
{
"context": "API call):\n\n(map :name [{:name \"Yannick\"} {:name \"Luke\"} {:name \"Leia\"}])\n\n;; Maps themselves? Also func",
"end": 6938,
"score": 0.9998186230659485,
"start": 6934,
"tag": "NAME",
"value": "Luke"
},
{
"context": "p :name [{:name \"Yannick\"} {:name \"Luke\"} {:name \"Leia\"}])\n\n;; Maps themselves? Also functions:\n\n(name->",
"end": 6953,
"score": 0.9997894763946533,
"start": 6949,
"tag": "NAME",
"value": "Leia"
}
] |
src/playground/01_intro.clj
|
xsc/clojure-propaganda
| 1 |
(ns playground.01-intro
(:require [clojure.repl :refer [doc source]]))
;; ## REPL = Read Eval Print Loop
;;
;; - Read - Parse the expression
;; - Eval - Evaluate to get a result value
;; - Print - Print it back to the console
;; - Loop - Back to the beginning.
;;
;; There is real power in connecting your editor to the REPL! You are
;; no longer switching between windows or splits, you're not restarting
;; anything, just getting results inline.
;;
;; Programming becomes more of a conversation:
;;
;; - "What does this result in?"
;; - "Does this work?"
;; - "How about this?"
;;
;; There are Clojure integrations/plugins for many editors. I'm using
;; [vim-iced](https://github.com/liquidz/vim-iced).
;; ## Introduction
;;
;; This is just a very, very basic introduction to parts of the language. Let's
;; take away the shock of seeing parentheses or operators in weird places.
;;
;; Afterwards, we can decide what's worth exploring next, when we're able to
;; focus on the problem and are no longer distracted by syntax.
;; ### Basic Data Types
;;
;; These evaluate to themselves.
1 ;; integers
1.0 ;; doubles
3/8 ;; ratios
"str" ;; strings
:one ;; keywords
'one ;; symbols
true ;; boolean
nil ;; null
;; You'll rarely use symbols, I'd say, but you'll see keywords everywhere. They
;; are Clojure's first choice when it comes to representing elements of a fixed
;; set of symbolic values. Think: enums, map keys, etc...
;;
;; Note that there are more numeric types - but we'll cross that bridge if ever
;; necessary.
;; ### Functions
;;
;; Here are the _operators in weird places_ I've mentioned. When Clojure sees
;; a _form_ with parentheses it will consider its first element the operator,
;; and everything else operands/parameters.
;;
;; For example, simple multiplication will look like this:
(* 3 2)
;; Note that, because my editor is connected to the REPL, I can get the result
;; of that form right here, and instantly. (It should be `6`, in case you are
;; wondering.)
;;
;; Now, since I'm doubling numbers a lot in my line of work, I think it's worth
;; giving a name to this piece of logic:
(defn make-realistic
[estimate]
(* estimate 2))
;; Again, `defn` will be considered the protagonist/operator of this form. There
;; is something special about it - it's a macro - but this is a topic for
;; another day. For now, it's enough to know that this defines a function
;;`make-realistic` that has one parameter named `estimate`, and a function body
;; consisting of the aforementioned doubling operation.
(make-realistic 3)
;; There is no `return` in Clojure - the last value of the chosen code path is
;; what is returned. Consider a similar function:
(defn make-realistic-but-trust-estimate-for-easy-tasks
[estimate]
(if (<= estimate 2)
estimate
(* estimate 2)))
(make-realistic-but-trust-estimate-for-easy-tasks 2)
(make-realistic-but-trust-estimate-for-easy-tasks 5)
;; Here, we can end up in one of two code paths, which both will return the
;; value of their last (and only) expression. Basically, any `if` in Clojure
;; behaves like the ternary operator: `x <= 2 ? x : x * 2`.
;;
;; Speaking of conditionals, there are specialized versions, like `if-not` and
;; `when` and `when-not`, as well as syntactic sugar for literal matches
;; (`case`) or more than two paths (`cond`, `condp`). I recommend you check out
;; their documentation, especially if you realise you're nesting `if`-statements
;; a lot.
;;
;; By the way, most editor integrations will allow you to access a functions
;; docstring inline - e.g. in vim-iced it's done by pressing `K` while the
;; cursor is over the symbol in question - which will rely again on the REPL
;; and the following function:
(doc cond)
;; You could even peek at the source code:
(source cond)
;; Anyways, we got side-tracked. Let's get back to what is the core of Clojure:
;; data.
;; ### Sequences
;;
;; There are three main sequence types, in order of popularity:
[1 2 3] ;; vectors
#{1 2 3} ;; sets
(list 1 2 3) ;; lists (you rarely use them explicitly, tbh)
;; (There is also maps - key/value pairs - but that's discussed in the next
;; section.)
;;
;; There are tons and tons of sequence functions, for example for inspection:
(first #{1 2 3})
(rest [1 2 3])
(nth [1 2 3] 2)
;; Or for manipulation:
(def data [1 2 3 4 5]) ;; Hey, look, a variable!
(cons 0 data) ;; always prepends to the front
(conj data 6) ;; depends on the sequence! (vector -> append, list -> prepend)
;; And the crown jewel: SEQUENCE. ITERATION. FUNCTIONS.
(filter odd? data) ;; only keep matching elements
(remove odd? data) ;; remove all matching elements
(map inc data) ;; apply a function to every element
;; Stop the presses! Have a look at the original `data` variable:
data
;; It has not changed - which is because of the _immutability_ of Clojure's data
;; structures: Every operation will create a new sequence and leave the inputs
;; untouched. It will go about it in a smart way and share common values rather
;; than doing a deep copy of the input, but you never run the risk of changing
;; something you don't want to change.
;;
;; Resume the presses!
(reduce + data) ;; classic fold operation
(reduce + 5 data) ;; classic fold operation, initial value for the accumulator
(reduce
(fn [acc x] ;; Hey, look, an anonymous function!
(+ acc (* x x))) ;; A nested function call, meaning: acc + x^2
0
data)
;; Clojure can get concise if it wants to. Or code-golfy, depending on your
;; stance. This is the same as above, with syntactic sugar for anonymous
;; functions (`%1` = first parameter, `%2` = second parameter, ...):
(reduce #(+ %1 (* %2 %2)) 0 data)
;; I'd suggest to only use this form when there is only one parameter. In which
;; case you can use `%` instead of `%1`. For example:
(map #(+ % 5) data)
;; Utilities galore, btw. If you want to do something with a sequence, chances
;; are that Clojure has a function for it:
(take 2 data)
(drop 2 data)
(drop-while odd? data)
(take-while odd? data)
(split-at 2 data)
(partition 2 data)
(partition-all 2 data)
(frequencies data)
;; And so. Many. More.
;; ### Maps
;;
;; Key/value pairs, objects, hash maps, etc... You know this kind of data
;; structure:
{:a "a", :b "b"} ;; We tend to use keywords for map keys
{"a" 1, "b" 2} ;; but we don't have to.
;; Get and put are, well, get and assoc in Clojure:
(def name->number {:one 1, :two 2, :three 3})
(get name->number :two)
(assoc name->number :four 4)
;; Without stopping the presses this time, you'll see that the original map has
;; not changed. Immutability is to blame/thank.
;;
;; Keywords are functions, btw, so there is a nice-looking way to lookup values:
(:two name->number)
;; This is, for one example, very useful to concisely get nested values (e.g.
;; from the result of an API call):
(map :name [{:name "Yannick"} {:name "Luke"} {:name "Leia"}])
;; Maps themselves? Also functions:
(name->number :two)
(map name->number [:one :one :two])
;; If you want to rip a map apart (you monster) this is how:
(keys name->number)
(vals name->number)
;; Finally, maps can be considered a sequence of key and value pairs, which
;; means that all the sequence iteration functions we looked at above will
;; work on maps too:
(seq name->number) ;; converts map to seq (usually done automatically)
(map first name->number) ;; similar to `keys`
(filter
(comp even? second) ;; Hey, look, function composition!
name->number)
;; Enough, now. This should make you a bit more comfortable when looking
;; at Clojure code. There is still a lot more to discover.
|
112671
|
(ns playground.01-intro
(:require [clojure.repl :refer [doc source]]))
;; ## REPL = Read Eval Print Loop
;;
;; - Read - Parse the expression
;; - Eval - Evaluate to get a result value
;; - Print - Print it back to the console
;; - Loop - Back to the beginning.
;;
;; There is real power in connecting your editor to the REPL! You are
;; no longer switching between windows or splits, you're not restarting
;; anything, just getting results inline.
;;
;; Programming becomes more of a conversation:
;;
;; - "What does this result in?"
;; - "Does this work?"
;; - "How about this?"
;;
;; There are Clojure integrations/plugins for many editors. I'm using
;; [vim-iced](https://github.com/liquidz/vim-iced).
;; ## Introduction
;;
;; This is just a very, very basic introduction to parts of the language. Let's
;; take away the shock of seeing parentheses or operators in weird places.
;;
;; Afterwards, we can decide what's worth exploring next, when we're able to
;; focus on the problem and are no longer distracted by syntax.
;; ### Basic Data Types
;;
;; These evaluate to themselves.
1 ;; integers
1.0 ;; doubles
3/8 ;; ratios
"str" ;; strings
:one ;; keywords
'one ;; symbols
true ;; boolean
nil ;; null
;; You'll rarely use symbols, I'd say, but you'll see keywords everywhere. They
;; are Clojure's first choice when it comes to representing elements of a fixed
;; set of symbolic values. Think: enums, map keys, etc...
;;
;; Note that there are more numeric types - but we'll cross that bridge if ever
;; necessary.
;; ### Functions
;;
;; Here are the _operators in weird places_ I've mentioned. When Clojure sees
;; a _form_ with parentheses it will consider its first element the operator,
;; and everything else operands/parameters.
;;
;; For example, simple multiplication will look like this:
(* 3 2)
;; Note that, because my editor is connected to the REPL, I can get the result
;; of that form right here, and instantly. (It should be `6`, in case you are
;; wondering.)
;;
;; Now, since I'm doubling numbers a lot in my line of work, I think it's worth
;; giving a name to this piece of logic:
(defn make-realistic
[estimate]
(* estimate 2))
;; Again, `defn` will be considered the protagonist/operator of this form. There
;; is something special about it - it's a macro - but this is a topic for
;; another day. For now, it's enough to know that this defines a function
;;`make-realistic` that has one parameter named `estimate`, and a function body
;; consisting of the aforementioned doubling operation.
(make-realistic 3)
;; There is no `return` in Clojure - the last value of the chosen code path is
;; what is returned. Consider a similar function:
(defn make-realistic-but-trust-estimate-for-easy-tasks
[estimate]
(if (<= estimate 2)
estimate
(* estimate 2)))
(make-realistic-but-trust-estimate-for-easy-tasks 2)
(make-realistic-but-trust-estimate-for-easy-tasks 5)
;; Here, we can end up in one of two code paths, which both will return the
;; value of their last (and only) expression. Basically, any `if` in Clojure
;; behaves like the ternary operator: `x <= 2 ? x : x * 2`.
;;
;; Speaking of conditionals, there are specialized versions, like `if-not` and
;; `when` and `when-not`, as well as syntactic sugar for literal matches
;; (`case`) or more than two paths (`cond`, `condp`). I recommend you check out
;; their documentation, especially if you realise you're nesting `if`-statements
;; a lot.
;;
;; By the way, most editor integrations will allow you to access a functions
;; docstring inline - e.g. in vim-iced it's done by pressing `K` while the
;; cursor is over the symbol in question - which will rely again on the REPL
;; and the following function:
(doc cond)
;; You could even peek at the source code:
(source cond)
;; Anyways, we got side-tracked. Let's get back to what is the core of Clojure:
;; data.
;; ### Sequences
;;
;; There are three main sequence types, in order of popularity:
[1 2 3] ;; vectors
#{1 2 3} ;; sets
(list 1 2 3) ;; lists (you rarely use them explicitly, tbh)
;; (There is also maps - key/value pairs - but that's discussed in the next
;; section.)
;;
;; There are tons and tons of sequence functions, for example for inspection:
(first #{1 2 3})
(rest [1 2 3])
(nth [1 2 3] 2)
;; Or for manipulation:
(def data [1 2 3 4 5]) ;; Hey, look, a variable!
(cons 0 data) ;; always prepends to the front
(conj data 6) ;; depends on the sequence! (vector -> append, list -> prepend)
;; And the crown jewel: SEQUENCE. ITERATION. FUNCTIONS.
(filter odd? data) ;; only keep matching elements
(remove odd? data) ;; remove all matching elements
(map inc data) ;; apply a function to every element
;; Stop the presses! Have a look at the original `data` variable:
data
;; It has not changed - which is because of the _immutability_ of Clojure's data
;; structures: Every operation will create a new sequence and leave the inputs
;; untouched. It will go about it in a smart way and share common values rather
;; than doing a deep copy of the input, but you never run the risk of changing
;; something you don't want to change.
;;
;; Resume the presses!
(reduce + data) ;; classic fold operation
(reduce + 5 data) ;; classic fold operation, initial value for the accumulator
(reduce
(fn [acc x] ;; Hey, look, an anonymous function!
(+ acc (* x x))) ;; A nested function call, meaning: acc + x^2
0
data)
;; Clojure can get concise if it wants to. Or code-golfy, depending on your
;; stance. This is the same as above, with syntactic sugar for anonymous
;; functions (`%1` = first parameter, `%2` = second parameter, ...):
(reduce #(+ %1 (* %2 %2)) 0 data)
;; I'd suggest to only use this form when there is only one parameter. In which
;; case you can use `%` instead of `%1`. For example:
(map #(+ % 5) data)
;; Utilities galore, btw. If you want to do something with a sequence, chances
;; are that Clojure has a function for it:
(take 2 data)
(drop 2 data)
(drop-while odd? data)
(take-while odd? data)
(split-at 2 data)
(partition 2 data)
(partition-all 2 data)
(frequencies data)
;; And so. Many. More.
;; ### Maps
;;
;; Key/value pairs, objects, hash maps, etc... You know this kind of data
;; structure:
{:a "a", :b "b"} ;; We tend to use keywords for map keys
{"a" 1, "b" 2} ;; but we don't have to.
;; Get and put are, well, get and assoc in Clojure:
(def name->number {:one 1, :two 2, :three 3})
(get name->number :two)
(assoc name->number :four 4)
;; Without stopping the presses this time, you'll see that the original map has
;; not changed. Immutability is to blame/thank.
;;
;; Keywords are functions, btw, so there is a nice-looking way to lookup values:
(:two name->number)
;; This is, for one example, very useful to concisely get nested values (e.g.
;; from the result of an API call):
(map :name [{:name "<NAME>"} {:name "<NAME>"} {:name "<NAME>"}])
;; Maps themselves? Also functions:
(name->number :two)
(map name->number [:one :one :two])
;; If you want to rip a map apart (you monster) this is how:
(keys name->number)
(vals name->number)
;; Finally, maps can be considered a sequence of key and value pairs, which
;; means that all the sequence iteration functions we looked at above will
;; work on maps too:
(seq name->number) ;; converts map to seq (usually done automatically)
(map first name->number) ;; similar to `keys`
(filter
(comp even? second) ;; Hey, look, function composition!
name->number)
;; Enough, now. This should make you a bit more comfortable when looking
;; at Clojure code. There is still a lot more to discover.
| true |
(ns playground.01-intro
(:require [clojure.repl :refer [doc source]]))
;; ## REPL = Read Eval Print Loop
;;
;; - Read - Parse the expression
;; - Eval - Evaluate to get a result value
;; - Print - Print it back to the console
;; - Loop - Back to the beginning.
;;
;; There is real power in connecting your editor to the REPL! You are
;; no longer switching between windows or splits, you're not restarting
;; anything, just getting results inline.
;;
;; Programming becomes more of a conversation:
;;
;; - "What does this result in?"
;; - "Does this work?"
;; - "How about this?"
;;
;; There are Clojure integrations/plugins for many editors. I'm using
;; [vim-iced](https://github.com/liquidz/vim-iced).
;; ## Introduction
;;
;; This is just a very, very basic introduction to parts of the language. Let's
;; take away the shock of seeing parentheses or operators in weird places.
;;
;; Afterwards, we can decide what's worth exploring next, when we're able to
;; focus on the problem and are no longer distracted by syntax.
;; ### Basic Data Types
;;
;; These evaluate to themselves.
1 ;; integers
1.0 ;; doubles
3/8 ;; ratios
"str" ;; strings
:one ;; keywords
'one ;; symbols
true ;; boolean
nil ;; null
;; You'll rarely use symbols, I'd say, but you'll see keywords everywhere. They
;; are Clojure's first choice when it comes to representing elements of a fixed
;; set of symbolic values. Think: enums, map keys, etc...
;;
;; Note that there are more numeric types - but we'll cross that bridge if ever
;; necessary.
;; ### Functions
;;
;; Here are the _operators in weird places_ I've mentioned. When Clojure sees
;; a _form_ with parentheses it will consider its first element the operator,
;; and everything else operands/parameters.
;;
;; For example, simple multiplication will look like this:
(* 3 2)
;; Note that, because my editor is connected to the REPL, I can get the result
;; of that form right here, and instantly. (It should be `6`, in case you are
;; wondering.)
;;
;; Now, since I'm doubling numbers a lot in my line of work, I think it's worth
;; giving a name to this piece of logic:
(defn make-realistic
[estimate]
(* estimate 2))
;; Again, `defn` will be considered the protagonist/operator of this form. There
;; is something special about it - it's a macro - but this is a topic for
;; another day. For now, it's enough to know that this defines a function
;;`make-realistic` that has one parameter named `estimate`, and a function body
;; consisting of the aforementioned doubling operation.
(make-realistic 3)
;; There is no `return` in Clojure - the last value of the chosen code path is
;; what is returned. Consider a similar function:
(defn make-realistic-but-trust-estimate-for-easy-tasks
[estimate]
(if (<= estimate 2)
estimate
(* estimate 2)))
(make-realistic-but-trust-estimate-for-easy-tasks 2)
(make-realistic-but-trust-estimate-for-easy-tasks 5)
;; Here, we can end up in one of two code paths, which both will return the
;; value of their last (and only) expression. Basically, any `if` in Clojure
;; behaves like the ternary operator: `x <= 2 ? x : x * 2`.
;;
;; Speaking of conditionals, there are specialized versions, like `if-not` and
;; `when` and `when-not`, as well as syntactic sugar for literal matches
;; (`case`) or more than two paths (`cond`, `condp`). I recommend you check out
;; their documentation, especially if you realise you're nesting `if`-statements
;; a lot.
;;
;; By the way, most editor integrations will allow you to access a functions
;; docstring inline - e.g. in vim-iced it's done by pressing `K` while the
;; cursor is over the symbol in question - which will rely again on the REPL
;; and the following function:
(doc cond)
;; You could even peek at the source code:
(source cond)
;; Anyways, we got side-tracked. Let's get back to what is the core of Clojure:
;; data.
;; ### Sequences
;;
;; There are three main sequence types, in order of popularity:
[1 2 3] ;; vectors
#{1 2 3} ;; sets
(list 1 2 3) ;; lists (you rarely use them explicitly, tbh)
;; (There is also maps - key/value pairs - but that's discussed in the next
;; section.)
;;
;; There are tons and tons of sequence functions, for example for inspection:
(first #{1 2 3})
(rest [1 2 3])
(nth [1 2 3] 2)
;; Or for manipulation:
(def data [1 2 3 4 5]) ;; Hey, look, a variable!
(cons 0 data) ;; always prepends to the front
(conj data 6) ;; depends on the sequence! (vector -> append, list -> prepend)
;; And the crown jewel: SEQUENCE. ITERATION. FUNCTIONS.
(filter odd? data) ;; only keep matching elements
(remove odd? data) ;; remove all matching elements
(map inc data) ;; apply a function to every element
;; Stop the presses! Have a look at the original `data` variable:
data
;; It has not changed - which is because of the _immutability_ of Clojure's data
;; structures: Every operation will create a new sequence and leave the inputs
;; untouched. It will go about it in a smart way and share common values rather
;; than doing a deep copy of the input, but you never run the risk of changing
;; something you don't want to change.
;;
;; Resume the presses!
(reduce + data) ;; classic fold operation
(reduce + 5 data) ;; classic fold operation, initial value for the accumulator
(reduce
(fn [acc x] ;; Hey, look, an anonymous function!
(+ acc (* x x))) ;; A nested function call, meaning: acc + x^2
0
data)
;; Clojure can get concise if it wants to. Or code-golfy, depending on your
;; stance. This is the same as above, with syntactic sugar for anonymous
;; functions (`%1` = first parameter, `%2` = second parameter, ...):
(reduce #(+ %1 (* %2 %2)) 0 data)
;; I'd suggest to only use this form when there is only one parameter. In which
;; case you can use `%` instead of `%1`. For example:
(map #(+ % 5) data)
;; Utilities galore, btw. If you want to do something with a sequence, chances
;; are that Clojure has a function for it:
(take 2 data)
(drop 2 data)
(drop-while odd? data)
(take-while odd? data)
(split-at 2 data)
(partition 2 data)
(partition-all 2 data)
(frequencies data)
;; And so. Many. More.
;; ### Maps
;;
;; Key/value pairs, objects, hash maps, etc... You know this kind of data
;; structure:
{:a "a", :b "b"} ;; We tend to use keywords for map keys
{"a" 1, "b" 2} ;; but we don't have to.
;; Get and put are, well, get and assoc in Clojure:
(def name->number {:one 1, :two 2, :three 3})
(get name->number :two)
(assoc name->number :four 4)
;; Without stopping the presses this time, you'll see that the original map has
;; not changed. Immutability is to blame/thank.
;;
;; Keywords are functions, btw, so there is a nice-looking way to lookup values:
(:two name->number)
;; This is, for one example, very useful to concisely get nested values (e.g.
;; from the result of an API call):
(map :name [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}])
;; Maps themselves? Also functions:
(name->number :two)
(map name->number [:one :one :two])
;; If you want to rip a map apart (you monster) this is how:
(keys name->number)
(vals name->number)
;; Finally, maps can be considered a sequence of key and value pairs, which
;; means that all the sequence iteration functions we looked at above will
;; work on maps too:
(seq name->number) ;; converts map to seq (usually done automatically)
(map first name->number) ;; similar to `keys`
(filter
(comp even? second) ;; Hey, look, function composition!
name->number)
;; Enough, now. This should make you a bit more comfortable when looking
;; at Clojure code. There is still a lot more to discover.
|
[
{
"context": " node\n {:type ->keyword}))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ",
"end": 10590,
"score": 0.9998525381088257,
"start": 10574,
"tag": "NAME",
"value": "Frederic Merizen"
}
] |
src/ferje/config/xml.clj
|
chourave/clojyday
| 0 |
;; Copyright and license information at end of file
(ns ferje.config.xml
"Parse the same xml configuration files as Jollyday, but faster,
and without requiring JAXB, which is getting deprecated as of Java 9."
(:require
[clojure.java.io :as io]
[clojure.spec.alpha :as s]
[clojure.string :as string]
[clojure.xml :as xml]
[ferje.config.core :as config]
[ferje.place :as place]
[ferje.util :as util])
(:import
(de.jollyday ManagerParameter)
(de.jollyday.datasource ConfigurationDataSource)))
;; XML reading
(s/def ::tag keyword?)
(s/def ::attrs (s/nilable (s/map-of keyword? string?)))
(s/def ::content (s/cat :first-text (s/? string?)
:nodes-and-text (s/* (s/cat :node `xml-node
:text (s/? string?)))))
(s/def xml-node
(s/keys :req-un [::tag ::attrs ::content]))
(defn strip-tag-namespace
"Discard the namespace prefix from a tag"
[tag]
(-> tag name (string/split #":" 2) last))
(s/fdef strip-tag-namespace
:args (s/cat :tag keyword?)
:ret string?)
(defn strip-namespaces
"Discard the namespace prefixes from all tags in a node
and its descendants."
[node]
(if-not (map? node)
node
(-> node
(update :tag #(-> % strip-tag-namespace keyword))
(update :content #(map strip-namespaces %)))))
(s/fdef strip-namespaces
:args (s/cat :node `xml-node)
:ret `xml-node)
(defn read-xml
"Read a Jollyday XML calendar configuration file for the given locale
and parse it to a xml map"
[suffix]
(-> (str "holidays/Holidays_" (name suffix) ".xml")
io/resource
io/input-stream
xml/parse))
(s/fdef read-xml
:args (s/cat :suffix ::calendar-name)
:ret `xml-node)
(defn attribute
"Get the value of the named attribute in an xml node"
[node attribute-name]
(get-in node [:attrs attribute-name]))
(s/fdef attribute
:args (s/cat :node `xml-node :attribute-name keyword?)
:ret (s/nilable string?))
(defn elements
"Get the child elements with a given tag of an xml node"
[node tag]
(let [prefixed (keyword tag)]
(->> node
:content
(filter #(= prefixed (:tag %)))
seq)))
(s/fdef elements
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable (s/coll-of `xml-node)))
(defn element
"Get the first child element with a given tag of an xml node"
[node tag]
(first (elements node tag)))
(s/fdef element
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable `xml-node))
;;
(defn parse-attributes
"Parse selected attributes from an xml node.
`attribute-fns` should be a map from attribute names to functions
that parse attribute values. The attributes names should be kebab-cased
keywords, and will be translated to camelCase when looking them up in
the node.
The return value is a map of kebab-cased attribute names to values returned
by the parsing function, for those attributes actually present in the node.
"
[node attribute-fns]
(reduce
(fn [res [att f]]
(let [att (name att)]
(if-let [v (attribute node (keyword (util/kebab->camel att)))]
(assoc res
(keyword att)
(f v))
res)))
{}
attribute-fns))
(s/fdef parse-attributes
:args (s/cat :node `xml-node
:attribute-fns (s/map-of keyword? ifn?))
:ret (s/map-of keyword? any?))
(defn ->int
"Parse a string to an integer"
[s]
(Integer/parseInt s))
(s/fdef ->int
:args (s/cat :s string?)
:ret int?)
(defn ->keyword
"parse a CONSTANT_CASE string to a :kebab-keyword"
[s]
(-> s
(string/replace "_" "-")
string/lower-case
keyword))
(s/fdef ->keyword
:args (s/cat :s string?)
:ret keyword?
:fn #(util/equals-ignore-case?
(-> % :ret name (util/strip "-"))
(-> % :args :s (util/strip "_"))))
(defn parse-moving-conditions
"Parse the moving conditions from an xml node into a map"
[node]
(when-let [conditions (elements node :MovingCondition)]
{:moving-conditions
(map #(parse-attributes
%
{:substitute ->keyword
:with ->keyword
:weekday ->keyword})
conditions)}))
(s/fdef parse-moving-conditions
:args (s/cat :node `xml-node)
:ret (s/nilable (s/keys :req-un [::config/moving-conditions])))
(defmulti -parse-holiday
"Parse the tag-specific parts of an xml node to a map.
Do not use directly, use `parse-holiday` instead (it also
handles the common parts)"
:tag)
(defn tag->holiday
"Parse the xml tag name of a holiday type to a holiday type keyword.
The xml namespace is discarded."
[tag]
(-> tag
strip-tag-namespace
util/camel->kebab
keyword))
(s/fdef tag->holiday
:args (s/cat :tag ::tag)
:ret ::config/holiday)
(defn parse-common-holiday-attributes
"Parse an xml node, reading the attributes that are common to all holiday types,
and return them as a map."
[node]
(let [description-key (attribute node :descriptionPropertiesKey)
holiday (-> node
(parse-attributes
{:valid-from ->int
:valid-to ->int
:every ->keyword
:localized-type ->keyword})
(assoc :holiday (-> node :tag tag->holiday)))]
(if description-key
(assoc holiday :description-key (->keyword description-key))
holiday)))
(s/fdef parse-common-holiday-attributes
:args (s/cat :node `xml-node)
:ret `config/holiday-tag-common)
(defn parse-holiday
"Parse an xml node describing a holiday to a holiday description map"
[node]
(merge
(parse-common-holiday-attributes node)
(-parse-holiday node)))
(s/fdef parse-holiday
:args (s/cat :node `xml-node)
:ret `config/holiday)
(defn parse-configuration'
"Parse an un-namespaced xml holiday configuration to a configuration map"
[configuration]
(let [holidays (element configuration :Holidays)
sub-configurations (elements configuration :SubConfigurations)
configuration {:description (attribute configuration :description)
:hierarchy (-> configuration (attribute :hierarchy) ->keyword)
:holidays (mapv parse-holiday (:content holidays))}]
(if sub-configurations
(assoc configuration :sub-configurations (mapv parse-configuration' sub-configurations))
configuration)))
(s/fdef parse-configuration'
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn parse-configuration
"Parse an xml holiday configuration to a configuration map"
[configuration]
(-> configuration
strip-namespaces
parse-configuration'))
(s/fdef parse-configuration
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn read-configuration
"Read the configuration for `calendar-name` from an xml file from the
Jollyday distribution, and parse it to a configuration map
Example: (read-configuration :fr)"
[calendar-name]
(parse-configuration (read-xml calendar-name)))
(s/fdef read-configuration
:args (s/cat :calendar-name ::config/calendar-name)
:ret ::config/configuration)
;; ferje/place integration
(place/add-format :xml-clj :xml)
(defmethod place/configuration-data-source :xml-clj
[_]
(reify
ConfigurationDataSource
(getConfiguration [_ parameters]
(-> ^ManagerParameter parameters
.createResourceUrl
io/input-stream
xml/parse
parse-configuration
config/->Configuration))))
;; Fixed day
(defn parse-fixed
"Parse a fixed day and month holiday from an xml node to a map"
[node]
(merge
(parse-attributes
node
{:month ->keyword
:day ->int})
(parse-moving-conditions node)))
(s/fdef parse-fixed
:args (s/cat :node `xml-node)
:ret ::config/date)
(defmethod -parse-holiday :Fixed [node]
(parse-fixed node))
;; Weekday relative to fixed
(defmethod -parse-holiday :RelativeToFixed [node]
(let [weekday (-> node (element :Weekday) :content first)
days (-> node (element :Days) :content first)
holiday {:when (-> node (element :When) :content first ->keyword)
:date (-> node (element :Date) parse-fixed)}]
(cond-> holiday
weekday (assoc :weekday (->keyword weekday))
days (assoc :days (->int days)))))
(defmethod -parse-holiday :FixedWeekdayBetweenFixed [node]
(-> node
(parse-attributes
{:weekday ->keyword})
(assoc :from (-> node (element :from) parse-fixed))
(assoc :to (-> node (element :to) parse-fixed))))
;; Weekday in month
(defn parse-fixed-weekday
"Parse a fixed weekday of month from an xml node to a map"
[node]
(parse-attributes
node
{:which ->keyword
:weekday ->keyword
:month ->keyword}))
(s/fdef parse-fixed-weekday
:args (s/cat :node `xml-node)
:ret ::config/fixed-weekday)
(defmethod -parse-holiday :FixedWeekday [node]
(parse-fixed-weekday node))
;; Relative to weekday in month
(defmethod -parse-holiday :RelativeToWeekdayInMonth [node]
(-> node
(parse-attributes
{:weekday ->keyword
:when ->keyword})
(assoc :fixed-weekday (-> node (element :FixedWeekday) parse-fixed-weekday))))
;; Weekday relative to fixed day
(defmethod -parse-holiday :FixedWeekdayRelativeToFixed [node]
(-> node
(parse-attributes
{:which ->keyword
:weekday ->keyword
:when ->keyword})
(assoc :date (-> node (element :day) parse-fixed))))
;; Christian
(defmethod -parse-holiday :ChristianHoliday [node]
(merge
(parse-attributes
node
{:type ->keyword
:chronology ->keyword})
(parse-moving-conditions node)))
(defmethod -parse-holiday :RelativeToEasterSunday [node]
{:chronology (-> node (element :chronology) :content first ->keyword)
:days (-> node (element :days) :content first ->int)})
;; Islamic
(defmethod -parse-holiday :IslamicHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hindu
(defmethod -parse-holiday :HinduHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hebrew
(defmethod -parse-holiday :HebrewHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Ethiopian orthodox
(defmethod -parse-holiday :EthiopianOrthodoxHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Copyright 2018 Frederic Merizen
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
|
39004
|
;; Copyright and license information at end of file
(ns ferje.config.xml
"Parse the same xml configuration files as Jollyday, but faster,
and without requiring JAXB, which is getting deprecated as of Java 9."
(:require
[clojure.java.io :as io]
[clojure.spec.alpha :as s]
[clojure.string :as string]
[clojure.xml :as xml]
[ferje.config.core :as config]
[ferje.place :as place]
[ferje.util :as util])
(:import
(de.jollyday ManagerParameter)
(de.jollyday.datasource ConfigurationDataSource)))
;; XML reading
(s/def ::tag keyword?)
(s/def ::attrs (s/nilable (s/map-of keyword? string?)))
(s/def ::content (s/cat :first-text (s/? string?)
:nodes-and-text (s/* (s/cat :node `xml-node
:text (s/? string?)))))
(s/def xml-node
(s/keys :req-un [::tag ::attrs ::content]))
(defn strip-tag-namespace
"Discard the namespace prefix from a tag"
[tag]
(-> tag name (string/split #":" 2) last))
(s/fdef strip-tag-namespace
:args (s/cat :tag keyword?)
:ret string?)
(defn strip-namespaces
"Discard the namespace prefixes from all tags in a node
and its descendants."
[node]
(if-not (map? node)
node
(-> node
(update :tag #(-> % strip-tag-namespace keyword))
(update :content #(map strip-namespaces %)))))
(s/fdef strip-namespaces
:args (s/cat :node `xml-node)
:ret `xml-node)
(defn read-xml
"Read a Jollyday XML calendar configuration file for the given locale
and parse it to a xml map"
[suffix]
(-> (str "holidays/Holidays_" (name suffix) ".xml")
io/resource
io/input-stream
xml/parse))
(s/fdef read-xml
:args (s/cat :suffix ::calendar-name)
:ret `xml-node)
(defn attribute
"Get the value of the named attribute in an xml node"
[node attribute-name]
(get-in node [:attrs attribute-name]))
(s/fdef attribute
:args (s/cat :node `xml-node :attribute-name keyword?)
:ret (s/nilable string?))
(defn elements
"Get the child elements with a given tag of an xml node"
[node tag]
(let [prefixed (keyword tag)]
(->> node
:content
(filter #(= prefixed (:tag %)))
seq)))
(s/fdef elements
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable (s/coll-of `xml-node)))
(defn element
"Get the first child element with a given tag of an xml node"
[node tag]
(first (elements node tag)))
(s/fdef element
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable `xml-node))
;;
(defn parse-attributes
"Parse selected attributes from an xml node.
`attribute-fns` should be a map from attribute names to functions
that parse attribute values. The attributes names should be kebab-cased
keywords, and will be translated to camelCase when looking them up in
the node.
The return value is a map of kebab-cased attribute names to values returned
by the parsing function, for those attributes actually present in the node.
"
[node attribute-fns]
(reduce
(fn [res [att f]]
(let [att (name att)]
(if-let [v (attribute node (keyword (util/kebab->camel att)))]
(assoc res
(keyword att)
(f v))
res)))
{}
attribute-fns))
(s/fdef parse-attributes
:args (s/cat :node `xml-node
:attribute-fns (s/map-of keyword? ifn?))
:ret (s/map-of keyword? any?))
(defn ->int
"Parse a string to an integer"
[s]
(Integer/parseInt s))
(s/fdef ->int
:args (s/cat :s string?)
:ret int?)
(defn ->keyword
"parse a CONSTANT_CASE string to a :kebab-keyword"
[s]
(-> s
(string/replace "_" "-")
string/lower-case
keyword))
(s/fdef ->keyword
:args (s/cat :s string?)
:ret keyword?
:fn #(util/equals-ignore-case?
(-> % :ret name (util/strip "-"))
(-> % :args :s (util/strip "_"))))
(defn parse-moving-conditions
"Parse the moving conditions from an xml node into a map"
[node]
(when-let [conditions (elements node :MovingCondition)]
{:moving-conditions
(map #(parse-attributes
%
{:substitute ->keyword
:with ->keyword
:weekday ->keyword})
conditions)}))
(s/fdef parse-moving-conditions
:args (s/cat :node `xml-node)
:ret (s/nilable (s/keys :req-un [::config/moving-conditions])))
(defmulti -parse-holiday
"Parse the tag-specific parts of an xml node to a map.
Do not use directly, use `parse-holiday` instead (it also
handles the common parts)"
:tag)
(defn tag->holiday
"Parse the xml tag name of a holiday type to a holiday type keyword.
The xml namespace is discarded."
[tag]
(-> tag
strip-tag-namespace
util/camel->kebab
keyword))
(s/fdef tag->holiday
:args (s/cat :tag ::tag)
:ret ::config/holiday)
(defn parse-common-holiday-attributes
"Parse an xml node, reading the attributes that are common to all holiday types,
and return them as a map."
[node]
(let [description-key (attribute node :descriptionPropertiesKey)
holiday (-> node
(parse-attributes
{:valid-from ->int
:valid-to ->int
:every ->keyword
:localized-type ->keyword})
(assoc :holiday (-> node :tag tag->holiday)))]
(if description-key
(assoc holiday :description-key (->keyword description-key))
holiday)))
(s/fdef parse-common-holiday-attributes
:args (s/cat :node `xml-node)
:ret `config/holiday-tag-common)
(defn parse-holiday
"Parse an xml node describing a holiday to a holiday description map"
[node]
(merge
(parse-common-holiday-attributes node)
(-parse-holiday node)))
(s/fdef parse-holiday
:args (s/cat :node `xml-node)
:ret `config/holiday)
(defn parse-configuration'
"Parse an un-namespaced xml holiday configuration to a configuration map"
[configuration]
(let [holidays (element configuration :Holidays)
sub-configurations (elements configuration :SubConfigurations)
configuration {:description (attribute configuration :description)
:hierarchy (-> configuration (attribute :hierarchy) ->keyword)
:holidays (mapv parse-holiday (:content holidays))}]
(if sub-configurations
(assoc configuration :sub-configurations (mapv parse-configuration' sub-configurations))
configuration)))
(s/fdef parse-configuration'
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn parse-configuration
"Parse an xml holiday configuration to a configuration map"
[configuration]
(-> configuration
strip-namespaces
parse-configuration'))
(s/fdef parse-configuration
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn read-configuration
"Read the configuration for `calendar-name` from an xml file from the
Jollyday distribution, and parse it to a configuration map
Example: (read-configuration :fr)"
[calendar-name]
(parse-configuration (read-xml calendar-name)))
(s/fdef read-configuration
:args (s/cat :calendar-name ::config/calendar-name)
:ret ::config/configuration)
;; ferje/place integration
(place/add-format :xml-clj :xml)
(defmethod place/configuration-data-source :xml-clj
[_]
(reify
ConfigurationDataSource
(getConfiguration [_ parameters]
(-> ^ManagerParameter parameters
.createResourceUrl
io/input-stream
xml/parse
parse-configuration
config/->Configuration))))
;; Fixed day
(defn parse-fixed
"Parse a fixed day and month holiday from an xml node to a map"
[node]
(merge
(parse-attributes
node
{:month ->keyword
:day ->int})
(parse-moving-conditions node)))
(s/fdef parse-fixed
:args (s/cat :node `xml-node)
:ret ::config/date)
(defmethod -parse-holiday :Fixed [node]
(parse-fixed node))
;; Weekday relative to fixed
(defmethod -parse-holiday :RelativeToFixed [node]
(let [weekday (-> node (element :Weekday) :content first)
days (-> node (element :Days) :content first)
holiday {:when (-> node (element :When) :content first ->keyword)
:date (-> node (element :Date) parse-fixed)}]
(cond-> holiday
weekday (assoc :weekday (->keyword weekday))
days (assoc :days (->int days)))))
(defmethod -parse-holiday :FixedWeekdayBetweenFixed [node]
(-> node
(parse-attributes
{:weekday ->keyword})
(assoc :from (-> node (element :from) parse-fixed))
(assoc :to (-> node (element :to) parse-fixed))))
;; Weekday in month
(defn parse-fixed-weekday
"Parse a fixed weekday of month from an xml node to a map"
[node]
(parse-attributes
node
{:which ->keyword
:weekday ->keyword
:month ->keyword}))
(s/fdef parse-fixed-weekday
:args (s/cat :node `xml-node)
:ret ::config/fixed-weekday)
(defmethod -parse-holiday :FixedWeekday [node]
(parse-fixed-weekday node))
;; Relative to weekday in month
(defmethod -parse-holiday :RelativeToWeekdayInMonth [node]
(-> node
(parse-attributes
{:weekday ->keyword
:when ->keyword})
(assoc :fixed-weekday (-> node (element :FixedWeekday) parse-fixed-weekday))))
;; Weekday relative to fixed day
(defmethod -parse-holiday :FixedWeekdayRelativeToFixed [node]
(-> node
(parse-attributes
{:which ->keyword
:weekday ->keyword
:when ->keyword})
(assoc :date (-> node (element :day) parse-fixed))))
;; Christian
(defmethod -parse-holiday :ChristianHoliday [node]
(merge
(parse-attributes
node
{:type ->keyword
:chronology ->keyword})
(parse-moving-conditions node)))
(defmethod -parse-holiday :RelativeToEasterSunday [node]
{:chronology (-> node (element :chronology) :content first ->keyword)
:days (-> node (element :days) :content first ->int)})
;; Islamic
(defmethod -parse-holiday :IslamicHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hindu
(defmethod -parse-holiday :HinduHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hebrew
(defmethod -parse-holiday :HebrewHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Ethiopian orthodox
(defmethod -parse-holiday :EthiopianOrthodoxHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Copyright 2018 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
| true |
;; Copyright and license information at end of file
(ns ferje.config.xml
"Parse the same xml configuration files as Jollyday, but faster,
and without requiring JAXB, which is getting deprecated as of Java 9."
(:require
[clojure.java.io :as io]
[clojure.spec.alpha :as s]
[clojure.string :as string]
[clojure.xml :as xml]
[ferje.config.core :as config]
[ferje.place :as place]
[ferje.util :as util])
(:import
(de.jollyday ManagerParameter)
(de.jollyday.datasource ConfigurationDataSource)))
;; XML reading
(s/def ::tag keyword?)
(s/def ::attrs (s/nilable (s/map-of keyword? string?)))
(s/def ::content (s/cat :first-text (s/? string?)
:nodes-and-text (s/* (s/cat :node `xml-node
:text (s/? string?)))))
(s/def xml-node
(s/keys :req-un [::tag ::attrs ::content]))
(defn strip-tag-namespace
"Discard the namespace prefix from a tag"
[tag]
(-> tag name (string/split #":" 2) last))
(s/fdef strip-tag-namespace
:args (s/cat :tag keyword?)
:ret string?)
(defn strip-namespaces
"Discard the namespace prefixes from all tags in a node
and its descendants."
[node]
(if-not (map? node)
node
(-> node
(update :tag #(-> % strip-tag-namespace keyword))
(update :content #(map strip-namespaces %)))))
(s/fdef strip-namespaces
:args (s/cat :node `xml-node)
:ret `xml-node)
(defn read-xml
"Read a Jollyday XML calendar configuration file for the given locale
and parse it to a xml map"
[suffix]
(-> (str "holidays/Holidays_" (name suffix) ".xml")
io/resource
io/input-stream
xml/parse))
(s/fdef read-xml
:args (s/cat :suffix ::calendar-name)
:ret `xml-node)
(defn attribute
"Get the value of the named attribute in an xml node"
[node attribute-name]
(get-in node [:attrs attribute-name]))
(s/fdef attribute
:args (s/cat :node `xml-node :attribute-name keyword?)
:ret (s/nilable string?))
(defn elements
"Get the child elements with a given tag of an xml node"
[node tag]
(let [prefixed (keyword tag)]
(->> node
:content
(filter #(= prefixed (:tag %)))
seq)))
(s/fdef elements
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable (s/coll-of `xml-node)))
(defn element
"Get the first child element with a given tag of an xml node"
[node tag]
(first (elements node tag)))
(s/fdef element
:args (s/cat :node `xml-node :tag keyword?)
:ret (s/nilable `xml-node))
;;
(defn parse-attributes
"Parse selected attributes from an xml node.
`attribute-fns` should be a map from attribute names to functions
that parse attribute values. The attributes names should be kebab-cased
keywords, and will be translated to camelCase when looking them up in
the node.
The return value is a map of kebab-cased attribute names to values returned
by the parsing function, for those attributes actually present in the node.
"
[node attribute-fns]
(reduce
(fn [res [att f]]
(let [att (name att)]
(if-let [v (attribute node (keyword (util/kebab->camel att)))]
(assoc res
(keyword att)
(f v))
res)))
{}
attribute-fns))
(s/fdef parse-attributes
:args (s/cat :node `xml-node
:attribute-fns (s/map-of keyword? ifn?))
:ret (s/map-of keyword? any?))
(defn ->int
"Parse a string to an integer"
[s]
(Integer/parseInt s))
(s/fdef ->int
:args (s/cat :s string?)
:ret int?)
(defn ->keyword
"parse a CONSTANT_CASE string to a :kebab-keyword"
[s]
(-> s
(string/replace "_" "-")
string/lower-case
keyword))
(s/fdef ->keyword
:args (s/cat :s string?)
:ret keyword?
:fn #(util/equals-ignore-case?
(-> % :ret name (util/strip "-"))
(-> % :args :s (util/strip "_"))))
(defn parse-moving-conditions
"Parse the moving conditions from an xml node into a map"
[node]
(when-let [conditions (elements node :MovingCondition)]
{:moving-conditions
(map #(parse-attributes
%
{:substitute ->keyword
:with ->keyword
:weekday ->keyword})
conditions)}))
(s/fdef parse-moving-conditions
:args (s/cat :node `xml-node)
:ret (s/nilable (s/keys :req-un [::config/moving-conditions])))
(defmulti -parse-holiday
"Parse the tag-specific parts of an xml node to a map.
Do not use directly, use `parse-holiday` instead (it also
handles the common parts)"
:tag)
(defn tag->holiday
"Parse the xml tag name of a holiday type to a holiday type keyword.
The xml namespace is discarded."
[tag]
(-> tag
strip-tag-namespace
util/camel->kebab
keyword))
(s/fdef tag->holiday
:args (s/cat :tag ::tag)
:ret ::config/holiday)
(defn parse-common-holiday-attributes
"Parse an xml node, reading the attributes that are common to all holiday types,
and return them as a map."
[node]
(let [description-key (attribute node :descriptionPropertiesKey)
holiday (-> node
(parse-attributes
{:valid-from ->int
:valid-to ->int
:every ->keyword
:localized-type ->keyword})
(assoc :holiday (-> node :tag tag->holiday)))]
(if description-key
(assoc holiday :description-key (->keyword description-key))
holiday)))
(s/fdef parse-common-holiday-attributes
:args (s/cat :node `xml-node)
:ret `config/holiday-tag-common)
(defn parse-holiday
"Parse an xml node describing a holiday to a holiday description map"
[node]
(merge
(parse-common-holiday-attributes node)
(-parse-holiday node)))
(s/fdef parse-holiday
:args (s/cat :node `xml-node)
:ret `config/holiday)
(defn parse-configuration'
"Parse an un-namespaced xml holiday configuration to a configuration map"
[configuration]
(let [holidays (element configuration :Holidays)
sub-configurations (elements configuration :SubConfigurations)
configuration {:description (attribute configuration :description)
:hierarchy (-> configuration (attribute :hierarchy) ->keyword)
:holidays (mapv parse-holiday (:content holidays))}]
(if sub-configurations
(assoc configuration :sub-configurations (mapv parse-configuration' sub-configurations))
configuration)))
(s/fdef parse-configuration'
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn parse-configuration
"Parse an xml holiday configuration to a configuration map"
[configuration]
(-> configuration
strip-namespaces
parse-configuration'))
(s/fdef parse-configuration
:args (s/cat :configuration `xml-node)
:ret ::config/configuration)
(defn read-configuration
"Read the configuration for `calendar-name` from an xml file from the
Jollyday distribution, and parse it to a configuration map
Example: (read-configuration :fr)"
[calendar-name]
(parse-configuration (read-xml calendar-name)))
(s/fdef read-configuration
:args (s/cat :calendar-name ::config/calendar-name)
:ret ::config/configuration)
;; ferje/place integration
(place/add-format :xml-clj :xml)
(defmethod place/configuration-data-source :xml-clj
[_]
(reify
ConfigurationDataSource
(getConfiguration [_ parameters]
(-> ^ManagerParameter parameters
.createResourceUrl
io/input-stream
xml/parse
parse-configuration
config/->Configuration))))
;; Fixed day
(defn parse-fixed
"Parse a fixed day and month holiday from an xml node to a map"
[node]
(merge
(parse-attributes
node
{:month ->keyword
:day ->int})
(parse-moving-conditions node)))
(s/fdef parse-fixed
:args (s/cat :node `xml-node)
:ret ::config/date)
(defmethod -parse-holiday :Fixed [node]
(parse-fixed node))
;; Weekday relative to fixed
(defmethod -parse-holiday :RelativeToFixed [node]
(let [weekday (-> node (element :Weekday) :content first)
days (-> node (element :Days) :content first)
holiday {:when (-> node (element :When) :content first ->keyword)
:date (-> node (element :Date) parse-fixed)}]
(cond-> holiday
weekday (assoc :weekday (->keyword weekday))
days (assoc :days (->int days)))))
(defmethod -parse-holiday :FixedWeekdayBetweenFixed [node]
(-> node
(parse-attributes
{:weekday ->keyword})
(assoc :from (-> node (element :from) parse-fixed))
(assoc :to (-> node (element :to) parse-fixed))))
;; Weekday in month
(defn parse-fixed-weekday
"Parse a fixed weekday of month from an xml node to a map"
[node]
(parse-attributes
node
{:which ->keyword
:weekday ->keyword
:month ->keyword}))
(s/fdef parse-fixed-weekday
:args (s/cat :node `xml-node)
:ret ::config/fixed-weekday)
(defmethod -parse-holiday :FixedWeekday [node]
(parse-fixed-weekday node))
;; Relative to weekday in month
(defmethod -parse-holiday :RelativeToWeekdayInMonth [node]
(-> node
(parse-attributes
{:weekday ->keyword
:when ->keyword})
(assoc :fixed-weekday (-> node (element :FixedWeekday) parse-fixed-weekday))))
;; Weekday relative to fixed day
(defmethod -parse-holiday :FixedWeekdayRelativeToFixed [node]
(-> node
(parse-attributes
{:which ->keyword
:weekday ->keyword
:when ->keyword})
(assoc :date (-> node (element :day) parse-fixed))))
;; Christian
(defmethod -parse-holiday :ChristianHoliday [node]
(merge
(parse-attributes
node
{:type ->keyword
:chronology ->keyword})
(parse-moving-conditions node)))
(defmethod -parse-holiday :RelativeToEasterSunday [node]
{:chronology (-> node (element :chronology) :content first ->keyword)
:days (-> node (element :days) :content first ->int)})
;; Islamic
(defmethod -parse-holiday :IslamicHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hindu
(defmethod -parse-holiday :HinduHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Hebrew
(defmethod -parse-holiday :HebrewHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Ethiopian orthodox
(defmethod -parse-holiday :EthiopianOrthodoxHoliday [node]
(parse-attributes
node
{:type ->keyword}))
;; Copyright 2018 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
|
[
{
"context": "ted on top of OkHttp.\"\n :url \"https://github.com/vincentjames501/clj-http-next\"\n :license {:name \"MIT License\" :u",
"end": 189,
"score": 0.9951520562171936,
"start": 174,
"tag": "USERNAME",
"value": "vincentjames501"
},
{
"context": "it\"}\n :scm {:name \"git\" :url \"https://github.com/vincentjames501/clj-http-next\"}\n :pom-addition [:developers\n ",
"end": 362,
"score": 0.960612952709198,
"start": 347,
"tag": "USERNAME",
"value": "vincentjames501"
},
{
"context": " [:developer\n [:name \"Vincent Pizzo\"]\n [:url \"https://github.com/vin",
"end": 476,
"score": 0.9998812675476074,
"start": 463,
"tag": "NAME",
"value": "Vincent Pizzo"
},
{
"context": "zzo\"]\n [:url \"https://github.com/vincentjames501\"]\n [:email \"vincentjames501@gmai",
"end": 538,
"score": 0.9988240599632263,
"start": 523,
"tag": "USERNAME",
"value": "vincentjames501"
},
{
"context": ".com/vincentjames501\"]\n [:email \"[email protected]\"]\n [:timezone \"-5\"]]]\n :deploy-",
"end": 593,
"score": 0.9999271035194397,
"start": 568,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
project.clj
|
vincentjames501/clj-okhttp
| 0 |
(defproject clj-http-next/clj-http-next "0.0.1-SNAPSHOT"
:description "A fast and lightweight clojure http client constructed on top of OkHttp."
:url "https://github.com/vincentjames501/clj-http-next"
:license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2022 :key "mit"}
:scm {:name "git" :url "https://github.com/vincentjames501/clj-http-next"}
:pom-addition [:developers
[:developer
[:name "Vincent Pizzo"]
[:url "https://github.com/vincentjames501"]
[:email "[email protected]"]
[:timezone "-5"]]]
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:dependencies [[org.clojure/clojure "1.10.3"]
[metosin/muuntaja "0.6.8"]
[metosin/jsonista "0.3.5"]
[com.squareup.okhttp3/okhttp "4.9.3"]]
:profiles {:test {:dependencies [[clj-http "3.12.3"]
[cheshire "5.10.2"]
[criterium "0.4.6"]
[org.slf4j/slf4j-simple "1.7.36"]
[org.testcontainers/testcontainers "1.16.3"]]}}
:cloverage {:selector [:coverage]}
:test-selectors {:coverage (complement :performance)}
:plugins [[lein-cloverage "1.1.2"]]
:repl-options {:init-ns clj-okhttp.core}
:global-vars {*warn-on-reflection* true})
|
36353
|
(defproject clj-http-next/clj-http-next "0.0.1-SNAPSHOT"
:description "A fast and lightweight clojure http client constructed on top of OkHttp."
:url "https://github.com/vincentjames501/clj-http-next"
:license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2022 :key "mit"}
:scm {:name "git" :url "https://github.com/vincentjames501/clj-http-next"}
:pom-addition [:developers
[:developer
[:name "<NAME>"]
[:url "https://github.com/vincentjames501"]
[:email "<EMAIL>"]
[:timezone "-5"]]]
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:dependencies [[org.clojure/clojure "1.10.3"]
[metosin/muuntaja "0.6.8"]
[metosin/jsonista "0.3.5"]
[com.squareup.okhttp3/okhttp "4.9.3"]]
:profiles {:test {:dependencies [[clj-http "3.12.3"]
[cheshire "5.10.2"]
[criterium "0.4.6"]
[org.slf4j/slf4j-simple "1.7.36"]
[org.testcontainers/testcontainers "1.16.3"]]}}
:cloverage {:selector [:coverage]}
:test-selectors {:coverage (complement :performance)}
:plugins [[lein-cloverage "1.1.2"]]
:repl-options {:init-ns clj-okhttp.core}
:global-vars {*warn-on-reflection* true})
| true |
(defproject clj-http-next/clj-http-next "0.0.1-SNAPSHOT"
:description "A fast and lightweight clojure http client constructed on top of OkHttp."
:url "https://github.com/vincentjames501/clj-http-next"
:license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2022 :key "mit"}
:scm {:name "git" :url "https://github.com/vincentjames501/clj-http-next"}
:pom-addition [:developers
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "https://github.com/vincentjames501"]
[:email "PI:EMAIL:<EMAIL>END_PI"]
[:timezone "-5"]]]
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:dependencies [[org.clojure/clojure "1.10.3"]
[metosin/muuntaja "0.6.8"]
[metosin/jsonista "0.3.5"]
[com.squareup.okhttp3/okhttp "4.9.3"]]
:profiles {:test {:dependencies [[clj-http "3.12.3"]
[cheshire "5.10.2"]
[criterium "0.4.6"]
[org.slf4j/slf4j-simple "1.7.36"]
[org.testcontainers/testcontainers "1.16.3"]]}}
:cloverage {:selector [:coverage]}
:test-selectors {:coverage (complement :performance)}
:plugins [[lein-cloverage "1.1.2"]]
:repl-options {:init-ns clj-okhttp.core}
:global-vars {*warn-on-reflection* true})
|
[
{
"context": " 1000\n :account/email \"[email protected]\"\n :account/password \"letm",
"end": 2040,
"score": 0.9999246597290039,
"start": 2025,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": ".com\"\n :account/password \"letmein\"}}\n :user/id {100 {:user/id 100\n ",
"end": 2093,
"score": 0.9991874098777771,
"start": 2086,
"tag": "PASSWORD",
"value": "letmein"
},
{
"context": " 100\n :user/name \"Emily\"\n :user/email \"emily@ex",
"end": 2185,
"score": 0.9931228756904602,
"start": 2180,
"tag": "NAME",
"value": "Emily"
},
{
"context": " \"Emily\"\n :user/email \"[email protected]\"\n :user/settings [:setting",
"end": 2244,
"score": 0.9999241232872009,
"start": 2227,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "hecking?]\n (div :.ui.segment\n (h2 \"Username is [email protected], password is letmein\")\n (div :.ui.form {:class",
"end": 14756,
"score": 0.9999114871025085,
"start": 14741,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "\n (h2 \"Username is [email protected], password is letmein\")\n (div :.ui.form {:classes [(when failed? \"er",
"end": 14777,
"score": 0.9990407824516296,
"start": 14770,
"tag": "PASSWORD",
"value": "letmein"
}
] |
src/workspaces/com/fulcrologic/fulcro/cards/composition4_cards.cljs
|
janezj/fulcro
| 1,312 |
(ns com.fulcrologic.fulcro.cards.composition4-cards
(:require
["react-dom" :as react-dom]
[clojure.pprint :refer [pprint]]
[nubank.workspaces.model :as wsm]
[nubank.workspaces.card-types.react :as ct.react]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[cljs.core.async :as async]
[com.fulcrologic.fulcro.dom :as dom :refer [div p input button h2 label]]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.raw.components :as rc]
[com.fulcrologic.fulcro.react.hooks :as hooks]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.mutations :as m]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.inspect.inspect-client :as inspect]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.algorithms.data-targeting :as dt]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.dom.events :as evt]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.lookup :as ah]
[edn-query-language.core :as eql]
[com.fulcrologic.fulcro.ui-state-machines :as uism]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mock Server and database, in Fulcro client format for ease of use in demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce pretend-server-database
(atom
{:settings/id {1 {:settings/id 1
:settings/marketing? true
:settings/theme :light-mode}}
:account/id {1000 {:account/id 1000
:account/email "[email protected]"
:account/password "letmein"}}
:user/id {100 {:user/id 100
:user/name "Emily"
:user/email "[email protected]"
:user/settings [:settings/id 1]}}}))
(pc/defresolver settings-resolver [_ {:settings/keys [id]}]
{::pc/input #{:settings/id}
::pc/output [:settings/marketing? :settings/theme]}
(get-in @pretend-server-database [:settings/id id]))
(pc/defresolver user-resolver [_ {:user/keys [id]}]
{::pc/input #{:user/id}
::pc/output [:user/name :user/email :user/age {:user/settings [:settings/id]}]}
(try
(-> @pretend-server-database
(get-in [:user/id id])
(update :user/settings #(into {} [%])))
(catch :default e
(log/error e "Resolver fail"))))
(pc/defresolver current-user-resolver [_ _]
{::pc/output [{:current-user [:user/id]}]}
{:current-user {:user/id 100}})
(pc/defmutation server-save-form [_ form-diff]
{::pc/sym `save-form}
(swap! pretend-server-database
(fn [s]
(reduce-kv
(fn [final-state ident changes]
(reduce-kv
(fn [fs k {:keys [after]}]
(if (nil? after)
(update-in fs ident dissoc k)
(assoc-in fs (conj ident k) after)))
final-state
changes))
s
form-diff)))
(log/info "Updated server to:" (with-out-str (pprint @pretend-server-database)))
nil)
;; For the UISM DEMO
(defonce session-id (atom 1000)) ; pretend like we have server state to remember client
(pc/defresolver account-resolver [_ {:account/keys [id]}]
{::pc/input #{:account/id}
::pc/output [:account/email]}
(select-keys (get-in @pretend-server-database [:account/id id] {}) [:account/email]))
(pc/defresolver session-resolver [_ {:account/keys [id]}]
{::pc/output [{:current-session [:account/id]}]}
(if @session-id
{:current-session {:account/id @session-id}}
{:current-session {:account/id :none}}))
(pc/defmutation server-login [_ {:keys [email password]}]
{::pc/sym `login
::pc/output [:account/id]}
(let [accounts (vals (get @pretend-server-database :account/id))
account (first
(filter
(fn [a] (and (= password (:account/password a)) (= email (:account/email a))))
accounts))]
(when (log/spy :info "Found account" account)
(reset! session-id (:account/id account))
account)))
(pc/defmutation server-logout [_ _]
{::pc/sym `logout}
(reset! session-id nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Registration for the above resolvers and mutations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def resolvers [user-resolver current-user-resolver settings-resolver server-save-form account-resolver session-resolver
server-login server-logout])
(def pathom-parser (p/parser {::p/env {::p/reader [p/map-reader
pc/reader2
pc/open-ident-reader]
::pc/mutation-join-globals [:tempids]}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register [resolvers]})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin]}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Client. We close over the server parser above using a mock http server. The
;; extra level of indirection allows hot code reload to refresh the mock server and
;; parser without wiping out the app.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce raw-app
(let [process-eql (fn [eql] (async/go
(let [tm (async/timeout 300)]
(async/<! tm)
(pathom-parser {} eql))))
app (app/fulcro-app {:remotes {:remote (mock-http-server {:parser process-eql})}
:batch-notifications (fn [render!] (react-dom/unstable_batchedUpdates render!))})]
(inspect/app-started! app)
app))
;; TODO: Write `raw/formc` that makes a form automatically with form config join and form fields on everything that isn't an id
#_#_(def Settings (raw/nc [:settings/id :settings/marketing? fs/form-config-join] {:form-fields #{:settings/marketing?}}))
(def User (raw/nc [:user/id :user/name fs/form-config-join {:user/settings (comp/get-query Settings)}] {:form-fields #{:user/name
:user/settings}}))
(def User (fs/formc [:ui/saving? [df/marker-table '_]
:user/id :user/name
{:user/settings [:settings/id :settings/marketing?]}]))
(comment
(comp/component-options User)
(comp/get-ident User {:user/id 34})
(comp/get-initial-state User {})
(comp/get-ident User {:user/id 34})
(-> (comp/get-query User) (meta) (:component) (comp/get-query))
)
(m/defmutation initialize-form [_]
(action [{:keys [state]}]
(let [ident (get @state :current-user)]
(fns/swap!-> state
(fs/add-form-config* User ident {:destructive? true})
(fs/mark-complete* ident)))))
(defn- set-saving! [{:keys [state ref]} tf]
(when (vector? ref)
(swap! state assoc-in (conj ref :ui/saving?) tf)))
(m/defmutation save-form [form]
(action [{:keys [state] :as env}]
(set-saving! env true)
(let [idk (rc/id-key form)
id (get form idk)]
(when (and idk id)
(swap! state fs/entity->pristine* [idk id]))))
(ok-action [env] (set-saving! env false))
(error-action [env] (set-saving! env false))
(remote [env]
(-> env
(m/with-params (fs/dirty-fields form true))
(m/returning User))))
(defn UserForm [_js-props]
(hooks/use-lifecycle (fn [] (df/load! raw-app :current-user User {:post-mutation `initialize-form
:marker ::user})))
(let [{:ui/keys [saving?]
:user/keys [id name settings] :as u} (hooks/use-root raw-app :current-user User {})
loading? (df/loading? (get-in u [df/marker-table ::user]))]
(div :.ui.segment
(h2 "Form")
(div :.ui.form {:classes [(when loading? "loading")]}
(div :.field
(label "Name")
(input {:value (or name "")
:onChange (fn [evt] (m/raw-set-value! raw-app u :user/name (evt/target-value evt)))}))
(let [{:settings/keys [marketing?]} settings]
(div :.ui.checkbox
(input {:type "checkbox"
:onChange (fn [_] (m/raw-update-value! raw-app settings :settings/marketing? not))
:checked (boolean marketing?)})
(label "Marketing Emails?")))
(div :.field
(dom/button :.ui.primary.button
{:classes [(when-not (fs/dirty? u) "disabled")
(when saving? "loading")]
:onClick (fn [] (comp/transact! raw-app [(save-form u)] {:ref [:user/id id]}))}
"Save"))))))
(def ui-user-form (interop/react-factory UserForm))
(defn RawReactWithFulcroIO [_] (ui-user-form))
(ws/defcard fulcro-io-composed-in-raw-react
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RawReactWithFulcroIO {})))
(def global-events {:event/unmounted {::uism/handler (fn [env] env)}})
(uism/defstatemachine session-machine
{::uism/actor-names
#{:actor/login-form :actor/current-account}
::uism/aliases
{:email [:actor/login-form :email]
:password [:actor/login-form :password]
:failed? [:actor/login-form :failed?]
:name [:actor/current-account :account/email]}
::uism/states
{:initial
{::uism/handler (fn [env]
(let [LoginForm (rc/nc [:component/id :email :password :failed?] {:componentName ::LoginForm})
Session (rc/nc [:account/id :account/email] {:componentName ::Session})]
(-> env
(uism/apply-action assoc-in [:account/id :none] {:account/id :none})
(uism/apply-action assoc-in [:component/id ::LoginForm] {:component/id ::LoginForm :email "" :password "" :failed? false})
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/reset-actor-ident :actor/login-form (uism/with-actor-class [:component/id ::LoginForm] LoginForm))
(uism/load :current-session :actor/current-account {::uism/ok-event :event/done
::uism/error-event :event/done})
(uism/activate :state/checking-session))))}
:state/checking-session
{::uism/events
(merge global-events
{:event/done {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [id (some-> state-map :current-session second)]
(cond-> env
(pos-int? id) (->
(uism/reset-actor-ident :actor/current-account [:account/id id])
(uism/activate :state/logged-in))
(not (pos-int? id)) (uism/activate :state/gathering-credentials))))}
:event/post-login {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [session-ident (get state-map :current-session)
Session (uism/actor-class env :actor/current-account)
logged-in? (pos-int? (second session-ident))]
(if logged-in?
(-> env
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class session-ident Session))
(uism/activate :state/logged-in))
(-> env
(uism/assoc-aliased :failed? true)
(uism/activate :state/gathering-credentials)))))}})}
:state/gathering-credentials
{::uism/events
(merge global-events
{:event/login {::uism/handler
(fn [env]
(-> env
(uism/assoc-aliased :failed? false)
(uism/trigger-remote-mutation :actor/login-form `login {:email (uism/alias-value env :email)
:password (uism/alias-value env :password)
::m/returning (uism/actor-class env :actor/current-account)
::dt/target [:current-session]
::uism/ok-event :event/post-login
::uism/error-event :event/post-login})
(uism/activate :state/checking-session)))}})}
:state/logged-in
{::uism/events
(merge global-events
{:event/logout {::uism/handler
(fn [env]
(let [Session (uism/actor-class env :actor/current-account)]
(-> env
(uism/apply-action assoc :account/id {:none {}})
(uism/assoc-aliased :email "" :password "" :failed? false)
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/trigger-remote-mutation :actor/current-account `logout {})
(uism/activate :state/gathering-credentials))))}})}}})
(defn ui-login-form [{:keys [email password failed?] :as login-form} checking?]
(div :.ui.segment
(h2 "Username is [email protected], password is letmein")
(div :.ui.form {:classes [(when failed? "error")
(when checking? "loading")]}
(div :.field
(label "Email")
(input {:value (or email "")
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :email (evt/target-value evt)))}))
(div :.field
(label "Password")
(input {:type "password"
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :password (evt/target-value evt)))
:value (or password "")}))
(div :.ui.error.message
"Invalid credentials. Please try again.")
(div :.field
(button :.ui.primary.button {:onClick (fn [] (uism/trigger! raw-app :sessions :event/login {}))} "Login")))))
(defn RootUISMSessions [_]
(let [{:actor/keys [login-form current-account]
:keys [active-state]
:as sm} (hooks/use-uism raw-app session-machine :sessions {})]
;; TODO: Not done yet...didn't have time to finish refining, but it looks like it'll work
(case active-state
:state/logged-in (div :.ui.segment
(dom/p {} (str "Hi," (:account/email current-account)))
(button :.ui.red.button {:onClick #(uism/trigger! raw-app :sessions :event/logout)} "Logout"))
(:state/checking-session :state/gathering-credentials) (ui-login-form login-form (= :state/checking-session active-state))
(div (str active-state)))))
(ws/defcard raw-uism-card
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RootUISMSessions {})))
|
33069
|
(ns com.fulcrologic.fulcro.cards.composition4-cards
(:require
["react-dom" :as react-dom]
[clojure.pprint :refer [pprint]]
[nubank.workspaces.model :as wsm]
[nubank.workspaces.card-types.react :as ct.react]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[cljs.core.async :as async]
[com.fulcrologic.fulcro.dom :as dom :refer [div p input button h2 label]]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.raw.components :as rc]
[com.fulcrologic.fulcro.react.hooks :as hooks]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.mutations :as m]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.inspect.inspect-client :as inspect]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.algorithms.data-targeting :as dt]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.dom.events :as evt]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.lookup :as ah]
[edn-query-language.core :as eql]
[com.fulcrologic.fulcro.ui-state-machines :as uism]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mock Server and database, in Fulcro client format for ease of use in demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce pretend-server-database
(atom
{:settings/id {1 {:settings/id 1
:settings/marketing? true
:settings/theme :light-mode}}
:account/id {1000 {:account/id 1000
:account/email "<EMAIL>"
:account/password "<PASSWORD>"}}
:user/id {100 {:user/id 100
:user/name "<NAME>"
:user/email "<EMAIL>"
:user/settings [:settings/id 1]}}}))
(pc/defresolver settings-resolver [_ {:settings/keys [id]}]
{::pc/input #{:settings/id}
::pc/output [:settings/marketing? :settings/theme]}
(get-in @pretend-server-database [:settings/id id]))
(pc/defresolver user-resolver [_ {:user/keys [id]}]
{::pc/input #{:user/id}
::pc/output [:user/name :user/email :user/age {:user/settings [:settings/id]}]}
(try
(-> @pretend-server-database
(get-in [:user/id id])
(update :user/settings #(into {} [%])))
(catch :default e
(log/error e "Resolver fail"))))
(pc/defresolver current-user-resolver [_ _]
{::pc/output [{:current-user [:user/id]}]}
{:current-user {:user/id 100}})
(pc/defmutation server-save-form [_ form-diff]
{::pc/sym `save-form}
(swap! pretend-server-database
(fn [s]
(reduce-kv
(fn [final-state ident changes]
(reduce-kv
(fn [fs k {:keys [after]}]
(if (nil? after)
(update-in fs ident dissoc k)
(assoc-in fs (conj ident k) after)))
final-state
changes))
s
form-diff)))
(log/info "Updated server to:" (with-out-str (pprint @pretend-server-database)))
nil)
;; For the UISM DEMO
(defonce session-id (atom 1000)) ; pretend like we have server state to remember client
(pc/defresolver account-resolver [_ {:account/keys [id]}]
{::pc/input #{:account/id}
::pc/output [:account/email]}
(select-keys (get-in @pretend-server-database [:account/id id] {}) [:account/email]))
(pc/defresolver session-resolver [_ {:account/keys [id]}]
{::pc/output [{:current-session [:account/id]}]}
(if @session-id
{:current-session {:account/id @session-id}}
{:current-session {:account/id :none}}))
(pc/defmutation server-login [_ {:keys [email password]}]
{::pc/sym `login
::pc/output [:account/id]}
(let [accounts (vals (get @pretend-server-database :account/id))
account (first
(filter
(fn [a] (and (= password (:account/password a)) (= email (:account/email a))))
accounts))]
(when (log/spy :info "Found account" account)
(reset! session-id (:account/id account))
account)))
(pc/defmutation server-logout [_ _]
{::pc/sym `logout}
(reset! session-id nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Registration for the above resolvers and mutations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def resolvers [user-resolver current-user-resolver settings-resolver server-save-form account-resolver session-resolver
server-login server-logout])
(def pathom-parser (p/parser {::p/env {::p/reader [p/map-reader
pc/reader2
pc/open-ident-reader]
::pc/mutation-join-globals [:tempids]}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register [resolvers]})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin]}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Client. We close over the server parser above using a mock http server. The
;; extra level of indirection allows hot code reload to refresh the mock server and
;; parser without wiping out the app.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce raw-app
(let [process-eql (fn [eql] (async/go
(let [tm (async/timeout 300)]
(async/<! tm)
(pathom-parser {} eql))))
app (app/fulcro-app {:remotes {:remote (mock-http-server {:parser process-eql})}
:batch-notifications (fn [render!] (react-dom/unstable_batchedUpdates render!))})]
(inspect/app-started! app)
app))
;; TODO: Write `raw/formc` that makes a form automatically with form config join and form fields on everything that isn't an id
#_#_(def Settings (raw/nc [:settings/id :settings/marketing? fs/form-config-join] {:form-fields #{:settings/marketing?}}))
(def User (raw/nc [:user/id :user/name fs/form-config-join {:user/settings (comp/get-query Settings)}] {:form-fields #{:user/name
:user/settings}}))
(def User (fs/formc [:ui/saving? [df/marker-table '_]
:user/id :user/name
{:user/settings [:settings/id :settings/marketing?]}]))
(comment
(comp/component-options User)
(comp/get-ident User {:user/id 34})
(comp/get-initial-state User {})
(comp/get-ident User {:user/id 34})
(-> (comp/get-query User) (meta) (:component) (comp/get-query))
)
(m/defmutation initialize-form [_]
(action [{:keys [state]}]
(let [ident (get @state :current-user)]
(fns/swap!-> state
(fs/add-form-config* User ident {:destructive? true})
(fs/mark-complete* ident)))))
(defn- set-saving! [{:keys [state ref]} tf]
(when (vector? ref)
(swap! state assoc-in (conj ref :ui/saving?) tf)))
(m/defmutation save-form [form]
(action [{:keys [state] :as env}]
(set-saving! env true)
(let [idk (rc/id-key form)
id (get form idk)]
(when (and idk id)
(swap! state fs/entity->pristine* [idk id]))))
(ok-action [env] (set-saving! env false))
(error-action [env] (set-saving! env false))
(remote [env]
(-> env
(m/with-params (fs/dirty-fields form true))
(m/returning User))))
(defn UserForm [_js-props]
(hooks/use-lifecycle (fn [] (df/load! raw-app :current-user User {:post-mutation `initialize-form
:marker ::user})))
(let [{:ui/keys [saving?]
:user/keys [id name settings] :as u} (hooks/use-root raw-app :current-user User {})
loading? (df/loading? (get-in u [df/marker-table ::user]))]
(div :.ui.segment
(h2 "Form")
(div :.ui.form {:classes [(when loading? "loading")]}
(div :.field
(label "Name")
(input {:value (or name "")
:onChange (fn [evt] (m/raw-set-value! raw-app u :user/name (evt/target-value evt)))}))
(let [{:settings/keys [marketing?]} settings]
(div :.ui.checkbox
(input {:type "checkbox"
:onChange (fn [_] (m/raw-update-value! raw-app settings :settings/marketing? not))
:checked (boolean marketing?)})
(label "Marketing Emails?")))
(div :.field
(dom/button :.ui.primary.button
{:classes [(when-not (fs/dirty? u) "disabled")
(when saving? "loading")]
:onClick (fn [] (comp/transact! raw-app [(save-form u)] {:ref [:user/id id]}))}
"Save"))))))
(def ui-user-form (interop/react-factory UserForm))
(defn RawReactWithFulcroIO [_] (ui-user-form))
(ws/defcard fulcro-io-composed-in-raw-react
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RawReactWithFulcroIO {})))
(def global-events {:event/unmounted {::uism/handler (fn [env] env)}})
(uism/defstatemachine session-machine
{::uism/actor-names
#{:actor/login-form :actor/current-account}
::uism/aliases
{:email [:actor/login-form :email]
:password [:actor/login-form :password]
:failed? [:actor/login-form :failed?]
:name [:actor/current-account :account/email]}
::uism/states
{:initial
{::uism/handler (fn [env]
(let [LoginForm (rc/nc [:component/id :email :password :failed?] {:componentName ::LoginForm})
Session (rc/nc [:account/id :account/email] {:componentName ::Session})]
(-> env
(uism/apply-action assoc-in [:account/id :none] {:account/id :none})
(uism/apply-action assoc-in [:component/id ::LoginForm] {:component/id ::LoginForm :email "" :password "" :failed? false})
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/reset-actor-ident :actor/login-form (uism/with-actor-class [:component/id ::LoginForm] LoginForm))
(uism/load :current-session :actor/current-account {::uism/ok-event :event/done
::uism/error-event :event/done})
(uism/activate :state/checking-session))))}
:state/checking-session
{::uism/events
(merge global-events
{:event/done {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [id (some-> state-map :current-session second)]
(cond-> env
(pos-int? id) (->
(uism/reset-actor-ident :actor/current-account [:account/id id])
(uism/activate :state/logged-in))
(not (pos-int? id)) (uism/activate :state/gathering-credentials))))}
:event/post-login {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [session-ident (get state-map :current-session)
Session (uism/actor-class env :actor/current-account)
logged-in? (pos-int? (second session-ident))]
(if logged-in?
(-> env
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class session-ident Session))
(uism/activate :state/logged-in))
(-> env
(uism/assoc-aliased :failed? true)
(uism/activate :state/gathering-credentials)))))}})}
:state/gathering-credentials
{::uism/events
(merge global-events
{:event/login {::uism/handler
(fn [env]
(-> env
(uism/assoc-aliased :failed? false)
(uism/trigger-remote-mutation :actor/login-form `login {:email (uism/alias-value env :email)
:password (uism/alias-value env :password)
::m/returning (uism/actor-class env :actor/current-account)
::dt/target [:current-session]
::uism/ok-event :event/post-login
::uism/error-event :event/post-login})
(uism/activate :state/checking-session)))}})}
:state/logged-in
{::uism/events
(merge global-events
{:event/logout {::uism/handler
(fn [env]
(let [Session (uism/actor-class env :actor/current-account)]
(-> env
(uism/apply-action assoc :account/id {:none {}})
(uism/assoc-aliased :email "" :password "" :failed? false)
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/trigger-remote-mutation :actor/current-account `logout {})
(uism/activate :state/gathering-credentials))))}})}}})
(defn ui-login-form [{:keys [email password failed?] :as login-form} checking?]
(div :.ui.segment
(h2 "Username is <EMAIL>, password is <PASSWORD>")
(div :.ui.form {:classes [(when failed? "error")
(when checking? "loading")]}
(div :.field
(label "Email")
(input {:value (or email "")
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :email (evt/target-value evt)))}))
(div :.field
(label "Password")
(input {:type "password"
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :password (evt/target-value evt)))
:value (or password "")}))
(div :.ui.error.message
"Invalid credentials. Please try again.")
(div :.field
(button :.ui.primary.button {:onClick (fn [] (uism/trigger! raw-app :sessions :event/login {}))} "Login")))))
(defn RootUISMSessions [_]
(let [{:actor/keys [login-form current-account]
:keys [active-state]
:as sm} (hooks/use-uism raw-app session-machine :sessions {})]
;; TODO: Not done yet...didn't have time to finish refining, but it looks like it'll work
(case active-state
:state/logged-in (div :.ui.segment
(dom/p {} (str "Hi," (:account/email current-account)))
(button :.ui.red.button {:onClick #(uism/trigger! raw-app :sessions :event/logout)} "Logout"))
(:state/checking-session :state/gathering-credentials) (ui-login-form login-form (= :state/checking-session active-state))
(div (str active-state)))))
(ws/defcard raw-uism-card
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RootUISMSessions {})))
| true |
(ns com.fulcrologic.fulcro.cards.composition4-cards
(:require
["react-dom" :as react-dom]
[clojure.pprint :refer [pprint]]
[nubank.workspaces.model :as wsm]
[nubank.workspaces.card-types.react :as ct.react]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[cljs.core.async :as async]
[com.fulcrologic.fulcro.dom :as dom :refer [div p input button h2 label]]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.raw.components :as rc]
[com.fulcrologic.fulcro.react.hooks :as hooks]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.mutations :as m]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.connect :as pc]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.inspect.inspect-client :as inspect]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.algorithms.data-targeting :as dt]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.dom.events :as evt]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.normalized-state :as fns]
[com.fulcrologic.fulcro.algorithms.lookup :as ah]
[edn-query-language.core :as eql]
[com.fulcrologic.fulcro.ui-state-machines :as uism]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mock Server and database, in Fulcro client format for ease of use in demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce pretend-server-database
(atom
{:settings/id {1 {:settings/id 1
:settings/marketing? true
:settings/theme :light-mode}}
:account/id {1000 {:account/id 1000
:account/email "PI:EMAIL:<EMAIL>END_PI"
:account/password "PI:PASSWORD:<PASSWORD>END_PI"}}
:user/id {100 {:user/id 100
:user/name "PI:NAME:<NAME>END_PI"
:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/settings [:settings/id 1]}}}))
(pc/defresolver settings-resolver [_ {:settings/keys [id]}]
{::pc/input #{:settings/id}
::pc/output [:settings/marketing? :settings/theme]}
(get-in @pretend-server-database [:settings/id id]))
(pc/defresolver user-resolver [_ {:user/keys [id]}]
{::pc/input #{:user/id}
::pc/output [:user/name :user/email :user/age {:user/settings [:settings/id]}]}
(try
(-> @pretend-server-database
(get-in [:user/id id])
(update :user/settings #(into {} [%])))
(catch :default e
(log/error e "Resolver fail"))))
(pc/defresolver current-user-resolver [_ _]
{::pc/output [{:current-user [:user/id]}]}
{:current-user {:user/id 100}})
(pc/defmutation server-save-form [_ form-diff]
{::pc/sym `save-form}
(swap! pretend-server-database
(fn [s]
(reduce-kv
(fn [final-state ident changes]
(reduce-kv
(fn [fs k {:keys [after]}]
(if (nil? after)
(update-in fs ident dissoc k)
(assoc-in fs (conj ident k) after)))
final-state
changes))
s
form-diff)))
(log/info "Updated server to:" (with-out-str (pprint @pretend-server-database)))
nil)
;; For the UISM DEMO
(defonce session-id (atom 1000)) ; pretend like we have server state to remember client
(pc/defresolver account-resolver [_ {:account/keys [id]}]
{::pc/input #{:account/id}
::pc/output [:account/email]}
(select-keys (get-in @pretend-server-database [:account/id id] {}) [:account/email]))
(pc/defresolver session-resolver [_ {:account/keys [id]}]
{::pc/output [{:current-session [:account/id]}]}
(if @session-id
{:current-session {:account/id @session-id}}
{:current-session {:account/id :none}}))
(pc/defmutation server-login [_ {:keys [email password]}]
{::pc/sym `login
::pc/output [:account/id]}
(let [accounts (vals (get @pretend-server-database :account/id))
account (first
(filter
(fn [a] (and (= password (:account/password a)) (= email (:account/email a))))
accounts))]
(when (log/spy :info "Found account" account)
(reset! session-id (:account/id account))
account)))
(pc/defmutation server-logout [_ _]
{::pc/sym `logout}
(reset! session-id nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Registration for the above resolvers and mutations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def resolvers [user-resolver current-user-resolver settings-resolver server-save-form account-resolver session-resolver
server-login server-logout])
(def pathom-parser (p/parser {::p/env {::p/reader [p/map-reader
pc/reader2
pc/open-ident-reader]
::pc/mutation-join-globals [:tempids]}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register [resolvers]})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin]}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Client. We close over the server parser above using a mock http server. The
;; extra level of indirection allows hot code reload to refresh the mock server and
;; parser without wiping out the app.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce raw-app
(let [process-eql (fn [eql] (async/go
(let [tm (async/timeout 300)]
(async/<! tm)
(pathom-parser {} eql))))
app (app/fulcro-app {:remotes {:remote (mock-http-server {:parser process-eql})}
:batch-notifications (fn [render!] (react-dom/unstable_batchedUpdates render!))})]
(inspect/app-started! app)
app))
;; TODO: Write `raw/formc` that makes a form automatically with form config join and form fields on everything that isn't an id
#_#_(def Settings (raw/nc [:settings/id :settings/marketing? fs/form-config-join] {:form-fields #{:settings/marketing?}}))
(def User (raw/nc [:user/id :user/name fs/form-config-join {:user/settings (comp/get-query Settings)}] {:form-fields #{:user/name
:user/settings}}))
(def User (fs/formc [:ui/saving? [df/marker-table '_]
:user/id :user/name
{:user/settings [:settings/id :settings/marketing?]}]))
(comment
(comp/component-options User)
(comp/get-ident User {:user/id 34})
(comp/get-initial-state User {})
(comp/get-ident User {:user/id 34})
(-> (comp/get-query User) (meta) (:component) (comp/get-query))
)
(m/defmutation initialize-form [_]
(action [{:keys [state]}]
(let [ident (get @state :current-user)]
(fns/swap!-> state
(fs/add-form-config* User ident {:destructive? true})
(fs/mark-complete* ident)))))
(defn- set-saving! [{:keys [state ref]} tf]
(when (vector? ref)
(swap! state assoc-in (conj ref :ui/saving?) tf)))
(m/defmutation save-form [form]
(action [{:keys [state] :as env}]
(set-saving! env true)
(let [idk (rc/id-key form)
id (get form idk)]
(when (and idk id)
(swap! state fs/entity->pristine* [idk id]))))
(ok-action [env] (set-saving! env false))
(error-action [env] (set-saving! env false))
(remote [env]
(-> env
(m/with-params (fs/dirty-fields form true))
(m/returning User))))
(defn UserForm [_js-props]
(hooks/use-lifecycle (fn [] (df/load! raw-app :current-user User {:post-mutation `initialize-form
:marker ::user})))
(let [{:ui/keys [saving?]
:user/keys [id name settings] :as u} (hooks/use-root raw-app :current-user User {})
loading? (df/loading? (get-in u [df/marker-table ::user]))]
(div :.ui.segment
(h2 "Form")
(div :.ui.form {:classes [(when loading? "loading")]}
(div :.field
(label "Name")
(input {:value (or name "")
:onChange (fn [evt] (m/raw-set-value! raw-app u :user/name (evt/target-value evt)))}))
(let [{:settings/keys [marketing?]} settings]
(div :.ui.checkbox
(input {:type "checkbox"
:onChange (fn [_] (m/raw-update-value! raw-app settings :settings/marketing? not))
:checked (boolean marketing?)})
(label "Marketing Emails?")))
(div :.field
(dom/button :.ui.primary.button
{:classes [(when-not (fs/dirty? u) "disabled")
(when saving? "loading")]
:onClick (fn [] (comp/transact! raw-app [(save-form u)] {:ref [:user/id id]}))}
"Save"))))))
(def ui-user-form (interop/react-factory UserForm))
(defn RawReactWithFulcroIO [_] (ui-user-form))
(ws/defcard fulcro-io-composed-in-raw-react
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RawReactWithFulcroIO {})))
(def global-events {:event/unmounted {::uism/handler (fn [env] env)}})
(uism/defstatemachine session-machine
{::uism/actor-names
#{:actor/login-form :actor/current-account}
::uism/aliases
{:email [:actor/login-form :email]
:password [:actor/login-form :password]
:failed? [:actor/login-form :failed?]
:name [:actor/current-account :account/email]}
::uism/states
{:initial
{::uism/handler (fn [env]
(let [LoginForm (rc/nc [:component/id :email :password :failed?] {:componentName ::LoginForm})
Session (rc/nc [:account/id :account/email] {:componentName ::Session})]
(-> env
(uism/apply-action assoc-in [:account/id :none] {:account/id :none})
(uism/apply-action assoc-in [:component/id ::LoginForm] {:component/id ::LoginForm :email "" :password "" :failed? false})
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/reset-actor-ident :actor/login-form (uism/with-actor-class [:component/id ::LoginForm] LoginForm))
(uism/load :current-session :actor/current-account {::uism/ok-event :event/done
::uism/error-event :event/done})
(uism/activate :state/checking-session))))}
:state/checking-session
{::uism/events
(merge global-events
{:event/done {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [id (some-> state-map :current-session second)]
(cond-> env
(pos-int? id) (->
(uism/reset-actor-ident :actor/current-account [:account/id id])
(uism/activate :state/logged-in))
(not (pos-int? id)) (uism/activate :state/gathering-credentials))))}
:event/post-login {::uism/handler
(fn [{::uism/keys [state-map] :as env}]
(let [session-ident (get state-map :current-session)
Session (uism/actor-class env :actor/current-account)
logged-in? (pos-int? (second session-ident))]
(if logged-in?
(-> env
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class session-ident Session))
(uism/activate :state/logged-in))
(-> env
(uism/assoc-aliased :failed? true)
(uism/activate :state/gathering-credentials)))))}})}
:state/gathering-credentials
{::uism/events
(merge global-events
{:event/login {::uism/handler
(fn [env]
(-> env
(uism/assoc-aliased :failed? false)
(uism/trigger-remote-mutation :actor/login-form `login {:email (uism/alias-value env :email)
:password (uism/alias-value env :password)
::m/returning (uism/actor-class env :actor/current-account)
::dt/target [:current-session]
::uism/ok-event :event/post-login
::uism/error-event :event/post-login})
(uism/activate :state/checking-session)))}})}
:state/logged-in
{::uism/events
(merge global-events
{:event/logout {::uism/handler
(fn [env]
(let [Session (uism/actor-class env :actor/current-account)]
(-> env
(uism/apply-action assoc :account/id {:none {}})
(uism/assoc-aliased :email "" :password "" :failed? false)
(uism/reset-actor-ident :actor/current-account (uism/with-actor-class [:account/id :none] Session))
(uism/trigger-remote-mutation :actor/current-account `logout {})
(uism/activate :state/gathering-credentials))))}})}}})
(defn ui-login-form [{:keys [email password failed?] :as login-form} checking?]
(div :.ui.segment
(h2 "Username is PI:EMAIL:<EMAIL>END_PI, password is PI:PASSWORD:<PASSWORD>END_PI")
(div :.ui.form {:classes [(when failed? "error")
(when checking? "loading")]}
(div :.field
(label "Email")
(input {:value (or email "")
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :email (evt/target-value evt)))}))
(div :.field
(label "Password")
(input {:type "password"
:onChange (fn [evt] (m/raw-set-value! raw-app login-form :password (evt/target-value evt)))
:value (or password "")}))
(div :.ui.error.message
"Invalid credentials. Please try again.")
(div :.field
(button :.ui.primary.button {:onClick (fn [] (uism/trigger! raw-app :sessions :event/login {}))} "Login")))))
(defn RootUISMSessions [_]
(let [{:actor/keys [login-form current-account]
:keys [active-state]
:as sm} (hooks/use-uism raw-app session-machine :sessions {})]
;; TODO: Not done yet...didn't have time to finish refining, but it looks like it'll work
(case active-state
:state/logged-in (div :.ui.segment
(dom/p {} (str "Hi," (:account/email current-account)))
(button :.ui.red.button {:onClick #(uism/trigger! raw-app :sessions :event/logout)} "Logout"))
(:state/checking-session :state/gathering-credentials) (ui-login-form login-form (= :state/checking-session active-state))
(div (str active-state)))))
(ws/defcard raw-uism-card
{::wsm/align {:flex 1}}
(ct.react/react-card
(dom/create-element RootUISMSessions {})))
|
[
{
"context": "oc \"Hello world for neanderthal/mkl.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-24\"\n :version \"2017-04-25\"}",
"end": 287,
"score": 0.9936220049858093,
"start": 251,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] |
src/scripts/clojure/palisades/lakes/elements/scripts/uncomplicate/mkl.clj
|
palisades-lakes/les-elemens
| 0 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.mkl
{:doc "Hello world for neanderthal/mkl."
:author "palisades dot lakes at gmail dot com"
:since "2017-04-24"
:version "2017-04-25"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def x (unn/dv (into [] (defs/uniform-doubles (* 32 1024 1024)))))
(println (unc/dim x))
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))
;;----------------------------------------------------------------
|
38843
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.mkl
{:doc "Hello world for neanderthal/mkl."
:author "<EMAIL>"
:since "2017-04-24"
:version "2017-04-25"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def x (unn/dv (into [] (defs/uniform-doubles (* 32 1024 1024)))))
(println (unc/dim x))
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))
;;----------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.elements.scripts.uncomplicate.mkl
{:doc "Hello world for neanderthal/mkl."
:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-04-24"
:version "2017-04-25"}
(:require [clojure.pprint :as pp]
[palisades.lakes.elements.scripts.defs :as defs]))
;;----------------------------------------------------------------
(set! *warn-on-reflection* false) ;
(set! *unchecked-math* false)
(require '[uncomplicate.neanderthal
[core :as unc]
[native :as unn]])
(require '[criterium.core :as criterium])
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(def x (unn/dv (into [] (defs/uniform-doubles (* 32 1024 1024)))))
(println (unc/dim x))
(pp/pprint
(defs/simplify
(time
(criterium/benchmark (unc/sum x) {}))))
;;----------------------------------------------------------------
|
[
{
"context": "t : Make a program that does anything\n;; Student : Nirman Dave\n\n;; Program information\n;; ---\n;; Name : Patinc\n;",
"end": 181,
"score": 0.9998403787612915,
"start": 170,
"tag": "NAME",
"value": "Nirman Dave"
},
{
"context": "rman Dave\n\n;; Program information\n;; ---\n;; Name : Patinc\n;; Version : 1.0\n;; Description : A program that ",
"end": 229,
"score": 0.9991142749786377,
"start": 223,
"tag": "NAME",
"value": "Patinc"
}
] |
patinc-code.clj
|
nddave/AI-Assignment-1
| 1 |
;; This is my canvas. This is my art.
;; Assignment information
;; ---
;; Class : Artificial Intelligence
;; Assignment : Make a program that does anything
;; Student : Nirman Dave
;; Program information
;; ---
;; Name : Patinc
;; Version : 1.0
;; Description : A program that identifies pattern between three numbers
;; and generates formulas for the pattern so that anyone
;; can easily predict the pattern using the formula.
;; Language : Clojure
;; Importing default libraries and name space
(ns patinc.core
(:gen-class))
;; The program is divided into two parts.
;; 1) Pattern identification
;; 2) Formula Making
;; ====
;; PATTERN IDENTIFICATION
;; ====
;; This part of the program goes on to define two distinct pattern recognition tests.
;; One is for Arithmetic Progression, another is for Geometric Progression.
;; Defining test for Arithmetic progression, for three values.
(defn aptest [a b c]
;; An 'if' condition identifies if the difference between numbers is the same or not.
(if (= (- b a) (- c b))
;; If the condition is satisfied, the following text is printed.
"\nAP; conduct 'aform' for formula\n"
;; Else, the following text is printed.
"not an AP"))
;; Defining test for Geometric progression, for three values.
(defn gptest [a b c]
;; This uses the same code language for the 'aptest' module.
;; An 'if' condition identifies if the division between numbers has the same result or not.
(if (= (/ b a) (/ c b))
"\nGP; conduct 'gform' for formula\n"
"not an GP"))
;; In most cases the user does not know what they are looking for in a pattern.
;; So therefore the following code runs both, the 'aptest' and the 'gptest', on the values given to find out
;; what the pattern is.
;; Defining test for an unknown pattern, 'patrec' stands for pattern recognition.
(defn patrec [a b c]
(println (aptest a b c))
(println (gptest a b c))
)
;; ====
;; FORMULA MAKING
;; ====
;; Once the user is aware of the pattern in the numbers, it is now time to make a formula that defines the pattern.
;; Using this formula, the user can calculate the value of nth term in the pattern.
;; Defining formula for Arithmetic progression, for the three values.
(defn aform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def difference-value (- b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = " first-number " + ((n-1)*" difference-value ")\n"))
)
;; Defining formula for Geometric progression, for the three values.
(defn gform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def r-value (/ b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = (" first-number "(1-" r-value "^n)) / (1-" r-value ")\n" ))
)
|
105491
|
;; This is my canvas. This is my art.
;; Assignment information
;; ---
;; Class : Artificial Intelligence
;; Assignment : Make a program that does anything
;; Student : <NAME>
;; Program information
;; ---
;; Name : <NAME>
;; Version : 1.0
;; Description : A program that identifies pattern between three numbers
;; and generates formulas for the pattern so that anyone
;; can easily predict the pattern using the formula.
;; Language : Clojure
;; Importing default libraries and name space
(ns patinc.core
(:gen-class))
;; The program is divided into two parts.
;; 1) Pattern identification
;; 2) Formula Making
;; ====
;; PATTERN IDENTIFICATION
;; ====
;; This part of the program goes on to define two distinct pattern recognition tests.
;; One is for Arithmetic Progression, another is for Geometric Progression.
;; Defining test for Arithmetic progression, for three values.
(defn aptest [a b c]
;; An 'if' condition identifies if the difference between numbers is the same or not.
(if (= (- b a) (- c b))
;; If the condition is satisfied, the following text is printed.
"\nAP; conduct 'aform' for formula\n"
;; Else, the following text is printed.
"not an AP"))
;; Defining test for Geometric progression, for three values.
(defn gptest [a b c]
;; This uses the same code language for the 'aptest' module.
;; An 'if' condition identifies if the division between numbers has the same result or not.
(if (= (/ b a) (/ c b))
"\nGP; conduct 'gform' for formula\n"
"not an GP"))
;; In most cases the user does not know what they are looking for in a pattern.
;; So therefore the following code runs both, the 'aptest' and the 'gptest', on the values given to find out
;; what the pattern is.
;; Defining test for an unknown pattern, 'patrec' stands for pattern recognition.
(defn patrec [a b c]
(println (aptest a b c))
(println (gptest a b c))
)
;; ====
;; FORMULA MAKING
;; ====
;; Once the user is aware of the pattern in the numbers, it is now time to make a formula that defines the pattern.
;; Using this formula, the user can calculate the value of nth term in the pattern.
;; Defining formula for Arithmetic progression, for the three values.
(defn aform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def difference-value (- b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = " first-number " + ((n-1)*" difference-value ")\n"))
)
;; Defining formula for Geometric progression, for the three values.
(defn gform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def r-value (/ b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = (" first-number "(1-" r-value "^n)) / (1-" r-value ")\n" ))
)
| true |
;; This is my canvas. This is my art.
;; Assignment information
;; ---
;; Class : Artificial Intelligence
;; Assignment : Make a program that does anything
;; Student : PI:NAME:<NAME>END_PI
;; Program information
;; ---
;; Name : PI:NAME:<NAME>END_PI
;; Version : 1.0
;; Description : A program that identifies pattern between three numbers
;; and generates formulas for the pattern so that anyone
;; can easily predict the pattern using the formula.
;; Language : Clojure
;; Importing default libraries and name space
(ns patinc.core
(:gen-class))
;; The program is divided into two parts.
;; 1) Pattern identification
;; 2) Formula Making
;; ====
;; PATTERN IDENTIFICATION
;; ====
;; This part of the program goes on to define two distinct pattern recognition tests.
;; One is for Arithmetic Progression, another is for Geometric Progression.
;; Defining test for Arithmetic progression, for three values.
(defn aptest [a b c]
;; An 'if' condition identifies if the difference between numbers is the same or not.
(if (= (- b a) (- c b))
;; If the condition is satisfied, the following text is printed.
"\nAP; conduct 'aform' for formula\n"
;; Else, the following text is printed.
"not an AP"))
;; Defining test for Geometric progression, for three values.
(defn gptest [a b c]
;; This uses the same code language for the 'aptest' module.
;; An 'if' condition identifies if the division between numbers has the same result or not.
(if (= (/ b a) (/ c b))
"\nGP; conduct 'gform' for formula\n"
"not an GP"))
;; In most cases the user does not know what they are looking for in a pattern.
;; So therefore the following code runs both, the 'aptest' and the 'gptest', on the values given to find out
;; what the pattern is.
;; Defining test for an unknown pattern, 'patrec' stands for pattern recognition.
(defn patrec [a b c]
(println (aptest a b c))
(println (gptest a b c))
)
;; ====
;; FORMULA MAKING
;; ====
;; Once the user is aware of the pattern in the numbers, it is now time to make a formula that defines the pattern.
;; Using this formula, the user can calculate the value of nth term in the pattern.
;; Defining formula for Arithmetic progression, for the three values.
(defn aform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def difference-value (- b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = " first-number " + ((n-1)*" difference-value ")\n"))
)
;; Defining formula for Geometric progression, for the three values.
(defn gform [a b c]
;; The code splits the numbers into variables.
(def first-number a)
(def r-value (/ b a))
;; Prints out the formula using the variables defined.
(println (str "\nnth term = (" first-number "(1-" r-value "^n)) / (1-" r-value ")\n" ))
)
|
[
{
"context": "gan County\"\n \"01105\" \"Perry County\"\n \"01107\" \"Pickens County\"\n \"01109\" \"Pike County\"\n \"01111\" \"",
"end": 1580,
"score": 0.5682514309883118,
"start": 1577,
"tag": "NAME",
"value": "Pic"
},
{
"context": "son County\"\n \"08061\" \"Kiowa County\"\n \"08063\" \"Kit Carson County\"\n \"08065\" \"Lake County\"\n \"08067\" \"La P",
"end": 8187,
"score": 0.9587672352790833,
"start": 8177,
"tag": "NAME",
"value": "Kit Carson"
},
{
"context": "tte County\"\n \"13115\" \"Floyd County\"\n \"13117\" \"Forsyth County\"\n \"13119\" \"Franklin County\"\n \"13121\"",
"end": 12977,
"score": 0.6015740633010864,
"start": 12972,
"tag": "NAME",
"value": "Forsy"
},
{
"context": "in County\"\n \"13121\" \"Fulton County\"\n \"13123\" \"Gilmer County\"\n \"13125\" \"Glascock County\"\n \"131",
"end": 13057,
"score": 0.5827657580375671,
"start": 13056,
"tag": "NAME",
"value": "G"
},
{
"context": "on County\"\n \"13123\" \"Gilmer County\"\n \"13125\" \"Glascock County\"\n \"13127\" \"Glynn County\"\n \"13129\" ",
"end": 13087,
"score": 0.7837545275688171,
"start": 13083,
"tag": "NAME",
"value": "Glas"
},
{
"context": " County\"\n \"13125\" \"Glascock County\"\n \"13127\" \"Glynn County\"\n \"13129\" \"Gordon County\"\n \"13131\" \"Gr",
"end": 13117,
"score": 0.9041668772697449,
"start": 13112,
"tag": "NAME",
"value": "Glynn"
},
{
"context": "ock County\"\n \"13127\" \"Glynn County\"\n \"13129\" \"Gordon County\"\n \"13131\" \"Grady County\"\n \"13133\" \"Gre",
"end": 13144,
"score": 0.656715452671051,
"start": 13138,
"tag": "NAME",
"value": "Gordon"
},
{
"context": "l County\"\n \"13141\" \"Hancock County\"\n \"13143\" \"Haralson County\"\n \"13145\" \"Harris County\"\n \"13147\" ",
"end": 13335,
"score": 0.6297390460968018,
"start": 13330,
"tag": "NAME",
"value": "Haral"
},
{
"context": "ton County\"\n \"13155\" \"Irwin County\"\n \"13157\" \"Jackson County\"\n \"13159\" \"Jasper County\"\n \"13161\" ",
"end": 13521,
"score": 0.716763436794281,
"start": 13517,
"tag": "NAME",
"value": "Jack"
},
{
"context": " County\"\n \"13157\" \"Jackson County\"\n \"13159\" \"Jasper County\"\n \"13161\" \"Jeff Davis County\"\n \"13163\"",
"end": 13551,
"score": 0.5376591682434082,
"start": 13546,
"tag": "NAME",
"value": "asper"
},
{
"context": "on County\"\n \"13159\" \"Jasper County\"\n \"13161\" \"Jeff Davis County\"\n \"13163\" \"Jefferson County\"\n \"13165\" ",
"end": 13582,
"score": 0.8851855397224426,
"start": 13572,
"tag": "NAME",
"value": "Jeff Davis"
},
{
"context": "ounty\"\n \"13161\" \"Jeff Davis County\"\n \"13163\" \"Jefferson County\"\n \"13165\" \"Jenkins County\"\n \"13167\" \"J",
"end": 13612,
"score": 0.7762038111686707,
"start": 13603,
"tag": "NAME",
"value": "Jefferson"
},
{
"context": "County\"\n \"13163\" \"Jefferson County\"\n \"13165\" \"Jenkins County\"\n \"13167\" \"Johnson County\"\n \"131",
"end": 13634,
"score": 0.8795999884605408,
"start": 13633,
"tag": "NAME",
"value": "J"
},
{
"context": "ne County\"\n \"16081\" \"Teton County\"\n \"16083\" \"Twin Falls County\"\n \"16085\" \"Valley County\"\n \"1608",
"end": 17081,
"score": 0.6284331679344177,
"start": 17078,
"tag": "NAME",
"value": "win"
},
{
"context": " County\"\n \"17075\" \"Iroquois County\"\n \"17077\" \"Jackson County\"\n \"17079\" \"Jasper County\"\n \"17081\" ",
"end": 18235,
"score": 0.7861290574073792,
"start": 18231,
"tag": "NAME",
"value": "Jack"
},
{
"context": "on County\"\n \"17079\" \"Jasper County\"\n \"17081\" \"Jefferson County\"\n \"17083\" \"Jersey County\"\n \"17085",
"end": 18290,
"score": 0.7035260796546936,
"start": 18286,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "on County\"\n \"17083\" \"Jersey County\"\n \"17085\" \"Jo Daviess County\"\n \"17087\" \"Johnson County\"\n \"17089\" \"K",
"end": 18353,
"score": 0.9990944862365723,
"start": 18343,
"tag": "NAME",
"value": "Jo Daviess"
},
{
"context": "ounty\"\n \"17085\" \"Jo Daviess County\"\n \"17087\" \"Johnson County\"\n \"17089\" \"Kane County\"\n \"17091\" \"K",
"end": 18378,
"score": 0.7038273215293884,
"start": 18374,
"tag": "NAME",
"value": "John"
},
{
"context": "ounty\"\n \"18069\" \"Huntington County\"\n \"18071\" \"Jackson County\"\n \"18073\" \"Jasper County\"\n \"18075\" \"Ja",
"end": 21002,
"score": 0.7090645432472229,
"start": 20995,
"tag": "NAME",
"value": "Jackson"
},
{
"context": "asper County\"\n \"18075\" \"Jay County\"\n \"18077\" \"Jefferson County\"\n \"18079\" \"Jennings County\"\n \"",
"end": 21075,
"score": 0.5449247360229492,
"start": 21074,
"tag": "NAME",
"value": "J"
},
{
"context": " County\"\n \"18099\" \"Marshall County\"\n \"18101\" \"Martin County\"\n \"18103\" \"Miami County\"\n \"18105\" \"M",
"end": 21415,
"score": 0.6058734655380249,
"start": 21411,
"tag": "NAME",
"value": "Mart"
},
{
"context": "ounty\"\n \"18141\" \"St. Joseph County\"\n \"18143\" \"Scott County\"\n \"18145\" \"Shelby County\"\n \"18147\"",
"end": 21977,
"score": 0.6429954767227173,
"start": 21976,
"tag": "NAME",
"value": "S"
},
{
"context": "\"Ida County\"\n \"19095\" \"Iowa County\"\n \"19097\" \"Jackson County\"\n \"19099\" \"Jasper County\"\n \"19101\" ",
"end": 23919,
"score": 0.5912736654281616,
"start": 23915,
"tag": "NAME",
"value": "Jack"
},
{
"context": "on County\"\n \"19099\" \"Jasper County\"\n \"19101\" \"Jefferson County\"\n \"19103\" \"Johnson County\"\n \"1",
"end": 23971,
"score": 0.6569603681564331,
"start": 23970,
"tag": "NAME",
"value": "J"
},
{
"context": "County\"\n \"19101\" \"Jefferson County\"\n \"19103\" \"Johnson County\"\n \"19105\" \"Jones County\"\n \"19107\" \"",
"end": 24004,
"score": 0.9351497888565063,
"start": 24000,
"tag": "NAME",
"value": "John"
},
{
"context": "lor County\"\n \"19175\" \"Union County\"\n \"19177\" \"Van Buren County\"\n \"19179\" \"Wapello County\"\n \"191",
"end": 25017,
"score": 0.5689181685447693,
"start": 25014,
"tag": "NAME",
"value": "Van"
},
{
"context": " County\"\n \"20083\" \"Hodgeman County\"\n \"20085\" \"Jackson County\"\n \"20087\" \"Jefferson County\"\n \"2008",
"end": 26502,
"score": 0.606182873249054,
"start": 26498,
"tag": "NAME",
"value": "Jack"
},
{
"context": "on County\"\n \"20089\" \"Jewell County\"\n \"20091\" \"Johnson County\"\n \"20093\" \"Kearny County\"\n \"20095\" ",
"end": 26587,
"score": 0.6567600965499878,
"start": 26583,
"tag": "NAME",
"value": "John"
},
{
"context": "n County\"\n \"21107\" \"Hopkins County\"\n \"21109\" \"Jackson County\"\n \"21111\" \"Jefferson County\"\n \"2111",
"end": 29752,
"score": 0.8016636967658997,
"start": 29748,
"tag": "NAME",
"value": "Jack"
},
{
"context": "s County\"\n \"21109\" \"Jackson County\"\n \"21111\" \"Jefferson County\"\n \"21113\" \"Jessamine County\"\n \"21",
"end": 29780,
"score": 0.651398777961731,
"start": 29776,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "County\"\n \"21113\" \"Jessamine County\"\n \"21115\" \"Johnson County\"\n \"21117\" \"Kenton County\"\n \"21119\" ",
"end": 29840,
"score": 0.5987178683280945,
"start": 29836,
"tag": "NAME",
"value": "John"
},
{
"context": "ounty\"\n \"21177\" \"Muhlenberg County\"\n \"21179\" \"Nelson County\"\n \"21181\" \"Nicholas County\"\n \"211",
"end": 30718,
"score": 0.8110426664352417,
"start": 30717,
"tag": "NAME",
"value": "N"
},
{
"context": "l County\"\n \"21199\" \"Pulaski County\"\n \"21201\" \"Robertson County\"\n \"21203\" \"Rockcastle County\"\n \"21205\"",
"end": 31022,
"score": 0.8868468403816223,
"start": 31013,
"tag": "NAME",
"value": "Robertson"
},
{
"context": "tle County\"\n \"21205\" \"Rowan County\"\n \"21207\" \"Russell County\"\n \"21209\" \"Scott County\"\n \"21211",
"end": 31101,
"score": 0.5373730063438416,
"start": 31100,
"tag": "NAME",
"value": "R"
},
{
"context": " County\"\n \"21207\" \"Russell County\"\n \"21209\" \"Scott County\"\n \"21211\" \"Shelby County\"\n \"21213\" \"Si",
"end": 31133,
"score": 0.5603998899459839,
"start": 31129,
"tag": "NAME",
"value": "cott"
},
{
"context": "tt County\"\n \"21211\" \"Shelby County\"\n \"21213\" \"Simpson County\"\n \"21215\" \"Spencer County\"\n \"21217\" \"T",
"end": 31188,
"score": 0.7768797874450684,
"start": 31181,
"tag": "NAME",
"value": "Simpson"
},
{
"context": "y County\"\n \"21213\" \"Simpson County\"\n \"21215\" \"Spencer County\"\n \"21217\" \"Taylor County\"\n \"21219\" ",
"end": 31213,
"score": 0.6208764314651489,
"start": 31209,
"tag": "NAME",
"value": "Spen"
},
{
"context": "er County\"\n \"21217\" \"Taylor County\"\n \"21219\" \"Todd County\"\n \"21221\" \"Trigg County\"\n \"21223\" \"Tri",
"end": 31268,
"score": 0.7195248603820801,
"start": 31264,
"tag": "NAME",
"value": "Todd"
},
{
"context": "ier Parish\"\n \"22017\" \"Caddo Parish\"\n \"22019\" \"Calcasieu Parish\"\n \"22021\" \"Caldwell Parish\"\n \"22023\" \"",
"end": 31852,
"score": 0.8577203750610352,
"start": 31843,
"tag": "NAME",
"value": "Calcasieu"
},
{
"context": " Parish\"\n \"22021\" \"Caldwell Parish\"\n \"22023\" \"Cameron Parish\"\n \"22025\" \"Catahoula Parish\"\n \"22027\" ",
"end": 31909,
"score": 0.9074153900146484,
"start": 31902,
"tag": "NAME",
"value": "Cameron"
},
{
"context": "Parish\"\n \"22047\" \"Iberville Parish\"\n \"22049\" \"Jackson Parish\"\n \"22051\" \"Jefferson Parish\"\n \"22053\" ",
"end": 32303,
"score": 0.9556044340133667,
"start": 32296,
"tag": "NAME",
"value": "Jackson"
},
{
"context": "e Parish\"\n \"22049\" \"Jackson Parish\"\n \"22051\" \"Jefferson Parish\"\n \"22053\" \"Jefferson Davis Parish\"\n \"2",
"end": 32333,
"score": 0.9043075442314148,
"start": 32324,
"tag": "NAME",
"value": "Jefferson"
},
{
"context": "Parish\"\n \"22051\" \"Jefferson Parish\"\n \"22053\" \"Jefferson Davis Parish\"\n \"22055\" \"Lafayette Parish\"\n \"22057\" \"Lafour",
"end": 32376,
"score": 0.9971283674240112,
"start": 32354,
"tag": "NAME",
"value": "Jefferson Davis Parish"
},
{
"context": "e Parish\"\n \"22059\" \"LaSalle Parish\"\n \"22061\" \"Lincoln Parish\"\n \"22063\" \"Livingston Parish\"\n \"22065\" \"Madis",
"end": 32492,
"score": 0.8722019195556641,
"start": 32478,
"tag": "NAME",
"value": "Lincoln Parish"
},
{
"context": "n County\"\n \"28061\" \"Jasper County\"\n \"28063\" \"Jefferson County\"\n \"28065\" \"Jefferson Davis County\"\n",
"end": 40850,
"score": 0.6288245916366577,
"start": 40847,
"tag": "NAME",
"value": "eff"
},
{
"context": "County\"\n \"28063\" \"Jefferson County\"\n \"28065\" \"Jefferson Davis County\"\n \"28067\" \"Jones County\"\n \"28069\" \"Kem",
"end": 40891,
"score": 0.8601033091545105,
"start": 40876,
"tag": "NAME",
"value": "Jefferson Davis"
},
{
"context": "s County\"\n \"28119\" \"Quitman County\"\n \"28121\" \"Rankin County\"\n \"28123\" \"Scott County\"\n \"28125\" \"S",
"end": 41670,
"score": 0.6356666088104248,
"start": 41666,
"tag": "NAME",
"value": "Rank"
},
{
"context": "de County\"\n \"29059\" \"Dallas County\"\n \"29061\" \"Daviess County\"\n \"29063\" \"DeKalb County\"\n \"29065\" \"De",
"end": 43132,
"score": 0.763282299041748,
"start": 43125,
"tag": "NAME",
"value": "Daviess"
},
{
"context": "s County\"\n \"29061\" \"Daviess County\"\n \"29063\" \"DeKalb County\"\n \"29065\" \"Dent County\"\n \"29067\" \"Doug",
"end": 43159,
"score": 0.6713173389434814,
"start": 43153,
"tag": "NAME",
"value": "DeKalb"
},
{
"context": "s County\"\n \"29069\" \"Dunklin County\"\n \"29071\" \"Franklin County\"\n \"29073\" \"Gasconade County\"\n \"2",
"end": 43263,
"score": 0.5371013879776001,
"start": 43261,
"tag": "NAME",
"value": "Fr"
},
{
"context": "well County\"\n \"29093\" \"Iron County\"\n \"29095\" \"Jackson County\"\n \"29097\" \"Jasper County\"\n \"29099\" ",
"end": 43592,
"score": 0.70406174659729,
"start": 43588,
"tag": "NAME",
"value": "Jack"
},
{
"context": "on County\"\n \"29097\" \"Jasper County\"\n \"29099\" \"Jefferson County\"\n \"29101\" \"Johnson County\"\n \"2910",
"end": 43647,
"score": 0.8240674734115601,
"start": 43643,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "County\"\n \"29099\" \"Jefferson County\"\n \"29101\" \"Johnson County\"\n \"29103\" \"Knox County\"\n \"29105\" \"L",
"end": 43677,
"score": 0.9109839200973511,
"start": 43673,
"tag": "NAME",
"value": "John"
},
{
"context": "n County\"\n \"29101\" \"Johnson County\"\n \"29103\" \"Knox County\"\n \"29105\" \"Laclede County\"\n \"29107\" \"L",
"end": 43705,
"score": 0.6251038312911987,
"start": 43701,
"tag": "NAME",
"value": "Knox"
},
{
"context": "e County\"\n \"37097\" \"Iredell County\"\n \"37099\" \"Jackson County\"\n \"37101\" \"Johnston County\"\n \"37103",
"end": 55195,
"score": 0.5916656255722046,
"start": 55191,
"tag": "NAME",
"value": "Jack"
},
{
"context": " County\"\n \"46081\" \"Lawrence County\"\n \"46083\" \"Lincoln County\"\n \"46085\" \"Lyman County\"\n \"46087\" ",
"end": 68276,
"score": 0.5297182202339172,
"start": 68273,
"tag": "NAME",
"value": "Lin"
},
{
"context": "e County\"\n \"46083\" \"Lincoln County\"\n \"46085\" \"Lyman County\"\n \"46087\" \"McCook County\"\n \"46089\" \"Mc",
"end": 68306,
"score": 0.6091945171356201,
"start": 68301,
"tag": "NAME",
"value": "Lyman"
},
{
"context": "an County\"\n \"46087\" \"McCook County\"\n \"46089\" \"McPherson County\"\n \"46091\" \"Marshall County\"\n \"460",
"end": 68358,
"score": 0.6685235500335693,
"start": 68354,
"tag": "NAME",
"value": "McPh"
},
{
"context": "ns County\"\n \"46107\" \"Potter County\"\n \"46109\" \"Roberts County\"\n \"46111\" \"Sanborn County\"\n \"46115",
"end": 68673,
"score": 0.7357094883918762,
"start": 68670,
"tag": "NAME",
"value": "Rob"
},
{
"context": "k County\"\n \"46117\" \"Stanley County\"\n \"46119\" \"Sully County\"\n \"46121\" \"Todd County\"\n \"46123\" \"",
"end": 68781,
"score": 0.514369010925293,
"start": 68780,
"tag": "NAME",
"value": "S"
},
{
"context": "ley County\"\n \"46119\" \"Sully County\"\n \"46121\" \"Todd County\"\n \"46123\" \"Tripp County\"\n \"46125\" \"",
"end": 68807,
"score": 0.7106457948684692,
"start": 68806,
"tag": "NAME",
"value": "T"
},
{
"context": "odd County\"\n \"46123\" \"Tripp County\"\n \"46125\" \"Turner County\"\n \"46127\" \"Union County\"\n \"46129\" \"W",
"end": 68861,
"score": 0.6639096736907959,
"start": 68857,
"tag": "NAME",
"value": "Turn"
},
{
"context": "ounty\"\n \"47035\" \"Cumberland County\"\n \"47037\" \"Davidson County\"\n \"47039\" \"Decatur County\"\n \"47041\"",
"end": 69523,
"score": 0.7959877848625183,
"start": 69518,
"tag": "NAME",
"value": "David"
},
{
"context": " County\"\n \"47069\" \"Hardeman County\"\n \"47071\" \"Hardin County\"\n \"47073\" \"Hawkins County\"\n \"47075\" \"H",
"end": 69997,
"score": 0.6523267030715942,
"start": 69991,
"tag": "NAME",
"value": "Hardin"
},
{
"context": "s County\"\n \"47087\" \"Jackson County\"\n \"47089\" \"Jefferson County\"\n \"47091\" \"Johnson County\"\n \"4",
"end": 70245,
"score": 0.7532773613929749,
"start": 70244,
"tag": "NAME",
"value": "J"
},
{
"context": "hea County\"\n \"47145\" \"Roane County\"\n \"47147\" \"Robertson County\"\n \"47149\" \"Rutherford County\"\n \"471",
"end": 71038,
"score": 0.5675931572914124,
"start": 71032,
"tag": "NAME",
"value": "Robert"
},
{
"context": "coi County\"\n \"47173\" \"Union County\"\n \"47175\" \"Van Buren County\"\n \"47177\" \"Warren County\"\n \"47179\" \"Wa",
"end": 71433,
"score": 0.6750240325927734,
"start": 71424,
"tag": "NAME",
"value": "Van Buren"
},
{
"context": " County\"\n \"48133\" \"Eastland County\"\n \"48135\" \"Ector County\"\n \"48137\" \"Edwards County\"\n \"48139\" \"E",
"end": 73518,
"score": 0.6029646992683411,
"start": 73513,
"tag": "NAME",
"value": "Ector"
},
{
"context": "and County\"\n \"48135\" \"Ector County\"\n \"48137\" \"Edwards County\"\n \"48139\" \"Ellis County\"\n \"48141\"",
"end": 73541,
"score": 0.5220041275024414,
"start": 73539,
"tag": "NAME",
"value": "Ed"
},
{
"context": "rds County\"\n \"48139\" \"Ellis County\"\n \"48141\" \"El Paso County\"\n \"48143\" \"Erath County\"\n \"48145\"",
"end": 73595,
"score": 0.6209415793418884,
"start": 73593,
"tag": "NAME",
"value": "El"
},
{
"context": "ck County\"\n \"48175\" \"Goliad County\"\n \"48177\" \"Gonzales County\"\n \"48179\" \"Gray County\"\n \"48181",
"end": 74092,
"score": 0.6706743836402893,
"start": 74091,
"tag": "NAME",
"value": "G"
},
{
"context": "ales County\"\n \"48179\" \"Gray County\"\n \"48181\" \"Grayson County\"\n \"48183\" \"Gregg County\"\n \"48185\" \"",
"end": 74149,
"score": 0.7754129767417908,
"start": 74145,
"tag": "NAME",
"value": "Gray"
},
{
"context": " County\"\n \"48211\" \"Hemphill County\"\n \"48213\" \"Henderson County\"\n \"48215\" \"Hidalgo County\"\n \"4821",
"end": 74590,
"score": 0.6083109378814697,
"start": 74586,
"tag": "NAME",
"value": "Hend"
},
{
"context": "County\"\n \"48213\" \"Henderson County\"\n \"48215\" \"Hidalgo County\"\n \"48217\" \"Hill County\"\n \"48219\" \"",
"end": 74619,
"score": 0.7429129481315613,
"start": 74616,
"tag": "NAME",
"value": "Hid"
},
{
"context": "on County\"\n \"48227\" \"Howard County\"\n \"48229\" \"Hudspeth County\"\n \"48231\" \"Hunt County\"\n \"48233\" \"Hutc",
"end": 74813,
"score": 0.6703920960426331,
"start": 74805,
"tag": "NAME",
"value": "Hudspeth"
},
{
"context": "ounty\"\n \"48233\" \"Hutchinson County\"\n \"48235\" \"Irion County\"\n \"48237\" \"Jack County\"\n \"48239\" \"J",
"end": 74892,
"score": 0.5291907787322998,
"start": 74890,
"tag": "NAME",
"value": "Ir"
},
{
"context": "rion County\"\n \"48237\" \"Jack County\"\n \"48239\" \"Jackson County\"\n \"48241\" \"Jasper County\"\n \"48243\" \"Je",
"end": 74948,
"score": 0.8535884022712708,
"start": 74941,
"tag": "NAME",
"value": "Jackson"
},
{
"context": " County\"\n \"48239\" \"Jackson County\"\n \"48241\" \"Jasper County\"\n \"48243\" \"Jeff Davis County\"\n \"48245\"",
"end": 74975,
"score": 0.6355467438697815,
"start": 74970,
"tag": "NAME",
"value": "asper"
},
{
"context": "on County\"\n \"48241\" \"Jasper County\"\n \"48243\" \"Jeff Davis County\"\n \"48245\" \"Jefferson County\"\n \"48247\" ",
"end": 75006,
"score": 0.982342004776001,
"start": 74996,
"tag": "NAME",
"value": "Jeff Davis"
},
{
"context": "ounty\"\n \"48243\" \"Jeff Davis County\"\n \"48245\" \"Jefferson County\"\n \"48247\" \"Jim Hogg County\"\n \"482",
"end": 75031,
"score": 0.8326390981674194,
"start": 75027,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "County\"\n \"48245\" \"Jefferson County\"\n \"48247\" \"Jim Hogg County\"\n \"48249\" \"Jim Wells County\"\n \"48251\" ",
"end": 75065,
"score": 0.9112529754638672,
"start": 75057,
"tag": "NAME",
"value": "Jim Hogg"
},
{
"context": " County\"\n \"48247\" \"Jim Hogg County\"\n \"48249\" \"Jim Wells County\"\n \"48251\" \"Johnson County\"\n \"48253\" \"J",
"end": 75095,
"score": 0.9134042859077454,
"start": 75086,
"tag": "NAME",
"value": "Jim Wells"
},
{
"context": "County\"\n \"48249\" \"Jim Wells County\"\n \"48251\" \"Johnson County\"\n \"48253\" \"Jones County\"\n \"48255\" \"",
"end": 75120,
"score": 0.8338932394981384,
"start": 75116,
"tag": "NAME",
"value": "John"
},
{
"context": "o County\"\n \"48393\" \"Roberts County\"\n \"48395\" \"Robertson County\"\n \"48397\" \"Rockwall County\"\n \"48399",
"end": 77095,
"score": 0.6086814403533936,
"start": 77089,
"tag": "NAME",
"value": "Robert"
},
{
"context": "ton County\"\n \"48449\" \"Titus County\"\n \"48451\" \"Tom Green County\"\n \"48453\" \"Travis County\"\n \"4845",
"end": 77897,
"score": 0.6355932354927063,
"start": 77894,
"tag": "NAME",
"value": "Tom"
}
] |
src/cljs/early_vote_site/places.cljs
|
votinginfoproject/Metis
| 11 |
(ns early-vote-site.places
(:require [clojure.string :as str]))
(def fips->name
{"01" "Alabama"
"01001" "Autauga County"
"01003" "Baldwin County"
"01005" "Barbour County"
"01007" "Bibb County"
"01009" "Blount County"
"01011" "Bullock County"
"01013" "Butler County"
"01015" "Calhoun County"
"01017" "Chambers County"
"01019" "Cherokee County"
"01021" "Chilton County"
"01023" "Choctaw County"
"01025" "Clarke County"
"01027" "Clay County"
"01029" "Cleburne County"
"01031" "Coffee County"
"01033" "Colbert County"
"01035" "Conecuh County"
"01037" "Coosa County"
"01039" "Covington County"
"01041" "Crenshaw County"
"01043" "Cullman County"
"01045" "Dale County"
"01047" "Dallas County"
"01049" "DeKalb County"
"01051" "Elmore County"
"01053" "Escambia County"
"01055" "Etowah County"
"01057" "Fayette County"
"01059" "Franklin County"
"01061" "Geneva County"
"01063" "Greene County"
"01065" "Hale County"
"01067" "Henry County"
"01069" "Houston County"
"01071" "Jackson County"
"01073" "Jefferson County"
"01075" "Lamar County"
"01077" "Lauderdale County"
"01079" "Lawrence County"
"01081" "Lee County"
"01083" "Limestone County"
"01085" "Lowndes County"
"01087" "Macon County"
"01089" "Madison County"
"01091" "Marengo County"
"01093" "Marion County"
"01095" "Marshall County"
"01097" "Mobile County"
"01099" "Monroe County"
"01101" "Montgomery County"
"01103" "Morgan County"
"01105" "Perry County"
"01107" "Pickens County"
"01109" "Pike County"
"01111" "Randolph County"
"01113" "Russell County"
"01115" "St. Clair County"
"01117" "Shelby County"
"01119" "Sumter County"
"01121" "Talladega County"
"01123" "Tallapoosa County"
"01125" "Tuscaloosa County"
"01127" "Walker County"
"01129" "Washington County"
"01131" "Wilcox County"
"01133" "Winston County"
"02" "Alaska"
"02013" "Aleutians East Borough"
"02016" "Aleutians West Census Area"
"02020" "Anchorage Municipality"
"02050" "Bethel Census Area"
"02060" "Bristol Bay Borough"
"02068" "Denali Borough"
"02070" "Dillingham Census Area"
"02090" "Fairbanks North Star Borough"
"02100" "Haines Borough"
"02105" "Hoonah-Angoon Census Area"
"02110" "Juneau City and Borough"
"02122" "Kenai Peninsula Borough"
"02130" "Ketchikan Gateway Borough"
"02150" "Kodiak Island Borough"
"02158" "Kusilvak Census Area"
"02164" "Lake and Peninsula Borough"
"02170" "Matanuska-Susitna Borough"
"02180" "Nome Census Area"
"02185" "North Slope Borough"
"02188" "Northwest Arctic Borough"
"02195" "Petersburg Borough"
"02198" "Prince of Wales-Hyder Census Area"
"02220" "Sitka City and Borough"
"02230" "Skagway Municipality"
"02240" "Southeast Fairbanks Census Area"
"02261" "Valdez-Cordova Census Area"
"02275" "Wrangell City and Borough"
"02282" "Yakutat City and Borough"
"02290" "Yukon-Koyukuk Census Area"
"04" "Arizona"
"04001" "Apache County"
"04003" "Cochise County"
"04005" "Coconino County"
"04007" "Gila County"
"04009" "Graham County"
"04011" "Greenlee County"
"04012" "La Paz County"
"04013" "Maricopa County"
"04015" "Mohave County"
"04017" "Navajo County"
"04019" "Pima County"
"04021" "Pinal County"
"04023" "Santa Cruz County"
"04025" "Yavapai County"
"04027" "Yuma County"
"05" "Arkansas"
"05001" "Arkansas County"
"05003" "Ashley County"
"05005" "Baxter County"
"05007" "Benton County"
"05009" "Boone County"
"05011" "Bradley County"
"05013" "Calhoun County"
"05015" "Carroll County"
"05017" "Chicot County"
"05019" "Clark County"
"05021" "Clay County"
"05023" "Cleburne County"
"05025" "Cleveland County"
"05027" "Columbia County"
"05029" "Conway County"
"05031" "Craighead County"
"05033" "Crawford County"
"05035" "Crittenden County"
"05037" "Cross County"
"05039" "Dallas County"
"05041" "Desha County"
"05043" "Drew County"
"05045" "Faulkner County"
"05047" "Franklin County"
"05049" "Fulton County"
"05051" "Garland County"
"05053" "Grant County"
"05055" "Greene County"
"05057" "Hempstead County"
"05059" "Hot Spring County"
"05061" "Howard County"
"05063" "Independence County"
"05065" "Izard County"
"05067" "Jackson County"
"05069" "Jefferson County"
"05071" "Johnson County"
"05073" "Lafayette County"
"05075" "Lawrence County"
"05077" "Lee County"
"05079" "Lincoln County"
"05081" "Little River County"
"05083" "Logan County"
"05085" "Lonoke County"
"05087" "Madison County"
"05089" "Marion County"
"05091" "Miller County"
"05093" "Mississippi County"
"05095" "Monroe County"
"05097" "Montgomery County"
"05099" "Nevada County"
"05101" "Newton County"
"05103" "Ouachita County"
"05105" "Perry County"
"05107" "Phillips County"
"05109" "Pike County"
"05111" "Poinsett County"
"05113" "Polk County"
"05115" "Pope County"
"05117" "Prairie County"
"05119" "Pulaski County"
"05121" "Randolph County"
"05123" "St. Francis County"
"05125" "Saline County"
"05127" "Scott County"
"05129" "Searcy County"
"05131" "Sebastian County"
"05133" "Sevier County"
"05135" "Sharp County"
"05137" "Stone County"
"05139" "Union County"
"05141" "Van Buren County"
"05143" "Washington County"
"05145" "White County"
"05147" "Woodruff County"
"05149" "Yell County"
"06" "California"
"06001" "Alameda County"
"06003" "Alpine County"
"06005" "Amador County"
"06007" "Butte County"
"06009" "Calaveras County"
"06011" "Colusa County"
"06013" "Contra Costa County"
"06015" "Del Norte County"
"06017" "El Dorado County"
"06019" "Fresno County"
"06021" "Glenn County"
"06023" "Humboldt County"
"06025" "Imperial County"
"06027" "Inyo County"
"06029" "Kern County"
"06031" "Kings County"
"06033" "Lake County"
"06035" "Lassen County"
"06037" "Los Angeles County"
"06039" "Madera County"
"06041" "Marin County"
"06043" "Mariposa County"
"06045" "Mendocino County"
"06047" "Merced County"
"06049" "Modoc County"
"06051" "Mono County"
"06053" "Monterey County"
"06055" "Napa County"
"06057" "Nevada County"
"06059" "Orange County"
"06061" "Placer County"
"06063" "Plumas County"
"06065" "Riverside County"
"06067" "Sacramento County"
"06069" "San Benito County"
"06071" "San Bernardino County"
"06073" "San Diego County"
"06075" "San Francisco County"
"06077" "San Joaquin County"
"06079" "San Luis Obispo County"
"06081" "San Mateo County"
"06083" "Santa Barbara County"
"06085" "Santa Clara County"
"06087" "Santa Cruz County"
"06089" "Shasta County"
"06091" "Sierra County"
"06093" "Siskiyou County"
"06095" "Solano County"
"06097" "Sonoma County"
"06099" "Stanislaus County"
"06101" "Sutter County"
"06103" "Tehama County"
"06105" "Trinity County"
"06107" "Tulare County"
"06109" "Tuolumne County"
"06111" "Ventura County"
"06113" "Yolo County"
"06115" "Yuba County"
"08" "Colorado"
"08001" "Adams County"
"08003" "Alamosa County"
"08005" "Arapahoe County"
"08007" "Archuleta County"
"08009" "Baca County"
"08011" "Bent County"
"08013" "Boulder County"
"08014" "Broomfield County"
"08015" "Chaffee County"
"08017" "Cheyenne County"
"08019" "Clear Creek County"
"08021" "Conejos County"
"08023" "Costilla County"
"08025" "Crowley County"
"08027" "Custer County"
"08029" "Delta County"
"08031" "Denver County"
"08033" "Dolores County"
"08035" "Douglas County"
"08037" "Eagle County"
"08039" "Elbert County"
"08041" "El Paso County"
"08043" "Fremont County"
"08045" "Garfield County"
"08047" "Gilpin County"
"08049" "Grand County"
"08051" "Gunnison County"
"08053" "Hinsdale County"
"08055" "Huerfano County"
"08057" "Jackson County"
"08059" "Jefferson County"
"08061" "Kiowa County"
"08063" "Kit Carson County"
"08065" "Lake County"
"08067" "La Plata County"
"08069" "Larimer County"
"08071" "Las Animas County"
"08073" "Lincoln County"
"08075" "Logan County"
"08077" "Mesa County"
"08079" "Mineral County"
"08081" "Moffat County"
"08083" "Montezuma County"
"08085" "Montrose County"
"08087" "Morgan County"
"08089" "Otero County"
"08091" "Ouray County"
"08093" "Park County"
"08095" "Phillips County"
"08097" "Pitkin County"
"08099" "Prowers County"
"08101" "Pueblo County"
"08103" "Rio Blanco County"
"08105" "Rio Grande County"
"08107" "Routt County"
"08109" "Saguache County"
"08111" "San Juan County"
"08113" "San Miguel County"
"08115" "Sedgwick County"
"08117" "Summit County"
"08119" "Teller County"
"08121" "Washington County"
"08123" "Weld County"
"08125" "Yuma County"
"09" "Connecticut"
"09001" "Fairfield County"
"09003" "Hartford County"
"09005" "Litchfield County"
"09007" "Middlesex County"
"09009" "New Haven County"
"09011" "New London County"
"09013" "Tolland County"
"09015" "Windham County"
"10" "Delaware"
"10001" "Kent County"
"10003" "New Castle County"
"10005" "Sussex County"
"11" "District of Columbia"
"11001" "District of Columbia"
"12" "Florida"
"12001" "Alachua County"
"12003" "Baker County"
"12005" "Bay County"
"12007" "Bradford County"
"12009" "Brevard County"
"12011" "Broward County"
"12013" "Calhoun County"
"12015" "Charlotte County"
"12017" "Citrus County"
"12019" "Clay County"
"12021" "Collier County"
"12023" "Columbia County"
"12027" "DeSoto County"
"12029" "Dixie County"
"12031" "Duval County"
"12033" "Escambia County"
"12035" "Flagler County"
"12037" "Franklin County"
"12039" "Gadsden County"
"12041" "Gilchrist County"
"12043" "Glades County"
"12045" "Gulf County"
"12047" "Hamilton County"
"12049" "Hardee County"
"12051" "Hendry County"
"12053" "Hernando County"
"12055" "Highlands County"
"12057" "Hillsborough County"
"12059" "Holmes County"
"12061" "Indian River County"
"12063" "Jackson County"
"12065" "Jefferson County"
"12067" "Lafayette County"
"12069" "Lake County"
"12071" "Lee County"
"12073" "Leon County"
"12075" "Levy County"
"12077" "Liberty County"
"12079" "Madison County"
"12081" "Manatee County"
"12083" "Marion County"
"12085" "Martin County"
"12086" "Miami-Dade County"
"12087" "Monroe County"
"12089" "Nassau County"
"12091" "Okaloosa County"
"12093" "Okeechobee County"
"12095" "Orange County"
"12097" "Osceola County"
"12099" "Palm Beach County"
"12101" "Pasco County"
"12103" "Pinellas County"
"12105" "Polk County"
"12107" "Putnam County"
"12109" "St. Johns County"
"12111" "St. Lucie County"
"12113" "Santa Rosa County"
"12115" "Sarasota County"
"12117" "Seminole County"
"12119" "Sumter County"
"12121" "Suwannee County"
"12123" "Taylor County"
"12125" "Union County"
"12127" "Volusia County"
"12129" "Wakulla County"
"12131" "Walton County"
"12133" "Washington County"
"13" "Georgia"
"13001" "Appling County"
"13003" "Atkinson County"
"13005" "Bacon County"
"13007" "Baker County"
"13009" "Baldwin County"
"13011" "Banks County"
"13013" "Barrow County"
"13015" "Bartow County"
"13017" "Ben Hill County"
"13019" "Berrien County"
"13021" "Bibb County"
"13023" "Bleckley County"
"13025" "Brantley County"
"13027" "Brooks County"
"13029" "Bryan County"
"13031" "Bulloch County"
"13033" "Burke County"
"13035" "Butts County"
"13037" "Calhoun County"
"13039" "Camden County"
"13043" "Candler County"
"13045" "Carroll County"
"13047" "Catoosa County"
"13049" "Charlton County"
"13051" "Chatham County"
"13053" "Chattahoochee County"
"13055" "Chattooga County"
"13057" "Cherokee County"
"13059" "Clarke County"
"13061" "Clay County"
"13063" "Clayton County"
"13065" "Clinch County"
"13067" "Cobb County"
"13069" "Coffee County"
"13071" "Colquitt County"
"13073" "Columbia County"
"13075" "Cook County"
"13077" "Coweta County"
"13079" "Crawford County"
"13081" "Crisp County"
"13083" "Dade County"
"13085" "Dawson County"
"13087" "Decatur County"
"13089" "DeKalb County"
"13091" "Dodge County"
"13093" "Dooly County"
"13095" "Dougherty County"
"13097" "Douglas County"
"13099" "Early County"
"13101" "Echols County"
"13103" "Effingham County"
"13105" "Elbert County"
"13107" "Emanuel County"
"13109" "Evans County"
"13111" "Fannin County"
"13113" "Fayette County"
"13115" "Floyd County"
"13117" "Forsyth County"
"13119" "Franklin County"
"13121" "Fulton County"
"13123" "Gilmer County"
"13125" "Glascock County"
"13127" "Glynn County"
"13129" "Gordon County"
"13131" "Grady County"
"13133" "Greene County"
"13135" "Gwinnett County"
"13137" "Habersham County"
"13139" "Hall County"
"13141" "Hancock County"
"13143" "Haralson County"
"13145" "Harris County"
"13147" "Hart County"
"13149" "Heard County"
"13151" "Henry County"
"13153" "Houston County"
"13155" "Irwin County"
"13157" "Jackson County"
"13159" "Jasper County"
"13161" "Jeff Davis County"
"13163" "Jefferson County"
"13165" "Jenkins County"
"13167" "Johnson County"
"13169" "Jones County"
"13171" "Lamar County"
"13173" "Lanier County"
"13175" "Laurens County"
"13177" "Lee County"
"13179" "Liberty County"
"13181" "Lincoln County"
"13183" "Long County"
"13185" "Lowndes County"
"13187" "Lumpkin County"
"13189" "McDuffie County"
"13191" "McIntosh County"
"13193" "Macon County"
"13195" "Madison County"
"13197" "Marion County"
"13199" "Meriwether County"
"13201" "Miller County"
"13205" "Mitchell County"
"13207" "Monroe County"
"13209" "Montgomery County"
"13211" "Morgan County"
"13213" "Murray County"
"13215" "Muscogee County"
"13217" "Newton County"
"13219" "Oconee County"
"13221" "Oglethorpe County"
"13223" "Paulding County"
"13225" "Peach County"
"13227" "Pickens County"
"13229" "Pierce County"
"13231" "Pike County"
"13233" "Polk County"
"13235" "Pulaski County"
"13237" "Putnam County"
"13239" "Quitman County"
"13241" "Rabun County"
"13243" "Randolph County"
"13245" "Richmond County"
"13247" "Rockdale County"
"13249" "Schley County"
"13251" "Screven County"
"13253" "Seminole County"
"13255" "Spalding County"
"13257" "Stephens County"
"13259" "Stewart County"
"13261" "Sumter County"
"13263" "Talbot County"
"13265" "Taliaferro County"
"13267" "Tattnall County"
"13269" "Taylor County"
"13271" "Telfair County"
"13273" "Terrell County"
"13275" "Thomas County"
"13277" "Tift County"
"13279" "Toombs County"
"13281" "Towns County"
"13283" "Treutlen County"
"13285" "Troup County"
"13287" "Turner County"
"13289" "Twiggs County"
"13291" "Union County"
"13293" "Upson County"
"13295" "Walker County"
"13297" "Walton County"
"13299" "Ware County"
"13301" "Warren County"
"13303" "Washington County"
"13305" "Wayne County"
"13307" "Webster County"
"13309" "Wheeler County"
"13311" "White County"
"13313" "Whitfield County"
"13315" "Wilcox County"
"13317" "Wilkes County"
"13319" "Wilkinson County"
"13321" "Worth County"
"15" "Hawaii"
"15001" "Hawaii County"
"15003" "Honolulu County"
"15005" "Kalawao County"
"15007" "Kauai County"
"15009" "Maui County"
"16" "Idaho"
"16001" "Ada County"
"16003" "Adams County"
"16005" "Bannock County"
"16007" "Bear Lake County"
"16009" "Benewah County"
"16011" "Bingham County"
"16013" "Blaine County"
"16015" "Boise County"
"16017" "Bonner County"
"16019" "Bonneville County"
"16021" "Boundary County"
"16023" "Butte County"
"16025" "Camas County"
"16027" "Canyon County"
"16029" "Caribou County"
"16031" "Cassia County"
"16033" "Clark County"
"16035" "Clearwater County"
"16037" "Custer County"
"16039" "Elmore County"
"16041" "Franklin County"
"16043" "Fremont County"
"16045" "Gem County"
"16047" "Gooding County"
"16049" "Idaho County"
"16051" "Jefferson County"
"16053" "Jerome County"
"16055" "Kootenai County"
"16057" "Latah County"
"16059" "Lemhi County"
"16061" "Lewis County"
"16063" "Lincoln County"
"16065" "Madison County"
"16067" "Minidoka County"
"16069" "Nez Perce County"
"16071" "Oneida County"
"16073" "Owyhee County"
"16075" "Payette County"
"16077" "Power County"
"16079" "Shoshone County"
"16081" "Teton County"
"16083" "Twin Falls County"
"16085" "Valley County"
"16087" "Washington County"
"17" "Illinois"
"17001" "Adams County"
"17003" "Alexander County"
"17005" "Bond County"
"17007" "Boone County"
"17009" "Brown County"
"17011" "Bureau County"
"17013" "Calhoun County"
"17015" "Carroll County"
"17017" "Cass County"
"17019" "Champaign County"
"17021" "Christian County"
"17023" "Clark County"
"17025" "Clay County"
"17027" "Clinton County"
"17029" "Coles County"
"17031" "Cook County"
"17033" "Crawford County"
"17035" "Cumberland County"
"17037" "DeKalb County"
"17039" "De Witt County"
"17041" "Douglas County"
"17043" "DuPage County"
"17045" "Edgar County"
"17047" "Edwards County"
"17049" "Effingham County"
"17051" "Fayette County"
"17053" "Ford County"
"17055" "Franklin County"
"17057" "Fulton County"
"17059" "Gallatin County"
"17061" "Greene County"
"17063" "Grundy County"
"17065" "Hamilton County"
"17067" "Hancock County"
"17069" "Hardin County"
"17071" "Henderson County"
"17073" "Henry County"
"17075" "Iroquois County"
"17077" "Jackson County"
"17079" "Jasper County"
"17081" "Jefferson County"
"17083" "Jersey County"
"17085" "Jo Daviess County"
"17087" "Johnson County"
"17089" "Kane County"
"17091" "Kankakee County"
"17093" "Kendall County"
"17095" "Knox County"
"17097" "Lake County"
"17099" "LaSalle County"
"17101" "Lawrence County"
"17103" "Lee County"
"17105" "Livingston County"
"17107" "Logan County"
"17109" "McDonough County"
"17111" "McHenry County"
"17113" "McLean County"
"17115" "Macon County"
"17117" "Macoupin County"
"17119" "Madison County"
"17121" "Marion County"
"17123" "Marshall County"
"17125" "Mason County"
"17127" "Massac County"
"17129" "Menard County"
"17131" "Mercer County"
"17133" "Monroe County"
"17135" "Montgomery County"
"17137" "Morgan County"
"17139" "Moultrie County"
"17141" "Ogle County"
"17143" "Peoria County"
"17145" "Perry County"
"17147" "Piatt County"
"17149" "Pike County"
"17151" "Pope County"
"17153" "Pulaski County"
"17155" "Putnam County"
"17157" "Randolph County"
"17159" "Richland County"
"17161" "Rock Island County"
"17163" "St. Clair County"
"17165" "Saline County"
"17167" "Sangamon County"
"17169" "Schuyler County"
"17171" "Scott County"
"17173" "Shelby County"
"17175" "Stark County"
"17177" "Stephenson County"
"17179" "Tazewell County"
"17181" "Union County"
"17183" "Vermilion County"
"17185" "Wabash County"
"17187" "Warren County"
"17189" "Washington County"
"17191" "Wayne County"
"17193" "White County"
"17195" "Whiteside County"
"17197" "Will County"
"17199" "Williamson County"
"17201" "Winnebago County"
"17203" "Woodford County"
"18" "Indiana"
"18001" "Adams County"
"18003" "Allen County"
"18005" "Bartholomew County"
"18007" "Benton County"
"18009" "Blackford County"
"18011" "Boone County"
"18013" "Brown County"
"18015" "Carroll County"
"18017" "Cass County"
"18019" "Clark County"
"18021" "Clay County"
"18023" "Clinton County"
"18025" "Crawford County"
"18027" "Daviess County"
"18029" "Dearborn County"
"18031" "Decatur County"
"18033" "DeKalb County"
"18035" "Delaware County"
"18037" "Dubois County"
"18039" "Elkhart County"
"18041" "Fayette County"
"18043" "Floyd County"
"18045" "Fountain County"
"18047" "Franklin County"
"18049" "Fulton County"
"18051" "Gibson County"
"18053" "Grant County"
"18055" "Greene County"
"18057" "Hamilton County"
"18059" "Hancock County"
"18061" "Harrison County"
"18063" "Hendricks County"
"18065" "Henry County"
"18067" "Howard County"
"18069" "Huntington County"
"18071" "Jackson County"
"18073" "Jasper County"
"18075" "Jay County"
"18077" "Jefferson County"
"18079" "Jennings County"
"18081" "Johnson County"
"18083" "Knox County"
"18085" "Kosciusko County"
"18087" "LaGrange County"
"18089" "Lake County"
"18091" "LaPorte County"
"18093" "Lawrence County"
"18095" "Madison County"
"18097" "Marion County"
"18099" "Marshall County"
"18101" "Martin County"
"18103" "Miami County"
"18105" "Monroe County"
"18107" "Montgomery County"
"18109" "Morgan County"
"18111" "Newton County"
"18113" "Noble County"
"18115" "Ohio County"
"18117" "Orange County"
"18119" "Owen County"
"18121" "Parke County"
"18123" "Perry County"
"18125" "Pike County"
"18127" "Porter County"
"18129" "Posey County"
"18131" "Pulaski County"
"18133" "Putnam County"
"18135" "Randolph County"
"18137" "Ripley County"
"18139" "Rush County"
"18141" "St. Joseph County"
"18143" "Scott County"
"18145" "Shelby County"
"18147" "Spencer County"
"18149" "Starke County"
"18151" "Steuben County"
"18153" "Sullivan County"
"18155" "Switzerland County"
"18157" "Tippecanoe County"
"18159" "Tipton County"
"18161" "Union County"
"18163" "Vanderburgh County"
"18165" "Vermillion County"
"18167" "Vigo County"
"18169" "Wabash County"
"18171" "Warren County"
"18173" "Warrick County"
"18175" "Washington County"
"18177" "Wayne County"
"18179" "Wells County"
"18181" "White County"
"18183" "Whitley County"
"19" "Iowa"
"19001" "Adair County"
"19003" "Adams County"
"19005" "Allamakee County"
"19007" "Appanoose County"
"19009" "Audubon County"
"19011" "Benton County"
"19013" "Black Hawk County"
"19015" "Boone County"
"19017" "Bremer County"
"19019" "Buchanan County"
"19021" "Buena Vista County"
"19023" "Butler County"
"19025" "Calhoun County"
"19027" "Carroll County"
"19029" "Cass County"
"19031" "Cedar County"
"19033" "Cerro Gordo County"
"19035" "Cherokee County"
"19037" "Chickasaw County"
"19039" "Clarke County"
"19041" "Clay County"
"19043" "Clayton County"
"19045" "Clinton County"
"19047" "Crawford County"
"19049" "Dallas County"
"19051" "Davis County"
"19053" "Decatur County"
"19055" "Delaware County"
"19057" "Des Moines County"
"19059" "Dickinson County"
"19061" "Dubuque County"
"19063" "Emmet County"
"19065" "Fayette County"
"19067" "Floyd County"
"19069" "Franklin County"
"19071" "Fremont County"
"19073" "Greene County"
"19075" "Grundy County"
"19077" "Guthrie County"
"19079" "Hamilton County"
"19081" "Hancock County"
"19083" "Hardin County"
"19085" "Harrison County"
"19087" "Henry County"
"19089" "Howard County"
"19091" "Humboldt County"
"19093" "Ida County"
"19095" "Iowa County"
"19097" "Jackson County"
"19099" "Jasper County"
"19101" "Jefferson County"
"19103" "Johnson County"
"19105" "Jones County"
"19107" "Keokuk County"
"19109" "Kossuth County"
"19111" "Lee County"
"19113" "Linn County"
"19115" "Louisa County"
"19117" "Lucas County"
"19119" "Lyon County"
"19121" "Madison County"
"19123" "Mahaska County"
"19125" "Marion County"
"19127" "Marshall County"
"19129" "Mills County"
"19131" "Mitchell County"
"19133" "Monona County"
"19135" "Monroe County"
"19137" "Montgomery County"
"19139" "Muscatine County"
"19141" "O'Brien County"
"19143" "Osceola County"
"19145" "Page County"
"19147" "Palo Alto County"
"19149" "Plymouth County"
"19151" "Pocahontas County"
"19153" "Polk County"
"19155" "Pottawattamie County"
"19157" "Poweshiek County"
"19159" "Ringgold County"
"19161" "Sac County"
"19163" "Scott County"
"19165" "Shelby County"
"19167" "Sioux County"
"19169" "Story County"
"19171" "Tama County"
"19173" "Taylor County"
"19175" "Union County"
"19177" "Van Buren County"
"19179" "Wapello County"
"19181" "Warren County"
"19183" "Washington County"
"19185" "Wayne County"
"19187" "Webster County"
"19189" "Winnebago County"
"19191" "Winneshiek County"
"19193" "Woodbury County"
"19195" "Worth County"
"19197" "Wright County"
"20" "Kansas"
"20001" "Allen County"
"20003" "Anderson County"
"20005" "Atchison County"
"20007" "Barber County"
"20009" "Barton County"
"20011" "Bourbon County"
"20013" "Brown County"
"20015" "Butler County"
"20017" "Chase County"
"20019" "Chautauqua County"
"20021" "Cherokee County"
"20023" "Cheyenne County"
"20025" "Clark County"
"20027" "Clay County"
"20029" "Cloud County"
"20031" "Coffey County"
"20033" "Comanche County"
"20035" "Cowley County"
"20037" "Crawford County"
"20039" "Decatur County"
"20041" "Dickinson County"
"20043" "Doniphan County"
"20045" "Douglas County"
"20047" "Edwards County"
"20049" "Elk County"
"20051" "Ellis County"
"20053" "Ellsworth County"
"20055" "Finney County"
"20057" "Ford County"
"20059" "Franklin County"
"20061" "Geary County"
"20063" "Gove County"
"20065" "Graham County"
"20067" "Grant County"
"20069" "Gray County"
"20071" "Greeley County"
"20073" "Greenwood County"
"20075" "Hamilton County"
"20077" "Harper County"
"20079" "Harvey County"
"20081" "Haskell County"
"20083" "Hodgeman County"
"20085" "Jackson County"
"20087" "Jefferson County"
"20089" "Jewell County"
"20091" "Johnson County"
"20093" "Kearny County"
"20095" "Kingman County"
"20097" "Kiowa County"
"20099" "Labette County"
"20101" "Lane County"
"20103" "Leavenworth County"
"20105" "Lincoln County"
"20107" "Linn County"
"20109" "Logan County"
"20111" "Lyon County"
"20113" "McPherson County"
"20115" "Marion County"
"20117" "Marshall County"
"20119" "Meade County"
"20121" "Miami County"
"20123" "Mitchell County"
"20125" "Montgomery County"
"20127" "Morris County"
"20129" "Morton County"
"20131" "Nemaha County"
"20133" "Neosho County"
"20135" "Ness County"
"20137" "Norton County"
"20139" "Osage County"
"20141" "Osborne County"
"20143" "Ottawa County"
"20145" "Pawnee County"
"20147" "Phillips County"
"20149" "Pottawatomie County"
"20151" "Pratt County"
"20153" "Rawlins County"
"20155" "Reno County"
"20157" "Republic County"
"20159" "Rice County"
"20161" "Riley County"
"20163" "Rooks County"
"20165" "Rush County"
"20167" "Russell County"
"20169" "Saline County"
"20171" "Scott County"
"20173" "Sedgwick County"
"20175" "Seward County"
"20177" "Shawnee County"
"20179" "Sheridan County"
"20181" "Sherman County"
"20183" "Smith County"
"20185" "Stafford County"
"20187" "Stanton County"
"20189" "Stevens County"
"20191" "Sumner County"
"20193" "Thomas County"
"20195" "Trego County"
"20197" "Wabaunsee County"
"20199" "Wallace County"
"20201" "Washington County"
"20203" "Wichita County"
"20205" "Wilson County"
"20207" "Woodson County"
"20209" "Wyandotte County"
"21" "Kentucky"
"21001" "Adair County"
"21003" "Allen County"
"21005" "Anderson County"
"21007" "Ballard County"
"21009" "Barren County"
"21011" "Bath County"
"21013" "Bell County"
"21015" "Boone County"
"21017" "Bourbon County"
"21019" "Boyd County"
"21021" "Boyle County"
"21023" "Bracken County"
"21025" "Breathitt County"
"21027" "Breckinridge County"
"21029" "Bullitt County"
"21031" "Butler County"
"21033" "Caldwell County"
"21035" "Calloway County"
"21037" "Campbell County"
"21039" "Carlisle County"
"21041" "Carroll County"
"21043" "Carter County"
"21045" "Casey County"
"21047" "Christian County"
"21049" "Clark County"
"21051" "Clay County"
"21053" "Clinton County"
"21055" "Crittenden County"
"21057" "Cumberland County"
"21059" "Daviess County"
"21061" "Edmonson County"
"21063" "Elliott County"
"21065" "Estill County"
"21067" "Fayette County"
"21069" "Fleming County"
"21071" "Floyd County"
"21073" "Franklin County"
"21075" "Fulton County"
"21077" "Gallatin County"
"21079" "Garrard County"
"21081" "Grant County"
"21083" "Graves County"
"21085" "Grayson County"
"21087" "Green County"
"21089" "Greenup County"
"21091" "Hancock County"
"21093" "Hardin County"
"21095" "Harlan County"
"21097" "Harrison County"
"21099" "Hart County"
"21101" "Henderson County"
"21103" "Henry County"
"21105" "Hickman County"
"21107" "Hopkins County"
"21109" "Jackson County"
"21111" "Jefferson County"
"21113" "Jessamine County"
"21115" "Johnson County"
"21117" "Kenton County"
"21119" "Knott County"
"21121" "Knox County"
"21123" "Larue County"
"21125" "Laurel County"
"21127" "Lawrence County"
"21129" "Lee County"
"21131" "Leslie County"
"21133" "Letcher County"
"21135" "Lewis County"
"21137" "Lincoln County"
"21139" "Livingston County"
"21141" "Logan County"
"21143" "Lyon County"
"21145" "McCracken County"
"21147" "McCreary County"
"21149" "McLean County"
"21151" "Madison County"
"21153" "Magoffin County"
"21155" "Marion County"
"21157" "Marshall County"
"21159" "Martin County"
"21161" "Mason County"
"21163" "Meade County"
"21165" "Menifee County"
"21167" "Mercer County"
"21169" "Metcalfe County"
"21171" "Monroe County"
"21173" "Montgomery County"
"21175" "Morgan County"
"21177" "Muhlenberg County"
"21179" "Nelson County"
"21181" "Nicholas County"
"21183" "Ohio County"
"21185" "Oldham County"
"21187" "Owen County"
"21189" "Owsley County"
"21191" "Pendleton County"
"21193" "Perry County"
"21195" "Pike County"
"21197" "Powell County"
"21199" "Pulaski County"
"21201" "Robertson County"
"21203" "Rockcastle County"
"21205" "Rowan County"
"21207" "Russell County"
"21209" "Scott County"
"21211" "Shelby County"
"21213" "Simpson County"
"21215" "Spencer County"
"21217" "Taylor County"
"21219" "Todd County"
"21221" "Trigg County"
"21223" "Trimble County"
"21225" "Union County"
"21227" "Warren County"
"21229" "Washington County"
"21231" "Wayne County"
"21233" "Webster County"
"21235" "Whitley County"
"21237" "Wolfe County"
"21239" "Woodford County"
"22" "Louisiana"
"22001" "Acadia Parish"
"22003" "Allen Parish"
"22005" "Ascension Parish"
"22007" "Assumption Parish"
"22009" "Avoyelles Parish"
"22011" "Beauregard Parish"
"22013" "Bienville Parish"
"22015" "Bossier Parish"
"22017" "Caddo Parish"
"22019" "Calcasieu Parish"
"22021" "Caldwell Parish"
"22023" "Cameron Parish"
"22025" "Catahoula Parish"
"22027" "Claiborne Parish"
"22029" "Concordia Parish"
"22031" "De Soto Parish"
"22033" "East Baton Rouge Parish"
"22035" "East Carroll Parish"
"22037" "East Feliciana Parish"
"22039" "Evangeline Parish"
"22041" "Franklin Parish"
"22043" "Grant Parish"
"22045" "Iberia Parish"
"22047" "Iberville Parish"
"22049" "Jackson Parish"
"22051" "Jefferson Parish"
"22053" "Jefferson Davis Parish"
"22055" "Lafayette Parish"
"22057" "Lafourche Parish"
"22059" "LaSalle Parish"
"22061" "Lincoln Parish"
"22063" "Livingston Parish"
"22065" "Madison Parish"
"22067" "Morehouse Parish"
"22069" "Natchitoches Parish"
"22071" "Orleans Parish"
"22073" "Ouachita Parish"
"22075" "Plaquemines Parish"
"22077" "Pointe Coupee Parish"
"22079" "Rapides Parish"
"22081" "Red River Parish"
"22083" "Richland Parish"
"22085" "Sabine Parish"
"22087" "St. Bernard Parish"
"22089" "St. Charles Parish"
"22091" "St. Helena Parish"
"22093" "St. James Parish"
"22095" "St. John the Baptist Parish"
"22097" "St. Landry Parish"
"22099" "St. Martin Parish"
"22101" "St. Mary Parish"
"22103" "St. Tammany Parish"
"22105" "Tangipahoa Parish"
"22107" "Tensas Parish"
"22109" "Terrebonne Parish"
"22111" "Union Parish"
"22113" "Vermilion Parish"
"22115" "Vernon Parish"
"22117" "Washington Parish"
"22119" "Webster Parish"
"22121" "West Baton Rouge Parish"
"22123" "West Carroll Parish"
"22125" "West Feliciana Parish"
"22127" "Winn Parish"
"23" "Maine"
"23001" "Androscoggin County"
"23003" "Aroostook County"
"23005" "Cumberland County"
"23007" "Franklin County"
"23009" "Hancock County"
"23011" "Kennebec County"
"23013" "Knox County"
"23015" "Lincoln County"
"23017" "Oxford County"
"23019" "Penobscot County"
"23021" "Piscataquis County"
"23023" "Sagadahoc County"
"23025" "Somerset County"
"23027" "Waldo County"
"23029" "Washington County"
"23031" "York County"
"24" "Maryland"
"24001" "Allegany County"
"24003" "Anne Arundel County"
"24005" "Baltimore County"
"24009" "Calvert County"
"24011" "Caroline County"
"24013" "Carroll County"
"24015" "Cecil County"
"24017" "Charles County"
"24019" "Dorchester County"
"24021" "Frederick County"
"24023" "Garrett County"
"24025" "Harford County"
"24027" "Howard County"
"24029" "Kent County"
"24031" "Montgomery County"
"24033" "Prince George's County"
"24035" "Queen Anne's County"
"24037" "St. Mary's County"
"24039" "Somerset County"
"24041" "Talbot County"
"24043" "Washington County"
"24045" "Wicomico County"
"24047" "Worcester County"
"24510" "Baltimore city"
"25" "Massachusetts"
"25001" "Barnstable County"
"25003" "Berkshire County"
"25005" "Bristol County"
"25007" "Dukes County"
"25009" "Essex County"
"25011" "Franklin County"
"25013" "Hampden County"
"25015" "Hampshire County"
"25017" "Middlesex County"
"25019" "Nantucket County"
"25021" "Norfolk County"
"25023" "Plymouth County"
"25025" "Suffolk County"
"25027" "Worcester County"
"26" "Michigan"
"26001" "Alcona County"
"26003" "Alger County"
"26005" "Allegan County"
"26007" "Alpena County"
"26009" "Antrim County"
"26011" "Arenac County"
"26013" "Baraga County"
"26015" "Barry County"
"26017" "Bay County"
"26019" "Benzie County"
"26021" "Berrien County"
"26023" "Branch County"
"26025" "Calhoun County"
"26027" "Cass County"
"26029" "Charlevoix County"
"26031" "Cheboygan County"
"26033" "Chippewa County"
"26035" "Clare County"
"26037" "Clinton County"
"26039" "Crawford County"
"26041" "Delta County"
"26043" "Dickinson County"
"26045" "Eaton County"
"26047" "Emmet County"
"26049" "Genesee County"
"26051" "Gladwin County"
"26053" "Gogebic County"
"26055" "Grand Traverse County"
"26057" "Gratiot County"
"26059" "Hillsdale County"
"26061" "Houghton County"
"26063" "Huron County"
"26065" "Ingham County"
"26067" "Ionia County"
"26069" "Iosco County"
"26071" "Iron County"
"26073" "Isabella County"
"26075" "Jackson County"
"26077" "Kalamazoo County"
"26079" "Kalkaska County"
"26081" "Kent County"
"26083" "Keweenaw County"
"26085" "Lake County"
"26087" "Lapeer County"
"26089" "Leelanau County"
"26091" "Lenawee County"
"26093" "Livingston County"
"26095" "Luce County"
"26097" "Mackinac County"
"26099" "Macomb County"
"26101" "Manistee County"
"26103" "Marquette County"
"26105" "Mason County"
"26107" "Mecosta County"
"26109" "Menominee County"
"26111" "Midland County"
"26113" "Missaukee County"
"26115" "Monroe County"
"26117" "Montcalm County"
"26119" "Montmorency County"
"26121" "Muskegon County"
"26123" "Newaygo County"
"26125" "Oakland County"
"26127" "Oceana County"
"26129" "Ogemaw County"
"26131" "Ontonagon County"
"26133" "Osceola County"
"26135" "Oscoda County"
"26137" "Otsego County"
"26139" "Ottawa County"
"26141" "Presque Isle County"
"26143" "Roscommon County"
"26145" "Saginaw County"
"26147" "St. Clair County"
"26149" "St. Joseph County"
"26151" "Sanilac County"
"26153" "Schoolcraft County"
"26155" "Shiawassee County"
"26157" "Tuscola County"
"26159" "Van Buren County"
"26161" "Washtenaw County"
"26163" "Wayne County"
"26165" "Wexford County"
"27" "Minnesota"
"27001" "Aitkin County"
"27003" "Anoka County"
"27005" "Becker County"
"27007" "Beltrami County"
"27009" "Benton County"
"27011" "Big Stone County"
"27013" "Blue Earth County"
"27015" "Brown County"
"27017" "Carlton County"
"27019" "Carver County"
"27021" "Cass County"
"27023" "Chippewa County"
"27025" "Chisago County"
"27027" "Clay County"
"27029" "Clearwater County"
"27031" "Cook County"
"27033" "Cottonwood County"
"27035" "Crow Wing County"
"27037" "Dakota County"
"27039" "Dodge County"
"27041" "Douglas County"
"27043" "Faribault County"
"27045" "Fillmore County"
"27047" "Freeborn County"
"27049" "Goodhue County"
"27051" "Grant County"
"27053" "Hennepin County"
"27055" "Houston County"
"27057" "Hubbard County"
"27059" "Isanti County"
"27061" "Itasca County"
"27063" "Jackson County"
"27065" "Kanabec County"
"27067" "Kandiyohi County"
"27069" "Kittson County"
"27071" "Koochiching County"
"27073" "Lac qui Parle County"
"27075" "Lake County"
"27077" "Lake of the Woods County"
"27079" "Le Sueur County"
"27081" "Lincoln County"
"27083" "Lyon County"
"27085" "McLeod County"
"27087" "Mahnomen County"
"27089" "Marshall County"
"27091" "Martin County"
"27093" "Meeker County"
"27095" "Mille Lacs County"
"27097" "Morrison County"
"27099" "Mower County"
"27101" "Murray County"
"27103" "Nicollet County"
"27105" "Nobles County"
"27107" "Norman County"
"27109" "Olmsted County"
"27111" "Otter Tail County"
"27113" "Pennington County"
"27115" "Pine County"
"27117" "Pipestone County"
"27119" "Polk County"
"27121" "Pope County"
"27123" "Ramsey County"
"27125" "Red Lake County"
"27127" "Redwood County"
"27129" "Renville County"
"27131" "Rice County"
"27133" "Rock County"
"27135" "Roseau County"
"27137" "St. Louis County"
"27139" "Scott County"
"27141" "Sherburne County"
"27143" "Sibley County"
"27145" "Stearns County"
"27147" "Steele County"
"27149" "Stevens County"
"27151" "Swift County"
"27153" "Todd County"
"27155" "Traverse County"
"27157" "Wabasha County"
"27159" "Wadena County"
"27161" "Waseca County"
"27163" "Washington County"
"27165" "Watonwan County"
"27167" "Wilkin County"
"27169" "Winona County"
"27171" "Wright County"
"27173" "Yellow Medicine County"
"28" "Mississippi"
"28001" "Adams County"
"28003" "Alcorn County"
"28005" "Amite County"
"28007" "Attala County"
"28009" "Benton County"
"28011" "Bolivar County"
"28013" "Calhoun County"
"28015" "Carroll County"
"28017" "Chickasaw County"
"28019" "Choctaw County"
"28021" "Claiborne County"
"28023" "Clarke County"
"28025" "Clay County"
"28027" "Coahoma County"
"28029" "Copiah County"
"28031" "Covington County"
"28033" "DeSoto County"
"28035" "Forrest County"
"28037" "Franklin County"
"28039" "George County"
"28041" "Greene County"
"28043" "Grenada County"
"28045" "Hancock County"
"28047" "Harrison County"
"28049" "Hinds County"
"28051" "Holmes County"
"28053" "Humphreys County"
"28055" "Issaquena County"
"28057" "Itawamba County"
"28059" "Jackson County"
"28061" "Jasper County"
"28063" "Jefferson County"
"28065" "Jefferson Davis County"
"28067" "Jones County"
"28069" "Kemper County"
"28071" "Lafayette County"
"28073" "Lamar County"
"28075" "Lauderdale County"
"28077" "Lawrence County"
"28079" "Leake County"
"28081" "Lee County"
"28083" "Leflore County"
"28085" "Lincoln County"
"28087" "Lowndes County"
"28089" "Madison County"
"28091" "Marion County"
"28093" "Marshall County"
"28095" "Monroe County"
"28097" "Montgomery County"
"28099" "Neshoba County"
"28101" "Newton County"
"28103" "Noxubee County"
"28105" "Oktibbeha County"
"28107" "Panola County"
"28109" "Pearl River County"
"28111" "Perry County"
"28113" "Pike County"
"28115" "Pontotoc County"
"28117" "Prentiss County"
"28119" "Quitman County"
"28121" "Rankin County"
"28123" "Scott County"
"28125" "Sharkey County"
"28127" "Simpson County"
"28129" "Smith County"
"28131" "Stone County"
"28133" "Sunflower County"
"28135" "Tallahatchie County"
"28137" "Tate County"
"28139" "Tippah County"
"28141" "Tishomingo County"
"28143" "Tunica County"
"28145" "Union County"
"28147" "Walthall County"
"28149" "Warren County"
"28151" "Washington County"
"28153" "Wayne County"
"28155" "Webster County"
"28157" "Wilkinson County"
"28159" "Winston County"
"28161" "Yalobusha County"
"28163" "Yazoo County"
"29" "Missouri"
"29001" "Adair County"
"29003" "Andrew County"
"29005" "Atchison County"
"29007" "Audrain County"
"29009" "Barry County"
"29011" "Barton County"
"29013" "Bates County"
"29015" "Benton County"
"29017" "Bollinger County"
"29019" "Boone County"
"29021" "Buchanan County"
"29023" "Butler County"
"29025" "Caldwell County"
"29027" "Callaway County"
"29029" "Camden County"
"29031" "Cape Girardeau County"
"29033" "Carroll County"
"29035" "Carter County"
"29037" "Cass County"
"29039" "Cedar County"
"29041" "Chariton County"
"29043" "Christian County"
"29045" "Clark County"
"29047" "Clay County"
"29049" "Clinton County"
"29051" "Cole County"
"29053" "Cooper County"
"29055" "Crawford County"
"29057" "Dade County"
"29059" "Dallas County"
"29061" "Daviess County"
"29063" "DeKalb County"
"29065" "Dent County"
"29067" "Douglas County"
"29069" "Dunklin County"
"29071" "Franklin County"
"29073" "Gasconade County"
"29075" "Gentry County"
"29077" "Greene County"
"29079" "Grundy County"
"29081" "Harrison County"
"29083" "Henry County"
"29085" "Hickory County"
"29087" "Holt County"
"29089" "Howard County"
"29091" "Howell County"
"29093" "Iron County"
"29095" "Jackson County"
"29097" "Jasper County"
"29099" "Jefferson County"
"29101" "Johnson County"
"29103" "Knox County"
"29105" "Laclede County"
"29107" "Lafayette County"
"29109" "Lawrence County"
"29111" "Lewis County"
"29113" "Lincoln County"
"29115" "Linn County"
"29117" "Livingston County"
"29119" "McDonald County"
"29121" "Macon County"
"29123" "Madison County"
"29125" "Maries County"
"29127" "Marion County"
"29129" "Mercer County"
"29131" "Miller County"
"29133" "Mississippi County"
"29135" "Moniteau County"
"29137" "Monroe County"
"29139" "Montgomery County"
"29141" "Morgan County"
"29143" "New Madrid County"
"29145" "Newton County"
"29147" "Nodaway County"
"29149" "Oregon County"
"29151" "Osage County"
"29153" "Ozark County"
"29155" "Pemiscot County"
"29157" "Perry County"
"29159" "Pettis County"
"29161" "Phelps County"
"29163" "Pike County"
"29165" "Platte County"
"29167" "Polk County"
"29169" "Pulaski County"
"29171" "Putnam County"
"29173" "Ralls County"
"29175" "Randolph County"
"29177" "Ray County"
"29179" "Reynolds County"
"29181" "Ripley County"
"29183" "St. Charles County"
"29185" "St. Clair County"
"29186" "Ste. Genevieve County"
"29187" "St. Francois County"
"29189" "St. Louis County"
"29195" "Saline County"
"29197" "Schuyler County"
"29199" "Scotland County"
"29201" "Scott County"
"29203" "Shannon County"
"29205" "Shelby County"
"29207" "Stoddard County"
"29209" "Stone County"
"29211" "Sullivan County"
"29213" "Taney County"
"29215" "Texas County"
"29217" "Vernon County"
"29219" "Warren County"
"29221" "Washington County"
"29223" "Wayne County"
"29225" "Webster County"
"29227" "Worth County"
"29229" "Wright County"
"29510" "St. Louis city"
"30" "Montana"
"30001" "Beaverhead County"
"30003" "Big Horn County"
"30005" "Blaine County"
"30007" "Broadwater County"
"30009" "Carbon County"
"30011" "Carter County"
"30013" "Cascade County"
"30015" "Chouteau County"
"30017" "Custer County"
"30019" "Daniels County"
"30021" "Dawson County"
"30023" "Deer Lodge County"
"30025" "Fallon County"
"30027" "Fergus County"
"30029" "Flathead County"
"30031" "Gallatin County"
"30033" "Garfield County"
"30035" "Glacier County"
"30037" "Golden Valley County"
"30039" "Granite County"
"30041" "Hill County"
"30043" "Jefferson County"
"30045" "Judith Basin County"
"30047" "Lake County"
"30049" "Lewis and Clark County"
"30051" "Liberty County"
"30053" "Lincoln County"
"30055" "McCone County"
"30057" "Madison County"
"30059" "Meagher County"
"30061" "Mineral County"
"30063" "Missoula County"
"30065" "Musselshell County"
"30067" "Park County"
"30069" "Petroleum County"
"30071" "Phillips County"
"30073" "Pondera County"
"30075" "Powder River County"
"30077" "Powell County"
"30079" "Prairie County"
"30081" "Ravalli County"
"30083" "Richland County"
"30085" "Roosevelt County"
"30087" "Rosebud County"
"30089" "Sanders County"
"30091" "Sheridan County"
"30093" "Silver Bow County"
"30095" "Stillwater County"
"30097" "Sweet Grass County"
"30099" "Teton County"
"30101" "Toole County"
"30103" "Treasure County"
"30105" "Valley County"
"30107" "Wheatland County"
"30109" "Wibaux County"
"30111" "Yellowstone County"
"31" "Nebraska"
"31001" "Adams County"
"31003" "Antelope County"
"31005" "Arthur County"
"31007" "Banner County"
"31009" "Blaine County"
"31011" "Boone County"
"31013" "Box Butte County"
"31015" "Boyd County"
"31017" "Brown County"
"31019" "Buffalo County"
"31021" "Burt County"
"31023" "Butler County"
"31025" "Cass County"
"31027" "Cedar County"
"31029" "Chase County"
"31031" "Cherry County"
"31033" "Cheyenne County"
"31035" "Clay County"
"31037" "Colfax County"
"31039" "Cuming County"
"31041" "Custer County"
"31043" "Dakota County"
"31045" "Dawes County"
"31047" "Dawson County"
"31049" "Deuel County"
"31051" "Dixon County"
"31053" "Dodge County"
"31055" "Douglas County"
"31057" "Dundy County"
"31059" "Fillmore County"
"31061" "Franklin County"
"31063" "Frontier County"
"31065" "Furnas County"
"31067" "Gage County"
"31069" "Garden County"
"31071" "Garfield County"
"31073" "Gosper County"
"31075" "Grant County"
"31077" "Greeley County"
"31079" "Hall County"
"31081" "Hamilton County"
"31083" "Harlan County"
"31085" "Hayes County"
"31087" "Hitchcock County"
"31089" "Holt County"
"31091" "Hooker County"
"31093" "Howard County"
"31095" "Jefferson County"
"31097" "Johnson County"
"31099" "Kearney County"
"31101" "Keith County"
"31103" "Keya Paha County"
"31105" "Kimball County"
"31107" "Knox County"
"31109" "Lancaster County"
"31111" "Lincoln County"
"31113" "Logan County"
"31115" "Loup County"
"31117" "McPherson County"
"31119" "Madison County"
"31121" "Merrick County"
"31123" "Morrill County"
"31125" "Nance County"
"31127" "Nemaha County"
"31129" "Nuckolls County"
"31131" "Otoe County"
"31133" "Pawnee County"
"31135" "Perkins County"
"31137" "Phelps County"
"31139" "Pierce County"
"31141" "Platte County"
"31143" "Polk County"
"31145" "Red Willow County"
"31147" "Richardson County"
"31149" "Rock County"
"31151" "Saline County"
"31153" "Sarpy County"
"31155" "Saunders County"
"31157" "Scotts Bluff County"
"31159" "Seward County"
"31161" "Sheridan County"
"31163" "Sherman County"
"31165" "Sioux County"
"31167" "Stanton County"
"31169" "Thayer County"
"31171" "Thomas County"
"31173" "Thurston County"
"31175" "Valley County"
"31177" "Washington County"
"31179" "Wayne County"
"31181" "Webster County"
"31183" "Wheeler County"
"31185" "York County"
"32" "Nevada"
"32001" "Churchill County"
"32003" "Clark County"
"32005" "Douglas County"
"32007" "Elko County"
"32009" "Esmeralda County"
"32011" "Eureka County"
"32013" "Humboldt County"
"32015" "Lander County"
"32017" "Lincoln County"
"32019" "Lyon County"
"32021" "Mineral County"
"32023" "Nye County"
"32027" "Pershing County"
"32029" "Storey County"
"32031" "Washoe County"
"32033" "White Pine County"
"32510" "Carson City"
"33" "New Hampshire"
"33001" "Belknap County"
"33003" "Carroll County"
"33005" "Cheshire County"
"33007" "Coos County"
"33009" "Grafton County"
"33011" "Hillsborough County"
"33013" "Merrimack County"
"33015" "Rockingham County"
"33017" "Strafford County"
"33019" "Sullivan County"
"34" "New Jersey"
"34001" "Atlantic County"
"34003" "Bergen County"
"34005" "Burlington County"
"34007" "Camden County"
"34009" "Cape May County"
"34011" "Cumberland County"
"34013" "Essex County"
"34015" "Gloucester County"
"34017" "Hudson County"
"34019" "Hunterdon County"
"34021" "Mercer County"
"34023" "Middlesex County"
"34025" "Monmouth County"
"34027" "Morris County"
"34029" "Ocean County"
"34031" "Passaic County"
"34033" "Salem County"
"34035" "Somerset County"
"34037" "Sussex County"
"34039" "Union County"
"34041" "Warren County"
"35" "New Mexico"
"35001" "Bernalillo County"
"35003" "Catron County"
"35005" "Chaves County"
"35006" "Cibola County"
"35007" "Colfax County"
"35009" "Curry County"
"35011" "De Baca County"
"35013" "Do\u00f1a Ana County"
"35015" "Eddy County"
"35017" "Grant County"
"35019" "Guadalupe County"
"35021" "Harding County"
"35023" "Hidalgo County"
"35025" "Lea County"
"35027" "Lincoln County"
"35028" "Los Alamos County"
"35029" "Luna County"
"35031" "McKinley County"
"35033" "Mora County"
"35035" "Otero County"
"35037" "Quay County"
"35039" "Rio Arriba County"
"35041" "Roosevelt County"
"35043" "Sandoval County"
"35045" "San Juan County"
"35047" "San Miguel County"
"35049" "Santa Fe County"
"35051" "Sierra County"
"35053" "Socorro County"
"35055" "Taos County"
"35057" "Torrance County"
"35059" "Union County"
"35061" "Valencia County"
"36" "New York"
"36001" "Albany County"
"36003" "Allegany County"
"36005" "Bronx County"
"36007" "Broome County"
"36009" "Cattaraugus County"
"36011" "Cayuga County"
"36013" "Chautauqua County"
"36015" "Chemung County"
"36017" "Chenango County"
"36019" "Clinton County"
"36021" "Columbia County"
"36023" "Cortland County"
"36025" "Delaware County"
"36027" "Dutchess County"
"36029" "Erie County"
"36031" "Essex County"
"36033" "Franklin County"
"36035" "Fulton County"
"36037" "Genesee County"
"36039" "Greene County"
"36041" "Hamilton County"
"36043" "Herkimer County"
"36045" "Jefferson County"
"36047" "Kings County"
"36049" "Lewis County"
"36051" "Livingston County"
"36053" "Madison County"
"36055" "Monroe County"
"36057" "Montgomery County"
"36059" "Nassau County"
"36061" "New York County"
"36063" "Niagara County"
"36065" "Oneida County"
"36067" "Onondaga County"
"36069" "Ontario County"
"36071" "Orange County"
"36073" "Orleans County"
"36075" "Oswego County"
"36077" "Otsego County"
"36079" "Putnam County"
"36081" "Queens County"
"36083" "Rensselaer County"
"36085" "Richmond County"
"36087" "Rockland County"
"36089" "St. Lawrence County"
"36091" "Saratoga County"
"36093" "Schenectady County"
"36095" "Schoharie County"
"36097" "Schuyler County"
"36099" "Seneca County"
"36101" "Steuben County"
"36103" "Suffolk County"
"36105" "Sullivan County"
"36107" "Tioga County"
"36109" "Tompkins County"
"36111" "Ulster County"
"36113" "Warren County"
"36115" "Washington County"
"36117" "Wayne County"
"36119" "Westchester County"
"36121" "Wyoming County"
"36123" "Yates County"
"37" "North Carolina"
"37001" "Alamance County"
"37003" "Alexander County"
"37005" "Alleghany County"
"37007" "Anson County"
"37009" "Ashe County"
"37011" "Avery County"
"37013" "Beaufort County"
"37015" "Bertie County"
"37017" "Bladen County"
"37019" "Brunswick County"
"37021" "Buncombe County"
"37023" "Burke County"
"37025" "Cabarrus County"
"37027" "Caldwell County"
"37029" "Camden County"
"37031" "Carteret County"
"37033" "Caswell County"
"37035" "Catawba County"
"37037" "Chatham County"
"37039" "Cherokee County"
"37041" "Chowan County"
"37043" "Clay County"
"37045" "Cleveland County"
"37047" "Columbus County"
"37049" "Craven County"
"37051" "Cumberland County"
"37053" "Currituck County"
"37055" "Dare County"
"37057" "Davidson County"
"37059" "Davie County"
"37061" "Duplin County"
"37063" "Durham County"
"37065" "Edgecombe County"
"37067" "Forsyth County"
"37069" "Franklin County"
"37071" "Gaston County"
"37073" "Gates County"
"37075" "Graham County"
"37077" "Granville County"
"37079" "Greene County"
"37081" "Guilford County"
"37083" "Halifax County"
"37085" "Harnett County"
"37087" "Haywood County"
"37089" "Henderson County"
"37091" "Hertford County"
"37093" "Hoke County"
"37095" "Hyde County"
"37097" "Iredell County"
"37099" "Jackson County"
"37101" "Johnston County"
"37103" "Jones County"
"37105" "Lee County"
"37107" "Lenoir County"
"37109" "Lincoln County"
"37111" "McDowell County"
"37113" "Macon County"
"37115" "Madison County"
"37117" "Martin County"
"37119" "Mecklenburg County"
"37121" "Mitchell County"
"37123" "Montgomery County"
"37125" "Moore County"
"37127" "Nash County"
"37129" "New Hanover County"
"37131" "Northampton County"
"37133" "Onslow County"
"37135" "Orange County"
"37137" "Pamlico County"
"37139" "Pasquotank County"
"37141" "Pender County"
"37143" "Perquimans County"
"37145" "Person County"
"37147" "Pitt County"
"37149" "Polk County"
"37151" "Randolph County"
"37153" "Richmond County"
"37155" "Robeson County"
"37157" "Rockingham County"
"37159" "Rowan County"
"37161" "Rutherford County"
"37163" "Sampson County"
"37165" "Scotland County"
"37167" "Stanly County"
"37169" "Stokes County"
"37171" "Surry County"
"37173" "Swain County"
"37175" "Transylvania County"
"37177" "Tyrrell County"
"37179" "Union County"
"37181" "Vance County"
"37183" "Wake County"
"37185" "Warren County"
"37187" "Washington County"
"37189" "Watauga County"
"37191" "Wayne County"
"37193" "Wilkes County"
"37195" "Wilson County"
"37197" "Yadkin County"
"37199" "Yancey County"
"38" "North Dakota"
"38001" "Adams County"
"38003" "Barnes County"
"38005" "Benson County"
"38007" "Billings County"
"38009" "Bottineau County"
"38011" "Bowman County"
"38013" "Burke County"
"38015" "Burleigh County"
"38017" "Cass County"
"38019" "Cavalier County"
"38021" "Dickey County"
"38023" "Divide County"
"38025" "Dunn County"
"38027" "Eddy County"
"38029" "Emmons County"
"38031" "Foster County"
"38033" "Golden Valley County"
"38035" "Grand Forks County"
"38037" "Grant County"
"38039" "Griggs County"
"38041" "Hettinger County"
"38043" "Kidder County"
"38045" "LaMoure County"
"38047" "Logan County"
"38049" "McHenry County"
"38051" "McIntosh County"
"38053" "McKenzie County"
"38055" "McLean County"
"38057" "Mercer County"
"38059" "Morton County"
"38061" "Mountrail County"
"38063" "Nelson County"
"38065" "Oliver County"
"38067" "Pembina County"
"38069" "Pierce County"
"38071" "Ramsey County"
"38073" "Ransom County"
"38075" "Renville County"
"38077" "Richland County"
"38079" "Rolette County"
"38081" "Sargent County"
"38083" "Sheridan County"
"38085" "Sioux County"
"38087" "Slope County"
"38089" "Stark County"
"38091" "Steele County"
"38093" "Stutsman County"
"38095" "Towner County"
"38097" "Traill County"
"38099" "Walsh County"
"38101" "Ward County"
"38103" "Wells County"
"38105" "Williams County"
"39" "Ohio"
"39001" "Adams County"
"39003" "Allen County"
"39005" "Ashland County"
"39007" "Ashtabula County"
"39009" "Athens County"
"39011" "Auglaize County"
"39013" "Belmont County"
"39015" "Brown County"
"39017" "Butler County"
"39019" "Carroll County"
"39021" "Champaign County"
"39023" "Clark County"
"39025" "Clermont County"
"39027" "Clinton County"
"39029" "Columbiana County"
"39031" "Coshocton County"
"39033" "Crawford County"
"39035" "Cuyahoga County"
"39037" "Darke County"
"39039" "Defiance County"
"39041" "Delaware County"
"39043" "Erie County"
"39045" "Fairfield County"
"39047" "Fayette County"
"39049" "Franklin County"
"39051" "Fulton County"
"39053" "Gallia County"
"39055" "Geauga County"
"39057" "Greene County"
"39059" "Guernsey County"
"39061" "Hamilton County"
"39063" "Hancock County"
"39065" "Hardin County"
"39067" "Harrison County"
"39069" "Henry County"
"39071" "Highland County"
"39073" "Hocking County"
"39075" "Holmes County"
"39077" "Huron County"
"39079" "Jackson County"
"39081" "Jefferson County"
"39083" "Knox County"
"39085" "Lake County"
"39087" "Lawrence County"
"39089" "Licking County"
"39091" "Logan County"
"39093" "Lorain County"
"39095" "Lucas County"
"39097" "Madison County"
"39099" "Mahoning County"
"39101" "Marion County"
"39103" "Medina County"
"39105" "Meigs County"
"39107" "Mercer County"
"39109" "Miami County"
"39111" "Monroe County"
"39113" "Montgomery County"
"39115" "Morgan County"
"39117" "Morrow County"
"39119" "Muskingum County"
"39121" "Noble County"
"39123" "Ottawa County"
"39125" "Paulding County"
"39127" "Perry County"
"39129" "Pickaway County"
"39131" "Pike County"
"39133" "Portage County"
"39135" "Preble County"
"39137" "Putnam County"
"39139" "Richland County"
"39141" "Ross County"
"39143" "Sandusky County"
"39145" "Scioto County"
"39147" "Seneca County"
"39149" "Shelby County"
"39151" "Stark County"
"39153" "Summit County"
"39155" "Trumbull County"
"39157" "Tuscarawas County"
"39159" "Union County"
"39161" "Van Wert County"
"39163" "Vinton County"
"39165" "Warren County"
"39167" "Washington County"
"39169" "Wayne County"
"39171" "Williams County"
"39173" "Wood County"
"39175" "Wyandot County"
"40" "Oklahoma"
"40001" "Adair County"
"40003" "Alfalfa County"
"40005" "Atoka County"
"40007" "Beaver County"
"40009" "Beckham County"
"40011" "Blaine County"
"40013" "Bryan County"
"40015" "Caddo County"
"40017" "Canadian County"
"40019" "Carter County"
"40021" "Cherokee County"
"40023" "Choctaw County"
"40025" "Cimarron County"
"40027" "Cleveland County"
"40029" "Coal County"
"40031" "Comanche County"
"40033" "Cotton County"
"40035" "Craig County"
"40037" "Creek County"
"40039" "Custer County"
"40041" "Delaware County"
"40043" "Dewey County"
"40045" "Ellis County"
"40047" "Garfield County"
"40049" "Garvin County"
"40051" "Grady County"
"40053" "Grant County"
"40055" "Greer County"
"40057" "Harmon County"
"40059" "Harper County"
"40061" "Haskell County"
"40063" "Hughes County"
"40065" "Jackson County"
"40067" "Jefferson County"
"40069" "Johnston County"
"40071" "Kay County"
"40073" "Kingfisher County"
"40075" "Kiowa County"
"40077" "Latimer County"
"40079" "Le Flore County"
"40081" "Lincoln County"
"40083" "Logan County"
"40085" "Love County"
"40087" "McClain County"
"40089" "McCurtain County"
"40091" "McIntosh County"
"40093" "Major County"
"40095" "Marshall County"
"40097" "Mayes County"
"40099" "Murray County"
"40101" "Muskogee County"
"40103" "Noble County"
"40105" "Nowata County"
"40107" "Okfuskee County"
"40109" "Oklahoma County"
"40111" "Okmulgee County"
"40113" "Osage County"
"40115" "Ottawa County"
"40117" "Pawnee County"
"40119" "Payne County"
"40121" "Pittsburg County"
"40123" "Pontotoc County"
"40125" "Pottawatomie County"
"40127" "Pushmataha County"
"40129" "Roger Mills County"
"40131" "Rogers County"
"40133" "Seminole County"
"40135" "Sequoyah County"
"40137" "Stephens County"
"40139" "Texas County"
"40141" "Tillman County"
"40143" "Tulsa County"
"40145" "Wagoner County"
"40147" "Washington County"
"40149" "Washita County"
"40151" "Woods County"
"40153" "Woodward County"
"41" "Oregon"
"41001" "Baker County"
"41003" "Benton County"
"41005" "Clackamas County"
"41007" "Clatsop County"
"41009" "Columbia County"
"41011" "Coos County"
"41013" "Crook County"
"41015" "Curry County"
"41017" "Deschutes County"
"41019" "Douglas County"
"41021" "Gilliam County"
"41023" "Grant County"
"41025" "Harney County"
"41027" "Hood River County"
"41029" "Jackson County"
"41031" "Jefferson County"
"41033" "Josephine County"
"41035" "Klamath County"
"41037" "Lake County"
"41039" "Lane County"
"41041" "Lincoln County"
"41043" "Linn County"
"41045" "Malheur County"
"41047" "Marion County"
"41049" "Morrow County"
"41051" "Multnomah County"
"41053" "Polk County"
"41055" "Sherman County"
"41057" "Tillamook County"
"41059" "Umatilla County"
"41061" "Union County"
"41063" "Wallowa County"
"41065" "Wasco County"
"41067" "Washington County"
"41069" "Wheeler County"
"41071" "Yamhill County"
"42" "Pennsylvania"
"42001" "Adams County"
"42003" "Allegheny County"
"42005" "Armstrong County"
"42007" "Beaver County"
"42009" "Bedford County"
"42011" "Berks County"
"42013" "Blair County"
"42015" "Bradford County"
"42017" "Bucks County"
"42019" "Butler County"
"42021" "Cambria County"
"42023" "Cameron County"
"42025" "Carbon County"
"42027" "Centre County"
"42029" "Chester County"
"42031" "Clarion County"
"42033" "Clearfield County"
"42035" "Clinton County"
"42037" "Columbia County"
"42039" "Crawford County"
"42041" "Cumberland County"
"42043" "Dauphin County"
"42045" "Delaware County"
"42047" "Elk County"
"42049" "Erie County"
"42051" "Fayette County"
"42053" "Forest County"
"42055" "Franklin County"
"42057" "Fulton County"
"42059" "Greene County"
"42061" "Huntingdon County"
"42063" "Indiana County"
"42065" "Jefferson County"
"42067" "Juniata County"
"42069" "Lackawanna County"
"42071" "Lancaster County"
"42073" "Lawrence County"
"42075" "Lebanon County"
"42077" "Lehigh County"
"42079" "Luzerne County"
"42081" "Lycoming County"
"42083" "McKean County"
"42085" "Mercer County"
"42087" "Mifflin County"
"42089" "Monroe County"
"42091" "Montgomery County"
"42093" "Montour County"
"42095" "Northampton County"
"42097" "Northumberland County"
"42099" "Perry County"
"42101" "Philadelphia County"
"42103" "Pike County"
"42105" "Potter County"
"42107" "Schuylkill County"
"42109" "Snyder County"
"42111" "Somerset County"
"42113" "Sullivan County"
"42115" "Susquehanna County"
"42117" "Tioga County"
"42119" "Union County"
"42121" "Venango County"
"42123" "Warren County"
"42125" "Washington County"
"42127" "Wayne County"
"42129" "Westmoreland County"
"42131" "Wyoming County"
"42133" "York County"
"44" "Rhode Island"
"44001" "Bristol County"
"44003" "Kent County"
"44005" "Newport County"
"44007" "Providence County"
"44009" "Washington County"
"45" "South Carolina"
"45001" "Abbeville County"
"45003" "Aiken County"
"45005" "Allendale County"
"45007" "Anderson County"
"45009" "Bamberg County"
"45011" "Barnwell County"
"45013" "Beaufort County"
"45015" "Berkeley County"
"45017" "Calhoun County"
"45019" "Charleston County"
"45021" "Cherokee County"
"45023" "Chester County"
"45025" "Chesterfield County"
"45027" "Clarendon County"
"45029" "Colleton County"
"45031" "Darlington County"
"45033" "Dillon County"
"45035" "Dorchester County"
"45037" "Edgefield County"
"45039" "Fairfield County"
"45041" "Florence County"
"45043" "Georgetown County"
"45045" "Greenville County"
"45047" "Greenwood County"
"45049" "Hampton County"
"45051" "Horry County"
"45053" "Jasper County"
"45055" "Kershaw County"
"45057" "Lancaster County"
"45059" "Laurens County"
"45061" "Lee County"
"45063" "Lexington County"
"45065" "McCormick County"
"45067" "Marion County"
"45069" "Marlboro County"
"45071" "Newberry County"
"45073" "Oconee County"
"45075" "Orangeburg County"
"45077" "Pickens County"
"45079" "Richland County"
"45081" "Saluda County"
"45083" "Spartanburg County"
"45085" "Sumter County"
"45087" "Union County"
"45089" "Williamsburg County"
"45091" "York County"
"46" "South Dakota"
"46003" "Aurora County"
"46005" "Beadle County"
"46007" "Bennett County"
"46009" "Bon Homme County"
"46011" "Brookings County"
"46013" "Brown County"
"46015" "Brule County"
"46017" "Buffalo County"
"46019" "Butte County"
"46021" "Campbell County"
"46023" "Charles Mix County"
"46025" "Clark County"
"46027" "Clay County"
"46029" "Codington County"
"46031" "Corson County"
"46033" "Custer County"
"46035" "Davison County"
"46037" "Day County"
"46039" "Deuel County"
"46041" "Dewey County"
"46043" "Douglas County"
"46045" "Edmunds County"
"46047" "Fall River County"
"46049" "Faulk County"
"46051" "Grant County"
"46053" "Gregory County"
"46055" "Haakon County"
"46057" "Hamlin County"
"46059" "Hand County"
"46061" "Hanson County"
"46063" "Harding County"
"46065" "Hughes County"
"46067" "Hutchinson County"
"46069" "Hyde County"
"46071" "Jackson County"
"46073" "Jerauld County"
"46075" "Jones County"
"46077" "Kingsbury County"
"46079" "Lake County"
"46081" "Lawrence County"
"46083" "Lincoln County"
"46085" "Lyman County"
"46087" "McCook County"
"46089" "McPherson County"
"46091" "Marshall County"
"46093" "Meade County"
"46095" "Mellette County"
"46097" "Miner County"
"46099" "Minnehaha County"
"46101" "Moody County"
"46102" "Oglala Lakota County"
"46103" "Pennington County"
"46105" "Perkins County"
"46107" "Potter County"
"46109" "Roberts County"
"46111" "Sanborn County"
"46115" "Spink County"
"46117" "Stanley County"
"46119" "Sully County"
"46121" "Todd County"
"46123" "Tripp County"
"46125" "Turner County"
"46127" "Union County"
"46129" "Walworth County"
"46135" "Yankton County"
"46137" "Ziebach County"
"47" "Tennessee"
"47001" "Anderson County"
"47003" "Bedford County"
"47005" "Benton County"
"47007" "Bledsoe County"
"47009" "Blount County"
"47011" "Bradley County"
"47013" "Campbell County"
"47015" "Cannon County"
"47017" "Carroll County"
"47019" "Carter County"
"47021" "Cheatham County"
"47023" "Chester County"
"47025" "Claiborne County"
"47027" "Clay County"
"47029" "Cocke County"
"47031" "Coffee County"
"47033" "Crockett County"
"47035" "Cumberland County"
"47037" "Davidson County"
"47039" "Decatur County"
"47041" "DeKalb County"
"47043" "Dickson County"
"47045" "Dyer County"
"47047" "Fayette County"
"47049" "Fentress County"
"47051" "Franklin County"
"47053" "Gibson County"
"47055" "Giles County"
"47057" "Grainger County"
"47059" "Greene County"
"47061" "Grundy County"
"47063" "Hamblen County"
"47065" "Hamilton County"
"47067" "Hancock County"
"47069" "Hardeman County"
"47071" "Hardin County"
"47073" "Hawkins County"
"47075" "Haywood County"
"47077" "Henderson County"
"47079" "Henry County"
"47081" "Hickman County"
"47083" "Houston County"
"47085" "Humphreys County"
"47087" "Jackson County"
"47089" "Jefferson County"
"47091" "Johnson County"
"47093" "Knox County"
"47095" "Lake County"
"47097" "Lauderdale County"
"47099" "Lawrence County"
"47101" "Lewis County"
"47103" "Lincoln County"
"47105" "Loudon County"
"47107" "McMinn County"
"47109" "McNairy County"
"47111" "Macon County"
"47113" "Madison County"
"47115" "Marion County"
"47117" "Marshall County"
"47119" "Maury County"
"47121" "Meigs County"
"47123" "Monroe County"
"47125" "Montgomery County"
"47127" "Moore County"
"47129" "Morgan County"
"47131" "Obion County"
"47133" "Overton County"
"47135" "Perry County"
"47137" "Pickett County"
"47139" "Polk County"
"47141" "Putnam County"
"47143" "Rhea County"
"47145" "Roane County"
"47147" "Robertson County"
"47149" "Rutherford County"
"47151" "Scott County"
"47153" "Sequatchie County"
"47155" "Sevier County"
"47157" "Shelby County"
"47159" "Smith County"
"47161" "Stewart County"
"47163" "Sullivan County"
"47165" "Sumner County"
"47167" "Tipton County"
"47169" "Trousdale County"
"47171" "Unicoi County"
"47173" "Union County"
"47175" "Van Buren County"
"47177" "Warren County"
"47179" "Washington County"
"47181" "Wayne County"
"47183" "Weakley County"
"47185" "White County"
"47187" "Williamson County"
"47189" "Wilson County"
"48" "Texas"
"48001" "Anderson County"
"48003" "Andrews County"
"48005" "Angelina County"
"48007" "Aransas County"
"48009" "Archer County"
"48011" "Armstrong County"
"48013" "Atascosa County"
"48015" "Austin County"
"48017" "Bailey County"
"48019" "Bandera County"
"48021" "Bastrop County"
"48023" "Baylor County"
"48025" "Bee County"
"48027" "Bell County"
"48029" "Bexar County"
"48031" "Blanco County"
"48033" "Borden County"
"48035" "Bosque County"
"48037" "Bowie County"
"48039" "Brazoria County"
"48041" "Brazos County"
"48043" "Brewster County"
"48045" "Briscoe County"
"48047" "Brooks County"
"48049" "Brown County"
"48051" "Burleson County"
"48053" "Burnet County"
"48055" "Caldwell County"
"48057" "Calhoun County"
"48059" "Callahan County"
"48061" "Cameron County"
"48063" "Camp County"
"48065" "Carson County"
"48067" "Cass County"
"48069" "Castro County"
"48071" "Chambers County"
"48073" "Cherokee County"
"48075" "Childress County"
"48077" "Clay County"
"48079" "Cochran County"
"48081" "Coke County"
"48083" "Coleman County"
"48085" "Collin County"
"48087" "Collingsworth County"
"48089" "Colorado County"
"48091" "Comal County"
"48093" "Comanche County"
"48095" "Concho County"
"48097" "Cooke County"
"48099" "Coryell County"
"48101" "Cottle County"
"48103" "Crane County"
"48105" "Crockett County"
"48107" "Crosby County"
"48109" "Culberson County"
"48111" "Dallam County"
"48113" "Dallas County"
"48115" "Dawson County"
"48117" "Deaf Smith County"
"48119" "Delta County"
"48121" "Denton County"
"48123" "DeWitt County"
"48125" "Dickens County"
"48127" "Dimmit County"
"48129" "Donley County"
"48131" "Duval County"
"48133" "Eastland County"
"48135" "Ector County"
"48137" "Edwards County"
"48139" "Ellis County"
"48141" "El Paso County"
"48143" "Erath County"
"48145" "Falls County"
"48147" "Fannin County"
"48149" "Fayette County"
"48151" "Fisher County"
"48153" "Floyd County"
"48155" "Foard County"
"48157" "Fort Bend County"
"48159" "Franklin County"
"48161" "Freestone County"
"48163" "Frio County"
"48165" "Gaines County"
"48167" "Galveston County"
"48169" "Garza County"
"48171" "Gillespie County"
"48173" "Glasscock County"
"48175" "Goliad County"
"48177" "Gonzales County"
"48179" "Gray County"
"48181" "Grayson County"
"48183" "Gregg County"
"48185" "Grimes County"
"48187" "Guadalupe County"
"48189" "Hale County"
"48191" "Hall County"
"48193" "Hamilton County"
"48195" "Hansford County"
"48197" "Hardeman County"
"48199" "Hardin County"
"48201" "Harris County"
"48203" "Harrison County"
"48205" "Hartley County"
"48207" "Haskell County"
"48209" "Hays County"
"48211" "Hemphill County"
"48213" "Henderson County"
"48215" "Hidalgo County"
"48217" "Hill County"
"48219" "Hockley County"
"48221" "Hood County"
"48223" "Hopkins County"
"48225" "Houston County"
"48227" "Howard County"
"48229" "Hudspeth County"
"48231" "Hunt County"
"48233" "Hutchinson County"
"48235" "Irion County"
"48237" "Jack County"
"48239" "Jackson County"
"48241" "Jasper County"
"48243" "Jeff Davis County"
"48245" "Jefferson County"
"48247" "Jim Hogg County"
"48249" "Jim Wells County"
"48251" "Johnson County"
"48253" "Jones County"
"48255" "Karnes County"
"48257" "Kaufman County"
"48259" "Kendall County"
"48261" "Kenedy County"
"48263" "Kent County"
"48265" "Kerr County"
"48267" "Kimble County"
"48269" "King County"
"48271" "Kinney County"
"48273" "Kleberg County"
"48275" "Knox County"
"48277" "Lamar County"
"48279" "Lamb County"
"48281" "Lampasas County"
"48283" "La Salle County"
"48285" "Lavaca County"
"48287" "Lee County"
"48289" "Leon County"
"48291" "Liberty County"
"48293" "Limestone County"
"48295" "Lipscomb County"
"48297" "Live Oak County"
"48299" "Llano County"
"48301" "Loving County"
"48303" "Lubbock County"
"48305" "Lynn County"
"48307" "McCulloch County"
"48309" "McLennan County"
"48311" "McMullen County"
"48313" "Madison County"
"48315" "Marion County"
"48317" "Martin County"
"48319" "Mason County"
"48321" "Matagorda County"
"48323" "Maverick County"
"48325" "Medina County"
"48327" "Menard County"
"48329" "Midland County"
"48331" "Milam County"
"48333" "Mills County"
"48335" "Mitchell County"
"48337" "Montague County"
"48339" "Montgomery County"
"48341" "Moore County"
"48343" "Morris County"
"48345" "Motley County"
"48347" "Nacogdoches County"
"48349" "Navarro County"
"48351" "Newton County"
"48353" "Nolan County"
"48355" "Nueces County"
"48357" "Ochiltree County"
"48359" "Oldham County"
"48361" "Orange County"
"48363" "Palo Pinto County"
"48365" "Panola County"
"48367" "Parker County"
"48369" "Parmer County"
"48371" "Pecos County"
"48373" "Polk County"
"48375" "Potter County"
"48377" "Presidio County"
"48379" "Rains County"
"48381" "Randall County"
"48383" "Reagan County"
"48385" "Real County"
"48387" "Red River County"
"48389" "Reeves County"
"48391" "Refugio County"
"48393" "Roberts County"
"48395" "Robertson County"
"48397" "Rockwall County"
"48399" "Runnels County"
"48401" "Rusk County"
"48403" "Sabine County"
"48405" "San Augustine County"
"48407" "San Jacinto County"
"48409" "San Patricio County"
"48411" "San Saba County"
"48413" "Schleicher County"
"48415" "Scurry County"
"48417" "Shackelford County"
"48419" "Shelby County"
"48421" "Sherman County"
"48423" "Smith County"
"48425" "Somervell County"
"48427" "Starr County"
"48429" "Stephens County"
"48431" "Sterling County"
"48433" "Stonewall County"
"48435" "Sutton County"
"48437" "Swisher County"
"48439" "Tarrant County"
"48441" "Taylor County"
"48443" "Terrell County"
"48445" "Terry County"
"48447" "Throckmorton County"
"48449" "Titus County"
"48451" "Tom Green County"
"48453" "Travis County"
"48455" "Trinity County"
"48457" "Tyler County"
"48459" "Upshur County"
"48461" "Upton County"
"48463" "Uvalde County"
"48465" "Val Verde County"
"48467" "Van Zandt County"
"48469" "Victoria County"
"48471" "Walker County"
"48473" "Waller County"
"48475" "Ward County"
"48477" "Washington County"
"48479" "Webb County"
"48481" "Wharton County"
"48483" "Wheeler County"
"48485" "Wichita County"
"48487" "Wilbarger County"
"48489" "Willacy County"
"48491" "Williamson County"
"48493" "Wilson County"
"48495" "Winkler County"
"48497" "Wise County"
"48499" "Wood County"
"48501" "Yoakum County"
"48503" "Young County"
"48505" "Zapata County"
"48507" "Zavala County"
"49" "Utah"
"49001" "Beaver County"
"49003" "Box Elder County"
"49005" "Cache County"
"49007" "Carbon County"
"49009" "Daggett County"
"49011" "Davis County"
"49013" "Duchesne County"
"49015" "Emery County"
"49017" "Garfield County"
"49019" "Grand County"
"49021" "Iron County"
"49023" "Juab County"
"49025" "Kane County"
"49027" "Millard County"
"49029" "Morgan County"
"49031" "Piute County"
"49033" "Rich County"
"49035" "Salt Lake County"
"49037" "San Juan County"
"49039" "Sanpete County"
"49041" "Sevier County"
"49043" "Summit County"
"49045" "Tooele County"
"49047" "Uintah County"
"49049" "Utah County"
"49051" "Wasatch County"
"49053" "Washington County"
"49055" "Wayne County"
"49057" "Weber County"
"50" "Vermont"
"50001" "Addison County"
"50003" "Bennington County"
"50005" "Caledonia County"
"50007" "Chittenden County"
"50009" "Essex County"
"50011" "Franklin County"
"50013" "Grand Isle County"
"50015" "Lamoille County"
"50017" "Orange County"
"50019" "Orleans County"
"50021" "Rutland County"
"50023" "Washington County"
"50025" "Windham County"
"50027" "Windsor County"
"51" "Virginia"
"51001" "Accomack County"
"51003" "Albemarle County"
"51005" "Alleghany County"
"51007" "Amelia County"
"51009" "Amherst County"
"51011" "Appomattox County"
"51013" "Arlington County"
"51015" "Augusta County"
"51017" "Bath County"
"51019" "Bedford County"
"51021" "Bland County"
"51023" "Botetourt County"
"51025" "Brunswick County"
"51027" "Buchanan County"
"51029" "Buckingham County"
"51031" "Campbell County"
"51033" "Caroline County"
"51035" "Carroll County"
"51036" "Charles City County"
"51037" "Charlotte County"
"51041" "Chesterfield County"
"51043" "Clarke County"
"51045" "Craig County"
"51047" "Culpeper County"
"51049" "Cumberland County"
"51051" "Dickenson County"
"51053" "Dinwiddie County"
"51057" "Essex County"
"51059" "Fairfax County"
"51061" "Fauquier County"
"51063" "Floyd County"
"51065" "Fluvanna County"
"51067" "Franklin County"
"51069" "Frederick County"
"51071" "Giles County"
"51073" "Gloucester County"
"51075" "Goochland County"
"51077" "Grayson County"
"51079" "Greene County"
"51081" "Greensville County"
"51083" "Halifax County"
"51085" "Hanover County"
"51087" "Henrico County"
"51089" "Henry County"
"51091" "Highland County"
"51093" "Isle of Wight County"
"51095" "James City County"
"51097" "King and Queen County"
"51099" "King George County"
"51101" "King William County"
"51103" "Lancaster County"
"51105" "Lee County"
"51107" "Loudoun County"
"51109" "Louisa County"
"51111" "Lunenburg County"
"51113" "Madison County"
"51115" "Mathews County"
"51117" "Mecklenburg County"
"51119" "Middlesex County"
"51121" "Montgomery County"
"51125" "Nelson County"
"51127" "New Kent County"
"51131" "Northampton County"
"51133" "Northumberland County"
"51135" "Nottoway County"
"51137" "Orange County"
"51139" "Page County"
"51141" "Patrick County"
"51143" "Pittsylvania County"
"51145" "Powhatan County"
"51147" "Prince Edward County"
"51149" "Prince George County"
"51153" "Prince William County"
"51155" "Pulaski County"
"51157" "Rappahannock County"
"51159" "Richmond County"
"51161" "Roanoke County"
"51163" "Rockbridge County"
"51165" "Rockingham County"
"51167" "Russell County"
"51169" "Scott County"
"51171" "Shenandoah County"
"51173" "Smyth County"
"51175" "Southampton County"
"51177" "Spotsylvania County"
"51179" "Stafford County"
"51181" "Surry County"
"51183" "Sussex County"
"51185" "Tazewell County"
"51187" "Warren County"
"51191" "Washington County"
"51193" "Westmoreland County"
"51195" "Wise County"
"51197" "Wythe County"
"51199" "York County"
"51510" "Alexandria city"
"51520" "Bristol city"
"51530" "Buena Vista city"
"51540" "Charlottesville city"
"51550" "Chesapeake city"
"51570" "Colonial Heights city"
"51580" "Covington city"
"51590" "Danville city"
"51595" "Emporia city"
"51600" "Fairfax city"
"51610" "Falls Church city"
"51620" "Franklin city"
"51630" "Fredericksburg city"
"51640" "Galax city"
"51650" "Hampton city"
"51660" "Harrisonburg city"
"51670" "Hopewell city"
"51678" "Lexington city"
"51680" "Lynchburg city"
"51683" "Manassas city"
"51685" "Manassas Park city"
"51690" "Martinsville city"
"51700" "Newport News city"
"51710" "Norfolk city"
"51720" "Norton city"
"51730" "Petersburg city"
"51735" "Poquoson city"
"51740" "Portsmouth city"
"51750" "Radford city"
"51760" "Richmond city"
"51770" "Roanoke city"
"51775" "Salem city"
"51790" "Staunton city"
"51800" "Suffolk city"
"51810" "Virginia Beach city"
"51820" "Waynesboro city"
"51830" "Williamsburg city"
"51840" "Winchester city"
"53" "Washington"
"53001" "Adams County"
"53003" "Asotin County"
"53005" "Benton County"
"53007" "Chelan County"
"53009" "Clallam County"
"53011" "Clark County"
"53013" "Columbia County"
"53015" "Cowlitz County"
"53017" "Douglas County"
"53019" "Ferry County"
"53021" "Franklin County"
"53023" "Garfield County"
"53025" "Grant County"
"53027" "Grays Harbor County"
"53029" "Island County"
"53031" "Jefferson County"
"53033" "King County"
"53035" "Kitsap County"
"53037" "Kittitas County"
"53039" "Klickitat County"
"53041" "Lewis County"
"53043" "Lincoln County"
"53045" "Mason County"
"53047" "Okanogan County"
"53049" "Pacific County"
"53051" "Pend Oreille County"
"53053" "Pierce County"
"53055" "San Juan County"
"53057" "Skagit County"
"53059" "Skamania County"
"53061" "Snohomish County"
"53063" "Spokane County"
"53065" "Stevens County"
"53067" "Thurston County"
"53069" "Wahkiakum County"
"53071" "Walla Walla County"
"53073" "Whatcom County"
"53075" "Whitman County"
"53077" "Yakima County"
"54" "West Virginia"
"54001" "Barbour County"
"54003" "Berkeley County"
"54005" "Boone County"
"54007" "Braxton County"
"54009" "Brooke County"
"54011" "Cabell County"
"54013" "Calhoun County"
"54015" "Clay County"
"54017" "Doddridge County"
"54019" "Fayette County"
"54021" "Gilmer County"
"54023" "Grant County"
"54025" "Greenbrier County"
"54027" "Hampshire County"
"54029" "Hancock County"
"54031" "Hardy County"
"54033" "Harrison County"
"54035" "Jackson County"
"54037" "Jefferson County"
"54039" "Kanawha County"
"54041" "Lewis County"
"54043" "Lincoln County"
"54045" "Logan County"
"54047" "McDowell County"
"54049" "Marion County"
"54051" "Marshall County"
"54053" "Mason County"
"54055" "Mercer County"
"54057" "Mineral County"
"54059" "Mingo County"
"54061" "Monongalia County"
"54063" "Monroe County"
"54065" "Morgan County"
"54067" "Nicholas County"
"54069" "Ohio County"
"54071" "Pendleton County"
"54073" "Pleasants County"
"54075" "Pocahontas County"
"54077" "Preston County"
"54079" "Putnam County"
"54081" "Raleigh County"
"54083" "Randolph County"
"54085" "Ritchie County"
"54087" "Roane County"
"54089" "Summers County"
"54091" "Taylor County"
"54093" "Tucker County"
"54095" "Tyler County"
"54097" "Upshur County"
"54099" "Wayne County"
"54101" "Webster County"
"54103" "Wetzel County"
"54105" "Wirt County"
"54107" "Wood County"
"54109" "Wyoming County"
"55" "Wisconsin"
"55001" "Adams County"
"55003" "Ashland County"
"55005" "Barron County"
"55007" "Bayfield County"
"55009" "Brown County"
"55011" "Buffalo County"
"55013" "Burnett County"
"55015" "Calumet County"
"55017" "Chippewa County"
"55019" "Clark County"
"55021" "Columbia County"
"55023" "Crawford County"
"55025" "Dane County"
"55027" "Dodge County"
"55029" "Door County"
"55031" "Douglas County"
"55033" "Dunn County"
"55035" "Eau Claire County"
"55037" "Florence County"
"55039" "Fond du Lac County"
"55041" "Forest County"
"55043" "Grant County"
"55045" "Green County"
"55047" "Green Lake County"
"55049" "Iowa County"
"55051" "Iron County"
"55053" "Jackson County"
"55055" "Jefferson County"
"55057" "Juneau County"
"55059" "Kenosha County"
"55061" "Kewaunee County"
"55063" "La Crosse County"
"55065" "Lafayette County"
"55067" "Langlade County"
"55069" "Lincoln County"
"55071" "Manitowoc County"
"55073" "Marathon County"
"55075" "Marinette County"
"55077" "Marquette County"
"55078" "Menominee County"
"55079" "Milwaukee County"
"55081" "Monroe County"
"55083" "Oconto County"
"55085" "Oneida County"
"55087" "Outagamie County"
"55089" "Ozaukee County"
"55091" "Pepin County"
"55093" "Pierce County"
"55095" "Polk County"
"55097" "Portage County"
"55099" "Price County"
"55101" "Racine County"
"55103" "Richland County"
"55105" "Rock County"
"55107" "Rusk County"
"55109" "St. Croix County"
"55111" "Sauk County"
"55113" "Sawyer County"
"55115" "Shawano County"
"55117" "Sheboygan County"
"55119" "Taylor County"
"55121" "Trempealeau County"
"55123" "Vernon County"
"55125" "Vilas County"
"55127" "Walworth County"
"55129" "Washburn County"
"55131" "Washington County"
"55133" "Waukesha County"
"55135" "Waupaca County"
"55137" "Waushara County"
"55139" "Winnebago County"
"55141" "Wood County"
"56" "Wyoming"
"56001" "Albany County"
"56003" "Big Horn County"
"56005" "Campbell County"
"56007" "Carbon County"
"56009" "Converse County"
"56011" "Crook County"
"56013" "Fremont County"
"56015" "Goshen County"
"56017" "Hot Springs County"
"56019" "Johnson County"
"56021" "Laramie County"
"56023" "Lincoln County"
"56025" "Natrona County"
"56027" "Niobrara County"
"56029" "Park County"
"56031" "Platte County"
"56033" "Sheridan County"
"56035" "Sublette County"
"56037" "Sweetwater County"
"56039" "Teton County"
"56041" "Uinta County"
"56043" "Washakie County"
"56045" "Weston County"})
(defn fips-name
([state-fips county-fips]
(fips-name (str state-fips county-fips)))
([fips]
(get fips->name fips fips)))
(defn county-list
"Given a state fips, returns a vector of vectors like:
[[\"01001\" \"Autauga County\"]
[\"01003\" \"Baldwin County\"]
...]
The order is defined by the order of the county fips codes.
The counties come from the fips->name map."
[state-fips]
(letfn [(in-state? [candidate-fips]
(str/starts-with? candidate-fips state-fips))
(county-fips? [candidate-fips]
(= 5 (count candidate-fips)))
(county-fips-for-state? [candidate-fips]
(and (in-state? candidate-fips)
(county-fips? candidate-fips)))]
(let [county-keys (->> (keys fips->name)
(filter county-fips-for-state?)
sort)
county-names (map fips->name county-keys)]
(mapv vector county-keys county-names))))
(def state-fips->abbreviation
{"01" "AL"
"02" "AK"
"04" "AZ"
"05" "AR"
"06" "CA"
"08" "CO"
"09" "CT"
"10" "DE"
"11" "DC"
"12" "FL"
"13" "GA"
"15" "HI"
"16" "ID"
"17" "IL"
"18" "IN"
"19" "IA"
"20" "KS"
"21" "KY"
"22" "LA"
"23" "ME"
"24" "MD"
"25" "MA"
"26" "MI"
"27" "MN"
"28" "MS"
"29" "MO"
"30" "MT"
"31" "NE"
"32" "NV"
"33" "NH"
"34" "NJ"
"35" "NM"
"36" "NY"
"37" "NC"
"38" "ND"
"39" "OH"
"40" "OK"
"41" "OR"
"42" "PA"
"44" "RI"
"45" "SC"
"46" "SD"
"47" "TN"
"48" "TX"
"49" "UT"
"50" "VT"
"51" "VA"
"53" "WA"
"54" "WV"
"55" "WI"
"56" "WY"})
|
44585
|
(ns early-vote-site.places
(:require [clojure.string :as str]))
(def fips->name
{"01" "Alabama"
"01001" "Autauga County"
"01003" "Baldwin County"
"01005" "Barbour County"
"01007" "Bibb County"
"01009" "Blount County"
"01011" "Bullock County"
"01013" "Butler County"
"01015" "Calhoun County"
"01017" "Chambers County"
"01019" "Cherokee County"
"01021" "Chilton County"
"01023" "Choctaw County"
"01025" "Clarke County"
"01027" "Clay County"
"01029" "Cleburne County"
"01031" "Coffee County"
"01033" "Colbert County"
"01035" "Conecuh County"
"01037" "Coosa County"
"01039" "Covington County"
"01041" "Crenshaw County"
"01043" "Cullman County"
"01045" "Dale County"
"01047" "Dallas County"
"01049" "DeKalb County"
"01051" "Elmore County"
"01053" "Escambia County"
"01055" "Etowah County"
"01057" "Fayette County"
"01059" "Franklin County"
"01061" "Geneva County"
"01063" "Greene County"
"01065" "Hale County"
"01067" "Henry County"
"01069" "Houston County"
"01071" "Jackson County"
"01073" "Jefferson County"
"01075" "Lamar County"
"01077" "Lauderdale County"
"01079" "Lawrence County"
"01081" "Lee County"
"01083" "Limestone County"
"01085" "Lowndes County"
"01087" "Macon County"
"01089" "Madison County"
"01091" "Marengo County"
"01093" "Marion County"
"01095" "Marshall County"
"01097" "Mobile County"
"01099" "Monroe County"
"01101" "Montgomery County"
"01103" "Morgan County"
"01105" "Perry County"
"01107" "<NAME>kens County"
"01109" "Pike County"
"01111" "Randolph County"
"01113" "Russell County"
"01115" "St. Clair County"
"01117" "Shelby County"
"01119" "Sumter County"
"01121" "Talladega County"
"01123" "Tallapoosa County"
"01125" "Tuscaloosa County"
"01127" "Walker County"
"01129" "Washington County"
"01131" "Wilcox County"
"01133" "Winston County"
"02" "Alaska"
"02013" "Aleutians East Borough"
"02016" "Aleutians West Census Area"
"02020" "Anchorage Municipality"
"02050" "Bethel Census Area"
"02060" "Bristol Bay Borough"
"02068" "Denali Borough"
"02070" "Dillingham Census Area"
"02090" "Fairbanks North Star Borough"
"02100" "Haines Borough"
"02105" "Hoonah-Angoon Census Area"
"02110" "Juneau City and Borough"
"02122" "Kenai Peninsula Borough"
"02130" "Ketchikan Gateway Borough"
"02150" "Kodiak Island Borough"
"02158" "Kusilvak Census Area"
"02164" "Lake and Peninsula Borough"
"02170" "Matanuska-Susitna Borough"
"02180" "Nome Census Area"
"02185" "North Slope Borough"
"02188" "Northwest Arctic Borough"
"02195" "Petersburg Borough"
"02198" "Prince of Wales-Hyder Census Area"
"02220" "Sitka City and Borough"
"02230" "Skagway Municipality"
"02240" "Southeast Fairbanks Census Area"
"02261" "Valdez-Cordova Census Area"
"02275" "Wrangell City and Borough"
"02282" "Yakutat City and Borough"
"02290" "Yukon-Koyukuk Census Area"
"04" "Arizona"
"04001" "Apache County"
"04003" "Cochise County"
"04005" "Coconino County"
"04007" "Gila County"
"04009" "Graham County"
"04011" "Greenlee County"
"04012" "La Paz County"
"04013" "Maricopa County"
"04015" "Mohave County"
"04017" "Navajo County"
"04019" "Pima County"
"04021" "Pinal County"
"04023" "Santa Cruz County"
"04025" "Yavapai County"
"04027" "Yuma County"
"05" "Arkansas"
"05001" "Arkansas County"
"05003" "Ashley County"
"05005" "Baxter County"
"05007" "Benton County"
"05009" "Boone County"
"05011" "Bradley County"
"05013" "Calhoun County"
"05015" "Carroll County"
"05017" "Chicot County"
"05019" "Clark County"
"05021" "Clay County"
"05023" "Cleburne County"
"05025" "Cleveland County"
"05027" "Columbia County"
"05029" "Conway County"
"05031" "Craighead County"
"05033" "Crawford County"
"05035" "Crittenden County"
"05037" "Cross County"
"05039" "Dallas County"
"05041" "Desha County"
"05043" "Drew County"
"05045" "Faulkner County"
"05047" "Franklin County"
"05049" "Fulton County"
"05051" "Garland County"
"05053" "Grant County"
"05055" "Greene County"
"05057" "Hempstead County"
"05059" "Hot Spring County"
"05061" "Howard County"
"05063" "Independence County"
"05065" "Izard County"
"05067" "Jackson County"
"05069" "Jefferson County"
"05071" "Johnson County"
"05073" "Lafayette County"
"05075" "Lawrence County"
"05077" "Lee County"
"05079" "Lincoln County"
"05081" "Little River County"
"05083" "Logan County"
"05085" "Lonoke County"
"05087" "Madison County"
"05089" "Marion County"
"05091" "Miller County"
"05093" "Mississippi County"
"05095" "Monroe County"
"05097" "Montgomery County"
"05099" "Nevada County"
"05101" "Newton County"
"05103" "Ouachita County"
"05105" "Perry County"
"05107" "Phillips County"
"05109" "Pike County"
"05111" "Poinsett County"
"05113" "Polk County"
"05115" "Pope County"
"05117" "Prairie County"
"05119" "Pulaski County"
"05121" "Randolph County"
"05123" "St. Francis County"
"05125" "Saline County"
"05127" "Scott County"
"05129" "Searcy County"
"05131" "Sebastian County"
"05133" "Sevier County"
"05135" "Sharp County"
"05137" "Stone County"
"05139" "Union County"
"05141" "Van Buren County"
"05143" "Washington County"
"05145" "White County"
"05147" "Woodruff County"
"05149" "Yell County"
"06" "California"
"06001" "Alameda County"
"06003" "Alpine County"
"06005" "Amador County"
"06007" "Butte County"
"06009" "Calaveras County"
"06011" "Colusa County"
"06013" "Contra Costa County"
"06015" "Del Norte County"
"06017" "El Dorado County"
"06019" "Fresno County"
"06021" "Glenn County"
"06023" "Humboldt County"
"06025" "Imperial County"
"06027" "Inyo County"
"06029" "Kern County"
"06031" "Kings County"
"06033" "Lake County"
"06035" "Lassen County"
"06037" "Los Angeles County"
"06039" "Madera County"
"06041" "Marin County"
"06043" "Mariposa County"
"06045" "Mendocino County"
"06047" "Merced County"
"06049" "Modoc County"
"06051" "Mono County"
"06053" "Monterey County"
"06055" "Napa County"
"06057" "Nevada County"
"06059" "Orange County"
"06061" "Placer County"
"06063" "Plumas County"
"06065" "Riverside County"
"06067" "Sacramento County"
"06069" "San Benito County"
"06071" "San Bernardino County"
"06073" "San Diego County"
"06075" "San Francisco County"
"06077" "San Joaquin County"
"06079" "San Luis Obispo County"
"06081" "San Mateo County"
"06083" "Santa Barbara County"
"06085" "Santa Clara County"
"06087" "Santa Cruz County"
"06089" "Shasta County"
"06091" "Sierra County"
"06093" "Siskiyou County"
"06095" "Solano County"
"06097" "Sonoma County"
"06099" "Stanislaus County"
"06101" "Sutter County"
"06103" "Tehama County"
"06105" "Trinity County"
"06107" "Tulare County"
"06109" "Tuolumne County"
"06111" "Ventura County"
"06113" "Yolo County"
"06115" "Yuba County"
"08" "Colorado"
"08001" "Adams County"
"08003" "Alamosa County"
"08005" "Arapahoe County"
"08007" "Archuleta County"
"08009" "Baca County"
"08011" "Bent County"
"08013" "Boulder County"
"08014" "Broomfield County"
"08015" "Chaffee County"
"08017" "Cheyenne County"
"08019" "Clear Creek County"
"08021" "Conejos County"
"08023" "Costilla County"
"08025" "Crowley County"
"08027" "Custer County"
"08029" "Delta County"
"08031" "Denver County"
"08033" "Dolores County"
"08035" "Douglas County"
"08037" "Eagle County"
"08039" "Elbert County"
"08041" "El Paso County"
"08043" "Fremont County"
"08045" "Garfield County"
"08047" "Gilpin County"
"08049" "Grand County"
"08051" "Gunnison County"
"08053" "Hinsdale County"
"08055" "Huerfano County"
"08057" "Jackson County"
"08059" "Jefferson County"
"08061" "Kiowa County"
"08063" "<NAME> County"
"08065" "Lake County"
"08067" "La Plata County"
"08069" "Larimer County"
"08071" "Las Animas County"
"08073" "Lincoln County"
"08075" "Logan County"
"08077" "Mesa County"
"08079" "Mineral County"
"08081" "Moffat County"
"08083" "Montezuma County"
"08085" "Montrose County"
"08087" "Morgan County"
"08089" "Otero County"
"08091" "Ouray County"
"08093" "Park County"
"08095" "Phillips County"
"08097" "Pitkin County"
"08099" "Prowers County"
"08101" "Pueblo County"
"08103" "Rio Blanco County"
"08105" "Rio Grande County"
"08107" "Routt County"
"08109" "Saguache County"
"08111" "San Juan County"
"08113" "San Miguel County"
"08115" "Sedgwick County"
"08117" "Summit County"
"08119" "Teller County"
"08121" "Washington County"
"08123" "Weld County"
"08125" "Yuma County"
"09" "Connecticut"
"09001" "Fairfield County"
"09003" "Hartford County"
"09005" "Litchfield County"
"09007" "Middlesex County"
"09009" "New Haven County"
"09011" "New London County"
"09013" "Tolland County"
"09015" "Windham County"
"10" "Delaware"
"10001" "Kent County"
"10003" "New Castle County"
"10005" "Sussex County"
"11" "District of Columbia"
"11001" "District of Columbia"
"12" "Florida"
"12001" "Alachua County"
"12003" "Baker County"
"12005" "Bay County"
"12007" "Bradford County"
"12009" "Brevard County"
"12011" "Broward County"
"12013" "Calhoun County"
"12015" "Charlotte County"
"12017" "Citrus County"
"12019" "Clay County"
"12021" "Collier County"
"12023" "Columbia County"
"12027" "DeSoto County"
"12029" "Dixie County"
"12031" "Duval County"
"12033" "Escambia County"
"12035" "Flagler County"
"12037" "Franklin County"
"12039" "Gadsden County"
"12041" "Gilchrist County"
"12043" "Glades County"
"12045" "Gulf County"
"12047" "Hamilton County"
"12049" "Hardee County"
"12051" "Hendry County"
"12053" "Hernando County"
"12055" "Highlands County"
"12057" "Hillsborough County"
"12059" "Holmes County"
"12061" "Indian River County"
"12063" "Jackson County"
"12065" "Jefferson County"
"12067" "Lafayette County"
"12069" "Lake County"
"12071" "Lee County"
"12073" "Leon County"
"12075" "Levy County"
"12077" "Liberty County"
"12079" "Madison County"
"12081" "Manatee County"
"12083" "Marion County"
"12085" "Martin County"
"12086" "Miami-Dade County"
"12087" "Monroe County"
"12089" "Nassau County"
"12091" "Okaloosa County"
"12093" "Okeechobee County"
"12095" "Orange County"
"12097" "Osceola County"
"12099" "Palm Beach County"
"12101" "Pasco County"
"12103" "Pinellas County"
"12105" "Polk County"
"12107" "Putnam County"
"12109" "St. Johns County"
"12111" "St. Lucie County"
"12113" "Santa Rosa County"
"12115" "Sarasota County"
"12117" "Seminole County"
"12119" "Sumter County"
"12121" "Suwannee County"
"12123" "Taylor County"
"12125" "Union County"
"12127" "Volusia County"
"12129" "Wakulla County"
"12131" "Walton County"
"12133" "Washington County"
"13" "Georgia"
"13001" "Appling County"
"13003" "Atkinson County"
"13005" "Bacon County"
"13007" "Baker County"
"13009" "Baldwin County"
"13011" "Banks County"
"13013" "Barrow County"
"13015" "Bartow County"
"13017" "Ben Hill County"
"13019" "Berrien County"
"13021" "Bibb County"
"13023" "Bleckley County"
"13025" "Brantley County"
"13027" "Brooks County"
"13029" "Bryan County"
"13031" "Bulloch County"
"13033" "Burke County"
"13035" "Butts County"
"13037" "Calhoun County"
"13039" "Camden County"
"13043" "Candler County"
"13045" "Carroll County"
"13047" "Catoosa County"
"13049" "Charlton County"
"13051" "Chatham County"
"13053" "Chattahoochee County"
"13055" "Chattooga County"
"13057" "Cherokee County"
"13059" "Clarke County"
"13061" "Clay County"
"13063" "Clayton County"
"13065" "Clinch County"
"13067" "Cobb County"
"13069" "Coffee County"
"13071" "Colquitt County"
"13073" "Columbia County"
"13075" "Cook County"
"13077" "Coweta County"
"13079" "Crawford County"
"13081" "Crisp County"
"13083" "Dade County"
"13085" "Dawson County"
"13087" "Decatur County"
"13089" "DeKalb County"
"13091" "Dodge County"
"13093" "Dooly County"
"13095" "Dougherty County"
"13097" "Douglas County"
"13099" "Early County"
"13101" "Echols County"
"13103" "Effingham County"
"13105" "Elbert County"
"13107" "Emanuel County"
"13109" "Evans County"
"13111" "Fannin County"
"13113" "Fayette County"
"13115" "Floyd County"
"13117" "<NAME>th County"
"13119" "Franklin County"
"13121" "Fulton County"
"13123" "<NAME>ilmer County"
"13125" "<NAME>cock County"
"13127" "<NAME> County"
"13129" "<NAME> County"
"13131" "Grady County"
"13133" "Greene County"
"13135" "Gwinnett County"
"13137" "Habersham County"
"13139" "Hall County"
"13141" "Hancock County"
"13143" "<NAME>son County"
"13145" "Harris County"
"13147" "Hart County"
"13149" "Heard County"
"13151" "Henry County"
"13153" "Houston County"
"13155" "Irwin County"
"13157" "<NAME>son County"
"13159" "J<NAME> County"
"13161" "<NAME> County"
"13163" "<NAME> County"
"13165" "<NAME>enkins County"
"13167" "Johnson County"
"13169" "Jones County"
"13171" "Lamar County"
"13173" "Lanier County"
"13175" "Laurens County"
"13177" "Lee County"
"13179" "Liberty County"
"13181" "Lincoln County"
"13183" "Long County"
"13185" "Lowndes County"
"13187" "Lumpkin County"
"13189" "McDuffie County"
"13191" "McIntosh County"
"13193" "Macon County"
"13195" "Madison County"
"13197" "Marion County"
"13199" "Meriwether County"
"13201" "Miller County"
"13205" "Mitchell County"
"13207" "Monroe County"
"13209" "Montgomery County"
"13211" "Morgan County"
"13213" "Murray County"
"13215" "Muscogee County"
"13217" "Newton County"
"13219" "Oconee County"
"13221" "Oglethorpe County"
"13223" "Paulding County"
"13225" "Peach County"
"13227" "Pickens County"
"13229" "Pierce County"
"13231" "Pike County"
"13233" "Polk County"
"13235" "Pulaski County"
"13237" "Putnam County"
"13239" "Quitman County"
"13241" "Rabun County"
"13243" "Randolph County"
"13245" "Richmond County"
"13247" "Rockdale County"
"13249" "Schley County"
"13251" "Screven County"
"13253" "Seminole County"
"13255" "Spalding County"
"13257" "Stephens County"
"13259" "Stewart County"
"13261" "Sumter County"
"13263" "Talbot County"
"13265" "Taliaferro County"
"13267" "Tattnall County"
"13269" "Taylor County"
"13271" "Telfair County"
"13273" "Terrell County"
"13275" "Thomas County"
"13277" "Tift County"
"13279" "Toombs County"
"13281" "Towns County"
"13283" "Treutlen County"
"13285" "Troup County"
"13287" "Turner County"
"13289" "Twiggs County"
"13291" "Union County"
"13293" "Upson County"
"13295" "Walker County"
"13297" "Walton County"
"13299" "Ware County"
"13301" "Warren County"
"13303" "Washington County"
"13305" "Wayne County"
"13307" "Webster County"
"13309" "Wheeler County"
"13311" "White County"
"13313" "Whitfield County"
"13315" "Wilcox County"
"13317" "Wilkes County"
"13319" "Wilkinson County"
"13321" "Worth County"
"15" "Hawaii"
"15001" "Hawaii County"
"15003" "Honolulu County"
"15005" "Kalawao County"
"15007" "Kauai County"
"15009" "Maui County"
"16" "Idaho"
"16001" "Ada County"
"16003" "Adams County"
"16005" "Bannock County"
"16007" "Bear Lake County"
"16009" "Benewah County"
"16011" "Bingham County"
"16013" "Blaine County"
"16015" "Boise County"
"16017" "Bonner County"
"16019" "Bonneville County"
"16021" "Boundary County"
"16023" "Butte County"
"16025" "Camas County"
"16027" "Canyon County"
"16029" "Caribou County"
"16031" "Cassia County"
"16033" "Clark County"
"16035" "Clearwater County"
"16037" "Custer County"
"16039" "Elmore County"
"16041" "Franklin County"
"16043" "Fremont County"
"16045" "Gem County"
"16047" "Gooding County"
"16049" "Idaho County"
"16051" "Jefferson County"
"16053" "Jerome County"
"16055" "Kootenai County"
"16057" "Latah County"
"16059" "Lemhi County"
"16061" "Lewis County"
"16063" "Lincoln County"
"16065" "Madison County"
"16067" "Minidoka County"
"16069" "Nez Perce County"
"16071" "Oneida County"
"16073" "Owyhee County"
"16075" "Payette County"
"16077" "Power County"
"16079" "Shoshone County"
"16081" "Teton County"
"16083" "T<NAME> Falls County"
"16085" "Valley County"
"16087" "Washington County"
"17" "Illinois"
"17001" "Adams County"
"17003" "Alexander County"
"17005" "Bond County"
"17007" "Boone County"
"17009" "Brown County"
"17011" "Bureau County"
"17013" "Calhoun County"
"17015" "Carroll County"
"17017" "Cass County"
"17019" "Champaign County"
"17021" "Christian County"
"17023" "Clark County"
"17025" "Clay County"
"17027" "Clinton County"
"17029" "Coles County"
"17031" "Cook County"
"17033" "Crawford County"
"17035" "Cumberland County"
"17037" "DeKalb County"
"17039" "De Witt County"
"17041" "Douglas County"
"17043" "DuPage County"
"17045" "Edgar County"
"17047" "Edwards County"
"17049" "Effingham County"
"17051" "Fayette County"
"17053" "Ford County"
"17055" "Franklin County"
"17057" "Fulton County"
"17059" "Gallatin County"
"17061" "Greene County"
"17063" "Grundy County"
"17065" "Hamilton County"
"17067" "Hancock County"
"17069" "Hardin County"
"17071" "Henderson County"
"17073" "Henry County"
"17075" "Iroquois County"
"17077" "<NAME>son County"
"17079" "Jasper County"
"17081" "<NAME>erson County"
"17083" "Jersey County"
"17085" "<NAME> County"
"17087" "<NAME>son County"
"17089" "Kane County"
"17091" "Kankakee County"
"17093" "Kendall County"
"17095" "Knox County"
"17097" "Lake County"
"17099" "LaSalle County"
"17101" "Lawrence County"
"17103" "Lee County"
"17105" "Livingston County"
"17107" "Logan County"
"17109" "McDonough County"
"17111" "McHenry County"
"17113" "McLean County"
"17115" "Macon County"
"17117" "Macoupin County"
"17119" "Madison County"
"17121" "Marion County"
"17123" "Marshall County"
"17125" "Mason County"
"17127" "Massac County"
"17129" "Menard County"
"17131" "Mercer County"
"17133" "Monroe County"
"17135" "Montgomery County"
"17137" "Morgan County"
"17139" "Moultrie County"
"17141" "Ogle County"
"17143" "Peoria County"
"17145" "Perry County"
"17147" "Piatt County"
"17149" "Pike County"
"17151" "Pope County"
"17153" "Pulaski County"
"17155" "Putnam County"
"17157" "Randolph County"
"17159" "Richland County"
"17161" "Rock Island County"
"17163" "St. Clair County"
"17165" "Saline County"
"17167" "Sangamon County"
"17169" "Schuyler County"
"17171" "Scott County"
"17173" "Shelby County"
"17175" "Stark County"
"17177" "Stephenson County"
"17179" "Tazewell County"
"17181" "Union County"
"17183" "Vermilion County"
"17185" "Wabash County"
"17187" "Warren County"
"17189" "Washington County"
"17191" "Wayne County"
"17193" "White County"
"17195" "Whiteside County"
"17197" "Will County"
"17199" "Williamson County"
"17201" "Winnebago County"
"17203" "Woodford County"
"18" "Indiana"
"18001" "Adams County"
"18003" "Allen County"
"18005" "Bartholomew County"
"18007" "Benton County"
"18009" "Blackford County"
"18011" "Boone County"
"18013" "Brown County"
"18015" "Carroll County"
"18017" "Cass County"
"18019" "Clark County"
"18021" "Clay County"
"18023" "Clinton County"
"18025" "Crawford County"
"18027" "Daviess County"
"18029" "Dearborn County"
"18031" "Decatur County"
"18033" "DeKalb County"
"18035" "Delaware County"
"18037" "Dubois County"
"18039" "Elkhart County"
"18041" "Fayette County"
"18043" "Floyd County"
"18045" "Fountain County"
"18047" "Franklin County"
"18049" "Fulton County"
"18051" "Gibson County"
"18053" "Grant County"
"18055" "Greene County"
"18057" "Hamilton County"
"18059" "Hancock County"
"18061" "Harrison County"
"18063" "Hendricks County"
"18065" "Henry County"
"18067" "Howard County"
"18069" "Huntington County"
"18071" "<NAME> County"
"18073" "Jasper County"
"18075" "Jay County"
"18077" "<NAME>efferson County"
"18079" "Jennings County"
"18081" "Johnson County"
"18083" "Knox County"
"18085" "Kosciusko County"
"18087" "LaGrange County"
"18089" "Lake County"
"18091" "LaPorte County"
"18093" "Lawrence County"
"18095" "Madison County"
"18097" "Marion County"
"18099" "Marshall County"
"18101" "<NAME>in County"
"18103" "Miami County"
"18105" "Monroe County"
"18107" "Montgomery County"
"18109" "Morgan County"
"18111" "Newton County"
"18113" "Noble County"
"18115" "Ohio County"
"18117" "Orange County"
"18119" "Owen County"
"18121" "Parke County"
"18123" "Perry County"
"18125" "Pike County"
"18127" "Porter County"
"18129" "Posey County"
"18131" "Pulaski County"
"18133" "Putnam County"
"18135" "Randolph County"
"18137" "Ripley County"
"18139" "Rush County"
"18141" "St. Joseph County"
"18143" "<NAME>cott County"
"18145" "Shelby County"
"18147" "Spencer County"
"18149" "Starke County"
"18151" "Steuben County"
"18153" "Sullivan County"
"18155" "Switzerland County"
"18157" "Tippecanoe County"
"18159" "Tipton County"
"18161" "Union County"
"18163" "Vanderburgh County"
"18165" "Vermillion County"
"18167" "Vigo County"
"18169" "Wabash County"
"18171" "Warren County"
"18173" "Warrick County"
"18175" "Washington County"
"18177" "Wayne County"
"18179" "Wells County"
"18181" "White County"
"18183" "Whitley County"
"19" "Iowa"
"19001" "Adair County"
"19003" "Adams County"
"19005" "Allamakee County"
"19007" "Appanoose County"
"19009" "Audubon County"
"19011" "Benton County"
"19013" "Black Hawk County"
"19015" "Boone County"
"19017" "Bremer County"
"19019" "Buchanan County"
"19021" "Buena Vista County"
"19023" "Butler County"
"19025" "Calhoun County"
"19027" "Carroll County"
"19029" "Cass County"
"19031" "Cedar County"
"19033" "Cerro Gordo County"
"19035" "Cherokee County"
"19037" "Chickasaw County"
"19039" "Clarke County"
"19041" "Clay County"
"19043" "Clayton County"
"19045" "Clinton County"
"19047" "Crawford County"
"19049" "Dallas County"
"19051" "Davis County"
"19053" "Decatur County"
"19055" "Delaware County"
"19057" "Des Moines County"
"19059" "Dickinson County"
"19061" "Dubuque County"
"19063" "Emmet County"
"19065" "Fayette County"
"19067" "Floyd County"
"19069" "Franklin County"
"19071" "Fremont County"
"19073" "Greene County"
"19075" "Grundy County"
"19077" "Guthrie County"
"19079" "Hamilton County"
"19081" "Hancock County"
"19083" "Hardin County"
"19085" "Harrison County"
"19087" "Henry County"
"19089" "Howard County"
"19091" "Humboldt County"
"19093" "Ida County"
"19095" "Iowa County"
"19097" "<NAME>son County"
"19099" "Jasper County"
"19101" "<NAME>efferson County"
"19103" "<NAME>son County"
"19105" "Jones County"
"19107" "Keokuk County"
"19109" "Kossuth County"
"19111" "Lee County"
"19113" "Linn County"
"19115" "Louisa County"
"19117" "Lucas County"
"19119" "Lyon County"
"19121" "Madison County"
"19123" "Mahaska County"
"19125" "Marion County"
"19127" "Marshall County"
"19129" "Mills County"
"19131" "Mitchell County"
"19133" "Monona County"
"19135" "Monroe County"
"19137" "Montgomery County"
"19139" "Muscatine County"
"19141" "O'Brien County"
"19143" "Osceola County"
"19145" "Page County"
"19147" "Palo Alto County"
"19149" "Plymouth County"
"19151" "Pocahontas County"
"19153" "Polk County"
"19155" "Pottawattamie County"
"19157" "Poweshiek County"
"19159" "Ringgold County"
"19161" "Sac County"
"19163" "Scott County"
"19165" "Shelby County"
"19167" "Sioux County"
"19169" "Story County"
"19171" "Tama County"
"19173" "Taylor County"
"19175" "Union County"
"19177" "<NAME> Buren County"
"19179" "Wapello County"
"19181" "Warren County"
"19183" "Washington County"
"19185" "Wayne County"
"19187" "Webster County"
"19189" "Winnebago County"
"19191" "Winneshiek County"
"19193" "Woodbury County"
"19195" "Worth County"
"19197" "Wright County"
"20" "Kansas"
"20001" "Allen County"
"20003" "Anderson County"
"20005" "Atchison County"
"20007" "Barber County"
"20009" "Barton County"
"20011" "Bourbon County"
"20013" "Brown County"
"20015" "Butler County"
"20017" "Chase County"
"20019" "Chautauqua County"
"20021" "Cherokee County"
"20023" "Cheyenne County"
"20025" "Clark County"
"20027" "Clay County"
"20029" "Cloud County"
"20031" "Coffey County"
"20033" "Comanche County"
"20035" "Cowley County"
"20037" "Crawford County"
"20039" "Decatur County"
"20041" "Dickinson County"
"20043" "Doniphan County"
"20045" "Douglas County"
"20047" "Edwards County"
"20049" "Elk County"
"20051" "Ellis County"
"20053" "Ellsworth County"
"20055" "Finney County"
"20057" "Ford County"
"20059" "Franklin County"
"20061" "Geary County"
"20063" "Gove County"
"20065" "Graham County"
"20067" "Grant County"
"20069" "Gray County"
"20071" "Greeley County"
"20073" "Greenwood County"
"20075" "Hamilton County"
"20077" "Harper County"
"20079" "Harvey County"
"20081" "Haskell County"
"20083" "Hodgeman County"
"20085" "<NAME>son County"
"20087" "Jefferson County"
"20089" "Jewell County"
"20091" "<NAME>son County"
"20093" "Kearny County"
"20095" "Kingman County"
"20097" "Kiowa County"
"20099" "Labette County"
"20101" "Lane County"
"20103" "Leavenworth County"
"20105" "Lincoln County"
"20107" "Linn County"
"20109" "Logan County"
"20111" "Lyon County"
"20113" "McPherson County"
"20115" "Marion County"
"20117" "Marshall County"
"20119" "Meade County"
"20121" "Miami County"
"20123" "Mitchell County"
"20125" "Montgomery County"
"20127" "Morris County"
"20129" "Morton County"
"20131" "Nemaha County"
"20133" "Neosho County"
"20135" "Ness County"
"20137" "Norton County"
"20139" "Osage County"
"20141" "Osborne County"
"20143" "Ottawa County"
"20145" "Pawnee County"
"20147" "Phillips County"
"20149" "Pottawatomie County"
"20151" "Pratt County"
"20153" "Rawlins County"
"20155" "Reno County"
"20157" "Republic County"
"20159" "Rice County"
"20161" "Riley County"
"20163" "Rooks County"
"20165" "Rush County"
"20167" "Russell County"
"20169" "Saline County"
"20171" "Scott County"
"20173" "Sedgwick County"
"20175" "Seward County"
"20177" "Shawnee County"
"20179" "Sheridan County"
"20181" "Sherman County"
"20183" "Smith County"
"20185" "Stafford County"
"20187" "Stanton County"
"20189" "Stevens County"
"20191" "Sumner County"
"20193" "Thomas County"
"20195" "Trego County"
"20197" "Wabaunsee County"
"20199" "Wallace County"
"20201" "Washington County"
"20203" "Wichita County"
"20205" "Wilson County"
"20207" "Woodson County"
"20209" "Wyandotte County"
"21" "Kentucky"
"21001" "Adair County"
"21003" "Allen County"
"21005" "Anderson County"
"21007" "Ballard County"
"21009" "Barren County"
"21011" "Bath County"
"21013" "Bell County"
"21015" "Boone County"
"21017" "Bourbon County"
"21019" "Boyd County"
"21021" "Boyle County"
"21023" "Bracken County"
"21025" "Breathitt County"
"21027" "Breckinridge County"
"21029" "Bullitt County"
"21031" "Butler County"
"21033" "Caldwell County"
"21035" "Calloway County"
"21037" "Campbell County"
"21039" "Carlisle County"
"21041" "Carroll County"
"21043" "Carter County"
"21045" "Casey County"
"21047" "Christian County"
"21049" "Clark County"
"21051" "Clay County"
"21053" "Clinton County"
"21055" "Crittenden County"
"21057" "Cumberland County"
"21059" "Daviess County"
"21061" "Edmonson County"
"21063" "Elliott County"
"21065" "Estill County"
"21067" "Fayette County"
"21069" "Fleming County"
"21071" "Floyd County"
"21073" "Franklin County"
"21075" "Fulton County"
"21077" "Gallatin County"
"21079" "Garrard County"
"21081" "Grant County"
"21083" "Graves County"
"21085" "Grayson County"
"21087" "Green County"
"21089" "Greenup County"
"21091" "Hancock County"
"21093" "Hardin County"
"21095" "Harlan County"
"21097" "Harrison County"
"21099" "Hart County"
"21101" "Henderson County"
"21103" "Henry County"
"21105" "Hickman County"
"21107" "Hopkins County"
"21109" "<NAME>son County"
"21111" "<NAME>erson County"
"21113" "Jessamine County"
"21115" "<NAME>son County"
"21117" "Kenton County"
"21119" "Knott County"
"21121" "Knox County"
"21123" "Larue County"
"21125" "Laurel County"
"21127" "Lawrence County"
"21129" "Lee County"
"21131" "Leslie County"
"21133" "Letcher County"
"21135" "Lewis County"
"21137" "Lincoln County"
"21139" "Livingston County"
"21141" "Logan County"
"21143" "Lyon County"
"21145" "McCracken County"
"21147" "McCreary County"
"21149" "McLean County"
"21151" "Madison County"
"21153" "Magoffin County"
"21155" "Marion County"
"21157" "Marshall County"
"21159" "Martin County"
"21161" "Mason County"
"21163" "Meade County"
"21165" "Menifee County"
"21167" "Mercer County"
"21169" "Metcalfe County"
"21171" "Monroe County"
"21173" "Montgomery County"
"21175" "Morgan County"
"21177" "Muhlenberg County"
"21179" "<NAME>elson County"
"21181" "Nicholas County"
"21183" "Ohio County"
"21185" "Oldham County"
"21187" "Owen County"
"21189" "Owsley County"
"21191" "Pendleton County"
"21193" "Perry County"
"21195" "Pike County"
"21197" "Powell County"
"21199" "Pulaski County"
"21201" "<NAME> County"
"21203" "Rockcastle County"
"21205" "Rowan County"
"21207" "<NAME>ussell County"
"21209" "S<NAME> County"
"21211" "Shelby County"
"21213" "<NAME> County"
"21215" "<NAME>cer County"
"21217" "Taylor County"
"21219" "<NAME> County"
"21221" "Trigg County"
"21223" "Trimble County"
"21225" "Union County"
"21227" "Warren County"
"21229" "Washington County"
"21231" "Wayne County"
"21233" "Webster County"
"21235" "Whitley County"
"21237" "Wolfe County"
"21239" "Woodford County"
"22" "Louisiana"
"22001" "Acadia Parish"
"22003" "Allen Parish"
"22005" "Ascension Parish"
"22007" "Assumption Parish"
"22009" "Avoyelles Parish"
"22011" "Beauregard Parish"
"22013" "Bienville Parish"
"22015" "Bossier Parish"
"22017" "Caddo Parish"
"22019" "<NAME> Parish"
"22021" "Caldwell Parish"
"22023" "<NAME> Parish"
"22025" "Catahoula Parish"
"22027" "Claiborne Parish"
"22029" "Concordia Parish"
"22031" "De Soto Parish"
"22033" "East Baton Rouge Parish"
"22035" "East Carroll Parish"
"22037" "East Feliciana Parish"
"22039" "Evangeline Parish"
"22041" "Franklin Parish"
"22043" "Grant Parish"
"22045" "Iberia Parish"
"22047" "Iberville Parish"
"22049" "<NAME> Parish"
"22051" "<NAME> Parish"
"22053" "<NAME>"
"22055" "Lafayette Parish"
"22057" "Lafourche Parish"
"22059" "LaSalle Parish"
"22061" "<NAME>"
"22063" "Livingston Parish"
"22065" "Madison Parish"
"22067" "Morehouse Parish"
"22069" "Natchitoches Parish"
"22071" "Orleans Parish"
"22073" "Ouachita Parish"
"22075" "Plaquemines Parish"
"22077" "Pointe Coupee Parish"
"22079" "Rapides Parish"
"22081" "Red River Parish"
"22083" "Richland Parish"
"22085" "Sabine Parish"
"22087" "St. Bernard Parish"
"22089" "St. Charles Parish"
"22091" "St. Helena Parish"
"22093" "St. James Parish"
"22095" "St. John the Baptist Parish"
"22097" "St. Landry Parish"
"22099" "St. Martin Parish"
"22101" "St. Mary Parish"
"22103" "St. Tammany Parish"
"22105" "Tangipahoa Parish"
"22107" "Tensas Parish"
"22109" "Terrebonne Parish"
"22111" "Union Parish"
"22113" "Vermilion Parish"
"22115" "Vernon Parish"
"22117" "Washington Parish"
"22119" "Webster Parish"
"22121" "West Baton Rouge Parish"
"22123" "West Carroll Parish"
"22125" "West Feliciana Parish"
"22127" "Winn Parish"
"23" "Maine"
"23001" "Androscoggin County"
"23003" "Aroostook County"
"23005" "Cumberland County"
"23007" "Franklin County"
"23009" "Hancock County"
"23011" "Kennebec County"
"23013" "Knox County"
"23015" "Lincoln County"
"23017" "Oxford County"
"23019" "Penobscot County"
"23021" "Piscataquis County"
"23023" "Sagadahoc County"
"23025" "Somerset County"
"23027" "Waldo County"
"23029" "Washington County"
"23031" "York County"
"24" "Maryland"
"24001" "Allegany County"
"24003" "Anne Arundel County"
"24005" "Baltimore County"
"24009" "Calvert County"
"24011" "Caroline County"
"24013" "Carroll County"
"24015" "Cecil County"
"24017" "Charles County"
"24019" "Dorchester County"
"24021" "Frederick County"
"24023" "Garrett County"
"24025" "Harford County"
"24027" "Howard County"
"24029" "Kent County"
"24031" "Montgomery County"
"24033" "Prince George's County"
"24035" "Queen Anne's County"
"24037" "St. Mary's County"
"24039" "Somerset County"
"24041" "Talbot County"
"24043" "Washington County"
"24045" "Wicomico County"
"24047" "Worcester County"
"24510" "Baltimore city"
"25" "Massachusetts"
"25001" "Barnstable County"
"25003" "Berkshire County"
"25005" "Bristol County"
"25007" "Dukes County"
"25009" "Essex County"
"25011" "Franklin County"
"25013" "Hampden County"
"25015" "Hampshire County"
"25017" "Middlesex County"
"25019" "Nantucket County"
"25021" "Norfolk County"
"25023" "Plymouth County"
"25025" "Suffolk County"
"25027" "Worcester County"
"26" "Michigan"
"26001" "Alcona County"
"26003" "Alger County"
"26005" "Allegan County"
"26007" "Alpena County"
"26009" "Antrim County"
"26011" "Arenac County"
"26013" "Baraga County"
"26015" "Barry County"
"26017" "Bay County"
"26019" "Benzie County"
"26021" "Berrien County"
"26023" "Branch County"
"26025" "Calhoun County"
"26027" "Cass County"
"26029" "Charlevoix County"
"26031" "Cheboygan County"
"26033" "Chippewa County"
"26035" "Clare County"
"26037" "Clinton County"
"26039" "Crawford County"
"26041" "Delta County"
"26043" "Dickinson County"
"26045" "Eaton County"
"26047" "Emmet County"
"26049" "Genesee County"
"26051" "Gladwin County"
"26053" "Gogebic County"
"26055" "Grand Traverse County"
"26057" "Gratiot County"
"26059" "Hillsdale County"
"26061" "Houghton County"
"26063" "Huron County"
"26065" "Ingham County"
"26067" "Ionia County"
"26069" "Iosco County"
"26071" "Iron County"
"26073" "Isabella County"
"26075" "Jackson County"
"26077" "Kalamazoo County"
"26079" "Kalkaska County"
"26081" "Kent County"
"26083" "Keweenaw County"
"26085" "Lake County"
"26087" "Lapeer County"
"26089" "Leelanau County"
"26091" "Lenawee County"
"26093" "Livingston County"
"26095" "Luce County"
"26097" "Mackinac County"
"26099" "Macomb County"
"26101" "Manistee County"
"26103" "Marquette County"
"26105" "Mason County"
"26107" "Mecosta County"
"26109" "Menominee County"
"26111" "Midland County"
"26113" "Missaukee County"
"26115" "Monroe County"
"26117" "Montcalm County"
"26119" "Montmorency County"
"26121" "Muskegon County"
"26123" "Newaygo County"
"26125" "Oakland County"
"26127" "Oceana County"
"26129" "Ogemaw County"
"26131" "Ontonagon County"
"26133" "Osceola County"
"26135" "Oscoda County"
"26137" "Otsego County"
"26139" "Ottawa County"
"26141" "Presque Isle County"
"26143" "Roscommon County"
"26145" "Saginaw County"
"26147" "St. Clair County"
"26149" "St. Joseph County"
"26151" "Sanilac County"
"26153" "Schoolcraft County"
"26155" "Shiawassee County"
"26157" "Tuscola County"
"26159" "Van Buren County"
"26161" "Washtenaw County"
"26163" "Wayne County"
"26165" "Wexford County"
"27" "Minnesota"
"27001" "Aitkin County"
"27003" "Anoka County"
"27005" "Becker County"
"27007" "Beltrami County"
"27009" "Benton County"
"27011" "Big Stone County"
"27013" "Blue Earth County"
"27015" "Brown County"
"27017" "Carlton County"
"27019" "Carver County"
"27021" "Cass County"
"27023" "Chippewa County"
"27025" "Chisago County"
"27027" "Clay County"
"27029" "Clearwater County"
"27031" "Cook County"
"27033" "Cottonwood County"
"27035" "Crow Wing County"
"27037" "Dakota County"
"27039" "Dodge County"
"27041" "Douglas County"
"27043" "Faribault County"
"27045" "Fillmore County"
"27047" "Freeborn County"
"27049" "Goodhue County"
"27051" "Grant County"
"27053" "Hennepin County"
"27055" "Houston County"
"27057" "Hubbard County"
"27059" "Isanti County"
"27061" "Itasca County"
"27063" "Jackson County"
"27065" "Kanabec County"
"27067" "Kandiyohi County"
"27069" "Kittson County"
"27071" "Koochiching County"
"27073" "Lac qui Parle County"
"27075" "Lake County"
"27077" "Lake of the Woods County"
"27079" "Le Sueur County"
"27081" "Lincoln County"
"27083" "Lyon County"
"27085" "McLeod County"
"27087" "Mahnomen County"
"27089" "Marshall County"
"27091" "Martin County"
"27093" "Meeker County"
"27095" "Mille Lacs County"
"27097" "Morrison County"
"27099" "Mower County"
"27101" "Murray County"
"27103" "Nicollet County"
"27105" "Nobles County"
"27107" "Norman County"
"27109" "Olmsted County"
"27111" "Otter Tail County"
"27113" "Pennington County"
"27115" "Pine County"
"27117" "Pipestone County"
"27119" "Polk County"
"27121" "Pope County"
"27123" "Ramsey County"
"27125" "Red Lake County"
"27127" "Redwood County"
"27129" "Renville County"
"27131" "Rice County"
"27133" "Rock County"
"27135" "Roseau County"
"27137" "St. Louis County"
"27139" "Scott County"
"27141" "Sherburne County"
"27143" "Sibley County"
"27145" "Stearns County"
"27147" "Steele County"
"27149" "Stevens County"
"27151" "Swift County"
"27153" "Todd County"
"27155" "Traverse County"
"27157" "Wabasha County"
"27159" "Wadena County"
"27161" "Waseca County"
"27163" "Washington County"
"27165" "Watonwan County"
"27167" "Wilkin County"
"27169" "Winona County"
"27171" "Wright County"
"27173" "Yellow Medicine County"
"28" "Mississippi"
"28001" "Adams County"
"28003" "Alcorn County"
"28005" "Amite County"
"28007" "Attala County"
"28009" "Benton County"
"28011" "Bolivar County"
"28013" "Calhoun County"
"28015" "Carroll County"
"28017" "Chickasaw County"
"28019" "Choctaw County"
"28021" "Claiborne County"
"28023" "Clarke County"
"28025" "Clay County"
"28027" "Coahoma County"
"28029" "Copiah County"
"28031" "Covington County"
"28033" "DeSoto County"
"28035" "Forrest County"
"28037" "Franklin County"
"28039" "George County"
"28041" "Greene County"
"28043" "Grenada County"
"28045" "Hancock County"
"28047" "Harrison County"
"28049" "Hinds County"
"28051" "Holmes County"
"28053" "Humphreys County"
"28055" "Issaquena County"
"28057" "Itawamba County"
"28059" "Jackson County"
"28061" "Jasper County"
"28063" "J<NAME>erson County"
"28065" "<NAME> County"
"28067" "Jones County"
"28069" "Kemper County"
"28071" "Lafayette County"
"28073" "Lamar County"
"28075" "Lauderdale County"
"28077" "Lawrence County"
"28079" "Leake County"
"28081" "Lee County"
"28083" "Leflore County"
"28085" "Lincoln County"
"28087" "Lowndes County"
"28089" "Madison County"
"28091" "Marion County"
"28093" "Marshall County"
"28095" "Monroe County"
"28097" "Montgomery County"
"28099" "Neshoba County"
"28101" "Newton County"
"28103" "Noxubee County"
"28105" "Oktibbeha County"
"28107" "Panola County"
"28109" "Pearl River County"
"28111" "Perry County"
"28113" "Pike County"
"28115" "Pontotoc County"
"28117" "Prentiss County"
"28119" "Quitman County"
"28121" "<NAME>in County"
"28123" "Scott County"
"28125" "Sharkey County"
"28127" "Simpson County"
"28129" "Smith County"
"28131" "Stone County"
"28133" "Sunflower County"
"28135" "Tallahatchie County"
"28137" "Tate County"
"28139" "Tippah County"
"28141" "Tishomingo County"
"28143" "Tunica County"
"28145" "Union County"
"28147" "Walthall County"
"28149" "Warren County"
"28151" "Washington County"
"28153" "Wayne County"
"28155" "Webster County"
"28157" "Wilkinson County"
"28159" "Winston County"
"28161" "Yalobusha County"
"28163" "Yazoo County"
"29" "Missouri"
"29001" "Adair County"
"29003" "Andrew County"
"29005" "Atchison County"
"29007" "Audrain County"
"29009" "Barry County"
"29011" "Barton County"
"29013" "Bates County"
"29015" "Benton County"
"29017" "Bollinger County"
"29019" "Boone County"
"29021" "Buchanan County"
"29023" "Butler County"
"29025" "Caldwell County"
"29027" "Callaway County"
"29029" "Camden County"
"29031" "Cape Girardeau County"
"29033" "Carroll County"
"29035" "Carter County"
"29037" "Cass County"
"29039" "Cedar County"
"29041" "Chariton County"
"29043" "Christian County"
"29045" "Clark County"
"29047" "Clay County"
"29049" "Clinton County"
"29051" "Cole County"
"29053" "Cooper County"
"29055" "Crawford County"
"29057" "Dade County"
"29059" "Dallas County"
"29061" "<NAME> County"
"29063" "<NAME> County"
"29065" "Dent County"
"29067" "Douglas County"
"29069" "Dunklin County"
"29071" "<NAME>anklin County"
"29073" "Gasconade County"
"29075" "Gentry County"
"29077" "Greene County"
"29079" "Grundy County"
"29081" "Harrison County"
"29083" "Henry County"
"29085" "Hickory County"
"29087" "Holt County"
"29089" "Howard County"
"29091" "Howell County"
"29093" "Iron County"
"29095" "<NAME>son County"
"29097" "Jasper County"
"29099" "<NAME>erson County"
"29101" "<NAME>son County"
"29103" "<NAME> County"
"29105" "Laclede County"
"29107" "Lafayette County"
"29109" "Lawrence County"
"29111" "Lewis County"
"29113" "Lincoln County"
"29115" "Linn County"
"29117" "Livingston County"
"29119" "McDonald County"
"29121" "Macon County"
"29123" "Madison County"
"29125" "Maries County"
"29127" "Marion County"
"29129" "Mercer County"
"29131" "Miller County"
"29133" "Mississippi County"
"29135" "Moniteau County"
"29137" "Monroe County"
"29139" "Montgomery County"
"29141" "Morgan County"
"29143" "New Madrid County"
"29145" "Newton County"
"29147" "Nodaway County"
"29149" "Oregon County"
"29151" "Osage County"
"29153" "Ozark County"
"29155" "Pemiscot County"
"29157" "Perry County"
"29159" "Pettis County"
"29161" "Phelps County"
"29163" "Pike County"
"29165" "Platte County"
"29167" "Polk County"
"29169" "Pulaski County"
"29171" "Putnam County"
"29173" "Ralls County"
"29175" "Randolph County"
"29177" "Ray County"
"29179" "Reynolds County"
"29181" "Ripley County"
"29183" "St. Charles County"
"29185" "St. Clair County"
"29186" "Ste. Genevieve County"
"29187" "St. Francois County"
"29189" "St. Louis County"
"29195" "Saline County"
"29197" "Schuyler County"
"29199" "Scotland County"
"29201" "Scott County"
"29203" "Shannon County"
"29205" "Shelby County"
"29207" "Stoddard County"
"29209" "Stone County"
"29211" "Sullivan County"
"29213" "Taney County"
"29215" "Texas County"
"29217" "Vernon County"
"29219" "Warren County"
"29221" "Washington County"
"29223" "Wayne County"
"29225" "Webster County"
"29227" "Worth County"
"29229" "Wright County"
"29510" "St. Louis city"
"30" "Montana"
"30001" "Beaverhead County"
"30003" "Big Horn County"
"30005" "Blaine County"
"30007" "Broadwater County"
"30009" "Carbon County"
"30011" "Carter County"
"30013" "Cascade County"
"30015" "Chouteau County"
"30017" "Custer County"
"30019" "Daniels County"
"30021" "Dawson County"
"30023" "Deer Lodge County"
"30025" "Fallon County"
"30027" "Fergus County"
"30029" "Flathead County"
"30031" "Gallatin County"
"30033" "Garfield County"
"30035" "Glacier County"
"30037" "Golden Valley County"
"30039" "Granite County"
"30041" "Hill County"
"30043" "Jefferson County"
"30045" "Judith Basin County"
"30047" "Lake County"
"30049" "Lewis and Clark County"
"30051" "Liberty County"
"30053" "Lincoln County"
"30055" "McCone County"
"30057" "Madison County"
"30059" "Meagher County"
"30061" "Mineral County"
"30063" "Missoula County"
"30065" "Musselshell County"
"30067" "Park County"
"30069" "Petroleum County"
"30071" "Phillips County"
"30073" "Pondera County"
"30075" "Powder River County"
"30077" "Powell County"
"30079" "Prairie County"
"30081" "Ravalli County"
"30083" "Richland County"
"30085" "Roosevelt County"
"30087" "Rosebud County"
"30089" "Sanders County"
"30091" "Sheridan County"
"30093" "Silver Bow County"
"30095" "Stillwater County"
"30097" "Sweet Grass County"
"30099" "Teton County"
"30101" "Toole County"
"30103" "Treasure County"
"30105" "Valley County"
"30107" "Wheatland County"
"30109" "Wibaux County"
"30111" "Yellowstone County"
"31" "Nebraska"
"31001" "Adams County"
"31003" "Antelope County"
"31005" "Arthur County"
"31007" "Banner County"
"31009" "Blaine County"
"31011" "Boone County"
"31013" "Box Butte County"
"31015" "Boyd County"
"31017" "Brown County"
"31019" "Buffalo County"
"31021" "Burt County"
"31023" "Butler County"
"31025" "Cass County"
"31027" "Cedar County"
"31029" "Chase County"
"31031" "Cherry County"
"31033" "Cheyenne County"
"31035" "Clay County"
"31037" "Colfax County"
"31039" "Cuming County"
"31041" "Custer County"
"31043" "Dakota County"
"31045" "Dawes County"
"31047" "Dawson County"
"31049" "Deuel County"
"31051" "Dixon County"
"31053" "Dodge County"
"31055" "Douglas County"
"31057" "Dundy County"
"31059" "Fillmore County"
"31061" "Franklin County"
"31063" "Frontier County"
"31065" "Furnas County"
"31067" "Gage County"
"31069" "Garden County"
"31071" "Garfield County"
"31073" "Gosper County"
"31075" "Grant County"
"31077" "Greeley County"
"31079" "Hall County"
"31081" "Hamilton County"
"31083" "Harlan County"
"31085" "Hayes County"
"31087" "Hitchcock County"
"31089" "Holt County"
"31091" "Hooker County"
"31093" "Howard County"
"31095" "Jefferson County"
"31097" "Johnson County"
"31099" "Kearney County"
"31101" "Keith County"
"31103" "Keya Paha County"
"31105" "Kimball County"
"31107" "Knox County"
"31109" "Lancaster County"
"31111" "Lincoln County"
"31113" "Logan County"
"31115" "Loup County"
"31117" "McPherson County"
"31119" "Madison County"
"31121" "Merrick County"
"31123" "Morrill County"
"31125" "Nance County"
"31127" "Nemaha County"
"31129" "Nuckolls County"
"31131" "Otoe County"
"31133" "Pawnee County"
"31135" "Perkins County"
"31137" "Phelps County"
"31139" "Pierce County"
"31141" "Platte County"
"31143" "Polk County"
"31145" "Red Willow County"
"31147" "Richardson County"
"31149" "Rock County"
"31151" "Saline County"
"31153" "Sarpy County"
"31155" "Saunders County"
"31157" "Scotts Bluff County"
"31159" "Seward County"
"31161" "Sheridan County"
"31163" "Sherman County"
"31165" "Sioux County"
"31167" "Stanton County"
"31169" "Thayer County"
"31171" "Thomas County"
"31173" "Thurston County"
"31175" "Valley County"
"31177" "Washington County"
"31179" "Wayne County"
"31181" "Webster County"
"31183" "Wheeler County"
"31185" "York County"
"32" "Nevada"
"32001" "Churchill County"
"32003" "Clark County"
"32005" "Douglas County"
"32007" "Elko County"
"32009" "Esmeralda County"
"32011" "Eureka County"
"32013" "Humboldt County"
"32015" "Lander County"
"32017" "Lincoln County"
"32019" "Lyon County"
"32021" "Mineral County"
"32023" "Nye County"
"32027" "Pershing County"
"32029" "Storey County"
"32031" "Washoe County"
"32033" "White Pine County"
"32510" "Carson City"
"33" "New Hampshire"
"33001" "Belknap County"
"33003" "Carroll County"
"33005" "Cheshire County"
"33007" "Coos County"
"33009" "Grafton County"
"33011" "Hillsborough County"
"33013" "Merrimack County"
"33015" "Rockingham County"
"33017" "Strafford County"
"33019" "Sullivan County"
"34" "New Jersey"
"34001" "Atlantic County"
"34003" "Bergen County"
"34005" "Burlington County"
"34007" "Camden County"
"34009" "Cape May County"
"34011" "Cumberland County"
"34013" "Essex County"
"34015" "Gloucester County"
"34017" "Hudson County"
"34019" "Hunterdon County"
"34021" "Mercer County"
"34023" "Middlesex County"
"34025" "Monmouth County"
"34027" "Morris County"
"34029" "Ocean County"
"34031" "Passaic County"
"34033" "Salem County"
"34035" "Somerset County"
"34037" "Sussex County"
"34039" "Union County"
"34041" "Warren County"
"35" "New Mexico"
"35001" "Bernalillo County"
"35003" "Catron County"
"35005" "Chaves County"
"35006" "Cibola County"
"35007" "Colfax County"
"35009" "Curry County"
"35011" "De Baca County"
"35013" "Do\u00f1a Ana County"
"35015" "Eddy County"
"35017" "Grant County"
"35019" "Guadalupe County"
"35021" "Harding County"
"35023" "Hidalgo County"
"35025" "Lea County"
"35027" "Lincoln County"
"35028" "Los Alamos County"
"35029" "Luna County"
"35031" "McKinley County"
"35033" "Mora County"
"35035" "Otero County"
"35037" "Quay County"
"35039" "Rio Arriba County"
"35041" "Roosevelt County"
"35043" "Sandoval County"
"35045" "San Juan County"
"35047" "San Miguel County"
"35049" "Santa Fe County"
"35051" "Sierra County"
"35053" "Socorro County"
"35055" "Taos County"
"35057" "Torrance County"
"35059" "Union County"
"35061" "Valencia County"
"36" "New York"
"36001" "Albany County"
"36003" "Allegany County"
"36005" "Bronx County"
"36007" "Broome County"
"36009" "Cattaraugus County"
"36011" "Cayuga County"
"36013" "Chautauqua County"
"36015" "Chemung County"
"36017" "Chenango County"
"36019" "Clinton County"
"36021" "Columbia County"
"36023" "Cortland County"
"36025" "Delaware County"
"36027" "Dutchess County"
"36029" "Erie County"
"36031" "Essex County"
"36033" "Franklin County"
"36035" "Fulton County"
"36037" "Genesee County"
"36039" "Greene County"
"36041" "Hamilton County"
"36043" "Herkimer County"
"36045" "Jefferson County"
"36047" "Kings County"
"36049" "Lewis County"
"36051" "Livingston County"
"36053" "Madison County"
"36055" "Monroe County"
"36057" "Montgomery County"
"36059" "Nassau County"
"36061" "New York County"
"36063" "Niagara County"
"36065" "Oneida County"
"36067" "Onondaga County"
"36069" "Ontario County"
"36071" "Orange County"
"36073" "Orleans County"
"36075" "Oswego County"
"36077" "Otsego County"
"36079" "Putnam County"
"36081" "Queens County"
"36083" "Rensselaer County"
"36085" "Richmond County"
"36087" "Rockland County"
"36089" "St. Lawrence County"
"36091" "Saratoga County"
"36093" "Schenectady County"
"36095" "Schoharie County"
"36097" "Schuyler County"
"36099" "Seneca County"
"36101" "Steuben County"
"36103" "Suffolk County"
"36105" "Sullivan County"
"36107" "Tioga County"
"36109" "Tompkins County"
"36111" "Ulster County"
"36113" "Warren County"
"36115" "Washington County"
"36117" "Wayne County"
"36119" "Westchester County"
"36121" "Wyoming County"
"36123" "Yates County"
"37" "North Carolina"
"37001" "Alamance County"
"37003" "Alexander County"
"37005" "Alleghany County"
"37007" "Anson County"
"37009" "Ashe County"
"37011" "Avery County"
"37013" "Beaufort County"
"37015" "Bertie County"
"37017" "Bladen County"
"37019" "Brunswick County"
"37021" "Buncombe County"
"37023" "Burke County"
"37025" "Cabarrus County"
"37027" "Caldwell County"
"37029" "Camden County"
"37031" "Carteret County"
"37033" "Caswell County"
"37035" "Catawba County"
"37037" "Chatham County"
"37039" "Cherokee County"
"37041" "Chowan County"
"37043" "Clay County"
"37045" "Cleveland County"
"37047" "Columbus County"
"37049" "Craven County"
"37051" "Cumberland County"
"37053" "Currituck County"
"37055" "Dare County"
"37057" "Davidson County"
"37059" "Davie County"
"37061" "Duplin County"
"37063" "Durham County"
"37065" "Edgecombe County"
"37067" "Forsyth County"
"37069" "Franklin County"
"37071" "Gaston County"
"37073" "Gates County"
"37075" "Graham County"
"37077" "Granville County"
"37079" "Greene County"
"37081" "Guilford County"
"37083" "Halifax County"
"37085" "Harnett County"
"37087" "Haywood County"
"37089" "Henderson County"
"37091" "Hertford County"
"37093" "Hoke County"
"37095" "Hyde County"
"37097" "Iredell County"
"37099" "<NAME>son County"
"37101" "Johnston County"
"37103" "Jones County"
"37105" "Lee County"
"37107" "Lenoir County"
"37109" "Lincoln County"
"37111" "McDowell County"
"37113" "Macon County"
"37115" "Madison County"
"37117" "Martin County"
"37119" "Mecklenburg County"
"37121" "Mitchell County"
"37123" "Montgomery County"
"37125" "Moore County"
"37127" "Nash County"
"37129" "New Hanover County"
"37131" "Northampton County"
"37133" "Onslow County"
"37135" "Orange County"
"37137" "Pamlico County"
"37139" "Pasquotank County"
"37141" "Pender County"
"37143" "Perquimans County"
"37145" "Person County"
"37147" "Pitt County"
"37149" "Polk County"
"37151" "Randolph County"
"37153" "Richmond County"
"37155" "Robeson County"
"37157" "Rockingham County"
"37159" "Rowan County"
"37161" "Rutherford County"
"37163" "Sampson County"
"37165" "Scotland County"
"37167" "Stanly County"
"37169" "Stokes County"
"37171" "Surry County"
"37173" "Swain County"
"37175" "Transylvania County"
"37177" "Tyrrell County"
"37179" "Union County"
"37181" "Vance County"
"37183" "Wake County"
"37185" "Warren County"
"37187" "Washington County"
"37189" "Watauga County"
"37191" "Wayne County"
"37193" "Wilkes County"
"37195" "Wilson County"
"37197" "Yadkin County"
"37199" "Yancey County"
"38" "North Dakota"
"38001" "Adams County"
"38003" "Barnes County"
"38005" "Benson County"
"38007" "Billings County"
"38009" "Bottineau County"
"38011" "Bowman County"
"38013" "Burke County"
"38015" "Burleigh County"
"38017" "Cass County"
"38019" "Cavalier County"
"38021" "Dickey County"
"38023" "Divide County"
"38025" "Dunn County"
"38027" "Eddy County"
"38029" "Emmons County"
"38031" "Foster County"
"38033" "Golden Valley County"
"38035" "Grand Forks County"
"38037" "Grant County"
"38039" "Griggs County"
"38041" "Hettinger County"
"38043" "Kidder County"
"38045" "LaMoure County"
"38047" "Logan County"
"38049" "McHenry County"
"38051" "McIntosh County"
"38053" "McKenzie County"
"38055" "McLean County"
"38057" "Mercer County"
"38059" "Morton County"
"38061" "Mountrail County"
"38063" "Nelson County"
"38065" "Oliver County"
"38067" "Pembina County"
"38069" "Pierce County"
"38071" "Ramsey County"
"38073" "Ransom County"
"38075" "Renville County"
"38077" "Richland County"
"38079" "Rolette County"
"38081" "Sargent County"
"38083" "Sheridan County"
"38085" "Sioux County"
"38087" "Slope County"
"38089" "Stark County"
"38091" "Steele County"
"38093" "Stutsman County"
"38095" "Towner County"
"38097" "Traill County"
"38099" "Walsh County"
"38101" "Ward County"
"38103" "Wells County"
"38105" "Williams County"
"39" "Ohio"
"39001" "Adams County"
"39003" "Allen County"
"39005" "Ashland County"
"39007" "Ashtabula County"
"39009" "Athens County"
"39011" "Auglaize County"
"39013" "Belmont County"
"39015" "Brown County"
"39017" "Butler County"
"39019" "Carroll County"
"39021" "Champaign County"
"39023" "Clark County"
"39025" "Clermont County"
"39027" "Clinton County"
"39029" "Columbiana County"
"39031" "Coshocton County"
"39033" "Crawford County"
"39035" "Cuyahoga County"
"39037" "Darke County"
"39039" "Defiance County"
"39041" "Delaware County"
"39043" "Erie County"
"39045" "Fairfield County"
"39047" "Fayette County"
"39049" "Franklin County"
"39051" "Fulton County"
"39053" "Gallia County"
"39055" "Geauga County"
"39057" "Greene County"
"39059" "Guernsey County"
"39061" "Hamilton County"
"39063" "Hancock County"
"39065" "Hardin County"
"39067" "Harrison County"
"39069" "Henry County"
"39071" "Highland County"
"39073" "Hocking County"
"39075" "Holmes County"
"39077" "Huron County"
"39079" "Jackson County"
"39081" "Jefferson County"
"39083" "Knox County"
"39085" "Lake County"
"39087" "Lawrence County"
"39089" "Licking County"
"39091" "Logan County"
"39093" "Lorain County"
"39095" "Lucas County"
"39097" "Madison County"
"39099" "Mahoning County"
"39101" "Marion County"
"39103" "Medina County"
"39105" "Meigs County"
"39107" "Mercer County"
"39109" "Miami County"
"39111" "Monroe County"
"39113" "Montgomery County"
"39115" "Morgan County"
"39117" "Morrow County"
"39119" "Muskingum County"
"39121" "Noble County"
"39123" "Ottawa County"
"39125" "Paulding County"
"39127" "Perry County"
"39129" "Pickaway County"
"39131" "Pike County"
"39133" "Portage County"
"39135" "Preble County"
"39137" "Putnam County"
"39139" "Richland County"
"39141" "Ross County"
"39143" "Sandusky County"
"39145" "Scioto County"
"39147" "Seneca County"
"39149" "Shelby County"
"39151" "Stark County"
"39153" "Summit County"
"39155" "Trumbull County"
"39157" "Tuscarawas County"
"39159" "Union County"
"39161" "Van Wert County"
"39163" "Vinton County"
"39165" "Warren County"
"39167" "Washington County"
"39169" "Wayne County"
"39171" "Williams County"
"39173" "Wood County"
"39175" "Wyandot County"
"40" "Oklahoma"
"40001" "Adair County"
"40003" "Alfalfa County"
"40005" "Atoka County"
"40007" "Beaver County"
"40009" "Beckham County"
"40011" "Blaine County"
"40013" "Bryan County"
"40015" "Caddo County"
"40017" "Canadian County"
"40019" "Carter County"
"40021" "Cherokee County"
"40023" "Choctaw County"
"40025" "Cimarron County"
"40027" "Cleveland County"
"40029" "Coal County"
"40031" "Comanche County"
"40033" "Cotton County"
"40035" "Craig County"
"40037" "Creek County"
"40039" "Custer County"
"40041" "Delaware County"
"40043" "Dewey County"
"40045" "Ellis County"
"40047" "Garfield County"
"40049" "Garvin County"
"40051" "Grady County"
"40053" "Grant County"
"40055" "Greer County"
"40057" "Harmon County"
"40059" "Harper County"
"40061" "Haskell County"
"40063" "Hughes County"
"40065" "Jackson County"
"40067" "Jefferson County"
"40069" "Johnston County"
"40071" "Kay County"
"40073" "Kingfisher County"
"40075" "Kiowa County"
"40077" "Latimer County"
"40079" "Le Flore County"
"40081" "Lincoln County"
"40083" "Logan County"
"40085" "Love County"
"40087" "McClain County"
"40089" "McCurtain County"
"40091" "McIntosh County"
"40093" "Major County"
"40095" "Marshall County"
"40097" "Mayes County"
"40099" "Murray County"
"40101" "Muskogee County"
"40103" "Noble County"
"40105" "Nowata County"
"40107" "Okfuskee County"
"40109" "Oklahoma County"
"40111" "Okmulgee County"
"40113" "Osage County"
"40115" "Ottawa County"
"40117" "Pawnee County"
"40119" "Payne County"
"40121" "Pittsburg County"
"40123" "Pontotoc County"
"40125" "Pottawatomie County"
"40127" "Pushmataha County"
"40129" "Roger Mills County"
"40131" "Rogers County"
"40133" "Seminole County"
"40135" "Sequoyah County"
"40137" "Stephens County"
"40139" "Texas County"
"40141" "Tillman County"
"40143" "Tulsa County"
"40145" "Wagoner County"
"40147" "Washington County"
"40149" "Washita County"
"40151" "Woods County"
"40153" "Woodward County"
"41" "Oregon"
"41001" "Baker County"
"41003" "Benton County"
"41005" "Clackamas County"
"41007" "Clatsop County"
"41009" "Columbia County"
"41011" "Coos County"
"41013" "Crook County"
"41015" "Curry County"
"41017" "Deschutes County"
"41019" "Douglas County"
"41021" "Gilliam County"
"41023" "Grant County"
"41025" "Harney County"
"41027" "Hood River County"
"41029" "Jackson County"
"41031" "Jefferson County"
"41033" "Josephine County"
"41035" "Klamath County"
"41037" "Lake County"
"41039" "Lane County"
"41041" "Lincoln County"
"41043" "Linn County"
"41045" "Malheur County"
"41047" "Marion County"
"41049" "Morrow County"
"41051" "Multnomah County"
"41053" "Polk County"
"41055" "Sherman County"
"41057" "Tillamook County"
"41059" "Umatilla County"
"41061" "Union County"
"41063" "Wallowa County"
"41065" "Wasco County"
"41067" "Washington County"
"41069" "Wheeler County"
"41071" "Yamhill County"
"42" "Pennsylvania"
"42001" "Adams County"
"42003" "Allegheny County"
"42005" "Armstrong County"
"42007" "Beaver County"
"42009" "Bedford County"
"42011" "Berks County"
"42013" "Blair County"
"42015" "Bradford County"
"42017" "Bucks County"
"42019" "Butler County"
"42021" "Cambria County"
"42023" "Cameron County"
"42025" "Carbon County"
"42027" "Centre County"
"42029" "Chester County"
"42031" "Clarion County"
"42033" "Clearfield County"
"42035" "Clinton County"
"42037" "Columbia County"
"42039" "Crawford County"
"42041" "Cumberland County"
"42043" "Dauphin County"
"42045" "Delaware County"
"42047" "Elk County"
"42049" "Erie County"
"42051" "Fayette County"
"42053" "Forest County"
"42055" "Franklin County"
"42057" "Fulton County"
"42059" "Greene County"
"42061" "Huntingdon County"
"42063" "Indiana County"
"42065" "Jefferson County"
"42067" "Juniata County"
"42069" "Lackawanna County"
"42071" "Lancaster County"
"42073" "Lawrence County"
"42075" "Lebanon County"
"42077" "Lehigh County"
"42079" "Luzerne County"
"42081" "Lycoming County"
"42083" "McKean County"
"42085" "Mercer County"
"42087" "Mifflin County"
"42089" "Monroe County"
"42091" "Montgomery County"
"42093" "Montour County"
"42095" "Northampton County"
"42097" "Northumberland County"
"42099" "Perry County"
"42101" "Philadelphia County"
"42103" "Pike County"
"42105" "Potter County"
"42107" "Schuylkill County"
"42109" "Snyder County"
"42111" "Somerset County"
"42113" "Sullivan County"
"42115" "Susquehanna County"
"42117" "Tioga County"
"42119" "Union County"
"42121" "Venango County"
"42123" "Warren County"
"42125" "Washington County"
"42127" "Wayne County"
"42129" "Westmoreland County"
"42131" "Wyoming County"
"42133" "York County"
"44" "Rhode Island"
"44001" "Bristol County"
"44003" "Kent County"
"44005" "Newport County"
"44007" "Providence County"
"44009" "Washington County"
"45" "South Carolina"
"45001" "Abbeville County"
"45003" "Aiken County"
"45005" "Allendale County"
"45007" "Anderson County"
"45009" "Bamberg County"
"45011" "Barnwell County"
"45013" "Beaufort County"
"45015" "Berkeley County"
"45017" "Calhoun County"
"45019" "Charleston County"
"45021" "Cherokee County"
"45023" "Chester County"
"45025" "Chesterfield County"
"45027" "Clarendon County"
"45029" "Colleton County"
"45031" "Darlington County"
"45033" "Dillon County"
"45035" "Dorchester County"
"45037" "Edgefield County"
"45039" "Fairfield County"
"45041" "Florence County"
"45043" "Georgetown County"
"45045" "Greenville County"
"45047" "Greenwood County"
"45049" "Hampton County"
"45051" "Horry County"
"45053" "Jasper County"
"45055" "Kershaw County"
"45057" "Lancaster County"
"45059" "Laurens County"
"45061" "Lee County"
"45063" "Lexington County"
"45065" "McCormick County"
"45067" "Marion County"
"45069" "Marlboro County"
"45071" "Newberry County"
"45073" "Oconee County"
"45075" "Orangeburg County"
"45077" "Pickens County"
"45079" "Richland County"
"45081" "Saluda County"
"45083" "Spartanburg County"
"45085" "Sumter County"
"45087" "Union County"
"45089" "Williamsburg County"
"45091" "York County"
"46" "South Dakota"
"46003" "Aurora County"
"46005" "Beadle County"
"46007" "Bennett County"
"46009" "Bon Homme County"
"46011" "Brookings County"
"46013" "Brown County"
"46015" "Brule County"
"46017" "Buffalo County"
"46019" "Butte County"
"46021" "Campbell County"
"46023" "Charles Mix County"
"46025" "Clark County"
"46027" "Clay County"
"46029" "Codington County"
"46031" "Corson County"
"46033" "Custer County"
"46035" "Davison County"
"46037" "Day County"
"46039" "Deuel County"
"46041" "Dewey County"
"46043" "Douglas County"
"46045" "Edmunds County"
"46047" "Fall River County"
"46049" "Faulk County"
"46051" "Grant County"
"46053" "Gregory County"
"46055" "Haakon County"
"46057" "Hamlin County"
"46059" "Hand County"
"46061" "Hanson County"
"46063" "Harding County"
"46065" "Hughes County"
"46067" "Hutchinson County"
"46069" "Hyde County"
"46071" "Jackson County"
"46073" "Jerauld County"
"46075" "Jones County"
"46077" "Kingsbury County"
"46079" "Lake County"
"46081" "Lawrence County"
"46083" "<NAME>coln County"
"46085" "<NAME> County"
"46087" "McCook County"
"46089" "<NAME>erson County"
"46091" "Marshall County"
"46093" "Meade County"
"46095" "Mellette County"
"46097" "Miner County"
"46099" "Minnehaha County"
"46101" "Moody County"
"46102" "Oglala Lakota County"
"46103" "Pennington County"
"46105" "Perkins County"
"46107" "Potter County"
"46109" "<NAME>erts County"
"46111" "Sanborn County"
"46115" "Spink County"
"46117" "Stanley County"
"46119" "<NAME>ully County"
"46121" "<NAME>odd County"
"46123" "Tripp County"
"46125" "<NAME>er County"
"46127" "Union County"
"46129" "Walworth County"
"46135" "Yankton County"
"46137" "Ziebach County"
"47" "Tennessee"
"47001" "Anderson County"
"47003" "Bedford County"
"47005" "Benton County"
"47007" "Bledsoe County"
"47009" "Blount County"
"47011" "Bradley County"
"47013" "Campbell County"
"47015" "Cannon County"
"47017" "Carroll County"
"47019" "Carter County"
"47021" "Cheatham County"
"47023" "Chester County"
"47025" "Claiborne County"
"47027" "Clay County"
"47029" "Cocke County"
"47031" "Coffee County"
"47033" "Crockett County"
"47035" "Cumberland County"
"47037" "<NAME>son County"
"47039" "Decatur County"
"47041" "DeKalb County"
"47043" "Dickson County"
"47045" "Dyer County"
"47047" "Fayette County"
"47049" "Fentress County"
"47051" "Franklin County"
"47053" "Gibson County"
"47055" "Giles County"
"47057" "Grainger County"
"47059" "Greene County"
"47061" "Grundy County"
"47063" "Hamblen County"
"47065" "Hamilton County"
"47067" "Hancock County"
"47069" "Hardeman County"
"47071" "<NAME> County"
"47073" "Hawkins County"
"47075" "Haywood County"
"47077" "Henderson County"
"47079" "Henry County"
"47081" "Hickman County"
"47083" "Houston County"
"47085" "Humphreys County"
"47087" "Jackson County"
"47089" "<NAME>efferson County"
"47091" "Johnson County"
"47093" "Knox County"
"47095" "Lake County"
"47097" "Lauderdale County"
"47099" "Lawrence County"
"47101" "Lewis County"
"47103" "Lincoln County"
"47105" "Loudon County"
"47107" "McMinn County"
"47109" "McNairy County"
"47111" "Macon County"
"47113" "Madison County"
"47115" "Marion County"
"47117" "Marshall County"
"47119" "Maury County"
"47121" "Meigs County"
"47123" "Monroe County"
"47125" "Montgomery County"
"47127" "Moore County"
"47129" "Morgan County"
"47131" "Obion County"
"47133" "Overton County"
"47135" "Perry County"
"47137" "Pickett County"
"47139" "Polk County"
"47141" "Putnam County"
"47143" "Rhea County"
"47145" "Roane County"
"47147" "<NAME>son County"
"47149" "Rutherford County"
"47151" "Scott County"
"47153" "Sequatchie County"
"47155" "Sevier County"
"47157" "Shelby County"
"47159" "Smith County"
"47161" "Stewart County"
"47163" "Sullivan County"
"47165" "Sumner County"
"47167" "Tipton County"
"47169" "Trousdale County"
"47171" "Unicoi County"
"47173" "Union County"
"47175" "<NAME> County"
"47177" "Warren County"
"47179" "Washington County"
"47181" "Wayne County"
"47183" "Weakley County"
"47185" "White County"
"47187" "Williamson County"
"47189" "Wilson County"
"48" "Texas"
"48001" "Anderson County"
"48003" "Andrews County"
"48005" "Angelina County"
"48007" "Aransas County"
"48009" "Archer County"
"48011" "Armstrong County"
"48013" "Atascosa County"
"48015" "Austin County"
"48017" "Bailey County"
"48019" "Bandera County"
"48021" "Bastrop County"
"48023" "Baylor County"
"48025" "Bee County"
"48027" "Bell County"
"48029" "Bexar County"
"48031" "Blanco County"
"48033" "Borden County"
"48035" "Bosque County"
"48037" "Bowie County"
"48039" "Brazoria County"
"48041" "Brazos County"
"48043" "Brewster County"
"48045" "Briscoe County"
"48047" "Brooks County"
"48049" "Brown County"
"48051" "Burleson County"
"48053" "Burnet County"
"48055" "Caldwell County"
"48057" "Calhoun County"
"48059" "Callahan County"
"48061" "Cameron County"
"48063" "Camp County"
"48065" "Carson County"
"48067" "Cass County"
"48069" "Castro County"
"48071" "Chambers County"
"48073" "Cherokee County"
"48075" "Childress County"
"48077" "Clay County"
"48079" "Cochran County"
"48081" "Coke County"
"48083" "Coleman County"
"48085" "Collin County"
"48087" "Collingsworth County"
"48089" "Colorado County"
"48091" "Comal County"
"48093" "Comanche County"
"48095" "Concho County"
"48097" "Cooke County"
"48099" "Coryell County"
"48101" "Cottle County"
"48103" "Crane County"
"48105" "Crockett County"
"48107" "Crosby County"
"48109" "Culberson County"
"48111" "Dallam County"
"48113" "Dallas County"
"48115" "Dawson County"
"48117" "Deaf Smith County"
"48119" "Delta County"
"48121" "Denton County"
"48123" "DeWitt County"
"48125" "Dickens County"
"48127" "Dimmit County"
"48129" "Donley County"
"48131" "Duval County"
"48133" "Eastland County"
"48135" "<NAME> County"
"48137" "<NAME>wards County"
"48139" "Ellis County"
"48141" "<NAME> Paso County"
"48143" "Erath County"
"48145" "Falls County"
"48147" "Fannin County"
"48149" "Fayette County"
"48151" "Fisher County"
"48153" "Floyd County"
"48155" "Foard County"
"48157" "Fort Bend County"
"48159" "Franklin County"
"48161" "Freestone County"
"48163" "Frio County"
"48165" "Gaines County"
"48167" "Galveston County"
"48169" "Garza County"
"48171" "Gillespie County"
"48173" "Glasscock County"
"48175" "Goliad County"
"48177" "<NAME>onzales County"
"48179" "Gray County"
"48181" "<NAME>son County"
"48183" "Gregg County"
"48185" "Grimes County"
"48187" "Guadalupe County"
"48189" "Hale County"
"48191" "Hall County"
"48193" "Hamilton County"
"48195" "Hansford County"
"48197" "Hardeman County"
"48199" "Hardin County"
"48201" "Harris County"
"48203" "Harrison County"
"48205" "Hartley County"
"48207" "Haskell County"
"48209" "Hays County"
"48211" "Hemphill County"
"48213" "<NAME>erson County"
"48215" "<NAME>algo County"
"48217" "Hill County"
"48219" "Hockley County"
"48221" "Hood County"
"48223" "Hopkins County"
"48225" "Houston County"
"48227" "Howard County"
"48229" "<NAME> County"
"48231" "Hunt County"
"48233" "Hutchinson County"
"48235" "<NAME>ion County"
"48237" "Jack County"
"48239" "<NAME> County"
"48241" "J<NAME> County"
"48243" "<NAME> County"
"48245" "<NAME>erson County"
"48247" "<NAME> County"
"48249" "<NAME> County"
"48251" "<NAME>son County"
"48253" "Jones County"
"48255" "Karnes County"
"48257" "Kaufman County"
"48259" "Kendall County"
"48261" "Kenedy County"
"48263" "Kent County"
"48265" "Kerr County"
"48267" "Kimble County"
"48269" "King County"
"48271" "Kinney County"
"48273" "Kleberg County"
"48275" "Knox County"
"48277" "Lamar County"
"48279" "Lamb County"
"48281" "Lampasas County"
"48283" "La Salle County"
"48285" "Lavaca County"
"48287" "Lee County"
"48289" "Leon County"
"48291" "Liberty County"
"48293" "Limestone County"
"48295" "Lipscomb County"
"48297" "Live Oak County"
"48299" "Llano County"
"48301" "Loving County"
"48303" "Lubbock County"
"48305" "Lynn County"
"48307" "McCulloch County"
"48309" "McLennan County"
"48311" "McMullen County"
"48313" "Madison County"
"48315" "Marion County"
"48317" "Martin County"
"48319" "Mason County"
"48321" "Matagorda County"
"48323" "Maverick County"
"48325" "Medina County"
"48327" "Menard County"
"48329" "Midland County"
"48331" "Milam County"
"48333" "Mills County"
"48335" "Mitchell County"
"48337" "Montague County"
"48339" "Montgomery County"
"48341" "Moore County"
"48343" "Morris County"
"48345" "Motley County"
"48347" "Nacogdoches County"
"48349" "Navarro County"
"48351" "Newton County"
"48353" "Nolan County"
"48355" "Nueces County"
"48357" "Ochiltree County"
"48359" "Oldham County"
"48361" "Orange County"
"48363" "Palo Pinto County"
"48365" "Panola County"
"48367" "Parker County"
"48369" "Parmer County"
"48371" "Pecos County"
"48373" "Polk County"
"48375" "Potter County"
"48377" "Presidio County"
"48379" "Rains County"
"48381" "Randall County"
"48383" "Reagan County"
"48385" "Real County"
"48387" "Red River County"
"48389" "Reeves County"
"48391" "Refugio County"
"48393" "Roberts County"
"48395" "<NAME>son County"
"48397" "Rockwall County"
"48399" "Runnels County"
"48401" "Rusk County"
"48403" "Sabine County"
"48405" "San Augustine County"
"48407" "San Jacinto County"
"48409" "San Patricio County"
"48411" "San Saba County"
"48413" "Schleicher County"
"48415" "Scurry County"
"48417" "Shackelford County"
"48419" "Shelby County"
"48421" "Sherman County"
"48423" "Smith County"
"48425" "Somervell County"
"48427" "Starr County"
"48429" "Stephens County"
"48431" "Sterling County"
"48433" "Stonewall County"
"48435" "Sutton County"
"48437" "Swisher County"
"48439" "Tarrant County"
"48441" "Taylor County"
"48443" "Terrell County"
"48445" "Terry County"
"48447" "Throckmorton County"
"48449" "Titus County"
"48451" "<NAME> Green County"
"48453" "Travis County"
"48455" "Trinity County"
"48457" "Tyler County"
"48459" "Upshur County"
"48461" "Upton County"
"48463" "Uvalde County"
"48465" "Val Verde County"
"48467" "Van Zandt County"
"48469" "Victoria County"
"48471" "Walker County"
"48473" "Waller County"
"48475" "Ward County"
"48477" "Washington County"
"48479" "Webb County"
"48481" "Wharton County"
"48483" "Wheeler County"
"48485" "Wichita County"
"48487" "Wilbarger County"
"48489" "Willacy County"
"48491" "Williamson County"
"48493" "Wilson County"
"48495" "Winkler County"
"48497" "Wise County"
"48499" "Wood County"
"48501" "Yoakum County"
"48503" "Young County"
"48505" "Zapata County"
"48507" "Zavala County"
"49" "Utah"
"49001" "Beaver County"
"49003" "Box Elder County"
"49005" "Cache County"
"49007" "Carbon County"
"49009" "Daggett County"
"49011" "Davis County"
"49013" "Duchesne County"
"49015" "Emery County"
"49017" "Garfield County"
"49019" "Grand County"
"49021" "Iron County"
"49023" "Juab County"
"49025" "Kane County"
"49027" "Millard County"
"49029" "Morgan County"
"49031" "Piute County"
"49033" "Rich County"
"49035" "Salt Lake County"
"49037" "San Juan County"
"49039" "Sanpete County"
"49041" "Sevier County"
"49043" "Summit County"
"49045" "Tooele County"
"49047" "Uintah County"
"49049" "Utah County"
"49051" "Wasatch County"
"49053" "Washington County"
"49055" "Wayne County"
"49057" "Weber County"
"50" "Vermont"
"50001" "Addison County"
"50003" "Bennington County"
"50005" "Caledonia County"
"50007" "Chittenden County"
"50009" "Essex County"
"50011" "Franklin County"
"50013" "Grand Isle County"
"50015" "Lamoille County"
"50017" "Orange County"
"50019" "Orleans County"
"50021" "Rutland County"
"50023" "Washington County"
"50025" "Windham County"
"50027" "Windsor County"
"51" "Virginia"
"51001" "Accomack County"
"51003" "Albemarle County"
"51005" "Alleghany County"
"51007" "Amelia County"
"51009" "Amherst County"
"51011" "Appomattox County"
"51013" "Arlington County"
"51015" "Augusta County"
"51017" "Bath County"
"51019" "Bedford County"
"51021" "Bland County"
"51023" "Botetourt County"
"51025" "Brunswick County"
"51027" "Buchanan County"
"51029" "Buckingham County"
"51031" "Campbell County"
"51033" "Caroline County"
"51035" "Carroll County"
"51036" "Charles City County"
"51037" "Charlotte County"
"51041" "Chesterfield County"
"51043" "Clarke County"
"51045" "Craig County"
"51047" "Culpeper County"
"51049" "Cumberland County"
"51051" "Dickenson County"
"51053" "Dinwiddie County"
"51057" "Essex County"
"51059" "Fairfax County"
"51061" "Fauquier County"
"51063" "Floyd County"
"51065" "Fluvanna County"
"51067" "Franklin County"
"51069" "Frederick County"
"51071" "Giles County"
"51073" "Gloucester County"
"51075" "Goochland County"
"51077" "Grayson County"
"51079" "Greene County"
"51081" "Greensville County"
"51083" "Halifax County"
"51085" "Hanover County"
"51087" "Henrico County"
"51089" "Henry County"
"51091" "Highland County"
"51093" "Isle of Wight County"
"51095" "James City County"
"51097" "King and Queen County"
"51099" "King George County"
"51101" "King William County"
"51103" "Lancaster County"
"51105" "Lee County"
"51107" "Loudoun County"
"51109" "Louisa County"
"51111" "Lunenburg County"
"51113" "Madison County"
"51115" "Mathews County"
"51117" "Mecklenburg County"
"51119" "Middlesex County"
"51121" "Montgomery County"
"51125" "Nelson County"
"51127" "New Kent County"
"51131" "Northampton County"
"51133" "Northumberland County"
"51135" "Nottoway County"
"51137" "Orange County"
"51139" "Page County"
"51141" "Patrick County"
"51143" "Pittsylvania County"
"51145" "Powhatan County"
"51147" "Prince Edward County"
"51149" "Prince George County"
"51153" "Prince William County"
"51155" "Pulaski County"
"51157" "Rappahannock County"
"51159" "Richmond County"
"51161" "Roanoke County"
"51163" "Rockbridge County"
"51165" "Rockingham County"
"51167" "Russell County"
"51169" "Scott County"
"51171" "Shenandoah County"
"51173" "Smyth County"
"51175" "Southampton County"
"51177" "Spotsylvania County"
"51179" "Stafford County"
"51181" "Surry County"
"51183" "Sussex County"
"51185" "Tazewell County"
"51187" "Warren County"
"51191" "Washington County"
"51193" "Westmoreland County"
"51195" "Wise County"
"51197" "Wythe County"
"51199" "York County"
"51510" "Alexandria city"
"51520" "Bristol city"
"51530" "Buena Vista city"
"51540" "Charlottesville city"
"51550" "Chesapeake city"
"51570" "Colonial Heights city"
"51580" "Covington city"
"51590" "Danville city"
"51595" "Emporia city"
"51600" "Fairfax city"
"51610" "Falls Church city"
"51620" "Franklin city"
"51630" "Fredericksburg city"
"51640" "Galax city"
"51650" "Hampton city"
"51660" "Harrisonburg city"
"51670" "Hopewell city"
"51678" "Lexington city"
"51680" "Lynchburg city"
"51683" "Manassas city"
"51685" "Manassas Park city"
"51690" "Martinsville city"
"51700" "Newport News city"
"51710" "Norfolk city"
"51720" "Norton city"
"51730" "Petersburg city"
"51735" "Poquoson city"
"51740" "Portsmouth city"
"51750" "Radford city"
"51760" "Richmond city"
"51770" "Roanoke city"
"51775" "Salem city"
"51790" "Staunton city"
"51800" "Suffolk city"
"51810" "Virginia Beach city"
"51820" "Waynesboro city"
"51830" "Williamsburg city"
"51840" "Winchester city"
"53" "Washington"
"53001" "Adams County"
"53003" "Asotin County"
"53005" "Benton County"
"53007" "Chelan County"
"53009" "Clallam County"
"53011" "Clark County"
"53013" "Columbia County"
"53015" "Cowlitz County"
"53017" "Douglas County"
"53019" "Ferry County"
"53021" "Franklin County"
"53023" "Garfield County"
"53025" "Grant County"
"53027" "Grays Harbor County"
"53029" "Island County"
"53031" "Jefferson County"
"53033" "King County"
"53035" "Kitsap County"
"53037" "Kittitas County"
"53039" "Klickitat County"
"53041" "Lewis County"
"53043" "Lincoln County"
"53045" "Mason County"
"53047" "Okanogan County"
"53049" "Pacific County"
"53051" "Pend Oreille County"
"53053" "Pierce County"
"53055" "San Juan County"
"53057" "Skagit County"
"53059" "Skamania County"
"53061" "Snohomish County"
"53063" "Spokane County"
"53065" "Stevens County"
"53067" "Thurston County"
"53069" "Wahkiakum County"
"53071" "Walla Walla County"
"53073" "Whatcom County"
"53075" "Whitman County"
"53077" "Yakima County"
"54" "West Virginia"
"54001" "Barbour County"
"54003" "Berkeley County"
"54005" "Boone County"
"54007" "Braxton County"
"54009" "Brooke County"
"54011" "Cabell County"
"54013" "Calhoun County"
"54015" "Clay County"
"54017" "Doddridge County"
"54019" "Fayette County"
"54021" "Gilmer County"
"54023" "Grant County"
"54025" "Greenbrier County"
"54027" "Hampshire County"
"54029" "Hancock County"
"54031" "Hardy County"
"54033" "Harrison County"
"54035" "Jackson County"
"54037" "Jefferson County"
"54039" "Kanawha County"
"54041" "Lewis County"
"54043" "Lincoln County"
"54045" "Logan County"
"54047" "McDowell County"
"54049" "Marion County"
"54051" "Marshall County"
"54053" "Mason County"
"54055" "Mercer County"
"54057" "Mineral County"
"54059" "Mingo County"
"54061" "Monongalia County"
"54063" "Monroe County"
"54065" "Morgan County"
"54067" "Nicholas County"
"54069" "Ohio County"
"54071" "Pendleton County"
"54073" "Pleasants County"
"54075" "Pocahontas County"
"54077" "Preston County"
"54079" "Putnam County"
"54081" "Raleigh County"
"54083" "Randolph County"
"54085" "Ritchie County"
"54087" "Roane County"
"54089" "Summers County"
"54091" "Taylor County"
"54093" "Tucker County"
"54095" "Tyler County"
"54097" "Upshur County"
"54099" "Wayne County"
"54101" "Webster County"
"54103" "Wetzel County"
"54105" "Wirt County"
"54107" "Wood County"
"54109" "Wyoming County"
"55" "Wisconsin"
"55001" "Adams County"
"55003" "Ashland County"
"55005" "Barron County"
"55007" "Bayfield County"
"55009" "Brown County"
"55011" "Buffalo County"
"55013" "Burnett County"
"55015" "Calumet County"
"55017" "Chippewa County"
"55019" "Clark County"
"55021" "Columbia County"
"55023" "Crawford County"
"55025" "Dane County"
"55027" "Dodge County"
"55029" "Door County"
"55031" "Douglas County"
"55033" "Dunn County"
"55035" "Eau Claire County"
"55037" "Florence County"
"55039" "Fond du Lac County"
"55041" "Forest County"
"55043" "Grant County"
"55045" "Green County"
"55047" "Green Lake County"
"55049" "Iowa County"
"55051" "Iron County"
"55053" "Jackson County"
"55055" "Jefferson County"
"55057" "Juneau County"
"55059" "Kenosha County"
"55061" "Kewaunee County"
"55063" "La Crosse County"
"55065" "Lafayette County"
"55067" "Langlade County"
"55069" "Lincoln County"
"55071" "Manitowoc County"
"55073" "Marathon County"
"55075" "Marinette County"
"55077" "Marquette County"
"55078" "Menominee County"
"55079" "Milwaukee County"
"55081" "Monroe County"
"55083" "Oconto County"
"55085" "Oneida County"
"55087" "Outagamie County"
"55089" "Ozaukee County"
"55091" "Pepin County"
"55093" "Pierce County"
"55095" "Polk County"
"55097" "Portage County"
"55099" "Price County"
"55101" "Racine County"
"55103" "Richland County"
"55105" "Rock County"
"55107" "Rusk County"
"55109" "St. Croix County"
"55111" "Sauk County"
"55113" "Sawyer County"
"55115" "Shawano County"
"55117" "Sheboygan County"
"55119" "Taylor County"
"55121" "Trempealeau County"
"55123" "Vernon County"
"55125" "Vilas County"
"55127" "Walworth County"
"55129" "Washburn County"
"55131" "Washington County"
"55133" "Waukesha County"
"55135" "Waupaca County"
"55137" "Waushara County"
"55139" "Winnebago County"
"55141" "Wood County"
"56" "Wyoming"
"56001" "Albany County"
"56003" "Big Horn County"
"56005" "Campbell County"
"56007" "Carbon County"
"56009" "Converse County"
"56011" "Crook County"
"56013" "Fremont County"
"56015" "Goshen County"
"56017" "Hot Springs County"
"56019" "Johnson County"
"56021" "Laramie County"
"56023" "Lincoln County"
"56025" "Natrona County"
"56027" "Niobrara County"
"56029" "Park County"
"56031" "Platte County"
"56033" "Sheridan County"
"56035" "Sublette County"
"56037" "Sweetwater County"
"56039" "Teton County"
"56041" "Uinta County"
"56043" "Washakie County"
"56045" "Weston County"})
(defn fips-name
([state-fips county-fips]
(fips-name (str state-fips county-fips)))
([fips]
(get fips->name fips fips)))
(defn county-list
"Given a state fips, returns a vector of vectors like:
[[\"01001\" \"Autauga County\"]
[\"01003\" \"Baldwin County\"]
...]
The order is defined by the order of the county fips codes.
The counties come from the fips->name map."
[state-fips]
(letfn [(in-state? [candidate-fips]
(str/starts-with? candidate-fips state-fips))
(county-fips? [candidate-fips]
(= 5 (count candidate-fips)))
(county-fips-for-state? [candidate-fips]
(and (in-state? candidate-fips)
(county-fips? candidate-fips)))]
(let [county-keys (->> (keys fips->name)
(filter county-fips-for-state?)
sort)
county-names (map fips->name county-keys)]
(mapv vector county-keys county-names))))
(def state-fips->abbreviation
{"01" "AL"
"02" "AK"
"04" "AZ"
"05" "AR"
"06" "CA"
"08" "CO"
"09" "CT"
"10" "DE"
"11" "DC"
"12" "FL"
"13" "GA"
"15" "HI"
"16" "ID"
"17" "IL"
"18" "IN"
"19" "IA"
"20" "KS"
"21" "KY"
"22" "LA"
"23" "ME"
"24" "MD"
"25" "MA"
"26" "MI"
"27" "MN"
"28" "MS"
"29" "MO"
"30" "MT"
"31" "NE"
"32" "NV"
"33" "NH"
"34" "NJ"
"35" "NM"
"36" "NY"
"37" "NC"
"38" "ND"
"39" "OH"
"40" "OK"
"41" "OR"
"42" "PA"
"44" "RI"
"45" "SC"
"46" "SD"
"47" "TN"
"48" "TX"
"49" "UT"
"50" "VT"
"51" "VA"
"53" "WA"
"54" "WV"
"55" "WI"
"56" "WY"})
| true |
(ns early-vote-site.places
(:require [clojure.string :as str]))
(def fips->name
{"01" "Alabama"
"01001" "Autauga County"
"01003" "Baldwin County"
"01005" "Barbour County"
"01007" "Bibb County"
"01009" "Blount County"
"01011" "Bullock County"
"01013" "Butler County"
"01015" "Calhoun County"
"01017" "Chambers County"
"01019" "Cherokee County"
"01021" "Chilton County"
"01023" "Choctaw County"
"01025" "Clarke County"
"01027" "Clay County"
"01029" "Cleburne County"
"01031" "Coffee County"
"01033" "Colbert County"
"01035" "Conecuh County"
"01037" "Coosa County"
"01039" "Covington County"
"01041" "Crenshaw County"
"01043" "Cullman County"
"01045" "Dale County"
"01047" "Dallas County"
"01049" "DeKalb County"
"01051" "Elmore County"
"01053" "Escambia County"
"01055" "Etowah County"
"01057" "Fayette County"
"01059" "Franklin County"
"01061" "Geneva County"
"01063" "Greene County"
"01065" "Hale County"
"01067" "Henry County"
"01069" "Houston County"
"01071" "Jackson County"
"01073" "Jefferson County"
"01075" "Lamar County"
"01077" "Lauderdale County"
"01079" "Lawrence County"
"01081" "Lee County"
"01083" "Limestone County"
"01085" "Lowndes County"
"01087" "Macon County"
"01089" "Madison County"
"01091" "Marengo County"
"01093" "Marion County"
"01095" "Marshall County"
"01097" "Mobile County"
"01099" "Monroe County"
"01101" "Montgomery County"
"01103" "Morgan County"
"01105" "Perry County"
"01107" "PI:NAME:<NAME>END_PIkens County"
"01109" "Pike County"
"01111" "Randolph County"
"01113" "Russell County"
"01115" "St. Clair County"
"01117" "Shelby County"
"01119" "Sumter County"
"01121" "Talladega County"
"01123" "Tallapoosa County"
"01125" "Tuscaloosa County"
"01127" "Walker County"
"01129" "Washington County"
"01131" "Wilcox County"
"01133" "Winston County"
"02" "Alaska"
"02013" "Aleutians East Borough"
"02016" "Aleutians West Census Area"
"02020" "Anchorage Municipality"
"02050" "Bethel Census Area"
"02060" "Bristol Bay Borough"
"02068" "Denali Borough"
"02070" "Dillingham Census Area"
"02090" "Fairbanks North Star Borough"
"02100" "Haines Borough"
"02105" "Hoonah-Angoon Census Area"
"02110" "Juneau City and Borough"
"02122" "Kenai Peninsula Borough"
"02130" "Ketchikan Gateway Borough"
"02150" "Kodiak Island Borough"
"02158" "Kusilvak Census Area"
"02164" "Lake and Peninsula Borough"
"02170" "Matanuska-Susitna Borough"
"02180" "Nome Census Area"
"02185" "North Slope Borough"
"02188" "Northwest Arctic Borough"
"02195" "Petersburg Borough"
"02198" "Prince of Wales-Hyder Census Area"
"02220" "Sitka City and Borough"
"02230" "Skagway Municipality"
"02240" "Southeast Fairbanks Census Area"
"02261" "Valdez-Cordova Census Area"
"02275" "Wrangell City and Borough"
"02282" "Yakutat City and Borough"
"02290" "Yukon-Koyukuk Census Area"
"04" "Arizona"
"04001" "Apache County"
"04003" "Cochise County"
"04005" "Coconino County"
"04007" "Gila County"
"04009" "Graham County"
"04011" "Greenlee County"
"04012" "La Paz County"
"04013" "Maricopa County"
"04015" "Mohave County"
"04017" "Navajo County"
"04019" "Pima County"
"04021" "Pinal County"
"04023" "Santa Cruz County"
"04025" "Yavapai County"
"04027" "Yuma County"
"05" "Arkansas"
"05001" "Arkansas County"
"05003" "Ashley County"
"05005" "Baxter County"
"05007" "Benton County"
"05009" "Boone County"
"05011" "Bradley County"
"05013" "Calhoun County"
"05015" "Carroll County"
"05017" "Chicot County"
"05019" "Clark County"
"05021" "Clay County"
"05023" "Cleburne County"
"05025" "Cleveland County"
"05027" "Columbia County"
"05029" "Conway County"
"05031" "Craighead County"
"05033" "Crawford County"
"05035" "Crittenden County"
"05037" "Cross County"
"05039" "Dallas County"
"05041" "Desha County"
"05043" "Drew County"
"05045" "Faulkner County"
"05047" "Franklin County"
"05049" "Fulton County"
"05051" "Garland County"
"05053" "Grant County"
"05055" "Greene County"
"05057" "Hempstead County"
"05059" "Hot Spring County"
"05061" "Howard County"
"05063" "Independence County"
"05065" "Izard County"
"05067" "Jackson County"
"05069" "Jefferson County"
"05071" "Johnson County"
"05073" "Lafayette County"
"05075" "Lawrence County"
"05077" "Lee County"
"05079" "Lincoln County"
"05081" "Little River County"
"05083" "Logan County"
"05085" "Lonoke County"
"05087" "Madison County"
"05089" "Marion County"
"05091" "Miller County"
"05093" "Mississippi County"
"05095" "Monroe County"
"05097" "Montgomery County"
"05099" "Nevada County"
"05101" "Newton County"
"05103" "Ouachita County"
"05105" "Perry County"
"05107" "Phillips County"
"05109" "Pike County"
"05111" "Poinsett County"
"05113" "Polk County"
"05115" "Pope County"
"05117" "Prairie County"
"05119" "Pulaski County"
"05121" "Randolph County"
"05123" "St. Francis County"
"05125" "Saline County"
"05127" "Scott County"
"05129" "Searcy County"
"05131" "Sebastian County"
"05133" "Sevier County"
"05135" "Sharp County"
"05137" "Stone County"
"05139" "Union County"
"05141" "Van Buren County"
"05143" "Washington County"
"05145" "White County"
"05147" "Woodruff County"
"05149" "Yell County"
"06" "California"
"06001" "Alameda County"
"06003" "Alpine County"
"06005" "Amador County"
"06007" "Butte County"
"06009" "Calaveras County"
"06011" "Colusa County"
"06013" "Contra Costa County"
"06015" "Del Norte County"
"06017" "El Dorado County"
"06019" "Fresno County"
"06021" "Glenn County"
"06023" "Humboldt County"
"06025" "Imperial County"
"06027" "Inyo County"
"06029" "Kern County"
"06031" "Kings County"
"06033" "Lake County"
"06035" "Lassen County"
"06037" "Los Angeles County"
"06039" "Madera County"
"06041" "Marin County"
"06043" "Mariposa County"
"06045" "Mendocino County"
"06047" "Merced County"
"06049" "Modoc County"
"06051" "Mono County"
"06053" "Monterey County"
"06055" "Napa County"
"06057" "Nevada County"
"06059" "Orange County"
"06061" "Placer County"
"06063" "Plumas County"
"06065" "Riverside County"
"06067" "Sacramento County"
"06069" "San Benito County"
"06071" "San Bernardino County"
"06073" "San Diego County"
"06075" "San Francisco County"
"06077" "San Joaquin County"
"06079" "San Luis Obispo County"
"06081" "San Mateo County"
"06083" "Santa Barbara County"
"06085" "Santa Clara County"
"06087" "Santa Cruz County"
"06089" "Shasta County"
"06091" "Sierra County"
"06093" "Siskiyou County"
"06095" "Solano County"
"06097" "Sonoma County"
"06099" "Stanislaus County"
"06101" "Sutter County"
"06103" "Tehama County"
"06105" "Trinity County"
"06107" "Tulare County"
"06109" "Tuolumne County"
"06111" "Ventura County"
"06113" "Yolo County"
"06115" "Yuba County"
"08" "Colorado"
"08001" "Adams County"
"08003" "Alamosa County"
"08005" "Arapahoe County"
"08007" "Archuleta County"
"08009" "Baca County"
"08011" "Bent County"
"08013" "Boulder County"
"08014" "Broomfield County"
"08015" "Chaffee County"
"08017" "Cheyenne County"
"08019" "Clear Creek County"
"08021" "Conejos County"
"08023" "Costilla County"
"08025" "Crowley County"
"08027" "Custer County"
"08029" "Delta County"
"08031" "Denver County"
"08033" "Dolores County"
"08035" "Douglas County"
"08037" "Eagle County"
"08039" "Elbert County"
"08041" "El Paso County"
"08043" "Fremont County"
"08045" "Garfield County"
"08047" "Gilpin County"
"08049" "Grand County"
"08051" "Gunnison County"
"08053" "Hinsdale County"
"08055" "Huerfano County"
"08057" "Jackson County"
"08059" "Jefferson County"
"08061" "Kiowa County"
"08063" "PI:NAME:<NAME>END_PI County"
"08065" "Lake County"
"08067" "La Plata County"
"08069" "Larimer County"
"08071" "Las Animas County"
"08073" "Lincoln County"
"08075" "Logan County"
"08077" "Mesa County"
"08079" "Mineral County"
"08081" "Moffat County"
"08083" "Montezuma County"
"08085" "Montrose County"
"08087" "Morgan County"
"08089" "Otero County"
"08091" "Ouray County"
"08093" "Park County"
"08095" "Phillips County"
"08097" "Pitkin County"
"08099" "Prowers County"
"08101" "Pueblo County"
"08103" "Rio Blanco County"
"08105" "Rio Grande County"
"08107" "Routt County"
"08109" "Saguache County"
"08111" "San Juan County"
"08113" "San Miguel County"
"08115" "Sedgwick County"
"08117" "Summit County"
"08119" "Teller County"
"08121" "Washington County"
"08123" "Weld County"
"08125" "Yuma County"
"09" "Connecticut"
"09001" "Fairfield County"
"09003" "Hartford County"
"09005" "Litchfield County"
"09007" "Middlesex County"
"09009" "New Haven County"
"09011" "New London County"
"09013" "Tolland County"
"09015" "Windham County"
"10" "Delaware"
"10001" "Kent County"
"10003" "New Castle County"
"10005" "Sussex County"
"11" "District of Columbia"
"11001" "District of Columbia"
"12" "Florida"
"12001" "Alachua County"
"12003" "Baker County"
"12005" "Bay County"
"12007" "Bradford County"
"12009" "Brevard County"
"12011" "Broward County"
"12013" "Calhoun County"
"12015" "Charlotte County"
"12017" "Citrus County"
"12019" "Clay County"
"12021" "Collier County"
"12023" "Columbia County"
"12027" "DeSoto County"
"12029" "Dixie County"
"12031" "Duval County"
"12033" "Escambia County"
"12035" "Flagler County"
"12037" "Franklin County"
"12039" "Gadsden County"
"12041" "Gilchrist County"
"12043" "Glades County"
"12045" "Gulf County"
"12047" "Hamilton County"
"12049" "Hardee County"
"12051" "Hendry County"
"12053" "Hernando County"
"12055" "Highlands County"
"12057" "Hillsborough County"
"12059" "Holmes County"
"12061" "Indian River County"
"12063" "Jackson County"
"12065" "Jefferson County"
"12067" "Lafayette County"
"12069" "Lake County"
"12071" "Lee County"
"12073" "Leon County"
"12075" "Levy County"
"12077" "Liberty County"
"12079" "Madison County"
"12081" "Manatee County"
"12083" "Marion County"
"12085" "Martin County"
"12086" "Miami-Dade County"
"12087" "Monroe County"
"12089" "Nassau County"
"12091" "Okaloosa County"
"12093" "Okeechobee County"
"12095" "Orange County"
"12097" "Osceola County"
"12099" "Palm Beach County"
"12101" "Pasco County"
"12103" "Pinellas County"
"12105" "Polk County"
"12107" "Putnam County"
"12109" "St. Johns County"
"12111" "St. Lucie County"
"12113" "Santa Rosa County"
"12115" "Sarasota County"
"12117" "Seminole County"
"12119" "Sumter County"
"12121" "Suwannee County"
"12123" "Taylor County"
"12125" "Union County"
"12127" "Volusia County"
"12129" "Wakulla County"
"12131" "Walton County"
"12133" "Washington County"
"13" "Georgia"
"13001" "Appling County"
"13003" "Atkinson County"
"13005" "Bacon County"
"13007" "Baker County"
"13009" "Baldwin County"
"13011" "Banks County"
"13013" "Barrow County"
"13015" "Bartow County"
"13017" "Ben Hill County"
"13019" "Berrien County"
"13021" "Bibb County"
"13023" "Bleckley County"
"13025" "Brantley County"
"13027" "Brooks County"
"13029" "Bryan County"
"13031" "Bulloch County"
"13033" "Burke County"
"13035" "Butts County"
"13037" "Calhoun County"
"13039" "Camden County"
"13043" "Candler County"
"13045" "Carroll County"
"13047" "Catoosa County"
"13049" "Charlton County"
"13051" "Chatham County"
"13053" "Chattahoochee County"
"13055" "Chattooga County"
"13057" "Cherokee County"
"13059" "Clarke County"
"13061" "Clay County"
"13063" "Clayton County"
"13065" "Clinch County"
"13067" "Cobb County"
"13069" "Coffee County"
"13071" "Colquitt County"
"13073" "Columbia County"
"13075" "Cook County"
"13077" "Coweta County"
"13079" "Crawford County"
"13081" "Crisp County"
"13083" "Dade County"
"13085" "Dawson County"
"13087" "Decatur County"
"13089" "DeKalb County"
"13091" "Dodge County"
"13093" "Dooly County"
"13095" "Dougherty County"
"13097" "Douglas County"
"13099" "Early County"
"13101" "Echols County"
"13103" "Effingham County"
"13105" "Elbert County"
"13107" "Emanuel County"
"13109" "Evans County"
"13111" "Fannin County"
"13113" "Fayette County"
"13115" "Floyd County"
"13117" "PI:NAME:<NAME>END_PIth County"
"13119" "Franklin County"
"13121" "Fulton County"
"13123" "PI:NAME:<NAME>END_PIilmer County"
"13125" "PI:NAME:<NAME>END_PIcock County"
"13127" "PI:NAME:<NAME>END_PI County"
"13129" "PI:NAME:<NAME>END_PI County"
"13131" "Grady County"
"13133" "Greene County"
"13135" "Gwinnett County"
"13137" "Habersham County"
"13139" "Hall County"
"13141" "Hancock County"
"13143" "PI:NAME:<NAME>END_PIson County"
"13145" "Harris County"
"13147" "Hart County"
"13149" "Heard County"
"13151" "Henry County"
"13153" "Houston County"
"13155" "Irwin County"
"13157" "PI:NAME:<NAME>END_PIson County"
"13159" "JPI:NAME:<NAME>END_PI County"
"13161" "PI:NAME:<NAME>END_PI County"
"13163" "PI:NAME:<NAME>END_PI County"
"13165" "PI:NAME:<NAME>END_PIenkins County"
"13167" "Johnson County"
"13169" "Jones County"
"13171" "Lamar County"
"13173" "Lanier County"
"13175" "Laurens County"
"13177" "Lee County"
"13179" "Liberty County"
"13181" "Lincoln County"
"13183" "Long County"
"13185" "Lowndes County"
"13187" "Lumpkin County"
"13189" "McDuffie County"
"13191" "McIntosh County"
"13193" "Macon County"
"13195" "Madison County"
"13197" "Marion County"
"13199" "Meriwether County"
"13201" "Miller County"
"13205" "Mitchell County"
"13207" "Monroe County"
"13209" "Montgomery County"
"13211" "Morgan County"
"13213" "Murray County"
"13215" "Muscogee County"
"13217" "Newton County"
"13219" "Oconee County"
"13221" "Oglethorpe County"
"13223" "Paulding County"
"13225" "Peach County"
"13227" "Pickens County"
"13229" "Pierce County"
"13231" "Pike County"
"13233" "Polk County"
"13235" "Pulaski County"
"13237" "Putnam County"
"13239" "Quitman County"
"13241" "Rabun County"
"13243" "Randolph County"
"13245" "Richmond County"
"13247" "Rockdale County"
"13249" "Schley County"
"13251" "Screven County"
"13253" "Seminole County"
"13255" "Spalding County"
"13257" "Stephens County"
"13259" "Stewart County"
"13261" "Sumter County"
"13263" "Talbot County"
"13265" "Taliaferro County"
"13267" "Tattnall County"
"13269" "Taylor County"
"13271" "Telfair County"
"13273" "Terrell County"
"13275" "Thomas County"
"13277" "Tift County"
"13279" "Toombs County"
"13281" "Towns County"
"13283" "Treutlen County"
"13285" "Troup County"
"13287" "Turner County"
"13289" "Twiggs County"
"13291" "Union County"
"13293" "Upson County"
"13295" "Walker County"
"13297" "Walton County"
"13299" "Ware County"
"13301" "Warren County"
"13303" "Washington County"
"13305" "Wayne County"
"13307" "Webster County"
"13309" "Wheeler County"
"13311" "White County"
"13313" "Whitfield County"
"13315" "Wilcox County"
"13317" "Wilkes County"
"13319" "Wilkinson County"
"13321" "Worth County"
"15" "Hawaii"
"15001" "Hawaii County"
"15003" "Honolulu County"
"15005" "Kalawao County"
"15007" "Kauai County"
"15009" "Maui County"
"16" "Idaho"
"16001" "Ada County"
"16003" "Adams County"
"16005" "Bannock County"
"16007" "Bear Lake County"
"16009" "Benewah County"
"16011" "Bingham County"
"16013" "Blaine County"
"16015" "Boise County"
"16017" "Bonner County"
"16019" "Bonneville County"
"16021" "Boundary County"
"16023" "Butte County"
"16025" "Camas County"
"16027" "Canyon County"
"16029" "Caribou County"
"16031" "Cassia County"
"16033" "Clark County"
"16035" "Clearwater County"
"16037" "Custer County"
"16039" "Elmore County"
"16041" "Franklin County"
"16043" "Fremont County"
"16045" "Gem County"
"16047" "Gooding County"
"16049" "Idaho County"
"16051" "Jefferson County"
"16053" "Jerome County"
"16055" "Kootenai County"
"16057" "Latah County"
"16059" "Lemhi County"
"16061" "Lewis County"
"16063" "Lincoln County"
"16065" "Madison County"
"16067" "Minidoka County"
"16069" "Nez Perce County"
"16071" "Oneida County"
"16073" "Owyhee County"
"16075" "Payette County"
"16077" "Power County"
"16079" "Shoshone County"
"16081" "Teton County"
"16083" "TPI:NAME:<NAME>END_PI Falls County"
"16085" "Valley County"
"16087" "Washington County"
"17" "Illinois"
"17001" "Adams County"
"17003" "Alexander County"
"17005" "Bond County"
"17007" "Boone County"
"17009" "Brown County"
"17011" "Bureau County"
"17013" "Calhoun County"
"17015" "Carroll County"
"17017" "Cass County"
"17019" "Champaign County"
"17021" "Christian County"
"17023" "Clark County"
"17025" "Clay County"
"17027" "Clinton County"
"17029" "Coles County"
"17031" "Cook County"
"17033" "Crawford County"
"17035" "Cumberland County"
"17037" "DeKalb County"
"17039" "De Witt County"
"17041" "Douglas County"
"17043" "DuPage County"
"17045" "Edgar County"
"17047" "Edwards County"
"17049" "Effingham County"
"17051" "Fayette County"
"17053" "Ford County"
"17055" "Franklin County"
"17057" "Fulton County"
"17059" "Gallatin County"
"17061" "Greene County"
"17063" "Grundy County"
"17065" "Hamilton County"
"17067" "Hancock County"
"17069" "Hardin County"
"17071" "Henderson County"
"17073" "Henry County"
"17075" "Iroquois County"
"17077" "PI:NAME:<NAME>END_PIson County"
"17079" "Jasper County"
"17081" "PI:NAME:<NAME>END_PIerson County"
"17083" "Jersey County"
"17085" "PI:NAME:<NAME>END_PI County"
"17087" "PI:NAME:<NAME>END_PIson County"
"17089" "Kane County"
"17091" "Kankakee County"
"17093" "Kendall County"
"17095" "Knox County"
"17097" "Lake County"
"17099" "LaSalle County"
"17101" "Lawrence County"
"17103" "Lee County"
"17105" "Livingston County"
"17107" "Logan County"
"17109" "McDonough County"
"17111" "McHenry County"
"17113" "McLean County"
"17115" "Macon County"
"17117" "Macoupin County"
"17119" "Madison County"
"17121" "Marion County"
"17123" "Marshall County"
"17125" "Mason County"
"17127" "Massac County"
"17129" "Menard County"
"17131" "Mercer County"
"17133" "Monroe County"
"17135" "Montgomery County"
"17137" "Morgan County"
"17139" "Moultrie County"
"17141" "Ogle County"
"17143" "Peoria County"
"17145" "Perry County"
"17147" "Piatt County"
"17149" "Pike County"
"17151" "Pope County"
"17153" "Pulaski County"
"17155" "Putnam County"
"17157" "Randolph County"
"17159" "Richland County"
"17161" "Rock Island County"
"17163" "St. Clair County"
"17165" "Saline County"
"17167" "Sangamon County"
"17169" "Schuyler County"
"17171" "Scott County"
"17173" "Shelby County"
"17175" "Stark County"
"17177" "Stephenson County"
"17179" "Tazewell County"
"17181" "Union County"
"17183" "Vermilion County"
"17185" "Wabash County"
"17187" "Warren County"
"17189" "Washington County"
"17191" "Wayne County"
"17193" "White County"
"17195" "Whiteside County"
"17197" "Will County"
"17199" "Williamson County"
"17201" "Winnebago County"
"17203" "Woodford County"
"18" "Indiana"
"18001" "Adams County"
"18003" "Allen County"
"18005" "Bartholomew County"
"18007" "Benton County"
"18009" "Blackford County"
"18011" "Boone County"
"18013" "Brown County"
"18015" "Carroll County"
"18017" "Cass County"
"18019" "Clark County"
"18021" "Clay County"
"18023" "Clinton County"
"18025" "Crawford County"
"18027" "Daviess County"
"18029" "Dearborn County"
"18031" "Decatur County"
"18033" "DeKalb County"
"18035" "Delaware County"
"18037" "Dubois County"
"18039" "Elkhart County"
"18041" "Fayette County"
"18043" "Floyd County"
"18045" "Fountain County"
"18047" "Franklin County"
"18049" "Fulton County"
"18051" "Gibson County"
"18053" "Grant County"
"18055" "Greene County"
"18057" "Hamilton County"
"18059" "Hancock County"
"18061" "Harrison County"
"18063" "Hendricks County"
"18065" "Henry County"
"18067" "Howard County"
"18069" "Huntington County"
"18071" "PI:NAME:<NAME>END_PI County"
"18073" "Jasper County"
"18075" "Jay County"
"18077" "PI:NAME:<NAME>END_PIefferson County"
"18079" "Jennings County"
"18081" "Johnson County"
"18083" "Knox County"
"18085" "Kosciusko County"
"18087" "LaGrange County"
"18089" "Lake County"
"18091" "LaPorte County"
"18093" "Lawrence County"
"18095" "Madison County"
"18097" "Marion County"
"18099" "Marshall County"
"18101" "PI:NAME:<NAME>END_PIin County"
"18103" "Miami County"
"18105" "Monroe County"
"18107" "Montgomery County"
"18109" "Morgan County"
"18111" "Newton County"
"18113" "Noble County"
"18115" "Ohio County"
"18117" "Orange County"
"18119" "Owen County"
"18121" "Parke County"
"18123" "Perry County"
"18125" "Pike County"
"18127" "Porter County"
"18129" "Posey County"
"18131" "Pulaski County"
"18133" "Putnam County"
"18135" "Randolph County"
"18137" "Ripley County"
"18139" "Rush County"
"18141" "St. Joseph County"
"18143" "PI:NAME:<NAME>END_PIcott County"
"18145" "Shelby County"
"18147" "Spencer County"
"18149" "Starke County"
"18151" "Steuben County"
"18153" "Sullivan County"
"18155" "Switzerland County"
"18157" "Tippecanoe County"
"18159" "Tipton County"
"18161" "Union County"
"18163" "Vanderburgh County"
"18165" "Vermillion County"
"18167" "Vigo County"
"18169" "Wabash County"
"18171" "Warren County"
"18173" "Warrick County"
"18175" "Washington County"
"18177" "Wayne County"
"18179" "Wells County"
"18181" "White County"
"18183" "Whitley County"
"19" "Iowa"
"19001" "Adair County"
"19003" "Adams County"
"19005" "Allamakee County"
"19007" "Appanoose County"
"19009" "Audubon County"
"19011" "Benton County"
"19013" "Black Hawk County"
"19015" "Boone County"
"19017" "Bremer County"
"19019" "Buchanan County"
"19021" "Buena Vista County"
"19023" "Butler County"
"19025" "Calhoun County"
"19027" "Carroll County"
"19029" "Cass County"
"19031" "Cedar County"
"19033" "Cerro Gordo County"
"19035" "Cherokee County"
"19037" "Chickasaw County"
"19039" "Clarke County"
"19041" "Clay County"
"19043" "Clayton County"
"19045" "Clinton County"
"19047" "Crawford County"
"19049" "Dallas County"
"19051" "Davis County"
"19053" "Decatur County"
"19055" "Delaware County"
"19057" "Des Moines County"
"19059" "Dickinson County"
"19061" "Dubuque County"
"19063" "Emmet County"
"19065" "Fayette County"
"19067" "Floyd County"
"19069" "Franklin County"
"19071" "Fremont County"
"19073" "Greene County"
"19075" "Grundy County"
"19077" "Guthrie County"
"19079" "Hamilton County"
"19081" "Hancock County"
"19083" "Hardin County"
"19085" "Harrison County"
"19087" "Henry County"
"19089" "Howard County"
"19091" "Humboldt County"
"19093" "Ida County"
"19095" "Iowa County"
"19097" "PI:NAME:<NAME>END_PIson County"
"19099" "Jasper County"
"19101" "PI:NAME:<NAME>END_PIefferson County"
"19103" "PI:NAME:<NAME>END_PIson County"
"19105" "Jones County"
"19107" "Keokuk County"
"19109" "Kossuth County"
"19111" "Lee County"
"19113" "Linn County"
"19115" "Louisa County"
"19117" "Lucas County"
"19119" "Lyon County"
"19121" "Madison County"
"19123" "Mahaska County"
"19125" "Marion County"
"19127" "Marshall County"
"19129" "Mills County"
"19131" "Mitchell County"
"19133" "Monona County"
"19135" "Monroe County"
"19137" "Montgomery County"
"19139" "Muscatine County"
"19141" "O'Brien County"
"19143" "Osceola County"
"19145" "Page County"
"19147" "Palo Alto County"
"19149" "Plymouth County"
"19151" "Pocahontas County"
"19153" "Polk County"
"19155" "Pottawattamie County"
"19157" "Poweshiek County"
"19159" "Ringgold County"
"19161" "Sac County"
"19163" "Scott County"
"19165" "Shelby County"
"19167" "Sioux County"
"19169" "Story County"
"19171" "Tama County"
"19173" "Taylor County"
"19175" "Union County"
"19177" "PI:NAME:<NAME>END_PI Buren County"
"19179" "Wapello County"
"19181" "Warren County"
"19183" "Washington County"
"19185" "Wayne County"
"19187" "Webster County"
"19189" "Winnebago County"
"19191" "Winneshiek County"
"19193" "Woodbury County"
"19195" "Worth County"
"19197" "Wright County"
"20" "Kansas"
"20001" "Allen County"
"20003" "Anderson County"
"20005" "Atchison County"
"20007" "Barber County"
"20009" "Barton County"
"20011" "Bourbon County"
"20013" "Brown County"
"20015" "Butler County"
"20017" "Chase County"
"20019" "Chautauqua County"
"20021" "Cherokee County"
"20023" "Cheyenne County"
"20025" "Clark County"
"20027" "Clay County"
"20029" "Cloud County"
"20031" "Coffey County"
"20033" "Comanche County"
"20035" "Cowley County"
"20037" "Crawford County"
"20039" "Decatur County"
"20041" "Dickinson County"
"20043" "Doniphan County"
"20045" "Douglas County"
"20047" "Edwards County"
"20049" "Elk County"
"20051" "Ellis County"
"20053" "Ellsworth County"
"20055" "Finney County"
"20057" "Ford County"
"20059" "Franklin County"
"20061" "Geary County"
"20063" "Gove County"
"20065" "Graham County"
"20067" "Grant County"
"20069" "Gray County"
"20071" "Greeley County"
"20073" "Greenwood County"
"20075" "Hamilton County"
"20077" "Harper County"
"20079" "Harvey County"
"20081" "Haskell County"
"20083" "Hodgeman County"
"20085" "PI:NAME:<NAME>END_PIson County"
"20087" "Jefferson County"
"20089" "Jewell County"
"20091" "PI:NAME:<NAME>END_PIson County"
"20093" "Kearny County"
"20095" "Kingman County"
"20097" "Kiowa County"
"20099" "Labette County"
"20101" "Lane County"
"20103" "Leavenworth County"
"20105" "Lincoln County"
"20107" "Linn County"
"20109" "Logan County"
"20111" "Lyon County"
"20113" "McPherson County"
"20115" "Marion County"
"20117" "Marshall County"
"20119" "Meade County"
"20121" "Miami County"
"20123" "Mitchell County"
"20125" "Montgomery County"
"20127" "Morris County"
"20129" "Morton County"
"20131" "Nemaha County"
"20133" "Neosho County"
"20135" "Ness County"
"20137" "Norton County"
"20139" "Osage County"
"20141" "Osborne County"
"20143" "Ottawa County"
"20145" "Pawnee County"
"20147" "Phillips County"
"20149" "Pottawatomie County"
"20151" "Pratt County"
"20153" "Rawlins County"
"20155" "Reno County"
"20157" "Republic County"
"20159" "Rice County"
"20161" "Riley County"
"20163" "Rooks County"
"20165" "Rush County"
"20167" "Russell County"
"20169" "Saline County"
"20171" "Scott County"
"20173" "Sedgwick County"
"20175" "Seward County"
"20177" "Shawnee County"
"20179" "Sheridan County"
"20181" "Sherman County"
"20183" "Smith County"
"20185" "Stafford County"
"20187" "Stanton County"
"20189" "Stevens County"
"20191" "Sumner County"
"20193" "Thomas County"
"20195" "Trego County"
"20197" "Wabaunsee County"
"20199" "Wallace County"
"20201" "Washington County"
"20203" "Wichita County"
"20205" "Wilson County"
"20207" "Woodson County"
"20209" "Wyandotte County"
"21" "Kentucky"
"21001" "Adair County"
"21003" "Allen County"
"21005" "Anderson County"
"21007" "Ballard County"
"21009" "Barren County"
"21011" "Bath County"
"21013" "Bell County"
"21015" "Boone County"
"21017" "Bourbon County"
"21019" "Boyd County"
"21021" "Boyle County"
"21023" "Bracken County"
"21025" "Breathitt County"
"21027" "Breckinridge County"
"21029" "Bullitt County"
"21031" "Butler County"
"21033" "Caldwell County"
"21035" "Calloway County"
"21037" "Campbell County"
"21039" "Carlisle County"
"21041" "Carroll County"
"21043" "Carter County"
"21045" "Casey County"
"21047" "Christian County"
"21049" "Clark County"
"21051" "Clay County"
"21053" "Clinton County"
"21055" "Crittenden County"
"21057" "Cumberland County"
"21059" "Daviess County"
"21061" "Edmonson County"
"21063" "Elliott County"
"21065" "Estill County"
"21067" "Fayette County"
"21069" "Fleming County"
"21071" "Floyd County"
"21073" "Franklin County"
"21075" "Fulton County"
"21077" "Gallatin County"
"21079" "Garrard County"
"21081" "Grant County"
"21083" "Graves County"
"21085" "Grayson County"
"21087" "Green County"
"21089" "Greenup County"
"21091" "Hancock County"
"21093" "Hardin County"
"21095" "Harlan County"
"21097" "Harrison County"
"21099" "Hart County"
"21101" "Henderson County"
"21103" "Henry County"
"21105" "Hickman County"
"21107" "Hopkins County"
"21109" "PI:NAME:<NAME>END_PIson County"
"21111" "PI:NAME:<NAME>END_PIerson County"
"21113" "Jessamine County"
"21115" "PI:NAME:<NAME>END_PIson County"
"21117" "Kenton County"
"21119" "Knott County"
"21121" "Knox County"
"21123" "Larue County"
"21125" "Laurel County"
"21127" "Lawrence County"
"21129" "Lee County"
"21131" "Leslie County"
"21133" "Letcher County"
"21135" "Lewis County"
"21137" "Lincoln County"
"21139" "Livingston County"
"21141" "Logan County"
"21143" "Lyon County"
"21145" "McCracken County"
"21147" "McCreary County"
"21149" "McLean County"
"21151" "Madison County"
"21153" "Magoffin County"
"21155" "Marion County"
"21157" "Marshall County"
"21159" "Martin County"
"21161" "Mason County"
"21163" "Meade County"
"21165" "Menifee County"
"21167" "Mercer County"
"21169" "Metcalfe County"
"21171" "Monroe County"
"21173" "Montgomery County"
"21175" "Morgan County"
"21177" "Muhlenberg County"
"21179" "PI:NAME:<NAME>END_PIelson County"
"21181" "Nicholas County"
"21183" "Ohio County"
"21185" "Oldham County"
"21187" "Owen County"
"21189" "Owsley County"
"21191" "Pendleton County"
"21193" "Perry County"
"21195" "Pike County"
"21197" "Powell County"
"21199" "Pulaski County"
"21201" "PI:NAME:<NAME>END_PI County"
"21203" "Rockcastle County"
"21205" "Rowan County"
"21207" "PI:NAME:<NAME>END_PIussell County"
"21209" "SPI:NAME:<NAME>END_PI County"
"21211" "Shelby County"
"21213" "PI:NAME:<NAME>END_PI County"
"21215" "PI:NAME:<NAME>END_PIcer County"
"21217" "Taylor County"
"21219" "PI:NAME:<NAME>END_PI County"
"21221" "Trigg County"
"21223" "Trimble County"
"21225" "Union County"
"21227" "Warren County"
"21229" "Washington County"
"21231" "Wayne County"
"21233" "Webster County"
"21235" "Whitley County"
"21237" "Wolfe County"
"21239" "Woodford County"
"22" "Louisiana"
"22001" "Acadia Parish"
"22003" "Allen Parish"
"22005" "Ascension Parish"
"22007" "Assumption Parish"
"22009" "Avoyelles Parish"
"22011" "Beauregard Parish"
"22013" "Bienville Parish"
"22015" "Bossier Parish"
"22017" "Caddo Parish"
"22019" "PI:NAME:<NAME>END_PI Parish"
"22021" "Caldwell Parish"
"22023" "PI:NAME:<NAME>END_PI Parish"
"22025" "Catahoula Parish"
"22027" "Claiborne Parish"
"22029" "Concordia Parish"
"22031" "De Soto Parish"
"22033" "East Baton Rouge Parish"
"22035" "East Carroll Parish"
"22037" "East Feliciana Parish"
"22039" "Evangeline Parish"
"22041" "Franklin Parish"
"22043" "Grant Parish"
"22045" "Iberia Parish"
"22047" "Iberville Parish"
"22049" "PI:NAME:<NAME>END_PI Parish"
"22051" "PI:NAME:<NAME>END_PI Parish"
"22053" "PI:NAME:<NAME>END_PI"
"22055" "Lafayette Parish"
"22057" "Lafourche Parish"
"22059" "LaSalle Parish"
"22061" "PI:NAME:<NAME>END_PI"
"22063" "Livingston Parish"
"22065" "Madison Parish"
"22067" "Morehouse Parish"
"22069" "Natchitoches Parish"
"22071" "Orleans Parish"
"22073" "Ouachita Parish"
"22075" "Plaquemines Parish"
"22077" "Pointe Coupee Parish"
"22079" "Rapides Parish"
"22081" "Red River Parish"
"22083" "Richland Parish"
"22085" "Sabine Parish"
"22087" "St. Bernard Parish"
"22089" "St. Charles Parish"
"22091" "St. Helena Parish"
"22093" "St. James Parish"
"22095" "St. John the Baptist Parish"
"22097" "St. Landry Parish"
"22099" "St. Martin Parish"
"22101" "St. Mary Parish"
"22103" "St. Tammany Parish"
"22105" "Tangipahoa Parish"
"22107" "Tensas Parish"
"22109" "Terrebonne Parish"
"22111" "Union Parish"
"22113" "Vermilion Parish"
"22115" "Vernon Parish"
"22117" "Washington Parish"
"22119" "Webster Parish"
"22121" "West Baton Rouge Parish"
"22123" "West Carroll Parish"
"22125" "West Feliciana Parish"
"22127" "Winn Parish"
"23" "Maine"
"23001" "Androscoggin County"
"23003" "Aroostook County"
"23005" "Cumberland County"
"23007" "Franklin County"
"23009" "Hancock County"
"23011" "Kennebec County"
"23013" "Knox County"
"23015" "Lincoln County"
"23017" "Oxford County"
"23019" "Penobscot County"
"23021" "Piscataquis County"
"23023" "Sagadahoc County"
"23025" "Somerset County"
"23027" "Waldo County"
"23029" "Washington County"
"23031" "York County"
"24" "Maryland"
"24001" "Allegany County"
"24003" "Anne Arundel County"
"24005" "Baltimore County"
"24009" "Calvert County"
"24011" "Caroline County"
"24013" "Carroll County"
"24015" "Cecil County"
"24017" "Charles County"
"24019" "Dorchester County"
"24021" "Frederick County"
"24023" "Garrett County"
"24025" "Harford County"
"24027" "Howard County"
"24029" "Kent County"
"24031" "Montgomery County"
"24033" "Prince George's County"
"24035" "Queen Anne's County"
"24037" "St. Mary's County"
"24039" "Somerset County"
"24041" "Talbot County"
"24043" "Washington County"
"24045" "Wicomico County"
"24047" "Worcester County"
"24510" "Baltimore city"
"25" "Massachusetts"
"25001" "Barnstable County"
"25003" "Berkshire County"
"25005" "Bristol County"
"25007" "Dukes County"
"25009" "Essex County"
"25011" "Franklin County"
"25013" "Hampden County"
"25015" "Hampshire County"
"25017" "Middlesex County"
"25019" "Nantucket County"
"25021" "Norfolk County"
"25023" "Plymouth County"
"25025" "Suffolk County"
"25027" "Worcester County"
"26" "Michigan"
"26001" "Alcona County"
"26003" "Alger County"
"26005" "Allegan County"
"26007" "Alpena County"
"26009" "Antrim County"
"26011" "Arenac County"
"26013" "Baraga County"
"26015" "Barry County"
"26017" "Bay County"
"26019" "Benzie County"
"26021" "Berrien County"
"26023" "Branch County"
"26025" "Calhoun County"
"26027" "Cass County"
"26029" "Charlevoix County"
"26031" "Cheboygan County"
"26033" "Chippewa County"
"26035" "Clare County"
"26037" "Clinton County"
"26039" "Crawford County"
"26041" "Delta County"
"26043" "Dickinson County"
"26045" "Eaton County"
"26047" "Emmet County"
"26049" "Genesee County"
"26051" "Gladwin County"
"26053" "Gogebic County"
"26055" "Grand Traverse County"
"26057" "Gratiot County"
"26059" "Hillsdale County"
"26061" "Houghton County"
"26063" "Huron County"
"26065" "Ingham County"
"26067" "Ionia County"
"26069" "Iosco County"
"26071" "Iron County"
"26073" "Isabella County"
"26075" "Jackson County"
"26077" "Kalamazoo County"
"26079" "Kalkaska County"
"26081" "Kent County"
"26083" "Keweenaw County"
"26085" "Lake County"
"26087" "Lapeer County"
"26089" "Leelanau County"
"26091" "Lenawee County"
"26093" "Livingston County"
"26095" "Luce County"
"26097" "Mackinac County"
"26099" "Macomb County"
"26101" "Manistee County"
"26103" "Marquette County"
"26105" "Mason County"
"26107" "Mecosta County"
"26109" "Menominee County"
"26111" "Midland County"
"26113" "Missaukee County"
"26115" "Monroe County"
"26117" "Montcalm County"
"26119" "Montmorency County"
"26121" "Muskegon County"
"26123" "Newaygo County"
"26125" "Oakland County"
"26127" "Oceana County"
"26129" "Ogemaw County"
"26131" "Ontonagon County"
"26133" "Osceola County"
"26135" "Oscoda County"
"26137" "Otsego County"
"26139" "Ottawa County"
"26141" "Presque Isle County"
"26143" "Roscommon County"
"26145" "Saginaw County"
"26147" "St. Clair County"
"26149" "St. Joseph County"
"26151" "Sanilac County"
"26153" "Schoolcraft County"
"26155" "Shiawassee County"
"26157" "Tuscola County"
"26159" "Van Buren County"
"26161" "Washtenaw County"
"26163" "Wayne County"
"26165" "Wexford County"
"27" "Minnesota"
"27001" "Aitkin County"
"27003" "Anoka County"
"27005" "Becker County"
"27007" "Beltrami County"
"27009" "Benton County"
"27011" "Big Stone County"
"27013" "Blue Earth County"
"27015" "Brown County"
"27017" "Carlton County"
"27019" "Carver County"
"27021" "Cass County"
"27023" "Chippewa County"
"27025" "Chisago County"
"27027" "Clay County"
"27029" "Clearwater County"
"27031" "Cook County"
"27033" "Cottonwood County"
"27035" "Crow Wing County"
"27037" "Dakota County"
"27039" "Dodge County"
"27041" "Douglas County"
"27043" "Faribault County"
"27045" "Fillmore County"
"27047" "Freeborn County"
"27049" "Goodhue County"
"27051" "Grant County"
"27053" "Hennepin County"
"27055" "Houston County"
"27057" "Hubbard County"
"27059" "Isanti County"
"27061" "Itasca County"
"27063" "Jackson County"
"27065" "Kanabec County"
"27067" "Kandiyohi County"
"27069" "Kittson County"
"27071" "Koochiching County"
"27073" "Lac qui Parle County"
"27075" "Lake County"
"27077" "Lake of the Woods County"
"27079" "Le Sueur County"
"27081" "Lincoln County"
"27083" "Lyon County"
"27085" "McLeod County"
"27087" "Mahnomen County"
"27089" "Marshall County"
"27091" "Martin County"
"27093" "Meeker County"
"27095" "Mille Lacs County"
"27097" "Morrison County"
"27099" "Mower County"
"27101" "Murray County"
"27103" "Nicollet County"
"27105" "Nobles County"
"27107" "Norman County"
"27109" "Olmsted County"
"27111" "Otter Tail County"
"27113" "Pennington County"
"27115" "Pine County"
"27117" "Pipestone County"
"27119" "Polk County"
"27121" "Pope County"
"27123" "Ramsey County"
"27125" "Red Lake County"
"27127" "Redwood County"
"27129" "Renville County"
"27131" "Rice County"
"27133" "Rock County"
"27135" "Roseau County"
"27137" "St. Louis County"
"27139" "Scott County"
"27141" "Sherburne County"
"27143" "Sibley County"
"27145" "Stearns County"
"27147" "Steele County"
"27149" "Stevens County"
"27151" "Swift County"
"27153" "Todd County"
"27155" "Traverse County"
"27157" "Wabasha County"
"27159" "Wadena County"
"27161" "Waseca County"
"27163" "Washington County"
"27165" "Watonwan County"
"27167" "Wilkin County"
"27169" "Winona County"
"27171" "Wright County"
"27173" "Yellow Medicine County"
"28" "Mississippi"
"28001" "Adams County"
"28003" "Alcorn County"
"28005" "Amite County"
"28007" "Attala County"
"28009" "Benton County"
"28011" "Bolivar County"
"28013" "Calhoun County"
"28015" "Carroll County"
"28017" "Chickasaw County"
"28019" "Choctaw County"
"28021" "Claiborne County"
"28023" "Clarke County"
"28025" "Clay County"
"28027" "Coahoma County"
"28029" "Copiah County"
"28031" "Covington County"
"28033" "DeSoto County"
"28035" "Forrest County"
"28037" "Franklin County"
"28039" "George County"
"28041" "Greene County"
"28043" "Grenada County"
"28045" "Hancock County"
"28047" "Harrison County"
"28049" "Hinds County"
"28051" "Holmes County"
"28053" "Humphreys County"
"28055" "Issaquena County"
"28057" "Itawamba County"
"28059" "Jackson County"
"28061" "Jasper County"
"28063" "JPI:NAME:<NAME>END_PIerson County"
"28065" "PI:NAME:<NAME>END_PI County"
"28067" "Jones County"
"28069" "Kemper County"
"28071" "Lafayette County"
"28073" "Lamar County"
"28075" "Lauderdale County"
"28077" "Lawrence County"
"28079" "Leake County"
"28081" "Lee County"
"28083" "Leflore County"
"28085" "Lincoln County"
"28087" "Lowndes County"
"28089" "Madison County"
"28091" "Marion County"
"28093" "Marshall County"
"28095" "Monroe County"
"28097" "Montgomery County"
"28099" "Neshoba County"
"28101" "Newton County"
"28103" "Noxubee County"
"28105" "Oktibbeha County"
"28107" "Panola County"
"28109" "Pearl River County"
"28111" "Perry County"
"28113" "Pike County"
"28115" "Pontotoc County"
"28117" "Prentiss County"
"28119" "Quitman County"
"28121" "PI:NAME:<NAME>END_PIin County"
"28123" "Scott County"
"28125" "Sharkey County"
"28127" "Simpson County"
"28129" "Smith County"
"28131" "Stone County"
"28133" "Sunflower County"
"28135" "Tallahatchie County"
"28137" "Tate County"
"28139" "Tippah County"
"28141" "Tishomingo County"
"28143" "Tunica County"
"28145" "Union County"
"28147" "Walthall County"
"28149" "Warren County"
"28151" "Washington County"
"28153" "Wayne County"
"28155" "Webster County"
"28157" "Wilkinson County"
"28159" "Winston County"
"28161" "Yalobusha County"
"28163" "Yazoo County"
"29" "Missouri"
"29001" "Adair County"
"29003" "Andrew County"
"29005" "Atchison County"
"29007" "Audrain County"
"29009" "Barry County"
"29011" "Barton County"
"29013" "Bates County"
"29015" "Benton County"
"29017" "Bollinger County"
"29019" "Boone County"
"29021" "Buchanan County"
"29023" "Butler County"
"29025" "Caldwell County"
"29027" "Callaway County"
"29029" "Camden County"
"29031" "Cape Girardeau County"
"29033" "Carroll County"
"29035" "Carter County"
"29037" "Cass County"
"29039" "Cedar County"
"29041" "Chariton County"
"29043" "Christian County"
"29045" "Clark County"
"29047" "Clay County"
"29049" "Clinton County"
"29051" "Cole County"
"29053" "Cooper County"
"29055" "Crawford County"
"29057" "Dade County"
"29059" "Dallas County"
"29061" "PI:NAME:<NAME>END_PI County"
"29063" "PI:NAME:<NAME>END_PI County"
"29065" "Dent County"
"29067" "Douglas County"
"29069" "Dunklin County"
"29071" "PI:NAME:<NAME>END_PIanklin County"
"29073" "Gasconade County"
"29075" "Gentry County"
"29077" "Greene County"
"29079" "Grundy County"
"29081" "Harrison County"
"29083" "Henry County"
"29085" "Hickory County"
"29087" "Holt County"
"29089" "Howard County"
"29091" "Howell County"
"29093" "Iron County"
"29095" "PI:NAME:<NAME>END_PIson County"
"29097" "Jasper County"
"29099" "PI:NAME:<NAME>END_PIerson County"
"29101" "PI:NAME:<NAME>END_PIson County"
"29103" "PI:NAME:<NAME>END_PI County"
"29105" "Laclede County"
"29107" "Lafayette County"
"29109" "Lawrence County"
"29111" "Lewis County"
"29113" "Lincoln County"
"29115" "Linn County"
"29117" "Livingston County"
"29119" "McDonald County"
"29121" "Macon County"
"29123" "Madison County"
"29125" "Maries County"
"29127" "Marion County"
"29129" "Mercer County"
"29131" "Miller County"
"29133" "Mississippi County"
"29135" "Moniteau County"
"29137" "Monroe County"
"29139" "Montgomery County"
"29141" "Morgan County"
"29143" "New Madrid County"
"29145" "Newton County"
"29147" "Nodaway County"
"29149" "Oregon County"
"29151" "Osage County"
"29153" "Ozark County"
"29155" "Pemiscot County"
"29157" "Perry County"
"29159" "Pettis County"
"29161" "Phelps County"
"29163" "Pike County"
"29165" "Platte County"
"29167" "Polk County"
"29169" "Pulaski County"
"29171" "Putnam County"
"29173" "Ralls County"
"29175" "Randolph County"
"29177" "Ray County"
"29179" "Reynolds County"
"29181" "Ripley County"
"29183" "St. Charles County"
"29185" "St. Clair County"
"29186" "Ste. Genevieve County"
"29187" "St. Francois County"
"29189" "St. Louis County"
"29195" "Saline County"
"29197" "Schuyler County"
"29199" "Scotland County"
"29201" "Scott County"
"29203" "Shannon County"
"29205" "Shelby County"
"29207" "Stoddard County"
"29209" "Stone County"
"29211" "Sullivan County"
"29213" "Taney County"
"29215" "Texas County"
"29217" "Vernon County"
"29219" "Warren County"
"29221" "Washington County"
"29223" "Wayne County"
"29225" "Webster County"
"29227" "Worth County"
"29229" "Wright County"
"29510" "St. Louis city"
"30" "Montana"
"30001" "Beaverhead County"
"30003" "Big Horn County"
"30005" "Blaine County"
"30007" "Broadwater County"
"30009" "Carbon County"
"30011" "Carter County"
"30013" "Cascade County"
"30015" "Chouteau County"
"30017" "Custer County"
"30019" "Daniels County"
"30021" "Dawson County"
"30023" "Deer Lodge County"
"30025" "Fallon County"
"30027" "Fergus County"
"30029" "Flathead County"
"30031" "Gallatin County"
"30033" "Garfield County"
"30035" "Glacier County"
"30037" "Golden Valley County"
"30039" "Granite County"
"30041" "Hill County"
"30043" "Jefferson County"
"30045" "Judith Basin County"
"30047" "Lake County"
"30049" "Lewis and Clark County"
"30051" "Liberty County"
"30053" "Lincoln County"
"30055" "McCone County"
"30057" "Madison County"
"30059" "Meagher County"
"30061" "Mineral County"
"30063" "Missoula County"
"30065" "Musselshell County"
"30067" "Park County"
"30069" "Petroleum County"
"30071" "Phillips County"
"30073" "Pondera County"
"30075" "Powder River County"
"30077" "Powell County"
"30079" "Prairie County"
"30081" "Ravalli County"
"30083" "Richland County"
"30085" "Roosevelt County"
"30087" "Rosebud County"
"30089" "Sanders County"
"30091" "Sheridan County"
"30093" "Silver Bow County"
"30095" "Stillwater County"
"30097" "Sweet Grass County"
"30099" "Teton County"
"30101" "Toole County"
"30103" "Treasure County"
"30105" "Valley County"
"30107" "Wheatland County"
"30109" "Wibaux County"
"30111" "Yellowstone County"
"31" "Nebraska"
"31001" "Adams County"
"31003" "Antelope County"
"31005" "Arthur County"
"31007" "Banner County"
"31009" "Blaine County"
"31011" "Boone County"
"31013" "Box Butte County"
"31015" "Boyd County"
"31017" "Brown County"
"31019" "Buffalo County"
"31021" "Burt County"
"31023" "Butler County"
"31025" "Cass County"
"31027" "Cedar County"
"31029" "Chase County"
"31031" "Cherry County"
"31033" "Cheyenne County"
"31035" "Clay County"
"31037" "Colfax County"
"31039" "Cuming County"
"31041" "Custer County"
"31043" "Dakota County"
"31045" "Dawes County"
"31047" "Dawson County"
"31049" "Deuel County"
"31051" "Dixon County"
"31053" "Dodge County"
"31055" "Douglas County"
"31057" "Dundy County"
"31059" "Fillmore County"
"31061" "Franklin County"
"31063" "Frontier County"
"31065" "Furnas County"
"31067" "Gage County"
"31069" "Garden County"
"31071" "Garfield County"
"31073" "Gosper County"
"31075" "Grant County"
"31077" "Greeley County"
"31079" "Hall County"
"31081" "Hamilton County"
"31083" "Harlan County"
"31085" "Hayes County"
"31087" "Hitchcock County"
"31089" "Holt County"
"31091" "Hooker County"
"31093" "Howard County"
"31095" "Jefferson County"
"31097" "Johnson County"
"31099" "Kearney County"
"31101" "Keith County"
"31103" "Keya Paha County"
"31105" "Kimball County"
"31107" "Knox County"
"31109" "Lancaster County"
"31111" "Lincoln County"
"31113" "Logan County"
"31115" "Loup County"
"31117" "McPherson County"
"31119" "Madison County"
"31121" "Merrick County"
"31123" "Morrill County"
"31125" "Nance County"
"31127" "Nemaha County"
"31129" "Nuckolls County"
"31131" "Otoe County"
"31133" "Pawnee County"
"31135" "Perkins County"
"31137" "Phelps County"
"31139" "Pierce County"
"31141" "Platte County"
"31143" "Polk County"
"31145" "Red Willow County"
"31147" "Richardson County"
"31149" "Rock County"
"31151" "Saline County"
"31153" "Sarpy County"
"31155" "Saunders County"
"31157" "Scotts Bluff County"
"31159" "Seward County"
"31161" "Sheridan County"
"31163" "Sherman County"
"31165" "Sioux County"
"31167" "Stanton County"
"31169" "Thayer County"
"31171" "Thomas County"
"31173" "Thurston County"
"31175" "Valley County"
"31177" "Washington County"
"31179" "Wayne County"
"31181" "Webster County"
"31183" "Wheeler County"
"31185" "York County"
"32" "Nevada"
"32001" "Churchill County"
"32003" "Clark County"
"32005" "Douglas County"
"32007" "Elko County"
"32009" "Esmeralda County"
"32011" "Eureka County"
"32013" "Humboldt County"
"32015" "Lander County"
"32017" "Lincoln County"
"32019" "Lyon County"
"32021" "Mineral County"
"32023" "Nye County"
"32027" "Pershing County"
"32029" "Storey County"
"32031" "Washoe County"
"32033" "White Pine County"
"32510" "Carson City"
"33" "New Hampshire"
"33001" "Belknap County"
"33003" "Carroll County"
"33005" "Cheshire County"
"33007" "Coos County"
"33009" "Grafton County"
"33011" "Hillsborough County"
"33013" "Merrimack County"
"33015" "Rockingham County"
"33017" "Strafford County"
"33019" "Sullivan County"
"34" "New Jersey"
"34001" "Atlantic County"
"34003" "Bergen County"
"34005" "Burlington County"
"34007" "Camden County"
"34009" "Cape May County"
"34011" "Cumberland County"
"34013" "Essex County"
"34015" "Gloucester County"
"34017" "Hudson County"
"34019" "Hunterdon County"
"34021" "Mercer County"
"34023" "Middlesex County"
"34025" "Monmouth County"
"34027" "Morris County"
"34029" "Ocean County"
"34031" "Passaic County"
"34033" "Salem County"
"34035" "Somerset County"
"34037" "Sussex County"
"34039" "Union County"
"34041" "Warren County"
"35" "New Mexico"
"35001" "Bernalillo County"
"35003" "Catron County"
"35005" "Chaves County"
"35006" "Cibola County"
"35007" "Colfax County"
"35009" "Curry County"
"35011" "De Baca County"
"35013" "Do\u00f1a Ana County"
"35015" "Eddy County"
"35017" "Grant County"
"35019" "Guadalupe County"
"35021" "Harding County"
"35023" "Hidalgo County"
"35025" "Lea County"
"35027" "Lincoln County"
"35028" "Los Alamos County"
"35029" "Luna County"
"35031" "McKinley County"
"35033" "Mora County"
"35035" "Otero County"
"35037" "Quay County"
"35039" "Rio Arriba County"
"35041" "Roosevelt County"
"35043" "Sandoval County"
"35045" "San Juan County"
"35047" "San Miguel County"
"35049" "Santa Fe County"
"35051" "Sierra County"
"35053" "Socorro County"
"35055" "Taos County"
"35057" "Torrance County"
"35059" "Union County"
"35061" "Valencia County"
"36" "New York"
"36001" "Albany County"
"36003" "Allegany County"
"36005" "Bronx County"
"36007" "Broome County"
"36009" "Cattaraugus County"
"36011" "Cayuga County"
"36013" "Chautauqua County"
"36015" "Chemung County"
"36017" "Chenango County"
"36019" "Clinton County"
"36021" "Columbia County"
"36023" "Cortland County"
"36025" "Delaware County"
"36027" "Dutchess County"
"36029" "Erie County"
"36031" "Essex County"
"36033" "Franklin County"
"36035" "Fulton County"
"36037" "Genesee County"
"36039" "Greene County"
"36041" "Hamilton County"
"36043" "Herkimer County"
"36045" "Jefferson County"
"36047" "Kings County"
"36049" "Lewis County"
"36051" "Livingston County"
"36053" "Madison County"
"36055" "Monroe County"
"36057" "Montgomery County"
"36059" "Nassau County"
"36061" "New York County"
"36063" "Niagara County"
"36065" "Oneida County"
"36067" "Onondaga County"
"36069" "Ontario County"
"36071" "Orange County"
"36073" "Orleans County"
"36075" "Oswego County"
"36077" "Otsego County"
"36079" "Putnam County"
"36081" "Queens County"
"36083" "Rensselaer County"
"36085" "Richmond County"
"36087" "Rockland County"
"36089" "St. Lawrence County"
"36091" "Saratoga County"
"36093" "Schenectady County"
"36095" "Schoharie County"
"36097" "Schuyler County"
"36099" "Seneca County"
"36101" "Steuben County"
"36103" "Suffolk County"
"36105" "Sullivan County"
"36107" "Tioga County"
"36109" "Tompkins County"
"36111" "Ulster County"
"36113" "Warren County"
"36115" "Washington County"
"36117" "Wayne County"
"36119" "Westchester County"
"36121" "Wyoming County"
"36123" "Yates County"
"37" "North Carolina"
"37001" "Alamance County"
"37003" "Alexander County"
"37005" "Alleghany County"
"37007" "Anson County"
"37009" "Ashe County"
"37011" "Avery County"
"37013" "Beaufort County"
"37015" "Bertie County"
"37017" "Bladen County"
"37019" "Brunswick County"
"37021" "Buncombe County"
"37023" "Burke County"
"37025" "Cabarrus County"
"37027" "Caldwell County"
"37029" "Camden County"
"37031" "Carteret County"
"37033" "Caswell County"
"37035" "Catawba County"
"37037" "Chatham County"
"37039" "Cherokee County"
"37041" "Chowan County"
"37043" "Clay County"
"37045" "Cleveland County"
"37047" "Columbus County"
"37049" "Craven County"
"37051" "Cumberland County"
"37053" "Currituck County"
"37055" "Dare County"
"37057" "Davidson County"
"37059" "Davie County"
"37061" "Duplin County"
"37063" "Durham County"
"37065" "Edgecombe County"
"37067" "Forsyth County"
"37069" "Franklin County"
"37071" "Gaston County"
"37073" "Gates County"
"37075" "Graham County"
"37077" "Granville County"
"37079" "Greene County"
"37081" "Guilford County"
"37083" "Halifax County"
"37085" "Harnett County"
"37087" "Haywood County"
"37089" "Henderson County"
"37091" "Hertford County"
"37093" "Hoke County"
"37095" "Hyde County"
"37097" "Iredell County"
"37099" "PI:NAME:<NAME>END_PIson County"
"37101" "Johnston County"
"37103" "Jones County"
"37105" "Lee County"
"37107" "Lenoir County"
"37109" "Lincoln County"
"37111" "McDowell County"
"37113" "Macon County"
"37115" "Madison County"
"37117" "Martin County"
"37119" "Mecklenburg County"
"37121" "Mitchell County"
"37123" "Montgomery County"
"37125" "Moore County"
"37127" "Nash County"
"37129" "New Hanover County"
"37131" "Northampton County"
"37133" "Onslow County"
"37135" "Orange County"
"37137" "Pamlico County"
"37139" "Pasquotank County"
"37141" "Pender County"
"37143" "Perquimans County"
"37145" "Person County"
"37147" "Pitt County"
"37149" "Polk County"
"37151" "Randolph County"
"37153" "Richmond County"
"37155" "Robeson County"
"37157" "Rockingham County"
"37159" "Rowan County"
"37161" "Rutherford County"
"37163" "Sampson County"
"37165" "Scotland County"
"37167" "Stanly County"
"37169" "Stokes County"
"37171" "Surry County"
"37173" "Swain County"
"37175" "Transylvania County"
"37177" "Tyrrell County"
"37179" "Union County"
"37181" "Vance County"
"37183" "Wake County"
"37185" "Warren County"
"37187" "Washington County"
"37189" "Watauga County"
"37191" "Wayne County"
"37193" "Wilkes County"
"37195" "Wilson County"
"37197" "Yadkin County"
"37199" "Yancey County"
"38" "North Dakota"
"38001" "Adams County"
"38003" "Barnes County"
"38005" "Benson County"
"38007" "Billings County"
"38009" "Bottineau County"
"38011" "Bowman County"
"38013" "Burke County"
"38015" "Burleigh County"
"38017" "Cass County"
"38019" "Cavalier County"
"38021" "Dickey County"
"38023" "Divide County"
"38025" "Dunn County"
"38027" "Eddy County"
"38029" "Emmons County"
"38031" "Foster County"
"38033" "Golden Valley County"
"38035" "Grand Forks County"
"38037" "Grant County"
"38039" "Griggs County"
"38041" "Hettinger County"
"38043" "Kidder County"
"38045" "LaMoure County"
"38047" "Logan County"
"38049" "McHenry County"
"38051" "McIntosh County"
"38053" "McKenzie County"
"38055" "McLean County"
"38057" "Mercer County"
"38059" "Morton County"
"38061" "Mountrail County"
"38063" "Nelson County"
"38065" "Oliver County"
"38067" "Pembina County"
"38069" "Pierce County"
"38071" "Ramsey County"
"38073" "Ransom County"
"38075" "Renville County"
"38077" "Richland County"
"38079" "Rolette County"
"38081" "Sargent County"
"38083" "Sheridan County"
"38085" "Sioux County"
"38087" "Slope County"
"38089" "Stark County"
"38091" "Steele County"
"38093" "Stutsman County"
"38095" "Towner County"
"38097" "Traill County"
"38099" "Walsh County"
"38101" "Ward County"
"38103" "Wells County"
"38105" "Williams County"
"39" "Ohio"
"39001" "Adams County"
"39003" "Allen County"
"39005" "Ashland County"
"39007" "Ashtabula County"
"39009" "Athens County"
"39011" "Auglaize County"
"39013" "Belmont County"
"39015" "Brown County"
"39017" "Butler County"
"39019" "Carroll County"
"39021" "Champaign County"
"39023" "Clark County"
"39025" "Clermont County"
"39027" "Clinton County"
"39029" "Columbiana County"
"39031" "Coshocton County"
"39033" "Crawford County"
"39035" "Cuyahoga County"
"39037" "Darke County"
"39039" "Defiance County"
"39041" "Delaware County"
"39043" "Erie County"
"39045" "Fairfield County"
"39047" "Fayette County"
"39049" "Franklin County"
"39051" "Fulton County"
"39053" "Gallia County"
"39055" "Geauga County"
"39057" "Greene County"
"39059" "Guernsey County"
"39061" "Hamilton County"
"39063" "Hancock County"
"39065" "Hardin County"
"39067" "Harrison County"
"39069" "Henry County"
"39071" "Highland County"
"39073" "Hocking County"
"39075" "Holmes County"
"39077" "Huron County"
"39079" "Jackson County"
"39081" "Jefferson County"
"39083" "Knox County"
"39085" "Lake County"
"39087" "Lawrence County"
"39089" "Licking County"
"39091" "Logan County"
"39093" "Lorain County"
"39095" "Lucas County"
"39097" "Madison County"
"39099" "Mahoning County"
"39101" "Marion County"
"39103" "Medina County"
"39105" "Meigs County"
"39107" "Mercer County"
"39109" "Miami County"
"39111" "Monroe County"
"39113" "Montgomery County"
"39115" "Morgan County"
"39117" "Morrow County"
"39119" "Muskingum County"
"39121" "Noble County"
"39123" "Ottawa County"
"39125" "Paulding County"
"39127" "Perry County"
"39129" "Pickaway County"
"39131" "Pike County"
"39133" "Portage County"
"39135" "Preble County"
"39137" "Putnam County"
"39139" "Richland County"
"39141" "Ross County"
"39143" "Sandusky County"
"39145" "Scioto County"
"39147" "Seneca County"
"39149" "Shelby County"
"39151" "Stark County"
"39153" "Summit County"
"39155" "Trumbull County"
"39157" "Tuscarawas County"
"39159" "Union County"
"39161" "Van Wert County"
"39163" "Vinton County"
"39165" "Warren County"
"39167" "Washington County"
"39169" "Wayne County"
"39171" "Williams County"
"39173" "Wood County"
"39175" "Wyandot County"
"40" "Oklahoma"
"40001" "Adair County"
"40003" "Alfalfa County"
"40005" "Atoka County"
"40007" "Beaver County"
"40009" "Beckham County"
"40011" "Blaine County"
"40013" "Bryan County"
"40015" "Caddo County"
"40017" "Canadian County"
"40019" "Carter County"
"40021" "Cherokee County"
"40023" "Choctaw County"
"40025" "Cimarron County"
"40027" "Cleveland County"
"40029" "Coal County"
"40031" "Comanche County"
"40033" "Cotton County"
"40035" "Craig County"
"40037" "Creek County"
"40039" "Custer County"
"40041" "Delaware County"
"40043" "Dewey County"
"40045" "Ellis County"
"40047" "Garfield County"
"40049" "Garvin County"
"40051" "Grady County"
"40053" "Grant County"
"40055" "Greer County"
"40057" "Harmon County"
"40059" "Harper County"
"40061" "Haskell County"
"40063" "Hughes County"
"40065" "Jackson County"
"40067" "Jefferson County"
"40069" "Johnston County"
"40071" "Kay County"
"40073" "Kingfisher County"
"40075" "Kiowa County"
"40077" "Latimer County"
"40079" "Le Flore County"
"40081" "Lincoln County"
"40083" "Logan County"
"40085" "Love County"
"40087" "McClain County"
"40089" "McCurtain County"
"40091" "McIntosh County"
"40093" "Major County"
"40095" "Marshall County"
"40097" "Mayes County"
"40099" "Murray County"
"40101" "Muskogee County"
"40103" "Noble County"
"40105" "Nowata County"
"40107" "Okfuskee County"
"40109" "Oklahoma County"
"40111" "Okmulgee County"
"40113" "Osage County"
"40115" "Ottawa County"
"40117" "Pawnee County"
"40119" "Payne County"
"40121" "Pittsburg County"
"40123" "Pontotoc County"
"40125" "Pottawatomie County"
"40127" "Pushmataha County"
"40129" "Roger Mills County"
"40131" "Rogers County"
"40133" "Seminole County"
"40135" "Sequoyah County"
"40137" "Stephens County"
"40139" "Texas County"
"40141" "Tillman County"
"40143" "Tulsa County"
"40145" "Wagoner County"
"40147" "Washington County"
"40149" "Washita County"
"40151" "Woods County"
"40153" "Woodward County"
"41" "Oregon"
"41001" "Baker County"
"41003" "Benton County"
"41005" "Clackamas County"
"41007" "Clatsop County"
"41009" "Columbia County"
"41011" "Coos County"
"41013" "Crook County"
"41015" "Curry County"
"41017" "Deschutes County"
"41019" "Douglas County"
"41021" "Gilliam County"
"41023" "Grant County"
"41025" "Harney County"
"41027" "Hood River County"
"41029" "Jackson County"
"41031" "Jefferson County"
"41033" "Josephine County"
"41035" "Klamath County"
"41037" "Lake County"
"41039" "Lane County"
"41041" "Lincoln County"
"41043" "Linn County"
"41045" "Malheur County"
"41047" "Marion County"
"41049" "Morrow County"
"41051" "Multnomah County"
"41053" "Polk County"
"41055" "Sherman County"
"41057" "Tillamook County"
"41059" "Umatilla County"
"41061" "Union County"
"41063" "Wallowa County"
"41065" "Wasco County"
"41067" "Washington County"
"41069" "Wheeler County"
"41071" "Yamhill County"
"42" "Pennsylvania"
"42001" "Adams County"
"42003" "Allegheny County"
"42005" "Armstrong County"
"42007" "Beaver County"
"42009" "Bedford County"
"42011" "Berks County"
"42013" "Blair County"
"42015" "Bradford County"
"42017" "Bucks County"
"42019" "Butler County"
"42021" "Cambria County"
"42023" "Cameron County"
"42025" "Carbon County"
"42027" "Centre County"
"42029" "Chester County"
"42031" "Clarion County"
"42033" "Clearfield County"
"42035" "Clinton County"
"42037" "Columbia County"
"42039" "Crawford County"
"42041" "Cumberland County"
"42043" "Dauphin County"
"42045" "Delaware County"
"42047" "Elk County"
"42049" "Erie County"
"42051" "Fayette County"
"42053" "Forest County"
"42055" "Franklin County"
"42057" "Fulton County"
"42059" "Greene County"
"42061" "Huntingdon County"
"42063" "Indiana County"
"42065" "Jefferson County"
"42067" "Juniata County"
"42069" "Lackawanna County"
"42071" "Lancaster County"
"42073" "Lawrence County"
"42075" "Lebanon County"
"42077" "Lehigh County"
"42079" "Luzerne County"
"42081" "Lycoming County"
"42083" "McKean County"
"42085" "Mercer County"
"42087" "Mifflin County"
"42089" "Monroe County"
"42091" "Montgomery County"
"42093" "Montour County"
"42095" "Northampton County"
"42097" "Northumberland County"
"42099" "Perry County"
"42101" "Philadelphia County"
"42103" "Pike County"
"42105" "Potter County"
"42107" "Schuylkill County"
"42109" "Snyder County"
"42111" "Somerset County"
"42113" "Sullivan County"
"42115" "Susquehanna County"
"42117" "Tioga County"
"42119" "Union County"
"42121" "Venango County"
"42123" "Warren County"
"42125" "Washington County"
"42127" "Wayne County"
"42129" "Westmoreland County"
"42131" "Wyoming County"
"42133" "York County"
"44" "Rhode Island"
"44001" "Bristol County"
"44003" "Kent County"
"44005" "Newport County"
"44007" "Providence County"
"44009" "Washington County"
"45" "South Carolina"
"45001" "Abbeville County"
"45003" "Aiken County"
"45005" "Allendale County"
"45007" "Anderson County"
"45009" "Bamberg County"
"45011" "Barnwell County"
"45013" "Beaufort County"
"45015" "Berkeley County"
"45017" "Calhoun County"
"45019" "Charleston County"
"45021" "Cherokee County"
"45023" "Chester County"
"45025" "Chesterfield County"
"45027" "Clarendon County"
"45029" "Colleton County"
"45031" "Darlington County"
"45033" "Dillon County"
"45035" "Dorchester County"
"45037" "Edgefield County"
"45039" "Fairfield County"
"45041" "Florence County"
"45043" "Georgetown County"
"45045" "Greenville County"
"45047" "Greenwood County"
"45049" "Hampton County"
"45051" "Horry County"
"45053" "Jasper County"
"45055" "Kershaw County"
"45057" "Lancaster County"
"45059" "Laurens County"
"45061" "Lee County"
"45063" "Lexington County"
"45065" "McCormick County"
"45067" "Marion County"
"45069" "Marlboro County"
"45071" "Newberry County"
"45073" "Oconee County"
"45075" "Orangeburg County"
"45077" "Pickens County"
"45079" "Richland County"
"45081" "Saluda County"
"45083" "Spartanburg County"
"45085" "Sumter County"
"45087" "Union County"
"45089" "Williamsburg County"
"45091" "York County"
"46" "South Dakota"
"46003" "Aurora County"
"46005" "Beadle County"
"46007" "Bennett County"
"46009" "Bon Homme County"
"46011" "Brookings County"
"46013" "Brown County"
"46015" "Brule County"
"46017" "Buffalo County"
"46019" "Butte County"
"46021" "Campbell County"
"46023" "Charles Mix County"
"46025" "Clark County"
"46027" "Clay County"
"46029" "Codington County"
"46031" "Corson County"
"46033" "Custer County"
"46035" "Davison County"
"46037" "Day County"
"46039" "Deuel County"
"46041" "Dewey County"
"46043" "Douglas County"
"46045" "Edmunds County"
"46047" "Fall River County"
"46049" "Faulk County"
"46051" "Grant County"
"46053" "Gregory County"
"46055" "Haakon County"
"46057" "Hamlin County"
"46059" "Hand County"
"46061" "Hanson County"
"46063" "Harding County"
"46065" "Hughes County"
"46067" "Hutchinson County"
"46069" "Hyde County"
"46071" "Jackson County"
"46073" "Jerauld County"
"46075" "Jones County"
"46077" "Kingsbury County"
"46079" "Lake County"
"46081" "Lawrence County"
"46083" "PI:NAME:<NAME>END_PIcoln County"
"46085" "PI:NAME:<NAME>END_PI County"
"46087" "McCook County"
"46089" "PI:NAME:<NAME>END_PIerson County"
"46091" "Marshall County"
"46093" "Meade County"
"46095" "Mellette County"
"46097" "Miner County"
"46099" "Minnehaha County"
"46101" "Moody County"
"46102" "Oglala Lakota County"
"46103" "Pennington County"
"46105" "Perkins County"
"46107" "Potter County"
"46109" "PI:NAME:<NAME>END_PIerts County"
"46111" "Sanborn County"
"46115" "Spink County"
"46117" "Stanley County"
"46119" "PI:NAME:<NAME>END_PIully County"
"46121" "PI:NAME:<NAME>END_PIodd County"
"46123" "Tripp County"
"46125" "PI:NAME:<NAME>END_PIer County"
"46127" "Union County"
"46129" "Walworth County"
"46135" "Yankton County"
"46137" "Ziebach County"
"47" "Tennessee"
"47001" "Anderson County"
"47003" "Bedford County"
"47005" "Benton County"
"47007" "Bledsoe County"
"47009" "Blount County"
"47011" "Bradley County"
"47013" "Campbell County"
"47015" "Cannon County"
"47017" "Carroll County"
"47019" "Carter County"
"47021" "Cheatham County"
"47023" "Chester County"
"47025" "Claiborne County"
"47027" "Clay County"
"47029" "Cocke County"
"47031" "Coffee County"
"47033" "Crockett County"
"47035" "Cumberland County"
"47037" "PI:NAME:<NAME>END_PIson County"
"47039" "Decatur County"
"47041" "DeKalb County"
"47043" "Dickson County"
"47045" "Dyer County"
"47047" "Fayette County"
"47049" "Fentress County"
"47051" "Franklin County"
"47053" "Gibson County"
"47055" "Giles County"
"47057" "Grainger County"
"47059" "Greene County"
"47061" "Grundy County"
"47063" "Hamblen County"
"47065" "Hamilton County"
"47067" "Hancock County"
"47069" "Hardeman County"
"47071" "PI:NAME:<NAME>END_PI County"
"47073" "Hawkins County"
"47075" "Haywood County"
"47077" "Henderson County"
"47079" "Henry County"
"47081" "Hickman County"
"47083" "Houston County"
"47085" "Humphreys County"
"47087" "Jackson County"
"47089" "PI:NAME:<NAME>END_PIefferson County"
"47091" "Johnson County"
"47093" "Knox County"
"47095" "Lake County"
"47097" "Lauderdale County"
"47099" "Lawrence County"
"47101" "Lewis County"
"47103" "Lincoln County"
"47105" "Loudon County"
"47107" "McMinn County"
"47109" "McNairy County"
"47111" "Macon County"
"47113" "Madison County"
"47115" "Marion County"
"47117" "Marshall County"
"47119" "Maury County"
"47121" "Meigs County"
"47123" "Monroe County"
"47125" "Montgomery County"
"47127" "Moore County"
"47129" "Morgan County"
"47131" "Obion County"
"47133" "Overton County"
"47135" "Perry County"
"47137" "Pickett County"
"47139" "Polk County"
"47141" "Putnam County"
"47143" "Rhea County"
"47145" "Roane County"
"47147" "PI:NAME:<NAME>END_PIson County"
"47149" "Rutherford County"
"47151" "Scott County"
"47153" "Sequatchie County"
"47155" "Sevier County"
"47157" "Shelby County"
"47159" "Smith County"
"47161" "Stewart County"
"47163" "Sullivan County"
"47165" "Sumner County"
"47167" "Tipton County"
"47169" "Trousdale County"
"47171" "Unicoi County"
"47173" "Union County"
"47175" "PI:NAME:<NAME>END_PI County"
"47177" "Warren County"
"47179" "Washington County"
"47181" "Wayne County"
"47183" "Weakley County"
"47185" "White County"
"47187" "Williamson County"
"47189" "Wilson County"
"48" "Texas"
"48001" "Anderson County"
"48003" "Andrews County"
"48005" "Angelina County"
"48007" "Aransas County"
"48009" "Archer County"
"48011" "Armstrong County"
"48013" "Atascosa County"
"48015" "Austin County"
"48017" "Bailey County"
"48019" "Bandera County"
"48021" "Bastrop County"
"48023" "Baylor County"
"48025" "Bee County"
"48027" "Bell County"
"48029" "Bexar County"
"48031" "Blanco County"
"48033" "Borden County"
"48035" "Bosque County"
"48037" "Bowie County"
"48039" "Brazoria County"
"48041" "Brazos County"
"48043" "Brewster County"
"48045" "Briscoe County"
"48047" "Brooks County"
"48049" "Brown County"
"48051" "Burleson County"
"48053" "Burnet County"
"48055" "Caldwell County"
"48057" "Calhoun County"
"48059" "Callahan County"
"48061" "Cameron County"
"48063" "Camp County"
"48065" "Carson County"
"48067" "Cass County"
"48069" "Castro County"
"48071" "Chambers County"
"48073" "Cherokee County"
"48075" "Childress County"
"48077" "Clay County"
"48079" "Cochran County"
"48081" "Coke County"
"48083" "Coleman County"
"48085" "Collin County"
"48087" "Collingsworth County"
"48089" "Colorado County"
"48091" "Comal County"
"48093" "Comanche County"
"48095" "Concho County"
"48097" "Cooke County"
"48099" "Coryell County"
"48101" "Cottle County"
"48103" "Crane County"
"48105" "Crockett County"
"48107" "Crosby County"
"48109" "Culberson County"
"48111" "Dallam County"
"48113" "Dallas County"
"48115" "Dawson County"
"48117" "Deaf Smith County"
"48119" "Delta County"
"48121" "Denton County"
"48123" "DeWitt County"
"48125" "Dickens County"
"48127" "Dimmit County"
"48129" "Donley County"
"48131" "Duval County"
"48133" "Eastland County"
"48135" "PI:NAME:<NAME>END_PI County"
"48137" "PI:NAME:<NAME>END_PIwards County"
"48139" "Ellis County"
"48141" "PI:NAME:<NAME>END_PI Paso County"
"48143" "Erath County"
"48145" "Falls County"
"48147" "Fannin County"
"48149" "Fayette County"
"48151" "Fisher County"
"48153" "Floyd County"
"48155" "Foard County"
"48157" "Fort Bend County"
"48159" "Franklin County"
"48161" "Freestone County"
"48163" "Frio County"
"48165" "Gaines County"
"48167" "Galveston County"
"48169" "Garza County"
"48171" "Gillespie County"
"48173" "Glasscock County"
"48175" "Goliad County"
"48177" "PI:NAME:<NAME>END_PIonzales County"
"48179" "Gray County"
"48181" "PI:NAME:<NAME>END_PIson County"
"48183" "Gregg County"
"48185" "Grimes County"
"48187" "Guadalupe County"
"48189" "Hale County"
"48191" "Hall County"
"48193" "Hamilton County"
"48195" "Hansford County"
"48197" "Hardeman County"
"48199" "Hardin County"
"48201" "Harris County"
"48203" "Harrison County"
"48205" "Hartley County"
"48207" "Haskell County"
"48209" "Hays County"
"48211" "Hemphill County"
"48213" "PI:NAME:<NAME>END_PIerson County"
"48215" "PI:NAME:<NAME>END_PIalgo County"
"48217" "Hill County"
"48219" "Hockley County"
"48221" "Hood County"
"48223" "Hopkins County"
"48225" "Houston County"
"48227" "Howard County"
"48229" "PI:NAME:<NAME>END_PI County"
"48231" "Hunt County"
"48233" "Hutchinson County"
"48235" "PI:NAME:<NAME>END_PIion County"
"48237" "Jack County"
"48239" "PI:NAME:<NAME>END_PI County"
"48241" "JPI:NAME:<NAME>END_PI County"
"48243" "PI:NAME:<NAME>END_PI County"
"48245" "PI:NAME:<NAME>END_PIerson County"
"48247" "PI:NAME:<NAME>END_PI County"
"48249" "PI:NAME:<NAME>END_PI County"
"48251" "PI:NAME:<NAME>END_PIson County"
"48253" "Jones County"
"48255" "Karnes County"
"48257" "Kaufman County"
"48259" "Kendall County"
"48261" "Kenedy County"
"48263" "Kent County"
"48265" "Kerr County"
"48267" "Kimble County"
"48269" "King County"
"48271" "Kinney County"
"48273" "Kleberg County"
"48275" "Knox County"
"48277" "Lamar County"
"48279" "Lamb County"
"48281" "Lampasas County"
"48283" "La Salle County"
"48285" "Lavaca County"
"48287" "Lee County"
"48289" "Leon County"
"48291" "Liberty County"
"48293" "Limestone County"
"48295" "Lipscomb County"
"48297" "Live Oak County"
"48299" "Llano County"
"48301" "Loving County"
"48303" "Lubbock County"
"48305" "Lynn County"
"48307" "McCulloch County"
"48309" "McLennan County"
"48311" "McMullen County"
"48313" "Madison County"
"48315" "Marion County"
"48317" "Martin County"
"48319" "Mason County"
"48321" "Matagorda County"
"48323" "Maverick County"
"48325" "Medina County"
"48327" "Menard County"
"48329" "Midland County"
"48331" "Milam County"
"48333" "Mills County"
"48335" "Mitchell County"
"48337" "Montague County"
"48339" "Montgomery County"
"48341" "Moore County"
"48343" "Morris County"
"48345" "Motley County"
"48347" "Nacogdoches County"
"48349" "Navarro County"
"48351" "Newton County"
"48353" "Nolan County"
"48355" "Nueces County"
"48357" "Ochiltree County"
"48359" "Oldham County"
"48361" "Orange County"
"48363" "Palo Pinto County"
"48365" "Panola County"
"48367" "Parker County"
"48369" "Parmer County"
"48371" "Pecos County"
"48373" "Polk County"
"48375" "Potter County"
"48377" "Presidio County"
"48379" "Rains County"
"48381" "Randall County"
"48383" "Reagan County"
"48385" "Real County"
"48387" "Red River County"
"48389" "Reeves County"
"48391" "Refugio County"
"48393" "Roberts County"
"48395" "PI:NAME:<NAME>END_PIson County"
"48397" "Rockwall County"
"48399" "Runnels County"
"48401" "Rusk County"
"48403" "Sabine County"
"48405" "San Augustine County"
"48407" "San Jacinto County"
"48409" "San Patricio County"
"48411" "San Saba County"
"48413" "Schleicher County"
"48415" "Scurry County"
"48417" "Shackelford County"
"48419" "Shelby County"
"48421" "Sherman County"
"48423" "Smith County"
"48425" "Somervell County"
"48427" "Starr County"
"48429" "Stephens County"
"48431" "Sterling County"
"48433" "Stonewall County"
"48435" "Sutton County"
"48437" "Swisher County"
"48439" "Tarrant County"
"48441" "Taylor County"
"48443" "Terrell County"
"48445" "Terry County"
"48447" "Throckmorton County"
"48449" "Titus County"
"48451" "PI:NAME:<NAME>END_PI Green County"
"48453" "Travis County"
"48455" "Trinity County"
"48457" "Tyler County"
"48459" "Upshur County"
"48461" "Upton County"
"48463" "Uvalde County"
"48465" "Val Verde County"
"48467" "Van Zandt County"
"48469" "Victoria County"
"48471" "Walker County"
"48473" "Waller County"
"48475" "Ward County"
"48477" "Washington County"
"48479" "Webb County"
"48481" "Wharton County"
"48483" "Wheeler County"
"48485" "Wichita County"
"48487" "Wilbarger County"
"48489" "Willacy County"
"48491" "Williamson County"
"48493" "Wilson County"
"48495" "Winkler County"
"48497" "Wise County"
"48499" "Wood County"
"48501" "Yoakum County"
"48503" "Young County"
"48505" "Zapata County"
"48507" "Zavala County"
"49" "Utah"
"49001" "Beaver County"
"49003" "Box Elder County"
"49005" "Cache County"
"49007" "Carbon County"
"49009" "Daggett County"
"49011" "Davis County"
"49013" "Duchesne County"
"49015" "Emery County"
"49017" "Garfield County"
"49019" "Grand County"
"49021" "Iron County"
"49023" "Juab County"
"49025" "Kane County"
"49027" "Millard County"
"49029" "Morgan County"
"49031" "Piute County"
"49033" "Rich County"
"49035" "Salt Lake County"
"49037" "San Juan County"
"49039" "Sanpete County"
"49041" "Sevier County"
"49043" "Summit County"
"49045" "Tooele County"
"49047" "Uintah County"
"49049" "Utah County"
"49051" "Wasatch County"
"49053" "Washington County"
"49055" "Wayne County"
"49057" "Weber County"
"50" "Vermont"
"50001" "Addison County"
"50003" "Bennington County"
"50005" "Caledonia County"
"50007" "Chittenden County"
"50009" "Essex County"
"50011" "Franklin County"
"50013" "Grand Isle County"
"50015" "Lamoille County"
"50017" "Orange County"
"50019" "Orleans County"
"50021" "Rutland County"
"50023" "Washington County"
"50025" "Windham County"
"50027" "Windsor County"
"51" "Virginia"
"51001" "Accomack County"
"51003" "Albemarle County"
"51005" "Alleghany County"
"51007" "Amelia County"
"51009" "Amherst County"
"51011" "Appomattox County"
"51013" "Arlington County"
"51015" "Augusta County"
"51017" "Bath County"
"51019" "Bedford County"
"51021" "Bland County"
"51023" "Botetourt County"
"51025" "Brunswick County"
"51027" "Buchanan County"
"51029" "Buckingham County"
"51031" "Campbell County"
"51033" "Caroline County"
"51035" "Carroll County"
"51036" "Charles City County"
"51037" "Charlotte County"
"51041" "Chesterfield County"
"51043" "Clarke County"
"51045" "Craig County"
"51047" "Culpeper County"
"51049" "Cumberland County"
"51051" "Dickenson County"
"51053" "Dinwiddie County"
"51057" "Essex County"
"51059" "Fairfax County"
"51061" "Fauquier County"
"51063" "Floyd County"
"51065" "Fluvanna County"
"51067" "Franklin County"
"51069" "Frederick County"
"51071" "Giles County"
"51073" "Gloucester County"
"51075" "Goochland County"
"51077" "Grayson County"
"51079" "Greene County"
"51081" "Greensville County"
"51083" "Halifax County"
"51085" "Hanover County"
"51087" "Henrico County"
"51089" "Henry County"
"51091" "Highland County"
"51093" "Isle of Wight County"
"51095" "James City County"
"51097" "King and Queen County"
"51099" "King George County"
"51101" "King William County"
"51103" "Lancaster County"
"51105" "Lee County"
"51107" "Loudoun County"
"51109" "Louisa County"
"51111" "Lunenburg County"
"51113" "Madison County"
"51115" "Mathews County"
"51117" "Mecklenburg County"
"51119" "Middlesex County"
"51121" "Montgomery County"
"51125" "Nelson County"
"51127" "New Kent County"
"51131" "Northampton County"
"51133" "Northumberland County"
"51135" "Nottoway County"
"51137" "Orange County"
"51139" "Page County"
"51141" "Patrick County"
"51143" "Pittsylvania County"
"51145" "Powhatan County"
"51147" "Prince Edward County"
"51149" "Prince George County"
"51153" "Prince William County"
"51155" "Pulaski County"
"51157" "Rappahannock County"
"51159" "Richmond County"
"51161" "Roanoke County"
"51163" "Rockbridge County"
"51165" "Rockingham County"
"51167" "Russell County"
"51169" "Scott County"
"51171" "Shenandoah County"
"51173" "Smyth County"
"51175" "Southampton County"
"51177" "Spotsylvania County"
"51179" "Stafford County"
"51181" "Surry County"
"51183" "Sussex County"
"51185" "Tazewell County"
"51187" "Warren County"
"51191" "Washington County"
"51193" "Westmoreland County"
"51195" "Wise County"
"51197" "Wythe County"
"51199" "York County"
"51510" "Alexandria city"
"51520" "Bristol city"
"51530" "Buena Vista city"
"51540" "Charlottesville city"
"51550" "Chesapeake city"
"51570" "Colonial Heights city"
"51580" "Covington city"
"51590" "Danville city"
"51595" "Emporia city"
"51600" "Fairfax city"
"51610" "Falls Church city"
"51620" "Franklin city"
"51630" "Fredericksburg city"
"51640" "Galax city"
"51650" "Hampton city"
"51660" "Harrisonburg city"
"51670" "Hopewell city"
"51678" "Lexington city"
"51680" "Lynchburg city"
"51683" "Manassas city"
"51685" "Manassas Park city"
"51690" "Martinsville city"
"51700" "Newport News city"
"51710" "Norfolk city"
"51720" "Norton city"
"51730" "Petersburg city"
"51735" "Poquoson city"
"51740" "Portsmouth city"
"51750" "Radford city"
"51760" "Richmond city"
"51770" "Roanoke city"
"51775" "Salem city"
"51790" "Staunton city"
"51800" "Suffolk city"
"51810" "Virginia Beach city"
"51820" "Waynesboro city"
"51830" "Williamsburg city"
"51840" "Winchester city"
"53" "Washington"
"53001" "Adams County"
"53003" "Asotin County"
"53005" "Benton County"
"53007" "Chelan County"
"53009" "Clallam County"
"53011" "Clark County"
"53013" "Columbia County"
"53015" "Cowlitz County"
"53017" "Douglas County"
"53019" "Ferry County"
"53021" "Franklin County"
"53023" "Garfield County"
"53025" "Grant County"
"53027" "Grays Harbor County"
"53029" "Island County"
"53031" "Jefferson County"
"53033" "King County"
"53035" "Kitsap County"
"53037" "Kittitas County"
"53039" "Klickitat County"
"53041" "Lewis County"
"53043" "Lincoln County"
"53045" "Mason County"
"53047" "Okanogan County"
"53049" "Pacific County"
"53051" "Pend Oreille County"
"53053" "Pierce County"
"53055" "San Juan County"
"53057" "Skagit County"
"53059" "Skamania County"
"53061" "Snohomish County"
"53063" "Spokane County"
"53065" "Stevens County"
"53067" "Thurston County"
"53069" "Wahkiakum County"
"53071" "Walla Walla County"
"53073" "Whatcom County"
"53075" "Whitman County"
"53077" "Yakima County"
"54" "West Virginia"
"54001" "Barbour County"
"54003" "Berkeley County"
"54005" "Boone County"
"54007" "Braxton County"
"54009" "Brooke County"
"54011" "Cabell County"
"54013" "Calhoun County"
"54015" "Clay County"
"54017" "Doddridge County"
"54019" "Fayette County"
"54021" "Gilmer County"
"54023" "Grant County"
"54025" "Greenbrier County"
"54027" "Hampshire County"
"54029" "Hancock County"
"54031" "Hardy County"
"54033" "Harrison County"
"54035" "Jackson County"
"54037" "Jefferson County"
"54039" "Kanawha County"
"54041" "Lewis County"
"54043" "Lincoln County"
"54045" "Logan County"
"54047" "McDowell County"
"54049" "Marion County"
"54051" "Marshall County"
"54053" "Mason County"
"54055" "Mercer County"
"54057" "Mineral County"
"54059" "Mingo County"
"54061" "Monongalia County"
"54063" "Monroe County"
"54065" "Morgan County"
"54067" "Nicholas County"
"54069" "Ohio County"
"54071" "Pendleton County"
"54073" "Pleasants County"
"54075" "Pocahontas County"
"54077" "Preston County"
"54079" "Putnam County"
"54081" "Raleigh County"
"54083" "Randolph County"
"54085" "Ritchie County"
"54087" "Roane County"
"54089" "Summers County"
"54091" "Taylor County"
"54093" "Tucker County"
"54095" "Tyler County"
"54097" "Upshur County"
"54099" "Wayne County"
"54101" "Webster County"
"54103" "Wetzel County"
"54105" "Wirt County"
"54107" "Wood County"
"54109" "Wyoming County"
"55" "Wisconsin"
"55001" "Adams County"
"55003" "Ashland County"
"55005" "Barron County"
"55007" "Bayfield County"
"55009" "Brown County"
"55011" "Buffalo County"
"55013" "Burnett County"
"55015" "Calumet County"
"55017" "Chippewa County"
"55019" "Clark County"
"55021" "Columbia County"
"55023" "Crawford County"
"55025" "Dane County"
"55027" "Dodge County"
"55029" "Door County"
"55031" "Douglas County"
"55033" "Dunn County"
"55035" "Eau Claire County"
"55037" "Florence County"
"55039" "Fond du Lac County"
"55041" "Forest County"
"55043" "Grant County"
"55045" "Green County"
"55047" "Green Lake County"
"55049" "Iowa County"
"55051" "Iron County"
"55053" "Jackson County"
"55055" "Jefferson County"
"55057" "Juneau County"
"55059" "Kenosha County"
"55061" "Kewaunee County"
"55063" "La Crosse County"
"55065" "Lafayette County"
"55067" "Langlade County"
"55069" "Lincoln County"
"55071" "Manitowoc County"
"55073" "Marathon County"
"55075" "Marinette County"
"55077" "Marquette County"
"55078" "Menominee County"
"55079" "Milwaukee County"
"55081" "Monroe County"
"55083" "Oconto County"
"55085" "Oneida County"
"55087" "Outagamie County"
"55089" "Ozaukee County"
"55091" "Pepin County"
"55093" "Pierce County"
"55095" "Polk County"
"55097" "Portage County"
"55099" "Price County"
"55101" "Racine County"
"55103" "Richland County"
"55105" "Rock County"
"55107" "Rusk County"
"55109" "St. Croix County"
"55111" "Sauk County"
"55113" "Sawyer County"
"55115" "Shawano County"
"55117" "Sheboygan County"
"55119" "Taylor County"
"55121" "Trempealeau County"
"55123" "Vernon County"
"55125" "Vilas County"
"55127" "Walworth County"
"55129" "Washburn County"
"55131" "Washington County"
"55133" "Waukesha County"
"55135" "Waupaca County"
"55137" "Waushara County"
"55139" "Winnebago County"
"55141" "Wood County"
"56" "Wyoming"
"56001" "Albany County"
"56003" "Big Horn County"
"56005" "Campbell County"
"56007" "Carbon County"
"56009" "Converse County"
"56011" "Crook County"
"56013" "Fremont County"
"56015" "Goshen County"
"56017" "Hot Springs County"
"56019" "Johnson County"
"56021" "Laramie County"
"56023" "Lincoln County"
"56025" "Natrona County"
"56027" "Niobrara County"
"56029" "Park County"
"56031" "Platte County"
"56033" "Sheridan County"
"56035" "Sublette County"
"56037" "Sweetwater County"
"56039" "Teton County"
"56041" "Uinta County"
"56043" "Washakie County"
"56045" "Weston County"})
(defn fips-name
([state-fips county-fips]
(fips-name (str state-fips county-fips)))
([fips]
(get fips->name fips fips)))
(defn county-list
"Given a state fips, returns a vector of vectors like:
[[\"01001\" \"Autauga County\"]
[\"01003\" \"Baldwin County\"]
...]
The order is defined by the order of the county fips codes.
The counties come from the fips->name map."
[state-fips]
(letfn [(in-state? [candidate-fips]
(str/starts-with? candidate-fips state-fips))
(county-fips? [candidate-fips]
(= 5 (count candidate-fips)))
(county-fips-for-state? [candidate-fips]
(and (in-state? candidate-fips)
(county-fips? candidate-fips)))]
(let [county-keys (->> (keys fips->name)
(filter county-fips-for-state?)
sort)
county-names (map fips->name county-keys)]
(mapv vector county-keys county-names))))
(def state-fips->abbreviation
{"01" "AL"
"02" "AK"
"04" "AZ"
"05" "AR"
"06" "CA"
"08" "CO"
"09" "CT"
"10" "DE"
"11" "DC"
"12" "FL"
"13" "GA"
"15" "HI"
"16" "ID"
"17" "IL"
"18" "IN"
"19" "IA"
"20" "KS"
"21" "KY"
"22" "LA"
"23" "ME"
"24" "MD"
"25" "MA"
"26" "MI"
"27" "MN"
"28" "MS"
"29" "MO"
"30" "MT"
"31" "NE"
"32" "NV"
"33" "NH"
"34" "NJ"
"35" "NM"
"36" "NY"
"37" "NC"
"38" "ND"
"39" "OH"
"40" "OK"
"41" "OR"
"42" "PA"
"44" "RI"
"45" "SC"
"46" "SD"
"47" "TN"
"48" "TX"
"49" "UT"
"50" "VT"
"51" "VA"
"53" "WA"
"54" "WV"
"55" "WI"
"56" "WY"})
|
[
{
"context": "ations rt [:arachne/id :test/adapter])\n\n (let [james (UUID/randomUUID)\n mary (UUID/randomUUID",
"end": 754,
"score": 0.8301027417182922,
"start": 749,
"tag": "NAME",
"value": "james"
},
{
"context": "ter])\n\n (let [james (UUID/randomUUID)\n mary (UUID/randomUUID)\n elizabeth (UUID/rando",
"end": 787,
"score": 0.9895711541175842,
"start": 783,
"tag": "NAME",
"value": "mary"
},
{
"context": "omUUID)\n mary (UUID/randomUUID)\n elizabeth (UUID/randomUUID)]\n\n (testing \"cannot create",
"end": 825,
"score": 0.769422709941864,
"start": 816,
"tag": "NAME",
"value": "elizabeth"
},
{
"context": " {:test.person/id james\n :",
"end": 1115,
"score": 0.8994177579879761,
"start": 1110,
"tag": "NAME",
"value": "james"
},
{
"context": " :test.person/name \"James\"\n ",
"end": 1188,
"score": 0.9981123805046082,
"start": 1183,
"tag": "NAME",
"value": "James"
},
{
"context": ".person/friends #{(chimera/lookup [:test.person/id mary])}})))\n (chimera/operate adapter :chimera.",
"end": 1298,
"score": 0.8538343906402588,
"start": 1294,
"tag": "NAME",
"value": "mary"
},
{
"context": "te adapter :chimera.operation/put {:test.person/id james\n ",
"end": 1384,
"score": 0.8667240142822266,
"start": 1379,
"tag": "NAME",
"value": "james"
},
{
"context": " :test.person/name \"James\"}))\n\n (testing \"can create refs to elements ",
"end": 1466,
"score": 0.9973464608192444,
"start": 1461,
"tag": "NAME",
"value": "James"
},
{
"context": " [[:chimera.operation/put {:test.person/id mary\n :te",
"end": 1669,
"score": 0.9211299419403076,
"start": 1665,
"tag": "NAME",
"value": "mary"
},
{
"context": " :test.person/name \"Mary\"}]\n [:chimera.operation/put {",
"end": 1739,
"score": 0.997732400894165,
"start": 1735,
"tag": "NAME",
"value": "Mary"
},
{
"context": " [:chimera.operation/put {:test.person/id james\n :te",
"end": 1810,
"score": 0.8304038643836975,
"start": 1805,
"tag": "NAME",
"value": "james"
},
{
"context": ".person/friends #{(chimera/lookup [:test.person/id mary])}}]]))))\n\n (testing \"can't set cardinality-",
"end": 1917,
"score": 0.8525731563568115,
"start": 1913,
"tag": "NAME",
"value": "mary"
},
{
"context": "ut\n {:test.person/id mary\n :test.person/frie",
"end": 2170,
"score": 0.965293824672699,
"start": 2166,
"tag": "NAME",
"value": "mary"
},
{
"context": "est.person/friends (chimera/lookup :test.person/id james)}))))\n\n (testing \"can't set cardinality-one ",
"end": 2261,
"score": 0.7025490999221802,
"start": 2256,
"tag": "NAME",
"value": "james"
},
{
"context": " {:test.person/id mary\n :",
"end": 2543,
"score": 0.9789696335792542,
"start": 2539,
"tag": "NAME",
"value": "mary"
},
{
"context": "on/best-friend #{(chimera/lookup :test.person/id james)}}))))\n\n (chimera/operate adapter :chimera.o",
"end": 2656,
"score": 0.652311384677887,
"start": 2652,
"tag": "NAME",
"value": "ames"
},
{
"context": " :test.person/name \"Elizabeth\"}]\n [:chimera.operation/put {:test.person",
"end": 2843,
"score": 0.9917925596237183,
"start": 2834,
"tag": "NAME",
"value": "Elizabeth"
},
{
"context": "\n [:chimera.operation/put {:test.person/id james\n :test.person/fr",
"end": 2902,
"score": 0.8796699047088623,
"start": 2897,
"tag": "NAME",
"value": "james"
},
{
"context": "\n [[:chimera.operation/put {:test.person/id james\n :test.person/be",
"end": 3119,
"score": 0.8498221039772034,
"start": 3114,
"tag": "NAME",
"value": "james"
},
{
"context": "turned as lookups\"\n (is (= {:test.person/id james\n :test.person/name \"James\"\n ",
"end": 3320,
"score": 0.8366400003433228,
"start": 3315,
"tag": "NAME",
"value": "james"
},
{
"context": "erson/id james\n :test.person/name \"James\"\n :test.person/friends #{(chimera/",
"end": 3361,
"score": 0.9979179501533508,
"start": 3356,
"tag": "NAME",
"value": "James"
},
{
"context": "t.person/friends #{(chimera/lookup :test.person/id mary)\n (chimera/",
"end": 3438,
"score": 0.8749698996543884,
"start": 3434,
"tag": "NAME",
"value": "mary"
},
{
"context": "tion/delete-entity (chimera/lookup :test.person/id mary))\n (is (= 1 (count (:test.person/friends (",
"end": 4028,
"score": 0.9701976776123047,
"start": 4024,
"tag": "NAME",
"value": "mary"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james)))))))\n\n (testing \"ref attrs are removed whe",
"end": 4162,
"score": 0.8246979117393494,
"start": 4157,
"tag": "NAME",
"value": "james"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))\n (chimera/operate adapter :chimera.ope",
"end": 4368,
"score": 0.7838423252105713,
"start": 4363,
"tag": "NAME",
"value": "james"
},
{
"context": "tion/delete-entity (chimera/lookup :test.person/id elizabeth))\n (is (not (:test.person/best-friend (chi",
"end": 4480,
"score": 0.9927260875701904,
"start": 4471,
"tag": "NAME",
"value": "elizabeth"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))))\n\n )))\n\n(defn component-operations\n [a",
"end": 4611,
"score": 0.807357668876648,
"start": 4606,
"tag": "NAME",
"value": "james"
},
{
"context": " [:chimera.operation/put {:test.person/id james\n :test.person/",
"end": 6264,
"score": 0.9630377292633057,
"start": 6259,
"tag": "NAME",
"value": "james"
},
{
"context": "id address3)}}]])\n\n (is (= {:test.person/id james\n :test.person/primary-address {:te",
"end": 6624,
"score": 0.912338376045227,
"start": 6619,
"tag": "NAME",
"value": "james"
},
{
"context": ".operation/delete [(chimera/lookup :test.person/id james) :test.person/primary-address])\n\n (is ",
"end": 8883,
"score": 0.9935666918754578,
"start": 8882,
"tag": "NAME",
"value": "j"
},
{
"context": "peration/delete [(chimera/lookup :test.person/id james) :test.person/primary-address])\n\n (is (= {",
"end": 8887,
"score": 0.8072329759597778,
"start": 8883,
"tag": "NAME",
"value": "ames"
},
{
"context": "primary-address])\n\n (is (= {:test.person/id james\n :test.person/addresses #{{:te",
"end": 8954,
"score": 0.9940119385719299,
"start": 8953,
"tag": "NAME",
"value": "j"
},
{
"context": "imary-address])\n\n (is (= {:test.person/id james\n :test.person/addresses #{{:test.a",
"end": 8958,
"score": 0.7128474712371826,
"start": 8954,
"tag": "NAME",
"value": "ames"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))\n\n (is (nil? (chimera/operate adapt",
"end": 9553,
"score": 0.9891514182090759,
"start": 9552,
"tag": "NAME",
"value": "j"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james))))\n\n (is (nil? (chimera/operate adapter :",
"end": 9557,
"score": 0.8478735685348511,
"start": 9553,
"tag": "NAME",
"value": "ames"
},
{
"context": "tion/delete-entity (chimera/lookup :test.person/id james))\n\n (is (nil? (chimera/operate adapter",
"end": 9893,
"score": 0.9872893691062927,
"start": 9892,
"tag": "NAME",
"value": "j"
},
{
"context": "on/delete-entity (chimera/lookup :test.person/id james))\n\n (is (nil? (chimera/operate adapter :ch",
"end": 9897,
"score": 0.8768367171287537,
"start": 9893,
"tag": "NAME",
"value": "ames"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))\n (is (nil? (chimera/operate adapte",
"end": 10000,
"score": 0.9679542183876038,
"start": 9999,
"tag": "NAME",
"value": "j"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james))))\n (is (nil? (chimera/operate adapter :c",
"end": 10004,
"score": 0.9265670776367188,
"start": 10000,
"tag": "NAME",
"value": "ames"
}
] |
src/arachne/chimera/test_harness/refs.clj
|
arachne-framework/arachne-chimera
| 2 |
(ns arachne.chimera.test-harness.refs
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn basic-ref-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
mary (UUID/randomUUID)
elizabeth (UUID/randomUUID)]
(testing "cannot create ref to nonexistent entity"
(is (thrown-with-msg? ArachneException #"does not exist"
(chimera/operate adapter :chimera.operation/put
{:test.person/id james
:test.person/name "James"
:test.person/friends #{(chimera/lookup [:test.person/id mary])}})))
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/name "James"}))
(testing "can create refs to elements in the same batch"
(is (nil? (chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id mary
:test.person/name "Mary"}]
[:chimera.operation/put {:test.person/id james
:test.person/friends #{(chimera/lookup [:test.person/id mary])}}]]))))
(testing "can't set cardinality-many refs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id mary
:test.person/friends (chimera/lookup :test.person/id james)}))))
(testing "can't set cardinality-one refs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id mary
:test.person/best-friend #{(chimera/lookup :test.person/id james)}}))))
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id elizabeth
:test.person/name "Elizabeth"}]
[:chimera.operation/put {:test.person/id james
:test.person/friends #{(chimera/lookup :test.person/id elizabeth)}}]])
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id james
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}]])
(testing "ref attributes are returned as lookups"
(is (= {:test.person/id james
:test.person/name "James"
:test.person/friends #{(chimera/lookup :test.person/id mary)
(chimera/lookup :test.person/id elizabeth)}
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))
(testing "ref attrs are removed when target is removed (card many)"
(is (= 2 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id mary))
(is (= 1 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))))
(testing "ref attrs are removed when target is removed (card one)"
(is (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id elizabeth))
(is (not (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
)))
(defn component-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
detail1 (UUID/randomUUID)
detail2 (UUID/randomUUID)
address1 (UUID/randomUUID)
address2 (UUID/randomUUID)
address3 (UUID/randomUUID)]
(testing "Components are returned as nested maps"
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}]
[:chimera.operation/put {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}]
[:chimera.operation/put {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail1)}}]
[:chimera.operation/put {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail2)}}]
[:chimera.operation/put {:test.address/id address3
:test.address/street "Street 3"}]
[:chimera.operation/put {:test.person/id james
:test.person/primary-address (chimera/lookup :test.address/id address1)
:test.person/addresses #{(chimera/lookup :test.address/id address2)
(chimera/lookup :test.address/id address3)}}]])
(is (= {:test.person/id james
:test.person/primary-address {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (= {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (= {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (= {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(is (= {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2)))))
(testing "Deletes are recursive"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id james) :test.person/primary-address])
(is (= {:test.person/id james
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id james))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address3))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2))))))))
(defn exercise-all
[adapter-dsl-fn modules]
(basic-ref-operations adapter-dsl-fn modules)
(component-operations adapter-dsl-fn modules))
|
99911
|
(ns arachne.chimera.test-harness.refs
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn basic-ref-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [<NAME> (UUID/randomUUID)
<NAME> (UUID/randomUUID)
<NAME> (UUID/randomUUID)]
(testing "cannot create ref to nonexistent entity"
(is (thrown-with-msg? ArachneException #"does not exist"
(chimera/operate adapter :chimera.operation/put
{:test.person/id <NAME>
:test.person/name "<NAME>"
:test.person/friends #{(chimera/lookup [:test.person/id <NAME>])}})))
(chimera/operate adapter :chimera.operation/put {:test.person/id <NAME>
:test.person/name "<NAME>"}))
(testing "can create refs to elements in the same batch"
(is (nil? (chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id <NAME>
:test.person/name "<NAME>"}]
[:chimera.operation/put {:test.person/id <NAME>
:test.person/friends #{(chimera/lookup [:test.person/id <NAME>])}}]]))))
(testing "can't set cardinality-many refs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id <NAME>
:test.person/friends (chimera/lookup :test.person/id <NAME>)}))))
(testing "can't set cardinality-one refs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id <NAME>
:test.person/best-friend #{(chimera/lookup :test.person/id j<NAME>)}}))))
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id elizabeth
:test.person/name "<NAME>"}]
[:chimera.operation/put {:test.person/id <NAME>
:test.person/friends #{(chimera/lookup :test.person/id elizabeth)}}]])
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id <NAME>
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}]])
(testing "ref attributes are returned as lookups"
(is (= {:test.person/id <NAME>
:test.person/name "<NAME>"
:test.person/friends #{(chimera/lookup :test.person/id <NAME>)
(chimera/lookup :test.person/id elizabeth)}
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))
(testing "ref attrs are removed when target is removed (card many)"
(is (= 2 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id <NAME>))
(is (= 1 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME>)))))))
(testing "ref attrs are removed when target is removed (card one)"
(is (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME>))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id <NAME>))
(is (not (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME>))))))
)))
(defn component-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
detail1 (UUID/randomUUID)
detail2 (UUID/randomUUID)
address1 (UUID/randomUUID)
address2 (UUID/randomUUID)
address3 (UUID/randomUUID)]
(testing "Components are returned as nested maps"
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}]
[:chimera.operation/put {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}]
[:chimera.operation/put {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail1)}}]
[:chimera.operation/put {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail2)}}]
[:chimera.operation/put {:test.address/id address3
:test.address/street "Street 3"}]
[:chimera.operation/put {:test.person/id <NAME>
:test.person/primary-address (chimera/lookup :test.address/id address1)
:test.person/addresses #{(chimera/lookup :test.address/id address2)
(chimera/lookup :test.address/id address3)}}]])
(is (= {:test.person/id <NAME>
:test.person/primary-address {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (= {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (= {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (= {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(is (= {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2)))))
(testing "Deletes are recursive"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id <NAME> <NAME>) :test.person/primary-address])
(is (= {:test.person/id <NAME> <NAME>
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME> <NAME>))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id <NAME> <NAME>))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME> <NAME>))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address3))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2))))))))
(defn exercise-all
[adapter-dsl-fn modules]
(basic-ref-operations adapter-dsl-fn modules)
(component-operations adapter-dsl-fn modules))
| true |
(ns arachne.chimera.test-harness.refs
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn basic-ref-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [PI:NAME:<NAME>END_PI (UUID/randomUUID)
PI:NAME:<NAME>END_PI (UUID/randomUUID)
PI:NAME:<NAME>END_PI (UUID/randomUUID)]
(testing "cannot create ref to nonexistent entity"
(is (thrown-with-msg? ArachneException #"does not exist"
(chimera/operate adapter :chimera.operation/put
{:test.person/id PI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/friends #{(chimera/lookup [:test.person/id PI:NAME:<NAME>END_PI])}})))
(chimera/operate adapter :chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"}))
(testing "can create refs to elements in the same batch"
(is (nil? (chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"}]
[:chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/friends #{(chimera/lookup [:test.person/id PI:NAME:<NAME>END_PI])}}]]))))
(testing "can't set cardinality-many refs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id PI:NAME:<NAME>END_PI
:test.person/friends (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI)}))))
(testing "can't set cardinality-one refs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id PI:NAME:<NAME>END_PI
:test.person/best-friend #{(chimera/lookup :test.person/id jPI:NAME:<NAME>END_PI)}}))))
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id elizabeth
:test.person/name "PI:NAME:<NAME>END_PI"}]
[:chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/friends #{(chimera/lookup :test.person/id elizabeth)}}]])
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}]])
(testing "ref attributes are returned as lookups"
(is (= {:test.person/id PI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/friends #{(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI)
(chimera/lookup :test.person/id elizabeth)}
:test.person/best-friend (chimera/lookup :test.person/id elizabeth)}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))
(testing "ref attrs are removed when target is removed (card many)"
(is (= 2 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI))
(is (= 1 (count (:test.person/friends (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI)))))))
(testing "ref attrs are removed when target is removed (card one)"
(is (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI))
(is (not (:test.person/best-friend (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI))))))
)))
(defn component-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
detail1 (UUID/randomUUID)
detail2 (UUID/randomUUID)
address1 (UUID/randomUUID)
address2 (UUID/randomUUID)
address3 (UUID/randomUUID)]
(testing "Components are returned as nested maps"
(chimera/operate adapter :chimera.operation/batch
[[:chimera.operation/put {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}]
[:chimera.operation/put {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}]
[:chimera.operation/put {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail1)}}]
[:chimera.operation/put {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{(chimera/lookup :test.address-detail/id detail2)}}]
[:chimera.operation/put {:test.address/id address3
:test.address/street "Street 3"}]
[:chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/primary-address (chimera/lookup :test.address/id address1)
:test.person/addresses #{(chimera/lookup :test.address/id address2)
(chimera/lookup :test.address/id address3)}}]])
(is (= {:test.person/id PI:NAME:<NAME>END_PI
:test.person/primary-address {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (= {:test.address/id address1
:test.address/street "Street 1"
:test.address/detail #{{:test.address-detail/id detail1
:test.address-detail/note "Some notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (= {:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (= {:test.address-detail/id detail1
:test.address-detail/note "Some notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(is (= {:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2)))))
(testing "Deletes are recursive"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) :test.person/primary-address])
(is (= {:test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
:test.person/addresses #{{:test.address/id address2
:test.address/street "Street 2"
:test.address/detail #{{:test.address-detail/id detail2
:test.address-detail/note "Some other notes"}}}
{:test.address/id address3
:test.address/street "Street 3"}}}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address1))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail1))))
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address2))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address/id address3))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.address-detail/id detail2))))))))
(defn exercise-all
[adapter-dsl-fn modules]
(basic-ref-operations adapter-dsl-fn modules)
(component-operations adapter-dsl-fn modules))
|
[
{
"context": "GE_MILLISECONDS (* 60 60 1000))\n(def SESSION_KEY \"session-id\")\n\n(defn- expire-at []\n (java.util.Date. (+ SESS",
"end": 241,
"score": 0.998934268951416,
"start": 231,
"tag": "KEY",
"value": "session-id"
}
] |
src/bubble/login/session.clj
|
jackrr/bubble
| 1 |
(ns bubble.login.session
(:require [bubble.db :refer [db]]
[next.jdbc :as sql]
[ring.middleware.session.cookie :as ring-cookie]))
;; 1 hour
(def SESSION_AGE_MILLISECONDS (* 60 60 1000))
(def SESSION_KEY "session-id")
(defn- expire-at []
(java.util.Date. (+ SESSION_AGE_MILLISECONDS (System/currentTimeMillis))))
(defn- session-id-from-req [{:keys [cookies]}]
(some-> cookies
(get-in [SESSION_KEY :value])
java.util.UUID/fromString))
(defn- delete-expired-sessions! []
(sql/execute! db ["delete from sessions where expires_at < ?" (java.util.Date.)]))
(defn- create-session [user-id]
(delete-expired-sessions!)
(->
(sql/execute-one!
db
["insert into sessions (user_id, expires_at) values (?,?)"
user-id (expire-at)]
{:return-keys true})
:sessions/id
str))
(defn- extend-session [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["update sessions set expires_at = ? where id = ?"
(expire-at)
session-id])))
(defn- user-from-req [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["select * from sessions s left join users u on u.id = s.user_id where s.id = ?"
session-id])))
(defn log-out-user [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["delete from sessions s where s.id = ?"
session-id])))
(defn current-user
([req]
(user-from-req req))
([req {:keys [extend]}]
(do
(extend-session req)
(user-from-req req))))
(defn create-session-cookie [user-id]
{SESSION_KEY {:value (create-session user-id)
:secure true
:http-only true
:same-site :strict
:path "/"
:max-age SESSION_AGE_MILLISECONDS}})
|
20613
|
(ns bubble.login.session
(:require [bubble.db :refer [db]]
[next.jdbc :as sql]
[ring.middleware.session.cookie :as ring-cookie]))
;; 1 hour
(def SESSION_AGE_MILLISECONDS (* 60 60 1000))
(def SESSION_KEY "<KEY>")
(defn- expire-at []
(java.util.Date. (+ SESSION_AGE_MILLISECONDS (System/currentTimeMillis))))
(defn- session-id-from-req [{:keys [cookies]}]
(some-> cookies
(get-in [SESSION_KEY :value])
java.util.UUID/fromString))
(defn- delete-expired-sessions! []
(sql/execute! db ["delete from sessions where expires_at < ?" (java.util.Date.)]))
(defn- create-session [user-id]
(delete-expired-sessions!)
(->
(sql/execute-one!
db
["insert into sessions (user_id, expires_at) values (?,?)"
user-id (expire-at)]
{:return-keys true})
:sessions/id
str))
(defn- extend-session [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["update sessions set expires_at = ? where id = ?"
(expire-at)
session-id])))
(defn- user-from-req [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["select * from sessions s left join users u on u.id = s.user_id where s.id = ?"
session-id])))
(defn log-out-user [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["delete from sessions s where s.id = ?"
session-id])))
(defn current-user
([req]
(user-from-req req))
([req {:keys [extend]}]
(do
(extend-session req)
(user-from-req req))))
(defn create-session-cookie [user-id]
{SESSION_KEY {:value (create-session user-id)
:secure true
:http-only true
:same-site :strict
:path "/"
:max-age SESSION_AGE_MILLISECONDS}})
| true |
(ns bubble.login.session
(:require [bubble.db :refer [db]]
[next.jdbc :as sql]
[ring.middleware.session.cookie :as ring-cookie]))
;; 1 hour
(def SESSION_AGE_MILLISECONDS (* 60 60 1000))
(def SESSION_KEY "PI:KEY:<KEY>END_PI")
(defn- expire-at []
(java.util.Date. (+ SESSION_AGE_MILLISECONDS (System/currentTimeMillis))))
(defn- session-id-from-req [{:keys [cookies]}]
(some-> cookies
(get-in [SESSION_KEY :value])
java.util.UUID/fromString))
(defn- delete-expired-sessions! []
(sql/execute! db ["delete from sessions where expires_at < ?" (java.util.Date.)]))
(defn- create-session [user-id]
(delete-expired-sessions!)
(->
(sql/execute-one!
db
["insert into sessions (user_id, expires_at) values (?,?)"
user-id (expire-at)]
{:return-keys true})
:sessions/id
str))
(defn- extend-session [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["update sessions set expires_at = ? where id = ?"
(expire-at)
session-id])))
(defn- user-from-req [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["select * from sessions s left join users u on u.id = s.user_id where s.id = ?"
session-id])))
(defn log-out-user [req]
(when-let [session-id (session-id-from-req req)]
(sql/execute-one!
db
["delete from sessions s where s.id = ?"
session-id])))
(defn current-user
([req]
(user-from-req req))
([req {:keys [extend]}]
(do
(extend-session req)
(user-from-req req))))
(defn create-session-cookie [user-id]
{SESSION_KEY {:value (create-session user-id)
:secure true
:http-only true
:same-site :strict
:path "/"
:max-age SESSION_AGE_MILLISECONDS}})
|
[
{
"context": "\n :default :refseq77}}\n\n :email {:default \"[email protected]\"\n ;; All your other users\n ;; key",
"end": 804,
"score": 0.997214674949646,
"start": 772,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "{:smtphost \"smtp.gmail.com\"\n :sender \"[email protected]\"\n :user \"your-aerobio-email-acct@so",
"end": 1038,
"score": 0.9997304081916809,
"start": 1015,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " \"[email protected]\"\n :user \"[email protected]\"\n :pass \"the-pw-for-acct\"}\n}\n",
"end": 1105,
"score": 0.9905930757522583,
"start": 1062,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]\"\n :pass \"the-pw-for-acct\"}\n}\n",
"end": 1144,
"score": 0.9967929720878601,
"start": 1129,
"tag": "PASSWORD",
"value": "the-pw-for-acct"
}
] |
Support/config.clj
|
jsa-aerial/aerobio
| 3 |
{:scratch-base "/ExpOut"
:fastq-dirname "Fastq"
:refdir "/Refs"
:nextseq-base "/NextSeq2"
:nextseq-fqdir "Data/Intensities/BaseCalls"
:ports
{:server 7070
:repl 4003}
:logging
{:dir "~/.aerobio"
:file "main-log.txt"}
:jobs
{:dir "~/.aerobio/DBs"
:file "job-db.clj"}
:biodb-info
{:genomes
{:base "/GenomeSeqs"
:refseq46 "RefSeq46"
:refseq58 "RefSeq58"
:refseq77 "RefSeq77"
:tvoseq02 "TVOSeq02"
:default :refseq77}
:blast
{:base "/BlastDBs"
:refseq58 "RefSeq58/refseq58_microbial_genomic"
:refseq77 "RefSeq77/Microbial/refseq77_microbial_complete"
:refseq77-arch "RefSeq77/Archaea/refseq77_arhaea_complete"
:refseq77-bact "RefSeq77/Bacteria/refseq77_bacteria_complete"
:default :refseq77}}
:email {:default "[email protected]"
;; All your other users
;; keyword version of user acct name as key,
;; string of full email address as value
}
:mailcfg {:smtphost "smtp.gmail.com"
:sender "[email protected]"
:user "[email protected]"
:pass "the-pw-for-acct"}
}
|
29050
|
{:scratch-base "/ExpOut"
:fastq-dirname "Fastq"
:refdir "/Refs"
:nextseq-base "/NextSeq2"
:nextseq-fqdir "Data/Intensities/BaseCalls"
:ports
{:server 7070
:repl 4003}
:logging
{:dir "~/.aerobio"
:file "main-log.txt"}
:jobs
{:dir "~/.aerobio/DBs"
:file "job-db.clj"}
:biodb-info
{:genomes
{:base "/GenomeSeqs"
:refseq46 "RefSeq46"
:refseq58 "RefSeq58"
:refseq77 "RefSeq77"
:tvoseq02 "TVOSeq02"
:default :refseq77}
:blast
{:base "/BlastDBs"
:refseq58 "RefSeq58/refseq58_microbial_genomic"
:refseq77 "RefSeq77/Microbial/refseq77_microbial_complete"
:refseq77-arch "RefSeq77/Archaea/refseq77_arhaea_complete"
:refseq77-bact "RefSeq77/Bacteria/refseq77_bacteria_complete"
:default :refseq77}}
:email {:default "<EMAIL>"
;; All your other users
;; keyword version of user acct name as key,
;; string of full email address as value
}
:mailcfg {:smtphost "smtp.gmail.com"
:sender "<EMAIL>"
:user "<EMAIL>"
:pass "<PASSWORD>"}
}
| true |
{:scratch-base "/ExpOut"
:fastq-dirname "Fastq"
:refdir "/Refs"
:nextseq-base "/NextSeq2"
:nextseq-fqdir "Data/Intensities/BaseCalls"
:ports
{:server 7070
:repl 4003}
:logging
{:dir "~/.aerobio"
:file "main-log.txt"}
:jobs
{:dir "~/.aerobio/DBs"
:file "job-db.clj"}
:biodb-info
{:genomes
{:base "/GenomeSeqs"
:refseq46 "RefSeq46"
:refseq58 "RefSeq58"
:refseq77 "RefSeq77"
:tvoseq02 "TVOSeq02"
:default :refseq77}
:blast
{:base "/BlastDBs"
:refseq58 "RefSeq58/refseq58_microbial_genomic"
:refseq77 "RefSeq77/Microbial/refseq77_microbial_complete"
:refseq77-arch "RefSeq77/Archaea/refseq77_arhaea_complete"
:refseq77-bact "RefSeq77/Bacteria/refseq77_bacteria_complete"
:default :refseq77}}
:email {:default "PI:EMAIL:<EMAIL>END_PI"
;; All your other users
;; keyword version of user acct name as key,
;; string of full email address as value
}
:mailcfg {:smtphost "smtp.gmail.com"
:sender "PI:EMAIL:<EMAIL>END_PI"
:user "PI:EMAIL:<EMAIL>END_PI"
:pass "PI:PASSWORD:<PASSWORD>END_PI"}
}
|
[
{
"context": " C struct/typedef parser functions.\"\n ^{:author \"Karsten Schmidt\"}\n (:require\n \t[net.cgrand.parsley :as p]\n \t[c",
"end": 101,
"score": 0.9998071789741516,
"start": 86,
"tag": "NAME",
"value": "Karsten Schmidt"
}
] |
src/thi/ng/structgen/parser.clj
|
thi-ng/structgen
| 10 |
(ns thi.ng.structgen.parser
"Basic C struct/typedef parser functions."
^{:author "Karsten Schmidt"}
(:require
[net.cgrand.parsley :as p]
[clojure.string :as str]))
(def c-ws #"\s+")
(def c-symbol #"[a-zA-Z_][\w]*")
(def c-float #"[\-\+]?\d+[Ee\.]?[\dEe\-\+]*")
(def c-define
(re-pattern
(str "#define (" c-symbol ") ((" c-symbol ")|(" c-float "))" c-ws)))
(def ignore-terminals #"[\s\[\]\;]+")
(defmulti transform-node (fn [t c] t))
(defmethod transform-node :sym [t c]
{:tag t :content (first c)})
(defmethod transform-node :num [t c]
{:tag t :content (first c)})
(defmethod transform-node :array [t c]
{:tag t :content (:content (first c))})
(defmethod transform-node :decl [t c]
(let [[type id len] (map #(-> % :content) c)
len (if len (Integer/parseInt len))]
{:tag t :content [(keyword id) (keyword type) len]}))
(defmethod transform-node :typedef [t c]
{:tag t
:content {
:declares (map :content (filter #(and (map? %) (= :decl (:tag %))) c))
:id (-> (filter #(and (map? %) (= :sym (:tag %))) c) first :content keyword)}})
(defmethod transform-node :default [t c]
{:tag t :content c})
(defn preprocess
([src & {:as userdefs}]
(let [defines (re-seq c-define src)]
(reduce
(fn[s [o d r]]
(-> s
(str/replace o "")
(str/replace d (str (get userdefs (keyword d) r)))))
src defines))))
(def parser
(p/parser
{:main :expr*
:space :ws?
:make-node #(transform-node %1 (filter (complement nil?) %2))
:make-leaf (fn[x] (when-not (re-matches ignore-terminals x) x))
}
:expr- #{:pragma :typedef}
:ws- c-ws
:sym c-symbol
:num c-float
:atom #{:sym :num}
:a-start- \[
:a-end- \]
:term- \;
:array [:a-start :num :a-end]
:decl [:sym :sym :array? :term]
:typedef ["typedef struct {" :decl* "}" :sym :term]
:pragma ["#pragma" :sym :atom]))
(defn tree->specs
[tree]
(map
#(let [{:keys [id declares]} (:content %)] (vec (cons id declares)))
(filter #(= :typedef (:tag %)) (:content tree))))
(defn parse
[src & userdefs]
(parser (apply preprocess src userdefs)))
(defn parse-specs
[src & userdefs]
(-> (apply preprocess src userdefs) (parser) (tree->specs)))
|
80177
|
(ns thi.ng.structgen.parser
"Basic C struct/typedef parser functions."
^{:author "<NAME>"}
(:require
[net.cgrand.parsley :as p]
[clojure.string :as str]))
(def c-ws #"\s+")
(def c-symbol #"[a-zA-Z_][\w]*")
(def c-float #"[\-\+]?\d+[Ee\.]?[\dEe\-\+]*")
(def c-define
(re-pattern
(str "#define (" c-symbol ") ((" c-symbol ")|(" c-float "))" c-ws)))
(def ignore-terminals #"[\s\[\]\;]+")
(defmulti transform-node (fn [t c] t))
(defmethod transform-node :sym [t c]
{:tag t :content (first c)})
(defmethod transform-node :num [t c]
{:tag t :content (first c)})
(defmethod transform-node :array [t c]
{:tag t :content (:content (first c))})
(defmethod transform-node :decl [t c]
(let [[type id len] (map #(-> % :content) c)
len (if len (Integer/parseInt len))]
{:tag t :content [(keyword id) (keyword type) len]}))
(defmethod transform-node :typedef [t c]
{:tag t
:content {
:declares (map :content (filter #(and (map? %) (= :decl (:tag %))) c))
:id (-> (filter #(and (map? %) (= :sym (:tag %))) c) first :content keyword)}})
(defmethod transform-node :default [t c]
{:tag t :content c})
(defn preprocess
([src & {:as userdefs}]
(let [defines (re-seq c-define src)]
(reduce
(fn[s [o d r]]
(-> s
(str/replace o "")
(str/replace d (str (get userdefs (keyword d) r)))))
src defines))))
(def parser
(p/parser
{:main :expr*
:space :ws?
:make-node #(transform-node %1 (filter (complement nil?) %2))
:make-leaf (fn[x] (when-not (re-matches ignore-terminals x) x))
}
:expr- #{:pragma :typedef}
:ws- c-ws
:sym c-symbol
:num c-float
:atom #{:sym :num}
:a-start- \[
:a-end- \]
:term- \;
:array [:a-start :num :a-end]
:decl [:sym :sym :array? :term]
:typedef ["typedef struct {" :decl* "}" :sym :term]
:pragma ["#pragma" :sym :atom]))
(defn tree->specs
[tree]
(map
#(let [{:keys [id declares]} (:content %)] (vec (cons id declares)))
(filter #(= :typedef (:tag %)) (:content tree))))
(defn parse
[src & userdefs]
(parser (apply preprocess src userdefs)))
(defn parse-specs
[src & userdefs]
(-> (apply preprocess src userdefs) (parser) (tree->specs)))
| true |
(ns thi.ng.structgen.parser
"Basic C struct/typedef parser functions."
^{:author "PI:NAME:<NAME>END_PI"}
(:require
[net.cgrand.parsley :as p]
[clojure.string :as str]))
(def c-ws #"\s+")
(def c-symbol #"[a-zA-Z_][\w]*")
(def c-float #"[\-\+]?\d+[Ee\.]?[\dEe\-\+]*")
(def c-define
(re-pattern
(str "#define (" c-symbol ") ((" c-symbol ")|(" c-float "))" c-ws)))
(def ignore-terminals #"[\s\[\]\;]+")
(defmulti transform-node (fn [t c] t))
(defmethod transform-node :sym [t c]
{:tag t :content (first c)})
(defmethod transform-node :num [t c]
{:tag t :content (first c)})
(defmethod transform-node :array [t c]
{:tag t :content (:content (first c))})
(defmethod transform-node :decl [t c]
(let [[type id len] (map #(-> % :content) c)
len (if len (Integer/parseInt len))]
{:tag t :content [(keyword id) (keyword type) len]}))
(defmethod transform-node :typedef [t c]
{:tag t
:content {
:declares (map :content (filter #(and (map? %) (= :decl (:tag %))) c))
:id (-> (filter #(and (map? %) (= :sym (:tag %))) c) first :content keyword)}})
(defmethod transform-node :default [t c]
{:tag t :content c})
(defn preprocess
([src & {:as userdefs}]
(let [defines (re-seq c-define src)]
(reduce
(fn[s [o d r]]
(-> s
(str/replace o "")
(str/replace d (str (get userdefs (keyword d) r)))))
src defines))))
(def parser
(p/parser
{:main :expr*
:space :ws?
:make-node #(transform-node %1 (filter (complement nil?) %2))
:make-leaf (fn[x] (when-not (re-matches ignore-terminals x) x))
}
:expr- #{:pragma :typedef}
:ws- c-ws
:sym c-symbol
:num c-float
:atom #{:sym :num}
:a-start- \[
:a-end- \]
:term- \;
:array [:a-start :num :a-end]
:decl [:sym :sym :array? :term]
:typedef ["typedef struct {" :decl* "}" :sym :term]
:pragma ["#pragma" :sym :atom]))
(defn tree->specs
[tree]
(map
#(let [{:keys [id declares]} (:content %)] (vec (cons id declares)))
(filter #(= :typedef (:tag %)) (:content tree))))
(defn parse
[src & userdefs]
(parser (apply preprocess src userdefs)))
(defn parse-specs
[src & userdefs]
(-> (apply preprocess src userdefs) (parser) (tree->specs)))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998133778572083,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] |
src/clj/cljm/analyzer.clj
|
joshaber/clojurem
| 31 |
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(set! *warn-on-reflection* true)
(ns cljm.analyzer
(:refer-clojure :exclude [macroexpand-1])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[cljm.tagged-literals :as tags])
(:import java.lang.StringBuilder))
(declare resolve-var)
(declare resolve-existing-var)
(declare warning)
(def ^:dynamic *cljm-warn-on-undeclared* false)
(declare confirm-bindings)
(declare ^:dynamic *cljm-file*)
;; to resolve keywords like ::foo - the namespace
;; must be determined during analysis - the reader
;; did not know
(def ^:dynamic *reader-ns-name* (gensym))
(def ^:dynamic *reader-ns* (create-ns *reader-ns-name*))
(defonce namespaces (atom '{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn reset-namespaces! []
(reset! namespaces
'{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn get-namespace [key]
(@namespaces key))
(defn set-namespace [key val]
(swap! namespaces assoc key val))
(def ^:dynamic *cljm-ns* 'cljm.user)
(def ^:dynamic *cljm-file* nil)
(def ^:dynamic *cljm-warn-on-redef* true)
(def ^:dynamic *cljm-warn-on-dynamic* true)
(def ^:dynamic *cljm-warn-on-fn-var* true)
(def ^:dynamic *cljm-warn-fn-arity* true)
(def ^:dynamic *unchecked-if* (atom false))
(def ^:dynamic *cljm-static-fns* false)
(def ^:dynamic *cljm-macros-path* "/cljm/core")
(def ^:dynamic *cljm-macros-is-classpath* true)
(def -cljm-macros-loaded (atom false))
(defn load-core []
(when (not @-cljm-macros-loaded)
(reset! -cljm-macros-loaded true)
(if *cljm-macros-is-classpath*
(load *cljm-macros-path*)
(load-file *cljm-macros-path*))))
(defmacro with-core-macros
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path]
~@body)))
(defmacro with-core-macros-file
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path
*cljm-macros-is-classpath* false]
~@body)))
(defn empty-env []
{:ns (@namespaces *cljm-ns*) :context :statement :locals {}})
(defmacro ^:private debug-prn
[& args]
`(.println System/err (str ~@args)))
(defn warning [env s]
(binding [*out* *err*]
(println
(str s (when (:line env)
(str " at line " (:line env) " " *cljm-file*))))))
(defn confirm-var-exists [env prefix suffix]
(when *cljm-warn-on-undeclared*
(let [crnt-ns (-> env :ns :name)]
(when (= prefix crnt-ns)
(when-not (-> @namespaces crnt-ns :defs suffix)
(warning env
(str "WARNING: Use of undeclared Var " prefix "/" suffix)))))))
(defn resolve-ns-alias [env name]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (get (:defs (@namespaces 'cljm.core)) sym)
(not (contains? (-> env :ns :excludes) sym))))
(defn resolve-existing-var [env sym]
(cond
; If the namespace is all caps then we assume it's the class prefix for an
; Objective-C class.
(and (not (nil? (namespace sym))) (= (string/upper-case (namespace sym)) (namespace sym)))
{:name (symbol (str (namespace sym) (name sym))) :ns 'ObjectiveCClass}
(= (namespace sym) "js")
{:name sym :ns 'js}
:else
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)
full-ns (resolve-ns-alias env ns)]
(confirm-var-exists env full-ns (symbol (name sym)))
(merge (get-in @namespaces [full-ns :defs (symbol (name sym))])
{:name (symbol (str full-ns) (str (name sym)))
:ns full-ns}))
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s (inc idx))
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
(do
(confirm-var-exists env prefix (symbol suffix))
(merge (get-in @namespaces [prefix :defs (symbol suffix)])
{:name (if (= "" prefix) (symbol suffix) (symbol (str prefix) suffix))
:ns prefix}))))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns (-> env :ns :name)}))
:else
(let [full-ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
(confirm-var-exists env full-ns sym)
(merge (get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns full-ns}))))))
(defn resolve-var [env sym]
(if (= (namespace sym) "js")
{:name sym}
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)]
{:name (symbol (str (resolve-ns-alias env ns)) (name sym))})
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s idx)
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
{:name sym}))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (name sym))}))
:else
(let [ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
{:name (symbol (str ns) (name sym))})))))
(defn confirm-bindings [env names]
(doseq [name names]
(let [env (merge env {:ns (@namespaces *cljm-ns*)})
ev (resolve-existing-var env name)]
(when (and *cljm-warn-on-dynamic*
ev (not (-> ev :dynamic)))
(warning env
(str "WARNING: " (:name ev) " not declared ^:dynamic"))))))
(declare analyze analyze-symbol analyze-seq)
(def specials '#{if def fn* do let* loop* letfn* throw try* recur new set! ns defprotocol* deftype* defrecord* . objc* & quote})
(def ^:dynamic *recur-frames* nil)
(def ^:dynamic *loop-lets* nil)
(defmacro disallowing-recur [& body]
`(binding [*recur-frames* (cons nil *recur-frames*)] ~@body))
(defn analyze-keyword
[env sym]
{:op :constant :env env
:form (if (= (namespace sym) (name *reader-ns-name*))
(keyword (-> env :ns :name name) (name sym))
sym)})
(defn analyze-block
"returns {:statements .. :ret ..}"
[env exprs]
(let [statements (disallowing-recur
(seq (map #(analyze (assoc env :context :statement) %) (butlast exprs))))
ret (if (<= (count exprs) 1)
(analyze env (first exprs))
(analyze (assoc env :context (if (= :statement (:context env)) :statement :return)) (last exprs)))]
{:statements statements :ret ret}))
(defmulti parse (fn [op & rest] op))
(defmethod parse 'if
[op env [_ test then else :as form] name]
(let [test-expr (disallowing-recur (analyze (assoc env :context :expr) test))
then-expr (analyze env then)
else-expr (analyze env else)]
{:env env :op :if :form form
:test test-expr :then then-expr :else else-expr
:unchecked @*unchecked-if*
:children [test-expr then-expr else-expr]}))
(defmethod parse 'throw
[op env [_ throw :as form] name]
(let [throw-expr (disallowing-recur (analyze (assoc env :context :expr) throw))]
{:env env :op :throw :form form
:throw throw-expr
:children [throw-expr]}))
(defn- block-children [{:keys [statements ret] :as block}]
(when block (conj (vec statements) ret)))
(defmethod parse 'try*
[op env [_ & body :as form] name]
(let [body (vec body)
catchenv (update-in env [:context] #(if (= :expr %) :return %))
tail (peek body)
fblock (when (and (seq? tail) (= 'finally (first tail)))
(rest tail))
finally (when fblock
(analyze-block
(assoc env :context :statement)
fblock))
body (if finally (pop body) body)
tail (peek body)
cblock (when (and (seq? tail)
(= 'catch (first tail)))
(rest tail))
name (first cblock)
locals (:locals catchenv)
locals (if name
(assoc locals name {:name name})
locals)
catch (when cblock
(analyze-block (assoc catchenv :locals locals) (rest cblock)))
body (if name (pop body) body)
try (when body
(analyze-block (if (or name finally) catchenv env) body))]
(when name (assert (not (namespace name)) "Can't qualify symbol in catch"))
{:env env :op :try* :form form
:try try
:finally finally
:name name
:catch catch
:children (vec (mapcat block-children
[try catch finally]))}))
(defmethod parse 'def
[op env form name]
(let [pfn (fn
([_ sym] {:sym sym})
([_ sym init] {:sym sym :init init})
([_ sym doc init] {:sym sym :doc doc :init init}))
args (apply pfn form)
sym (:sym args)
sym-meta (meta sym)
tag (-> sym meta :tag)
protocol (-> sym meta :protocol)
dynamic (-> sym meta :dynamic)
ns-name (-> env :ns :name)]
(assert (not (namespace sym)) "Can't def ns-qualified name")
(let [env (if (or (and (not= ns-name 'cljm.core)
(core-name? env sym))
(get-in @namespaces [ns-name :uses sym]))
(let [ev (resolve-existing-var (dissoc env :locals) sym)]
(when *cljm-warn-on-redef*
(warning env
(str "WARNING: " sym " already refers to: " (symbol (str (:ns ev)) (str sym))
" being replaced by: " (symbol (str ns-name) (str sym)))))
(swap! namespaces update-in [ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
name (:name (resolve-var (dissoc env :locals) sym))
init-expr (when (contains? args :init)
(disallowing-recur
(analyze (assoc env :context :expr) (:init args) sym)))
fn-var? (and init-expr (= (:op init-expr) :fn))
private? (when-let [private? (-> sym meta :private)]
(if (= true private?) true false))
doc (or (:doc args) (-> sym meta :doc))]
(when-let [v (get-in @namespaces [ns-name :defs sym])]
(when (and *cljm-warn-on-fn-var*
(not (-> sym meta :declared))
(and (:fn-var v) (not fn-var?)))
(warning env
(str "WARNING: " (symbol (str ns-name) (str sym))
" no longer fn, references are stale"))))
(swap! namespaces update-in [ns-name :defs sym]
(fn [m]
(let [m (assoc (or m {}) :name name)]
(merge m
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when-let [line (:line env)]
{:file *cljm-file* :line line})
;; the protocol a protocol fn belongs to
(when protocol
{:protocol protocol})
;; symbol for reified protocol
(when-let [protocol-symbol (-> sym meta :protocol-symbol)]
{:protocol-symbol protocol-symbol})
(when fn-var?
{:fn-var true
;; protocol implementation context
:protocol-impl (:protocol-impl init-expr)
;; inline protocol implementation context
:protocol-inline (:protocol-inline init-expr)
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map (fn [m]
(:params m))
(:methods init-expr))})))))
(merge {:env env :op :def :form form
:name name :doc doc :init init-expr}
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when private? {:private private?})
(when sym-meta sym-meta)
(when init-expr {:children [init-expr]})))))
(defn- analyze-fn-method [env locals meth gthis]
(letfn [(uniqify [[p & r]]
(when p
(cons (if (some #{p} r) (gensym (str p)) p)
(uniqify r))))]
(let [params (first meth)
variadic (boolean (some '#{&} params))
params (vec (uniqify (remove '#{&} params)))
fixed-arity (count (if variadic (butlast params) params))
body (next meth)
locals (reduce (fn [m name]
(assoc m name {:name name
:local true
:tag (-> name meta :tag)}))
locals params)
recur-frame {:names params :flag (atom nil)}
block (binding [*recur-frames* (cons recur-frame *recur-frames*)]
(analyze-block (assoc env :context :return :locals locals) body))]
(merge {:env env :variadic variadic :params params :max-fixed-arity fixed-arity
:gthis gthis :recurs @(:flag recur-frame)}
block))))
(defmethod parse 'fn*
[op env [_ & args :as form] name]
(let [[name meths] (if (symbol? (first args))
[(first args) (next args)]
[name (seq args)])
;;turn (fn [] ...) into (fn ([]...))
meths (if (vector? (first meths)) (list meths) meths)
locals (:locals env)
locals (if name (assoc locals name {:name name}) locals)
fields (-> form meta ::fields)
protocol-impl (-> form meta :protocol-impl)
protocol-inline (-> form meta :protocol-inline)
gthis (and fields (gensym "this__"))
locals (reduce (fn [m fld]
(assoc m fld
{:name fld
:field true
:local true
:mutable (-> fld meta :mutable)
:tag (-> fld meta :tag)}))
locals fields)
menv (if (> (count meths) 1) (assoc env :context :expr) env)
menv (merge menv
{:protocol-impl protocol-impl
:protocol-inline protocol-inline})
methods (map #(analyze-fn-method menv locals % gthis) meths)
max-fixed-arity (apply max (map :max-fixed-arity methods))
variadic (boolean (some :variadic methods))
locals (if name (assoc locals name {:name name :fn-var true
:variadic variadic
:max-fixed-arity max-fixed-arity
:method-params (map :params methods)}))
methods (if name
;; a second pass with knowledge of our function-ness/arity
;; lets us optimize self calls
(map #(analyze-fn-method menv locals % gthis) meths)
methods)
imp-fn? (-> form meta :imp-fn)]
;;todo - validate unique arities, at most one variadic, variadic takes max required args
{:env env :op :fn :form form :name name :methods methods :variadic variadic
:recur-frames *recur-frames* :loop-lets *loop-lets*
:max-fixed-arity max-fixed-arity
:protocol-impl protocol-impl
:protocol-inline protocol-inline
:imp-fn imp-fn?
:children (vec (mapcat block-children
methods))}))
(defmethod parse 'letfn*
[op env [_ bindings & exprs :as form] name]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [n->fexpr (into {} (map (juxt first second) (partition 2 bindings)))
names (keys n->fexpr)
n->gsym (into {} (map (juxt identity #(gensym (str % "__"))) names))
gsym->n (into {} (map (juxt n->gsym identity) names))
context (:context env)
bes (reduce (fn [bes n]
(let [g (n->gsym n)]
(conj bes {:name g
:tag (-> n meta :tag)
:local true})))
[]
names)
meth-env (reduce (fn [env be]
(let [n (gsym->n (be :name))]
(assoc-in env [:locals n] be)))
(assoc env :context :expr)
bes)
[meth-env finits]
(reduce (fn [[env finits] n]
(let [finit (analyze meth-env (n->fexpr n))
be (-> (get-in env [:locals n])
(assoc :init finit))]
[(assoc-in env [:locals n] be)
(conj finits finit)]))
[meth-env []]
names)
{:keys [statements ret]}
(analyze-block (assoc meth-env :context (if (= :expr context) :return context)) exprs)
bes (vec (map #(get-in meth-env [:locals %]) names))]
{:env env :op :letfn :bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'do
[op env [_ & exprs :as form] _]
(let [block (analyze-block env exprs)]
(merge {:env env :op :do :form form :children (block-children block)} block)))
(defn analyze-let
[encl-env [_ bindings & exprs :as form] is-loop]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [context (:context encl-env)
[bes env]
(disallowing-recur
(loop [bes []
env (assoc encl-env :context :expr)
bindings (seq (partition 2 bindings))]
(if-let [[name init] (first bindings)]
(do
(assert (not (or (namespace name) (.contains (str name) "."))) (str "Invalid local name: " name))
(let [init-expr (analyze env init)
be {:name (gensym (str name "__"))
:init init-expr
:tag (or (-> name meta :tag)
(-> init-expr :tag)
(-> init-expr :info :tag))
:local true}]
(recur (conj bes be)
(assoc-in env [:locals name] be)
(next bindings))))
[bes env])))
recur-frame (when is-loop {:names (vec (map :name bes)) :flag (atom nil)})
{:keys [statements ret]}
(binding [*recur-frames* (if recur-frame (cons recur-frame *recur-frames*) *recur-frames*)
*loop-lets* (cond
is-loop (or *loop-lets* ())
*loop-lets* (cons {:names (vec (map :name bes))} *loop-lets*))]
(analyze-block (assoc env :context (if (= :expr context) :return context)) exprs))]
{:env encl-env :op :let :loop is-loop
:bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'let*
[op encl-env form _]
(analyze-let encl-env form false))
(defmethod parse 'loop*
[op encl-env form _]
(analyze-let encl-env form true))
(defmethod parse 'recur
[op env [_ & exprs :as form] _]
(let [context (:context env)
frame (first *recur-frames*)
exprs (disallowing-recur (vec (map #(analyze (assoc env :context :expr) %) exprs)))]
(assert frame "Can't recur here")
(assert (= (count exprs) (count (:names frame))) "recur argument count mismatch")
(reset! (:flag frame) true)
(assoc {:env env :op :recur :form form}
:frame frame
:exprs exprs
:children exprs)))
(defmethod parse 'quote
[_ env [_ x] _]
{:op :constant :env env :form x})
(defmethod parse 'new
[_ env [_ ctor & args :as form] _]
(disallowing-recur
(let [enve (assoc env :context :expr)
ctorexpr (analyze enve ctor)
argexprs (vec (map #(analyze enve %) args))
known-num-fields (:num-fields (resolve-existing-var env ctor))
argc (count args)]
(when (and known-num-fields (not= known-num-fields argc))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " ctor)))
{:env env :op :new :form form :ctor ctorexpr :args argexprs
:children (into [ctorexpr] argexprs)})))
(defmethod parse 'set!
[_ env [_ target val alt :as form] _]
(let [[target val] (if alt
;; (set! o -prop val)
[`(. ~target ~val) alt]
[target val])]
(disallowing-recur
(let [enve (assoc env :context :expr)
targetexpr (cond
;; TODO: proper resolve
(= target '*unchecked-if*)
(do
(reset! *unchecked-if* val)
::set-unchecked-if)
(symbol? target)
(do
(let [local (-> env :locals target)]
(assert (or (nil? local)
(and (:field local)
(:mutable local)))
"Can't set! local var or non-mutable field"))
(analyze-symbol enve target))
:else
(when (seq? target)
(let [targetexpr (analyze-seq enve target nil)]
(when (:field targetexpr)
targetexpr))))
valexpr (analyze enve val)]
(assert targetexpr "set! target must be a field or a symbol naming a var")
(cond
(= targetexpr ::set-unchecked-if) {:env env :op :no-op}
:else {:env env :op :set! :form form :target targetexpr :val valexpr
:children [targetexpr valexpr]})))))
(defn munge-path [ss]
(clojure.lang.Compiler/munge (str ss)))
(defn ns->relpath [s]
(str (string/replace (munge-path s) \. \/) ".cljm"))
(declare analyze-file)
(defn analyze-deps [deps]
(doseq [dep deps]
(when-not (:defs (@namespaces dep))
(let [relpath (ns->relpath dep)]
(when (io/resource relpath)
(analyze-file relpath))))))
(defmethod parse 'ns
[_ env [_ name & args :as form] _]
(let [docstring (if (string? (first args)) (first args) nil)
args (if docstring (next args) args)
excludes
(reduce (fn [s [k exclude xs]]
(if (= k :refer-clojure)
(do
(assert (= exclude :exclude) "Only [:refer-clojure :exclude [names]] form supported")
(assert (not (seq s)) "Only one :refer-clojure form is allowed per namespace definition")
(into s xs))
s))
#{} args)
deps (atom #{})
valid-forms (atom #{:use :use-macros :require :require-macros})
error-msg (fn [spec msg] (str msg "; offending spec: " (pr-str spec)))
parse-require-spec (fn parse-require-spec [macros? spec]
(assert (or (symbol? spec) (vector? spec))
(error-msg spec "Only [lib.ns & options] and lib.ns specs supported in :require / :require-macros"))
(when (vector? spec)
(assert (symbol? (first spec))
(error-msg spec "Library name must be specified as a symbol in :require / :require-macros"))
(assert (odd? (count spec))
(error-msg spec "Only :as alias and :refer [names] options supported in :require"))
(assert (every? #{:as :refer} (map first (partition 2 (next spec))))
(error-msg spec "Only :as and :refer options supported in :require / :require-macros"))
(assert (let [fs (frequencies (next spec))]
(and (<= (fs :as 0) 1)
(<= (fs :refer 0) 1)))
(error-msg spec "Each of :as and :refer options may only be specified once in :require / :require-macros")))
(if (symbol? spec)
(recur macros? [spec])
(let [[lib & opts] spec
{alias :as referred :refer :or {alias lib}} (apply hash-map opts)
[rk uk] (if macros? [:require-macros :use-macros] [:require :use])]
(assert (or (symbol? alias) (nil? alias))
(error-msg spec ":as must be followed by a symbol in :require / :require-macros"))
(assert (or (and (vector? referred) (every? symbol? referred))
(nil? referred))
(error-msg spec ":refer must be followed by a vector of symbols in :require / :require-macros"))
(swap! deps conj lib)
(merge (when alias {rk {alias lib}})
(when referred {uk (apply hash-map (interleave referred (repeat lib)))})))))
use->require (fn use->require [[lib kw referred :as spec]]
(assert (and (symbol? lib) (= :only kw) (vector? referred) (every? symbol? referred))
(error-msg spec "Only [lib.ns :only [names]] specs supported in :use / :use-macros"))
[lib :refer referred])
{uses :use requires :require uses-macros :use-macros requires-macros :require-macros :as params}
(reduce (fn [m [k & libs]]
(assert (#{:use :use-macros :require :require-macros} k)
"Only :refer-clojure, :require, :require-macros, :use and :use-macros libspecs supported")
(assert (@valid-forms k)
(str "Only one " k " form is allowed per namespace definition"))
(swap! valid-forms disj k)
(apply merge-with merge m
(map (partial parse-require-spec (contains? #{:require-macros :use-macros} k))
(if (contains? #{:use :use-macros} k)
(map use->require libs)
libs))))
{} (remove (fn [[r]] (= r :refer-clojure)) args))]
(when (seq @deps)
(analyze-deps @deps))
(set! *cljm-ns* name)
(load-core)
(doseq [nsym (concat (vals requires-macros) (vals uses-macros))]
(clojure.core/require nsym))
(swap! namespaces #(-> %
(assoc-in [name :name] name)
(assoc-in [name :excludes] excludes)
(assoc-in [name :uses] uses)
(assoc-in [name :requires] requires)
(assoc-in [name :uses-macros] uses-macros)
(assoc-in [name :requires-macros]
(into {} (map (fn [[alias nsym]]
[alias (find-ns nsym)])
requires-macros)))))
{:env env :op :ns :form form :name name :uses uses :requires requires
:uses-macros uses-macros :requires-macros requires-macros :excludes excludes}))
(defmethod parse 'defprotocol*
[_ env [_ psym & methods :as form] _]
(let [p (:name (resolve-var (dissoc env :locals) psym))]
(swap! namespaces update-in [(-> env :ns :name) :defs psym]
(fn [m]
(let [m (assoc (or m {})
:name p
:type true
:is-protocol true)]
;;:num-fields (count fields))]
(merge m
{:protocols (-> psym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env
:op :defprotocol*
:form form
:p p
:methods methods}))
(defmethod parse 'deftype*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))
superclass (:superclass (meta tsym))
protocols (:protocols (meta tsym))
is-reify? (:reify (meta tsym))
methods (:methods (meta tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {})
:name t
:type true
:num-fields (count fields)
:fields fields)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :deftype* :form form :t t :fields fields :pmasks pmasks :protocols protocols :superclass superclass :reify is-reify? :methods methods}))
(defmethod parse 'defrecord*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {}) :name t :type true)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :defrecord* :form form :t t :fields fields :pmasks pmasks}))
;; dot accessor code
(def ^:private property-symbol? #(boolean (and (symbol? %) (re-matches #"^-.*" (name %)))))
(defn- classify-dot-form
[[target member args]]
[(cond (nil? target) ::error
:default ::expr)
(cond (property-symbol? member) ::property
(symbol? member) ::symbol
(seq? member) ::list
(string? member) ::string
:default ::error)
(cond (nil? args) ()
:default ::expr)])
(defmulti build-dot-form #(classify-dot-form %))
;; (. o -p)
;; (. (...) -p)
(defmethod build-dot-form [::expr ::property ()]
[[target prop _]]
{:dot-action ::access :target target :field (-> prop name (.substring 1) symbol)})
;; (. o -p <args>)
(defmethod build-dot-form [::expr ::property ::list]
[[target prop args]]
(throw (Error. (str "Cannot provide arguments " args " on property access " prop))))
(defn- build-method-call
"Builds the intermediate method call map used to reason about the parsed form during
compilation."
[target meth args]
(cond
(or (symbol? meth) (string? meth)) {:dot-action ::call :target target :method meth :args args}
:else {:dot-action ::call :target target :method (first meth) :args args}))
;; (. o m 1 2)
(defmethod build-dot-form [::expr ::symbol ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o "m" 1 2)
(defmethod build-dot-form [::expr ::string ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o m)
(defmethod build-dot-form [::expr ::symbol ()]
[[target meth args]]
(build-method-call target meth args))
;; (. o (m))
;; (. o (m 1 2))
(defmethod build-dot-form [::expr ::list ()]
[[target meth-expr _]]
(build-method-call target (first meth-expr) (rest meth-expr)))
(defmethod build-dot-form :default
[dot-form]
(throw (Error. (str "Unknown dot form of " (list* '. dot-form) " with classification " (classify-dot-form dot-form)))))
(defmethod parse '.
[_ env [_ target & [field & member+] :as form] _]
(disallowing-recur
(let [{:keys [dot-action target method field args]} (build-dot-form [target field member+])
enve (assoc env :context :expr)
targetexpr (analyze enve target)]
(case dot-action
::access {:env env :op :dot :form form
:target targetexpr
:field field
:children [targetexpr]
:tag (-> form meta :tag)}
::call (let [argexprs (map #(analyze enve %) args)]
{:env env :op :dot :form form
:target targetexpr
:method method
:args argexprs
:children (into [targetexpr] argexprs)
:tag (-> form meta :tag)})))))
(defmethod parse 'objc*
[op env [_ objcform & args :as form] _]
(assert (string? objcform))
(if args
(disallowing-recur
(let [seg (fn seg [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)]
(cons (subs s 0 idx) (seg (subs s (inc end))))))))
enve (assoc env :context :expr)
argexprs (vec (map #(analyze enve %) args))]
{:env env :op :js :segs (seg objcform) :args argexprs
:tag (-> form meta :tag) :form form :children argexprs}))
(let [interp (fn interp [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)
inner (:name (resolve-existing-var env (symbol (subs s (+ 2 idx) end))))]
(cons (subs s 0 idx) (cons inner (interp (subs s (inc end)))))))))]
{:env env :op :js :form form :code (apply str (interp objcform))
:tag (-> form meta :tag)})))
(defn parse-invoke
[env [f & args :as form]]
(disallowing-recur
(let [enve (assoc env :context :expr)
fexpr (analyze enve f)
argexprs (vec (map #(analyze enve %) args))
argc (count args)]
(if (and *cljm-warn-fn-arity* (-> fexpr :info :fn-var))
(let [{:keys [variadic max-fixed-arity method-params name]} (:info fexpr)]
(when (and (not (some #{argc} (map count method-params)))
(or (not variadic)
(and variadic (< argc max-fixed-arity))))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " name)))))
{:env env :op :invoke :form form :f fexpr :args argexprs
:tag (or (-> fexpr :info :tag) (-> form meta :tag)) :children (into [fexpr] argexprs)})))
(defn analyze-symbol
"Finds the var associated with sym"
[env sym]
(let [ret {:env env :form sym}
lb (-> env :locals sym)]
(if lb
(assoc ret :op :var :info lb)
(assoc ret :op :var :info (resolve-existing-var env sym)))))
(defn get-expander [sym env]
(let [mvar
(when-not (or (-> env :locals sym) ;locals hide macros
(and (or (-> env :ns :excludes sym)
(get-in @namespaces [(-> env :ns :name) :excludes sym]))
(not (or (-> env :ns :uses-macros sym)
(get-in @namespaces [(-> env :ns :name) :uses-macros sym])))))
(if-let [nstr (namespace sym)]
(when-let [ns (cond
(= "clojure.core" nstr) (find-ns 'cljm.core)
(.contains nstr ".") (find-ns (symbol nstr))
:else
(-> env :ns :requires-macros (get (symbol nstr))))]
(.findInternedVar ^clojure.lang.Namespace ns (symbol (name sym))))
(if-let [nsym (-> env :ns :uses-macros sym)]
(.findInternedVar ^clojure.lang.Namespace (find-ns nsym) sym)
(.findInternedVar ^clojure.lang.Namespace (find-ns 'cljm.core) sym))))]
(when (and mvar (.isMacro ^clojure.lang.Var mvar))
@mvar)))
(defn macroexpand-1 [env form]
(let [op (first form)]
(if (specials op)
form
(if-let [mac (and (symbol? op) (get-expander op env))]
(binding [*ns* (create-ns *cljm-ns*)]
(apply mac form env (rest form)))
(if (symbol? op)
(let [opname (str op)]
(cond
(= (first opname) \.) (let [[target & args] (next form)]
(with-meta (list* '. target (symbol (subs opname 1)) args)
(meta form)))
(= (last opname) \.) (with-meta
(list* 'new (symbol (subs opname 0 (dec (count opname)))) (next form))
(meta form))
:else form))
form)))))
(defn analyze-seq
[env form name]
(let [env (assoc env :line
(or (-> form meta :line)
(:line env)))]
(let [op (first form)]
(assert (not (nil? op)) "Can't call nil")
(let [mform (macroexpand-1 env form)]
(if (identical? form mform)
(if (specials op)
(parse op env form name)
(parse-invoke env form))
(analyze env mform name))))))
(declare analyze-wrap-meta)
(defn analyze-map
[env form name]
(let [expr-env (assoc env :context :expr)
simple-keys? (every? #(or (string? %) (keyword? %))
(keys form))
ks (disallowing-recur (vec (map #(analyze expr-env % name) (keys form))))
vs (disallowing-recur (vec (map #(analyze expr-env % name) (vals form))))]
(analyze-wrap-meta {:op :map :env env :form form
:keys ks :vals vs :simple-keys? simple-keys?
:children (vec (interleave ks vs))}
name)))
(defn analyze-vector
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :vector :env env :form form :items items :children items} name)))
(defn analyze-set
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :set :env env :form form :items items :children items} name)))
(defn analyze-wrap-meta [expr name]
(let [form (:form expr)]
(if (meta form)
(let [env (:env expr) ; take on expr's context ourselves
expr (assoc-in expr [:env :context] :expr) ; change expr to :expr
meta-expr (analyze-map (:env expr) (meta form) name)]
{:op :meta :env env :form form
:meta meta-expr :expr expr :children [meta-expr expr]})
expr)))
(defn analyze
"Given an environment, a map containing {:locals (mapping of names to bindings), :context
(one of :statement, :expr, :return), :ns (a symbol naming the
compilation ns)}, and form, returns an expression object (a map
containing at least :form, :op and :env keys). If expr has any (immediately)
nested exprs, must have :children [exprs...] entry. This will
facilitate code walking without knowing the details of the op set."
([env form] (analyze env form nil))
([env form name]
(let [form (if (instance? clojure.lang.LazySeq form)
(or (seq form) ())
form)]
(load-core)
(cond
(symbol? form) (analyze-symbol env form)
(and (seq? form) (seq form)) (analyze-seq env form name)
(map? form) (analyze-map env form name)
(vector? form) (analyze-vector env form name)
(set? form) (analyze-set env form name)
(keyword? form) (analyze-keyword env form)
:else {:op :constant :env env :form form}))))
(defn analyze-file
[^String f]
(let [res (if (re-find #"^file://" f) (java.net.URL. f) (io/resource f))]
(assert res (str "Can't find " f " in classpath"))
(binding [*cljm-ns* 'cljm.user
*cljm-file* (.getPath ^java.net.URL res)
*ns* *reader-ns*]
(with-open [r (io/reader res)]
(let [env (empty-env)
pbr (clojure.lang.LineNumberingPushbackReader. r)
eof (Object.)]
(loop [r (read pbr false eof false)]
(let [env (assoc env :ns (get-namespace *cljm-ns*))]
(when-not (identical? eof r)
(analyze env r)
(recur (read pbr false eof false))))))))))
|
88864
|
; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(set! *warn-on-reflection* true)
(ns cljm.analyzer
(:refer-clojure :exclude [macroexpand-1])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[cljm.tagged-literals :as tags])
(:import java.lang.StringBuilder))
(declare resolve-var)
(declare resolve-existing-var)
(declare warning)
(def ^:dynamic *cljm-warn-on-undeclared* false)
(declare confirm-bindings)
(declare ^:dynamic *cljm-file*)
;; to resolve keywords like ::foo - the namespace
;; must be determined during analysis - the reader
;; did not know
(def ^:dynamic *reader-ns-name* (gensym))
(def ^:dynamic *reader-ns* (create-ns *reader-ns-name*))
(defonce namespaces (atom '{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn reset-namespaces! []
(reset! namespaces
'{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn get-namespace [key]
(@namespaces key))
(defn set-namespace [key val]
(swap! namespaces assoc key val))
(def ^:dynamic *cljm-ns* 'cljm.user)
(def ^:dynamic *cljm-file* nil)
(def ^:dynamic *cljm-warn-on-redef* true)
(def ^:dynamic *cljm-warn-on-dynamic* true)
(def ^:dynamic *cljm-warn-on-fn-var* true)
(def ^:dynamic *cljm-warn-fn-arity* true)
(def ^:dynamic *unchecked-if* (atom false))
(def ^:dynamic *cljm-static-fns* false)
(def ^:dynamic *cljm-macros-path* "/cljm/core")
(def ^:dynamic *cljm-macros-is-classpath* true)
(def -cljm-macros-loaded (atom false))
(defn load-core []
(when (not @-cljm-macros-loaded)
(reset! -cljm-macros-loaded true)
(if *cljm-macros-is-classpath*
(load *cljm-macros-path*)
(load-file *cljm-macros-path*))))
(defmacro with-core-macros
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path]
~@body)))
(defmacro with-core-macros-file
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path
*cljm-macros-is-classpath* false]
~@body)))
(defn empty-env []
{:ns (@namespaces *cljm-ns*) :context :statement :locals {}})
(defmacro ^:private debug-prn
[& args]
`(.println System/err (str ~@args)))
(defn warning [env s]
(binding [*out* *err*]
(println
(str s (when (:line env)
(str " at line " (:line env) " " *cljm-file*))))))
(defn confirm-var-exists [env prefix suffix]
(when *cljm-warn-on-undeclared*
(let [crnt-ns (-> env :ns :name)]
(when (= prefix crnt-ns)
(when-not (-> @namespaces crnt-ns :defs suffix)
(warning env
(str "WARNING: Use of undeclared Var " prefix "/" suffix)))))))
(defn resolve-ns-alias [env name]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (get (:defs (@namespaces 'cljm.core)) sym)
(not (contains? (-> env :ns :excludes) sym))))
(defn resolve-existing-var [env sym]
(cond
; If the namespace is all caps then we assume it's the class prefix for an
; Objective-C class.
(and (not (nil? (namespace sym))) (= (string/upper-case (namespace sym)) (namespace sym)))
{:name (symbol (str (namespace sym) (name sym))) :ns 'ObjectiveCClass}
(= (namespace sym) "js")
{:name sym :ns 'js}
:else
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)
full-ns (resolve-ns-alias env ns)]
(confirm-var-exists env full-ns (symbol (name sym)))
(merge (get-in @namespaces [full-ns :defs (symbol (name sym))])
{:name (symbol (str full-ns) (str (name sym)))
:ns full-ns}))
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s (inc idx))
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
(do
(confirm-var-exists env prefix (symbol suffix))
(merge (get-in @namespaces [prefix :defs (symbol suffix)])
{:name (if (= "" prefix) (symbol suffix) (symbol (str prefix) suffix))
:ns prefix}))))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns (-> env :ns :name)}))
:else
(let [full-ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
(confirm-var-exists env full-ns sym)
(merge (get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns full-ns}))))))
(defn resolve-var [env sym]
(if (= (namespace sym) "js")
{:name sym}
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)]
{:name (symbol (str (resolve-ns-alias env ns)) (name sym))})
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s idx)
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
{:name sym}))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (name sym))}))
:else
(let [ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
{:name (symbol (str ns) (name sym))})))))
(defn confirm-bindings [env names]
(doseq [name names]
(let [env (merge env {:ns (@namespaces *cljm-ns*)})
ev (resolve-existing-var env name)]
(when (and *cljm-warn-on-dynamic*
ev (not (-> ev :dynamic)))
(warning env
(str "WARNING: " (:name ev) " not declared ^:dynamic"))))))
(declare analyze analyze-symbol analyze-seq)
(def specials '#{if def fn* do let* loop* letfn* throw try* recur new set! ns defprotocol* deftype* defrecord* . objc* & quote})
(def ^:dynamic *recur-frames* nil)
(def ^:dynamic *loop-lets* nil)
(defmacro disallowing-recur [& body]
`(binding [*recur-frames* (cons nil *recur-frames*)] ~@body))
(defn analyze-keyword
[env sym]
{:op :constant :env env
:form (if (= (namespace sym) (name *reader-ns-name*))
(keyword (-> env :ns :name name) (name sym))
sym)})
(defn analyze-block
"returns {:statements .. :ret ..}"
[env exprs]
(let [statements (disallowing-recur
(seq (map #(analyze (assoc env :context :statement) %) (butlast exprs))))
ret (if (<= (count exprs) 1)
(analyze env (first exprs))
(analyze (assoc env :context (if (= :statement (:context env)) :statement :return)) (last exprs)))]
{:statements statements :ret ret}))
(defmulti parse (fn [op & rest] op))
(defmethod parse 'if
[op env [_ test then else :as form] name]
(let [test-expr (disallowing-recur (analyze (assoc env :context :expr) test))
then-expr (analyze env then)
else-expr (analyze env else)]
{:env env :op :if :form form
:test test-expr :then then-expr :else else-expr
:unchecked @*unchecked-if*
:children [test-expr then-expr else-expr]}))
(defmethod parse 'throw
[op env [_ throw :as form] name]
(let [throw-expr (disallowing-recur (analyze (assoc env :context :expr) throw))]
{:env env :op :throw :form form
:throw throw-expr
:children [throw-expr]}))
(defn- block-children [{:keys [statements ret] :as block}]
(when block (conj (vec statements) ret)))
(defmethod parse 'try*
[op env [_ & body :as form] name]
(let [body (vec body)
catchenv (update-in env [:context] #(if (= :expr %) :return %))
tail (peek body)
fblock (when (and (seq? tail) (= 'finally (first tail)))
(rest tail))
finally (when fblock
(analyze-block
(assoc env :context :statement)
fblock))
body (if finally (pop body) body)
tail (peek body)
cblock (when (and (seq? tail)
(= 'catch (first tail)))
(rest tail))
name (first cblock)
locals (:locals catchenv)
locals (if name
(assoc locals name {:name name})
locals)
catch (when cblock
(analyze-block (assoc catchenv :locals locals) (rest cblock)))
body (if name (pop body) body)
try (when body
(analyze-block (if (or name finally) catchenv env) body))]
(when name (assert (not (namespace name)) "Can't qualify symbol in catch"))
{:env env :op :try* :form form
:try try
:finally finally
:name name
:catch catch
:children (vec (mapcat block-children
[try catch finally]))}))
(defmethod parse 'def
[op env form name]
(let [pfn (fn
([_ sym] {:sym sym})
([_ sym init] {:sym sym :init init})
([_ sym doc init] {:sym sym :doc doc :init init}))
args (apply pfn form)
sym (:sym args)
sym-meta (meta sym)
tag (-> sym meta :tag)
protocol (-> sym meta :protocol)
dynamic (-> sym meta :dynamic)
ns-name (-> env :ns :name)]
(assert (not (namespace sym)) "Can't def ns-qualified name")
(let [env (if (or (and (not= ns-name 'cljm.core)
(core-name? env sym))
(get-in @namespaces [ns-name :uses sym]))
(let [ev (resolve-existing-var (dissoc env :locals) sym)]
(when *cljm-warn-on-redef*
(warning env
(str "WARNING: " sym " already refers to: " (symbol (str (:ns ev)) (str sym))
" being replaced by: " (symbol (str ns-name) (str sym)))))
(swap! namespaces update-in [ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
name (:name (resolve-var (dissoc env :locals) sym))
init-expr (when (contains? args :init)
(disallowing-recur
(analyze (assoc env :context :expr) (:init args) sym)))
fn-var? (and init-expr (= (:op init-expr) :fn))
private? (when-let [private? (-> sym meta :private)]
(if (= true private?) true false))
doc (or (:doc args) (-> sym meta :doc))]
(when-let [v (get-in @namespaces [ns-name :defs sym])]
(when (and *cljm-warn-on-fn-var*
(not (-> sym meta :declared))
(and (:fn-var v) (not fn-var?)))
(warning env
(str "WARNING: " (symbol (str ns-name) (str sym))
" no longer fn, references are stale"))))
(swap! namespaces update-in [ns-name :defs sym]
(fn [m]
(let [m (assoc (or m {}) :name name)]
(merge m
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when-let [line (:line env)]
{:file *cljm-file* :line line})
;; the protocol a protocol fn belongs to
(when protocol
{:protocol protocol})
;; symbol for reified protocol
(when-let [protocol-symbol (-> sym meta :protocol-symbol)]
{:protocol-symbol protocol-symbol})
(when fn-var?
{:fn-var true
;; protocol implementation context
:protocol-impl (:protocol-impl init-expr)
;; inline protocol implementation context
:protocol-inline (:protocol-inline init-expr)
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map (fn [m]
(:params m))
(:methods init-expr))})))))
(merge {:env env :op :def :form form
:name name :doc doc :init init-expr}
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when private? {:private private?})
(when sym-meta sym-meta)
(when init-expr {:children [init-expr]})))))
(defn- analyze-fn-method [env locals meth gthis]
(letfn [(uniqify [[p & r]]
(when p
(cons (if (some #{p} r) (gensym (str p)) p)
(uniqify r))))]
(let [params (first meth)
variadic (boolean (some '#{&} params))
params (vec (uniqify (remove '#{&} params)))
fixed-arity (count (if variadic (butlast params) params))
body (next meth)
locals (reduce (fn [m name]
(assoc m name {:name name
:local true
:tag (-> name meta :tag)}))
locals params)
recur-frame {:names params :flag (atom nil)}
block (binding [*recur-frames* (cons recur-frame *recur-frames*)]
(analyze-block (assoc env :context :return :locals locals) body))]
(merge {:env env :variadic variadic :params params :max-fixed-arity fixed-arity
:gthis gthis :recurs @(:flag recur-frame)}
block))))
(defmethod parse 'fn*
[op env [_ & args :as form] name]
(let [[name meths] (if (symbol? (first args))
[(first args) (next args)]
[name (seq args)])
;;turn (fn [] ...) into (fn ([]...))
meths (if (vector? (first meths)) (list meths) meths)
locals (:locals env)
locals (if name (assoc locals name {:name name}) locals)
fields (-> form meta ::fields)
protocol-impl (-> form meta :protocol-impl)
protocol-inline (-> form meta :protocol-inline)
gthis (and fields (gensym "this__"))
locals (reduce (fn [m fld]
(assoc m fld
{:name fld
:field true
:local true
:mutable (-> fld meta :mutable)
:tag (-> fld meta :tag)}))
locals fields)
menv (if (> (count meths) 1) (assoc env :context :expr) env)
menv (merge menv
{:protocol-impl protocol-impl
:protocol-inline protocol-inline})
methods (map #(analyze-fn-method menv locals % gthis) meths)
max-fixed-arity (apply max (map :max-fixed-arity methods))
variadic (boolean (some :variadic methods))
locals (if name (assoc locals name {:name name :fn-var true
:variadic variadic
:max-fixed-arity max-fixed-arity
:method-params (map :params methods)}))
methods (if name
;; a second pass with knowledge of our function-ness/arity
;; lets us optimize self calls
(map #(analyze-fn-method menv locals % gthis) meths)
methods)
imp-fn? (-> form meta :imp-fn)]
;;todo - validate unique arities, at most one variadic, variadic takes max required args
{:env env :op :fn :form form :name name :methods methods :variadic variadic
:recur-frames *recur-frames* :loop-lets *loop-lets*
:max-fixed-arity max-fixed-arity
:protocol-impl protocol-impl
:protocol-inline protocol-inline
:imp-fn imp-fn?
:children (vec (mapcat block-children
methods))}))
(defmethod parse 'letfn*
[op env [_ bindings & exprs :as form] name]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [n->fexpr (into {} (map (juxt first second) (partition 2 bindings)))
names (keys n->fexpr)
n->gsym (into {} (map (juxt identity #(gensym (str % "__"))) names))
gsym->n (into {} (map (juxt n->gsym identity) names))
context (:context env)
bes (reduce (fn [bes n]
(let [g (n->gsym n)]
(conj bes {:name g
:tag (-> n meta :tag)
:local true})))
[]
names)
meth-env (reduce (fn [env be]
(let [n (gsym->n (be :name))]
(assoc-in env [:locals n] be)))
(assoc env :context :expr)
bes)
[meth-env finits]
(reduce (fn [[env finits] n]
(let [finit (analyze meth-env (n->fexpr n))
be (-> (get-in env [:locals n])
(assoc :init finit))]
[(assoc-in env [:locals n] be)
(conj finits finit)]))
[meth-env []]
names)
{:keys [statements ret]}
(analyze-block (assoc meth-env :context (if (= :expr context) :return context)) exprs)
bes (vec (map #(get-in meth-env [:locals %]) names))]
{:env env :op :letfn :bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'do
[op env [_ & exprs :as form] _]
(let [block (analyze-block env exprs)]
(merge {:env env :op :do :form form :children (block-children block)} block)))
(defn analyze-let
[encl-env [_ bindings & exprs :as form] is-loop]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [context (:context encl-env)
[bes env]
(disallowing-recur
(loop [bes []
env (assoc encl-env :context :expr)
bindings (seq (partition 2 bindings))]
(if-let [[name init] (first bindings)]
(do
(assert (not (or (namespace name) (.contains (str name) "."))) (str "Invalid local name: " name))
(let [init-expr (analyze env init)
be {:name (gensym (str name "__"))
:init init-expr
:tag (or (-> name meta :tag)
(-> init-expr :tag)
(-> init-expr :info :tag))
:local true}]
(recur (conj bes be)
(assoc-in env [:locals name] be)
(next bindings))))
[bes env])))
recur-frame (when is-loop {:names (vec (map :name bes)) :flag (atom nil)})
{:keys [statements ret]}
(binding [*recur-frames* (if recur-frame (cons recur-frame *recur-frames*) *recur-frames*)
*loop-lets* (cond
is-loop (or *loop-lets* ())
*loop-lets* (cons {:names (vec (map :name bes))} *loop-lets*))]
(analyze-block (assoc env :context (if (= :expr context) :return context)) exprs))]
{:env encl-env :op :let :loop is-loop
:bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'let*
[op encl-env form _]
(analyze-let encl-env form false))
(defmethod parse 'loop*
[op encl-env form _]
(analyze-let encl-env form true))
(defmethod parse 'recur
[op env [_ & exprs :as form] _]
(let [context (:context env)
frame (first *recur-frames*)
exprs (disallowing-recur (vec (map #(analyze (assoc env :context :expr) %) exprs)))]
(assert frame "Can't recur here")
(assert (= (count exprs) (count (:names frame))) "recur argument count mismatch")
(reset! (:flag frame) true)
(assoc {:env env :op :recur :form form}
:frame frame
:exprs exprs
:children exprs)))
(defmethod parse 'quote
[_ env [_ x] _]
{:op :constant :env env :form x})
(defmethod parse 'new
[_ env [_ ctor & args :as form] _]
(disallowing-recur
(let [enve (assoc env :context :expr)
ctorexpr (analyze enve ctor)
argexprs (vec (map #(analyze enve %) args))
known-num-fields (:num-fields (resolve-existing-var env ctor))
argc (count args)]
(when (and known-num-fields (not= known-num-fields argc))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " ctor)))
{:env env :op :new :form form :ctor ctorexpr :args argexprs
:children (into [ctorexpr] argexprs)})))
(defmethod parse 'set!
[_ env [_ target val alt :as form] _]
(let [[target val] (if alt
;; (set! o -prop val)
[`(. ~target ~val) alt]
[target val])]
(disallowing-recur
(let [enve (assoc env :context :expr)
targetexpr (cond
;; TODO: proper resolve
(= target '*unchecked-if*)
(do
(reset! *unchecked-if* val)
::set-unchecked-if)
(symbol? target)
(do
(let [local (-> env :locals target)]
(assert (or (nil? local)
(and (:field local)
(:mutable local)))
"Can't set! local var or non-mutable field"))
(analyze-symbol enve target))
:else
(when (seq? target)
(let [targetexpr (analyze-seq enve target nil)]
(when (:field targetexpr)
targetexpr))))
valexpr (analyze enve val)]
(assert targetexpr "set! target must be a field or a symbol naming a var")
(cond
(= targetexpr ::set-unchecked-if) {:env env :op :no-op}
:else {:env env :op :set! :form form :target targetexpr :val valexpr
:children [targetexpr valexpr]})))))
(defn munge-path [ss]
(clojure.lang.Compiler/munge (str ss)))
(defn ns->relpath [s]
(str (string/replace (munge-path s) \. \/) ".cljm"))
(declare analyze-file)
(defn analyze-deps [deps]
(doseq [dep deps]
(when-not (:defs (@namespaces dep))
(let [relpath (ns->relpath dep)]
(when (io/resource relpath)
(analyze-file relpath))))))
(defmethod parse 'ns
[_ env [_ name & args :as form] _]
(let [docstring (if (string? (first args)) (first args) nil)
args (if docstring (next args) args)
excludes
(reduce (fn [s [k exclude xs]]
(if (= k :refer-clojure)
(do
(assert (= exclude :exclude) "Only [:refer-clojure :exclude [names]] form supported")
(assert (not (seq s)) "Only one :refer-clojure form is allowed per namespace definition")
(into s xs))
s))
#{} args)
deps (atom #{})
valid-forms (atom #{:use :use-macros :require :require-macros})
error-msg (fn [spec msg] (str msg "; offending spec: " (pr-str spec)))
parse-require-spec (fn parse-require-spec [macros? spec]
(assert (or (symbol? spec) (vector? spec))
(error-msg spec "Only [lib.ns & options] and lib.ns specs supported in :require / :require-macros"))
(when (vector? spec)
(assert (symbol? (first spec))
(error-msg spec "Library name must be specified as a symbol in :require / :require-macros"))
(assert (odd? (count spec))
(error-msg spec "Only :as alias and :refer [names] options supported in :require"))
(assert (every? #{:as :refer} (map first (partition 2 (next spec))))
(error-msg spec "Only :as and :refer options supported in :require / :require-macros"))
(assert (let [fs (frequencies (next spec))]
(and (<= (fs :as 0) 1)
(<= (fs :refer 0) 1)))
(error-msg spec "Each of :as and :refer options may only be specified once in :require / :require-macros")))
(if (symbol? spec)
(recur macros? [spec])
(let [[lib & opts] spec
{alias :as referred :refer :or {alias lib}} (apply hash-map opts)
[rk uk] (if macros? [:require-macros :use-macros] [:require :use])]
(assert (or (symbol? alias) (nil? alias))
(error-msg spec ":as must be followed by a symbol in :require / :require-macros"))
(assert (or (and (vector? referred) (every? symbol? referred))
(nil? referred))
(error-msg spec ":refer must be followed by a vector of symbols in :require / :require-macros"))
(swap! deps conj lib)
(merge (when alias {rk {alias lib}})
(when referred {uk (apply hash-map (interleave referred (repeat lib)))})))))
use->require (fn use->require [[lib kw referred :as spec]]
(assert (and (symbol? lib) (= :only kw) (vector? referred) (every? symbol? referred))
(error-msg spec "Only [lib.ns :only [names]] specs supported in :use / :use-macros"))
[lib :refer referred])
{uses :use requires :require uses-macros :use-macros requires-macros :require-macros :as params}
(reduce (fn [m [k & libs]]
(assert (#{:use :use-macros :require :require-macros} k)
"Only :refer-clojure, :require, :require-macros, :use and :use-macros libspecs supported")
(assert (@valid-forms k)
(str "Only one " k " form is allowed per namespace definition"))
(swap! valid-forms disj k)
(apply merge-with merge m
(map (partial parse-require-spec (contains? #{:require-macros :use-macros} k))
(if (contains? #{:use :use-macros} k)
(map use->require libs)
libs))))
{} (remove (fn [[r]] (= r :refer-clojure)) args))]
(when (seq @deps)
(analyze-deps @deps))
(set! *cljm-ns* name)
(load-core)
(doseq [nsym (concat (vals requires-macros) (vals uses-macros))]
(clojure.core/require nsym))
(swap! namespaces #(-> %
(assoc-in [name :name] name)
(assoc-in [name :excludes] excludes)
(assoc-in [name :uses] uses)
(assoc-in [name :requires] requires)
(assoc-in [name :uses-macros] uses-macros)
(assoc-in [name :requires-macros]
(into {} (map (fn [[alias nsym]]
[alias (find-ns nsym)])
requires-macros)))))
{:env env :op :ns :form form :name name :uses uses :requires requires
:uses-macros uses-macros :requires-macros requires-macros :excludes excludes}))
(defmethod parse 'defprotocol*
[_ env [_ psym & methods :as form] _]
(let [p (:name (resolve-var (dissoc env :locals) psym))]
(swap! namespaces update-in [(-> env :ns :name) :defs psym]
(fn [m]
(let [m (assoc (or m {})
:name p
:type true
:is-protocol true)]
;;:num-fields (count fields))]
(merge m
{:protocols (-> psym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env
:op :defprotocol*
:form form
:p p
:methods methods}))
(defmethod parse 'deftype*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))
superclass (:superclass (meta tsym))
protocols (:protocols (meta tsym))
is-reify? (:reify (meta tsym))
methods (:methods (meta tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {})
:name t
:type true
:num-fields (count fields)
:fields fields)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :deftype* :form form :t t :fields fields :pmasks pmasks :protocols protocols :superclass superclass :reify is-reify? :methods methods}))
(defmethod parse 'defrecord*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {}) :name t :type true)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :defrecord* :form form :t t :fields fields :pmasks pmasks}))
;; dot accessor code
(def ^:private property-symbol? #(boolean (and (symbol? %) (re-matches #"^-.*" (name %)))))
(defn- classify-dot-form
[[target member args]]
[(cond (nil? target) ::error
:default ::expr)
(cond (property-symbol? member) ::property
(symbol? member) ::symbol
(seq? member) ::list
(string? member) ::string
:default ::error)
(cond (nil? args) ()
:default ::expr)])
(defmulti build-dot-form #(classify-dot-form %))
;; (. o -p)
;; (. (...) -p)
(defmethod build-dot-form [::expr ::property ()]
[[target prop _]]
{:dot-action ::access :target target :field (-> prop name (.substring 1) symbol)})
;; (. o -p <args>)
(defmethod build-dot-form [::expr ::property ::list]
[[target prop args]]
(throw (Error. (str "Cannot provide arguments " args " on property access " prop))))
(defn- build-method-call
"Builds the intermediate method call map used to reason about the parsed form during
compilation."
[target meth args]
(cond
(or (symbol? meth) (string? meth)) {:dot-action ::call :target target :method meth :args args}
:else {:dot-action ::call :target target :method (first meth) :args args}))
;; (. o m 1 2)
(defmethod build-dot-form [::expr ::symbol ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o "m" 1 2)
(defmethod build-dot-form [::expr ::string ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o m)
(defmethod build-dot-form [::expr ::symbol ()]
[[target meth args]]
(build-method-call target meth args))
;; (. o (m))
;; (. o (m 1 2))
(defmethod build-dot-form [::expr ::list ()]
[[target meth-expr _]]
(build-method-call target (first meth-expr) (rest meth-expr)))
(defmethod build-dot-form :default
[dot-form]
(throw (Error. (str "Unknown dot form of " (list* '. dot-form) " with classification " (classify-dot-form dot-form)))))
(defmethod parse '.
[_ env [_ target & [field & member+] :as form] _]
(disallowing-recur
(let [{:keys [dot-action target method field args]} (build-dot-form [target field member+])
enve (assoc env :context :expr)
targetexpr (analyze enve target)]
(case dot-action
::access {:env env :op :dot :form form
:target targetexpr
:field field
:children [targetexpr]
:tag (-> form meta :tag)}
::call (let [argexprs (map #(analyze enve %) args)]
{:env env :op :dot :form form
:target targetexpr
:method method
:args argexprs
:children (into [targetexpr] argexprs)
:tag (-> form meta :tag)})))))
(defmethod parse 'objc*
[op env [_ objcform & args :as form] _]
(assert (string? objcform))
(if args
(disallowing-recur
(let [seg (fn seg [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)]
(cons (subs s 0 idx) (seg (subs s (inc end))))))))
enve (assoc env :context :expr)
argexprs (vec (map #(analyze enve %) args))]
{:env env :op :js :segs (seg objcform) :args argexprs
:tag (-> form meta :tag) :form form :children argexprs}))
(let [interp (fn interp [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)
inner (:name (resolve-existing-var env (symbol (subs s (+ 2 idx) end))))]
(cons (subs s 0 idx) (cons inner (interp (subs s (inc end)))))))))]
{:env env :op :js :form form :code (apply str (interp objcform))
:tag (-> form meta :tag)})))
(defn parse-invoke
[env [f & args :as form]]
(disallowing-recur
(let [enve (assoc env :context :expr)
fexpr (analyze enve f)
argexprs (vec (map #(analyze enve %) args))
argc (count args)]
(if (and *cljm-warn-fn-arity* (-> fexpr :info :fn-var))
(let [{:keys [variadic max-fixed-arity method-params name]} (:info fexpr)]
(when (and (not (some #{argc} (map count method-params)))
(or (not variadic)
(and variadic (< argc max-fixed-arity))))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " name)))))
{:env env :op :invoke :form form :f fexpr :args argexprs
:tag (or (-> fexpr :info :tag) (-> form meta :tag)) :children (into [fexpr] argexprs)})))
(defn analyze-symbol
"Finds the var associated with sym"
[env sym]
(let [ret {:env env :form sym}
lb (-> env :locals sym)]
(if lb
(assoc ret :op :var :info lb)
(assoc ret :op :var :info (resolve-existing-var env sym)))))
(defn get-expander [sym env]
(let [mvar
(when-not (or (-> env :locals sym) ;locals hide macros
(and (or (-> env :ns :excludes sym)
(get-in @namespaces [(-> env :ns :name) :excludes sym]))
(not (or (-> env :ns :uses-macros sym)
(get-in @namespaces [(-> env :ns :name) :uses-macros sym])))))
(if-let [nstr (namespace sym)]
(when-let [ns (cond
(= "clojure.core" nstr) (find-ns 'cljm.core)
(.contains nstr ".") (find-ns (symbol nstr))
:else
(-> env :ns :requires-macros (get (symbol nstr))))]
(.findInternedVar ^clojure.lang.Namespace ns (symbol (name sym))))
(if-let [nsym (-> env :ns :uses-macros sym)]
(.findInternedVar ^clojure.lang.Namespace (find-ns nsym) sym)
(.findInternedVar ^clojure.lang.Namespace (find-ns 'cljm.core) sym))))]
(when (and mvar (.isMacro ^clojure.lang.Var mvar))
@mvar)))
(defn macroexpand-1 [env form]
(let [op (first form)]
(if (specials op)
form
(if-let [mac (and (symbol? op) (get-expander op env))]
(binding [*ns* (create-ns *cljm-ns*)]
(apply mac form env (rest form)))
(if (symbol? op)
(let [opname (str op)]
(cond
(= (first opname) \.) (let [[target & args] (next form)]
(with-meta (list* '. target (symbol (subs opname 1)) args)
(meta form)))
(= (last opname) \.) (with-meta
(list* 'new (symbol (subs opname 0 (dec (count opname)))) (next form))
(meta form))
:else form))
form)))))
(defn analyze-seq
[env form name]
(let [env (assoc env :line
(or (-> form meta :line)
(:line env)))]
(let [op (first form)]
(assert (not (nil? op)) "Can't call nil")
(let [mform (macroexpand-1 env form)]
(if (identical? form mform)
(if (specials op)
(parse op env form name)
(parse-invoke env form))
(analyze env mform name))))))
(declare analyze-wrap-meta)
(defn analyze-map
[env form name]
(let [expr-env (assoc env :context :expr)
simple-keys? (every? #(or (string? %) (keyword? %))
(keys form))
ks (disallowing-recur (vec (map #(analyze expr-env % name) (keys form))))
vs (disallowing-recur (vec (map #(analyze expr-env % name) (vals form))))]
(analyze-wrap-meta {:op :map :env env :form form
:keys ks :vals vs :simple-keys? simple-keys?
:children (vec (interleave ks vs))}
name)))
(defn analyze-vector
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :vector :env env :form form :items items :children items} name)))
(defn analyze-set
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :set :env env :form form :items items :children items} name)))
(defn analyze-wrap-meta [expr name]
(let [form (:form expr)]
(if (meta form)
(let [env (:env expr) ; take on expr's context ourselves
expr (assoc-in expr [:env :context] :expr) ; change expr to :expr
meta-expr (analyze-map (:env expr) (meta form) name)]
{:op :meta :env env :form form
:meta meta-expr :expr expr :children [meta-expr expr]})
expr)))
(defn analyze
"Given an environment, a map containing {:locals (mapping of names to bindings), :context
(one of :statement, :expr, :return), :ns (a symbol naming the
compilation ns)}, and form, returns an expression object (a map
containing at least :form, :op and :env keys). If expr has any (immediately)
nested exprs, must have :children [exprs...] entry. This will
facilitate code walking without knowing the details of the op set."
([env form] (analyze env form nil))
([env form name]
(let [form (if (instance? clojure.lang.LazySeq form)
(or (seq form) ())
form)]
(load-core)
(cond
(symbol? form) (analyze-symbol env form)
(and (seq? form) (seq form)) (analyze-seq env form name)
(map? form) (analyze-map env form name)
(vector? form) (analyze-vector env form name)
(set? form) (analyze-set env form name)
(keyword? form) (analyze-keyword env form)
:else {:op :constant :env env :form form}))))
(defn analyze-file
[^String f]
(let [res (if (re-find #"^file://" f) (java.net.URL. f) (io/resource f))]
(assert res (str "Can't find " f " in classpath"))
(binding [*cljm-ns* 'cljm.user
*cljm-file* (.getPath ^java.net.URL res)
*ns* *reader-ns*]
(with-open [r (io/reader res)]
(let [env (empty-env)
pbr (clojure.lang.LineNumberingPushbackReader. r)
eof (Object.)]
(loop [r (read pbr false eof false)]
(let [env (assoc env :ns (get-namespace *cljm-ns*))]
(when-not (identical? eof r)
(analyze env r)
(recur (read pbr false eof false))))))))))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(set! *warn-on-reflection* true)
(ns cljm.analyzer
(:refer-clojure :exclude [macroexpand-1])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[cljm.tagged-literals :as tags])
(:import java.lang.StringBuilder))
(declare resolve-var)
(declare resolve-existing-var)
(declare warning)
(def ^:dynamic *cljm-warn-on-undeclared* false)
(declare confirm-bindings)
(declare ^:dynamic *cljm-file*)
;; to resolve keywords like ::foo - the namespace
;; must be determined during analysis - the reader
;; did not know
(def ^:dynamic *reader-ns-name* (gensym))
(def ^:dynamic *reader-ns* (create-ns *reader-ns-name*))
(defonce namespaces (atom '{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn reset-namespaces! []
(reset! namespaces
'{cljm.core {:name cljm.core}
cljm.user {:name cljm.user}}))
(defn get-namespace [key]
(@namespaces key))
(defn set-namespace [key val]
(swap! namespaces assoc key val))
(def ^:dynamic *cljm-ns* 'cljm.user)
(def ^:dynamic *cljm-file* nil)
(def ^:dynamic *cljm-warn-on-redef* true)
(def ^:dynamic *cljm-warn-on-dynamic* true)
(def ^:dynamic *cljm-warn-on-fn-var* true)
(def ^:dynamic *cljm-warn-fn-arity* true)
(def ^:dynamic *unchecked-if* (atom false))
(def ^:dynamic *cljm-static-fns* false)
(def ^:dynamic *cljm-macros-path* "/cljm/core")
(def ^:dynamic *cljm-macros-is-classpath* true)
(def -cljm-macros-loaded (atom false))
(defn load-core []
(when (not @-cljm-macros-loaded)
(reset! -cljm-macros-loaded true)
(if *cljm-macros-is-classpath*
(load *cljm-macros-path*)
(load-file *cljm-macros-path*))))
(defmacro with-core-macros
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path]
~@body)))
(defmacro with-core-macros-file
[path & body]
`(do
(when (not= *cljm-macros-path* ~path)
(reset! -cljm-macros-loaded false))
(binding [*cljm-macros-path* ~path
*cljm-macros-is-classpath* false]
~@body)))
(defn empty-env []
{:ns (@namespaces *cljm-ns*) :context :statement :locals {}})
(defmacro ^:private debug-prn
[& args]
`(.println System/err (str ~@args)))
(defn warning [env s]
(binding [*out* *err*]
(println
(str s (when (:line env)
(str " at line " (:line env) " " *cljm-file*))))))
(defn confirm-var-exists [env prefix suffix]
(when *cljm-warn-on-undeclared*
(let [crnt-ns (-> env :ns :name)]
(when (= prefix crnt-ns)
(when-not (-> @namespaces crnt-ns :defs suffix)
(warning env
(str "WARNING: Use of undeclared Var " prefix "/" suffix)))))))
(defn resolve-ns-alias [env name]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (get (:defs (@namespaces 'cljm.core)) sym)
(not (contains? (-> env :ns :excludes) sym))))
(defn resolve-existing-var [env sym]
(cond
; If the namespace is all caps then we assume it's the class prefix for an
; Objective-C class.
(and (not (nil? (namespace sym))) (= (string/upper-case (namespace sym)) (namespace sym)))
{:name (symbol (str (namespace sym) (name sym))) :ns 'ObjectiveCClass}
(= (namespace sym) "js")
{:name sym :ns 'js}
:else
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)
full-ns (resolve-ns-alias env ns)]
(confirm-var-exists env full-ns (symbol (name sym)))
(merge (get-in @namespaces [full-ns :defs (symbol (name sym))])
{:name (symbol (str full-ns) (str (name sym)))
:ns full-ns}))
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s (inc idx))
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
(do
(confirm-var-exists env prefix (symbol suffix))
(merge (get-in @namespaces [prefix :defs (symbol suffix)])
{:name (if (= "" prefix) (symbol suffix) (symbol (str prefix) suffix))
:ns prefix}))))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns (-> env :ns :name)}))
:else
(let [full-ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
(confirm-var-exists env full-ns sym)
(merge (get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns full-ns}))))))
(defn resolve-var [env sym]
(if (= (namespace sym) "js")
{:name sym}
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljm.core" ns)]
{:name (symbol (str (resolve-ns-alias env ns)) (name sym))})
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s idx)
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb) suffix))}
{:name sym}))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns) (name sym))}))
:else
(let [ns (if (core-name? env sym)
'cljm.core
(-> env :ns :name))]
{:name (symbol (str ns) (name sym))})))))
(defn confirm-bindings [env names]
(doseq [name names]
(let [env (merge env {:ns (@namespaces *cljm-ns*)})
ev (resolve-existing-var env name)]
(when (and *cljm-warn-on-dynamic*
ev (not (-> ev :dynamic)))
(warning env
(str "WARNING: " (:name ev) " not declared ^:dynamic"))))))
(declare analyze analyze-symbol analyze-seq)
(def specials '#{if def fn* do let* loop* letfn* throw try* recur new set! ns defprotocol* deftype* defrecord* . objc* & quote})
(def ^:dynamic *recur-frames* nil)
(def ^:dynamic *loop-lets* nil)
(defmacro disallowing-recur [& body]
`(binding [*recur-frames* (cons nil *recur-frames*)] ~@body))
(defn analyze-keyword
[env sym]
{:op :constant :env env
:form (if (= (namespace sym) (name *reader-ns-name*))
(keyword (-> env :ns :name name) (name sym))
sym)})
(defn analyze-block
"returns {:statements .. :ret ..}"
[env exprs]
(let [statements (disallowing-recur
(seq (map #(analyze (assoc env :context :statement) %) (butlast exprs))))
ret (if (<= (count exprs) 1)
(analyze env (first exprs))
(analyze (assoc env :context (if (= :statement (:context env)) :statement :return)) (last exprs)))]
{:statements statements :ret ret}))
(defmulti parse (fn [op & rest] op))
(defmethod parse 'if
[op env [_ test then else :as form] name]
(let [test-expr (disallowing-recur (analyze (assoc env :context :expr) test))
then-expr (analyze env then)
else-expr (analyze env else)]
{:env env :op :if :form form
:test test-expr :then then-expr :else else-expr
:unchecked @*unchecked-if*
:children [test-expr then-expr else-expr]}))
(defmethod parse 'throw
[op env [_ throw :as form] name]
(let [throw-expr (disallowing-recur (analyze (assoc env :context :expr) throw))]
{:env env :op :throw :form form
:throw throw-expr
:children [throw-expr]}))
(defn- block-children [{:keys [statements ret] :as block}]
(when block (conj (vec statements) ret)))
(defmethod parse 'try*
[op env [_ & body :as form] name]
(let [body (vec body)
catchenv (update-in env [:context] #(if (= :expr %) :return %))
tail (peek body)
fblock (when (and (seq? tail) (= 'finally (first tail)))
(rest tail))
finally (when fblock
(analyze-block
(assoc env :context :statement)
fblock))
body (if finally (pop body) body)
tail (peek body)
cblock (when (and (seq? tail)
(= 'catch (first tail)))
(rest tail))
name (first cblock)
locals (:locals catchenv)
locals (if name
(assoc locals name {:name name})
locals)
catch (when cblock
(analyze-block (assoc catchenv :locals locals) (rest cblock)))
body (if name (pop body) body)
try (when body
(analyze-block (if (or name finally) catchenv env) body))]
(when name (assert (not (namespace name)) "Can't qualify symbol in catch"))
{:env env :op :try* :form form
:try try
:finally finally
:name name
:catch catch
:children (vec (mapcat block-children
[try catch finally]))}))
(defmethod parse 'def
[op env form name]
(let [pfn (fn
([_ sym] {:sym sym})
([_ sym init] {:sym sym :init init})
([_ sym doc init] {:sym sym :doc doc :init init}))
args (apply pfn form)
sym (:sym args)
sym-meta (meta sym)
tag (-> sym meta :tag)
protocol (-> sym meta :protocol)
dynamic (-> sym meta :dynamic)
ns-name (-> env :ns :name)]
(assert (not (namespace sym)) "Can't def ns-qualified name")
(let [env (if (or (and (not= ns-name 'cljm.core)
(core-name? env sym))
(get-in @namespaces [ns-name :uses sym]))
(let [ev (resolve-existing-var (dissoc env :locals) sym)]
(when *cljm-warn-on-redef*
(warning env
(str "WARNING: " sym " already refers to: " (symbol (str (:ns ev)) (str sym))
" being replaced by: " (symbol (str ns-name) (str sym)))))
(swap! namespaces update-in [ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
name (:name (resolve-var (dissoc env :locals) sym))
init-expr (when (contains? args :init)
(disallowing-recur
(analyze (assoc env :context :expr) (:init args) sym)))
fn-var? (and init-expr (= (:op init-expr) :fn))
private? (when-let [private? (-> sym meta :private)]
(if (= true private?) true false))
doc (or (:doc args) (-> sym meta :doc))]
(when-let [v (get-in @namespaces [ns-name :defs sym])]
(when (and *cljm-warn-on-fn-var*
(not (-> sym meta :declared))
(and (:fn-var v) (not fn-var?)))
(warning env
(str "WARNING: " (symbol (str ns-name) (str sym))
" no longer fn, references are stale"))))
(swap! namespaces update-in [ns-name :defs sym]
(fn [m]
(let [m (assoc (or m {}) :name name)]
(merge m
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when-let [line (:line env)]
{:file *cljm-file* :line line})
;; the protocol a protocol fn belongs to
(when protocol
{:protocol protocol})
;; symbol for reified protocol
(when-let [protocol-symbol (-> sym meta :protocol-symbol)]
{:protocol-symbol protocol-symbol})
(when fn-var?
{:fn-var true
;; protocol implementation context
:protocol-impl (:protocol-impl init-expr)
;; inline protocol implementation context
:protocol-inline (:protocol-inline init-expr)
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map (fn [m]
(:params m))
(:methods init-expr))})))))
(merge {:env env :op :def :form form
:name name :doc doc :init init-expr}
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when private? {:private private?})
(when sym-meta sym-meta)
(when init-expr {:children [init-expr]})))))
(defn- analyze-fn-method [env locals meth gthis]
(letfn [(uniqify [[p & r]]
(when p
(cons (if (some #{p} r) (gensym (str p)) p)
(uniqify r))))]
(let [params (first meth)
variadic (boolean (some '#{&} params))
params (vec (uniqify (remove '#{&} params)))
fixed-arity (count (if variadic (butlast params) params))
body (next meth)
locals (reduce (fn [m name]
(assoc m name {:name name
:local true
:tag (-> name meta :tag)}))
locals params)
recur-frame {:names params :flag (atom nil)}
block (binding [*recur-frames* (cons recur-frame *recur-frames*)]
(analyze-block (assoc env :context :return :locals locals) body))]
(merge {:env env :variadic variadic :params params :max-fixed-arity fixed-arity
:gthis gthis :recurs @(:flag recur-frame)}
block))))
(defmethod parse 'fn*
[op env [_ & args :as form] name]
(let [[name meths] (if (symbol? (first args))
[(first args) (next args)]
[name (seq args)])
;;turn (fn [] ...) into (fn ([]...))
meths (if (vector? (first meths)) (list meths) meths)
locals (:locals env)
locals (if name (assoc locals name {:name name}) locals)
fields (-> form meta ::fields)
protocol-impl (-> form meta :protocol-impl)
protocol-inline (-> form meta :protocol-inline)
gthis (and fields (gensym "this__"))
locals (reduce (fn [m fld]
(assoc m fld
{:name fld
:field true
:local true
:mutable (-> fld meta :mutable)
:tag (-> fld meta :tag)}))
locals fields)
menv (if (> (count meths) 1) (assoc env :context :expr) env)
menv (merge menv
{:protocol-impl protocol-impl
:protocol-inline protocol-inline})
methods (map #(analyze-fn-method menv locals % gthis) meths)
max-fixed-arity (apply max (map :max-fixed-arity methods))
variadic (boolean (some :variadic methods))
locals (if name (assoc locals name {:name name :fn-var true
:variadic variadic
:max-fixed-arity max-fixed-arity
:method-params (map :params methods)}))
methods (if name
;; a second pass with knowledge of our function-ness/arity
;; lets us optimize self calls
(map #(analyze-fn-method menv locals % gthis) meths)
methods)
imp-fn? (-> form meta :imp-fn)]
;;todo - validate unique arities, at most one variadic, variadic takes max required args
{:env env :op :fn :form form :name name :methods methods :variadic variadic
:recur-frames *recur-frames* :loop-lets *loop-lets*
:max-fixed-arity max-fixed-arity
:protocol-impl protocol-impl
:protocol-inline protocol-inline
:imp-fn imp-fn?
:children (vec (mapcat block-children
methods))}))
(defmethod parse 'letfn*
[op env [_ bindings & exprs :as form] name]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [n->fexpr (into {} (map (juxt first second) (partition 2 bindings)))
names (keys n->fexpr)
n->gsym (into {} (map (juxt identity #(gensym (str % "__"))) names))
gsym->n (into {} (map (juxt n->gsym identity) names))
context (:context env)
bes (reduce (fn [bes n]
(let [g (n->gsym n)]
(conj bes {:name g
:tag (-> n meta :tag)
:local true})))
[]
names)
meth-env (reduce (fn [env be]
(let [n (gsym->n (be :name))]
(assoc-in env [:locals n] be)))
(assoc env :context :expr)
bes)
[meth-env finits]
(reduce (fn [[env finits] n]
(let [finit (analyze meth-env (n->fexpr n))
be (-> (get-in env [:locals n])
(assoc :init finit))]
[(assoc-in env [:locals n] be)
(conj finits finit)]))
[meth-env []]
names)
{:keys [statements ret]}
(analyze-block (assoc meth-env :context (if (= :expr context) :return context)) exprs)
bes (vec (map #(get-in meth-env [:locals %]) names))]
{:env env :op :letfn :bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'do
[op env [_ & exprs :as form] _]
(let [block (analyze-block env exprs)]
(merge {:env env :op :do :form form :children (block-children block)} block)))
(defn analyze-let
[encl-env [_ bindings & exprs :as form] is-loop]
(assert (and (vector? bindings) (even? (count bindings))) "bindings must be vector of even number of elements")
(let [context (:context encl-env)
[bes env]
(disallowing-recur
(loop [bes []
env (assoc encl-env :context :expr)
bindings (seq (partition 2 bindings))]
(if-let [[name init] (first bindings)]
(do
(assert (not (or (namespace name) (.contains (str name) "."))) (str "Invalid local name: " name))
(let [init-expr (analyze env init)
be {:name (gensym (str name "__"))
:init init-expr
:tag (or (-> name meta :tag)
(-> init-expr :tag)
(-> init-expr :info :tag))
:local true}]
(recur (conj bes be)
(assoc-in env [:locals name] be)
(next bindings))))
[bes env])))
recur-frame (when is-loop {:names (vec (map :name bes)) :flag (atom nil)})
{:keys [statements ret]}
(binding [*recur-frames* (if recur-frame (cons recur-frame *recur-frames*) *recur-frames*)
*loop-lets* (cond
is-loop (or *loop-lets* ())
*loop-lets* (cons {:names (vec (map :name bes))} *loop-lets*))]
(analyze-block (assoc env :context (if (= :expr context) :return context)) exprs))]
{:env encl-env :op :let :loop is-loop
:bindings bes :statements statements :ret ret :form form
:children (into (vec (map :init bes))
(conj (vec statements) ret))}))
(defmethod parse 'let*
[op encl-env form _]
(analyze-let encl-env form false))
(defmethod parse 'loop*
[op encl-env form _]
(analyze-let encl-env form true))
(defmethod parse 'recur
[op env [_ & exprs :as form] _]
(let [context (:context env)
frame (first *recur-frames*)
exprs (disallowing-recur (vec (map #(analyze (assoc env :context :expr) %) exprs)))]
(assert frame "Can't recur here")
(assert (= (count exprs) (count (:names frame))) "recur argument count mismatch")
(reset! (:flag frame) true)
(assoc {:env env :op :recur :form form}
:frame frame
:exprs exprs
:children exprs)))
(defmethod parse 'quote
[_ env [_ x] _]
{:op :constant :env env :form x})
(defmethod parse 'new
[_ env [_ ctor & args :as form] _]
(disallowing-recur
(let [enve (assoc env :context :expr)
ctorexpr (analyze enve ctor)
argexprs (vec (map #(analyze enve %) args))
known-num-fields (:num-fields (resolve-existing-var env ctor))
argc (count args)]
(when (and known-num-fields (not= known-num-fields argc))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " ctor)))
{:env env :op :new :form form :ctor ctorexpr :args argexprs
:children (into [ctorexpr] argexprs)})))
(defmethod parse 'set!
[_ env [_ target val alt :as form] _]
(let [[target val] (if alt
;; (set! o -prop val)
[`(. ~target ~val) alt]
[target val])]
(disallowing-recur
(let [enve (assoc env :context :expr)
targetexpr (cond
;; TODO: proper resolve
(= target '*unchecked-if*)
(do
(reset! *unchecked-if* val)
::set-unchecked-if)
(symbol? target)
(do
(let [local (-> env :locals target)]
(assert (or (nil? local)
(and (:field local)
(:mutable local)))
"Can't set! local var or non-mutable field"))
(analyze-symbol enve target))
:else
(when (seq? target)
(let [targetexpr (analyze-seq enve target nil)]
(when (:field targetexpr)
targetexpr))))
valexpr (analyze enve val)]
(assert targetexpr "set! target must be a field or a symbol naming a var")
(cond
(= targetexpr ::set-unchecked-if) {:env env :op :no-op}
:else {:env env :op :set! :form form :target targetexpr :val valexpr
:children [targetexpr valexpr]})))))
(defn munge-path [ss]
(clojure.lang.Compiler/munge (str ss)))
(defn ns->relpath [s]
(str (string/replace (munge-path s) \. \/) ".cljm"))
(declare analyze-file)
(defn analyze-deps [deps]
(doseq [dep deps]
(when-not (:defs (@namespaces dep))
(let [relpath (ns->relpath dep)]
(when (io/resource relpath)
(analyze-file relpath))))))
(defmethod parse 'ns
[_ env [_ name & args :as form] _]
(let [docstring (if (string? (first args)) (first args) nil)
args (if docstring (next args) args)
excludes
(reduce (fn [s [k exclude xs]]
(if (= k :refer-clojure)
(do
(assert (= exclude :exclude) "Only [:refer-clojure :exclude [names]] form supported")
(assert (not (seq s)) "Only one :refer-clojure form is allowed per namespace definition")
(into s xs))
s))
#{} args)
deps (atom #{})
valid-forms (atom #{:use :use-macros :require :require-macros})
error-msg (fn [spec msg] (str msg "; offending spec: " (pr-str spec)))
parse-require-spec (fn parse-require-spec [macros? spec]
(assert (or (symbol? spec) (vector? spec))
(error-msg spec "Only [lib.ns & options] and lib.ns specs supported in :require / :require-macros"))
(when (vector? spec)
(assert (symbol? (first spec))
(error-msg spec "Library name must be specified as a symbol in :require / :require-macros"))
(assert (odd? (count spec))
(error-msg spec "Only :as alias and :refer [names] options supported in :require"))
(assert (every? #{:as :refer} (map first (partition 2 (next spec))))
(error-msg spec "Only :as and :refer options supported in :require / :require-macros"))
(assert (let [fs (frequencies (next spec))]
(and (<= (fs :as 0) 1)
(<= (fs :refer 0) 1)))
(error-msg spec "Each of :as and :refer options may only be specified once in :require / :require-macros")))
(if (symbol? spec)
(recur macros? [spec])
(let [[lib & opts] spec
{alias :as referred :refer :or {alias lib}} (apply hash-map opts)
[rk uk] (if macros? [:require-macros :use-macros] [:require :use])]
(assert (or (symbol? alias) (nil? alias))
(error-msg spec ":as must be followed by a symbol in :require / :require-macros"))
(assert (or (and (vector? referred) (every? symbol? referred))
(nil? referred))
(error-msg spec ":refer must be followed by a vector of symbols in :require / :require-macros"))
(swap! deps conj lib)
(merge (when alias {rk {alias lib}})
(when referred {uk (apply hash-map (interleave referred (repeat lib)))})))))
use->require (fn use->require [[lib kw referred :as spec]]
(assert (and (symbol? lib) (= :only kw) (vector? referred) (every? symbol? referred))
(error-msg spec "Only [lib.ns :only [names]] specs supported in :use / :use-macros"))
[lib :refer referred])
{uses :use requires :require uses-macros :use-macros requires-macros :require-macros :as params}
(reduce (fn [m [k & libs]]
(assert (#{:use :use-macros :require :require-macros} k)
"Only :refer-clojure, :require, :require-macros, :use and :use-macros libspecs supported")
(assert (@valid-forms k)
(str "Only one " k " form is allowed per namespace definition"))
(swap! valid-forms disj k)
(apply merge-with merge m
(map (partial parse-require-spec (contains? #{:require-macros :use-macros} k))
(if (contains? #{:use :use-macros} k)
(map use->require libs)
libs))))
{} (remove (fn [[r]] (= r :refer-clojure)) args))]
(when (seq @deps)
(analyze-deps @deps))
(set! *cljm-ns* name)
(load-core)
(doseq [nsym (concat (vals requires-macros) (vals uses-macros))]
(clojure.core/require nsym))
(swap! namespaces #(-> %
(assoc-in [name :name] name)
(assoc-in [name :excludes] excludes)
(assoc-in [name :uses] uses)
(assoc-in [name :requires] requires)
(assoc-in [name :uses-macros] uses-macros)
(assoc-in [name :requires-macros]
(into {} (map (fn [[alias nsym]]
[alias (find-ns nsym)])
requires-macros)))))
{:env env :op :ns :form form :name name :uses uses :requires requires
:uses-macros uses-macros :requires-macros requires-macros :excludes excludes}))
(defmethod parse 'defprotocol*
[_ env [_ psym & methods :as form] _]
(let [p (:name (resolve-var (dissoc env :locals) psym))]
(swap! namespaces update-in [(-> env :ns :name) :defs psym]
(fn [m]
(let [m (assoc (or m {})
:name p
:type true
:is-protocol true)]
;;:num-fields (count fields))]
(merge m
{:protocols (-> psym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env
:op :defprotocol*
:form form
:p p
:methods methods}))
(defmethod parse 'deftype*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))
superclass (:superclass (meta tsym))
protocols (:protocols (meta tsym))
is-reify? (:reify (meta tsym))
methods (:methods (meta tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {})
:name t
:type true
:num-fields (count fields)
:fields fields)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :deftype* :form form :t t :fields fields :pmasks pmasks :protocols protocols :superclass superclass :reify is-reify? :methods methods}))
(defmethod parse 'defrecord*
[_ env [_ tsym fields pmasks :as form] _]
(let [t (:name (resolve-var (dissoc env :locals) tsym))]
(swap! namespaces update-in [(-> env :ns :name) :defs tsym]
(fn [m]
(let [m (assoc (or m {}) :name t :type true)]
(merge m
{:protocols (-> tsym meta :protocols)}
(when-let [line (:line env)]
{:file *cljm-file*
:line line})))))
{:env env :op :defrecord* :form form :t t :fields fields :pmasks pmasks}))
;; dot accessor code
(def ^:private property-symbol? #(boolean (and (symbol? %) (re-matches #"^-.*" (name %)))))
(defn- classify-dot-form
[[target member args]]
[(cond (nil? target) ::error
:default ::expr)
(cond (property-symbol? member) ::property
(symbol? member) ::symbol
(seq? member) ::list
(string? member) ::string
:default ::error)
(cond (nil? args) ()
:default ::expr)])
(defmulti build-dot-form #(classify-dot-form %))
;; (. o -p)
;; (. (...) -p)
(defmethod build-dot-form [::expr ::property ()]
[[target prop _]]
{:dot-action ::access :target target :field (-> prop name (.substring 1) symbol)})
;; (. o -p <args>)
(defmethod build-dot-form [::expr ::property ::list]
[[target prop args]]
(throw (Error. (str "Cannot provide arguments " args " on property access " prop))))
(defn- build-method-call
"Builds the intermediate method call map used to reason about the parsed form during
compilation."
[target meth args]
(cond
(or (symbol? meth) (string? meth)) {:dot-action ::call :target target :method meth :args args}
:else {:dot-action ::call :target target :method (first meth) :args args}))
;; (. o m 1 2)
(defmethod build-dot-form [::expr ::symbol ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o "m" 1 2)
(defmethod build-dot-form [::expr ::string ::expr]
[[target meth args]]
(build-method-call target meth args))
;; (. o m)
(defmethod build-dot-form [::expr ::symbol ()]
[[target meth args]]
(build-method-call target meth args))
;; (. o (m))
;; (. o (m 1 2))
(defmethod build-dot-form [::expr ::list ()]
[[target meth-expr _]]
(build-method-call target (first meth-expr) (rest meth-expr)))
(defmethod build-dot-form :default
[dot-form]
(throw (Error. (str "Unknown dot form of " (list* '. dot-form) " with classification " (classify-dot-form dot-form)))))
(defmethod parse '.
[_ env [_ target & [field & member+] :as form] _]
(disallowing-recur
(let [{:keys [dot-action target method field args]} (build-dot-form [target field member+])
enve (assoc env :context :expr)
targetexpr (analyze enve target)]
(case dot-action
::access {:env env :op :dot :form form
:target targetexpr
:field field
:children [targetexpr]
:tag (-> form meta :tag)}
::call (let [argexprs (map #(analyze enve %) args)]
{:env env :op :dot :form form
:target targetexpr
:method method
:args argexprs
:children (into [targetexpr] argexprs)
:tag (-> form meta :tag)})))))
(defmethod parse 'objc*
[op env [_ objcform & args :as form] _]
(assert (string? objcform))
(if args
(disallowing-recur
(let [seg (fn seg [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)]
(cons (subs s 0 idx) (seg (subs s (inc end))))))))
enve (assoc env :context :expr)
argexprs (vec (map #(analyze enve %) args))]
{:env env :op :js :segs (seg objcform) :args argexprs
:tag (-> form meta :tag) :form form :children argexprs}))
(let [interp (fn interp [^String s]
(let [idx (.indexOf s "~{")]
(if (= -1 idx)
(list s)
(let [end (.indexOf s "}" idx)
inner (:name (resolve-existing-var env (symbol (subs s (+ 2 idx) end))))]
(cons (subs s 0 idx) (cons inner (interp (subs s (inc end)))))))))]
{:env env :op :js :form form :code (apply str (interp objcform))
:tag (-> form meta :tag)})))
(defn parse-invoke
[env [f & args :as form]]
(disallowing-recur
(let [enve (assoc env :context :expr)
fexpr (analyze enve f)
argexprs (vec (map #(analyze enve %) args))
argc (count args)]
(if (and *cljm-warn-fn-arity* (-> fexpr :info :fn-var))
(let [{:keys [variadic max-fixed-arity method-params name]} (:info fexpr)]
(when (and (not (some #{argc} (map count method-params)))
(or (not variadic)
(and variadic (< argc max-fixed-arity))))
(warning env
(str "WARNING: Wrong number of args (" argc ") passed to " name)))))
{:env env :op :invoke :form form :f fexpr :args argexprs
:tag (or (-> fexpr :info :tag) (-> form meta :tag)) :children (into [fexpr] argexprs)})))
(defn analyze-symbol
"Finds the var associated with sym"
[env sym]
(let [ret {:env env :form sym}
lb (-> env :locals sym)]
(if lb
(assoc ret :op :var :info lb)
(assoc ret :op :var :info (resolve-existing-var env sym)))))
(defn get-expander [sym env]
(let [mvar
(when-not (or (-> env :locals sym) ;locals hide macros
(and (or (-> env :ns :excludes sym)
(get-in @namespaces [(-> env :ns :name) :excludes sym]))
(not (or (-> env :ns :uses-macros sym)
(get-in @namespaces [(-> env :ns :name) :uses-macros sym])))))
(if-let [nstr (namespace sym)]
(when-let [ns (cond
(= "clojure.core" nstr) (find-ns 'cljm.core)
(.contains nstr ".") (find-ns (symbol nstr))
:else
(-> env :ns :requires-macros (get (symbol nstr))))]
(.findInternedVar ^clojure.lang.Namespace ns (symbol (name sym))))
(if-let [nsym (-> env :ns :uses-macros sym)]
(.findInternedVar ^clojure.lang.Namespace (find-ns nsym) sym)
(.findInternedVar ^clojure.lang.Namespace (find-ns 'cljm.core) sym))))]
(when (and mvar (.isMacro ^clojure.lang.Var mvar))
@mvar)))
(defn macroexpand-1 [env form]
(let [op (first form)]
(if (specials op)
form
(if-let [mac (and (symbol? op) (get-expander op env))]
(binding [*ns* (create-ns *cljm-ns*)]
(apply mac form env (rest form)))
(if (symbol? op)
(let [opname (str op)]
(cond
(= (first opname) \.) (let [[target & args] (next form)]
(with-meta (list* '. target (symbol (subs opname 1)) args)
(meta form)))
(= (last opname) \.) (with-meta
(list* 'new (symbol (subs opname 0 (dec (count opname)))) (next form))
(meta form))
:else form))
form)))))
(defn analyze-seq
[env form name]
(let [env (assoc env :line
(or (-> form meta :line)
(:line env)))]
(let [op (first form)]
(assert (not (nil? op)) "Can't call nil")
(let [mform (macroexpand-1 env form)]
(if (identical? form mform)
(if (specials op)
(parse op env form name)
(parse-invoke env form))
(analyze env mform name))))))
(declare analyze-wrap-meta)
(defn analyze-map
[env form name]
(let [expr-env (assoc env :context :expr)
simple-keys? (every? #(or (string? %) (keyword? %))
(keys form))
ks (disallowing-recur (vec (map #(analyze expr-env % name) (keys form))))
vs (disallowing-recur (vec (map #(analyze expr-env % name) (vals form))))]
(analyze-wrap-meta {:op :map :env env :form form
:keys ks :vals vs :simple-keys? simple-keys?
:children (vec (interleave ks vs))}
name)))
(defn analyze-vector
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :vector :env env :form form :items items :children items} name)))
(defn analyze-set
[env form name]
(let [expr-env (assoc env :context :expr)
items (disallowing-recur (vec (map #(analyze expr-env % name) form)))]
(analyze-wrap-meta {:op :set :env env :form form :items items :children items} name)))
(defn analyze-wrap-meta [expr name]
(let [form (:form expr)]
(if (meta form)
(let [env (:env expr) ; take on expr's context ourselves
expr (assoc-in expr [:env :context] :expr) ; change expr to :expr
meta-expr (analyze-map (:env expr) (meta form) name)]
{:op :meta :env env :form form
:meta meta-expr :expr expr :children [meta-expr expr]})
expr)))
(defn analyze
"Given an environment, a map containing {:locals (mapping of names to bindings), :context
(one of :statement, :expr, :return), :ns (a symbol naming the
compilation ns)}, and form, returns an expression object (a map
containing at least :form, :op and :env keys). If expr has any (immediately)
nested exprs, must have :children [exprs...] entry. This will
facilitate code walking without knowing the details of the op set."
([env form] (analyze env form nil))
([env form name]
(let [form (if (instance? clojure.lang.LazySeq form)
(or (seq form) ())
form)]
(load-core)
(cond
(symbol? form) (analyze-symbol env form)
(and (seq? form) (seq form)) (analyze-seq env form name)
(map? form) (analyze-map env form name)
(vector? form) (analyze-vector env form name)
(set? form) (analyze-set env form name)
(keyword? form) (analyze-keyword env form)
:else {:op :constant :env env :form form}))))
(defn analyze-file
[^String f]
(let [res (if (re-find #"^file://" f) (java.net.URL. f) (io/resource f))]
(assert res (str "Can't find " f " in classpath"))
(binding [*cljm-ns* 'cljm.user
*cljm-file* (.getPath ^java.net.URL res)
*ns* *reader-ns*]
(with-open [r (io/reader res)]
(let [env (empty-env)
pbr (clojure.lang.LineNumberingPushbackReader. r)
eof (Object.)]
(loop [r (read pbr false eof false)]
(let [env (assoc env :ns (get-namespace *cljm-ns*))]
(when-not (identical? eof r)
(analyze env r)
(recur (read pbr false eof false))))))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.