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": "generate alphanum-gen 10)\n key \"message\"\n value \"Hello World!!\"]\n (s",
"end": 2025,
"score": 0.8871956467628479,
"start": 2018,
"tag": "KEY",
"value": "message"
},
{
"context": "generate alphanum-gen 10)\n key \"message\"\n value \"Hello World!!\"\n ",
"end": 2588,
"score": 0.991188108921051,
"start": 2581,
"tag": "KEY",
"value": "message"
},
{
"context": "{}]\n (let [topic \"test-topic\"\n key \"message\"\n value \"Hello World!! from non-existant",
"end": 3028,
"score": 0.9866669178009033,
"start": 3021,
"tag": "KEY",
"value": "message"
},
{
"context": "generate alphanum-gen 10)\n key \"message\"\n value \"Hello World!!\"]\n (.",
"end": 4058,
"score": 0.9888452887535095,
"start": 4051,
"tag": "KEY",
"value": "message"
}
] | test/ziggurat/producer_test.clj | shubhang93/ziggurat | 0 | (ns ziggurat.producer-test
(:require [clojure.string :refer [blank?]]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[ziggurat.config :refer [ziggurat-config]]
[ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]]
[ziggurat.producer :refer [producer-properties-map send kafka-producers
property->fn -send producer-properties]]
[ziggurat.streams :refer [start-streams stop-streams]]
[ziggurat.tracer :refer [tracer]])
(:import (org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig)
[org.apache.kafka.streams.integration.utils IntegrationTestUtils]
[io.opentracing.contrib.kafka TracingKafkaProducer]))
(use-fixtures :once fix/mount-producer-with-config-and-tracer)
(def valid-config {:key-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:value-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:bootstrap-servers "localhost:8000"})
(defn stream-router-config-without-producer [])
(:stream-router {:default {:application-id "test"
:bootstrap-servers "localhost:9092"
:stream-threads-count [1 :int]
:origin-topic "topic"
:channels {:channel-1 {:worker-count [10 :int]
:retry {:count [5 :int]
:enabled [true :bool]}}}}})
(deftest send-data-with-topic-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "message"
value "Hello World!!"]
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-data-with-topic-key-partition-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "message"
value "Hello World!!"
partition (int 0)]
(send :default topic partition key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-throws-exception-when-no-producers-are-configured
(with-redefs [kafka-producers {}]
(let [topic "test-topic"
key "message"
value "Hello World!! from non-existant Kafka Producers"]
(is (not-empty (try (send :default topic key value)
(catch Exception e (ex-data e))))))))
(deftest producer-properties-map-is-empty-if-no-producers-configured
; Here ziggurat-config has been substituted with a custom map which
; does not have any valid producer configs.
(with-redefs [ziggurat-config stream-router-config-without-producer]
(is (empty? (producer-properties-map)))))
(deftest producer-properties-map-is-not-empty-if-producers-are-configured
; Here the config is read from config.test.edn which contains
; valid producer configs.
(is (seq (producer-properties-map))))
(deftest send-data-with-tracer-enabled
(with-redefs [kafka-producers (hash-map :default (TracingKafkaProducer. (KafkaProducer. *producer-properties*) tracer))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "message"
value "Hello World!!"]
(.reset tracer)
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)
finished-spans (.finishedSpans tracer)]
(is (= value (.value (first result))))
(is (= 1 (.size finished-spans)))
(is (= (str "To_" topic) (-> finished-spans
(.get 0)
(.operationName))))))))
(deftest java-send-test
(let [stream-config-key ":entity"
expected-stream-config-key (keyword (subs stream-config-key 1))
topic "topic"
key "key"
value "value"
partition 1
send-called? (atom false)
send-with-partition-called? (atom false)]
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-topic topic)
(= actual-value value))
(reset! send-called? true)))]
(-send stream-config-key topic key value)
(is (true? @send-called?))))
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), partition, key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-partition actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-partition partition)
(= actual-topic topic)
(= actual-value value))
(reset! send-with-partition-called? true)))]
(-send stream-config-key topic partition key value)
(is (true? @send-with-partition-called?))))))
(deftest producer-properties-test
(testing "with correct config"
(let [valid-config (assoc valid-config :linger-ms "1")
props (producer-properties valid-config)]
(is (= (.getProperty props ProducerConfig/LINGER_MS_CONFIG)
"1"))
(is (= (.getProperty props ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG)
(:key-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG)
(:value-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/BOOTSTRAP_SERVERS_CONFIG)
(:bootstrap-servers valid-config)))))
(testing "with incorrect config"
(let [valid-config (assoc valid-config :linger-ms-foo "1")]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.time.Clock"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.foo.Bar"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (dissoc valid-config :bootstrap-servers)]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))))
(deftest property->fn-test
(testing "should return the producer property for a given config"
(let [expected-properties #{"send.buffer.bytes"
"metrics.sample.window.ms"
"receive.buffer.bytes"
"client.dns.lookup"
"reconnect.backoff.ms"
"transactional.id"
"interceptor.classes"
"bootstrap.servers"
"request.timeout.ms"
"connections.max.idle.ms"
"metrics.num.samples"
"retry.backoff.ms"
"linger.ms"
"enable.idempotence"
"client.id"
"metadata.max.age.ms"
"max.block.ms"
"value.serializer"
"retries"
"key.serializer"
"reconnect.backoff.max.ms"
"metrics.recording.level"
"batch.size"
"delivery.timeout.ms"
"buffer.memory"
"max.in.flight.requests.per.connection"
"partitioner.class"
"acks"
"max.request.size"
"transaction.timeout.ms"
"compression.type"
"metric.reporters"}
configs [:key-serializer-class
:value-serializer-class
:retries
:bootstrap-servers
:metadata-max-age
:reconnect-backoff-ms
:client-id
:metrics-num-samples
:transaction-timeout
:retry-backoff-ms
:receive-buffer
:partitioner-class
:max-block-ms
:metric-reporter-classes
:compression-type
:max-request-size
:delivery-timeout-ms
:metrics-sample-window-ms
:request-timeout-ms
:buffer-memory
:interceptor-classes
:linger-ms
:connections-max-idle-ms
:acks
:enable-idempotence
:metrics-recording-level
:transactional-id
:reconnect-backoff-max-ms
:client-dns-lookup
:max-in-flight-requests-per-connection
:send-buffer
:batch-size]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
(deftest backward-compatibility-of-producer-configs
(testing "should allow key-serializer, value-serializer and retries-config attributes of kafka producer"
(let [expected-properties #{"value.serializer"
"retries"
"key.serializer"}
configs [:key-serializer
:value-serializer
:retries-config]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
| 74469 | (ns ziggurat.producer-test
(:require [clojure.string :refer [blank?]]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[ziggurat.config :refer [ziggurat-config]]
[ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]]
[ziggurat.producer :refer [producer-properties-map send kafka-producers
property->fn -send producer-properties]]
[ziggurat.streams :refer [start-streams stop-streams]]
[ziggurat.tracer :refer [tracer]])
(:import (org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig)
[org.apache.kafka.streams.integration.utils IntegrationTestUtils]
[io.opentracing.contrib.kafka TracingKafkaProducer]))
(use-fixtures :once fix/mount-producer-with-config-and-tracer)
(def valid-config {:key-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:value-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:bootstrap-servers "localhost:8000"})
(defn stream-router-config-without-producer [])
(:stream-router {:default {:application-id "test"
:bootstrap-servers "localhost:9092"
:stream-threads-count [1 :int]
:origin-topic "topic"
:channels {:channel-1 {:worker-count [10 :int]
:retry {:count [5 :int]
:enabled [true :bool]}}}}})
(deftest send-data-with-topic-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "<KEY>"
value "Hello World!!"]
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-data-with-topic-key-partition-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "<KEY>"
value "Hello World!!"
partition (int 0)]
(send :default topic partition key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-throws-exception-when-no-producers-are-configured
(with-redefs [kafka-producers {}]
(let [topic "test-topic"
key "<KEY>"
value "Hello World!! from non-existant Kafka Producers"]
(is (not-empty (try (send :default topic key value)
(catch Exception e (ex-data e))))))))
(deftest producer-properties-map-is-empty-if-no-producers-configured
; Here ziggurat-config has been substituted with a custom map which
; does not have any valid producer configs.
(with-redefs [ziggurat-config stream-router-config-without-producer]
(is (empty? (producer-properties-map)))))
(deftest producer-properties-map-is-not-empty-if-producers-are-configured
; Here the config is read from config.test.edn which contains
; valid producer configs.
(is (seq (producer-properties-map))))
(deftest send-data-with-tracer-enabled
(with-redefs [kafka-producers (hash-map :default (TracingKafkaProducer. (KafkaProducer. *producer-properties*) tracer))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "<KEY>"
value "Hello World!!"]
(.reset tracer)
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)
finished-spans (.finishedSpans tracer)]
(is (= value (.value (first result))))
(is (= 1 (.size finished-spans)))
(is (= (str "To_" topic) (-> finished-spans
(.get 0)
(.operationName))))))))
(deftest java-send-test
(let [stream-config-key ":entity"
expected-stream-config-key (keyword (subs stream-config-key 1))
topic "topic"
key "key"
value "value"
partition 1
send-called? (atom false)
send-with-partition-called? (atom false)]
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-topic topic)
(= actual-value value))
(reset! send-called? true)))]
(-send stream-config-key topic key value)
(is (true? @send-called?))))
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), partition, key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-partition actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-partition partition)
(= actual-topic topic)
(= actual-value value))
(reset! send-with-partition-called? true)))]
(-send stream-config-key topic partition key value)
(is (true? @send-with-partition-called?))))))
(deftest producer-properties-test
(testing "with correct config"
(let [valid-config (assoc valid-config :linger-ms "1")
props (producer-properties valid-config)]
(is (= (.getProperty props ProducerConfig/LINGER_MS_CONFIG)
"1"))
(is (= (.getProperty props ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG)
(:key-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG)
(:value-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/BOOTSTRAP_SERVERS_CONFIG)
(:bootstrap-servers valid-config)))))
(testing "with incorrect config"
(let [valid-config (assoc valid-config :linger-ms-foo "1")]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.time.Clock"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.foo.Bar"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (dissoc valid-config :bootstrap-servers)]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))))
(deftest property->fn-test
(testing "should return the producer property for a given config"
(let [expected-properties #{"send.buffer.bytes"
"metrics.sample.window.ms"
"receive.buffer.bytes"
"client.dns.lookup"
"reconnect.backoff.ms"
"transactional.id"
"interceptor.classes"
"bootstrap.servers"
"request.timeout.ms"
"connections.max.idle.ms"
"metrics.num.samples"
"retry.backoff.ms"
"linger.ms"
"enable.idempotence"
"client.id"
"metadata.max.age.ms"
"max.block.ms"
"value.serializer"
"retries"
"key.serializer"
"reconnect.backoff.max.ms"
"metrics.recording.level"
"batch.size"
"delivery.timeout.ms"
"buffer.memory"
"max.in.flight.requests.per.connection"
"partitioner.class"
"acks"
"max.request.size"
"transaction.timeout.ms"
"compression.type"
"metric.reporters"}
configs [:key-serializer-class
:value-serializer-class
:retries
:bootstrap-servers
:metadata-max-age
:reconnect-backoff-ms
:client-id
:metrics-num-samples
:transaction-timeout
:retry-backoff-ms
:receive-buffer
:partitioner-class
:max-block-ms
:metric-reporter-classes
:compression-type
:max-request-size
:delivery-timeout-ms
:metrics-sample-window-ms
:request-timeout-ms
:buffer-memory
:interceptor-classes
:linger-ms
:connections-max-idle-ms
:acks
:enable-idempotence
:metrics-recording-level
:transactional-id
:reconnect-backoff-max-ms
:client-dns-lookup
:max-in-flight-requests-per-connection
:send-buffer
:batch-size]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
(deftest backward-compatibility-of-producer-configs
(testing "should allow key-serializer, value-serializer and retries-config attributes of kafka producer"
(let [expected-properties #{"value.serializer"
"retries"
"key.serializer"}
configs [:key-serializer
:value-serializer
:retries-config]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
| true | (ns ziggurat.producer-test
(:require [clojure.string :refer [blank?]]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[ziggurat.config :refer [ziggurat-config]]
[ziggurat.fixtures :as fix :refer [*producer-properties* *consumer-properties*]]
[ziggurat.producer :refer [producer-properties-map send kafka-producers
property->fn -send producer-properties]]
[ziggurat.streams :refer [start-streams stop-streams]]
[ziggurat.tracer :refer [tracer]])
(:import (org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig)
[org.apache.kafka.streams.integration.utils IntegrationTestUtils]
[io.opentracing.contrib.kafka TracingKafkaProducer]))
(use-fixtures :once fix/mount-producer-with-config-and-tracer)
(def valid-config {:key-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:value-serializer-class "org.apache.kafka.common.serialization.StringSerializer"
:bootstrap-servers "localhost:8000"})
(defn stream-router-config-without-producer [])
(:stream-router {:default {:application-id "test"
:bootstrap-servers "localhost:9092"
:stream-threads-count [1 :int]
:origin-topic "topic"
:channels {:channel-1 {:worker-count [10 :int]
:retry {:count [5 :int]
:enabled [true :bool]}}}}})
(deftest send-data-with-topic-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "PI:KEY:<KEY>END_PI"
value "Hello World!!"]
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-data-with-topic-key-partition-and-value-test
(with-redefs [kafka-producers (hash-map :default (KafkaProducer. *producer-properties*))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "PI:KEY:<KEY>END_PI"
value "Hello World!!"
partition (int 0)]
(send :default topic partition key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)]
(is (= value (.value (first result))))))))
(deftest send-throws-exception-when-no-producers-are-configured
(with-redefs [kafka-producers {}]
(let [topic "test-topic"
key "PI:KEY:<KEY>END_PI"
value "Hello World!! from non-existant Kafka Producers"]
(is (not-empty (try (send :default topic key value)
(catch Exception e (ex-data e))))))))
(deftest producer-properties-map-is-empty-if-no-producers-configured
; Here ziggurat-config has been substituted with a custom map which
; does not have any valid producer configs.
(with-redefs [ziggurat-config stream-router-config-without-producer]
(is (empty? (producer-properties-map)))))
(deftest producer-properties-map-is-not-empty-if-producers-are-configured
; Here the config is read from config.test.edn which contains
; valid producer configs.
(is (seq (producer-properties-map))))
(deftest send-data-with-tracer-enabled
(with-redefs [kafka-producers (hash-map :default (TracingKafkaProducer. (KafkaProducer. *producer-properties*) tracer))]
(let [alphanum-gen (gen/such-that #(not (blank? %)) gen/string-alphanumeric)
topic (gen/generate alphanum-gen 10)
key "PI:KEY:<KEY>END_PI"
value "Hello World!!"]
(.reset tracer)
(send :default topic key value)
(let [result (IntegrationTestUtils/waitUntilMinKeyValueRecordsReceived *consumer-properties* topic 1 2000)
finished-spans (.finishedSpans tracer)]
(is (= value (.value (first result))))
(is (= 1 (.size finished-spans)))
(is (= (str "To_" topic) (-> finished-spans
(.get 0)
(.operationName))))))))
(deftest java-send-test
(let [stream-config-key ":entity"
expected-stream-config-key (keyword (subs stream-config-key 1))
topic "topic"
key "key"
value "value"
partition 1
send-called? (atom false)
send-with-partition-called? (atom false)]
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-topic topic)
(= actual-value value))
(reset! send-called? true)))]
(-send stream-config-key topic key value)
(is (true? @send-called?))))
(testing "it calls send with the correct parameters i.e. config-key(keyword), topic(string), partition, key, value"
(with-redefs [send (fn [actual-stream-config-key actual-topic actual-partition actual-key actual-value]
(if (and (= actual-stream-config-key expected-stream-config-key)
(= actual-key key)
(= actual-partition partition)
(= actual-topic topic)
(= actual-value value))
(reset! send-with-partition-called? true)))]
(-send stream-config-key topic partition key value)
(is (true? @send-with-partition-called?))))))
(deftest producer-properties-test
(testing "with correct config"
(let [valid-config (assoc valid-config :linger-ms "1")
props (producer-properties valid-config)]
(is (= (.getProperty props ProducerConfig/LINGER_MS_CONFIG)
"1"))
(is (= (.getProperty props ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG)
(:key-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG)
(:value-serializer-class valid-config)))
(is (= (.getProperty props ProducerConfig/BOOTSTRAP_SERVERS_CONFIG)
(:bootstrap-servers valid-config)))))
(testing "with incorrect config"
(let [valid-config (assoc valid-config :linger-ms-foo "1")]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.time.Clock"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (update valid-config :key-serializer-class (constantly "java.foo.Bar"))]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))
(let [valid-config (dissoc valid-config :bootstrap-servers)]
(is (thrown? java.lang.RuntimeException (producer-properties valid-config))))))
(deftest property->fn-test
(testing "should return the producer property for a given config"
(let [expected-properties #{"send.buffer.bytes"
"metrics.sample.window.ms"
"receive.buffer.bytes"
"client.dns.lookup"
"reconnect.backoff.ms"
"transactional.id"
"interceptor.classes"
"bootstrap.servers"
"request.timeout.ms"
"connections.max.idle.ms"
"metrics.num.samples"
"retry.backoff.ms"
"linger.ms"
"enable.idempotence"
"client.id"
"metadata.max.age.ms"
"max.block.ms"
"value.serializer"
"retries"
"key.serializer"
"reconnect.backoff.max.ms"
"metrics.recording.level"
"batch.size"
"delivery.timeout.ms"
"buffer.memory"
"max.in.flight.requests.per.connection"
"partitioner.class"
"acks"
"max.request.size"
"transaction.timeout.ms"
"compression.type"
"metric.reporters"}
configs [:key-serializer-class
:value-serializer-class
:retries
:bootstrap-servers
:metadata-max-age
:reconnect-backoff-ms
:client-id
:metrics-num-samples
:transaction-timeout
:retry-backoff-ms
:receive-buffer
:partitioner-class
:max-block-ms
:metric-reporter-classes
:compression-type
:max-request-size
:delivery-timeout-ms
:metrics-sample-window-ms
:request-timeout-ms
:buffer-memory
:interceptor-classes
:linger-ms
:connections-max-idle-ms
:acks
:enable-idempotence
:metrics-recording-level
:transactional-id
:reconnect-backoff-max-ms
:client-dns-lookup
:max-in-flight-requests-per-connection
:send-buffer
:batch-size]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
(deftest backward-compatibility-of-producer-configs
(testing "should allow key-serializer, value-serializer and retries-config attributes of kafka producer"
(let [expected-properties #{"value.serializer"
"retries"
"key.serializer"}
configs [:key-serializer
:value-serializer
:retries-config]
response (set (for [config configs]
(eval (property->fn config))))]
(is (= response
expected-properties)))))
|
[
{
"context": "; Copyright (c) Chris Houser, Dec 2008. All rights reserved.\n; The use and d",
"end": 30,
"score": 0.9998641014099121,
"start": 18,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "sed interactively at the REPL\n\n(ns \n #^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi\",\n :doc \"U",
"end": 548,
"score": 0.9998801946640015,
"start": 536,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "vely at the REPL\n\n(ns \n #^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi\",\n :doc \"Utilities meant to ",
"end": 566,
"score": 0.9998553991317749,
"start": 550,
"tag": "NAME",
"value": "Christophe Grand"
},
{
"context": "(ns \n #^{:author \"Chris Houser, Christophe Grand, Stephen Gilardi\",\n :doc \"Utilities meant to be used interacti",
"end": 583,
"score": 0.9998564720153809,
"start": 568,
"tag": "NAME",
"value": "Stephen Gilardi"
},
{
"context": "-----------------------------------------------\n;; scgilardi at gmail\n\n(defn run*\n \"Loads the specified names",
"end": 7565,
"score": 0.9151864051818848,
"start": 7556,
"tag": "USERNAME",
"value": "scgilardi"
}
] | ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/repl_utils.clj | allertonm/Couverjure | 3 | ; Copyright (c) Chris Houser, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Utilities meant to be used interactively at the REPL
(ns
#^{:author "Chris Houser, Christophe Grand, Stephen Gilardi",
:doc "Utilities meant to be used interactively at the REPL"}
clojure.contrib.repl-utils
(:import (java.io File LineNumberReader InputStreamReader PushbackReader)
(java.lang.reflect Modifier Method Constructor)
(clojure.lang RT Compiler Compiler$C))
(:use [clojure.contrib.seq-utils :only (indexed)]
[clojure.contrib.javadoc.browse :only (browse-url)]
[clojure.contrib.str-utils :only (str-join re-sub re-partition)]))
;; ----------------------------------------------------------------------
;; Examine Java classes
(defn- sortable [t]
(apply str (map (fn [[a b]] (str a (format "%04d" (Integer. b))))
(partition 2 (concat (re-partition #"\d+" t) [0])))))
(defn- param-str [m]
(str " (" (str-join
"," (map (fn [[c i]]
(if (> i 3)
(str (.getSimpleName c) "*" i)
(str-join "," (replicate i (.getSimpleName c)))))
(reduce (fn [pairs y] (let [[x i] (peek pairs)]
(if (= x y)
(conj (pop pairs) [y (inc i)])
(conj pairs [y 1]))))
[] (.getParameterTypes m))))
")"))
(defn- member-details [m]
(let [static? (Modifier/isStatic (.getModifiers m))
method? (instance? Method m)
ctor? (instance? Constructor m)
text (if ctor?
(str "<init>" (param-str m))
(str
(when static? "static ")
(.getName m) " : "
(if method?
(str (.getSimpleName (.getReturnType m)) (param-str m))
(str (.getSimpleName (.getType m))))))]
(assoc (bean m)
:sort-val [(not static?) method? (sortable text)]
:text text
:member m)))
(defn show
"With one arg prints all static and instance members of x or (class x).
Each member is listed with a number which can be given as 'selector'
to return the member object -- the REPL will print more details for
that member.
The selector also may be a string or regex, in which case only
members whose names match 'selector' as a case-insensitive regex
will be printed.
Finally, the selector also may be a predicate, in which case only
members for which the predicate returns true will be printed. The
predicate will be passed a single argument, a map that includes the
:text that will be printed and the :member object itself, as well as
all the properies of the member object as translated by 'bean'.
Examples: (show Integer) (show []) (show String 23) (show String \"case\")"
([x] (show x (constantly true)))
([x selector]
(let [c (if (class? x) x (class x))
members (sort-by :sort-val
(map member-details
(concat (.getFields c)
(.getMethods c)
(.getConstructors c))))]
(if (number? selector)
(:member (nth members selector))
(let [pred (if (ifn? selector)
selector
#(re-find (re-pattern (str "(?i)" selector)) (:name %)))]
(println "=== " (Modifier/toString (.getModifiers c)) c " ===")
(doseq [[i m] (indexed members)]
(when (pred m)
(printf "[%2d] %s\n" i (:text m)))))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn get-source
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (get-source 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.readLine rdr))
(let [text (StringBuilder.)
pbr (proxy [PushbackReader] [rdr]
(read [] (let [i (proxy-super read)]
(.append text (char i))
i)))]
(read (PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (get-source '~n) (str "Source not found"))))
;; ----------------------------------------------------------------------
;; Handle Ctrl-C keystrokes
(def #^{:doc "Threads to stop when Ctrl-C is pressed. See 'add-break-thread!'"}
break-threads (atom {}))
(let [first-time (atom true)]
(defn start-handling-break
"Register INT signal handler. After calling this, Ctrl-C will cause
all break-threads to be stopped. See 'add-break-thread!'"
[]
(when (= :need-init
(swap! first-time
{:need-init false, false false, true :need-init}))
(sun.misc.Signal/handle
(sun.misc.Signal. "INT")
(proxy [sun.misc.SignalHandler] []
(handle [sig]
(let [exc (Exception. (str sig))]
(doseq [tref (vals @break-threads) :when (.get tref)]
(.stop (.get tref) exc)))))))))
(defn add-break-thread!
"Add the given thread to break-threads so that it will be stopped
any time the user presses Ctrl-C. Calls start-handling-break for
you. Adds the current thread if none is given."
([] (add-break-thread! (Thread/currentThread)))
([t]
(start-handling-break)
(let [tref (java.lang.ref.WeakReference. t)]
(swap! break-threads assoc (.getId t) tref))))
;; ----------------------------------------------------------------------
;; Compiler hooks
(defn expression-info
"Uses the Clojure compiler to analyze the given s-expr. Returns
a map with keys :class and :primitive? indicating what the compiler
concluded about the return value of the expression. Returns nil if
not type info can be determined at compile-time.
Example: (expression-info '(+ (int 5) (float 10)))
Returns: {:class float, :primitive? true}"
[expr]
(let [fn-ast (Compiler/analyze Compiler$C/EXPRESSION `(fn [] ~expr))
expr-ast (.body (first (.methods fn-ast)))]
(when (.hasJavaClass expr-ast)
{:class (.getJavaClass expr-ast)
:primitive? (.isPrimitive (.getJavaClass expr-ast))})))
;; ----------------------------------------------------------------------
;; scgilardi at gmail
(defn run*
"Loads the specified namespace and invokes its \"main\" function with
optional args."
[ns-sym & args]
(require ns-sym :reload-all)
(apply (ns-resolve ns-sym 'main) args))
(defmacro run
"Loads the specified namespace and invokes its \"main\" function with
optional args. ns-name is not evaluated."
[ns-name & args]
`(run* '~ns-name ~@args))
(load "repl_utils/javadoc")
| 49106 | ; Copyright (c) <NAME>, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Utilities meant to be used interactively at the REPL
(ns
#^{:author "<NAME>, <NAME>, <NAME>",
:doc "Utilities meant to be used interactively at the REPL"}
clojure.contrib.repl-utils
(:import (java.io File LineNumberReader InputStreamReader PushbackReader)
(java.lang.reflect Modifier Method Constructor)
(clojure.lang RT Compiler Compiler$C))
(:use [clojure.contrib.seq-utils :only (indexed)]
[clojure.contrib.javadoc.browse :only (browse-url)]
[clojure.contrib.str-utils :only (str-join re-sub re-partition)]))
;; ----------------------------------------------------------------------
;; Examine Java classes
(defn- sortable [t]
(apply str (map (fn [[a b]] (str a (format "%04d" (Integer. b))))
(partition 2 (concat (re-partition #"\d+" t) [0])))))
(defn- param-str [m]
(str " (" (str-join
"," (map (fn [[c i]]
(if (> i 3)
(str (.getSimpleName c) "*" i)
(str-join "," (replicate i (.getSimpleName c)))))
(reduce (fn [pairs y] (let [[x i] (peek pairs)]
(if (= x y)
(conj (pop pairs) [y (inc i)])
(conj pairs [y 1]))))
[] (.getParameterTypes m))))
")"))
(defn- member-details [m]
(let [static? (Modifier/isStatic (.getModifiers m))
method? (instance? Method m)
ctor? (instance? Constructor m)
text (if ctor?
(str "<init>" (param-str m))
(str
(when static? "static ")
(.getName m) " : "
(if method?
(str (.getSimpleName (.getReturnType m)) (param-str m))
(str (.getSimpleName (.getType m))))))]
(assoc (bean m)
:sort-val [(not static?) method? (sortable text)]
:text text
:member m)))
(defn show
"With one arg prints all static and instance members of x or (class x).
Each member is listed with a number which can be given as 'selector'
to return the member object -- the REPL will print more details for
that member.
The selector also may be a string or regex, in which case only
members whose names match 'selector' as a case-insensitive regex
will be printed.
Finally, the selector also may be a predicate, in which case only
members for which the predicate returns true will be printed. The
predicate will be passed a single argument, a map that includes the
:text that will be printed and the :member object itself, as well as
all the properies of the member object as translated by 'bean'.
Examples: (show Integer) (show []) (show String 23) (show String \"case\")"
([x] (show x (constantly true)))
([x selector]
(let [c (if (class? x) x (class x))
members (sort-by :sort-val
(map member-details
(concat (.getFields c)
(.getMethods c)
(.getConstructors c))))]
(if (number? selector)
(:member (nth members selector))
(let [pred (if (ifn? selector)
selector
#(re-find (re-pattern (str "(?i)" selector)) (:name %)))]
(println "=== " (Modifier/toString (.getModifiers c)) c " ===")
(doseq [[i m] (indexed members)]
(when (pred m)
(printf "[%2d] %s\n" i (:text m)))))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn get-source
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (get-source 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.readLine rdr))
(let [text (StringBuilder.)
pbr (proxy [PushbackReader] [rdr]
(read [] (let [i (proxy-super read)]
(.append text (char i))
i)))]
(read (PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (get-source '~n) (str "Source not found"))))
;; ----------------------------------------------------------------------
;; Handle Ctrl-C keystrokes
(def #^{:doc "Threads to stop when Ctrl-C is pressed. See 'add-break-thread!'"}
break-threads (atom {}))
(let [first-time (atom true)]
(defn start-handling-break
"Register INT signal handler. After calling this, Ctrl-C will cause
all break-threads to be stopped. See 'add-break-thread!'"
[]
(when (= :need-init
(swap! first-time
{:need-init false, false false, true :need-init}))
(sun.misc.Signal/handle
(sun.misc.Signal. "INT")
(proxy [sun.misc.SignalHandler] []
(handle [sig]
(let [exc (Exception. (str sig))]
(doseq [tref (vals @break-threads) :when (.get tref)]
(.stop (.get tref) exc)))))))))
(defn add-break-thread!
"Add the given thread to break-threads so that it will be stopped
any time the user presses Ctrl-C. Calls start-handling-break for
you. Adds the current thread if none is given."
([] (add-break-thread! (Thread/currentThread)))
([t]
(start-handling-break)
(let [tref (java.lang.ref.WeakReference. t)]
(swap! break-threads assoc (.getId t) tref))))
;; ----------------------------------------------------------------------
;; Compiler hooks
(defn expression-info
"Uses the Clojure compiler to analyze the given s-expr. Returns
a map with keys :class and :primitive? indicating what the compiler
concluded about the return value of the expression. Returns nil if
not type info can be determined at compile-time.
Example: (expression-info '(+ (int 5) (float 10)))
Returns: {:class float, :primitive? true}"
[expr]
(let [fn-ast (Compiler/analyze Compiler$C/EXPRESSION `(fn [] ~expr))
expr-ast (.body (first (.methods fn-ast)))]
(when (.hasJavaClass expr-ast)
{:class (.getJavaClass expr-ast)
:primitive? (.isPrimitive (.getJavaClass expr-ast))})))
;; ----------------------------------------------------------------------
;; scgilardi at gmail
(defn run*
"Loads the specified namespace and invokes its \"main\" function with
optional args."
[ns-sym & args]
(require ns-sym :reload-all)
(apply (ns-resolve ns-sym 'main) args))
(defmacro run
"Loads the specified namespace and invokes its \"main\" function with
optional args. ns-name is not evaluated."
[ns-name & args]
`(run* '~ns-name ~@args))
(load "repl_utils/javadoc")
| true | ; Copyright (c) PI:NAME:<NAME>END_PI, Dec 2008. All rights reserved.
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
; which can be found in the file CPL.TXT at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Utilities meant to be used interactively at the REPL
(ns
#^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:doc "Utilities meant to be used interactively at the REPL"}
clojure.contrib.repl-utils
(:import (java.io File LineNumberReader InputStreamReader PushbackReader)
(java.lang.reflect Modifier Method Constructor)
(clojure.lang RT Compiler Compiler$C))
(:use [clojure.contrib.seq-utils :only (indexed)]
[clojure.contrib.javadoc.browse :only (browse-url)]
[clojure.contrib.str-utils :only (str-join re-sub re-partition)]))
;; ----------------------------------------------------------------------
;; Examine Java classes
(defn- sortable [t]
(apply str (map (fn [[a b]] (str a (format "%04d" (Integer. b))))
(partition 2 (concat (re-partition #"\d+" t) [0])))))
(defn- param-str [m]
(str " (" (str-join
"," (map (fn [[c i]]
(if (> i 3)
(str (.getSimpleName c) "*" i)
(str-join "," (replicate i (.getSimpleName c)))))
(reduce (fn [pairs y] (let [[x i] (peek pairs)]
(if (= x y)
(conj (pop pairs) [y (inc i)])
(conj pairs [y 1]))))
[] (.getParameterTypes m))))
")"))
(defn- member-details [m]
(let [static? (Modifier/isStatic (.getModifiers m))
method? (instance? Method m)
ctor? (instance? Constructor m)
text (if ctor?
(str "<init>" (param-str m))
(str
(when static? "static ")
(.getName m) " : "
(if method?
(str (.getSimpleName (.getReturnType m)) (param-str m))
(str (.getSimpleName (.getType m))))))]
(assoc (bean m)
:sort-val [(not static?) method? (sortable text)]
:text text
:member m)))
(defn show
"With one arg prints all static and instance members of x or (class x).
Each member is listed with a number which can be given as 'selector'
to return the member object -- the REPL will print more details for
that member.
The selector also may be a string or regex, in which case only
members whose names match 'selector' as a case-insensitive regex
will be printed.
Finally, the selector also may be a predicate, in which case only
members for which the predicate returns true will be printed. The
predicate will be passed a single argument, a map that includes the
:text that will be printed and the :member object itself, as well as
all the properies of the member object as translated by 'bean'.
Examples: (show Integer) (show []) (show String 23) (show String \"case\")"
([x] (show x (constantly true)))
([x selector]
(let [c (if (class? x) x (class x))
members (sort-by :sort-val
(map member-details
(concat (.getFields c)
(.getMethods c)
(.getConstructors c))))]
(if (number? selector)
(:member (nth members selector))
(let [pred (if (ifn? selector)
selector
#(re-find (re-pattern (str "(?i)" selector)) (:name %)))]
(println "=== " (Modifier/toString (.getModifiers c)) c " ===")
(doseq [[i m] (indexed members)]
(when (pred m)
(printf "[%2d] %s\n" i (:text m)))))))))
;; ----------------------------------------------------------------------
;; Examine Clojure functions (Vars, really)
(defn get-source
"Returns a string of the source code for the given symbol, if it can
find it. This requires that the symbol resolve to a Var defined in
a namespace for which the .clj is in the classpath. Returns nil if
it can't find the source. For most REPL usage, 'source' is more
convenient.
Example: (get-source 'filter)"
[x]
(when-let [v (resolve x)]
(when-let [filepath (:file (meta v))]
(when-let [strm (.getResourceAsStream (RT/baseLoader) filepath)]
(with-open [rdr (LineNumberReader. (InputStreamReader. strm))]
(dotimes [_ (dec (:line (meta v)))] (.readLine rdr))
(let [text (StringBuilder.)
pbr (proxy [PushbackReader] [rdr]
(read [] (let [i (proxy-super read)]
(.append text (char i))
i)))]
(read (PushbackReader. pbr))
(str text)))))))
(defmacro source
"Prints the source code for the given symbol, if it can find it.
This requires that the symbol resolve to a Var defined in a
namespace for which the .clj is in the classpath.
Example: (source filter)"
[n]
`(println (or (get-source '~n) (str "Source not found"))))
;; ----------------------------------------------------------------------
;; Handle Ctrl-C keystrokes
(def #^{:doc "Threads to stop when Ctrl-C is pressed. See 'add-break-thread!'"}
break-threads (atom {}))
(let [first-time (atom true)]
(defn start-handling-break
"Register INT signal handler. After calling this, Ctrl-C will cause
all break-threads to be stopped. See 'add-break-thread!'"
[]
(when (= :need-init
(swap! first-time
{:need-init false, false false, true :need-init}))
(sun.misc.Signal/handle
(sun.misc.Signal. "INT")
(proxy [sun.misc.SignalHandler] []
(handle [sig]
(let [exc (Exception. (str sig))]
(doseq [tref (vals @break-threads) :when (.get tref)]
(.stop (.get tref) exc)))))))))
(defn add-break-thread!
"Add the given thread to break-threads so that it will be stopped
any time the user presses Ctrl-C. Calls start-handling-break for
you. Adds the current thread if none is given."
([] (add-break-thread! (Thread/currentThread)))
([t]
(start-handling-break)
(let [tref (java.lang.ref.WeakReference. t)]
(swap! break-threads assoc (.getId t) tref))))
;; ----------------------------------------------------------------------
;; Compiler hooks
(defn expression-info
"Uses the Clojure compiler to analyze the given s-expr. Returns
a map with keys :class and :primitive? indicating what the compiler
concluded about the return value of the expression. Returns nil if
not type info can be determined at compile-time.
Example: (expression-info '(+ (int 5) (float 10)))
Returns: {:class float, :primitive? true}"
[expr]
(let [fn-ast (Compiler/analyze Compiler$C/EXPRESSION `(fn [] ~expr))
expr-ast (.body (first (.methods fn-ast)))]
(when (.hasJavaClass expr-ast)
{:class (.getJavaClass expr-ast)
:primitive? (.isPrimitive (.getJavaClass expr-ast))})))
;; ----------------------------------------------------------------------
;; scgilardi at gmail
(defn run*
"Loads the specified namespace and invokes its \"main\" function with
optional args."
[ns-sym & args]
(require ns-sym :reload-all)
(apply (ns-resolve ns-sym 'main) args))
(defmacro run
"Loads the specified namespace and invokes its \"main\" function with
optional args. ns-name is not evaluated."
[ns-name & args]
`(run* '~ns-name ~@args))
(load "repl_utils/javadoc")
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-12-22\"\n :doc \"Step function pro",
"end": 105,
"score": 0.9998731017112732,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/test/clojure/taiga/test/classify/step/tree.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-12-22"
:doc "Step function probability forest example." }
taiga.test.classify.step.tree
(:require [clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.tree :as tree]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.step.tree clojure:test > tests.txt
;;------------------------------------------------------------------------------
(def nss (str *ns*))
(test/deftest step-tree
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-diagonal-step-function 1.0))
options (assoc options :nterms 1)
forest (taiga/majority-vote-probability options)
predictors (into (sorted-map)
(dissoc record/attributes :ground-truth :prediction))
^clojure.lang.IFn$OD p record/true-probability
^clojure.lang.IFn$OD phat (fn phat ^double [datum]
(.invokePrim forest predictors datum))
_ (println "train MAD:"
(z/mean-absolute-difference p phat (:data options)))
_ (println "test MAD:"
(z/mean-absolute-difference p phat (:test-data options)))
y record/true-class
yhat (fn yhat ^double [datum]
(if (< (.invokePrim phat datum) 0.5) 0.0 1.0))
_ (println "train:" )
train-confusion (defs/print-confusion y yhat (:data options))
_ (println "test:" )
test-confusion (defs/print-confusion y yhat (:test-data options))]
(defs/serialization-test nss options forest)
(z/mapc #(tree/check-mincount options %) (taiga/terms forest))
(test/is (== (z/count (:data options)) (reduce + train-confusion)))
(test/is (= [14635 1776 1985 14372] train-confusion))
(test/is (== (z/count (:test-data options)) (reduce + test-confusion)))
(test/is (= [14338 1874 2090 14466] test-confusion))
(test/is (= (mapv taiga/node-height (taiga/terms forest)) [19]))
(test/is (= (mapv taiga/count-children (taiga/terms forest)) [203]))
(test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [102]))))
;------------------------------------------------------------------------------ | 113566 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-12-22"
:doc "Step function probability forest example." }
taiga.test.classify.step.tree
(:require [clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.tree :as tree]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.step.tree clojure:test > tests.txt
;;------------------------------------------------------------------------------
(def nss (str *ns*))
(test/deftest step-tree
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-diagonal-step-function 1.0))
options (assoc options :nterms 1)
forest (taiga/majority-vote-probability options)
predictors (into (sorted-map)
(dissoc record/attributes :ground-truth :prediction))
^clojure.lang.IFn$OD p record/true-probability
^clojure.lang.IFn$OD phat (fn phat ^double [datum]
(.invokePrim forest predictors datum))
_ (println "train MAD:"
(z/mean-absolute-difference p phat (:data options)))
_ (println "test MAD:"
(z/mean-absolute-difference p phat (:test-data options)))
y record/true-class
yhat (fn yhat ^double [datum]
(if (< (.invokePrim phat datum) 0.5) 0.0 1.0))
_ (println "train:" )
train-confusion (defs/print-confusion y yhat (:data options))
_ (println "test:" )
test-confusion (defs/print-confusion y yhat (:test-data options))]
(defs/serialization-test nss options forest)
(z/mapc #(tree/check-mincount options %) (taiga/terms forest))
(test/is (== (z/count (:data options)) (reduce + train-confusion)))
(test/is (= [14635 1776 1985 14372] train-confusion))
(test/is (== (z/count (:test-data options)) (reduce + test-confusion)))
(test/is (= [14338 1874 2090 14466] test-confusion))
(test/is (= (mapv taiga/node-height (taiga/terms forest)) [19]))
(test/is (= (mapv taiga/count-children (taiga/terms forest)) [203]))
(test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [102]))))
;------------------------------------------------------------------------------ | true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-12-22"
:doc "Step function probability forest example." }
taiga.test.classify.step.tree
(:require [clojure.test :as test]
[zana.api :as z]
[taiga.api :as taiga]
[taiga.test.tree :as tree]
[taiga.test.classify.data.record :as record]
[taiga.test.classify.data.defs :as defs]))
;; mvn -Dtest=taiga.test.classify.step.tree clojure:test > tests.txt
;;------------------------------------------------------------------------------
(def nss (str *ns*))
(test/deftest step-tree
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-diagonal-step-function 1.0))
options (assoc options :nterms 1)
forest (taiga/majority-vote-probability options)
predictors (into (sorted-map)
(dissoc record/attributes :ground-truth :prediction))
^clojure.lang.IFn$OD p record/true-probability
^clojure.lang.IFn$OD phat (fn phat ^double [datum]
(.invokePrim forest predictors datum))
_ (println "train MAD:"
(z/mean-absolute-difference p phat (:data options)))
_ (println "test MAD:"
(z/mean-absolute-difference p phat (:test-data options)))
y record/true-class
yhat (fn yhat ^double [datum]
(if (< (.invokePrim phat datum) 0.5) 0.0 1.0))
_ (println "train:" )
train-confusion (defs/print-confusion y yhat (:data options))
_ (println "test:" )
test-confusion (defs/print-confusion y yhat (:test-data options))]
(defs/serialization-test nss options forest)
(z/mapc #(tree/check-mincount options %) (taiga/terms forest))
(test/is (== (z/count (:data options)) (reduce + train-confusion)))
(test/is (= [14635 1776 1985 14372] train-confusion))
(test/is (== (z/count (:test-data options)) (reduce + test-confusion)))
(test/is (= [14338 1874 2090 14466] test-confusion))
(test/is (= (mapv taiga/node-height (taiga/terms forest)) [19]))
(test/is (= (mapv taiga/count-children (taiga/terms forest)) [203]))
(test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [102]))))
;------------------------------------------------------------------------------ |
[
{
"context": ";; Copyright (c) Thomas Athorne\n;;\n;; Licensed under the Apache License, Versio",
"end": 33,
"score": 0.9998769164085388,
"start": 19,
"tag": "NAME",
"value": "Thomas Athorne"
}
] | src/thicken/theme.clj | thomasathorne/thicken | 0 | ;; Copyright (c) Thomas Athorne
;;
;; 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 thicken.theme
(:import org.jfree.chart.renderer.xy.StandardXYBarPainter
org.jfree.chart.plot.PlotOrientation
java.awt.Color
java.awt.Shape))
(def vertical PlotOrientation/VERTICAL)
(defn color [r g b] (Color. r g b))
(defmulti set-theme type)
(defmethod set-theme org.jfree.chart.plot.Plot
[plot]
(doto plot
(.setBackgroundPaint Color/white)
(.setRangeGridlinePaint (color 200 100 200))
(.setDomainGridlinePaint (color 200 100 200))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYBarRenderer
[renderer]
(doto renderer
(.setOutlinePaint Color/white)
(.setPaint Color/gray)
(.setDrawBarOutline true)
(.setBarPainter (StandardXYBarPainter.))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYLineAndShapeRenderer
[renderer]
(let [point-size 4
c (- (/ point-size 2))
colors [Color/gray Color/green Color/red Color/blue Color/magenta
Color/pink Color/cyan Color/orange Color/yellow]]
(doseq [i (range 9)]
(.setSeriesPaint renderer i (nth colors i))
(.setSeriesShape renderer i (java.awt.geom.Ellipse2D$Double. c c point-size point-size)))))
(defmethod set-theme org.jfree.chart.JFreeChart
[chart]
(let [plot (.getPlot chart)
renderer (.getRenderer plot)]
(set-theme plot)
(set-theme renderer)))
(defmethod set-theme org.jfree.chart.renderer.category.BoxAndWhiskerRenderer
[renderer]
nil)
| 25730 | ;; Copyright (c) <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 thicken.theme
(:import org.jfree.chart.renderer.xy.StandardXYBarPainter
org.jfree.chart.plot.PlotOrientation
java.awt.Color
java.awt.Shape))
(def vertical PlotOrientation/VERTICAL)
(defn color [r g b] (Color. r g b))
(defmulti set-theme type)
(defmethod set-theme org.jfree.chart.plot.Plot
[plot]
(doto plot
(.setBackgroundPaint Color/white)
(.setRangeGridlinePaint (color 200 100 200))
(.setDomainGridlinePaint (color 200 100 200))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYBarRenderer
[renderer]
(doto renderer
(.setOutlinePaint Color/white)
(.setPaint Color/gray)
(.setDrawBarOutline true)
(.setBarPainter (StandardXYBarPainter.))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYLineAndShapeRenderer
[renderer]
(let [point-size 4
c (- (/ point-size 2))
colors [Color/gray Color/green Color/red Color/blue Color/magenta
Color/pink Color/cyan Color/orange Color/yellow]]
(doseq [i (range 9)]
(.setSeriesPaint renderer i (nth colors i))
(.setSeriesShape renderer i (java.awt.geom.Ellipse2D$Double. c c point-size point-size)))))
(defmethod set-theme org.jfree.chart.JFreeChart
[chart]
(let [plot (.getPlot chart)
renderer (.getRenderer plot)]
(set-theme plot)
(set-theme renderer)))
(defmethod set-theme org.jfree.chart.renderer.category.BoxAndWhiskerRenderer
[renderer]
nil)
| true | ;; Copyright (c) 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 thicken.theme
(:import org.jfree.chart.renderer.xy.StandardXYBarPainter
org.jfree.chart.plot.PlotOrientation
java.awt.Color
java.awt.Shape))
(def vertical PlotOrientation/VERTICAL)
(defn color [r g b] (Color. r g b))
(defmulti set-theme type)
(defmethod set-theme org.jfree.chart.plot.Plot
[plot]
(doto plot
(.setBackgroundPaint Color/white)
(.setRangeGridlinePaint (color 200 100 200))
(.setDomainGridlinePaint (color 200 100 200))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYBarRenderer
[renderer]
(doto renderer
(.setOutlinePaint Color/white)
(.setPaint Color/gray)
(.setDrawBarOutline true)
(.setBarPainter (StandardXYBarPainter.))))
(defmethod set-theme org.jfree.chart.renderer.xy.XYLineAndShapeRenderer
[renderer]
(let [point-size 4
c (- (/ point-size 2))
colors [Color/gray Color/green Color/red Color/blue Color/magenta
Color/pink Color/cyan Color/orange Color/yellow]]
(doseq [i (range 9)]
(.setSeriesPaint renderer i (nth colors i))
(.setSeriesShape renderer i (java.awt.geom.Ellipse2D$Double. c c point-size point-size)))))
(defmethod set-theme org.jfree.chart.JFreeChart
[chart]
(let [plot (.getPlot chart)
renderer (.getRenderer plot)]
(set-theme plot)
(set-theme renderer)))
(defmethod set-theme org.jfree.chart.renderer.category.BoxAndWhiskerRenderer
[renderer]
nil)
|
[
{
"context": "(ns state)\n\n; Code from: Programming Clojure, Alex Miller\n\n; p01: Refs and Software Transactional Memory\n\n;",
"end": 57,
"score": 0.9998659491539001,
"start": 46,
"tag": "NAME",
"value": "Alex Miller"
},
{
"context": "2: (deref reference)\n\n(deref current-track)\n;;=> \"Mars\"\n\n(identity @current-track)\n;;=> \"Mars\"\n\n; p01.03",
"end": 232,
"score": 0.9675577878952026,
"start": 228,
"tag": "NAME",
"value": "Mars"
},
{
"context": "ack)\n;;=> \"Mars\"\n\n(identity @current-track)\n;;=> \"Mars\"\n\n; p01.03: (ref-set reference new-value)\n\n(ref-s",
"end": 271,
"score": 0.935369610786438,
"start": 267,
"tag": "NAME",
"value": "Mars"
},
{
"context": "nder text])\n(->Message \"Ali\" \"Hi\")\n;;=> {:sender \"Ali\", :text \"Hi\"}\n\n(def messages (ref ()))\n\n; bad \n(d",
"end": 623,
"score": 0.5673530697822571,
"start": 620,
"tag": "NAME",
"value": "Ali"
},
{
"context": "message (->Message \"user1\" \"hi\"))\n;;=> ({:sender \"user1\", :text \"hi\"})\n\n; p03: (atom initial-state option",
"end": 1625,
"score": 0.7788980007171631,
"start": 1620,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "track (atom \"Mars\"))\n\n(deref current-track)\n;;=> \"Mars\"\n\n(identity @current-track)\n;;=> \"Mars\"\n\n; p03.02",
"end": 1747,
"score": 0.9462435841560364,
"start": 1743,
"tag": "NAME",
"value": "Mars"
},
{
"context": "ilar to commute\n\n(send counter inc)\n;;=> #<Agent@b7d9577: 1>\n\n(deref counter)\n;;=> 1\n",
"end": 2232,
"score": 0.6525560617446899,
"start": 2226,
"tag": "USERNAME",
"value": "7d9577"
}
] | clj/ex/study_clojure/ex06/src/state.clj | mertnuhoglu/study | 1 | (ns state)
; Code from: Programming Clojure, Alex Miller
; p01: Refs and Software Transactional Memory
; p01.01: (ref initial-state)
(def current-track (ref "Mars"))
; p01.02: (deref reference)
(deref current-track)
;;=> "Mars"
(identity @current-track)
;;=> "Mars"
; p01.03: (ref-set reference new-value)
(ref-set current-track "Venus")
; (err) Execution error (IllegalStateException) at state/eval9210 (REPL:21).
; p01.04: (dosync & exprs)
(dosync (ref-set current-track "Venus"))
;;=> "Venus"
; p02: (alter ref update-fn & args...)
(defrecord Message [sender text])
(->Message "Ali" "Hi")
;;=> {:sender "Ali", :text "Hi"}
(def messages (ref ()))
; bad
(defn naive-add-message [msg]
(dosync (ref-set messages (cons msg @messages))))
(defn add-message [msg]
(dosync (alter messages conj msg)))
(add-message (->Message "user1" "hi"))
(add-message (->Message "user2" "hola"))
;;=> ({:sender "user2", :text "hola"} {:sender "user1", :text "hi"})
; p02.02: (commute ref update-fn & args...)
; updates are commutative (in any order)
(defn add-message-commute [msg]
(dosync (commute messages conj msg)))
; p03: Validation to refs
; (ref initial-state options*)
; options:
; :validator validate-fn
; :meta metadata-map
(defn valid-message? [msg]
(and (:sender msg) (:text msg)))
(def validate-message-list #(every? valid-message? %))
(def messages (ref () :validator validate-message-list))
(add-message "not valid message")
; (err) Execution error (IllegalStateException) at state/add-message (REPL:42).
(identity @messages)
;;=> ()
(add-message (->Message "user1" "hi"))
;;=> ({:sender "user1", :text "hi"})
; p03: (atom initial-state options?)
(def current-track (atom "Mars"))
(deref current-track)
;;=> "Mars"
(identity @current-track)
;;=> "Mars"
; p03.02: (reset! an-atom newval)
(reset! current-track "Credo")
;;=> "Credo"
(reset! current-track {:title "t01" :composer "c01"})
;;=> {:title "t01", :composer "c01"}
; p03.03: (swap! an-atom f & args)
(swap! current-track assoc :title "t02")
;;=> {:title "t02", :composer "c01"}
; p04: (agent initial-state)
(def counter (agent 0))
; p04.02: (send agent update-fn & args)
; similar to commute
(send counter inc)
;;=> #<Agent@b7d9577: 1>
(deref counter)
;;=> 1
| 124289 | (ns state)
; Code from: Programming Clojure, <NAME>
; p01: Refs and Software Transactional Memory
; p01.01: (ref initial-state)
(def current-track (ref "Mars"))
; p01.02: (deref reference)
(deref current-track)
;;=> "<NAME>"
(identity @current-track)
;;=> "<NAME>"
; p01.03: (ref-set reference new-value)
(ref-set current-track "Venus")
; (err) Execution error (IllegalStateException) at state/eval9210 (REPL:21).
; p01.04: (dosync & exprs)
(dosync (ref-set current-track "Venus"))
;;=> "Venus"
; p02: (alter ref update-fn & args...)
(defrecord Message [sender text])
(->Message "Ali" "Hi")
;;=> {:sender "<NAME>", :text "Hi"}
(def messages (ref ()))
; bad
(defn naive-add-message [msg]
(dosync (ref-set messages (cons msg @messages))))
(defn add-message [msg]
(dosync (alter messages conj msg)))
(add-message (->Message "user1" "hi"))
(add-message (->Message "user2" "hola"))
;;=> ({:sender "user2", :text "hola"} {:sender "user1", :text "hi"})
; p02.02: (commute ref update-fn & args...)
; updates are commutative (in any order)
(defn add-message-commute [msg]
(dosync (commute messages conj msg)))
; p03: Validation to refs
; (ref initial-state options*)
; options:
; :validator validate-fn
; :meta metadata-map
(defn valid-message? [msg]
(and (:sender msg) (:text msg)))
(def validate-message-list #(every? valid-message? %))
(def messages (ref () :validator validate-message-list))
(add-message "not valid message")
; (err) Execution error (IllegalStateException) at state/add-message (REPL:42).
(identity @messages)
;;=> ()
(add-message (->Message "user1" "hi"))
;;=> ({:sender "user1", :text "hi"})
; p03: (atom initial-state options?)
(def current-track (atom "Mars"))
(deref current-track)
;;=> "<NAME>"
(identity @current-track)
;;=> "Mars"
; p03.02: (reset! an-atom newval)
(reset! current-track "Credo")
;;=> "Credo"
(reset! current-track {:title "t01" :composer "c01"})
;;=> {:title "t01", :composer "c01"}
; p03.03: (swap! an-atom f & args)
(swap! current-track assoc :title "t02")
;;=> {:title "t02", :composer "c01"}
; p04: (agent initial-state)
(def counter (agent 0))
; p04.02: (send agent update-fn & args)
; similar to commute
(send counter inc)
;;=> #<Agent@b7d9577: 1>
(deref counter)
;;=> 1
| true | (ns state)
; Code from: Programming Clojure, PI:NAME:<NAME>END_PI
; p01: Refs and Software Transactional Memory
; p01.01: (ref initial-state)
(def current-track (ref "Mars"))
; p01.02: (deref reference)
(deref current-track)
;;=> "PI:NAME:<NAME>END_PI"
(identity @current-track)
;;=> "PI:NAME:<NAME>END_PI"
; p01.03: (ref-set reference new-value)
(ref-set current-track "Venus")
; (err) Execution error (IllegalStateException) at state/eval9210 (REPL:21).
; p01.04: (dosync & exprs)
(dosync (ref-set current-track "Venus"))
;;=> "Venus"
; p02: (alter ref update-fn & args...)
(defrecord Message [sender text])
(->Message "Ali" "Hi")
;;=> {:sender "PI:NAME:<NAME>END_PI", :text "Hi"}
(def messages (ref ()))
; bad
(defn naive-add-message [msg]
(dosync (ref-set messages (cons msg @messages))))
(defn add-message [msg]
(dosync (alter messages conj msg)))
(add-message (->Message "user1" "hi"))
(add-message (->Message "user2" "hola"))
;;=> ({:sender "user2", :text "hola"} {:sender "user1", :text "hi"})
; p02.02: (commute ref update-fn & args...)
; updates are commutative (in any order)
(defn add-message-commute [msg]
(dosync (commute messages conj msg)))
; p03: Validation to refs
; (ref initial-state options*)
; options:
; :validator validate-fn
; :meta metadata-map
(defn valid-message? [msg]
(and (:sender msg) (:text msg)))
(def validate-message-list #(every? valid-message? %))
(def messages (ref () :validator validate-message-list))
(add-message "not valid message")
; (err) Execution error (IllegalStateException) at state/add-message (REPL:42).
(identity @messages)
;;=> ()
(add-message (->Message "user1" "hi"))
;;=> ({:sender "user1", :text "hi"})
; p03: (atom initial-state options?)
(def current-track (atom "Mars"))
(deref current-track)
;;=> "PI:NAME:<NAME>END_PI"
(identity @current-track)
;;=> "Mars"
; p03.02: (reset! an-atom newval)
(reset! current-track "Credo")
;;=> "Credo"
(reset! current-track {:title "t01" :composer "c01"})
;;=> {:title "t01", :composer "c01"}
; p03.03: (swap! an-atom f & args)
(swap! current-track assoc :title "t02")
;;=> {:title "t02", :composer "c01"}
; p04: (agent initial-state)
(def counter (agent 0))
; p04.02: (send agent update-fn & args)
; similar to commute
(send counter inc)
;;=> #<Agent@b7d9577: 1>
(deref counter)
;;=> 1
|
[
{
"context": "ntation of global thermonuclear war.\"\n {:author \"Daniel Solano Gómez\"}\n (:gen-class :main no\n :extends a",
"end": 1740,
"score": 0.999785840511322,
"start": 1721,
"tag": "NAME",
"value": "Daniel Solano Gómez"
}
] | jvm-lang/clojure/src/clojure/decafbot/clojure/GlobalThermonuclearWarActivity.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.GlobalThermonuclearWarActivity
"Implementation of global thermonuclear war."
{: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.widget.ArrayAdapter
[decafbot.clojure GuessTheNumberActivity
R$array R$id R$layout R$string]))
(def talker (atom nil))
(defn draw-conclusion
[activity]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/gtw_conclusion
:negative-button [R$string/no_thanks
#(.finish activity)]
:positive-button [R$string/sure
#(start-activity activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/gtw_conclusion)))
(defn learn-task
[activity adapter strategies]
(let [max-progress 10000
num-strategies (count strategies)
update-factor (/ max-progress num-strategies)
strategy-num (atom 0)
update-progress
(fn [strategy]
(.runOnUiThread activity
(reify Runnable
(run [_]
(.setProgress activity (int (* (swap! strategy-num inc)
update-factor)))
(.add adapter strategy)))))]
(proxy [android.os.AsyncTask] []
(onPreExecute []
(.setProgress activity 0))
(doInBackground [_]
(doseq [strategy strategies]
(Thread/sleep 50)
(update-progress strategy)))
(onPostExecute [_]
(.setProgress activity max-progress)
(draw-conclusion activity)))))
(defn -onCreate [this bundle]
(doto this
(.requestWindowFeature android.view.Window/FEATURE_PROGRESS)
(.superOnCreate bundle)
(.setContentView R$layout/global_thermonuclear_war))
(reset! talker (talker/init this))
(let [adapter (ArrayAdapter. this android.R$layout/simple_list_item_1)
strategies (.. this getResources (getStringArray R$array/gtw_strategies))]
(.. this (findViewById R$id/gtw_strategy_list) (setAdapter adapter))
(.execute (learn-task this adapter strategies) nil)))
(defn -onDestroy
[this]
(when @talker
(talker/shutdown @talker)
(reset! talker nil))
(.superOnDestroy this))
| 103953 | ; 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.GlobalThermonuclearWarActivity
"Implementation of global thermonuclear war."
{: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.widget.ArrayAdapter
[decafbot.clojure GuessTheNumberActivity
R$array R$id R$layout R$string]))
(def talker (atom nil))
(defn draw-conclusion
[activity]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/gtw_conclusion
:negative-button [R$string/no_thanks
#(.finish activity)]
:positive-button [R$string/sure
#(start-activity activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/gtw_conclusion)))
(defn learn-task
[activity adapter strategies]
(let [max-progress 10000
num-strategies (count strategies)
update-factor (/ max-progress num-strategies)
strategy-num (atom 0)
update-progress
(fn [strategy]
(.runOnUiThread activity
(reify Runnable
(run [_]
(.setProgress activity (int (* (swap! strategy-num inc)
update-factor)))
(.add adapter strategy)))))]
(proxy [android.os.AsyncTask] []
(onPreExecute []
(.setProgress activity 0))
(doInBackground [_]
(doseq [strategy strategies]
(Thread/sleep 50)
(update-progress strategy)))
(onPostExecute [_]
(.setProgress activity max-progress)
(draw-conclusion activity)))))
(defn -onCreate [this bundle]
(doto this
(.requestWindowFeature android.view.Window/FEATURE_PROGRESS)
(.superOnCreate bundle)
(.setContentView R$layout/global_thermonuclear_war))
(reset! talker (talker/init this))
(let [adapter (ArrayAdapter. this android.R$layout/simple_list_item_1)
strategies (.. this getResources (getStringArray R$array/gtw_strategies))]
(.. this (findViewById R$id/gtw_strategy_list) (setAdapter adapter))
(.execute (learn-task this adapter strategies) nil)))
(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.GlobalThermonuclearWarActivity
"Implementation of global thermonuclear war."
{: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.widget.ArrayAdapter
[decafbot.clojure GuessTheNumberActivity
R$array R$id R$layout R$string]))
(def talker (atom nil))
(defn draw-conclusion
[activity]
(show-dialog activity
:title R$string/game_name_global_thermonuclear_war
:message R$string/gtw_conclusion
:negative-button [R$string/no_thanks
#(.finish activity)]
:positive-button [R$string/sure
#(start-activity activity GuessTheNumberActivity)])
(talker/say @talker (.getString activity R$string/gtw_conclusion)))
(defn learn-task
[activity adapter strategies]
(let [max-progress 10000
num-strategies (count strategies)
update-factor (/ max-progress num-strategies)
strategy-num (atom 0)
update-progress
(fn [strategy]
(.runOnUiThread activity
(reify Runnable
(run [_]
(.setProgress activity (int (* (swap! strategy-num inc)
update-factor)))
(.add adapter strategy)))))]
(proxy [android.os.AsyncTask] []
(onPreExecute []
(.setProgress activity 0))
(doInBackground [_]
(doseq [strategy strategies]
(Thread/sleep 50)
(update-progress strategy)))
(onPostExecute [_]
(.setProgress activity max-progress)
(draw-conclusion activity)))))
(defn -onCreate [this bundle]
(doto this
(.requestWindowFeature android.view.Window/FEATURE_PROGRESS)
(.superOnCreate bundle)
(.setContentView R$layout/global_thermonuclear_war))
(reset! talker (talker/init this))
(let [adapter (ArrayAdapter. this android.R$layout/simple_list_item_1)
strategies (.. this getResources (getStringArray R$array/gtw_strategies))]
(.. this (findViewById R$id/gtw_strategy_list) (setAdapter adapter))
(.execute (learn-task this adapter strategies) nil)))
(defn -onDestroy
[this]
(when @talker
(talker/shutdown @talker)
(reset! talker nil))
(.superOnDestroy this))
|
[
{
"context": "{:auth\n {:KEY (.getBytes \"s49628MbrU8VoG8Q\")\n :MACKEY (.getBytes \"R4A6bX69a4NU68xK\")}\n }",
"end": 42,
"score": 0.9882316589355469,
"start": 26,
"tag": "KEY",
"value": "s49628MbrU8VoG8Q"
},
{
"context": "etBytes \"s49628MbrU8VoG8Q\")\n :MACKEY (.getBytes \"R4A6bX69a4NU68xK\")}\n }",
"end": 83,
"score": 0.9976020455360413,
"start": 67,
"tag": "KEY",
"value": "R4A6bX69a4NU68xK"
}
] | properties_example.clj | jrosti/ontrail | 1 | {:auth
{:KEY (.getBytes "s49628MbrU8VoG8Q")
:MACKEY (.getBytes "R4A6bX69a4NU68xK")}
} | 11641 | {:auth
{:KEY (.getBytes "<KEY>")
:MACKEY (.getBytes "<KEY>")}
} | true | {:auth
{:KEY (.getBytes "PI:KEY:<KEY>END_PI")
:MACKEY (.getBytes "PI:KEY:<KEY>END_PI")}
} |
[
{
"context": " }\n }\n :result {\n :id 1\n :name \"Luke Skywalker\"\n :weaponId 2\n }\n }}\n)\n\n(defn get-sample",
"end": 371,
"score": 0.9997665882110596,
"start": 357,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "details {}\n :result {\n :id 1\n :name \"Luke Skywalker\"\n :weaponId 2\n }\n }}\n)\n\n(defn get-sample",
"end": 521,
"score": 0.9996139407157898,
"start": 507,
"tag": "NAME",
"value": "Luke Skywalker"
}
] | test/unit/restql/core/response/headers_test.clj | caiorcferreira/restQL-clojure | 2 | (ns restql.core.response.headers-test
(:require [clojure.test :refer [deftest is]])
(:use restql.core.response.headers))
(defn get-sample-result []
{:jedis {
:details {
:headers {
:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"
}
}
:result {
:id 1
:name "Luke Skywalker"
:weaponId 2
}
}}
)
(defn get-sample-minimal-result []
{:jedis {
:details {}
:result {
:id 1
:name "Luke Skywalker"
:weaponId 2
}
}}
)
(defn get-sample-query [] ^{:cache-control 900} [:from "jedis"])
(defn get-sample-minimal-query [] [:from "jedis"])
(deftest map-headers-to-resource-test
(is
(= [{:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}]
(map map-headers-to-resource (get-sample-result))
)
)
)
(deftest map-response-headers-by-resources-test
(is
(= {:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}
(map-response-headers-by-resources (get-sample-result))
)
)
)
(deftest get-response-headers-test
(is
(= {:x-type-jedis "Jedi" :x-weapon-jedis "Light Saber" :cache-control "max-age=900"}
(get-response-headers (get-sample-query) (get-sample-result))
)
)
(is
(= {}
(get-response-headers (get-sample-minimal-query) (get-sample-minimal-result))
)
)
)
| 34503 | (ns restql.core.response.headers-test
(:require [clojure.test :refer [deftest is]])
(:use restql.core.response.headers))
(defn get-sample-result []
{:jedis {
:details {
:headers {
:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"
}
}
:result {
:id 1
:name "<NAME>"
:weaponId 2
}
}}
)
(defn get-sample-minimal-result []
{:jedis {
:details {}
:result {
:id 1
:name "<NAME>"
:weaponId 2
}
}}
)
(defn get-sample-query [] ^{:cache-control 900} [:from "jedis"])
(defn get-sample-minimal-query [] [:from "jedis"])
(deftest map-headers-to-resource-test
(is
(= [{:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}]
(map map-headers-to-resource (get-sample-result))
)
)
)
(deftest map-response-headers-by-resources-test
(is
(= {:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}
(map-response-headers-by-resources (get-sample-result))
)
)
)
(deftest get-response-headers-test
(is
(= {:x-type-jedis "Jedi" :x-weapon-jedis "Light Saber" :cache-control "max-age=900"}
(get-response-headers (get-sample-query) (get-sample-result))
)
)
(is
(= {}
(get-response-headers (get-sample-minimal-query) (get-sample-minimal-result))
)
)
)
| true | (ns restql.core.response.headers-test
(:require [clojure.test :refer [deftest is]])
(:use restql.core.response.headers))
(defn get-sample-result []
{:jedis {
:details {
:headers {
:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"
}
}
:result {
:id 1
:name "PI:NAME:<NAME>END_PI"
:weaponId 2
}
}}
)
(defn get-sample-minimal-result []
{:jedis {
:details {}
:result {
:id 1
:name "PI:NAME:<NAME>END_PI"
:weaponId 2
}
}}
)
(defn get-sample-query [] ^{:cache-control 900} [:from "jedis"])
(defn get-sample-minimal-query [] [:from "jedis"])
(deftest map-headers-to-resource-test
(is
(= [{:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}]
(map map-headers-to-resource (get-sample-result))
)
)
)
(deftest map-response-headers-by-resources-test
(is
(= {:jedis {:x-type "Jedi"
:x-weapon "Light Saber"
:cache-control "max-age=500, s-maxage=1200"}}
(map-response-headers-by-resources (get-sample-result))
)
)
)
(deftest get-response-headers-test
(is
(= {:x-type-jedis "Jedi" :x-weapon-jedis "Light Saber" :cache-control "max-age=900"}
(get-response-headers (get-sample-query) (get-sample-result))
)
)
(is
(= {}
(get-response-headers (get-sample-minimal-query) (get-sample-minimal-result))
)
)
)
|
[
{
"context": "(def pages {\"auto-complete\" {:key \"auto-complete\"\n :render-fn ",
"end": 612,
"score": 0.613296627998352,
"start": 612,
"tag": "KEY",
"value": ""
},
{
"context": "x 16px\"}}\n [:a {:href \"https://gitlab.com/synqrinus/syn-antd\"}\n \"Source\"]]\n [:li\n ",
"end": 2838,
"score": 0.9985199570655823,
"start": 2829,
"tag": "USERNAME",
"value": "synqrinus"
}
] | dev/syn_antd/test_page.cljs | heypragyan/syn-antd | 3 | (ns syn-antd.test-page
(:require
[re-frame.core :as re-frame]
[reagent.core :as reagent]
[syn-antd.layout :as layout]
[syn-antd.menu :as menu]
;; Demo pages
[syn-antd.auto-complete-page :as auto-complete-page]
[syn-antd.input-page :as input-page]
[syn-antd.input-number-page :as input-number-page]))
(re-frame/reg-sub ::active-page (fn [db _] (::active-page db)))
(re-frame/reg-event-fx
::change-page
(fn [{:keys [db]} [_ new-page handler]]
{:dispatch [handler]
:db (assoc db ::active-page new-page)}))
(def pages {"auto-complete" {:key "auto-complete"
:render-fn #'auto-complete-page/test-auto-complete-page
:change-handler ::auto-complete-page/init
:label "AutoComplete"}
"input" {:key "input"
:render-fn #'input-page/test-input-page
:change-handler ::input-page/init
:label "Input"}
"input-number" {:key "input-number"
:render-fn #'input-number-page/test-input-page
:change-handler ::input-number-page/init
:label "InputNumber"}})
(defn menu-item [{:keys [key label]}]
)
(defn test-page []
(let [active-page @(re-frame/subscribe [::active-page])]
[layout/layout
[layout/layout-sider
{:style {:overflow "auto"
:height "100vh"
:position "fixed"
:left 0}}
[menu/menu
{:theme "dark"
:mode "inline"
:selected-keys [active-page]
:on-select (fn [k]
(let [{:keys [key change-handler]} (get pages (aget k "key"))]
(re-frame/dispatch [::change-page key change-handler])))}
(for [[k {:keys [key label]}] pages]
^{:key k}
[menu/menu-item
{:key key}
label])]]
[layout/layout {:style {:margin-left "200px"}}
[layout/layout-header {:style {:background "#fff"}}
[:h1 "syn-antd"]]
[layout/layout-content {:style {:margin "24px 16px 0px"
:overflow "initial"}}
[:div {:style {:padding "24px"
:background "#fff"}}
(if (some? active-page)
[(get-in pages [active-page :render-fn])]
[:p "Select a page from the right to begin"])]]
[layout/layout-footer {:style {:text-align "center"}}
[:ul
{:style {:list-style "none"}}
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://gitlab.com/synqrinus/syn-antd"}
"Source"]]
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://ant.design/"}
"antd Docs"]]]]]]))
(defn ^:dev/after-load mount-components []
(re-frame/clear-subscription-cache!)
(reagent/render [#'test-page]
(.getElementById js/document "app")))
(defn init! []
(mount-components)) | 6932 | (ns syn-antd.test-page
(:require
[re-frame.core :as re-frame]
[reagent.core :as reagent]
[syn-antd.layout :as layout]
[syn-antd.menu :as menu]
;; Demo pages
[syn-antd.auto-complete-page :as auto-complete-page]
[syn-antd.input-page :as input-page]
[syn-antd.input-number-page :as input-number-page]))
(re-frame/reg-sub ::active-page (fn [db _] (::active-page db)))
(re-frame/reg-event-fx
::change-page
(fn [{:keys [db]} [_ new-page handler]]
{:dispatch [handler]
:db (assoc db ::active-page new-page)}))
(def pages {"auto-complete" {:key "auto<KEY>-complete"
:render-fn #'auto-complete-page/test-auto-complete-page
:change-handler ::auto-complete-page/init
:label "AutoComplete"}
"input" {:key "input"
:render-fn #'input-page/test-input-page
:change-handler ::input-page/init
:label "Input"}
"input-number" {:key "input-number"
:render-fn #'input-number-page/test-input-page
:change-handler ::input-number-page/init
:label "InputNumber"}})
(defn menu-item [{:keys [key label]}]
)
(defn test-page []
(let [active-page @(re-frame/subscribe [::active-page])]
[layout/layout
[layout/layout-sider
{:style {:overflow "auto"
:height "100vh"
:position "fixed"
:left 0}}
[menu/menu
{:theme "dark"
:mode "inline"
:selected-keys [active-page]
:on-select (fn [k]
(let [{:keys [key change-handler]} (get pages (aget k "key"))]
(re-frame/dispatch [::change-page key change-handler])))}
(for [[k {:keys [key label]}] pages]
^{:key k}
[menu/menu-item
{:key key}
label])]]
[layout/layout {:style {:margin-left "200px"}}
[layout/layout-header {:style {:background "#fff"}}
[:h1 "syn-antd"]]
[layout/layout-content {:style {:margin "24px 16px 0px"
:overflow "initial"}}
[:div {:style {:padding "24px"
:background "#fff"}}
(if (some? active-page)
[(get-in pages [active-page :render-fn])]
[:p "Select a page from the right to begin"])]]
[layout/layout-footer {:style {:text-align "center"}}
[:ul
{:style {:list-style "none"}}
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://gitlab.com/synqrinus/syn-antd"}
"Source"]]
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://ant.design/"}
"antd Docs"]]]]]]))
(defn ^:dev/after-load mount-components []
(re-frame/clear-subscription-cache!)
(reagent/render [#'test-page]
(.getElementById js/document "app")))
(defn init! []
(mount-components)) | true | (ns syn-antd.test-page
(:require
[re-frame.core :as re-frame]
[reagent.core :as reagent]
[syn-antd.layout :as layout]
[syn-antd.menu :as menu]
;; Demo pages
[syn-antd.auto-complete-page :as auto-complete-page]
[syn-antd.input-page :as input-page]
[syn-antd.input-number-page :as input-number-page]))
(re-frame/reg-sub ::active-page (fn [db _] (::active-page db)))
(re-frame/reg-event-fx
::change-page
(fn [{:keys [db]} [_ new-page handler]]
{:dispatch [handler]
:db (assoc db ::active-page new-page)}))
(def pages {"auto-complete" {:key "autoPI:KEY:<KEY>END_PI-complete"
:render-fn #'auto-complete-page/test-auto-complete-page
:change-handler ::auto-complete-page/init
:label "AutoComplete"}
"input" {:key "input"
:render-fn #'input-page/test-input-page
:change-handler ::input-page/init
:label "Input"}
"input-number" {:key "input-number"
:render-fn #'input-number-page/test-input-page
:change-handler ::input-number-page/init
:label "InputNumber"}})
(defn menu-item [{:keys [key label]}]
)
(defn test-page []
(let [active-page @(re-frame/subscribe [::active-page])]
[layout/layout
[layout/layout-sider
{:style {:overflow "auto"
:height "100vh"
:position "fixed"
:left 0}}
[menu/menu
{:theme "dark"
:mode "inline"
:selected-keys [active-page]
:on-select (fn [k]
(let [{:keys [key change-handler]} (get pages (aget k "key"))]
(re-frame/dispatch [::change-page key change-handler])))}
(for [[k {:keys [key label]}] pages]
^{:key k}
[menu/menu-item
{:key key}
label])]]
[layout/layout {:style {:margin-left "200px"}}
[layout/layout-header {:style {:background "#fff"}}
[:h1 "syn-antd"]]
[layout/layout-content {:style {:margin "24px 16px 0px"
:overflow "initial"}}
[:div {:style {:padding "24px"
:background "#fff"}}
(if (some? active-page)
[(get-in pages [active-page :render-fn])]
[:p "Select a page from the right to begin"])]]
[layout/layout-footer {:style {:text-align "center"}}
[:ul
{:style {:list-style "none"}}
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://gitlab.com/synqrinus/syn-antd"}
"Source"]]
[:li
{:style {:display "inline"
:padding "0px 16px"}}
[:a {:href "https://ant.design/"}
"antd Docs"]]]]]]))
(defn ^:dev/after-load mount-components []
(re-frame/clear-subscription-cache!)
(reagent/render [#'test-page]
(.getElementById js/document "app")))
(defn init! []
(mount-components)) |
[
{
"context": "lytics.io\\\",\n :type \\\"Organization\\\",\n :name \\\"Yet Analytics\\\"},\n :versions\n [{:id \\\"https://w3id.or",
"end": 1147,
"score": 0.648216962814331,
"start": 1145,
"tag": "NAME",
"value": "et"
}
] | src/test/com/yetanalytics/pan_test/errors_test_fixtures.cljc | yetanalytics/project-pan | 2 | (ns com.yetanalytics.pan-test.errors-test-fixtures)
;; Profile metadata error
(def err-msg-1
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an id\"
of property:
:id
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"Yet Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be a valid IRI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"Yet Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be: \"Profile\"
-------------------------
Detected 2 errors
")
;; Concept error
(def err-msg-2
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an iri\"
of property:
:recommendedVerbs
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid IRI
-- Spec failed --------------------
Value:
\"{\\\"type\\\": \\\"notAType\\\"}\"
of property:
:inlineSchema
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid JSON schema
-------------------------
Detected 2 errors
")
;; Statement Template error
;; Note: cljs version differs from clj by having an extra column in the table
(def err-msg-3
#?(:clj
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+===============================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+-----------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+-----------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"
:cljs
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+================================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+------------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+------------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"))
;; ID Error
(def err-msg-4
"
**** ID Errors ****
-- Spec failed --------------------
Identifier:
\"https://w3id.org/xapi/catch/v1\"
which occurs 2 times in the Profile
should be a unique identifier value
-- Spec failed --------------------
Identifier:
\"https://foo.org/template\"
which occurs 2 times in the Profile
should be a unique identifier value
-------------------------
Detected 2 errors
")
;; InScheme Error
(def err-msg-5
"
**** Version Errors ****
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/invalid\"
associated with the identifier:
\"https://foo.org/template\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/also-invalid\"
associated with the identifier:
\"https://foo.org/template2\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-------------------------
Detected 2 errors
")
;; Template edge errors - nonexistent destination node
(def err-msg-6
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-verb\",
:type nil,
:inScheme nil,
...}
via the property:
:verb
should not link to non-existent Concept or Template
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-aut1\",
:type nil,
:inScheme nil,
...}
via the property:
:attachmentUsageType
should not link to non-existent Concept or Template
-------------------------
Detected 2 errors
")
;; Template edge errors - invalid destinations
(def err-msg-7
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template2\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:verb
should link to type: \"Verb\"
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:attachmentUsageType
should not refer to itself
-------------------------
Detected 2 errors
")
;; Cyclic pattern error
(def err-msg-8
"
**** Pattern Cycle Errors ****
-- Spec failed --------------------
The following Patterns:
\"https://foo.org/pattern-one\"
\"https://foo.org/pattern-two\"
should not contain cyclical references
-------------------------
Detected 1 error
")
;; Pattern edge errors
(def err-msg-9
"
**** Pattern Edge Errors ****
-- Spec failed --------------------
Pattern:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:primary true,
...}
that links to object:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:oneOrMore ...,
...}
via the property:
:oneOrMore
and is used 1 time to link out to 1 object
should not refer to itself
-------------------------
Detected 1 error
")
;; Context errors
(def err-msg-10
"
**** Context Errors ****
-- Spec failed --------------------
Value:
\"profile:Profile\"
in context:
{:id \"@id\",
:type \"@type\",
:Profile \"profile:Profile\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:Verb\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:ActivityType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:AttachmentUsageType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-------------------------
Detected 4 errors
")
;; Context key errors
(def err-msg-11
"
**** Context Key Errors ****
-- Spec failed --------------------
Value:
:hello
in object:
{:id \"https://foo.org/activity/1\",
:type \"Activity\",
:_context \"https://w3id.org/xapi/profiles/activity-context\",
:hello \"World\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:foo
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:baz
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-------------------------
Detected 3 errors
") | 3834 | (ns com.yetanalytics.pan-test.errors-test-fixtures)
;; Profile metadata error
(def err-msg-1
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an id\"
of property:
:id
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"Yet Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be a valid IRI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"Y<NAME> Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be: \"Profile\"
-------------------------
Detected 2 errors
")
;; Concept error
(def err-msg-2
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an iri\"
of property:
:recommendedVerbs
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid IRI
-- Spec failed --------------------
Value:
\"{\\\"type\\\": \\\"notAType\\\"}\"
of property:
:inlineSchema
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid JSON schema
-------------------------
Detected 2 errors
")
;; Statement Template error
;; Note: cljs version differs from clj by having an extra column in the table
(def err-msg-3
#?(:clj
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+===============================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+-----------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+-----------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"
:cljs
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+================================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+------------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+------------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"))
;; ID Error
(def err-msg-4
"
**** ID Errors ****
-- Spec failed --------------------
Identifier:
\"https://w3id.org/xapi/catch/v1\"
which occurs 2 times in the Profile
should be a unique identifier value
-- Spec failed --------------------
Identifier:
\"https://foo.org/template\"
which occurs 2 times in the Profile
should be a unique identifier value
-------------------------
Detected 2 errors
")
;; InScheme Error
(def err-msg-5
"
**** Version Errors ****
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/invalid\"
associated with the identifier:
\"https://foo.org/template\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/also-invalid\"
associated with the identifier:
\"https://foo.org/template2\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-------------------------
Detected 2 errors
")
;; Template edge errors - nonexistent destination node
(def err-msg-6
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-verb\",
:type nil,
:inScheme nil,
...}
via the property:
:verb
should not link to non-existent Concept or Template
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-aut1\",
:type nil,
:inScheme nil,
...}
via the property:
:attachmentUsageType
should not link to non-existent Concept or Template
-------------------------
Detected 2 errors
")
;; Template edge errors - invalid destinations
(def err-msg-7
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template2\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:verb
should link to type: \"Verb\"
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:attachmentUsageType
should not refer to itself
-------------------------
Detected 2 errors
")
;; Cyclic pattern error
(def err-msg-8
"
**** Pattern Cycle Errors ****
-- Spec failed --------------------
The following Patterns:
\"https://foo.org/pattern-one\"
\"https://foo.org/pattern-two\"
should not contain cyclical references
-------------------------
Detected 1 error
")
;; Pattern edge errors
(def err-msg-9
"
**** Pattern Edge Errors ****
-- Spec failed --------------------
Pattern:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:primary true,
...}
that links to object:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:oneOrMore ...,
...}
via the property:
:oneOrMore
and is used 1 time to link out to 1 object
should not refer to itself
-------------------------
Detected 1 error
")
;; Context errors
(def err-msg-10
"
**** Context Errors ****
-- Spec failed --------------------
Value:
\"profile:Profile\"
in context:
{:id \"@id\",
:type \"@type\",
:Profile \"profile:Profile\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:Verb\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:ActivityType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:AttachmentUsageType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-------------------------
Detected 4 errors
")
;; Context key errors
(def err-msg-11
"
**** Context Key Errors ****
-- Spec failed --------------------
Value:
:hello
in object:
{:id \"https://foo.org/activity/1\",
:type \"Activity\",
:_context \"https://w3id.org/xapi/profiles/activity-context\",
:hello \"World\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:foo
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:baz
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-------------------------
Detected 3 errors
") | true | (ns com.yetanalytics.pan-test.errors-test-fixtures)
;; Profile metadata error
(def err-msg-1
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an id\"
of property:
:id
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"Yet Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be a valid IRI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"not an id\",
:type \"FooBar\",
:prefLabel {\"en\" \"Catch\"},
:definition
{\"en\" \"The profile for the trinity education application CATCH\"},
:_context \"https://w3id.org/xapi/profiles/context\",
:conformsTo \"https://w3id.org/xapi/profiles#1.0\",
:author
{:url \"https://www.yetanalytics.io\",
:type \"Organization\",
:name \"YPI:NAME:<NAME>END_PI Analytics\"},
:versions
[{:id \"https://w3id.org/xapi/catch/v1\",
:generatedAtTime \"2017-12-22T22:30:00-07:00\"}]}
should be: \"Profile\"
-------------------------
Detected 2 errors
")
;; Concept error
(def err-msg-2
"
**** Syntax Errors ****
-- Spec failed --------------------
Value:
\"not an iri\"
of property:
:recommendedVerbs
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid IRI
-- Spec failed --------------------
Value:
\"{\\\"type\\\": \\\"notAType\\\"}\"
of property:
:inlineSchema
in object:
{:id \"https://foo.org/bad-concept\",
:type \"ContextExtension\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
:prefLabel {\"en\" \"Bad Concept\"},
:definition {\"en\" \"foo bar\"},
:recommendedVerbs [\"not an iri\"],
:inlineSchema \"{\\\"type\\\": \\\"notAType\\\"}\"}
should be a valid JSON schema
-------------------------
Detected 2 errors
")
;; Statement Template error
;; Note: cljs version differs from clj by having an extra column in the table
(def err-msg-3
#?(:clj
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+===============================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+-----------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+-----------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"
:cljs
"
**** Syntax Errors ****
-- Spec failed --------------------
Object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should contain keys: :definition, :inScheme, :prefLabel
| key | spec |
|=============+================================================|
| :definition | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
|-------------+------------------------------------------------|
| :inScheme | (and |
| | :com.yetanalytics.pan.axioms/string |
| | (partial |
| | re-matches |
| | xapi-schema.spec.regex/AbsoluteIRIRegEx)) |
|-------------+------------------------------------------------|
| :prefLabel | (map-of |
| | :com.yetanalytics.pan.axioms/language-tag |
| | :com.yetanalytics.pan.axioms/lang-map-string |
| | :min-count |
| | 1) |
-- Spec failed --------------------
Value:
\"this-template-is-invalid\"
of property:
:id
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be a valid URI
-- Spec failed --------------------
Value:
\"FooBar\"
of property:
:type
in object:
{:id \"this-template-is-invalid\", :type \"FooBar\"}
should be: \"StatementTemplate\"
-------------------------
Detected 3 errors
"))
;; ID Error
(def err-msg-4
"
**** ID Errors ****
-- Spec failed --------------------
Identifier:
\"https://w3id.org/xapi/catch/v1\"
which occurs 2 times in the Profile
should be a unique identifier value
-- Spec failed --------------------
Identifier:
\"https://foo.org/template\"
which occurs 2 times in the Profile
should be a unique identifier value
-------------------------
Detected 2 errors
")
;; InScheme Error
(def err-msg-5
"
**** Version Errors ****
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/invalid\"
associated with the identifier:
\"https://foo.org/template\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-- Spec failed --------------------
InScheme IRI:
\"https://foo.org/also-invalid\"
associated with the identifier:
\"https://foo.org/template2\"
in a Profile with the following version IDs:
\"https://w3id.org/xapi/catch/v1\"
\"https://w3id.org/xapi/catch/v2\"
should be a valid version ID
-------------------------
Detected 2 errors
")
;; Template edge errors - nonexistent destination node
(def err-msg-6
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-verb\",
:type nil,
:inScheme nil,
...}
via the property:
:verb
should not link to non-existent Concept or Template
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/dead-aut1\",
:type nil,
:inScheme nil,
...}
via the property:
:attachmentUsageType
should not link to non-existent Concept or Template
-------------------------
Detected 2 errors
")
;; Template edge errors - invalid destinations
(def err-msg-7
"
**** Template Edge Errors ****
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template2\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:verb
should link to type: \"Verb\"
-- Spec failed --------------------
Statement Template:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
that links to object:
{:id \"https://foo.org/template\",
:type \"StatementTemplate\",
:inScheme \"https://w3id.org/xapi/catch/v1\",
...}
via the property:
:attachmentUsageType
should not refer to itself
-------------------------
Detected 2 errors
")
;; Cyclic pattern error
(def err-msg-8
"
**** Pattern Cycle Errors ****
-- Spec failed --------------------
The following Patterns:
\"https://foo.org/pattern-one\"
\"https://foo.org/pattern-two\"
should not contain cyclical references
-------------------------
Detected 1 error
")
;; Pattern edge errors
(def err-msg-9
"
**** Pattern Edge Errors ****
-- Spec failed --------------------
Pattern:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:primary true,
...}
that links to object:
{:id \"https://foo.org/pattern-three\",
:type \"Pattern\",
:oneOrMore ...,
...}
via the property:
:oneOrMore
and is used 1 time to link out to 1 object
should not refer to itself
-------------------------
Detected 1 error
")
;; Context errors
(def err-msg-10
"
**** Context Errors ****
-- Spec failed --------------------
Value:
\"profile:Profile\"
in context:
{:id \"@id\",
:type \"@type\",
:Profile \"profile:Profile\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:Verb\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:ActivityType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-- Spec failed --------------------
Value:
\"xapi:AttachmentUsageType\"
in context:
{:id \"@id\",
:type \"@type\",
:ActivityType \"xapi:ActivityType\",
:AttachmentUsageType \"xapi:AttachmentUsageType\",
:Profile \"profile:Profile\",
:Verb \"xapi:Verb\",
:profile \"https://w3id.org/xapi/profiles/ontology#\",
:prov \"http://www.w3.org/ns/prov#\",
:skos \"http://www.w3.org/2004/02/skos/core#\"}
should be a JSON-LD context keyword
or
should be a JSON-LD prefix
or
should be a simple term definition with a valid prefix
or
should be an expanded term definition with a valid prefix
-------------------------
Detected 4 errors
")
;; Context key errors
(def err-msg-11
"
**** Context Key Errors ****
-- Spec failed --------------------
Value:
:hello
in object:
{:id \"https://foo.org/activity/1\",
:type \"Activity\",
:_context \"https://w3id.org/xapi/profiles/activity-context\",
:hello \"World\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:foo
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-- Spec failed --------------------
Value:
:baz
in object:
{:id \"https://foo.org/profile\",
:type \"Profile\",
:_context \"https://w3id.org/xapi/profiles/context\",
:concepts [...],
:baz \"Qux\",
:foo \"Bar\"}
should be expandable into an absolute IRI
or
should be a JSON-LD keyword
-------------------------
Detected 3 errors
") |
[
{
"context": "; Copyright (c) 2014 Kevin Bell. All rights reserved.\n; See the file license.tx",
"end": 33,
"score": 0.9997622966766357,
"start": 23,
"tag": "NAME",
"value": "Kevin Bell"
},
{
"context": "g permission.\n\n(ns dacom.db\n \"https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/io",
"end": 152,
"score": 0.9980910420417786,
"start": 145,
"tag": "USERNAME",
"value": "Datomic"
},
{
"context": "tomic/samples/io.clj\n and\n https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/sc",
"end": 243,
"score": 0.9983745813369751,
"start": 236,
"tag": "USERNAME",
"value": "Datomic"
}
] | utils/src/dacom/db.clj | bellkev/dacom | 27 | ; Copyright (c) 2014 Kevin Bell. All rights reserved.
; See the file license.txt for copying permission.
(ns dacom.db
"https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/io.clj
and
https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/schema.clj"
(:require [datomic.api :as d :refer [db q]]
[clojure.java.io :as io]
[dacom.config :refer [read-config]])
(:import datomic.Util))
;===============================================================================
; io utils
;===============================================================================
(defn read-all
"Read all forms in f, where f is any resource that can
be opened by io/reader"
[f]
(Util/readAll (io/reader f)))
(defn transact-all
"Load and run all transactions from f, where f is any
resource that can be opened by io/reader."
[conn f]
(doseq [txd (read-all f)]
(d/transact conn txd))
:done)
;===============================================================================
; schema utils
;===============================================================================
(defn cardinality
"Returns the cardinality (:db.cardinality/one or
:db.cardinality/many) of the attribute"
[db attr]
(->>
(d/q '[:find ?v
:in $ ?attr
:where
[?attr :db/cardinality ?card]
[?card :db/ident ?v]]
db attr)
ffirst))
(defn has-attribute?
"Does database have an attribute named attr-name?"
[db attr-name]
(-> (d/entity db attr-name)
:db.install/_attribute
boolean))
(defn has-schema?
"Does database have a schema named schema-name installed?
Uses schema-attr (an attribute of transactions!) to track
which schema names are installed."
[db schema-attr schema-name]
(and (has-attribute? db schema-attr)
(-> (d/q '[:find ?e
:in $ ?sa ?sn
:where [?e ?sa ?sn]]
db schema-attr schema-name)
seq boolean)))
(defn- ensure-schema-attribute
"Ensure that schema-attr, a keyword-valued attribute used
as a value on transactions to track named schemas, is
installed in database."
[conn schema-attr]
(when-not (has-attribute? (d/db conn) schema-attr)
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident schema-attr
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/doc "Name of schema installed by this transaction"
:db/index true
:db.install/_attribute :db.part/db}])))
(defn ensure-schemas
"Ensure that schemas are installed.
schema-attr a keyword valued attribute of a transaction,
naming the schema
schema-map a map from schema names to schema installation
maps. A schema installation map contains two
keys: :txes is the data to install, and :requires
is a list of other schema names that must also
be installed
schema-names the names of schemas to install"
[conn schema-attr schema-map & schema-names]
(ensure-schema-attribute conn schema-attr)
(doseq [schema-name schema-names]
(if (has-schema? (d/db conn) schema-attr schema-name)
(println "Schema" schema-name "already installed")
(let [{:keys [requires txes]} (get schema-map schema-name)]
(println "Installing schema" schema-name "...")
(apply ensure-schemas conn schema-attr schema-map requires)
(if txes
(doseq [tx txes]
;; hrm, could mark the last tx specially
(d/transact conn (cons {:db/id #db/id [:db.part/tx]
schema-attr schema-name}
tx)))
(throw (ex-info (str "No data provided for schema" schema-name)
{:schema/missing schema-name})))))))
;===============================================================================
; install schema and sample data
;===============================================================================
(def db-uri (:datomic-uri (read-config)))
(d/create-database db-uri)
(def conn
(d/connect db-uri))
(def schema-map (first (read-all "db-resources/schema.edn")))
(defn install-schema []
(ensure-schemas conn :dacom/all-tx-tag schema-map :dacom/all))
(defn install-message []
(let [result (q '[:find ?e :where [?e :demo/message]] (db conn))]
(if (ffirst result)
(println "Demo message already installed")
(do
(println "Installing demo message...")
(d/transact conn [{:db/id (d/tempid :db.part/user)
:demo/message "Hello, from Datomic"}])))))
(defn -main [& args]
(install-schema)
(install-message)
(System/exit 0)) | 100974 | ; Copyright (c) 2014 <NAME>. All rights reserved.
; See the file license.txt for copying permission.
(ns dacom.db
"https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/io.clj
and
https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/schema.clj"
(:require [datomic.api :as d :refer [db q]]
[clojure.java.io :as io]
[dacom.config :refer [read-config]])
(:import datomic.Util))
;===============================================================================
; io utils
;===============================================================================
(defn read-all
"Read all forms in f, where f is any resource that can
be opened by io/reader"
[f]
(Util/readAll (io/reader f)))
(defn transact-all
"Load and run all transactions from f, where f is any
resource that can be opened by io/reader."
[conn f]
(doseq [txd (read-all f)]
(d/transact conn txd))
:done)
;===============================================================================
; schema utils
;===============================================================================
(defn cardinality
"Returns the cardinality (:db.cardinality/one or
:db.cardinality/many) of the attribute"
[db attr]
(->>
(d/q '[:find ?v
:in $ ?attr
:where
[?attr :db/cardinality ?card]
[?card :db/ident ?v]]
db attr)
ffirst))
(defn has-attribute?
"Does database have an attribute named attr-name?"
[db attr-name]
(-> (d/entity db attr-name)
:db.install/_attribute
boolean))
(defn has-schema?
"Does database have a schema named schema-name installed?
Uses schema-attr (an attribute of transactions!) to track
which schema names are installed."
[db schema-attr schema-name]
(and (has-attribute? db schema-attr)
(-> (d/q '[:find ?e
:in $ ?sa ?sn
:where [?e ?sa ?sn]]
db schema-attr schema-name)
seq boolean)))
(defn- ensure-schema-attribute
"Ensure that schema-attr, a keyword-valued attribute used
as a value on transactions to track named schemas, is
installed in database."
[conn schema-attr]
(when-not (has-attribute? (d/db conn) schema-attr)
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident schema-attr
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/doc "Name of schema installed by this transaction"
:db/index true
:db.install/_attribute :db.part/db}])))
(defn ensure-schemas
"Ensure that schemas are installed.
schema-attr a keyword valued attribute of a transaction,
naming the schema
schema-map a map from schema names to schema installation
maps. A schema installation map contains two
keys: :txes is the data to install, and :requires
is a list of other schema names that must also
be installed
schema-names the names of schemas to install"
[conn schema-attr schema-map & schema-names]
(ensure-schema-attribute conn schema-attr)
(doseq [schema-name schema-names]
(if (has-schema? (d/db conn) schema-attr schema-name)
(println "Schema" schema-name "already installed")
(let [{:keys [requires txes]} (get schema-map schema-name)]
(println "Installing schema" schema-name "...")
(apply ensure-schemas conn schema-attr schema-map requires)
(if txes
(doseq [tx txes]
;; hrm, could mark the last tx specially
(d/transact conn (cons {:db/id #db/id [:db.part/tx]
schema-attr schema-name}
tx)))
(throw (ex-info (str "No data provided for schema" schema-name)
{:schema/missing schema-name})))))))
;===============================================================================
; install schema and sample data
;===============================================================================
(def db-uri (:datomic-uri (read-config)))
(d/create-database db-uri)
(def conn
(d/connect db-uri))
(def schema-map (first (read-all "db-resources/schema.edn")))
(defn install-schema []
(ensure-schemas conn :dacom/all-tx-tag schema-map :dacom/all))
(defn install-message []
(let [result (q '[:find ?e :where [?e :demo/message]] (db conn))]
(if (ffirst result)
(println "Demo message already installed")
(do
(println "Installing demo message...")
(d/transact conn [{:db/id (d/tempid :db.part/user)
:demo/message "Hello, from Datomic"}])))))
(defn -main [& args]
(install-schema)
(install-message)
(System/exit 0)) | true | ; Copyright (c) 2014 PI:NAME:<NAME>END_PI. All rights reserved.
; See the file license.txt for copying permission.
(ns dacom.db
"https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/io.clj
and
https://github.com/Datomic/day-of-datomic/blob/master/src/datomic/samples/schema.clj"
(:require [datomic.api :as d :refer [db q]]
[clojure.java.io :as io]
[dacom.config :refer [read-config]])
(:import datomic.Util))
;===============================================================================
; io utils
;===============================================================================
(defn read-all
"Read all forms in f, where f is any resource that can
be opened by io/reader"
[f]
(Util/readAll (io/reader f)))
(defn transact-all
"Load and run all transactions from f, where f is any
resource that can be opened by io/reader."
[conn f]
(doseq [txd (read-all f)]
(d/transact conn txd))
:done)
;===============================================================================
; schema utils
;===============================================================================
(defn cardinality
"Returns the cardinality (:db.cardinality/one or
:db.cardinality/many) of the attribute"
[db attr]
(->>
(d/q '[:find ?v
:in $ ?attr
:where
[?attr :db/cardinality ?card]
[?card :db/ident ?v]]
db attr)
ffirst))
(defn has-attribute?
"Does database have an attribute named attr-name?"
[db attr-name]
(-> (d/entity db attr-name)
:db.install/_attribute
boolean))
(defn has-schema?
"Does database have a schema named schema-name installed?
Uses schema-attr (an attribute of transactions!) to track
which schema names are installed."
[db schema-attr schema-name]
(and (has-attribute? db schema-attr)
(-> (d/q '[:find ?e
:in $ ?sa ?sn
:where [?e ?sa ?sn]]
db schema-attr schema-name)
seq boolean)))
(defn- ensure-schema-attribute
"Ensure that schema-attr, a keyword-valued attribute used
as a value on transactions to track named schemas, is
installed in database."
[conn schema-attr]
(when-not (has-attribute? (d/db conn) schema-attr)
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident schema-attr
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/doc "Name of schema installed by this transaction"
:db/index true
:db.install/_attribute :db.part/db}])))
(defn ensure-schemas
"Ensure that schemas are installed.
schema-attr a keyword valued attribute of a transaction,
naming the schema
schema-map a map from schema names to schema installation
maps. A schema installation map contains two
keys: :txes is the data to install, and :requires
is a list of other schema names that must also
be installed
schema-names the names of schemas to install"
[conn schema-attr schema-map & schema-names]
(ensure-schema-attribute conn schema-attr)
(doseq [schema-name schema-names]
(if (has-schema? (d/db conn) schema-attr schema-name)
(println "Schema" schema-name "already installed")
(let [{:keys [requires txes]} (get schema-map schema-name)]
(println "Installing schema" schema-name "...")
(apply ensure-schemas conn schema-attr schema-map requires)
(if txes
(doseq [tx txes]
;; hrm, could mark the last tx specially
(d/transact conn (cons {:db/id #db/id [:db.part/tx]
schema-attr schema-name}
tx)))
(throw (ex-info (str "No data provided for schema" schema-name)
{:schema/missing schema-name})))))))
;===============================================================================
; install schema and sample data
;===============================================================================
(def db-uri (:datomic-uri (read-config)))
(d/create-database db-uri)
(def conn
(d/connect db-uri))
(def schema-map (first (read-all "db-resources/schema.edn")))
(defn install-schema []
(ensure-schemas conn :dacom/all-tx-tag schema-map :dacom/all))
(defn install-message []
(let [result (q '[:find ?e :where [?e :demo/message]] (db conn))]
(if (ffirst result)
(println "Demo message already installed")
(do
(println "Installing demo message...")
(d/transact conn [{:db/id (d/tempid :db.part/user)
:demo/message "Hello, from Datomic"}])))))
(defn -main [& args]
(install-schema)
(install-message)
(System/exit 0)) |
[
{
"context": "reasoning functionality.\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------",
"end": 392,
"score": 0.9998799562454224,
"start": 380,
"tag": "NAME",
"value": "Dennis Drown"
}
] | apps/say_sila/priv/fnode/say/src/say/infer.clj | dendrown/say_sila | 0 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Ontological reasoning functionality.
;;;;
;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.infer
(:require [say.genie :refer :all]
[tawny.reasoner :as rsn])
(:import (org.semanticweb.owlapi.model OWLOntology)
(org.semanticweb.owlapi.reasoner OWLReasoner)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn silence
"Returns an Atom whose value is a silent reasoner progress monitor."
[]
(atom rsn/reasoner-progress-monitor-silent))
;;; --------------------------------------------------------------------------
(defmacro with-silence
"Performs the reasoning operation in the body using a silent reasoner
progress monitor."
[& body]
`(binding [rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defmacro with-ns-silence
"Performs the reasoning operation in the body within the specified namespace
and using a silent reasoner progress monitor."
[nspace & body]
`(binding [*ns* (find-ns ~nspace)
rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defn unreason
"Detaches a reasoner from the specified ontology and destroys it (allowing
precious memory resources to become available once again."
([ont]
(unreason ont (rsn/reasoner-for-ontology ont)))
([^OWLOntology ont
^OWLReasoner rsnr]
;; Make sure HermiT doesn't hoard memory. Tawny-OWL (as of version 2.0.3) is
;; not calling dispose on the HermiT reasoner due to crashiness they've seen.
(when rsnr
(.dispose rsnr)
(rsn/discard-reasoner ont))))
| 113442 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Ontological reasoning functionality.
;;;;
;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.infer
(:require [say.genie :refer :all]
[tawny.reasoner :as rsn])
(:import (org.semanticweb.owlapi.model OWLOntology)
(org.semanticweb.owlapi.reasoner OWLReasoner)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn silence
"Returns an Atom whose value is a silent reasoner progress monitor."
[]
(atom rsn/reasoner-progress-monitor-silent))
;;; --------------------------------------------------------------------------
(defmacro with-silence
"Performs the reasoning operation in the body using a silent reasoner
progress monitor."
[& body]
`(binding [rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defmacro with-ns-silence
"Performs the reasoning operation in the body within the specified namespace
and using a silent reasoner progress monitor."
[nspace & body]
`(binding [*ns* (find-ns ~nspace)
rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defn unreason
"Detaches a reasoner from the specified ontology and destroys it (allowing
precious memory resources to become available once again."
([ont]
(unreason ont (rsn/reasoner-for-ontology ont)))
([^OWLOntology ont
^OWLReasoner rsnr]
;; Make sure HermiT doesn't hoard memory. Tawny-OWL (as of version 2.0.3) is
;; not calling dispose on the HermiT reasoner due to crashiness they've seen.
(when rsnr
(.dispose rsnr)
(rsn/discard-reasoner ont))))
| true | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Ontological reasoning functionality.
;;;;
;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.infer
(:require [say.genie :refer :all]
[tawny.reasoner :as rsn])
(:import (org.semanticweb.owlapi.model OWLOntology)
(org.semanticweb.owlapi.reasoner OWLReasoner)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; --------------------------------------------------------------------------
(defn silence
"Returns an Atom whose value is a silent reasoner progress monitor."
[]
(atom rsn/reasoner-progress-monitor-silent))
;;; --------------------------------------------------------------------------
(defmacro with-silence
"Performs the reasoning operation in the body using a silent reasoner
progress monitor."
[& body]
`(binding [rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defmacro with-ns-silence
"Performs the reasoning operation in the body within the specified namespace
and using a silent reasoner progress monitor."
[nspace & body]
`(binding [*ns* (find-ns ~nspace)
rsn/*reasoner-progress-monitor* (silence)]
~@body))
;;; --------------------------------------------------------------------------
(defn unreason
"Detaches a reasoner from the specified ontology and destroys it (allowing
precious memory resources to become available once again."
([ont]
(unreason ont (rsn/reasoner-for-ontology ont)))
([^OWLOntology ont
^OWLReasoner rsnr]
;; Make sure HermiT doesn't hoard memory. Tawny-OWL (as of version 2.0.3) is
;; not calling dispose on the HermiT reasoner due to crashiness they've seen.
(when rsnr
(.dispose rsnr)
(rsn/discard-reasoner ont))))
|
[
{
"context": "))\n\n(defn -main [& args]\n (println (salutations \"John\")))\n",
"end": 173,
"score": 0.9941710829734802,
"start": 169,
"tag": "NAME",
"value": "John"
}
] | 8. Clojure/src/hello/core.clj | skilbjo/lisp | 0 | (ns hello.core
(:require [clojure.java.io :as io])
(:gen-class))
(defn salutations [name]
(str "Greetings " name))
(defn -main [& args]
(println (salutations "John")))
| 10288 | (ns hello.core
(:require [clojure.java.io :as io])
(:gen-class))
(defn salutations [name]
(str "Greetings " name))
(defn -main [& args]
(println (salutations "<NAME>")))
| true | (ns hello.core
(:require [clojure.java.io :as io])
(:gen-class))
(defn salutations [name]
(str "Greetings " name))
(defn -main [& args]
(println (salutations "PI:NAME:<NAME>END_PI")))
|
[
{
"context": "; Copyright (c) 2014 Kevin Bell. All rights reserved.\n; See the file license.tx",
"end": 33,
"score": 0.9997546076774597,
"start": 23,
"tag": "NAME",
"value": "Kevin Bell"
},
{
"context": "compojure, and om\"\n :url \"https://github.com/bellkev/dacom\"\n :dependencies [[org.clojure/clojure \"1.5",
"end": 249,
"score": 0.8138934373855591,
"start": 246,
"tag": "USERNAME",
"value": "kev"
},
{
"context": "is needs to be here because of https://github.com/cemerick/austin/issues/23\n :plugins [[c",
"end": 2035,
"score": 0.9996551871299744,
"start": 2027,
"tag": "USERNAME",
"value": "cemerick"
}
] | project.clj | bellkev/dacom | 27 | ; Copyright (c) 2014 Kevin Bell. All rights reserved.
; See the file license.txt for copying permission.
(defproject dacom "0.1.3-SNAPSHOT"
:description "A skeleton app built with datomic, compojure, and om"
:url "https://github.com/bellkev/dacom"
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/clojurescript "0.0-2138"]
[ring "1.2.1"]
[ring-cors "0.1.0"]
[ring-middleware-format "0.3.1"]
[compojure "1.1.6"]
[cljs-ajax "0.2.3"]
[org.clojure/core.async "0.1.267.0-0d7780-alpha"]
[om "0.1.4"]
[sablono "0.1.5"]
[com.datomic/datomic-free "0.9.4384"]]
:plugins [[lein-cljsbuild "1.0.1-SNAPSHOT"]
[lein-ring "0.8.8"]
[lein-resource "0.3.1"]
[lein-httpd "1.0.0"]
[lein-shell "0.3.0"]
[fsrun "0.1.2"]]
:source-paths ["src"]
:target-path "target/"
:uberjar-exclusions [#".*\.cljs"]
:cljsbuild {:builds {:dev {:source-paths ["utils/src" "src"]
:compiler {:output-to "static/js/main.js"
:output-dir "static/js"
:optimizations :none
:pretty-print true
:source-map true}}
:prod {:source-paths ["src"]
:compiler {:output-to "dist/static/js/main.js"
:optimizations :advanced
:pretty-print false
;; From Om jar
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"]}}}}
:ring {:init dacom.server/init-conn
:handler dacom.server/app}
:profiles {:dev {;; This needs to be here because of https://github.com/cemerick/austin/issues/23
:plugins [[com.cemerick/austin "0.1.4-SNAPSHOT"]]
:source-paths ["utils/src"]
:repl-options {:init-ns dacom.repl}
:resource {:resource-paths ["web-resources/pages"]
:target-path "static"
:extra-values {:scripts [{:src "../bower_components/react/react.js"}
{:src "js/goog/base.js"}
{:src "js/main.js"}
{:body "goog.require('dacom.client')"}
{:body "goog.require('dacom.repl')"}]}}}
:db [:dev {:main dacom.db}]
:prod {:main dacom.server
:target-path "dist/server/"
:resource {:resource-paths ["web-resources/pages"]
:target-path "dist/static"
:extra-values {:scripts [{:src "js/main.js"}]}}}
:uberjar {:omit-source true
:aot :all}}
:aliases {"bower" ["shell" "bower" "install"]
"less-debug" ["shell" "lessc" "web-resources/stylesheets/style.less" "static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--source-map"]
"less-prod" ["shell" "lessc" "web-resources/stylesheets/style.less" "dist/static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--compress"]
"watch-less" ["fschange" "web-resources/stylesheets/*" "less-debug"]
"install-db" ["with-profile" "db" "run"]
"run-client" ["do" "bower," "cljsbuild" "once" "dev," "less-debug," "resource," "httpd" "8000"]
"run-server" ["ring" "server-headless"]
"dist" ["with-profile" "prod" "do" "bower," "uberjar," "cljsbuild" "once" "prod," "less-prod,"
"resource"]}
:clean-targets [:target-path :compile-path "static" "dist"])
| 35620 | ; Copyright (c) 2014 <NAME>. All rights reserved.
; See the file license.txt for copying permission.
(defproject dacom "0.1.3-SNAPSHOT"
:description "A skeleton app built with datomic, compojure, and om"
:url "https://github.com/bellkev/dacom"
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/clojurescript "0.0-2138"]
[ring "1.2.1"]
[ring-cors "0.1.0"]
[ring-middleware-format "0.3.1"]
[compojure "1.1.6"]
[cljs-ajax "0.2.3"]
[org.clojure/core.async "0.1.267.0-0d7780-alpha"]
[om "0.1.4"]
[sablono "0.1.5"]
[com.datomic/datomic-free "0.9.4384"]]
:plugins [[lein-cljsbuild "1.0.1-SNAPSHOT"]
[lein-ring "0.8.8"]
[lein-resource "0.3.1"]
[lein-httpd "1.0.0"]
[lein-shell "0.3.0"]
[fsrun "0.1.2"]]
:source-paths ["src"]
:target-path "target/"
:uberjar-exclusions [#".*\.cljs"]
:cljsbuild {:builds {:dev {:source-paths ["utils/src" "src"]
:compiler {:output-to "static/js/main.js"
:output-dir "static/js"
:optimizations :none
:pretty-print true
:source-map true}}
:prod {:source-paths ["src"]
:compiler {:output-to "dist/static/js/main.js"
:optimizations :advanced
:pretty-print false
;; From Om jar
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"]}}}}
:ring {:init dacom.server/init-conn
:handler dacom.server/app}
:profiles {:dev {;; This needs to be here because of https://github.com/cemerick/austin/issues/23
:plugins [[com.cemerick/austin "0.1.4-SNAPSHOT"]]
:source-paths ["utils/src"]
:repl-options {:init-ns dacom.repl}
:resource {:resource-paths ["web-resources/pages"]
:target-path "static"
:extra-values {:scripts [{:src "../bower_components/react/react.js"}
{:src "js/goog/base.js"}
{:src "js/main.js"}
{:body "goog.require('dacom.client')"}
{:body "goog.require('dacom.repl')"}]}}}
:db [:dev {:main dacom.db}]
:prod {:main dacom.server
:target-path "dist/server/"
:resource {:resource-paths ["web-resources/pages"]
:target-path "dist/static"
:extra-values {:scripts [{:src "js/main.js"}]}}}
:uberjar {:omit-source true
:aot :all}}
:aliases {"bower" ["shell" "bower" "install"]
"less-debug" ["shell" "lessc" "web-resources/stylesheets/style.less" "static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--source-map"]
"less-prod" ["shell" "lessc" "web-resources/stylesheets/style.less" "dist/static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--compress"]
"watch-less" ["fschange" "web-resources/stylesheets/*" "less-debug"]
"install-db" ["with-profile" "db" "run"]
"run-client" ["do" "bower," "cljsbuild" "once" "dev," "less-debug," "resource," "httpd" "8000"]
"run-server" ["ring" "server-headless"]
"dist" ["with-profile" "prod" "do" "bower," "uberjar," "cljsbuild" "once" "prod," "less-prod,"
"resource"]}
:clean-targets [:target-path :compile-path "static" "dist"])
| true | ; Copyright (c) 2014 PI:NAME:<NAME>END_PI. All rights reserved.
; See the file license.txt for copying permission.
(defproject dacom "0.1.3-SNAPSHOT"
:description "A skeleton app built with datomic, compojure, and om"
:url "https://github.com/bellkev/dacom"
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/clojurescript "0.0-2138"]
[ring "1.2.1"]
[ring-cors "0.1.0"]
[ring-middleware-format "0.3.1"]
[compojure "1.1.6"]
[cljs-ajax "0.2.3"]
[org.clojure/core.async "0.1.267.0-0d7780-alpha"]
[om "0.1.4"]
[sablono "0.1.5"]
[com.datomic/datomic-free "0.9.4384"]]
:plugins [[lein-cljsbuild "1.0.1-SNAPSHOT"]
[lein-ring "0.8.8"]
[lein-resource "0.3.1"]
[lein-httpd "1.0.0"]
[lein-shell "0.3.0"]
[fsrun "0.1.2"]]
:source-paths ["src"]
:target-path "target/"
:uberjar-exclusions [#".*\.cljs"]
:cljsbuild {:builds {:dev {:source-paths ["utils/src" "src"]
:compiler {:output-to "static/js/main.js"
:output-dir "static/js"
:optimizations :none
:pretty-print true
:source-map true}}
:prod {:source-paths ["src"]
:compiler {:output-to "dist/static/js/main.js"
:optimizations :advanced
:pretty-print false
;; From Om jar
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"]}}}}
:ring {:init dacom.server/init-conn
:handler dacom.server/app}
:profiles {:dev {;; This needs to be here because of https://github.com/cemerick/austin/issues/23
:plugins [[com.cemerick/austin "0.1.4-SNAPSHOT"]]
:source-paths ["utils/src"]
:repl-options {:init-ns dacom.repl}
:resource {:resource-paths ["web-resources/pages"]
:target-path "static"
:extra-values {:scripts [{:src "../bower_components/react/react.js"}
{:src "js/goog/base.js"}
{:src "js/main.js"}
{:body "goog.require('dacom.client')"}
{:body "goog.require('dacom.repl')"}]}}}
:db [:dev {:main dacom.db}]
:prod {:main dacom.server
:target-path "dist/server/"
:resource {:resource-paths ["web-resources/pages"]
:target-path "dist/static"
:extra-values {:scripts [{:src "js/main.js"}]}}}
:uberjar {:omit-source true
:aot :all}}
:aliases {"bower" ["shell" "bower" "install"]
"less-debug" ["shell" "lessc" "web-resources/stylesheets/style.less" "static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--source-map"]
"less-prod" ["shell" "lessc" "web-resources/stylesheets/style.less" "dist/static/css/style.css"
"--include-path=bower_components/bootstrap/less/" "--compress"]
"watch-less" ["fschange" "web-resources/stylesheets/*" "less-debug"]
"install-db" ["with-profile" "db" "run"]
"run-client" ["do" "bower," "cljsbuild" "once" "dev," "less-debug," "resource," "httpd" "8000"]
"run-server" ["ring" "server-headless"]
"dist" ["with-profile" "prod" "do" "bower," "uberjar," "cljsbuild" "once" "prod," "less-prod,"
"resource"]}
:clean-targets [:target-path :compile-path "static" "dist"])
|
[
{
"context": ".)\n content-ivan {:crux.db/id :ivan :name \"Ivan\"}\n content-hash (str (c/new-id content-iva",
"end": 750,
"score": 0.9211124777793884,
"start": 746,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.db/id {:user \"Xwop1A7Xog4nD6AfhZaPgg\"} :name \"Adam\"}\n submitted-tx (.submitTx f/*api* [[:crux",
"end": 1107,
"score": 0.9997009634971619,
"start": 1103,
"tag": "NAME",
"value": "Adam"
},
{
"context": ".)\n content-ivan {:crux.db/id :ivan :name \"Ivan\"}]\n\n (t/testing \"put works with no id\"\n (",
"end": 1404,
"score": 0.9278414249420166,
"start": 1400,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"} valid-time]])]\n (t/is (true? (.hasSubmitte",
"end": 2543,
"score": 0.9985566139221191,
"start": 2539,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :else\n (let [tx-topic-key (keyword \"crux.kafka.topic-partition\"\n (str (get-",
"end": 3185,
"score": 0.986414909362793,
"start": 3159,
"tag": "KEY",
"value": "crux.kafka.topic-partition"
},
{
"context": " (get-in f/*cluster-node* [:options :tx-topic]) \"-0\"))\n doc-topic-key (keyword \"crux.k",
"end": 3280,
"score": 0.8301794528961182,
"start": 3279,
"tag": "KEY",
"value": "0"
},
{
"context": "]) \"-0\"))\n doc-topic-key (keyword \"crux.kafka.topic-partition\"\n (str (get",
"end": 3350,
"score": 0.984828770160675,
"start": 3324,
"tag": "KEY",
"value": "crux.kafka.topic-partition"
},
{
"context": "(get-in f/*cluster-node* [:options :doc-topic]) \"-0\"))]\n (t/is (= {:lag 0\n ",
"end": 3447,
"score": 0.8022346496582031,
"start": 3446,
"tag": "KEY",
"value": "0"
},
{
"context": " :where [[e :name \"Ivan\"]]})))\n (t/is (= #{} (.q (.db f/*api* #ins",
"end": 4040,
"score": 0.9976897239685059,
"start": 4036,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where [[e :name \"Ivan\"]]})))\n\n (t/testing \"query string\"\n ",
"end": 4188,
"score": 0.9979722499847412,
"start": 4184,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " \"{:find [e] :where [[e :name \\\"Ivan\\\"]]}\"))))\n\n (t/testing \"query vector\"\n ",
"end": 4348,
"score": 0.9970894455909729,
"start": 4344,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where [e :name \"Ivan\"]]))))\n\n (t/testing \"malformed query\"\n ",
"end": 4523,
"score": 0.9978828430175781,
"start": 4519,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where [[e :name \"Ivan\"]]})]\n (t/is (instance? LazySeq re",
"end": 5012,
"score": 0.9996562004089355,
"start": 5008,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where [[e :name \"Ivan\"]]\n :",
"end": 5467,
"score": 0.9995712041854858,
"start": 5463,
"tag": "NAME",
"value": "Ivan"
},
{
"context": ":ivan, :crux.query/doc {:crux.db/id :ivan, :name \"Ivan\"}}]) result))\n (t/is (realized? re",
"end": 5757,
"score": 0.9993751049041748,
"start": 5753,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "RE { ?e <http://juxt.pro/crux/unqualified/name> \\\"Ivan\\\" }\"))))\n (finally\n ",
"end": 6201,
"score": 0.9985396862030029,
"start": 6197,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ntity\"\n (t/is (= {:crux.db/id :ivan :name \"Ivan\"} (.entity (.db f/*api*) :ivan)))\n (t/is (",
"end": 6351,
"score": 0.9994922876358032,
"start": 6347,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ent-hash (str (c/new-id {:crux.db/id :ivan :name \"Ivan\"}))\n :crux.db/valid-tim",
"end": 6756,
"score": 0.9996718168258667,
"start": 6752,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "tx))\n (t/is (= {:crux.db/id :ivan :name \"Ivan\"} (.document f/*api* (:crux.db/content-hash entit",
"end": 6901,
"score": 0.9997075796127319,
"start": 6897,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "new-id :ivan) (c/new-id {:crux.db/id :ivan :name \"Ivan\"}) valid-time]])]\n result))\n ",
"end": 7698,
"score": 0.9995981454849243,
"start": 7694,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "tx/put (c/new-id :ivan) {:crux.db/id :ivan :name \"Ivan\"} valid-time]])]\n result))\n",
"end": 8182,
"score": 0.9996089935302734,
"start": 8178,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 1}]])]\n (t/is (true? (.hasSubmittedT",
"end": 10169,
"score": 0.9978290796279907,
"start": 10165,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 2}]])]\n (t/is (true? (.hasSubmittedT",
"end": 10371,
"score": 0.9972960948944092,
"start": 10367,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "istory)))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2}\n {:crux.db/id :ivan :na",
"end": 10597,
"score": 0.9976993203163147,
"start": 10593,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ersion 2}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (for [content-hash (ma",
"end": 10655,
"score": 0.9980934262275696,
"start": 10651,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 1} #inst \"2019-02-01\"]])) nil)\n ",
"end": 10957,
"score": 0.9953873157501221,
"start": 10953,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 2} #inst \"2019-02-02\"]])) nil)\n ",
"end": 11132,
"score": 0.997899055480957,
"start": 11128,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 3} #inst \"2019-02-03\"]])) nil)\n ",
"end": 11307,
"score": 0.9964547753334045,
"start": 11303,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " f/*api* [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true} #inst \"2019-02-02\"]]",
"end": 11492,
"score": 0.9992698431015015,
"start": 11488,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " db)]\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 3}]\n (map :crux.db/doc ",
"end": 11774,
"score": 0.9991796016693115,
"start": 11770,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n))))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 3}\n {:crux.db/id :ivan",
"end": 11913,
"score": 0.9991515874862671,
"start": 11909,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "on 3}\n {:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true}\n {:",
"end": 11975,
"score": 0.999208927154541,
"start": 11971,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "true}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (map :crux.db/doc ",
"end": 12053,
"score": 0.9991823434829712,
"start": 12049,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " db)]\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true}\n {:",
"end": 12289,
"score": 0.9989163279533386,
"start": 12285,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "true}\n {:crux.db/id :ivan :name \"Ivan\" :version 3}]\n (map :crux.db/doc ",
"end": 12367,
"score": 0.999122142791748,
"start": 12363,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n))))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true}\n {:",
"end": 12506,
"score": 0.998904824256897,
"start": 12502,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "true}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (map :crux.db/doc ",
"end": 12584,
"score": 0.9992854595184326,
"start": 12580,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " db)]\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 1}\n {:crux.db/id :ivan",
"end": 12820,
"score": 0.9991769790649414,
"start": 12816,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "on 1}\n {:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true}\n {:",
"end": 12882,
"score": 0.99903404712677,
"start": 12878,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "true}\n {:crux.db/id :ivan :name \"Ivan\" :version 3}]\n (map :crux.db/doc ",
"end": 12960,
"score": 0.9989615678787231,
"start": 12956,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n))))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 3}\n {:crux.db/id :ivan",
"end": 13358,
"score": 0.9988150000572205,
"start": 13354,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "on 3}\n {:crux.db/id :ivan :name \"Ivan\" :version 2 :corrected true}\n {:",
"end": 13420,
"score": 0.9987890720367432,
"start": 13416,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "true}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (map :crux.db/doc ",
"end": 13498,
"score": 0.9984991550445557,
"start": 13494,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " db)]\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2}]\n (map :crux.db/doc ",
"end": 14040,
"score": 0.9981086254119873,
"start": 14036,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n))))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2}\n {:crux.db/id :ivan",
"end": 14179,
"score": 0.9981666803359985,
"start": 14175,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "on 2}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (map :crux.db/doc ",
"end": 14241,
"score": 0.9976755976676941,
"start": 14237,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n))))\n (t/is (= [{:crux.db/id :ivan :name \"Ivan\" :version 2}\n {:crux.db/id :ivan",
"end": 14586,
"score": 0.9993492960929871,
"start": 14582,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "on 2}\n {:crux.db/id :ivan :name \"Ivan\" :version 1}]\n (map :crux.db/doc ",
"end": 14648,
"score": 0.9995999336242676,
"start": 14644,
"tag": "NAME",
"value": "Ivan"
}
] | test/crux/api_test.clj | souenzzo/crux | 0 | (ns crux.api-test
(:require [clojure.test :as t]
[crux.bootstrap.standalone]
[crux.codec :as c]
[crux.fixtures :as f]
[crux.rdf :as rdf])
(:import clojure.lang.LazySeq
java.util.Date
java.time.Duration
crux.bootstrap.standalone.StandaloneSystem
org.eclipse.rdf4j.repository.sparql.SPARQLRepository
org.eclipse.rdf4j.repository.RepositoryConnection
org.eclipse.rdf4j.query.Binding))
(t/use-fixtures :once f/with-embedded-kafka-cluster)
(t/use-fixtures :each f/with-each-api-implementation)
(declare execute-sparql)
(t/deftest test-content-hash-invalid
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "Ivan"}
content-hash (str (c/new-id content-ivan))]
(t/is (thrown-with-msg? Exception (re-pattern (str content-hash "|HTTP status 400"))
(.submitTx f/*api* [[:crux.tx/put content-hash valid-time]])))))
(t/deftest test-can-write-entity-using-map-as-id
(let [doc {:crux.db/id {:user "Xwop1A7Xog4nD6AfhZaPgg"} :name "Adam"}
submitted-tx (.submitTx f/*api* [[:crux.tx/put doc]])]
(.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)
(t/is (.entity (.db f/*api*) {:user "Xwop1A7Xog4nD6AfhZaPgg"}))))
(t/deftest test-single-id
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "Ivan"}]
(t/testing "put works with no id"
(t/is
(let [submitted-tx (.submitTx f/*api* [[:crux.tx/put content-ivan valid-time]])]
(.db f/*api* valid-time (:crux.tx/tx-time submitted-tx)))))
(t/testing "Delete works with id"
(t/is (.submitTx f/*api* [[:crux.tx/delete :ivan]])))))
(t/deftest test-can-use-api-to-access-crux
(t/testing "status"
(t/is (= {:crux.zk/zk-active? (not (instance? StandaloneSystem f/*api*))
:crux.kv/kv-backend "crux.kv.rocksdb.RocksKv"
:crux.index/index-version 4}
(dissoc (.status f/*api*)
:crux.kv/estimate-num-keys
:crux.tx-log/consumer-state :crux.kv/size
:crux.version/version :crux.version/revision))))
(t/testing "empty db"
(t/is (.db f/*api*)))
(t/testing "syncing empty db"
(t/is (nil? (.sync f/*api* (Duration/ofSeconds 10)))))
(t/testing "transaction"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(let [status-map (.status f/*api*)]
(t/is (pos? (:crux.kv/estimate-num-keys status-map)))
(cond
(and (instance? StandaloneSystem f/*api*)
(instance? crux.tx.EventTxLog (:tx-log f/*api*)))
(t/is (= {:crux.tx/event-log {:lag 0 :next-offset (inc tx-id) :time tx-time}}
(:crux.tx-log/consumer-state status-map)))
:else
(let [tx-topic-key (keyword "crux.kafka.topic-partition"
(str (get-in f/*cluster-node* [:options :tx-topic]) "-0"))
doc-topic-key (keyword "crux.kafka.topic-partition"
(str (get-in f/*cluster-node* [:options :doc-topic]) "-0"))]
(t/is (= {:lag 0
:next-offset 1
:time tx-time}
(get-in status-map [:crux.tx-log/consumer-state tx-topic-key])))
(t/is (= {:lag 0
:next-offset 1}
(-> status-map
(get-in [:crux.tx-log/consumer-state doc-topic-key])
(dissoc :time)))))))
(t/testing "query"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
'{:find [e]
:where [[e :name "Ivan"]]})))
(t/is (= #{} (.q (.db f/*api* #inst "1999") '{:find [e]
:where [[e :name "Ivan"]]})))
(t/testing "query string"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
"{:find [e] :where [[e :name \"Ivan\"]]}"))))
(t/testing "query vector"
(t/is (= #{[:ivan]} (.q (.db f/*api*) '[:find e
:where [e :name "Ivan"]]))))
(t/testing "malformed query"
(t/is (thrown-with-msg? Exception
#"(status 400|Spec assertion failed)"
(.q (.db f/*api*) '{:find [e]}))))
(t/testing "query with streaming result"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "Ivan"]]})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([:ivan]) result))
(t/is (realized? result))))))
(t/testing "query returning full results"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "Ivan"]]
:full-results? true})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([{:crux.query/var e, :crux.query/value :ivan, :crux.query/doc {:crux.db/id :ivan, :name "Ivan"}}]) result))
(t/is (realized? result))))))
(t/testing "SPARQL query"
(when (bound? #'f/*api-url*)
(let [repo (SPARQLRepository. (str f/*api-url* "/sparql"))]
(try
(.initialize repo)
(with-open [conn (.getConnection repo)]
(t/is (= #{[:ivan]} (execute-sparql conn "SELECT ?e WHERE { ?e <http://juxt.pro/crux/unqualified/name> \"Ivan\" }"))))
(finally
(.shutDown repo)))))))
(t/testing "entity"
(t/is (= {:crux.db/id :ivan :name "Ivan"} (.entity (.db f/*api*) :ivan)))
(t/is (nil? (.entity (.db f/*api* #inst "1999") :ivan))))
(t/testing "entity-tx, document and history"
(let [entity-tx (.entityTx (.db f/*api*) :ivan)]
(t/is (= (merge submitted-tx
{:crux.db/id (str (c/new-id :ivan))
:crux.db/content-hash (str (c/new-id {:crux.db/id :ivan :name "Ivan"}))
:crux.db/valid-time valid-time})
entity-tx))
(t/is (= {:crux.db/id :ivan :name "Ivan"} (.document f/*api* (:crux.db/content-hash entity-tx))))
(t/is (= [entity-tx] (.history f/*api* :ivan)))
(t/is (= [entity-tx] (.historyRange f/*api* :ivan #inst "1990" #inst "1990" (:crux.tx/tx-time submitted-tx) (:crux.tx/tx-time submitted-tx))))
(t/is (nil? (.document f/*api* (c/new-id :does-not-exist))))
(t/is (nil? (.entityTx (.db f/*api* #inst "1999") :ivan)))))
(t/testing "tx-log"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) (c/new-id {:crux.db/id :ivan :name "Ivan"}) valid-time]])]
result))
(t/is (realized? result))))
(t/testing "with documents"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil true)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) {:crux.db/id :ivan :name "Ivan"} valid-time]])]
result))
(t/is (realized? result)))))
(t/testing "from tx id"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx (inc tx-id) false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (empty? result))
(t/is (realized? result))))))
(t/testing "statistics"
(let [stats (.attributeStats f/*api*)]
(t/is (= 1 (:name stats))))
(t/testing "updated"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan2"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(t/is (= tx-time (.sync f/*api* nil))))
(let [stats (.attributeStats f/*api*)]
(t/is (= 2 (:name stats)))))
(t/testing "reflect evicted documents"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/evict :ivan]])]
(t/is (.sync f/*api* tx-time nil))
;; actual removal of the document happends asyncronusly after
;; the transaction has been processed so waiting on the
;; submitted transaction time is not enough
(while (.entity (.db f/*api*) :ivan)
(assert (< (- (.getTime (Date.)) (.getTime valid-time)) 4000))
(Thread/sleep 100))
(let [stats (.attributeStats f/*api*)]
(t/is (= 0 (:name stats))))))))))
(t/deftest test-document-bug-123
(let [version-1-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 1}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-1-submitted-tx :ivan))))
(let [version-2-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 2}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-2-submitted-tx :ivan))))
(let [history (.history f/*api* :ivan)]
(t/is (= 2 (count history)))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(for [content-hash (map :crux.db/content-hash history)]
(.document f/*api* content-hash))))))
(t/deftest test-db-history-api
(let [version-1-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 1} #inst "2019-02-01"]])) nil)
version-2-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 2} #inst "2019-02-02"]])) nil)
version-3-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 3} #inst "2019-02-03"]])) nil)
version-2-corrected-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan" :version 2 :corrected true} #inst "2019-02-02"]])) nil)]
(let [history (.history f/*api* :ivan)]
(t/is (= 4 (count history))))
(let [db (.db f/*api* #inst "2019-02-03")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 3}
{:crux.db/id :ivan :name "Ivan" :version 2 :corrected true}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2 :corrected true}
{:crux.db/id :ivan :name "Ivan" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2 :corrected true}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 1}
{:crux.db/id :ivan :name "Ivan" :version 2 :corrected true}
{:crux.db/id :ivan :name "Ivan" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 3}
{:crux.db/id :ivan :name "Ivan" :version 2 :corrected true}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04" #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-03" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "Ivan" :version 2}
{:crux.db/id :ivan :name "Ivan" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))))
(defn execute-sparql [^RepositoryConnection conn q]
(with-open [tq (.evaluate (.prepareTupleQuery conn q))]
(set ((fn step []
(when (.hasNext tq)
(cons (mapv #(rdf/rdf->clj (.getValue ^Binding %))
(.next tq))
(lazy-seq (step)))))))))
| 257 | (ns crux.api-test
(:require [clojure.test :as t]
[crux.bootstrap.standalone]
[crux.codec :as c]
[crux.fixtures :as f]
[crux.rdf :as rdf])
(:import clojure.lang.LazySeq
java.util.Date
java.time.Duration
crux.bootstrap.standalone.StandaloneSystem
org.eclipse.rdf4j.repository.sparql.SPARQLRepository
org.eclipse.rdf4j.repository.RepositoryConnection
org.eclipse.rdf4j.query.Binding))
(t/use-fixtures :once f/with-embedded-kafka-cluster)
(t/use-fixtures :each f/with-each-api-implementation)
(declare execute-sparql)
(t/deftest test-content-hash-invalid
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "<NAME>"}
content-hash (str (c/new-id content-ivan))]
(t/is (thrown-with-msg? Exception (re-pattern (str content-hash "|HTTP status 400"))
(.submitTx f/*api* [[:crux.tx/put content-hash valid-time]])))))
(t/deftest test-can-write-entity-using-map-as-id
(let [doc {:crux.db/id {:user "Xwop1A7Xog4nD6AfhZaPgg"} :name "<NAME>"}
submitted-tx (.submitTx f/*api* [[:crux.tx/put doc]])]
(.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)
(t/is (.entity (.db f/*api*) {:user "Xwop1A7Xog4nD6AfhZaPgg"}))))
(t/deftest test-single-id
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "<NAME>"}]
(t/testing "put works with no id"
(t/is
(let [submitted-tx (.submitTx f/*api* [[:crux.tx/put content-ivan valid-time]])]
(.db f/*api* valid-time (:crux.tx/tx-time submitted-tx)))))
(t/testing "Delete works with id"
(t/is (.submitTx f/*api* [[:crux.tx/delete :ivan]])))))
(t/deftest test-can-use-api-to-access-crux
(t/testing "status"
(t/is (= {:crux.zk/zk-active? (not (instance? StandaloneSystem f/*api*))
:crux.kv/kv-backend "crux.kv.rocksdb.RocksKv"
:crux.index/index-version 4}
(dissoc (.status f/*api*)
:crux.kv/estimate-num-keys
:crux.tx-log/consumer-state :crux.kv/size
:crux.version/version :crux.version/revision))))
(t/testing "empty db"
(t/is (.db f/*api*)))
(t/testing "syncing empty db"
(t/is (nil? (.sync f/*api* (Duration/ofSeconds 10)))))
(t/testing "transaction"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(let [status-map (.status f/*api*)]
(t/is (pos? (:crux.kv/estimate-num-keys status-map)))
(cond
(and (instance? StandaloneSystem f/*api*)
(instance? crux.tx.EventTxLog (:tx-log f/*api*)))
(t/is (= {:crux.tx/event-log {:lag 0 :next-offset (inc tx-id) :time tx-time}}
(:crux.tx-log/consumer-state status-map)))
:else
(let [tx-topic-key (keyword "<KEY>"
(str (get-in f/*cluster-node* [:options :tx-topic]) "-<KEY>"))
doc-topic-key (keyword "<KEY>"
(str (get-in f/*cluster-node* [:options :doc-topic]) "-<KEY>"))]
(t/is (= {:lag 0
:next-offset 1
:time tx-time}
(get-in status-map [:crux.tx-log/consumer-state tx-topic-key])))
(t/is (= {:lag 0
:next-offset 1}
(-> status-map
(get-in [:crux.tx-log/consumer-state doc-topic-key])
(dissoc :time)))))))
(t/testing "query"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
'{:find [e]
:where [[e :name "<NAME>"]]})))
(t/is (= #{} (.q (.db f/*api* #inst "1999") '{:find [e]
:where [[e :name "<NAME>"]]})))
(t/testing "query string"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
"{:find [e] :where [[e :name \"<NAME>\"]]}"))))
(t/testing "query vector"
(t/is (= #{[:ivan]} (.q (.db f/*api*) '[:find e
:where [e :name "<NAME>"]]))))
(t/testing "malformed query"
(t/is (thrown-with-msg? Exception
#"(status 400|Spec assertion failed)"
(.q (.db f/*api*) '{:find [e]}))))
(t/testing "query with streaming result"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "<NAME>"]]})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([:ivan]) result))
(t/is (realized? result))))))
(t/testing "query returning full results"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "<NAME>"]]
:full-results? true})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([{:crux.query/var e, :crux.query/value :ivan, :crux.query/doc {:crux.db/id :ivan, :name "<NAME>"}}]) result))
(t/is (realized? result))))))
(t/testing "SPARQL query"
(when (bound? #'f/*api-url*)
(let [repo (SPARQLRepository. (str f/*api-url* "/sparql"))]
(try
(.initialize repo)
(with-open [conn (.getConnection repo)]
(t/is (= #{[:ivan]} (execute-sparql conn "SELECT ?e WHERE { ?e <http://juxt.pro/crux/unqualified/name> \"<NAME>\" }"))))
(finally
(.shutDown repo)))))))
(t/testing "entity"
(t/is (= {:crux.db/id :ivan :name "<NAME>"} (.entity (.db f/*api*) :ivan)))
(t/is (nil? (.entity (.db f/*api* #inst "1999") :ivan))))
(t/testing "entity-tx, document and history"
(let [entity-tx (.entityTx (.db f/*api*) :ivan)]
(t/is (= (merge submitted-tx
{:crux.db/id (str (c/new-id :ivan))
:crux.db/content-hash (str (c/new-id {:crux.db/id :ivan :name "<NAME>"}))
:crux.db/valid-time valid-time})
entity-tx))
(t/is (= {:crux.db/id :ivan :name "<NAME>"} (.document f/*api* (:crux.db/content-hash entity-tx))))
(t/is (= [entity-tx] (.history f/*api* :ivan)))
(t/is (= [entity-tx] (.historyRange f/*api* :ivan #inst "1990" #inst "1990" (:crux.tx/tx-time submitted-tx) (:crux.tx/tx-time submitted-tx))))
(t/is (nil? (.document f/*api* (c/new-id :does-not-exist))))
(t/is (nil? (.entityTx (.db f/*api* #inst "1999") :ivan)))))
(t/testing "tx-log"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) (c/new-id {:crux.db/id :ivan :name "<NAME>"}) valid-time]])]
result))
(t/is (realized? result))))
(t/testing "with documents"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil true)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) {:crux.db/id :ivan :name "<NAME>"} valid-time]])]
result))
(t/is (realized? result)))))
(t/testing "from tx id"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx (inc tx-id) false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (empty? result))
(t/is (realized? result))))))
(t/testing "statistics"
(let [stats (.attributeStats f/*api*)]
(t/is (= 1 (:name stats))))
(t/testing "updated"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan2"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(t/is (= tx-time (.sync f/*api* nil))))
(let [stats (.attributeStats f/*api*)]
(t/is (= 2 (:name stats)))))
(t/testing "reflect evicted documents"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/evict :ivan]])]
(t/is (.sync f/*api* tx-time nil))
;; actual removal of the document happends asyncronusly after
;; the transaction has been processed so waiting on the
;; submitted transaction time is not enough
(while (.entity (.db f/*api*) :ivan)
(assert (< (- (.getTime (Date.)) (.getTime valid-time)) 4000))
(Thread/sleep 100))
(let [stats (.attributeStats f/*api*)]
(t/is (= 0 (:name stats))))))))))
(t/deftest test-document-bug-123
(let [version-1-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 1}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-1-submitted-tx :ivan))))
(let [version-2-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 2}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-2-submitted-tx :ivan))))
(let [history (.history f/*api* :ivan)]
(t/is (= 2 (count history)))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(for [content-hash (map :crux.db/content-hash history)]
(.document f/*api* content-hash))))))
(t/deftest test-db-history-api
(let [version-1-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 1} #inst "2019-02-01"]])) nil)
version-2-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 2} #inst "2019-02-02"]])) nil)
version-3-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 3} #inst "2019-02-03"]])) nil)
version-2-corrected-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true} #inst "2019-02-02"]])) nil)]
(let [history (.history f/*api* :ivan)]
(t/is (= 4 (count history))))
(let [db (.db f/*api* #inst "2019-02-03")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 3}
{:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true}
{:crux.db/id :ivan :name "<NAME>" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 1}
{:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true}
{:crux.db/id :ivan :name "<NAME>" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 3}
{:crux.db/id :ivan :name "<NAME>" :version 2 :corrected true}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04" #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-03" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "<NAME>" :version 2}
{:crux.db/id :ivan :name "<NAME>" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))))
(defn execute-sparql [^RepositoryConnection conn q]
(with-open [tq (.evaluate (.prepareTupleQuery conn q))]
(set ((fn step []
(when (.hasNext tq)
(cons (mapv #(rdf/rdf->clj (.getValue ^Binding %))
(.next tq))
(lazy-seq (step)))))))))
| true | (ns crux.api-test
(:require [clojure.test :as t]
[crux.bootstrap.standalone]
[crux.codec :as c]
[crux.fixtures :as f]
[crux.rdf :as rdf])
(:import clojure.lang.LazySeq
java.util.Date
java.time.Duration
crux.bootstrap.standalone.StandaloneSystem
org.eclipse.rdf4j.repository.sparql.SPARQLRepository
org.eclipse.rdf4j.repository.RepositoryConnection
org.eclipse.rdf4j.query.Binding))
(t/use-fixtures :once f/with-embedded-kafka-cluster)
(t/use-fixtures :each f/with-each-api-implementation)
(declare execute-sparql)
(t/deftest test-content-hash-invalid
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}
content-hash (str (c/new-id content-ivan))]
(t/is (thrown-with-msg? Exception (re-pattern (str content-hash "|HTTP status 400"))
(.submitTx f/*api* [[:crux.tx/put content-hash valid-time]])))))
(t/deftest test-can-write-entity-using-map-as-id
(let [doc {:crux.db/id {:user "Xwop1A7Xog4nD6AfhZaPgg"} :name "PI:NAME:<NAME>END_PI"}
submitted-tx (.submitTx f/*api* [[:crux.tx/put doc]])]
(.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)
(t/is (.entity (.db f/*api*) {:user "Xwop1A7Xog4nD6AfhZaPgg"}))))
(t/deftest test-single-id
(let [valid-time (Date.)
content-ivan {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}]
(t/testing "put works with no id"
(t/is
(let [submitted-tx (.submitTx f/*api* [[:crux.tx/put content-ivan valid-time]])]
(.db f/*api* valid-time (:crux.tx/tx-time submitted-tx)))))
(t/testing "Delete works with id"
(t/is (.submitTx f/*api* [[:crux.tx/delete :ivan]])))))
(t/deftest test-can-use-api-to-access-crux
(t/testing "status"
(t/is (= {:crux.zk/zk-active? (not (instance? StandaloneSystem f/*api*))
:crux.kv/kv-backend "crux.kv.rocksdb.RocksKv"
:crux.index/index-version 4}
(dissoc (.status f/*api*)
:crux.kv/estimate-num-keys
:crux.tx-log/consumer-state :crux.kv/size
:crux.version/version :crux.version/revision))))
(t/testing "empty db"
(t/is (.db f/*api*)))
(t/testing "syncing empty db"
(t/is (nil? (.sync f/*api* (Duration/ofSeconds 10)))))
(t/testing "transaction"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(let [status-map (.status f/*api*)]
(t/is (pos? (:crux.kv/estimate-num-keys status-map)))
(cond
(and (instance? StandaloneSystem f/*api*)
(instance? crux.tx.EventTxLog (:tx-log f/*api*)))
(t/is (= {:crux.tx/event-log {:lag 0 :next-offset (inc tx-id) :time tx-time}}
(:crux.tx-log/consumer-state status-map)))
:else
(let [tx-topic-key (keyword "PI:KEY:<KEY>END_PI"
(str (get-in f/*cluster-node* [:options :tx-topic]) "-PI:KEY:<KEY>END_PI"))
doc-topic-key (keyword "PI:KEY:<KEY>END_PI"
(str (get-in f/*cluster-node* [:options :doc-topic]) "-PI:KEY:<KEY>END_PI"))]
(t/is (= {:lag 0
:next-offset 1
:time tx-time}
(get-in status-map [:crux.tx-log/consumer-state tx-topic-key])))
(t/is (= {:lag 0
:next-offset 1}
(-> status-map
(get-in [:crux.tx-log/consumer-state doc-topic-key])
(dissoc :time)))))))
(t/testing "query"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]})))
(t/is (= #{} (.q (.db f/*api* #inst "1999") '{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]})))
(t/testing "query string"
(t/is (= #{[:ivan]} (.q (.db f/*api*)
"{:find [e] :where [[e :name \"PI:NAME:<NAME>END_PI\"]]}"))))
(t/testing "query vector"
(t/is (= #{[:ivan]} (.q (.db f/*api*) '[:find e
:where [e :name "PI:NAME:<NAME>END_PI"]]))))
(t/testing "malformed query"
(t/is (thrown-with-msg? Exception
#"(status 400|Spec assertion failed)"
(.q (.db f/*api*) '{:find [e]}))))
(t/testing "query with streaming result"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([:ivan]) result))
(t/is (realized? result))))))
(t/testing "query returning full results"
(let [db (.db f/*api*)]
(with-open [snapshot (.newSnapshot db)]
(let [result (.q db snapshot '{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]
:full-results? true})]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= '([{:crux.query/var e, :crux.query/value :ivan, :crux.query/doc {:crux.db/id :ivan, :name "PI:NAME:<NAME>END_PI"}}]) result))
(t/is (realized? result))))))
(t/testing "SPARQL query"
(when (bound? #'f/*api-url*)
(let [repo (SPARQLRepository. (str f/*api-url* "/sparql"))]
(try
(.initialize repo)
(with-open [conn (.getConnection repo)]
(t/is (= #{[:ivan]} (execute-sparql conn "SELECT ?e WHERE { ?e <http://juxt.pro/crux/unqualified/name> \"PI:NAME:<NAME>END_PI\" }"))))
(finally
(.shutDown repo)))))))
(t/testing "entity"
(t/is (= {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} (.entity (.db f/*api*) :ivan)))
(t/is (nil? (.entity (.db f/*api* #inst "1999") :ivan))))
(t/testing "entity-tx, document and history"
(let [entity-tx (.entityTx (.db f/*api*) :ivan)]
(t/is (= (merge submitted-tx
{:crux.db/id (str (c/new-id :ivan))
:crux.db/content-hash (str (c/new-id {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}))
:crux.db/valid-time valid-time})
entity-tx))
(t/is (= {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} (.document f/*api* (:crux.db/content-hash entity-tx))))
(t/is (= [entity-tx] (.history f/*api* :ivan)))
(t/is (= [entity-tx] (.historyRange f/*api* :ivan #inst "1990" #inst "1990" (:crux.tx/tx-time submitted-tx) (:crux.tx/tx-time submitted-tx))))
(t/is (nil? (.document f/*api* (c/new-id :does-not-exist))))
(t/is (nil? (.entityTx (.db f/*api* #inst "1999") :ivan)))))
(t/testing "tx-log"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) (c/new-id {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}) valid-time]])]
result))
(t/is (realized? result))))
(t/testing "with documents"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx nil true)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (= [(assoc submitted-tx
:crux.api/tx-ops [[:crux.tx/put (c/new-id :ivan) {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} valid-time]])]
result))
(t/is (realized? result)))))
(t/testing "from tx id"
(with-open [ctx (.newTxLogContext f/*api*)]
(let [result (.txLog f/*api* ctx (inc tx-id) false)]
(t/is (instance? LazySeq result))
(t/is (not (realized? result)))
(t/is (empty? result))
(t/is (realized? result))))))
(t/testing "statistics"
(let [stats (.attributeStats f/*api*)]
(t/is (= 1 (:name stats))))
(t/testing "updated"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "Ivan2"} valid-time]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* submitted-tx :ivan)))
(t/is (= tx-time (.sync f/*api* (:crux.tx/tx-time submitted-tx) nil)))
(t/is (= tx-time (.sync f/*api* nil))))
(let [stats (.attributeStats f/*api*)]
(t/is (= 2 (:name stats)))))
(t/testing "reflect evicted documents"
(let [valid-time (Date.)
{:keys [crux.tx/tx-time
crux.tx/tx-id]
:as submitted-tx} (.submitTx f/*api* [[:crux.tx/evict :ivan]])]
(t/is (.sync f/*api* tx-time nil))
;; actual removal of the document happends asyncronusly after
;; the transaction has been processed so waiting on the
;; submitted transaction time is not enough
(while (.entity (.db f/*api*) :ivan)
(assert (< (- (.getTime (Date.)) (.getTime valid-time)) 4000))
(Thread/sleep 100))
(let [stats (.attributeStats f/*api*)]
(t/is (= 0 (:name stats))))))))))
(t/deftest test-document-bug-123
(let [version-1-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-1-submitted-tx :ivan))))
(let [version-2-submitted-tx (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2}]])]
(t/is (true? (.hasSubmittedTxUpdatedEntity f/*api* version-2-submitted-tx :ivan))))
(let [history (.history f/*api* :ivan)]
(t/is (= 2 (count history)))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(for [content-hash (map :crux.db/content-hash history)]
(.document f/*api* content-hash))))))
(t/deftest test-db-history-api
(let [version-1-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1} #inst "2019-02-01"]])) nil)
version-2-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2} #inst "2019-02-02"]])) nil)
version-3-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3} #inst "2019-02-03"]])) nil)
version-2-corrected-submitted-tx-time (.sync f/*api* (:crux.tx/tx-time (.submitTx f/*api* [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true} #inst "2019-02-02"]])) nil)]
(let [history (.history f/*api* :ivan)]
(t/is (= 4 (count history))))
(let [db (.db f/*api* #inst "2019-02-03")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 3}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2 :corrected true}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-04" #inst "2019-01-31")]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (empty? (map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-02" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2}]
(map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))
(let [db (.db f/*api* #inst "2019-02-03" version-2-submitted-tx-time)]
(with-open [snapshot (.newSnapshot db)]
(t/is (empty? (map :crux.db/doc (.historyAscending db snapshot :ivan))))
(t/is (= [{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 2}
{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :version 1}]
(map :crux.db/doc (.historyDescending db snapshot :ivan))))))))
(defn execute-sparql [^RepositoryConnection conn q]
(with-open [tq (.evaluate (.prepareTupleQuery conn q))]
(set ((fn step []
(when (.hasNext tq)
(cons (mapv #(rdf/rdf->clj (.getValue ^Binding %))
(.next tq))
(lazy-seq (step)))))))))
|
[
{
"context": "position 9}\n {:name \"user_name\", :base-type :type/Text, :d",
"end": 2113,
"score": 0.7815967798233032,
"start": 2109,
"tag": "NAME",
"value": "name"
},
{
"context": "ase-position 10}\n {:name \"user_last_login\", :base-type :type/Text, :databas",
"end": 2271,
"score": 0.9715072512626648,
"start": 2256,
"tag": "USERNAME",
"value": "user_last_login"
}
] | c#-metabase/modules/drivers/druid/test/metabase/driver/druid/sync_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.driver.druid.sync-test
(:require [clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.test :as mt]
[metabase.timeseries-query-processor-test.util :as tqpt]))
(deftest sync-test
(mt/test-driver :druid
(tqpt/with-flattened-dbdef
(testing "describe-database"
(is (= {:tables #{{:schema nil, :name "checkins"}}}
(driver/describe-database :druid (mt/db)))))
(testing "describe-table"
(is (= {:schema nil
:name "checkins"
:fields [{:name "timestamp", :base-type :type/Instant, :database-type "timestamp", :database-position 0, :pk? false}
{:name "venue_name", :base-type :type/Text, :database-type "STRING", :database-position 1}
{:name "user_password", :base-type :type/Text, :database-type "STRING", :database-position 2}
{:name "venue_longitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 3}
{:name "venue_latitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 4}
{:name "venue_price", :base-type :type/Integer, :database-type "LONG", :database-position 5}
{:name "venue_category_name", :base-type :type/Text, :database-type "STRING", :database-position 6}
{:name "id", :base-type :type/Integer, :database-type "LONG", :database-position 7}
{:name "count", :base-type :type/Integer, :database-type "LONG [metric]", :database-position 8}
{:name "unique_users", :base-type :type/DruidHyperUnique, :database-type "hyperUnique [metric]", :database-position 9}
{:name "user_name", :base-type :type/Text, :database-type "STRING", :database-position 10}
{:name "user_last_login", :base-type :type/Text, :database-type "STRING", :database-position 11}]}
(-> (driver/describe-table :druid (mt/db) {:name "checkins"})
(update :fields (partial sort-by :database-position)))))))))
| 40626 | (ns metabase.driver.druid.sync-test
(:require [clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.test :as mt]
[metabase.timeseries-query-processor-test.util :as tqpt]))
(deftest sync-test
(mt/test-driver :druid
(tqpt/with-flattened-dbdef
(testing "describe-database"
(is (= {:tables #{{:schema nil, :name "checkins"}}}
(driver/describe-database :druid (mt/db)))))
(testing "describe-table"
(is (= {:schema nil
:name "checkins"
:fields [{:name "timestamp", :base-type :type/Instant, :database-type "timestamp", :database-position 0, :pk? false}
{:name "venue_name", :base-type :type/Text, :database-type "STRING", :database-position 1}
{:name "user_password", :base-type :type/Text, :database-type "STRING", :database-position 2}
{:name "venue_longitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 3}
{:name "venue_latitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 4}
{:name "venue_price", :base-type :type/Integer, :database-type "LONG", :database-position 5}
{:name "venue_category_name", :base-type :type/Text, :database-type "STRING", :database-position 6}
{:name "id", :base-type :type/Integer, :database-type "LONG", :database-position 7}
{:name "count", :base-type :type/Integer, :database-type "LONG [metric]", :database-position 8}
{:name "unique_users", :base-type :type/DruidHyperUnique, :database-type "hyperUnique [metric]", :database-position 9}
{:name "user_<NAME>", :base-type :type/Text, :database-type "STRING", :database-position 10}
{:name "user_last_login", :base-type :type/Text, :database-type "STRING", :database-position 11}]}
(-> (driver/describe-table :druid (mt/db) {:name "checkins"})
(update :fields (partial sort-by :database-position)))))))))
| true | (ns metabase.driver.druid.sync-test
(:require [clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.test :as mt]
[metabase.timeseries-query-processor-test.util :as tqpt]))
(deftest sync-test
(mt/test-driver :druid
(tqpt/with-flattened-dbdef
(testing "describe-database"
(is (= {:tables #{{:schema nil, :name "checkins"}}}
(driver/describe-database :druid (mt/db)))))
(testing "describe-table"
(is (= {:schema nil
:name "checkins"
:fields [{:name "timestamp", :base-type :type/Instant, :database-type "timestamp", :database-position 0, :pk? false}
{:name "venue_name", :base-type :type/Text, :database-type "STRING", :database-position 1}
{:name "user_password", :base-type :type/Text, :database-type "STRING", :database-position 2}
{:name "venue_longitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 3}
{:name "venue_latitude", :base-type :type/Float, :database-type "DOUBLE", :database-position 4}
{:name "venue_price", :base-type :type/Integer, :database-type "LONG", :database-position 5}
{:name "venue_category_name", :base-type :type/Text, :database-type "STRING", :database-position 6}
{:name "id", :base-type :type/Integer, :database-type "LONG", :database-position 7}
{:name "count", :base-type :type/Integer, :database-type "LONG [metric]", :database-position 8}
{:name "unique_users", :base-type :type/DruidHyperUnique, :database-type "hyperUnique [metric]", :database-position 9}
{:name "user_PI:NAME:<NAME>END_PI", :base-type :type/Text, :database-type "STRING", :database-position 10}
{:name "user_last_login", :base-type :type/Text, :database-type "STRING", :database-position 11}]}
(-> (driver/describe-table :druid (mt/db) {:name "checkins"})
(update :fields (partial sort-by :database-position)))))))))
|
[
{
"context": "e when using wrong API key\"\n (let [username \"alice\"\n ;; need cookies and csrf to actually",
"end": 1712,
"score": 0.9976107478141785,
"start": 1707,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "l})\n (api-key/add-api-key! \"44\" {:comment \"only alice & malice\" :users [\"alice\" \"malice\"]})\n (testin",
"end": 2379,
"score": 0.6687209606170654,
"start": 2374,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "(api-key/add-api-key! \"44\" {:comment \"only alice & malice\" :users [\"alice\" \"malice\"]})\n (testing \"> a",
"end": 2385,
"score": 0.8548815250396729,
"start": 2382,
"tag": "NAME",
"value": "mal"
},
{
"context": "-key/add-api-key! \"44\" {:comment \"only alice & malice\" :users [\"alice\" \"malice\"]})\n (testing \"> api ",
"end": 2388,
"score": 0.7837268710136414,
"start": 2385,
"tag": "USERNAME",
"value": "ice"
},
{
"context": "ey! \"44\" {:comment \"only alice & malice\" :users [\"alice\" \"malice\"]})\n (testing \"> api key without whit",
"end": 2404,
"score": 0.9891471862792969,
"start": 2399,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " {:comment \"only alice & malice\" :users [\"alice\" \"malice\"]})\n (testing \"> api key without whitelist can",
"end": 2413,
"score": 0.9961540699005127,
"start": 2407,
"tag": "USERNAME",
"value": "malice"
},
{
"context": "ersonate any user >\"\n (doseq [user [\"owner\" \"alice\" \"malice\"]]\n (testing user\n (is (",
"end": 2522,
"score": 0.9697185754776001,
"start": 2517,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " any user >\"\n (doseq [user [\"owner\" \"alice\" \"malice\"]]\n (testing user\n (is (response-",
"end": 2531,
"score": 0.9904063940048218,
"start": 2525,
"tag": "USERNAME",
"value": "malice"
},
{
"context": "y impersonate given users >\"\n (doseq [user [\"alice\" \"malice\"]]\n (testing user\n (is (",
"end": 2791,
"score": 0.9912139773368835,
"start": 2786,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "onate given users >\"\n (doseq [user [\"alice\" \"malice\"]]\n (testing user\n (is (response-",
"end": 2800,
"score": 0.9956611394882202,
"start": 2794,
"tag": "USERNAME",
"value": "malice"
}
] | test/clj/rems/api/test_api.clj | ossilva/rems | 31 | (ns ^:integration rems.api.test-api
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.db.api-key :as api-key]
[rems.db.core :as db]
[rems.db.test-data-helpers :as test-helpers]
[rems.handler :refer [handler]]
[ring.mock.request :refer :all]))
(use-fixtures :once api-fixture)
(deftest test-api-not-found
(testing "unknown endpoint"
(let [resp (-> (request :get "/api/unknown")
handler)]
(is (response-is-not-found? resp))))
(testing "known endpoint, wrong method,"
(testing "unauthorized"
(let [resp (-> (request :get "/api/blacklist/remove")
handler)]
(is (response-is-not-found? resp))))
(testing "authorized,"
(testing "missing params"
;; Surprisingly hard to find a POST route that isn't shadowed
;; by a GET route. For example, GET /api/applications/command
;; hits the /api/applications/:application-id route.
(let [resp (-> (request :get "/api/blacklist/remove")
(authenticate "42" "handler")
handler)]
(is (response-is-not-found? resp)))))))
(deftest test-api-key-security
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "alice"})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing ":api-key role"
(testing "available for valid api key"
(is (response-is-ok? (-> (request :post "/api/email/send-reminders")
(authenticate "42" "owner")
handler))))
(testing "not available when using wrong API key"
(let [username "alice"
;; need cookies and csrf to actually get a forbidden instead of "invalid csrf token"
;; TODO check this
cookie (login-with-cookies username)
csrf (get-csrf-token cookie)
resp (-> (request :post "/api/email/send-reminders")
(header "Cookie" cookie)
(header "x-csrf-token" csrf)
(header "x-rems-api-key" "WRONG")
handler)]
(is (response-is-forbidden? resp)))))
(testing "api key user whitelist"
(api-key/add-api-key! "43" {:comment "all users" :users nil})
(api-key/add-api-key! "44" {:comment "only alice & malice" :users ["alice" "malice"]})
(testing "> api key without whitelist can impersonate any user >"
(doseq [user ["owner" "alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/catalogue/" nil
"43" user))))))
(testing "> api key with whitelist can only impersonate given users >"
(doseq [user ["alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/my-applications/" nil
"44" user)))
(is (response-is-unauthorized? (api-response :get "/api/my-applications/" nil
"44" "owner")))))))
(testing "api key path whitelist"
(api-key/add-api-key! "45" {:comment "all paths" :paths nil})
(api-key/add-api-key! "46" {:comment "limited paths" :paths [{:method "any"
:path "/api/applications"}
{:path "/api/my-applications"
:method "any"}]})
(api-key/add-api-key! "47" {:comment "regex path" :paths [{:method "any"
:path "/api/c.*"}
{:method "get"
:path "/api/users/.*"}]})
(testing "> api key without whitelist can access any path >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"45" "owner"))))))
(testing "> api key with whitelist can access only given paths >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"46" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/catalogue-items" nil
"46" "owner"))))
(testing "> api key with whitelist can access only matching paths >"
(doseq [path ["/api/catalogue?query=param" "/api/catalogue-items"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"47" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/applications" nil
"47" "owner"))))
(testing "> api key with whitelist can use only matching methods"
(is (response-is-ok? (api-response :get "/api/users/active" nil
"47" "owner")))
(is (response-is-unauthorized? (api-response :post "/api/users/create"
{:userid "testing"
:name nil
:email nil}
"47" "owner"))))))
(deftest test-health-api
;; create at least one event
(test-helpers/create-application! {:actor "alice"})
(let [body (-> (request :get "/api/health")
handler
read-ok-body)]
(is (:healthy body))
(is (string? (:latest-event body)))
(is (not (empty? (:latest-event body))))))
(deftest test-keepalive-api
(assert-response-is-ok (-> (request :get "/keepalive")
handler))
(is true))
(deftest data-exception-test
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing "a broken license without an organization"
(let [license-id (:id (db/create-license! {:owneruserid "owner"
:modifieruserid "owner"
:organization "does-not-exist"
:type "text"}))
response (-> (api-response :get (str "/api/licenses/" license-id)
nil
"42" "owner"))]
(testing "returns a useful description of the problem"
(is (= 503 (:status response)))
(is (= {:errors [{:args ["does-not-exist"]
:organization/id "does-not-exist"
:type "t.actions.errors/organization-does-not-exist"}]}
(read-body response)))))))
| 97010 | (ns ^:integration rems.api.test-api
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.db.api-key :as api-key]
[rems.db.core :as db]
[rems.db.test-data-helpers :as test-helpers]
[rems.handler :refer [handler]]
[ring.mock.request :refer :all]))
(use-fixtures :once api-fixture)
(deftest test-api-not-found
(testing "unknown endpoint"
(let [resp (-> (request :get "/api/unknown")
handler)]
(is (response-is-not-found? resp))))
(testing "known endpoint, wrong method,"
(testing "unauthorized"
(let [resp (-> (request :get "/api/blacklist/remove")
handler)]
(is (response-is-not-found? resp))))
(testing "authorized,"
(testing "missing params"
;; Surprisingly hard to find a POST route that isn't shadowed
;; by a GET route. For example, GET /api/applications/command
;; hits the /api/applications/:application-id route.
(let [resp (-> (request :get "/api/blacklist/remove")
(authenticate "42" "handler")
handler)]
(is (response-is-not-found? resp)))))))
(deftest test-api-key-security
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "alice"})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing ":api-key role"
(testing "available for valid api key"
(is (response-is-ok? (-> (request :post "/api/email/send-reminders")
(authenticate "42" "owner")
handler))))
(testing "not available when using wrong API key"
(let [username "alice"
;; need cookies and csrf to actually get a forbidden instead of "invalid csrf token"
;; TODO check this
cookie (login-with-cookies username)
csrf (get-csrf-token cookie)
resp (-> (request :post "/api/email/send-reminders")
(header "Cookie" cookie)
(header "x-csrf-token" csrf)
(header "x-rems-api-key" "WRONG")
handler)]
(is (response-is-forbidden? resp)))))
(testing "api key user whitelist"
(api-key/add-api-key! "43" {:comment "all users" :users nil})
(api-key/add-api-key! "44" {:comment "only alice & <NAME>ice" :users ["alice" "malice"]})
(testing "> api key without whitelist can impersonate any user >"
(doseq [user ["owner" "alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/catalogue/" nil
"43" user))))))
(testing "> api key with whitelist can only impersonate given users >"
(doseq [user ["alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/my-applications/" nil
"44" user)))
(is (response-is-unauthorized? (api-response :get "/api/my-applications/" nil
"44" "owner")))))))
(testing "api key path whitelist"
(api-key/add-api-key! "45" {:comment "all paths" :paths nil})
(api-key/add-api-key! "46" {:comment "limited paths" :paths [{:method "any"
:path "/api/applications"}
{:path "/api/my-applications"
:method "any"}]})
(api-key/add-api-key! "47" {:comment "regex path" :paths [{:method "any"
:path "/api/c.*"}
{:method "get"
:path "/api/users/.*"}]})
(testing "> api key without whitelist can access any path >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"45" "owner"))))))
(testing "> api key with whitelist can access only given paths >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"46" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/catalogue-items" nil
"46" "owner"))))
(testing "> api key with whitelist can access only matching paths >"
(doseq [path ["/api/catalogue?query=param" "/api/catalogue-items"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"47" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/applications" nil
"47" "owner"))))
(testing "> api key with whitelist can use only matching methods"
(is (response-is-ok? (api-response :get "/api/users/active" nil
"47" "owner")))
(is (response-is-unauthorized? (api-response :post "/api/users/create"
{:userid "testing"
:name nil
:email nil}
"47" "owner"))))))
(deftest test-health-api
;; create at least one event
(test-helpers/create-application! {:actor "alice"})
(let [body (-> (request :get "/api/health")
handler
read-ok-body)]
(is (:healthy body))
(is (string? (:latest-event body)))
(is (not (empty? (:latest-event body))))))
(deftest test-keepalive-api
(assert-response-is-ok (-> (request :get "/keepalive")
handler))
(is true))
(deftest data-exception-test
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing "a broken license without an organization"
(let [license-id (:id (db/create-license! {:owneruserid "owner"
:modifieruserid "owner"
:organization "does-not-exist"
:type "text"}))
response (-> (api-response :get (str "/api/licenses/" license-id)
nil
"42" "owner"))]
(testing "returns a useful description of the problem"
(is (= 503 (:status response)))
(is (= {:errors [{:args ["does-not-exist"]
:organization/id "does-not-exist"
:type "t.actions.errors/organization-does-not-exist"}]}
(read-body response)))))))
| true | (ns ^:integration rems.api.test-api
(:require [clojure.test :refer :all]
[rems.api.testing :refer :all]
[rems.db.api-key :as api-key]
[rems.db.core :as db]
[rems.db.test-data-helpers :as test-helpers]
[rems.handler :refer [handler]]
[ring.mock.request :refer :all]))
(use-fixtures :once api-fixture)
(deftest test-api-not-found
(testing "unknown endpoint"
(let [resp (-> (request :get "/api/unknown")
handler)]
(is (response-is-not-found? resp))))
(testing "known endpoint, wrong method,"
(testing "unauthorized"
(let [resp (-> (request :get "/api/blacklist/remove")
handler)]
(is (response-is-not-found? resp))))
(testing "authorized,"
(testing "missing params"
;; Surprisingly hard to find a POST route that isn't shadowed
;; by a GET route. For example, GET /api/applications/command
;; hits the /api/applications/:application-id route.
(let [resp (-> (request :get "/api/blacklist/remove")
(authenticate "42" "handler")
handler)]
(is (response-is-not-found? resp)))))))
(deftest test-api-key-security
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "alice"})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing ":api-key role"
(testing "available for valid api key"
(is (response-is-ok? (-> (request :post "/api/email/send-reminders")
(authenticate "42" "owner")
handler))))
(testing "not available when using wrong API key"
(let [username "alice"
;; need cookies and csrf to actually get a forbidden instead of "invalid csrf token"
;; TODO check this
cookie (login-with-cookies username)
csrf (get-csrf-token cookie)
resp (-> (request :post "/api/email/send-reminders")
(header "Cookie" cookie)
(header "x-csrf-token" csrf)
(header "x-rems-api-key" "WRONG")
handler)]
(is (response-is-forbidden? resp)))))
(testing "api key user whitelist"
(api-key/add-api-key! "43" {:comment "all users" :users nil})
(api-key/add-api-key! "44" {:comment "only alice & PI:NAME:<NAME>END_PIice" :users ["alice" "malice"]})
(testing "> api key without whitelist can impersonate any user >"
(doseq [user ["owner" "alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/catalogue/" nil
"43" user))))))
(testing "> api key with whitelist can only impersonate given users >"
(doseq [user ["alice" "malice"]]
(testing user
(is (response-is-ok? (api-response :get "/api/my-applications/" nil
"44" user)))
(is (response-is-unauthorized? (api-response :get "/api/my-applications/" nil
"44" "owner")))))))
(testing "api key path whitelist"
(api-key/add-api-key! "45" {:comment "all paths" :paths nil})
(api-key/add-api-key! "46" {:comment "limited paths" :paths [{:method "any"
:path "/api/applications"}
{:path "/api/my-applications"
:method "any"}]})
(api-key/add-api-key! "47" {:comment "regex path" :paths [{:method "any"
:path "/api/c.*"}
{:method "get"
:path "/api/users/.*"}]})
(testing "> api key without whitelist can access any path >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"45" "owner"))))))
(testing "> api key with whitelist can access only given paths >"
(doseq [path ["/api/applications" "/api/my-applications"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"46" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/catalogue-items" nil
"46" "owner"))))
(testing "> api key with whitelist can access only matching paths >"
(doseq [path ["/api/catalogue?query=param" "/api/catalogue-items"]]
(testing path
(is (response-is-ok? (api-response :get path nil
"47" "owner")))))
(is (response-is-unauthorized? (api-response :get "/api/applications" nil
"47" "owner"))))
(testing "> api key with whitelist can use only matching methods"
(is (response-is-ok? (api-response :get "/api/users/active" nil
"47" "owner")))
(is (response-is-unauthorized? (api-response :post "/api/users/create"
{:userid "testing"
:name nil
:email nil}
"47" "owner"))))))
(deftest test-health-api
;; create at least one event
(test-helpers/create-application! {:actor "alice"})
(let [body (-> (request :get "/api/health")
handler
read-ok-body)]
(is (:healthy body))
(is (string? (:latest-event body)))
(is (not (empty? (:latest-event body))))))
(deftest test-keepalive-api
(assert-response-is-ok (-> (request :get "/keepalive")
handler))
(is true))
(deftest data-exception-test
(api-key/add-api-key! "42" {})
(test-helpers/create-user! {:eppn "owner"} :owner)
(testing "a broken license without an organization"
(let [license-id (:id (db/create-license! {:owneruserid "owner"
:modifieruserid "owner"
:organization "does-not-exist"
:type "text"}))
response (-> (api-response :get (str "/api/licenses/" license-id)
nil
"42" "owner"))]
(testing "returns a useful description of the problem"
(is (= 503 (:status response)))
(is (= {:errors [{:args ["does-not-exist"]
:organization/id "does-not-exist"
:type "t.actions.errors/organization-does-not-exist"}]}
(read-body response)))))))
|
[
{
"context": " Kafka\n;; partitions, based on https://github.com/basho/bitcask\n\n;; Should really spill the local cached ",
"end": 966,
"score": 0.6691940426826477,
"start": 961,
"tag": "USERNAME",
"value": "basho"
},
{
"context": "tially using something like\n;; https://github.com/JakeWharton/DiskLruCache\n\n;; The hint map could also be cache",
"end": 1105,
"score": 0.9996401071548462,
"start": 1094,
"tag": "USERNAME",
"value": "JakeWharton"
},
{
"context": "ent]\n :as partial-node}\n {:keys [data-topic hint-topic data-partitions replication-facto",
"end": 2422,
"score": 0.7311995625495911,
"start": 2417,
"tag": "KEY",
"value": "data-"
},
{
"context": ":as partial-node}\n {:keys [data-topic hint-topic data-partitions replication-factor object-ca",
"end": 2432,
"score": 0.8304507732391357,
"start": 2432,
"tag": "KEY",
"value": ""
},
{
"context": "t [this snapshot k]\n (let [doc-key (str (c/new-id k))]\n (when-let [{:bitcask-kafka/keys [parti",
"end": 4079,
"score": 0.5842217206954956,
"start": 4077,
"tag": "KEY",
"value": "id"
},
{
"context": " :let [doc-key (str (c/new-id k))]]\n [doc-key\n ",
"end": 5362,
"score": 0.6079472303390503,
"start": 5356,
"tag": "KEY",
"value": "new-id"
}
] | dev/bitcask_kafka.clj | dotemacs/crux | 0 | (ns bitcask-kafka
(:require [clojure.edn :as edn]
[clojure.tools.logging :as log]
[crux.codec :as c]
[crux.db :as db]
[crux.kafka :as k]
[crux.kafka.consumer :as kc]
[crux.lru :as lru]
[crux.memory :as mem]
[taoensso.nippy :as nippy])
(:import [crux.kafka.nippy NippyDeserializer NippySerializer]
java.util.function.Supplier
java.io.Closeable
java.time.Duration
java.util.List
[org.apache.kafka.clients.consumer ConsumerRebalanceListener ConsumerRecord KafkaConsumer]
[org.apache.kafka.clients.producer KafkaProducer ProducerRecord RecordMetadata]
[org.apache.kafka.common.serialization BytesSerializer StringSerializer]
org.apache.kafka.common.TopicPartition))
;; Spike implementation of crux.db.ObjectStore on top of two Kafka
;; partitions, based on https://github.com/basho/bitcask
;; Should really spill the local cached values out to disk,
;; potentially using something like
;; https://github.com/JakeWharton/DiskLruCache
;; The hint map could also be cached locally to disk. The offset to
;; seek to would be the max + 1.
(def ^:private topic-config {"cleanup.policy" "compact"})
(def ^:private default-consumer-config {"enable.auto.commit" "false"})
(def ^:private data-consumer-config {"max.poll.records" "1"})
(defn- hint-consumer-main-loop [keydir running? consumer-config {:keys [timeout] :or {timeout 1000} :as options}]
(with-open [consumer (kc/create-consumer consumer-config)]
(let [topic-partitions [(TopicPartition. (get options :hint-topic) 0)]]
(.assign consumer topic-partitions)
(.seekToBeginning consumer topic-partitions)
(while @running?
(when-let [records (seq (.poll consumer (Duration/ofMillis timeout)))]
(->> (for [^ConsumerRecord record records]
[(.key record) (.value record)])
(into {})
(swap! keydir merge)))))))
(defrecord BitcaskKafkaObjectStore [keydir running? consumer-config
^KafkaProducer producer consumers ^ThreadLocal consumer-tl
object-cache
options ^Thread worker-thread]
db/ObjectStore
(init [this
{:keys [admin-client]
:as partial-node}
{:keys [data-topic hint-topic data-partitions replication-factor object-cache-size]
:or {data-topic "data-topic"
hint-topic "hint-topic"
data-partitions 3
replication-factor 1
object-cache-size 10000}
:as options}]
(k/create-topic admin-client hint-topic 1 replication-factor topic-config)
(k/create-topic admin-client data-topic data-partitions replication-factor topic-config)
(let [consumer-config (merge (@#'k/derive-kafka-config options) default-consumer-config)
keydir (atom (sorted-map))
running? (atom true)
options (assoc options :hint-topic hint-topic :data-topic data-topic)
consumers (atom #{})
consumer-tl (ThreadLocal/withInitial
(reify Supplier
(get [_]
(doto (kc/create-consumer (merge consumer-config data-consumer-config))
(->> (swap! consumers conj))))))]
(assoc this
:keydir keydir
:running? running?
:consumer-config consumer-config
:producer (k/create-producer consumer-config)
:options options
:consumer-tl consumer-tl
:consumers consumers
:object-cache (lru/new-cache object-cache-size)
:worker-thread
(doto (Thread. ^Runnable #(hint-consumer-main-loop keydir running? consumer-config options)
"bitcask-kafka.indexing-consumer-thread")
(.start)))))
(get-single-object [this snapshot k]
(let [doc-key (str (c/new-id k))]
(when-let [{:bitcask-kafka/keys [partition offset deleted?]} (get @keydir doc-key)]
(when-not deleted?
(lru/compute-if-absent
object-cache
[doc-key partition offset]
identity
(fn [_]
(let [^KafkaConsumer consumer (.get consumer-tl)
topic-partition (TopicPartition. (get options :data-topic) partition)]
(.assign consumer [topic-partition])
(.seek consumer topic-partition (long offset))
(when-let [^ConsumerRecord record (first (.poll consumer (Duration/ofMillis 1000)))]
(.value record)))))))))
(get-objects [this snapshot ks]
(->> (for [k ks
:let [v (db/get-single-object this nil k)]
:when (not (nil? v))]
[k v])
(into {})))
(known-keys? [this snapshot ks]
(let [keydir @keydir]
(->> (for [k ks]
(str (c/new-id k)))
(every? #(and (contains? keydir %)
(not (get-in keydir [% :bitcask-kafka/deleted?])))))))
(put-objects [this kvs]
(let [{:keys [data-topic hint-topic]} options
k+deleted?+mds (->> (for [[k v] kvs
:let [doc-key (str (c/new-id k))]]
[doc-key
(nil? v)
(.send producer (ProducerRecord. data-topic doc-key v))])
(doall))]
(.flush producer)
(doseq [[doc-key deleted? md] k+deleted?+mds
:let [^RecordMetadata metadata @md
hint {:bitcask-kafka/partition (.partition metadata)
:bitcask-kafka/offset (.offset metadata)
:bitcask-kafka/deleted? deleted?}]]
@(.send producer (ProducerRecord. hint-topic doc-key hint))
(swap! keydir assoc doc-key hint))))
(delete-objects [this ks]
(db/put-objects this (zipmap ks (repeat nil))))
Closeable
(close [this]
(reset! running? false)
(.join worker-thread)
(some-> producer (.close))
(doseq [^KafkaConsumer consumer @consumers]
(.close consumer))
(dissoc this :keydir)))
(comment
(dev)
(start)
(def os (db/init (bitcask-kafka/map->BitcaskKafkaObjectStore {})
node
(:options node)))
(db/put-objects os [[:bar "foo"]])
;;=> nil
@(:keydir os)
;;=> {key-hash hint}
(db/known-keys? os nil [:bar])
;;=> true
(db/get-single-object os nil :bar)
;;=> "foo"
(db/delete-objects os [:bar])
;;=> nil
(db/known-keys? os nil [:bar])
;;=> false
(db/get-single-object os nil :bar)
;;=> nil
)
| 74430 | (ns bitcask-kafka
(:require [clojure.edn :as edn]
[clojure.tools.logging :as log]
[crux.codec :as c]
[crux.db :as db]
[crux.kafka :as k]
[crux.kafka.consumer :as kc]
[crux.lru :as lru]
[crux.memory :as mem]
[taoensso.nippy :as nippy])
(:import [crux.kafka.nippy NippyDeserializer NippySerializer]
java.util.function.Supplier
java.io.Closeable
java.time.Duration
java.util.List
[org.apache.kafka.clients.consumer ConsumerRebalanceListener ConsumerRecord KafkaConsumer]
[org.apache.kafka.clients.producer KafkaProducer ProducerRecord RecordMetadata]
[org.apache.kafka.common.serialization BytesSerializer StringSerializer]
org.apache.kafka.common.TopicPartition))
;; Spike implementation of crux.db.ObjectStore on top of two Kafka
;; partitions, based on https://github.com/basho/bitcask
;; Should really spill the local cached values out to disk,
;; potentially using something like
;; https://github.com/JakeWharton/DiskLruCache
;; The hint map could also be cached locally to disk. The offset to
;; seek to would be the max + 1.
(def ^:private topic-config {"cleanup.policy" "compact"})
(def ^:private default-consumer-config {"enable.auto.commit" "false"})
(def ^:private data-consumer-config {"max.poll.records" "1"})
(defn- hint-consumer-main-loop [keydir running? consumer-config {:keys [timeout] :or {timeout 1000} :as options}]
(with-open [consumer (kc/create-consumer consumer-config)]
(let [topic-partitions [(TopicPartition. (get options :hint-topic) 0)]]
(.assign consumer topic-partitions)
(.seekToBeginning consumer topic-partitions)
(while @running?
(when-let [records (seq (.poll consumer (Duration/ofMillis timeout)))]
(->> (for [^ConsumerRecord record records]
[(.key record) (.value record)])
(into {})
(swap! keydir merge)))))))
(defrecord BitcaskKafkaObjectStore [keydir running? consumer-config
^KafkaProducer producer consumers ^ThreadLocal consumer-tl
object-cache
options ^Thread worker-thread]
db/ObjectStore
(init [this
{:keys [admin-client]
:as partial-node}
{:keys [<KEY>topic hint<KEY>-topic data-partitions replication-factor object-cache-size]
:or {data-topic "data-topic"
hint-topic "hint-topic"
data-partitions 3
replication-factor 1
object-cache-size 10000}
:as options}]
(k/create-topic admin-client hint-topic 1 replication-factor topic-config)
(k/create-topic admin-client data-topic data-partitions replication-factor topic-config)
(let [consumer-config (merge (@#'k/derive-kafka-config options) default-consumer-config)
keydir (atom (sorted-map))
running? (atom true)
options (assoc options :hint-topic hint-topic :data-topic data-topic)
consumers (atom #{})
consumer-tl (ThreadLocal/withInitial
(reify Supplier
(get [_]
(doto (kc/create-consumer (merge consumer-config data-consumer-config))
(->> (swap! consumers conj))))))]
(assoc this
:keydir keydir
:running? running?
:consumer-config consumer-config
:producer (k/create-producer consumer-config)
:options options
:consumer-tl consumer-tl
:consumers consumers
:object-cache (lru/new-cache object-cache-size)
:worker-thread
(doto (Thread. ^Runnable #(hint-consumer-main-loop keydir running? consumer-config options)
"bitcask-kafka.indexing-consumer-thread")
(.start)))))
(get-single-object [this snapshot k]
(let [doc-key (str (c/new-<KEY> k))]
(when-let [{:bitcask-kafka/keys [partition offset deleted?]} (get @keydir doc-key)]
(when-not deleted?
(lru/compute-if-absent
object-cache
[doc-key partition offset]
identity
(fn [_]
(let [^KafkaConsumer consumer (.get consumer-tl)
topic-partition (TopicPartition. (get options :data-topic) partition)]
(.assign consumer [topic-partition])
(.seek consumer topic-partition (long offset))
(when-let [^ConsumerRecord record (first (.poll consumer (Duration/ofMillis 1000)))]
(.value record)))))))))
(get-objects [this snapshot ks]
(->> (for [k ks
:let [v (db/get-single-object this nil k)]
:when (not (nil? v))]
[k v])
(into {})))
(known-keys? [this snapshot ks]
(let [keydir @keydir]
(->> (for [k ks]
(str (c/new-id k)))
(every? #(and (contains? keydir %)
(not (get-in keydir [% :bitcask-kafka/deleted?])))))))
(put-objects [this kvs]
(let [{:keys [data-topic hint-topic]} options
k+deleted?+mds (->> (for [[k v] kvs
:let [doc-key (str (c/<KEY> k))]]
[doc-key
(nil? v)
(.send producer (ProducerRecord. data-topic doc-key v))])
(doall))]
(.flush producer)
(doseq [[doc-key deleted? md] k+deleted?+mds
:let [^RecordMetadata metadata @md
hint {:bitcask-kafka/partition (.partition metadata)
:bitcask-kafka/offset (.offset metadata)
:bitcask-kafka/deleted? deleted?}]]
@(.send producer (ProducerRecord. hint-topic doc-key hint))
(swap! keydir assoc doc-key hint))))
(delete-objects [this ks]
(db/put-objects this (zipmap ks (repeat nil))))
Closeable
(close [this]
(reset! running? false)
(.join worker-thread)
(some-> producer (.close))
(doseq [^KafkaConsumer consumer @consumers]
(.close consumer))
(dissoc this :keydir)))
(comment
(dev)
(start)
(def os (db/init (bitcask-kafka/map->BitcaskKafkaObjectStore {})
node
(:options node)))
(db/put-objects os [[:bar "foo"]])
;;=> nil
@(:keydir os)
;;=> {key-hash hint}
(db/known-keys? os nil [:bar])
;;=> true
(db/get-single-object os nil :bar)
;;=> "foo"
(db/delete-objects os [:bar])
;;=> nil
(db/known-keys? os nil [:bar])
;;=> false
(db/get-single-object os nil :bar)
;;=> nil
)
| true | (ns bitcask-kafka
(:require [clojure.edn :as edn]
[clojure.tools.logging :as log]
[crux.codec :as c]
[crux.db :as db]
[crux.kafka :as k]
[crux.kafka.consumer :as kc]
[crux.lru :as lru]
[crux.memory :as mem]
[taoensso.nippy :as nippy])
(:import [crux.kafka.nippy NippyDeserializer NippySerializer]
java.util.function.Supplier
java.io.Closeable
java.time.Duration
java.util.List
[org.apache.kafka.clients.consumer ConsumerRebalanceListener ConsumerRecord KafkaConsumer]
[org.apache.kafka.clients.producer KafkaProducer ProducerRecord RecordMetadata]
[org.apache.kafka.common.serialization BytesSerializer StringSerializer]
org.apache.kafka.common.TopicPartition))
;; Spike implementation of crux.db.ObjectStore on top of two Kafka
;; partitions, based on https://github.com/basho/bitcask
;; Should really spill the local cached values out to disk,
;; potentially using something like
;; https://github.com/JakeWharton/DiskLruCache
;; The hint map could also be cached locally to disk. The offset to
;; seek to would be the max + 1.
(def ^:private topic-config {"cleanup.policy" "compact"})
(def ^:private default-consumer-config {"enable.auto.commit" "false"})
(def ^:private data-consumer-config {"max.poll.records" "1"})
(defn- hint-consumer-main-loop [keydir running? consumer-config {:keys [timeout] :or {timeout 1000} :as options}]
(with-open [consumer (kc/create-consumer consumer-config)]
(let [topic-partitions [(TopicPartition. (get options :hint-topic) 0)]]
(.assign consumer topic-partitions)
(.seekToBeginning consumer topic-partitions)
(while @running?
(when-let [records (seq (.poll consumer (Duration/ofMillis timeout)))]
(->> (for [^ConsumerRecord record records]
[(.key record) (.value record)])
(into {})
(swap! keydir merge)))))))
(defrecord BitcaskKafkaObjectStore [keydir running? consumer-config
^KafkaProducer producer consumers ^ThreadLocal consumer-tl
object-cache
options ^Thread worker-thread]
db/ObjectStore
(init [this
{:keys [admin-client]
:as partial-node}
{:keys [PI:KEY:<KEY>END_PItopic hintPI:KEY:<KEY>END_PI-topic data-partitions replication-factor object-cache-size]
:or {data-topic "data-topic"
hint-topic "hint-topic"
data-partitions 3
replication-factor 1
object-cache-size 10000}
:as options}]
(k/create-topic admin-client hint-topic 1 replication-factor topic-config)
(k/create-topic admin-client data-topic data-partitions replication-factor topic-config)
(let [consumer-config (merge (@#'k/derive-kafka-config options) default-consumer-config)
keydir (atom (sorted-map))
running? (atom true)
options (assoc options :hint-topic hint-topic :data-topic data-topic)
consumers (atom #{})
consumer-tl (ThreadLocal/withInitial
(reify Supplier
(get [_]
(doto (kc/create-consumer (merge consumer-config data-consumer-config))
(->> (swap! consumers conj))))))]
(assoc this
:keydir keydir
:running? running?
:consumer-config consumer-config
:producer (k/create-producer consumer-config)
:options options
:consumer-tl consumer-tl
:consumers consumers
:object-cache (lru/new-cache object-cache-size)
:worker-thread
(doto (Thread. ^Runnable #(hint-consumer-main-loop keydir running? consumer-config options)
"bitcask-kafka.indexing-consumer-thread")
(.start)))))
(get-single-object [this snapshot k]
(let [doc-key (str (c/new-PI:KEY:<KEY>END_PI k))]
(when-let [{:bitcask-kafka/keys [partition offset deleted?]} (get @keydir doc-key)]
(when-not deleted?
(lru/compute-if-absent
object-cache
[doc-key partition offset]
identity
(fn [_]
(let [^KafkaConsumer consumer (.get consumer-tl)
topic-partition (TopicPartition. (get options :data-topic) partition)]
(.assign consumer [topic-partition])
(.seek consumer topic-partition (long offset))
(when-let [^ConsumerRecord record (first (.poll consumer (Duration/ofMillis 1000)))]
(.value record)))))))))
(get-objects [this snapshot ks]
(->> (for [k ks
:let [v (db/get-single-object this nil k)]
:when (not (nil? v))]
[k v])
(into {})))
(known-keys? [this snapshot ks]
(let [keydir @keydir]
(->> (for [k ks]
(str (c/new-id k)))
(every? #(and (contains? keydir %)
(not (get-in keydir [% :bitcask-kafka/deleted?])))))))
(put-objects [this kvs]
(let [{:keys [data-topic hint-topic]} options
k+deleted?+mds (->> (for [[k v] kvs
:let [doc-key (str (c/PI:KEY:<KEY>END_PI k))]]
[doc-key
(nil? v)
(.send producer (ProducerRecord. data-topic doc-key v))])
(doall))]
(.flush producer)
(doseq [[doc-key deleted? md] k+deleted?+mds
:let [^RecordMetadata metadata @md
hint {:bitcask-kafka/partition (.partition metadata)
:bitcask-kafka/offset (.offset metadata)
:bitcask-kafka/deleted? deleted?}]]
@(.send producer (ProducerRecord. hint-topic doc-key hint))
(swap! keydir assoc doc-key hint))))
(delete-objects [this ks]
(db/put-objects this (zipmap ks (repeat nil))))
Closeable
(close [this]
(reset! running? false)
(.join worker-thread)
(some-> producer (.close))
(doseq [^KafkaConsumer consumer @consumers]
(.close consumer))
(dissoc this :keydir)))
(comment
(dev)
(start)
(def os (db/init (bitcask-kafka/map->BitcaskKafkaObjectStore {})
node
(:options node)))
(db/put-objects os [[:bar "foo"]])
;;=> nil
@(:keydir os)
;;=> {key-hash hint}
(db/known-keys? os nil [:bar])
;;=> true
(db/get-single-object os nil :bar)
;;=> "foo"
(db/delete-objects os [:bar])
;;=> nil
(db/known-keys? os nil [:bar])
;;=> false
(db/get-single-object os nil :bar)
;;=> nil
)
|
[
{
"context": "; Copyright (c) Christophe Grand. All rights reserved.\n; The use and distributio",
"end": 34,
"score": 0.9998701214790344,
"start": 18,
"tag": "NAME",
"value": "Christophe Grand"
}
] | server/target/net/cgrand/parsley.clj | OctavioBR/healthcheck | 0 | ; Copyright (c) Christophe Grand. 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 net.cgrand.parsley
"A total truly incremental parser generator. Grammars are expressed
in a value-based DSL."
(:require [net.cgrand.parsley.lrplus :as core]
[net.cgrand.parsley.fold :as f]
[net.cgrand.parsley.tree :as t]
[net.cgrand.parsley.util :as u]
[net.cgrand.parsley.grammar :as g]))
(defrecord Node [tag content]) ; for memory efficiency
(defn- stepper [table options-map]
(let [options-map (merge
{:make-node #(Node. %1 %2)
:make-leaf nil} ; nil for identity
options-map)
options-map (if-not (:make-unexpected options-map)
(let [make-node (:make-node options-map)
make-leaf (or (:make-leaf options-map) identity)]
(assoc options-map :make-unexpected
#(make-node ::unexpected [(make-leaf %)])))
options-map)
ops (select-keys options-map [:make-node :make-leaf :make-unexpected])]
^{::options options-map} ; feeling dirty, metadata make me uneasy
(fn self
([s]
(let [a (self core/zero s) b (self a nil)]
(-> (f/stitch a b) (nth 2) f/finish)))
([state s]
(core/step table ops state s)))))
(defn- flatten-rules [rules]
(if (map? rules)
(apply concat rules)
rules))
(defn make-parser [options-map rules]
(-> (apply g/grammar options-map (flatten-rules rules)) core/lr-table core/totalize
core/number-states (stepper options-map)))
(defn parser [options-map & rules]
(let [[options-map rules] (if-not (map? options-map)
[{} (cons options-map rules)]
[options-map rules])]
(make-parser options-map rules)))
(defn unspaced
"Creates an unspaced sequence."
[& specs]
(apply g/unspaced specs))
(defn- memoize-parser [f]
(let [cache (atom nil)]
(fn [input]
(u/cond
[last-result @cache
new-result (f/rebase last-result input)]
(if (identical? last-result new-result)
last-result
(reset! cache new-result))
(reset! cache (f input))))))
(defn- memoize1 [parser s]
(memoize-parser #(parser % s)))
(defn- memoize2 [mpa mpb]
(memoize-parser #(let [a (mpa %)
b (mpb a)]
(f/stitch a b))))
(defn- memoize-1shot [f]
(let [cache (atom [(Object.) nil])]
(fn [& args]
(let [[cargs cr] @cache]
(if (= args cargs)
cr
(let [r (apply f args)]
(reset! cache [args r])
r))))))
(defn- memoize-eof [parser]
(let [mp (memoize1 parser nil)]
(memoize-1shot #(-> (f/stitch % (mp %)) (nth 2) f/finish))))
(defn incremental-buffer
"Creates an empty incremental buffer for the specified parser."
[parser]
{:buffer (t/buffer {:unit #(memoize1 parser %)
:plus memoize2
:chunk #(.split ^String % "(?<=\n)")
:left #(subs %1 0 %2)
:right subs
:cat str})
:eof-parser (memoize-eof parser)
:options (::options (meta parser))})
(defn edit
"Returns a new buffer reflecting the specified edit."
[incremental-buffer offset length s]
(update-in incremental-buffer [:buffer] t/edit offset length s))
(defn parse-tree
"Returns the parse-tree."
[incremental-buffer]
(let [f (t/value (:buffer incremental-buffer))
a (f core/zero)]
((:eof-parser incremental-buffer) a)))
| 92450 | ; 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 net.cgrand.parsley
"A total truly incremental parser generator. Grammars are expressed
in a value-based DSL."
(:require [net.cgrand.parsley.lrplus :as core]
[net.cgrand.parsley.fold :as f]
[net.cgrand.parsley.tree :as t]
[net.cgrand.parsley.util :as u]
[net.cgrand.parsley.grammar :as g]))
(defrecord Node [tag content]) ; for memory efficiency
(defn- stepper [table options-map]
(let [options-map (merge
{:make-node #(Node. %1 %2)
:make-leaf nil} ; nil for identity
options-map)
options-map (if-not (:make-unexpected options-map)
(let [make-node (:make-node options-map)
make-leaf (or (:make-leaf options-map) identity)]
(assoc options-map :make-unexpected
#(make-node ::unexpected [(make-leaf %)])))
options-map)
ops (select-keys options-map [:make-node :make-leaf :make-unexpected])]
^{::options options-map} ; feeling dirty, metadata make me uneasy
(fn self
([s]
(let [a (self core/zero s) b (self a nil)]
(-> (f/stitch a b) (nth 2) f/finish)))
([state s]
(core/step table ops state s)))))
(defn- flatten-rules [rules]
(if (map? rules)
(apply concat rules)
rules))
(defn make-parser [options-map rules]
(-> (apply g/grammar options-map (flatten-rules rules)) core/lr-table core/totalize
core/number-states (stepper options-map)))
(defn parser [options-map & rules]
(let [[options-map rules] (if-not (map? options-map)
[{} (cons options-map rules)]
[options-map rules])]
(make-parser options-map rules)))
(defn unspaced
"Creates an unspaced sequence."
[& specs]
(apply g/unspaced specs))
(defn- memoize-parser [f]
(let [cache (atom nil)]
(fn [input]
(u/cond
[last-result @cache
new-result (f/rebase last-result input)]
(if (identical? last-result new-result)
last-result
(reset! cache new-result))
(reset! cache (f input))))))
(defn- memoize1 [parser s]
(memoize-parser #(parser % s)))
(defn- memoize2 [mpa mpb]
(memoize-parser #(let [a (mpa %)
b (mpb a)]
(f/stitch a b))))
(defn- memoize-1shot [f]
(let [cache (atom [(Object.) nil])]
(fn [& args]
(let [[cargs cr] @cache]
(if (= args cargs)
cr
(let [r (apply f args)]
(reset! cache [args r])
r))))))
(defn- memoize-eof [parser]
(let [mp (memoize1 parser nil)]
(memoize-1shot #(-> (f/stitch % (mp %)) (nth 2) f/finish))))
(defn incremental-buffer
"Creates an empty incremental buffer for the specified parser."
[parser]
{:buffer (t/buffer {:unit #(memoize1 parser %)
:plus memoize2
:chunk #(.split ^String % "(?<=\n)")
:left #(subs %1 0 %2)
:right subs
:cat str})
:eof-parser (memoize-eof parser)
:options (::options (meta parser))})
(defn edit
"Returns a new buffer reflecting the specified edit."
[incremental-buffer offset length s]
(update-in incremental-buffer [:buffer] t/edit offset length s))
(defn parse-tree
"Returns the parse-tree."
[incremental-buffer]
(let [f (t/value (:buffer incremental-buffer))
a (f core/zero)]
((:eof-parser incremental-buffer) a)))
| 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 net.cgrand.parsley
"A total truly incremental parser generator. Grammars are expressed
in a value-based DSL."
(:require [net.cgrand.parsley.lrplus :as core]
[net.cgrand.parsley.fold :as f]
[net.cgrand.parsley.tree :as t]
[net.cgrand.parsley.util :as u]
[net.cgrand.parsley.grammar :as g]))
(defrecord Node [tag content]) ; for memory efficiency
(defn- stepper [table options-map]
(let [options-map (merge
{:make-node #(Node. %1 %2)
:make-leaf nil} ; nil for identity
options-map)
options-map (if-not (:make-unexpected options-map)
(let [make-node (:make-node options-map)
make-leaf (or (:make-leaf options-map) identity)]
(assoc options-map :make-unexpected
#(make-node ::unexpected [(make-leaf %)])))
options-map)
ops (select-keys options-map [:make-node :make-leaf :make-unexpected])]
^{::options options-map} ; feeling dirty, metadata make me uneasy
(fn self
([s]
(let [a (self core/zero s) b (self a nil)]
(-> (f/stitch a b) (nth 2) f/finish)))
([state s]
(core/step table ops state s)))))
(defn- flatten-rules [rules]
(if (map? rules)
(apply concat rules)
rules))
(defn make-parser [options-map rules]
(-> (apply g/grammar options-map (flatten-rules rules)) core/lr-table core/totalize
core/number-states (stepper options-map)))
(defn parser [options-map & rules]
(let [[options-map rules] (if-not (map? options-map)
[{} (cons options-map rules)]
[options-map rules])]
(make-parser options-map rules)))
(defn unspaced
"Creates an unspaced sequence."
[& specs]
(apply g/unspaced specs))
(defn- memoize-parser [f]
(let [cache (atom nil)]
(fn [input]
(u/cond
[last-result @cache
new-result (f/rebase last-result input)]
(if (identical? last-result new-result)
last-result
(reset! cache new-result))
(reset! cache (f input))))))
(defn- memoize1 [parser s]
(memoize-parser #(parser % s)))
(defn- memoize2 [mpa mpb]
(memoize-parser #(let [a (mpa %)
b (mpb a)]
(f/stitch a b))))
(defn- memoize-1shot [f]
(let [cache (atom [(Object.) nil])]
(fn [& args]
(let [[cargs cr] @cache]
(if (= args cargs)
cr
(let [r (apply f args)]
(reset! cache [args r])
r))))))
(defn- memoize-eof [parser]
(let [mp (memoize1 parser nil)]
(memoize-1shot #(-> (f/stitch % (mp %)) (nth 2) f/finish))))
(defn incremental-buffer
"Creates an empty incremental buffer for the specified parser."
[parser]
{:buffer (t/buffer {:unit #(memoize1 parser %)
:plus memoize2
:chunk #(.split ^String % "(?<=\n)")
:left #(subs %1 0 %2)
:right subs
:cat str})
:eof-parser (memoize-eof parser)
:options (::options (meta parser))})
(defn edit
"Returns a new buffer reflecting the specified edit."
[incremental-buffer offset length s]
(update-in incremental-buffer [:buffer] t/edit offset length s))
(defn parse-tree
"Returns the parse-tree."
[incremental-buffer]
(let [f (t/value (:buffer incremental-buffer))
a (f core/zero)]
((:eof-parser incremental-buffer) a)))
|
[
{
"context": "Utilities for Clojure\"\n :url \"https://github.com/xsc/ancient-clj\"\n :license {:name \"MIT\"\n ",
"end": 124,
"score": 0.999566376209259,
"start": 121,
"tag": "USERNAME",
"value": "xsc"
},
{
"context": "ses/mit\"\n :year 2013\n :key \"mit\"}\n\n :dependencies [[org.clojure/clojure \"1.10.3\"",
"end": 300,
"score": 0.8273869156837463,
"start": 297,
"tag": "KEY",
"value": "mit"
},
{
"context": ".check \"1.1.0\"]\n [com.gfredericks/test.chuck \"0.2.10\"]]\n :global-vars ",
"end": 686,
"score": 0.9727185368537903,
"start": 675,
"tag": "USERNAME",
"value": "gfredericks"
}
] | project.clj | xsc/ancient-clj | 4 | (defproject ancient-clj "2.0.1-SNAPSHOT"
:description "Maven Version Utilities for Clojure"
:url "https://github.com/xsc/ancient-clj"
:license {:name "MIT"
:comment "MIT License"
:url "https://choosealicense.com/licenses/mit"
:year 2013
:key "mit"}
:dependencies [[org.clojure/clojure "1.10.3" :scope "provided"]
[clj-commons/pomegranate "1.2.0"]
[version-clj "2.0.1"]
[rewrite-clj "1.0.579-alpha"]
[org.clojure/tools.reader "1.3.5"]]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
: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.tcrawley/dynapath "1.1.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
: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)
| 113106 | (defproject ancient-clj "2.0.1-SNAPSHOT"
:description "Maven Version Utilities for Clojure"
:url "https://github.com/xsc/ancient-clj"
:license {:name "MIT"
:comment "MIT License"
:url "https://choosealicense.com/licenses/mit"
:year 2013
:key "<KEY>"}
:dependencies [[org.clojure/clojure "1.10.3" :scope "provided"]
[clj-commons/pomegranate "1.2.0"]
[version-clj "2.0.1"]
[rewrite-clj "1.0.579-alpha"]
[org.clojure/tools.reader "1.3.5"]]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
: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.tcrawley/dynapath "1.1.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
: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 ancient-clj "2.0.1-SNAPSHOT"
:description "Maven Version Utilities for Clojure"
:url "https://github.com/xsc/ancient-clj"
:license {:name "MIT"
:comment "MIT License"
:url "https://choosealicense.com/licenses/mit"
:year 2013
:key "PI:KEY:<KEY>END_PI"}
:dependencies [[org.clojure/clojure "1.10.3" :scope "provided"]
[clj-commons/pomegranate "1.2.0"]
[version-clj "2.0.1"]
[rewrite-clj "1.0.579-alpha"]
[org.clojure/tools.reader "1.3.5"]]
:profiles {:dev
{:dependencies [[org.clojure/test.check "1.1.0"]
[com.gfredericks/test.chuck "0.2.10"]]
: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.tcrawley/dynapath "1.1.0"]]}
:ci
[:kaocha
{:global-vars {*warn-on-reflection* false}}]}
: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": "ers 1))\n(println (nth '(7 8 9) 0))\n\n(def names '(\"alice\" \"bob\" \"fred\"))\n(println (nth names 0))",
"end": 110,
"score": 0.811069905757904,
"start": 105,
"tag": "NAME",
"value": "alice"
},
{
"context": "(println (nth '(7 8 9) 0))\n\n(def names '(\"alice\" \"bob\" \"fred\"))\n(println (nth names 0))",
"end": 116,
"score": 0.9901160001754761,
"start": 113,
"tag": "NAME",
"value": "bob"
},
{
"context": "ln (nth '(7 8 9) 0))\n\n(def names '(\"alice\" \"bob\" \"fred\"))\n(println (nth names 0))",
"end": 123,
"score": 0.9995343089103699,
"start": 119,
"tag": "NAME",
"value": "fred"
}
] | resources/data.clj | kalkirose/udemy-clojure-introduction | 0 |
(def numbers '(1 2 3 4 5 6 7 8 9))
(println (nth numbers 1))
(println (nth '(7 8 9) 0))
(def names '("alice" "bob" "fred"))
(println (nth names 0)) | 37217 |
(def numbers '(1 2 3 4 5 6 7 8 9))
(println (nth numbers 1))
(println (nth '(7 8 9) 0))
(def names '("<NAME>" "<NAME>" "<NAME>"))
(println (nth names 0)) | true |
(def numbers '(1 2 3 4 5 6 7 8 9))
(println (nth numbers 1))
(println (nth '(7 8 9) 0))
(def names '("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"))
(println (nth names 0)) |
[
{
"context": " :follower-name \"Follower Won\"\n :follower",
"end": 1916,
"score": 0.808807373046875,
"start": 1904,
"tag": "NAME",
"value": "Follower Won"
}
] | specs/untangled/server/protocol_support_spec.clj | untangled-web/server | 22 | (ns untangled.server.protocol-support-spec
(:require
[clojure.test :as t]
[com.stuartsierra.component :as component]
[datomic.api :as d]
[om.next.server :as om]
[taoensso.timbre :as timbre]
[untangled-spec.core :refer [specification behavior provided component assertions]]
[untangled.datomic.core :refer [resolve-ids build-database]]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :refer [make-seeder]]
[untangled.server.core :as core]
[untangled.server.protocol-support :as ps]))
(t/use-fixtures
:once #(timbre/with-merged-config
{:ns-blacklist ["untangled.datomic.*"
"untangled.server.protocol-support"
"untangled.server.impl.components.handler"
"untangled.server.impl.components.config"]}
(%)))
(defn make-old-one [id name madness]
{:db/id id
:old-one/name name
:old-one/madness madness})
(def protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 1" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 1"}]}})
(def bad-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 2" 13.37)]
:db2 [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE" 13.37)]
:db3 [(make-old-one :datomic.id/yog-sothoth "UNSPEAKABLE" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 2"}]}})
(def mutate-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "lululululu" 3.14159)]}
:server-tx '[(old-one/add-follower {:old-one-id :datomic.id/cthulhu
:follower-id :om.tempid/follower1
:follower-name "Follower Won"
:follower-devotion 42.0})
{:old-one [:old-one/name :old-one/followers :db/id]}]
:response {'old-one/add-follower {}
:old-one [{:old-one/name "lululululu",
:old-one/followers [{:db/id :om.tempid/follower1}]
:db/id :datomic.id/cthulhu}]}})
(defn api-read [{:keys [db query]} k params]
;(throw (ex-info "" {:db db}))
(let [conn (:connection db)]
(case k
:old-one {:value (vec (flatten (d/q `[:find (~'pull ?e ~query) :where [?e :old-one/madness]] (d/db conn))))}
nil)))
(defn mutate [env k {:keys [old-one-id follower-id follower-name follower-devotion]}]
(case k
'old-one/add-follower
{:action (fn []
(let [connection (.get-connection (:db env))
follower-tid (d/tempid :db.part/user)
omids->tempids {follower-id follower-tid}]
(try
(let [tx-data [{:db/id follower-tid
:follower/name follower-name
:follower/devotion follower-devotion}
[:db/add old-one-id :old-one/followers follower-tid]]
tempids->realids (:tempids @(d/transact connection tx-data))
omids->realids (resolve-ids (d/db connection) omids->tempids tempids->realids)]
{:tempids omids->realids})
(catch Throwable e
(throw e)))))}
nil))
(defrecord TestApiHandler []
core/Module
(system-key [_] ::api-handler)
(components [_] {})
core/APIHandler
(api-read [_] api-read)
(api-mutate [_] mutate))
(defn api-handler [deps]
(component/using
(map->TestApiHandler {})
deps))
(def test-system
(core/untangled-system
{:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data protocol-support-data))}
:modules [(api-handler [:db])]}))
(def bad-test-system
(core/untangled-system
{:modules [(api-handler [:db :db2 :db3])]
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data bad-protocol-support-data))}}))
(def mutate-test-system
(core/untangled-system
{:modules [(api-handler [:db])]
:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data mutate-protocol-support-data))}}))
(specification "test server response (untangled-system)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-system protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-system bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-system mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db ::api-handler
::core/api-handler :remap-fn
::ps/seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
;; ======= TESTING BACKWARDS COMPATABILITY (make-untangled-test-server) =======
(def test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data protocol-support-data))}))
(def bad-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db :db2 :db3}
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:seeder (make-seeder (:seed-data bad-protocol-support-data))}))
(def mutate-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read :mutate mutate})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data mutate-protocol-support-data))}))
(specification "test server response (make-untangled-test-server)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-server protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-server bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-server mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db :handler :remap-fn :seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
| 122917 | (ns untangled.server.protocol-support-spec
(:require
[clojure.test :as t]
[com.stuartsierra.component :as component]
[datomic.api :as d]
[om.next.server :as om]
[taoensso.timbre :as timbre]
[untangled-spec.core :refer [specification behavior provided component assertions]]
[untangled.datomic.core :refer [resolve-ids build-database]]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :refer [make-seeder]]
[untangled.server.core :as core]
[untangled.server.protocol-support :as ps]))
(t/use-fixtures
:once #(timbre/with-merged-config
{:ns-blacklist ["untangled.datomic.*"
"untangled.server.protocol-support"
"untangled.server.impl.components.handler"
"untangled.server.impl.components.config"]}
(%)))
(defn make-old-one [id name madness]
{:db/id id
:old-one/name name
:old-one/madness madness})
(def protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 1" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 1"}]}})
(def bad-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 2" 13.37)]
:db2 [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE" 13.37)]
:db3 [(make-old-one :datomic.id/yog-sothoth "UNSPEAKABLE" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 2"}]}})
(def mutate-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "lululululu" 3.14159)]}
:server-tx '[(old-one/add-follower {:old-one-id :datomic.id/cthulhu
:follower-id :om.tempid/follower1
:follower-name "<NAME>"
:follower-devotion 42.0})
{:old-one [:old-one/name :old-one/followers :db/id]}]
:response {'old-one/add-follower {}
:old-one [{:old-one/name "lululululu",
:old-one/followers [{:db/id :om.tempid/follower1}]
:db/id :datomic.id/cthulhu}]}})
(defn api-read [{:keys [db query]} k params]
;(throw (ex-info "" {:db db}))
(let [conn (:connection db)]
(case k
:old-one {:value (vec (flatten (d/q `[:find (~'pull ?e ~query) :where [?e :old-one/madness]] (d/db conn))))}
nil)))
(defn mutate [env k {:keys [old-one-id follower-id follower-name follower-devotion]}]
(case k
'old-one/add-follower
{:action (fn []
(let [connection (.get-connection (:db env))
follower-tid (d/tempid :db.part/user)
omids->tempids {follower-id follower-tid}]
(try
(let [tx-data [{:db/id follower-tid
:follower/name follower-name
:follower/devotion follower-devotion}
[:db/add old-one-id :old-one/followers follower-tid]]
tempids->realids (:tempids @(d/transact connection tx-data))
omids->realids (resolve-ids (d/db connection) omids->tempids tempids->realids)]
{:tempids omids->realids})
(catch Throwable e
(throw e)))))}
nil))
(defrecord TestApiHandler []
core/Module
(system-key [_] ::api-handler)
(components [_] {})
core/APIHandler
(api-read [_] api-read)
(api-mutate [_] mutate))
(defn api-handler [deps]
(component/using
(map->TestApiHandler {})
deps))
(def test-system
(core/untangled-system
{:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data protocol-support-data))}
:modules [(api-handler [:db])]}))
(def bad-test-system
(core/untangled-system
{:modules [(api-handler [:db :db2 :db3])]
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data bad-protocol-support-data))}}))
(def mutate-test-system
(core/untangled-system
{:modules [(api-handler [:db])]
:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data mutate-protocol-support-data))}}))
(specification "test server response (untangled-system)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-system protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-system bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-system mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db ::api-handler
::core/api-handler :remap-fn
::ps/seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
;; ======= TESTING BACKWARDS COMPATABILITY (make-untangled-test-server) =======
(def test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data protocol-support-data))}))
(def bad-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db :db2 :db3}
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:seeder (make-seeder (:seed-data bad-protocol-support-data))}))
(def mutate-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read :mutate mutate})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data mutate-protocol-support-data))}))
(specification "test server response (make-untangled-test-server)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-server protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-server bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-server mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db :handler :remap-fn :seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
| true | (ns untangled.server.protocol-support-spec
(:require
[clojure.test :as t]
[com.stuartsierra.component :as component]
[datomic.api :as d]
[om.next.server :as om]
[taoensso.timbre :as timbre]
[untangled-spec.core :refer [specification behavior provided component assertions]]
[untangled.datomic.core :refer [resolve-ids build-database]]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :refer [make-seeder]]
[untangled.server.core :as core]
[untangled.server.protocol-support :as ps]))
(t/use-fixtures
:once #(timbre/with-merged-config
{:ns-blacklist ["untangled.datomic.*"
"untangled.server.protocol-support"
"untangled.server.impl.components.handler"
"untangled.server.impl.components.config"]}
(%)))
(defn make-old-one [id name madness]
{:db/id id
:old-one/name name
:old-one/madness madness})
(def protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 1" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 1"}]}})
(def bad-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE 2" 13.37)]
:db2 [(make-old-one :datomic.id/cthulhu "UNSPEAKABLE" 13.37)]
:db3 [(make-old-one :datomic.id/yog-sothoth "UNSPEAKABLE" 13.37)]}
:server-tx [{:old-one [:old-one/name]}]
:response {:old-one [{:old-one/name "UNSPEAKABLE 2"}]}})
(def mutate-protocol-support-data
{:seed-data {:db [(make-old-one :datomic.id/cthulhu "lululululu" 3.14159)]}
:server-tx '[(old-one/add-follower {:old-one-id :datomic.id/cthulhu
:follower-id :om.tempid/follower1
:follower-name "PI:NAME:<NAME>END_PI"
:follower-devotion 42.0})
{:old-one [:old-one/name :old-one/followers :db/id]}]
:response {'old-one/add-follower {}
:old-one [{:old-one/name "lululululu",
:old-one/followers [{:db/id :om.tempid/follower1}]
:db/id :datomic.id/cthulhu}]}})
(defn api-read [{:keys [db query]} k params]
;(throw (ex-info "" {:db db}))
(let [conn (:connection db)]
(case k
:old-one {:value (vec (flatten (d/q `[:find (~'pull ?e ~query) :where [?e :old-one/madness]] (d/db conn))))}
nil)))
(defn mutate [env k {:keys [old-one-id follower-id follower-name follower-devotion]}]
(case k
'old-one/add-follower
{:action (fn []
(let [connection (.get-connection (:db env))
follower-tid (d/tempid :db.part/user)
omids->tempids {follower-id follower-tid}]
(try
(let [tx-data [{:db/id follower-tid
:follower/name follower-name
:follower/devotion follower-devotion}
[:db/add old-one-id :old-one/followers follower-tid]]
tempids->realids (:tempids @(d/transact connection tx-data))
omids->realids (resolve-ids (d/db connection) omids->tempids tempids->realids)]
{:tempids omids->realids})
(catch Throwable e
(throw e)))))}
nil))
(defrecord TestApiHandler []
core/Module
(system-key [_] ::api-handler)
(components [_] {})
core/APIHandler
(api-read [_] api-read)
(api-mutate [_] mutate))
(defn api-handler [deps]
(component/using
(map->TestApiHandler {})
deps))
(def test-system
(core/untangled-system
{:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data protocol-support-data))}
:modules [(api-handler [:db])]}))
(def bad-test-system
(core/untangled-system
{:modules [(api-handler [:db :db2 :db3])]
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data bad-protocol-support-data))}}))
(def mutate-test-system
(core/untangled-system
{:modules [(api-handler [:db])]
:components {:db (build-database :protocol-support)
:config (core/new-config "test.edn")
::ps/seeder (make-seeder (:seed-data mutate-protocol-support-data))}}))
(specification "test server response (untangled-system)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-system protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-system bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-system mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db ::api-handler
::core/api-handler :remap-fn
::ps/seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
;; ======= TESTING BACKWARDS COMPATABILITY (make-untangled-test-server) =======
(def test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data protocol-support-data))}))
(def bad-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read})
:parser-injections #{:db :db2 :db3}
:components {:db (build-database :protocol-support)
:db2 (build-database :protocol-support-2)
:db3 (build-database :protocol-support-3)
:seeder (make-seeder (:seed-data bad-protocol-support-data))}))
(def mutate-test-server
(core/make-untangled-test-server
:parser (om/parser {:read api-read :mutate mutate})
:parser-injections #{:db}
:components {:db (build-database :protocol-support)
:seeder (make-seeder (:seed-data mutate-protocol-support-data))}))
(specification "test server response (make-untangled-test-server)"
(behavior "test server response w/ protocol data"
(ps/check-response-to-client test-server protocol-support-data))
(behavior "test server response w/ bad protocol data"
(assertions
(ps/check-response-to-client bad-test-server bad-protocol-support-data)
=throws=> (AssertionError #"seed data tempids must have no overlap")))
(behavior "test server response w/ mutate protocol data"
(ps/check-response-to-client mutate-test-server mutate-protocol-support-data
:on-success (fn [system resp]
(assertions
(set (keys system)) => #{:config :db :handler :remap-fn :seeder}
"seed data is put inside each database"
(keys (:seed-result (udb/get-info (:db system))))
=> [:datomic.id/cthulhu])))))
|
[
{
"context": "stributed filesystem.\"\n :url \"https://github.com/nathanmarz/dfs-datastores\"\n :license {:name \"Eclipse Public",
"end": 351,
"score": 0.996612548828125,
"start": 341,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": "g}}\n :scm {:connection \"scm:git:git://github.com/nathanmarz/dfs-datastores.git\"\n :developerConnection ",
"end": 1111,
"score": 0.9991946220397949,
"start": 1101,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": "developerConnection \"scm:git:ssh://git@github.com/nathanmarz/dfs-datastores.git\"\n :url \"https://github.",
"end": 1201,
"score": 0.9990017414093018,
"start": 1191,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": "-datastores.git\"\n :url \"https://github.com/nathanmarz/dfs-datastores\"\n :dir \"..\"}\n :pom-additio",
"end": 1265,
"score": 0.9972659945487976,
"start": 1255,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": " [:developer\n [:name \"Nathan Marz\"]\n [:url \"http://twitter.com/nat",
"end": 1396,
"score": 0.9998680353164673,
"start": 1385,
"tag": "NAME",
"value": "Nathan Marz"
},
{
"context": "arz\"]\n [:url \"http://twitter.com/nathanmarz\"]]\n [:developer\n ",
"end": 1453,
"score": 0.9994705319404602,
"start": 1443,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": " [:developer\n [:name \"Soren Macbeth\"]\n [:url \"http://twitter.com/sor",
"end": 1525,
"score": 0.9998995065689087,
"start": 1512,
"tag": "NAME",
"value": "Soren Macbeth"
},
{
"context": "eth\"]\n [:url \"http://twitter.com/sorenmacbeth\"]]\n [:developer\n ",
"end": 1584,
"score": 0.9995664358139038,
"start": 1572,
"tag": "USERNAME",
"value": "sorenmacbeth"
},
{
"context": " [:developer\n [:name \"Sam Ritchie\"]\n [:url \"http://twitter.com/sri",
"end": 1654,
"score": 0.9999036192893982,
"start": 1643,
"tag": "NAME",
"value": "Sam Ritchie"
},
{
"context": "hie\"]\n [:url \"http://twitter.com/sritchie\"]]]\n :javac-options [\"-source\" \"1.6\" \"-target\" \"",
"end": 1709,
"score": 0.9996907114982605,
"start": 1701,
"tag": "USERNAME",
"value": "sritchie"
}
] | dfs-datastores-cascading/project.clj | cchepelov/dfs-datastores | 102 | (def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp))
(defproject com.backtype/dfs-datastores-cascading VERSION
:description "Dead-simple vertical partitioning, compression, appends, and consolidation of data on a distributed filesystem."
:url "https://github.com/nathanmarz/dfs-datastores"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[com.backtype/dfs-datastores ~VERSION]
[org.slf4j/slf4j-log4j12 "1.6.6"]
[cascading/cascading-hadoop "2.5.3"
:exclusions [org.apache.hadoop/hadoop-core]]]
:repositories {"conjars" "http://conjars.org/repo"}
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}}
:scm {:connection "scm:git:git://github.com/nathanmarz/dfs-datastores.git"
:developerConnection "scm:git:ssh://git@github.com/nathanmarz/dfs-datastores.git"
:url "https://github.com/nathanmarz/dfs-datastores"
:dir ".."}
:pom-addition [:developers
[:developer
[:name "Nathan Marz"]
[:url "http://twitter.com/nathanmarz"]]
[:developer
[:name "Soren Macbeth"]
[:url "http://twitter.com/sorenmacbeth"]]
[:developer
[:name "Sam Ritchie"]
[:url "http://twitter.com/sritchie"]]]
:javac-options ["-source" "1.6" "-target" "1.6"]
:java-source-paths ["src/main/java" "src/test/java"]
:junit ["src/test/java"]
:profiles {:dev
{:plugins [[lein-junit "1.1.5"]]}
:provided
{:dependencies [[org.apache.hadoop/hadoop-core "1.2.1"]]}}
:classifiers {:javadoc {:java-source-paths ^:replace []
:source-paths ^:replace []
:resource-paths ^:replace []}
:sources {:java-source-paths ^:replace []
:resource-paths ^:replace []}})
| 25301 | (def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp))
(defproject com.backtype/dfs-datastores-cascading VERSION
:description "Dead-simple vertical partitioning, compression, appends, and consolidation of data on a distributed filesystem."
:url "https://github.com/nathanmarz/dfs-datastores"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[com.backtype/dfs-datastores ~VERSION]
[org.slf4j/slf4j-log4j12 "1.6.6"]
[cascading/cascading-hadoop "2.5.3"
:exclusions [org.apache.hadoop/hadoop-core]]]
:repositories {"conjars" "http://conjars.org/repo"}
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}}
:scm {:connection "scm:git:git://github.com/nathanmarz/dfs-datastores.git"
:developerConnection "scm:git:ssh://git@github.com/nathanmarz/dfs-datastores.git"
:url "https://github.com/nathanmarz/dfs-datastores"
:dir ".."}
:pom-addition [:developers
[:developer
[:name "<NAME>"]
[:url "http://twitter.com/nathanmarz"]]
[:developer
[:name "<NAME>"]
[:url "http://twitter.com/sorenmacbeth"]]
[:developer
[:name "<NAME>"]
[:url "http://twitter.com/sritchie"]]]
:javac-options ["-source" "1.6" "-target" "1.6"]
:java-source-paths ["src/main/java" "src/test/java"]
:junit ["src/test/java"]
:profiles {:dev
{:plugins [[lein-junit "1.1.5"]]}
:provided
{:dependencies [[org.apache.hadoop/hadoop-core "1.2.1"]]}}
:classifiers {:javadoc {:java-source-paths ^:replace []
:source-paths ^:replace []
:resource-paths ^:replace []}
:sources {:java-source-paths ^:replace []
:resource-paths ^:replace []}})
| true | (def ROOT-DIR (subs *file* 0 (- (count *file*) (count "project.clj"))))
(def VERSION (-> ROOT-DIR (str "/../VERSION") slurp))
(defproject com.backtype/dfs-datastores-cascading VERSION
:description "Dead-simple vertical partitioning, compression, appends, and consolidation of data on a distributed filesystem."
:url "https://github.com/nathanmarz/dfs-datastores"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[com.backtype/dfs-datastores ~VERSION]
[org.slf4j/slf4j-log4j12 "1.6.6"]
[cascading/cascading-hadoop "2.5.3"
:exclusions [org.apache.hadoop/hadoop-core]]]
:repositories {"conjars" "http://conjars.org/repo"}
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}}
:scm {:connection "scm:git:git://github.com/nathanmarz/dfs-datastores.git"
:developerConnection "scm:git:ssh://git@github.com/nathanmarz/dfs-datastores.git"
:url "https://github.com/nathanmarz/dfs-datastores"
:dir ".."}
:pom-addition [:developers
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://twitter.com/nathanmarz"]]
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://twitter.com/sorenmacbeth"]]
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://twitter.com/sritchie"]]]
:javac-options ["-source" "1.6" "-target" "1.6"]
:java-source-paths ["src/main/java" "src/test/java"]
:junit ["src/test/java"]
:profiles {:dev
{:plugins [[lein-junit "1.1.5"]]}
:provided
{:dependencies [[org.apache.hadoop/hadoop-core "1.2.1"]]}}
:classifiers {:javadoc {:java-source-paths ^:replace []
:source-paths ^:replace []
:resource-paths ^:replace []}
:sources {:java-source-paths ^:replace []
:resource-paths ^:replace []}})
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow",
"end": 25,
"score": 0.9998520016670227,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>",
"end": 44,
"score": 0.9999348521232605,
"start": 28,
"tag": "EMAIL",
"value": "adam@opscode.com"
},
{
"context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2",
"end": 76,
"score": 0.9997496008872986,
"start": 59,
"tag": "NAME",
"value": "Christopher Brown"
},
{
"context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.",
"end": 93,
"score": 0.9999340176582336,
"start": 79,
"tag": "EMAIL",
"value": "cb@opscode.com"
}
] | src/omnibus/s3.clj | racker/omnibus | 2 | ;;
;; Author:: Adam Jacob (<adam@opscode.com>)
;; Author:: Christopher Brown (<cb@opscode.com>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns omnibus.s3
(:use [omnibus.log]
[clojure.contrib.logging :only [log]])
(:import [org.jets3t.service.security AWSCredentials]
[org.jets3t.service.impl.rest.httpclient RestS3Service]
[org.jets3t.service.acl AccessControlList]
[java.io File]
[org.jets3t.service.model S3Object])
(:gen-class))
(defn put-in-bucket
"Place the resulting file in an S3 bucket"
[filename bucket-name file-key access-key secret-access-key]
(let [s3 (RestS3Service. (AWSCredentials. access-key secret-access-key))
s3obj (S3Object. (File. filename))
s3bucket (. s3 getBucket bucket-name)]
(. s3obj setAcl AccessControlList/REST_CANNED_PUBLIC_READ)
(. s3obj setKey file-key)
(. s3 putObject s3bucket s3obj)))
| 69847 | ;;
;; Author:: <NAME> (<<EMAIL>>)
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns omnibus.s3
(:use [omnibus.log]
[clojure.contrib.logging :only [log]])
(:import [org.jets3t.service.security AWSCredentials]
[org.jets3t.service.impl.rest.httpclient RestS3Service]
[org.jets3t.service.acl AccessControlList]
[java.io File]
[org.jets3t.service.model S3Object])
(:gen-class))
(defn put-in-bucket
"Place the resulting file in an S3 bucket"
[filename bucket-name file-key access-key secret-access-key]
(let [s3 (RestS3Service. (AWSCredentials. access-key secret-access-key))
s3obj (S3Object. (File. filename))
s3bucket (. s3 getBucket bucket-name)]
(. s3obj setAcl AccessControlList/REST_CANNED_PUBLIC_READ)
(. s3obj setKey file-key)
(. s3 putObject s3bucket s3obj)))
| true | ;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns omnibus.s3
(:use [omnibus.log]
[clojure.contrib.logging :only [log]])
(:import [org.jets3t.service.security AWSCredentials]
[org.jets3t.service.impl.rest.httpclient RestS3Service]
[org.jets3t.service.acl AccessControlList]
[java.io File]
[org.jets3t.service.model S3Object])
(:gen-class))
(defn put-in-bucket
"Place the resulting file in an S3 bucket"
[filename bucket-name file-key access-key secret-access-key]
(let [s3 (RestS3Service. (AWSCredentials. access-key secret-access-key))
s3obj (S3Object. (File. filename))
s3bucket (. s3 getBucket bucket-name)]
(. s3obj setAcl AccessControlList/REST_CANNED_PUBLIC_READ)
(. s3obj setKey file-key)
(. s3 putObject s3bucket s3obj)))
|
[
{
"context": "piano])\n (:require [polynome.core :as poly]))\n\n;;Erik Satie Gnossienne No. 1\n\n(def phrase1a [:iii :v :iv# :iii :iii :ii#",
"end": 137,
"score": 0.9998772740364075,
"start": 116,
"tag": "NAME",
"value": "Erik Satie Gnossienne"
}
] | examples/satie.clj | samaaron/overtone | 2 | (ns examples.satie
(:use [overtone.live]
[overtone.inst piano])
(:require [polynome.core :as poly]))
;;Erik Satie Gnossienne No. 1
(def phrase1a [:iii :v :iv# :iii :iii :ii# :iii :ii#])
(def phrase1b [:iii :v :iv# :iii :v# :vi :v# :vi])
(def phrase1c [:iii :v :iv# :iii :iii :ii# :i :vii- :vi- :vii- :vi- :vii- :i :vii- :vii- :vi-])
(def phrase2 [:i :ii :i :vii- :i :ii :i :vii- :i :vii- :vii- :vi-])
(def phrase3 [:iii :iv# :v# :vi :vii :ii#+ :vii :vi :vii :vi :vii :vi :vi :v# :iv :iii :iii :ii# :i :vii- :vii- :vi-])
(def phrase1a-reprise [:iii :v :iv# :iii :iii :ii#])
(def phrase1b-reprise [:iii :v :iv# :iii :v# :vi])
(def phrase1-bass [:vi--- [:vi- :iii- :i-] [:vi- :iii- :i-]])
(def phrase2-bass [:iii-- [:iii- :vii-- :v--] [:iii- :vii-- :v--]])
(def phrase3-bass [:ii--- [:vi-- :ii- :iv-] [:vi-- :ii- :iv-]])
(def right-hand-degrees (concat phrase1a phrase1b phrase1c
phrase1a phrase1b phrase1c
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2
phrase1a-reprise
phrase1b-reprise
phrase1a-reprise
phrase1b-reprise
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2))
(def left-hand-degrees (concat (apply concat (repeat 6 phrase1-bass)) ;;A
phrase2-bass ;;B
(apply concat (repeat 8 phrase1-bass)) ;;C
phrase2-bass ;;D
(apply concat (repeat 2 phrase1-bass)) ;;E
(apply concat (repeat 2 phrase3-bass)) ;;F
(apply concat (repeat 2 phrase1-bass)) ;;G
(apply concat (repeat 2 phrase3-bass)) ;;H
(apply concat (repeat 14 phrase1-bass)) ;;I
(apply concat (repeat 2 phrase3-bass)) ;;J
(apply concat (repeat 2 phrase1-bass)) ;;K
(apply concat (repeat 2 phrase3-bass)) ;;L
(apply concat (repeat 10 phrase1-bass)) ;;M
(apply concat (repeat 2 phrase3-bass)) ;;N
(apply concat (repeat 2 phrase1-bass)) ;;O
(apply concat (repeat 2 phrase3-bass)) ;;P
(apply concat (repeat 14 phrase1-bass)) ;;Q
(apply concat (repeat 2 phrase3-bass)) ;;R
(apply concat (repeat 2 phrase1-bass)) ;;S
(apply concat (repeat 2 phrase3-bass)) ;;T
phrase1-bass ;;U
))
(def lh-pitches (degrees->pitches left-hand-degrees :major :Ab4))
(def rh-pitches (degrees->pitches right-hand-degrees :major :Ab4))
(def cur-pitch-rh (atom -1))
(def cur-pitch-lh (atom -1))
(defn reset-pos
[]
(reset! cur-pitch-rh -1)
(reset! cur-pitch-lh -1))
(defn play-next-rh
[vol]
(let [idx (swap! cur-pitch-rh inc)
pitch (nth (cycle rh-pitches) idx)]
(piano :note pitch :vel vol)))
(defn play-next-lh
[vol]
(let [idx (swap! cur-pitch-lh inc)
pitch (nth (cycle lh-pitches) idx)]
(if (sequential? pitch)
(doseq [p pitch]
(piano :note p :vel vol))
(piano :note pitch :vel vol))))
(def m (poly/init "/dev/tty.usbserial-m64-0790"))
(poly/on-press m (fn [x y s]
(if (= 7 x)
(reset-pos)
(do
(if (< 5 y)
(play-next-rh (+ (rand-int 5) (* 12 (+ x 4))))
(play-next-lh (+ (rand-int 5) (* 12 (+ x 4)))))
(poly/led-on m x y)))
(println [x y])))
(poly/on-release m (fn [x y s]
(poly/led-off m x y)))
;;(poly/remove-all-callbacks m)
| 92318 | (ns examples.satie
(:use [overtone.live]
[overtone.inst piano])
(:require [polynome.core :as poly]))
;;<NAME> No. 1
(def phrase1a [:iii :v :iv# :iii :iii :ii# :iii :ii#])
(def phrase1b [:iii :v :iv# :iii :v# :vi :v# :vi])
(def phrase1c [:iii :v :iv# :iii :iii :ii# :i :vii- :vi- :vii- :vi- :vii- :i :vii- :vii- :vi-])
(def phrase2 [:i :ii :i :vii- :i :ii :i :vii- :i :vii- :vii- :vi-])
(def phrase3 [:iii :iv# :v# :vi :vii :ii#+ :vii :vi :vii :vi :vii :vi :vi :v# :iv :iii :iii :ii# :i :vii- :vii- :vi-])
(def phrase1a-reprise [:iii :v :iv# :iii :iii :ii#])
(def phrase1b-reprise [:iii :v :iv# :iii :v# :vi])
(def phrase1-bass [:vi--- [:vi- :iii- :i-] [:vi- :iii- :i-]])
(def phrase2-bass [:iii-- [:iii- :vii-- :v--] [:iii- :vii-- :v--]])
(def phrase3-bass [:ii--- [:vi-- :ii- :iv-] [:vi-- :ii- :iv-]])
(def right-hand-degrees (concat phrase1a phrase1b phrase1c
phrase1a phrase1b phrase1c
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2
phrase1a-reprise
phrase1b-reprise
phrase1a-reprise
phrase1b-reprise
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2))
(def left-hand-degrees (concat (apply concat (repeat 6 phrase1-bass)) ;;A
phrase2-bass ;;B
(apply concat (repeat 8 phrase1-bass)) ;;C
phrase2-bass ;;D
(apply concat (repeat 2 phrase1-bass)) ;;E
(apply concat (repeat 2 phrase3-bass)) ;;F
(apply concat (repeat 2 phrase1-bass)) ;;G
(apply concat (repeat 2 phrase3-bass)) ;;H
(apply concat (repeat 14 phrase1-bass)) ;;I
(apply concat (repeat 2 phrase3-bass)) ;;J
(apply concat (repeat 2 phrase1-bass)) ;;K
(apply concat (repeat 2 phrase3-bass)) ;;L
(apply concat (repeat 10 phrase1-bass)) ;;M
(apply concat (repeat 2 phrase3-bass)) ;;N
(apply concat (repeat 2 phrase1-bass)) ;;O
(apply concat (repeat 2 phrase3-bass)) ;;P
(apply concat (repeat 14 phrase1-bass)) ;;Q
(apply concat (repeat 2 phrase3-bass)) ;;R
(apply concat (repeat 2 phrase1-bass)) ;;S
(apply concat (repeat 2 phrase3-bass)) ;;T
phrase1-bass ;;U
))
(def lh-pitches (degrees->pitches left-hand-degrees :major :Ab4))
(def rh-pitches (degrees->pitches right-hand-degrees :major :Ab4))
(def cur-pitch-rh (atom -1))
(def cur-pitch-lh (atom -1))
(defn reset-pos
[]
(reset! cur-pitch-rh -1)
(reset! cur-pitch-lh -1))
(defn play-next-rh
[vol]
(let [idx (swap! cur-pitch-rh inc)
pitch (nth (cycle rh-pitches) idx)]
(piano :note pitch :vel vol)))
(defn play-next-lh
[vol]
(let [idx (swap! cur-pitch-lh inc)
pitch (nth (cycle lh-pitches) idx)]
(if (sequential? pitch)
(doseq [p pitch]
(piano :note p :vel vol))
(piano :note pitch :vel vol))))
(def m (poly/init "/dev/tty.usbserial-m64-0790"))
(poly/on-press m (fn [x y s]
(if (= 7 x)
(reset-pos)
(do
(if (< 5 y)
(play-next-rh (+ (rand-int 5) (* 12 (+ x 4))))
(play-next-lh (+ (rand-int 5) (* 12 (+ x 4)))))
(poly/led-on m x y)))
(println [x y])))
(poly/on-release m (fn [x y s]
(poly/led-off m x y)))
;;(poly/remove-all-callbacks m)
| true | (ns examples.satie
(:use [overtone.live]
[overtone.inst piano])
(:require [polynome.core :as poly]))
;;PI:NAME:<NAME>END_PI No. 1
(def phrase1a [:iii :v :iv# :iii :iii :ii# :iii :ii#])
(def phrase1b [:iii :v :iv# :iii :v# :vi :v# :vi])
(def phrase1c [:iii :v :iv# :iii :iii :ii# :i :vii- :vi- :vii- :vi- :vii- :i :vii- :vii- :vi-])
(def phrase2 [:i :ii :i :vii- :i :ii :i :vii- :i :vii- :vii- :vi-])
(def phrase3 [:iii :iv# :v# :vi :vii :ii#+ :vii :vi :vii :vi :vii :vi :vi :v# :iv :iii :iii :ii# :i :vii- :vii- :vi-])
(def phrase1a-reprise [:iii :v :iv# :iii :iii :ii#])
(def phrase1b-reprise [:iii :v :iv# :iii :v# :vi])
(def phrase1-bass [:vi--- [:vi- :iii- :i-] [:vi- :iii- :i-]])
(def phrase2-bass [:iii-- [:iii- :vii-- :v--] [:iii- :vii-- :v--]])
(def phrase3-bass [:ii--- [:vi-- :ii- :iv-] [:vi-- :ii- :iv-]])
(def right-hand-degrees (concat phrase1a phrase1b phrase1c
phrase1a phrase1b phrase1c
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2
phrase1a-reprise
phrase1b-reprise
phrase1a-reprise
phrase1b-reprise
phrase2
phrase2
phrase3
phrase3
phrase2
phrase2))
(def left-hand-degrees (concat (apply concat (repeat 6 phrase1-bass)) ;;A
phrase2-bass ;;B
(apply concat (repeat 8 phrase1-bass)) ;;C
phrase2-bass ;;D
(apply concat (repeat 2 phrase1-bass)) ;;E
(apply concat (repeat 2 phrase3-bass)) ;;F
(apply concat (repeat 2 phrase1-bass)) ;;G
(apply concat (repeat 2 phrase3-bass)) ;;H
(apply concat (repeat 14 phrase1-bass)) ;;I
(apply concat (repeat 2 phrase3-bass)) ;;J
(apply concat (repeat 2 phrase1-bass)) ;;K
(apply concat (repeat 2 phrase3-bass)) ;;L
(apply concat (repeat 10 phrase1-bass)) ;;M
(apply concat (repeat 2 phrase3-bass)) ;;N
(apply concat (repeat 2 phrase1-bass)) ;;O
(apply concat (repeat 2 phrase3-bass)) ;;P
(apply concat (repeat 14 phrase1-bass)) ;;Q
(apply concat (repeat 2 phrase3-bass)) ;;R
(apply concat (repeat 2 phrase1-bass)) ;;S
(apply concat (repeat 2 phrase3-bass)) ;;T
phrase1-bass ;;U
))
(def lh-pitches (degrees->pitches left-hand-degrees :major :Ab4))
(def rh-pitches (degrees->pitches right-hand-degrees :major :Ab4))
(def cur-pitch-rh (atom -1))
(def cur-pitch-lh (atom -1))
(defn reset-pos
[]
(reset! cur-pitch-rh -1)
(reset! cur-pitch-lh -1))
(defn play-next-rh
[vol]
(let [idx (swap! cur-pitch-rh inc)
pitch (nth (cycle rh-pitches) idx)]
(piano :note pitch :vel vol)))
(defn play-next-lh
[vol]
(let [idx (swap! cur-pitch-lh inc)
pitch (nth (cycle lh-pitches) idx)]
(if (sequential? pitch)
(doseq [p pitch]
(piano :note p :vel vol))
(piano :note pitch :vel vol))))
(def m (poly/init "/dev/tty.usbserial-m64-0790"))
(poly/on-press m (fn [x y s]
(if (= 7 x)
(reset-pos)
(do
(if (< 5 y)
(play-next-rh (+ (rand-int 5) (* 12 (+ x 4))))
(play-next-lh (+ (rand-int 5) (* 12 (+ x 4)))))
(poly/led-on m x y)))
(println [x y])))
(poly/on-release m (fn [x y s]
(poly/led-off m x y)))
;;(poly/remove-all-callbacks m)
|
[
{
"context": "r constructor works\"\n (let [test-user (new-user \"Mark\" \"Mandel\" \"email\" \"password\")]\n (:id test-user",
"end": 68,
"score": 0.9987394213676453,
"start": 64,
"tag": "NAME",
"value": "Mark"
},
{
"context": "ructor works\"\n (let [test-user (new-user \"Mark\" \"Mandel\" \"email\" \"password\")]\n (:id test-user) => trut",
"end": 77,
"score": 0.9994699358940125,
"start": 71,
"tag": "NAME",
"value": "Mandel"
},
{
"context": "st-user) => truthy\n (:firstname test-user) => \"Mark\"\n (:lastname test-user) => \"Mandel\"\n (:pass",
"end": 165,
"score": 0.9990318417549133,
"start": 161,
"tag": "NAME",
"value": "Mark"
},
{
"context": "est-user) => \"Mark\"\n (:lastname test-user) => \"Mandel\"\n (:password<caret> test-user) => \"password\"\n ",
"end": 203,
"score": 0.9993224143981934,
"start": 197,
"tag": "NAME",
"value": "Mandel"
},
{
"context": " => \"Mandel\"\n (:password<caret> test-user) => \"password\"\n (:email test-user) => \"email\"\n (:photo te",
"end": 250,
"score": 0.9974672198295593,
"start": 242,
"tag": "PASSWORD",
"value": "password"
}
] | testdata/refactoring/MultiBody.clj | JetBrains/la-clojure | 91 | (fact
"Better constructor works"
(let [test-user (new-user "Mark" "Mandel" "email" "password")]
(:id test-user) => truthy
(:firstname test-user) => "Mark"
(:lastname test-user) => "Mandel"
(:password<caret> test-user) => "password"
(:email test-user) => "email"
(:photo test-user) => nil
(:last-logged-in test-user) => nil
)
) | 78153 | (fact
"Better constructor works"
(let [test-user (new-user "<NAME>" "<NAME>" "email" "password")]
(:id test-user) => truthy
(:firstname test-user) => "<NAME>"
(:lastname test-user) => "<NAME>"
(:password<caret> test-user) => "<PASSWORD>"
(:email test-user) => "email"
(:photo test-user) => nil
(:last-logged-in test-user) => nil
)
) | true | (fact
"Better constructor works"
(let [test-user (new-user "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "email" "password")]
(:id test-user) => truthy
(:firstname test-user) => "PI:NAME:<NAME>END_PI"
(:lastname test-user) => "PI:NAME:<NAME>END_PI"
(:password<caret> test-user) => "PI:PASSWORD:<PASSWORD>END_PI"
(:email test-user) => "email"
(:photo test-user) => nil
(:last-logged-in test-user) => nil
)
) |
[
{
"context": "tor `valid-email?)\n (f/html5-input :password \"password\" :validator `f/minmax-length? :validator-args {:m",
"end": 1704,
"score": 0.9992656707763672,
"start": 1696,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ":min 7 :max 100})\n (f/html5-input :password2 \"password\")\n (f/on-form-change `check-passwords-match)]",
"end": 1810,
"score": 0.9991558790206909,
"start": 1802,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "r [this]\n (let [{:keys [uid name email password password2 ui/password-error ui/create-failed] :as form} (om",
"end": 2976,
"score": 0.9285076856613159,
"start": 2967,
"tag": "PASSWORD",
"value": "password2"
},
{
"context": "m-field this form :name :className className :id \"username\"))}\n (tr \"Name\"))\n ",
"end": 4136,
"score": 0.9987861514091492,
"start": 4128,
"tag": "USERNAME",
"value": "username"
}
] | src/main/movie_database/ui/new_user.cljc | andrewbeach/movie-database | 0 | (ns movie-database.ui.new-user
(:require [om.next :as om :refer [defui]]
[fulcro.client.core :as u]
[om.dom :as dom]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.i18n :refer [tr]]
[fulcro.events :as evts]
[fulcro.ui.forms :as f]
[fulcro.ui.bootstrap3 :as b]
[fulcro.client.core :as uc]
[fulcro.client.data-fetch :as df]
[movie-database.ui.html5-routing :as r]))
(defmutation check-passwords-match
[{:keys [form-id field kind]}]
(action [{:keys [state]}]
(when (and (= :password2 field) (= kind :blur))
(let [form (get-in @state form-id)
a (f/current-value form :password)
b (f/current-value form :password2)]
(if (and a b (pos? (.-length a)) (pos? (.-length b)) (not= a b))
(swap! state update-in form-id assoc :ui/password-error (tr "Passwords must match"))
(swap! state update-in form-id assoc :ui/password-error nil))))))
(defmutation create-user-failed
[{:keys [id error]}]
(action [{:keys [state]}]
(swap! state assoc-in [:user/by-id id :ui/create-failed] true)))
(f/defvalidator valid-email?
[_ value args] ; crappy regex for email...but you get the point
(seq (re-matches #"^[^ @]+@[^ ]+[.a-zA-Z0-9]*[a-zA-Z]$" value)))
(declare UserForm)
(defui ^:once UserForm
static f/IForm
(form-spec [this]
[(f/id-field :uid)
(f/text-input :name :validator `f/not-empty?)
; TODO: add username in use check against server
(f/html5-input :email "email" :validator `valid-email?)
(f/html5-input :password "password" :validator `f/minmax-length? :validator-args {:min 7 :max 100})
(f/html5-input :password2 "password")
(f/on-form-change `check-passwords-match)])
static u/InitialAppState
(initial-state [this params] {:uid (om/tempid) :name "" :password "" :password2 ""})
static om/IQuery
(query [this] [:ui/create-failed :uid :name :email :password :password2 :ui/password-error f/form-root-key f/form-key])
static om/Ident
(ident [this props] [:user/by-id (:uid props)])
Object
; SSR state cannot properly initialize forms, so we ensure it is initialized on mount. This mutation is safe
; to run on an already initialized form, but we only do it once since the extra transact is not necessary
; and would be distracting in the logs.
(componentWillReceiveProps [this props] ; on return to this screen once cleared
(when (or (f/server-initialized? props) (not (f/is-form? props)))
(om/transact! this `[(f/initialize-form {})])))
(componentWillMount [this] ; on initial from server
(when (or (f/server-initialized? (om/props this)) (not (f/is-form? (om/props this))))
(om/transact! this `[(f/initialize-form {})])))
(render [this]
(let [{:keys [uid name email password password2 ui/password-error ui/create-failed] :as form} (om/props this)
sign-up (fn []
(m/set-value! this :ui/create-failed false)
(if (f/would-be-valid? form)
(f/commit-to-entity! this :remote true :fallback `create-user-failed :fallback-params {:id uid})
(om/transact! this `[(f/validate-form ~{:form-id [:user/by-id uid]})])))]
(if (om/tempid? uid) ; successful submission will remap the tempid to a real ID.
(when (f/is-form? form) ;prevents flicker on form init from SSR
(b/container-fluid {}
(b/row {}
(b/col {:lg-offset 3 :lg 6 :xs-offset 1 :xs 11}
(b/form-horizontal {}
(b/labeled-input {:split 3
:error (when (f/invalid? form :name) (tr "Please supply your name.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :name :className className :id "username"))}
(tr "Name"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :email) (tr "Must be a valid email address.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :email :className className :id "email"))}
(tr "Email Address"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :password) (tr "Password must be at least 7 characters long"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password :className className :id "password"))} (tr "Password"))
(b/labeled-input {:split 3
:error (when password-error password-error)
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password2 :className className :id "password2"
:onKeyDown (fn [evt]
(when (evts/enter-key? evt)
(sign-up)))))} (tr "Verify Password"))
(b/labeled-input {:id "submit" :split 3
:error (when create-failed (tr "A server error happened. Please try again."))
:input-generator (fn [props]
(b/button (merge props
{:kind :primary
:onClick sign-up}) (tr "Sign Up!")))} ""))))))
(b/container-fluid {}
(b/row {}
(b/col {:lg 6 :lg-offset 3 :xs 10 :xs-offset 1}
(b/alert {:kind :success} (dom/span nil (tr "Welcome! Your account has been created. ") (dom/a #js {:onClick #(r/nav-to! this :login)} (tr "Please, log in.")))))))))))
(def ui-user-form (om/factory UserForm))
(defui ^:once NewUser
static u/InitialAppState
(initial-state [this params] {:id :new-user :form (uc/get-initial-state UserForm {})})
static om/IQuery
(query [this] [:id {:form (om/get-query UserForm)}])
Object
(render [this]
(let [{:keys [form]} (om/props this)]
(ui-user-form form))))
| 4990 | (ns movie-database.ui.new-user
(:require [om.next :as om :refer [defui]]
[fulcro.client.core :as u]
[om.dom :as dom]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.i18n :refer [tr]]
[fulcro.events :as evts]
[fulcro.ui.forms :as f]
[fulcro.ui.bootstrap3 :as b]
[fulcro.client.core :as uc]
[fulcro.client.data-fetch :as df]
[movie-database.ui.html5-routing :as r]))
(defmutation check-passwords-match
[{:keys [form-id field kind]}]
(action [{:keys [state]}]
(when (and (= :password2 field) (= kind :blur))
(let [form (get-in @state form-id)
a (f/current-value form :password)
b (f/current-value form :password2)]
(if (and a b (pos? (.-length a)) (pos? (.-length b)) (not= a b))
(swap! state update-in form-id assoc :ui/password-error (tr "Passwords must match"))
(swap! state update-in form-id assoc :ui/password-error nil))))))
(defmutation create-user-failed
[{:keys [id error]}]
(action [{:keys [state]}]
(swap! state assoc-in [:user/by-id id :ui/create-failed] true)))
(f/defvalidator valid-email?
[_ value args] ; crappy regex for email...but you get the point
(seq (re-matches #"^[^ @]+@[^ ]+[.a-zA-Z0-9]*[a-zA-Z]$" value)))
(declare UserForm)
(defui ^:once UserForm
static f/IForm
(form-spec [this]
[(f/id-field :uid)
(f/text-input :name :validator `f/not-empty?)
; TODO: add username in use check against server
(f/html5-input :email "email" :validator `valid-email?)
(f/html5-input :password "<PASSWORD>" :validator `f/minmax-length? :validator-args {:min 7 :max 100})
(f/html5-input :password2 "<PASSWORD>")
(f/on-form-change `check-passwords-match)])
static u/InitialAppState
(initial-state [this params] {:uid (om/tempid) :name "" :password "" :password2 ""})
static om/IQuery
(query [this] [:ui/create-failed :uid :name :email :password :password2 :ui/password-error f/form-root-key f/form-key])
static om/Ident
(ident [this props] [:user/by-id (:uid props)])
Object
; SSR state cannot properly initialize forms, so we ensure it is initialized on mount. This mutation is safe
; to run on an already initialized form, but we only do it once since the extra transact is not necessary
; and would be distracting in the logs.
(componentWillReceiveProps [this props] ; on return to this screen once cleared
(when (or (f/server-initialized? props) (not (f/is-form? props)))
(om/transact! this `[(f/initialize-form {})])))
(componentWillMount [this] ; on initial from server
(when (or (f/server-initialized? (om/props this)) (not (f/is-form? (om/props this))))
(om/transact! this `[(f/initialize-form {})])))
(render [this]
(let [{:keys [uid name email password <PASSWORD> ui/password-error ui/create-failed] :as form} (om/props this)
sign-up (fn []
(m/set-value! this :ui/create-failed false)
(if (f/would-be-valid? form)
(f/commit-to-entity! this :remote true :fallback `create-user-failed :fallback-params {:id uid})
(om/transact! this `[(f/validate-form ~{:form-id [:user/by-id uid]})])))]
(if (om/tempid? uid) ; successful submission will remap the tempid to a real ID.
(when (f/is-form? form) ;prevents flicker on form init from SSR
(b/container-fluid {}
(b/row {}
(b/col {:lg-offset 3 :lg 6 :xs-offset 1 :xs 11}
(b/form-horizontal {}
(b/labeled-input {:split 3
:error (when (f/invalid? form :name) (tr "Please supply your name.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :name :className className :id "username"))}
(tr "Name"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :email) (tr "Must be a valid email address.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :email :className className :id "email"))}
(tr "Email Address"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :password) (tr "Password must be at least 7 characters long"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password :className className :id "password"))} (tr "Password"))
(b/labeled-input {:split 3
:error (when password-error password-error)
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password2 :className className :id "password2"
:onKeyDown (fn [evt]
(when (evts/enter-key? evt)
(sign-up)))))} (tr "Verify Password"))
(b/labeled-input {:id "submit" :split 3
:error (when create-failed (tr "A server error happened. Please try again."))
:input-generator (fn [props]
(b/button (merge props
{:kind :primary
:onClick sign-up}) (tr "Sign Up!")))} ""))))))
(b/container-fluid {}
(b/row {}
(b/col {:lg 6 :lg-offset 3 :xs 10 :xs-offset 1}
(b/alert {:kind :success} (dom/span nil (tr "Welcome! Your account has been created. ") (dom/a #js {:onClick #(r/nav-to! this :login)} (tr "Please, log in.")))))))))))
(def ui-user-form (om/factory UserForm))
(defui ^:once NewUser
static u/InitialAppState
(initial-state [this params] {:id :new-user :form (uc/get-initial-state UserForm {})})
static om/IQuery
(query [this] [:id {:form (om/get-query UserForm)}])
Object
(render [this]
(let [{:keys [form]} (om/props this)]
(ui-user-form form))))
| true | (ns movie-database.ui.new-user
(:require [om.next :as om :refer [defui]]
[fulcro.client.core :as u]
[om.dom :as dom]
[fulcro.client.mutations :as m :refer [defmutation]]
[fulcro.i18n :refer [tr]]
[fulcro.events :as evts]
[fulcro.ui.forms :as f]
[fulcro.ui.bootstrap3 :as b]
[fulcro.client.core :as uc]
[fulcro.client.data-fetch :as df]
[movie-database.ui.html5-routing :as r]))
(defmutation check-passwords-match
[{:keys [form-id field kind]}]
(action [{:keys [state]}]
(when (and (= :password2 field) (= kind :blur))
(let [form (get-in @state form-id)
a (f/current-value form :password)
b (f/current-value form :password2)]
(if (and a b (pos? (.-length a)) (pos? (.-length b)) (not= a b))
(swap! state update-in form-id assoc :ui/password-error (tr "Passwords must match"))
(swap! state update-in form-id assoc :ui/password-error nil))))))
(defmutation create-user-failed
[{:keys [id error]}]
(action [{:keys [state]}]
(swap! state assoc-in [:user/by-id id :ui/create-failed] true)))
(f/defvalidator valid-email?
[_ value args] ; crappy regex for email...but you get the point
(seq (re-matches #"^[^ @]+@[^ ]+[.a-zA-Z0-9]*[a-zA-Z]$" value)))
(declare UserForm)
(defui ^:once UserForm
static f/IForm
(form-spec [this]
[(f/id-field :uid)
(f/text-input :name :validator `f/not-empty?)
; TODO: add username in use check against server
(f/html5-input :email "email" :validator `valid-email?)
(f/html5-input :password "PI:PASSWORD:<PASSWORD>END_PI" :validator `f/minmax-length? :validator-args {:min 7 :max 100})
(f/html5-input :password2 "PI:PASSWORD:<PASSWORD>END_PI")
(f/on-form-change `check-passwords-match)])
static u/InitialAppState
(initial-state [this params] {:uid (om/tempid) :name "" :password "" :password2 ""})
static om/IQuery
(query [this] [:ui/create-failed :uid :name :email :password :password2 :ui/password-error f/form-root-key f/form-key])
static om/Ident
(ident [this props] [:user/by-id (:uid props)])
Object
; SSR state cannot properly initialize forms, so we ensure it is initialized on mount. This mutation is safe
; to run on an already initialized form, but we only do it once since the extra transact is not necessary
; and would be distracting in the logs.
(componentWillReceiveProps [this props] ; on return to this screen once cleared
(when (or (f/server-initialized? props) (not (f/is-form? props)))
(om/transact! this `[(f/initialize-form {})])))
(componentWillMount [this] ; on initial from server
(when (or (f/server-initialized? (om/props this)) (not (f/is-form? (om/props this))))
(om/transact! this `[(f/initialize-form {})])))
(render [this]
(let [{:keys [uid name email password PI:PASSWORD:<PASSWORD>END_PI ui/password-error ui/create-failed] :as form} (om/props this)
sign-up (fn []
(m/set-value! this :ui/create-failed false)
(if (f/would-be-valid? form)
(f/commit-to-entity! this :remote true :fallback `create-user-failed :fallback-params {:id uid})
(om/transact! this `[(f/validate-form ~{:form-id [:user/by-id uid]})])))]
(if (om/tempid? uid) ; successful submission will remap the tempid to a real ID.
(when (f/is-form? form) ;prevents flicker on form init from SSR
(b/container-fluid {}
(b/row {}
(b/col {:lg-offset 3 :lg 6 :xs-offset 1 :xs 11}
(b/form-horizontal {}
(b/labeled-input {:split 3
:error (when (f/invalid? form :name) (tr "Please supply your name.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :name :className className :id "username"))}
(tr "Name"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :email) (tr "Must be a valid email address.`"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :email :className className :id "email"))}
(tr "Email Address"))
(b/labeled-input {:split 3
:error (when (f/invalid? form :password) (tr "Password must be at least 7 characters long"))
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password :className className :id "password"))} (tr "Password"))
(b/labeled-input {:split 3
:error (when password-error password-error)
:input-generator (fn [{:keys [className]}]
(f/form-field this form :password2 :className className :id "password2"
:onKeyDown (fn [evt]
(when (evts/enter-key? evt)
(sign-up)))))} (tr "Verify Password"))
(b/labeled-input {:id "submit" :split 3
:error (when create-failed (tr "A server error happened. Please try again."))
:input-generator (fn [props]
(b/button (merge props
{:kind :primary
:onClick sign-up}) (tr "Sign Up!")))} ""))))))
(b/container-fluid {}
(b/row {}
(b/col {:lg 6 :lg-offset 3 :xs 10 :xs-offset 1}
(b/alert {:kind :success} (dom/span nil (tr "Welcome! Your account has been created. ") (dom/a #js {:onClick #(r/nav-to! this :login)} (tr "Please, log in.")))))))))))
(def ui-user-form (om/factory UserForm))
(defui ^:once NewUser
static u/InitialAppState
(initial-state [this params] {:id :new-user :form (uc/get-initial-state UserForm {})})
static om/IQuery
(query [this] [:id {:form (om/get-query UserForm)}])
Object
(render [this]
(let [{:keys [form]} (om/props this)]
(ui-user-form form))))
|
[
{
"context": " :query-params {:token \"dummy-token\"}})]\n (is (= 401 (:status response))))))\n\n(d",
"end": 5976,
"score": 0.6900952458381653,
"start": 5965,
"tag": "KEY",
"value": "dummy-token"
},
{
"context": "s/context))\n user1 (e/login (s/context) \"user1\")\n coll1 (d/ingest-umm-spec-collection \"",
"end": 7200,
"score": 0.7547100782394409,
"start": 7195,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :SubscriberId \"user1\"\n ",
"end": 10066,
"score": 0.9958922266960144,
"start": 10061,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :SubscriberId \"user1\"\n ",
"end": 10410,
"score": 0.996027946472168,
"start": 10405,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "ho-system-token)\n {:name \"Administrators\"\n :description \"A G",
"end": 11496,
"score": 0.4795386493206024,
"start": 11487,
"tag": "NAME",
"value": "Administr"
},
{
"context": "-token)\n {:name \"Administrators\"\n :description \"A Group\"",
"end": 11501,
"score": 0.43457287549972534,
"start": 11496,
"tag": "USERNAME",
"value": "ators"
},
{
"context": " :query-params {:token \"dummy-token\"}})]\n (is (= 401 (:status response))))))\n\n(d",
"end": 19349,
"score": 0.8187174797058105,
"start": 19338,
"tag": "KEY",
"value": "dummy-token"
},
{
"context": "ho-system-token)\n {:name \"Administrators\"\n :description \"A Group\"",
"end": 19854,
"score": 0.7492920160293579,
"start": 19840,
"tag": "USERNAME",
"value": "Administrators"
}
] | system-int-test/test/cmr/system_int_test/ingest/provider_ingest_test.clj | jaybarra/Common-Metadata-Repository | 0 | (ns cmr.system-int-test.ingest.provider-ingest-test
"CMR provider ingest integration test"
(:require
[clj-http.client :as client]
[clojure.set :as set]
[clojure.test :refer :all]
[cmr.access-control.test.util :as access-control]
[cmr.common.util :as u]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.association-util :as au]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.service-util :as services]
[cmr.system-int-test.utils.subscription-util :as subscriptions]
[cmr.system-int-test.utils.tool-util :as tools]
[cmr.system-int-test.utils.url-helper :as url]
[cmr.system-int-test.utils.variable-util :as variables]
[cmr.transmit.config :as transmit-config]))
(use-fixtures :each
(join-fixtures
[(ingest/reset-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"})
(subscriptions/grant-all-subscription-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"}
[:read :update]
[:read :update])]))
(deftest provider-ingest-test
(testing "create provider and get providers through ingest app"
(are [provider-id short-name cmr-only small]
(let [{:keys [status]} (ingest/create-ingest-provider {:provider-id provider-id
:short-name short-name
:cmr-only cmr-only
:small small})]
(and (= 201 status))
(= (ingest/get-providers) (ingest/get-ingest-providers)))
"PROV3" "S3" false false
"PROV4" "S4" true false
"PROV5" "S5" false true
"PROV6" "S6" true true
"PROV7" "S7" nil nil
"PROV8" nil nil nil))
(testing "create provider invalid value"
(u/are2
[provider error]
(let [response (ingest/create-ingest-provider provider)
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(= [400 [error]] [status errors]))
"cmr-only invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only "" :small false}
"Cmr Only must be either true or false but was [\"\"]"
"small invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only false :small ""}
"Small must be either true or false but was [\"\"]")
(testing "not json"
(let [response (client/post (url/ingest-create-provider-url)
{:body "<somexml/>"
:content-type :xml
:throw-exceptions false
:connection-manager (s/conn-mgr)
:headers {transmit-config/token-header (transmit-config/echo-system-token)}})
{:keys [status body]} response]
(is (= 415 status))
(is (re-find #"Creating or updating a provider requires a JSON content type" body))))))
(deftest update-provider-test
(testing "creating a provider and changing attributes"
(ingest/create-ingest-provider {:provider-id "PROV3"
:short-name "S3"
:cmr-only false
:small false})
(ingest/create-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only true
:small true})
(ingest/update-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only false
:small true})
(is (= #{{:provider-id "PROV4" :short-name "S4" :cmr-only false :small true}
{:provider-id "PROV3" :short-name "S3" :cmr-only false :small false}
{:provider-id "PROV2" :short-name "PROV2" :cmr-only true :small false}
{:provider-id "PROV1" :short-name "PROV1":cmr-only true :small false}}
(set (ingest/get-ingest-providers)))))
(testing "updating a non-existent provider fails"
(is (= 404 (:status (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})))))
(testing "update provider with a different small value is invalid"
(ingest/create-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small true})
(let [response (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(is (= [400 ["Provider [PROV5] small field cannot be modified."]]
[status errors]))))
(testing "update provider without permission"
(let [response (client/put (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "dummy-token"}})]
(is (= 401 (:status response))))))
(deftest force-full-provider-delete-test
(testing "force full provider delete"
(let [token (e/login-guest (cmr.system-int-test.system/context))
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))]
(index/wait-until-indexed)
;; delete provider PROV1, fails because collections exist
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors)))
(let [{:keys [status content-length]} (ingest/delete-ingest-provider
"PROV1"
{"Force-Full-Provider-Delete" "true"})]
(is (= 204 status))
(is (nil? content-length))))))
(deftest delete-provider-test
(testing "delete provider"
(let [token (e/login-guest (s/context))
user1 (e/login (s/context) "user1")
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))
gran1 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
gran2 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
coll2 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2"
:ShortName "S2"
:Version "V2"}))
gran3 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll2 "C1-PROV1"))
coll3 (d/ingest-umm-spec-collection "PROV2" (data-umm-c/collection {:EntryTitle "E3"
:ShortName "S3"
:Version "V3"}))
gran4 (d/ingest "PROV2" (dg/granule-with-umm-spec-collection coll3 "C1-PROV1"))
_ (index/wait-until-indexed)
variable1-concept (variables/make-variable-concept
{:Name "Variable1"}
{:native-id "var1"
:coll-concept-id (:concept-id coll1)})
variable2-concept (variables/make-variable-concept
{:Name "Variable2"
:provider-id "PROV2"}
{:native-id "var2"
:coll-concept-id (:concept-id coll3)})
variable1 (variables/ingest-variable-with-association variable1-concept)
variable2 (variables/ingest-variable-with-association variable2-concept)
service1 (services/ingest-service-with-attrs {:native-id "svc1"
:Name "service1"})
service2 (services/ingest-service-with-attrs {:native-id "svc2"
:Name "service2"
:provider-id "PROV2"})
tool1 (tools/ingest-tool-with-attrs {:native-id "tl1"
:Name "tool1"})
tool2 (tools/ingest-tool-with-attrs {:native-id "tl2"
:Name "tool2"
:provider-id "PROV2"})
sub1 (subscriptions/ingest-subscription-with-attrs {:native-id "sub1"
:Name "sub1"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
sub2 (subscriptions/ingest-subscription-with-attrs {:native-id "sub2"
:Name "sub2"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:provider-id "PROV2"})
_ (index/wait-until-indexed)
svc-association1 (au/make-service-association
token (:concept-id service1) [{:concept-id (:concept-id coll1)}])
svc-association2 (au/make-service-association
token (:concept-id service2) [{:concept-id (:concept-id coll3)}])
tool-association1 (au/make-tool-association
token (:concept-id tool1) [{:concept-id (:concept-id coll1)}])
tool-association2 (au/make-tool-association
token (:concept-id tool2) [{:concept-id (:concept-id coll3)}])
;; create an access group to test cascading deletes
access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "Administrators"
:description "A Group"
:provider_id "PROV1"}))
acl1 (u/map-keys->kebab-case
(access-control/create-acl (transmit-config/echo-system-token)
{:group_permissions [{:permissions [:create :update :read :delete]
:user_type "guest"}]
:provider_identity {:provider_id "PROV1"
:target "CATALOG_ITEM_ACL"}}))
_ (index/wait-until-indexed)
acl2 (u/map-keys->kebab-case
(access-control/create-acl token
{:group_permissions [{:permissions [:read :order]
:user_type "guest"}]
:catalog_item_identity {:name "PROV1 read, order"
:collection_applicable true
:provider_id "PROV1"}}))
acl3 {:concept-id
(e/grant (merge
{:token (transmit-config/echo-system-token)}
(cmr.system-int-test.system/context))
[{:permissions [:update]
:user_type "guest"}]
:provider_identity
{:provider_id "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
:revision-id 1}]
(index/wait-until-indexed)
(testing "concepts still exist"
(is (= 2 (count (:refs (search/find-refs :collection {:provider-id "PROV1"})))))
(is (= 3 (count (:refs (search/find-refs :granule {:provider-id "PROV1"})))))
(d/refs-match? [variable1] (search/find-refs :variable {:name "Variable1"}))
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(d/refs-match? [service1] (search/find-refs :service {:name "service1"}))
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))
(d/refs-match? [tool1] (search/find-refs :tool {:name "tool1"}))
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(d/refs-match? [sub1] (search/find-refs :subscription {:name "sub1"}))
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"})))
(testing "PROV1 group is indexed"
(is (= [(:concept-id access-group)]
(map :concept_id
(:items
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"}))))))
(testing "PROV1 ACLs are indexed"
(is (set/subset? (set [(:concept-id acl1) (:concept-id acl2) (:concept-id acl3)])
(set (map :concept_id
(:items
(access-control/search-for-acls (transmit-config/echo-system-token) {:provider "PROV1"})))))))
(testing "delete provider PROV1, fails because collections exist"
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors))))
(ingest/delete-concept (d/umm-c-collection->concept coll1 :echo10) {:accept-format :json
:raw? true})
(ingest/delete-concept (d/umm-c-collection->concept coll2 :echo10) {:accept-format :json
:raw? true})
(index/wait-until-indexed)
(testing "delete provider PROV1"
(let [{:keys [status content-length]} (ingest/delete-ingest-provider "PROV1")]
(is (= 204 status))
(is (nil? content-length)))
(index/wait-until-indexed))
(testing "PROV1 concepts are not in metadata-db"
(are [concept]
(not (mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept)))
coll1
coll2
gran1
gran2
gran3
variable1
service1
tool1
sub1
svc-association1
tool-association1
access-group
acl1
acl2))
(testing "PROV1 access group is unindexed"
(is (= 0 (:hits
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"})))))
(testing "PROV1 ACLs are no longer indexed"
(is (= 0 (:hits
(access-control/search-for-acls token {:provider "PROV1"})))))
(testing "PROV2 concepts are in metadata-db"
(are [concept]
(mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept))
coll3
gran4
variable2
service2
tool2
sub2
svc-association2
tool-association2))
(testing "search on PROV1 finds nothing"
(is (d/refs-match?
[]
(search/find-refs :collection {:provider-id "PROV1"})))
(is (d/refs-match?
[]
(search/find-refs :granule {:provider-id "PROV1"}))))
(testing "search on PROV2 finds the concepts")
(is (d/refs-match?
[coll3]
(search/find-refs :collection {:provider-id "PROV2"})))
(is (d/refs-match?
[gran4]
(search/find-refs :granule {:provider-id "PROV2"})))
(testing "Variable on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :variable {:name "Variable1"}))
(testing "Variable on PROV2 is still found in search")
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(testing "Tool on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :tool {:name "tool1"}))
(testing "Tool on PROV2 is still found in search")
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(testing "Subscription on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :subscription {:name "sub1"}))
(testing "Subscription on PROV2 is still found in search")
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"}))
(testing "Service on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :service {:name "service1"}))
(testing "Service on PROV2 is still found in search")
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))))
(testing "delete non-existent provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "NON_EXIST")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [404 ["Provider with provider-id [NON_EXIST] does not exist."]]
[status errors]))))
(testing "delete SMALL_PROV provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "SMALL_PROV")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [400 ["Provider [SMALL_PROV] is a reserved provider of CMR and cannot be deleted."]]
[status errors]))))
(testing "delete provider without permission"
(let [response (client/delete (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "dummy-token"}})]
(is (= 401 (:status response))))))
(deftest provider-delete-cascades-to-concepts-test
(doseq [provider [{:provider-id "SMALL" :short-name "SP" :cmr-only true :small true}
{:provider-id "NOTSMALL" :short-name "NSP"}]]
(ingest/create-ingest-provider provider)
(let [access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "Administrators"
:description "A Group"
:provider_id (:provider-id provider)}))]
(is (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))
(ingest/delete-ingest-provider (:provider-id provider))
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group))))
;; re-create the provider to ensure nothing has stuck around in the DB)
(ingest/create-ingest-provider provider)
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))))))
| 106933 | (ns cmr.system-int-test.ingest.provider-ingest-test
"CMR provider ingest integration test"
(:require
[clj-http.client :as client]
[clojure.set :as set]
[clojure.test :refer :all]
[cmr.access-control.test.util :as access-control]
[cmr.common.util :as u]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.association-util :as au]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.service-util :as services]
[cmr.system-int-test.utils.subscription-util :as subscriptions]
[cmr.system-int-test.utils.tool-util :as tools]
[cmr.system-int-test.utils.url-helper :as url]
[cmr.system-int-test.utils.variable-util :as variables]
[cmr.transmit.config :as transmit-config]))
(use-fixtures :each
(join-fixtures
[(ingest/reset-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"})
(subscriptions/grant-all-subscription-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"}
[:read :update]
[:read :update])]))
(deftest provider-ingest-test
(testing "create provider and get providers through ingest app"
(are [provider-id short-name cmr-only small]
(let [{:keys [status]} (ingest/create-ingest-provider {:provider-id provider-id
:short-name short-name
:cmr-only cmr-only
:small small})]
(and (= 201 status))
(= (ingest/get-providers) (ingest/get-ingest-providers)))
"PROV3" "S3" false false
"PROV4" "S4" true false
"PROV5" "S5" false true
"PROV6" "S6" true true
"PROV7" "S7" nil nil
"PROV8" nil nil nil))
(testing "create provider invalid value"
(u/are2
[provider error]
(let [response (ingest/create-ingest-provider provider)
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(= [400 [error]] [status errors]))
"cmr-only invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only "" :small false}
"Cmr Only must be either true or false but was [\"\"]"
"small invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only false :small ""}
"Small must be either true or false but was [\"\"]")
(testing "not json"
(let [response (client/post (url/ingest-create-provider-url)
{:body "<somexml/>"
:content-type :xml
:throw-exceptions false
:connection-manager (s/conn-mgr)
:headers {transmit-config/token-header (transmit-config/echo-system-token)}})
{:keys [status body]} response]
(is (= 415 status))
(is (re-find #"Creating or updating a provider requires a JSON content type" body))))))
(deftest update-provider-test
(testing "creating a provider and changing attributes"
(ingest/create-ingest-provider {:provider-id "PROV3"
:short-name "S3"
:cmr-only false
:small false})
(ingest/create-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only true
:small true})
(ingest/update-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only false
:small true})
(is (= #{{:provider-id "PROV4" :short-name "S4" :cmr-only false :small true}
{:provider-id "PROV3" :short-name "S3" :cmr-only false :small false}
{:provider-id "PROV2" :short-name "PROV2" :cmr-only true :small false}
{:provider-id "PROV1" :short-name "PROV1":cmr-only true :small false}}
(set (ingest/get-ingest-providers)))))
(testing "updating a non-existent provider fails"
(is (= 404 (:status (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})))))
(testing "update provider with a different small value is invalid"
(ingest/create-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small true})
(let [response (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(is (= [400 ["Provider [PROV5] small field cannot be modified."]]
[status errors]))))
(testing "update provider without permission"
(let [response (client/put (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "<KEY>"}})]
(is (= 401 (:status response))))))
(deftest force-full-provider-delete-test
(testing "force full provider delete"
(let [token (e/login-guest (cmr.system-int-test.system/context))
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))]
(index/wait-until-indexed)
;; delete provider PROV1, fails because collections exist
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors)))
(let [{:keys [status content-length]} (ingest/delete-ingest-provider
"PROV1"
{"Force-Full-Provider-Delete" "true"})]
(is (= 204 status))
(is (nil? content-length))))))
(deftest delete-provider-test
(testing "delete provider"
(let [token (e/login-guest (s/context))
user1 (e/login (s/context) "user1")
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))
gran1 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
gran2 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
coll2 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2"
:ShortName "S2"
:Version "V2"}))
gran3 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll2 "C1-PROV1"))
coll3 (d/ingest-umm-spec-collection "PROV2" (data-umm-c/collection {:EntryTitle "E3"
:ShortName "S3"
:Version "V3"}))
gran4 (d/ingest "PROV2" (dg/granule-with-umm-spec-collection coll3 "C1-PROV1"))
_ (index/wait-until-indexed)
variable1-concept (variables/make-variable-concept
{:Name "Variable1"}
{:native-id "var1"
:coll-concept-id (:concept-id coll1)})
variable2-concept (variables/make-variable-concept
{:Name "Variable2"
:provider-id "PROV2"}
{:native-id "var2"
:coll-concept-id (:concept-id coll3)})
variable1 (variables/ingest-variable-with-association variable1-concept)
variable2 (variables/ingest-variable-with-association variable2-concept)
service1 (services/ingest-service-with-attrs {:native-id "svc1"
:Name "service1"})
service2 (services/ingest-service-with-attrs {:native-id "svc2"
:Name "service2"
:provider-id "PROV2"})
tool1 (tools/ingest-tool-with-attrs {:native-id "tl1"
:Name "tool1"})
tool2 (tools/ingest-tool-with-attrs {:native-id "tl2"
:Name "tool2"
:provider-id "PROV2"})
sub1 (subscriptions/ingest-subscription-with-attrs {:native-id "sub1"
:Name "sub1"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
sub2 (subscriptions/ingest-subscription-with-attrs {:native-id "sub2"
:Name "sub2"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:provider-id "PROV2"})
_ (index/wait-until-indexed)
svc-association1 (au/make-service-association
token (:concept-id service1) [{:concept-id (:concept-id coll1)}])
svc-association2 (au/make-service-association
token (:concept-id service2) [{:concept-id (:concept-id coll3)}])
tool-association1 (au/make-tool-association
token (:concept-id tool1) [{:concept-id (:concept-id coll1)}])
tool-association2 (au/make-tool-association
token (:concept-id tool2) [{:concept-id (:concept-id coll3)}])
;; create an access group to test cascading deletes
access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "<NAME>ators"
:description "A Group"
:provider_id "PROV1"}))
acl1 (u/map-keys->kebab-case
(access-control/create-acl (transmit-config/echo-system-token)
{:group_permissions [{:permissions [:create :update :read :delete]
:user_type "guest"}]
:provider_identity {:provider_id "PROV1"
:target "CATALOG_ITEM_ACL"}}))
_ (index/wait-until-indexed)
acl2 (u/map-keys->kebab-case
(access-control/create-acl token
{:group_permissions [{:permissions [:read :order]
:user_type "guest"}]
:catalog_item_identity {:name "PROV1 read, order"
:collection_applicable true
:provider_id "PROV1"}}))
acl3 {:concept-id
(e/grant (merge
{:token (transmit-config/echo-system-token)}
(cmr.system-int-test.system/context))
[{:permissions [:update]
:user_type "guest"}]
:provider_identity
{:provider_id "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
:revision-id 1}]
(index/wait-until-indexed)
(testing "concepts still exist"
(is (= 2 (count (:refs (search/find-refs :collection {:provider-id "PROV1"})))))
(is (= 3 (count (:refs (search/find-refs :granule {:provider-id "PROV1"})))))
(d/refs-match? [variable1] (search/find-refs :variable {:name "Variable1"}))
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(d/refs-match? [service1] (search/find-refs :service {:name "service1"}))
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))
(d/refs-match? [tool1] (search/find-refs :tool {:name "tool1"}))
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(d/refs-match? [sub1] (search/find-refs :subscription {:name "sub1"}))
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"})))
(testing "PROV1 group is indexed"
(is (= [(:concept-id access-group)]
(map :concept_id
(:items
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"}))))))
(testing "PROV1 ACLs are indexed"
(is (set/subset? (set [(:concept-id acl1) (:concept-id acl2) (:concept-id acl3)])
(set (map :concept_id
(:items
(access-control/search-for-acls (transmit-config/echo-system-token) {:provider "PROV1"})))))))
(testing "delete provider PROV1, fails because collections exist"
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors))))
(ingest/delete-concept (d/umm-c-collection->concept coll1 :echo10) {:accept-format :json
:raw? true})
(ingest/delete-concept (d/umm-c-collection->concept coll2 :echo10) {:accept-format :json
:raw? true})
(index/wait-until-indexed)
(testing "delete provider PROV1"
(let [{:keys [status content-length]} (ingest/delete-ingest-provider "PROV1")]
(is (= 204 status))
(is (nil? content-length)))
(index/wait-until-indexed))
(testing "PROV1 concepts are not in metadata-db"
(are [concept]
(not (mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept)))
coll1
coll2
gran1
gran2
gran3
variable1
service1
tool1
sub1
svc-association1
tool-association1
access-group
acl1
acl2))
(testing "PROV1 access group is unindexed"
(is (= 0 (:hits
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"})))))
(testing "PROV1 ACLs are no longer indexed"
(is (= 0 (:hits
(access-control/search-for-acls token {:provider "PROV1"})))))
(testing "PROV2 concepts are in metadata-db"
(are [concept]
(mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept))
coll3
gran4
variable2
service2
tool2
sub2
svc-association2
tool-association2))
(testing "search on PROV1 finds nothing"
(is (d/refs-match?
[]
(search/find-refs :collection {:provider-id "PROV1"})))
(is (d/refs-match?
[]
(search/find-refs :granule {:provider-id "PROV1"}))))
(testing "search on PROV2 finds the concepts")
(is (d/refs-match?
[coll3]
(search/find-refs :collection {:provider-id "PROV2"})))
(is (d/refs-match?
[gran4]
(search/find-refs :granule {:provider-id "PROV2"})))
(testing "Variable on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :variable {:name "Variable1"}))
(testing "Variable on PROV2 is still found in search")
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(testing "Tool on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :tool {:name "tool1"}))
(testing "Tool on PROV2 is still found in search")
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(testing "Subscription on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :subscription {:name "sub1"}))
(testing "Subscription on PROV2 is still found in search")
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"}))
(testing "Service on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :service {:name "service1"}))
(testing "Service on PROV2 is still found in search")
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))))
(testing "delete non-existent provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "NON_EXIST")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [404 ["Provider with provider-id [NON_EXIST] does not exist."]]
[status errors]))))
(testing "delete SMALL_PROV provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "SMALL_PROV")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [400 ["Provider [SMALL_PROV] is a reserved provider of CMR and cannot be deleted."]]
[status errors]))))
(testing "delete provider without permission"
(let [response (client/delete (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "<KEY>"}})]
(is (= 401 (:status response))))))
(deftest provider-delete-cascades-to-concepts-test
(doseq [provider [{:provider-id "SMALL" :short-name "SP" :cmr-only true :small true}
{:provider-id "NOTSMALL" :short-name "NSP"}]]
(ingest/create-ingest-provider provider)
(let [access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "Administrators"
:description "A Group"
:provider_id (:provider-id provider)}))]
(is (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))
(ingest/delete-ingest-provider (:provider-id provider))
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group))))
;; re-create the provider to ensure nothing has stuck around in the DB)
(ingest/create-ingest-provider provider)
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))))))
| true | (ns cmr.system-int-test.ingest.provider-ingest-test
"CMR provider ingest integration test"
(:require
[clj-http.client :as client]
[clojure.set :as set]
[clojure.test :refer :all]
[cmr.access-control.test.util :as access-control]
[cmr.common.util :as u]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.association-util :as au]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.service-util :as services]
[cmr.system-int-test.utils.subscription-util :as subscriptions]
[cmr.system-int-test.utils.tool-util :as tools]
[cmr.system-int-test.utils.url-helper :as url]
[cmr.system-int-test.utils.variable-util :as variables]
[cmr.transmit.config :as transmit-config]))
(use-fixtures :each
(join-fixtures
[(ingest/reset-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"})
(subscriptions/grant-all-subscription-fixture
{"provguid1" "PROV1" "provguid2" "PROV2"}
[:read :update]
[:read :update])]))
(deftest provider-ingest-test
(testing "create provider and get providers through ingest app"
(are [provider-id short-name cmr-only small]
(let [{:keys [status]} (ingest/create-ingest-provider {:provider-id provider-id
:short-name short-name
:cmr-only cmr-only
:small small})]
(and (= 201 status))
(= (ingest/get-providers) (ingest/get-ingest-providers)))
"PROV3" "S3" false false
"PROV4" "S4" true false
"PROV5" "S5" false true
"PROV6" "S6" true true
"PROV7" "S7" nil nil
"PROV8" nil nil nil))
(testing "create provider invalid value"
(u/are2
[provider error]
(let [response (ingest/create-ingest-provider provider)
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(= [400 [error]] [status errors]))
"cmr-only invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only "" :small false}
"Cmr Only must be either true or false but was [\"\"]"
"small invalid value"
{:provider-id "PROV9" :short-name "S8" :cmr-only false :small ""}
"Small must be either true or false but was [\"\"]")
(testing "not json"
(let [response (client/post (url/ingest-create-provider-url)
{:body "<somexml/>"
:content-type :xml
:throw-exceptions false
:connection-manager (s/conn-mgr)
:headers {transmit-config/token-header (transmit-config/echo-system-token)}})
{:keys [status body]} response]
(is (= 415 status))
(is (re-find #"Creating or updating a provider requires a JSON content type" body))))))
(deftest update-provider-test
(testing "creating a provider and changing attributes"
(ingest/create-ingest-provider {:provider-id "PROV3"
:short-name "S3"
:cmr-only false
:small false})
(ingest/create-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only true
:small true})
(ingest/update-ingest-provider {:provider-id "PROV4"
:short-name "S4"
:cmr-only false
:small true})
(is (= #{{:provider-id "PROV4" :short-name "S4" :cmr-only false :small true}
{:provider-id "PROV3" :short-name "S3" :cmr-only false :small false}
{:provider-id "PROV2" :short-name "PROV2" :cmr-only true :small false}
{:provider-id "PROV1" :short-name "PROV1":cmr-only true :small false}}
(set (ingest/get-ingest-providers)))))
(testing "updating a non-existent provider fails"
(is (= 404 (:status (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})))))
(testing "update provider with a different small value is invalid"
(ingest/create-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small true})
(let [response (ingest/update-ingest-provider {:provider-id "PROV5"
:short-name "S5"
:cmr-only true
:small false})
{:keys [status errors]} (ingest/parse-ingest-response response {:accept-format :json})]
(is (= [400 ["Provider [PROV5] small field cannot be modified."]]
[status errors]))))
(testing "update provider without permission"
(let [response (client/put (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "PI:KEY:<KEY>END_PI"}})]
(is (= 401 (:status response))))))
(deftest force-full-provider-delete-test
(testing "force full provider delete"
(let [token (e/login-guest (cmr.system-int-test.system/context))
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))]
(index/wait-until-indexed)
;; delete provider PROV1, fails because collections exist
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors)))
(let [{:keys [status content-length]} (ingest/delete-ingest-provider
"PROV1"
{"Force-Full-Provider-Delete" "true"})]
(is (= 204 status))
(is (nil? content-length))))))
(deftest delete-provider-test
(testing "delete provider"
(let [token (e/login-guest (s/context))
user1 (e/login (s/context) "user1")
coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1"
:ShortName "S1"
:Version "V1"}))
gran1 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
gran2 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll1 "C1-PROV1"))
coll2 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E2"
:ShortName "S2"
:Version "V2"}))
gran3 (d/ingest "PROV1" (dg/granule-with-umm-spec-collection coll2 "C1-PROV1"))
coll3 (d/ingest-umm-spec-collection "PROV2" (data-umm-c/collection {:EntryTitle "E3"
:ShortName "S3"
:Version "V3"}))
gran4 (d/ingest "PROV2" (dg/granule-with-umm-spec-collection coll3 "C1-PROV1"))
_ (index/wait-until-indexed)
variable1-concept (variables/make-variable-concept
{:Name "Variable1"}
{:native-id "var1"
:coll-concept-id (:concept-id coll1)})
variable2-concept (variables/make-variable-concept
{:Name "Variable2"
:provider-id "PROV2"}
{:native-id "var2"
:coll-concept-id (:concept-id coll3)})
variable1 (variables/ingest-variable-with-association variable1-concept)
variable2 (variables/ingest-variable-with-association variable2-concept)
service1 (services/ingest-service-with-attrs {:native-id "svc1"
:Name "service1"})
service2 (services/ingest-service-with-attrs {:native-id "svc2"
:Name "service2"
:provider-id "PROV2"})
tool1 (tools/ingest-tool-with-attrs {:native-id "tl1"
:Name "tool1"})
tool2 (tools/ingest-tool-with-attrs {:native-id "tl2"
:Name "tool2"
:provider-id "PROV2"})
sub1 (subscriptions/ingest-subscription-with-attrs {:native-id "sub1"
:Name "sub1"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
sub2 (subscriptions/ingest-subscription-with-attrs {:native-id "sub2"
:Name "sub2"
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:provider-id "PROV2"})
_ (index/wait-until-indexed)
svc-association1 (au/make-service-association
token (:concept-id service1) [{:concept-id (:concept-id coll1)}])
svc-association2 (au/make-service-association
token (:concept-id service2) [{:concept-id (:concept-id coll3)}])
tool-association1 (au/make-tool-association
token (:concept-id tool1) [{:concept-id (:concept-id coll1)}])
tool-association2 (au/make-tool-association
token (:concept-id tool2) [{:concept-id (:concept-id coll3)}])
;; create an access group to test cascading deletes
access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "PI:NAME:<NAME>END_PIators"
:description "A Group"
:provider_id "PROV1"}))
acl1 (u/map-keys->kebab-case
(access-control/create-acl (transmit-config/echo-system-token)
{:group_permissions [{:permissions [:create :update :read :delete]
:user_type "guest"}]
:provider_identity {:provider_id "PROV1"
:target "CATALOG_ITEM_ACL"}}))
_ (index/wait-until-indexed)
acl2 (u/map-keys->kebab-case
(access-control/create-acl token
{:group_permissions [{:permissions [:read :order]
:user_type "guest"}]
:catalog_item_identity {:name "PROV1 read, order"
:collection_applicable true
:provider_id "PROV1"}}))
acl3 {:concept-id
(e/grant (merge
{:token (transmit-config/echo-system-token)}
(cmr.system-int-test.system/context))
[{:permissions [:update]
:user_type "guest"}]
:provider_identity
{:provider_id "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
:revision-id 1}]
(index/wait-until-indexed)
(testing "concepts still exist"
(is (= 2 (count (:refs (search/find-refs :collection {:provider-id "PROV1"})))))
(is (= 3 (count (:refs (search/find-refs :granule {:provider-id "PROV1"})))))
(d/refs-match? [variable1] (search/find-refs :variable {:name "Variable1"}))
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(d/refs-match? [service1] (search/find-refs :service {:name "service1"}))
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))
(d/refs-match? [tool1] (search/find-refs :tool {:name "tool1"}))
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(d/refs-match? [sub1] (search/find-refs :subscription {:name "sub1"}))
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"})))
(testing "PROV1 group is indexed"
(is (= [(:concept-id access-group)]
(map :concept_id
(:items
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"}))))))
(testing "PROV1 ACLs are indexed"
(is (set/subset? (set [(:concept-id acl1) (:concept-id acl2) (:concept-id acl3)])
(set (map :concept_id
(:items
(access-control/search-for-acls (transmit-config/echo-system-token) {:provider "PROV1"})))))))
(testing "delete provider PROV1, fails because collections exist"
(let [{:keys [status errors]} (ingest/delete-ingest-provider "PROV1")]
(is (= 401 status))
(is (= ["You cannot perform this action on a provider that has collections."]
errors))))
(ingest/delete-concept (d/umm-c-collection->concept coll1 :echo10) {:accept-format :json
:raw? true})
(ingest/delete-concept (d/umm-c-collection->concept coll2 :echo10) {:accept-format :json
:raw? true})
(index/wait-until-indexed)
(testing "delete provider PROV1"
(let [{:keys [status content-length]} (ingest/delete-ingest-provider "PROV1")]
(is (= 204 status))
(is (nil? content-length)))
(index/wait-until-indexed))
(testing "PROV1 concepts are not in metadata-db"
(are [concept]
(not (mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept)))
coll1
coll2
gran1
gran2
gran3
variable1
service1
tool1
sub1
svc-association1
tool-association1
access-group
acl1
acl2))
(testing "PROV1 access group is unindexed"
(is (= 0 (:hits
(access-control/search-for-groups (transmit-config/echo-system-token)
{:provider "PROV1"})))))
(testing "PROV1 ACLs are no longer indexed"
(is (= 0 (:hits
(access-control/search-for-acls token {:provider "PROV1"})))))
(testing "PROV2 concepts are in metadata-db"
(are [concept]
(mdb/concept-exists-in-mdb? (:concept-id concept) (:revision-id concept))
coll3
gran4
variable2
service2
tool2
sub2
svc-association2
tool-association2))
(testing "search on PROV1 finds nothing"
(is (d/refs-match?
[]
(search/find-refs :collection {:provider-id "PROV1"})))
(is (d/refs-match?
[]
(search/find-refs :granule {:provider-id "PROV1"}))))
(testing "search on PROV2 finds the concepts")
(is (d/refs-match?
[coll3]
(search/find-refs :collection {:provider-id "PROV2"})))
(is (d/refs-match?
[gran4]
(search/find-refs :granule {:provider-id "PROV2"})))
(testing "Variable on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :variable {:name "Variable1"}))
(testing "Variable on PROV2 is still found in search")
(d/refs-match? [variable2] (search/find-refs :variable {:name "Variable2"}))
(testing "Tool on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :tool {:name "tool1"}))
(testing "Tool on PROV2 is still found in search")
(d/refs-match? [tool2] (search/find-refs :tool {:name "tool2"}))
(testing "Subscription on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :subscription {:name "sub1"}))
(testing "Subscription on PROV2 is still found in search")
(d/refs-match? [sub2] (search/find-refs :subscription {:name "sub2"}))
(testing "Service on PROV1 is not found in search")
(d/refs-match? [] (search/find-refs :service {:name "service1"}))
(testing "Service on PROV2 is still found in search")
(d/refs-match? [service2] (search/find-refs :service {:name "service2"}))))
(testing "delete non-existent provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "NON_EXIST")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [404 ["Provider with provider-id [NON_EXIST] does not exist."]]
[status errors]))))
(testing "delete SMALL_PROV provider"
(let [{:keys [status errors content-type]} (ingest/delete-ingest-provider "SMALL_PROV")]
(is (= "application/json;charset=utf-8" content-type))
(is (= [400 ["Provider [SMALL_PROV] is a reserved provider of CMR and cannot be deleted."]]
[status errors]))))
(testing "delete provider without permission"
(let [response (client/delete (url/ingest-provider-url "PROV1")
{:throw-exceptions false
:connection-manager (s/conn-mgr)
:query-params {:token "PI:KEY:<KEY>END_PI"}})]
(is (= 401 (:status response))))))
(deftest provider-delete-cascades-to-concepts-test
(doseq [provider [{:provider-id "SMALL" :short-name "SP" :cmr-only true :small true}
{:provider-id "NOTSMALL" :short-name "NSP"}]]
(ingest/create-ingest-provider provider)
(let [access-group (u/map-keys->kebab-case
(access-control/create-group
(transmit-config/echo-system-token)
{:name "Administrators"
:description "A Group"
:provider_id (:provider-id provider)}))]
(is (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))
(ingest/delete-ingest-provider (:provider-id provider))
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group))))
;; re-create the provider to ensure nothing has stuck around in the DB)
(ingest/create-ingest-provider provider)
(is (not (mdb/concept-exists-in-mdb? (:concept-id access-group) (:revision-id access-group)))))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.999809980392456,
"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.9998204708099365,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/gl/vertex2.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2
(:require
[clojure.string :as str]
[editor.gl :as gl]
[editor.gl.protocols :refer [GlBind]]
[editor.gl.shader :as shader]
[editor.scene-cache :as scene-cache]
[editor.types :as types]
[internal.util :as util])
(:import
[com.jogamp.common.nio Buffers]
[java.nio ByteBuffer ByteOrder]
[com.jogamp.opengl GL GL2]))
(set! *warn-on-reflection* true)
(def type-sizes
{:ubyte Buffers/SIZEOF_BYTE
:byte Buffers/SIZEOF_BYTE
:ushort Buffers/SIZEOF_SHORT
:short Buffers/SIZEOF_SHORT
:uint Buffers/SIZEOF_INT
:int Buffers/SIZEOF_INT
:float Buffers/SIZEOF_FLOAT
:double Buffers/SIZEOF_DOUBLE})
(def gl-types
{:ubyte GL/GL_UNSIGNED_BYTE
:byte GL/GL_BYTE
:ushort GL/GL_UNSIGNED_SHORT
:short GL/GL_SHORT
:uint GL/GL_UNSIGNED_INT
:int GL2/GL_INT
:float GL/GL_FLOAT
:double GL2/GL_DOUBLE})
(def usage-types
{:static GL2/GL_STATIC_DRAW
:dynamic GL2/GL_DYNAMIC_DRAW})
(defn type->stream-type [type]
(case type
:float :value-type-float32
:ubyte :value-type-uint8
:ushort :value-type-uint16
:uint :value-type-uint32
:byte :value-type-int8
:short :value-type-int16
:int :value-type-int32))
;; TODO: Might need to add support for uint64/int64 in the future.
;; (OpenGL ES 2 doesn't support this currently, but Vulkan might.)
(defn stream-type->type [stream-type]
(case stream-type
:value-type-float32 :float
:value-type-uint8 :ubyte
:value-type-uint16 :ushort
:value-type-uint32 :uint
:value-type-int8 :byte
:value-type-int16 :short
:value-type-int32 :int))
;; VertexBuffer object
(defprotocol IVertexBuffer
(flip! [this] "make this buffer ready for use with OpenGL")
(flipped? [this])
(clear! [this])
(position! [this position])
(version [this]))
(deftype VertexBuffer [vertex-description usage ^ByteBuffer buf ^{:unsynchronized-mutable true} version]
IVertexBuffer
(flip! [this] (.flip buf) (set! version (inc version)) this)
(flipped? [this] (and (= 0 (.position buf))))
(clear! [this] (.clear buf) this)
(position! [this position] (.position buf (int (* position ^long (:size vertex-description)))) this)
(version [this] version)
clojure.lang.Counted
(count [this] (let [bytes (if (pos? (.position buf)) (.position buf) (.limit buf))]
(/ bytes ^long (:size vertex-description)))))
(defn make-vertex-buffer
[vertex-description usage ^long capacity]
(let [nbytes (* capacity ^long (:size vertex-description))
buf (doto (ByteBuffer/allocateDirect nbytes)
(.order ByteOrder/LITTLE_ENDIAN))]
(->VertexBuffer vertex-description usage buf 0)))
;; vertex description
(defn- attribute-sizes
[attributes]
(map (fn [{:keys [^long components type]}] (* components ^long (type-sizes type))) attributes))
(defn- vertex-size
[attributes]
(reduce + (attribute-sizes attributes)))
(defn make-vertex-description
[name attributes]
{:name name
:attributes attributes
:size (vertex-size attributes)})
;; defvertex macro
(defn- attribute-components
[attributes]
(for [{:keys [name components] :as attribute} attributes
n (range components)]
(-> attribute
(update :name str (nth ["-x" "-y" "-z" "-w"] n))
(dissoc :components))))
(defn make-put-fn
[attributes]
(let [args (for [{:keys [name type] :as component} (attribute-components attributes)]
(assoc component :arg (symbol name)))]
`(fn [~(with-meta 'vbuf {:tag `VertexBuffer}) ~@(map :arg args)]
(doto ~(with-meta '(.buf vbuf) {:tag `ByteBuffer})
~@(for [{:keys [arg type]} args]
(let [arg (with-meta arg {:tag (case type
:byte `Byte
:short `Short
:int `Integer
:float `Float
:double `Double
:ubyte `Byte
:ushort `Short
:uint `Integer)})]
(case type
:byte `(.put ~arg)
:short `(.putShort ~arg)
:int `(.putInt ~arg)
:float `(.putFloat ~arg)
:double `(.putDouble ~arg)
:ubyte `(.put (.byteValue (Long. (bit-and ~arg 0xff))))
:ushort `(.putShort (.shortValue (Long. (bit-and ~arg 0xffff))))
:uint `(.putInt (.intValue (Long. (bit-and ~arg 0xffffffff))))))))
~'vbuf)))
(def ^:private type-component-counts
{:vec1 1
:vec2 2
:vec3 3
:vec4 4})
(defn- parse-attribute-definition
[form]
(let [[type nm & [normalized?]] form
[prefix suffix] (str/split (name type) #"\.")
prefix (keyword prefix)
suffix (keyword (or suffix "float"))
num-components (type-component-counts prefix)]
(assert num-components (str type " is not a valid type name. It must start with vec1, vec2, vec3, or vec4."))
(assert (get gl-types suffix) (str type " is not a valid type name. It must end with byte, short, int, float, or double. (Defaults to float if no suffix.)"))
{:components num-components
:type suffix
:name (name nm)
:normalized? (true? normalized?)}))
(defmacro defvertex
[name & attribute-definitions]
(let [attributes (mapv parse-attribute-definition attribute-definitions)
vertex-description (make-vertex-description name attributes)
ctor-name (symbol (str "->" name))
put-name (symbol (str name "-put!"))
gen-put? (not (:no-put (meta name)))]
`(do
(def ~name '~vertex-description)
(defn ~ctor-name
([capacity#]
(make-vertex-buffer '~vertex-description :static capacity#))
([capacity# usage#]
(assert (contains? usage-types usage#) (format "usage must be %s" (str/join " or " (map str (keys usage-types)))))
(make-vertex-buffer '~vertex-description usage# capacity#)))
~(when gen-put?
`(def ~put-name ~(make-put-fn (:attributes vertex-description)))))))
;; GL stuff
(defn- vertex-locate-attribs
[^GL2 gl shader attribs]
(mapv #(shader/get-attrib-location shader gl (:name %)) attribs))
(defn- vertex-attrib-pointer
[^GL2 gl attrib loc stride offset]
(let [{:keys [name components type normalized?]} attrib]
(when (not= -1 loc)
(gl/gl-vertex-attrib-pointer gl ^int loc ^int components ^int (gl-types type) ^boolean normalized? ^int stride ^long offset))))
(defn- vertex-attrib-pointers
[^GL2 gl attribs attrib-locs]
(let [offsets (reductions + 0 (attribute-sizes attribs))
stride (vertex-size attribs)]
(doall
(map
(fn [offset attrib loc]
(vertex-attrib-pointer gl attrib loc stride offset))
offsets attribs attrib-locs))))
(defn- vertex-enable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-enable-vertex-attrib-array gl l)))
(defn- vertex-disable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-disable-vertex-attrib-array gl l)))
(defn- find-attribute-index [attribute-name attributes]
(util/first-index-where (fn [attribute] (= attribute-name (:name attribute)))
attributes))
(defn- request-vbo [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(scene-cache/request-object! ::vbo2 request-id gl {:vertex-buffer vertex-buffer :version (version vertex-buffer) :shader shader}))
(defn- bind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[vbo attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(vertex-attrib-pointers gl (:attributes (.vertex-description vertex-buffer)) attrib-locs)
(vertex-enable-attribs gl attrib-locs)))
(defn- unbind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[_ attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(vertex-disable-attribs gl attrib-locs))
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER 0))
(defrecord VertexBufferShaderLink [request-id ^VertexBuffer vertex-buffer shader]
GlBind
(bind [_this gl render-args]
(bind-vertex-buffer-with-shader! gl request-id vertex-buffer shader))
(unbind [_this gl render-args]
(unbind-vertex-buffer-with-shader! gl request-id vertex-buffer shader)))
(defn use-with
[request-id vertex-buffer shader]
(->VertexBufferShaderLink request-id vertex-buffer shader))
(defn- update-vbo [^GL2 gl [vbo _] data]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(let [^VertexBuffer vbuf (:vertex-buffer data)
^ByteBuffer buf (.buf vbuf)
shader (:shader data)
attributes (:attributes (.vertex-description vbuf))
attrib-locs (vertex-locate-attribs gl shader attributes)]
(assert (flipped? vbuf) "VertexBuffer must be flipped before use.")
(gl/gl-buffer-data ^GL2 gl GL/GL_ARRAY_BUFFER (.limit buf) buf (usage-types (.usage vbuf)))
[vbo attrib-locs]))
(defn- make-vbo [^GL2 gl data]
(let [vbo (first (gl/gl-gen-buffers gl 1))]
(update-vbo gl [vbo nil] data)))
(defn- destroy-vbos [^GL2 gl objs _]
(apply gl/gl-delete-buffers gl (map first objs)))
(scene-cache/register-object-cache! ::vbo2 make-vbo update-vbo destroy-vbos)
| 114950 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2
(:require
[clojure.string :as str]
[editor.gl :as gl]
[editor.gl.protocols :refer [GlBind]]
[editor.gl.shader :as shader]
[editor.scene-cache :as scene-cache]
[editor.types :as types]
[internal.util :as util])
(:import
[com.jogamp.common.nio Buffers]
[java.nio ByteBuffer ByteOrder]
[com.jogamp.opengl GL GL2]))
(set! *warn-on-reflection* true)
(def type-sizes
{:ubyte Buffers/SIZEOF_BYTE
:byte Buffers/SIZEOF_BYTE
:ushort Buffers/SIZEOF_SHORT
:short Buffers/SIZEOF_SHORT
:uint Buffers/SIZEOF_INT
:int Buffers/SIZEOF_INT
:float Buffers/SIZEOF_FLOAT
:double Buffers/SIZEOF_DOUBLE})
(def gl-types
{:ubyte GL/GL_UNSIGNED_BYTE
:byte GL/GL_BYTE
:ushort GL/GL_UNSIGNED_SHORT
:short GL/GL_SHORT
:uint GL/GL_UNSIGNED_INT
:int GL2/GL_INT
:float GL/GL_FLOAT
:double GL2/GL_DOUBLE})
(def usage-types
{:static GL2/GL_STATIC_DRAW
:dynamic GL2/GL_DYNAMIC_DRAW})
(defn type->stream-type [type]
(case type
:float :value-type-float32
:ubyte :value-type-uint8
:ushort :value-type-uint16
:uint :value-type-uint32
:byte :value-type-int8
:short :value-type-int16
:int :value-type-int32))
;; TODO: Might need to add support for uint64/int64 in the future.
;; (OpenGL ES 2 doesn't support this currently, but Vulkan might.)
(defn stream-type->type [stream-type]
(case stream-type
:value-type-float32 :float
:value-type-uint8 :ubyte
:value-type-uint16 :ushort
:value-type-uint32 :uint
:value-type-int8 :byte
:value-type-int16 :short
:value-type-int32 :int))
;; VertexBuffer object
(defprotocol IVertexBuffer
(flip! [this] "make this buffer ready for use with OpenGL")
(flipped? [this])
(clear! [this])
(position! [this position])
(version [this]))
(deftype VertexBuffer [vertex-description usage ^ByteBuffer buf ^{:unsynchronized-mutable true} version]
IVertexBuffer
(flip! [this] (.flip buf) (set! version (inc version)) this)
(flipped? [this] (and (= 0 (.position buf))))
(clear! [this] (.clear buf) this)
(position! [this position] (.position buf (int (* position ^long (:size vertex-description)))) this)
(version [this] version)
clojure.lang.Counted
(count [this] (let [bytes (if (pos? (.position buf)) (.position buf) (.limit buf))]
(/ bytes ^long (:size vertex-description)))))
(defn make-vertex-buffer
[vertex-description usage ^long capacity]
(let [nbytes (* capacity ^long (:size vertex-description))
buf (doto (ByteBuffer/allocateDirect nbytes)
(.order ByteOrder/LITTLE_ENDIAN))]
(->VertexBuffer vertex-description usage buf 0)))
;; vertex description
(defn- attribute-sizes
[attributes]
(map (fn [{:keys [^long components type]}] (* components ^long (type-sizes type))) attributes))
(defn- vertex-size
[attributes]
(reduce + (attribute-sizes attributes)))
(defn make-vertex-description
[name attributes]
{:name name
:attributes attributes
:size (vertex-size attributes)})
;; defvertex macro
(defn- attribute-components
[attributes]
(for [{:keys [name components] :as attribute} attributes
n (range components)]
(-> attribute
(update :name str (nth ["-x" "-y" "-z" "-w"] n))
(dissoc :components))))
(defn make-put-fn
[attributes]
(let [args (for [{:keys [name type] :as component} (attribute-components attributes)]
(assoc component :arg (symbol name)))]
`(fn [~(with-meta 'vbuf {:tag `VertexBuffer}) ~@(map :arg args)]
(doto ~(with-meta '(.buf vbuf) {:tag `ByteBuffer})
~@(for [{:keys [arg type]} args]
(let [arg (with-meta arg {:tag (case type
:byte `Byte
:short `Short
:int `Integer
:float `Float
:double `Double
:ubyte `Byte
:ushort `Short
:uint `Integer)})]
(case type
:byte `(.put ~arg)
:short `(.putShort ~arg)
:int `(.putInt ~arg)
:float `(.putFloat ~arg)
:double `(.putDouble ~arg)
:ubyte `(.put (.byteValue (Long. (bit-and ~arg 0xff))))
:ushort `(.putShort (.shortValue (Long. (bit-and ~arg 0xffff))))
:uint `(.putInt (.intValue (Long. (bit-and ~arg 0xffffffff))))))))
~'vbuf)))
(def ^:private type-component-counts
{:vec1 1
:vec2 2
:vec3 3
:vec4 4})
(defn- parse-attribute-definition
[form]
(let [[type nm & [normalized?]] form
[prefix suffix] (str/split (name type) #"\.")
prefix (keyword prefix)
suffix (keyword (or suffix "float"))
num-components (type-component-counts prefix)]
(assert num-components (str type " is not a valid type name. It must start with vec1, vec2, vec3, or vec4."))
(assert (get gl-types suffix) (str type " is not a valid type name. It must end with byte, short, int, float, or double. (Defaults to float if no suffix.)"))
{:components num-components
:type suffix
:name (name nm)
:normalized? (true? normalized?)}))
(defmacro defvertex
[name & attribute-definitions]
(let [attributes (mapv parse-attribute-definition attribute-definitions)
vertex-description (make-vertex-description name attributes)
ctor-name (symbol (str "->" name))
put-name (symbol (str name "-put!"))
gen-put? (not (:no-put (meta name)))]
`(do
(def ~name '~vertex-description)
(defn ~ctor-name
([capacity#]
(make-vertex-buffer '~vertex-description :static capacity#))
([capacity# usage#]
(assert (contains? usage-types usage#) (format "usage must be %s" (str/join " or " (map str (keys usage-types)))))
(make-vertex-buffer '~vertex-description usage# capacity#)))
~(when gen-put?
`(def ~put-name ~(make-put-fn (:attributes vertex-description)))))))
;; GL stuff
(defn- vertex-locate-attribs
[^GL2 gl shader attribs]
(mapv #(shader/get-attrib-location shader gl (:name %)) attribs))
(defn- vertex-attrib-pointer
[^GL2 gl attrib loc stride offset]
(let [{:keys [name components type normalized?]} attrib]
(when (not= -1 loc)
(gl/gl-vertex-attrib-pointer gl ^int loc ^int components ^int (gl-types type) ^boolean normalized? ^int stride ^long offset))))
(defn- vertex-attrib-pointers
[^GL2 gl attribs attrib-locs]
(let [offsets (reductions + 0 (attribute-sizes attribs))
stride (vertex-size attribs)]
(doall
(map
(fn [offset attrib loc]
(vertex-attrib-pointer gl attrib loc stride offset))
offsets attribs attrib-locs))))
(defn- vertex-enable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-enable-vertex-attrib-array gl l)))
(defn- vertex-disable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-disable-vertex-attrib-array gl l)))
(defn- find-attribute-index [attribute-name attributes]
(util/first-index-where (fn [attribute] (= attribute-name (:name attribute)))
attributes))
(defn- request-vbo [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(scene-cache/request-object! ::vbo2 request-id gl {:vertex-buffer vertex-buffer :version (version vertex-buffer) :shader shader}))
(defn- bind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[vbo attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(vertex-attrib-pointers gl (:attributes (.vertex-description vertex-buffer)) attrib-locs)
(vertex-enable-attribs gl attrib-locs)))
(defn- unbind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[_ attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(vertex-disable-attribs gl attrib-locs))
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER 0))
(defrecord VertexBufferShaderLink [request-id ^VertexBuffer vertex-buffer shader]
GlBind
(bind [_this gl render-args]
(bind-vertex-buffer-with-shader! gl request-id vertex-buffer shader))
(unbind [_this gl render-args]
(unbind-vertex-buffer-with-shader! gl request-id vertex-buffer shader)))
(defn use-with
[request-id vertex-buffer shader]
(->VertexBufferShaderLink request-id vertex-buffer shader))
(defn- update-vbo [^GL2 gl [vbo _] data]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(let [^VertexBuffer vbuf (:vertex-buffer data)
^ByteBuffer buf (.buf vbuf)
shader (:shader data)
attributes (:attributes (.vertex-description vbuf))
attrib-locs (vertex-locate-attribs gl shader attributes)]
(assert (flipped? vbuf) "VertexBuffer must be flipped before use.")
(gl/gl-buffer-data ^GL2 gl GL/GL_ARRAY_BUFFER (.limit buf) buf (usage-types (.usage vbuf)))
[vbo attrib-locs]))
(defn- make-vbo [^GL2 gl data]
(let [vbo (first (gl/gl-gen-buffers gl 1))]
(update-vbo gl [vbo nil] data)))
(defn- destroy-vbos [^GL2 gl objs _]
(apply gl/gl-delete-buffers gl (map first objs)))
(scene-cache/register-object-cache! ::vbo2 make-vbo update-vbo destroy-vbos)
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gl.vertex2
(:require
[clojure.string :as str]
[editor.gl :as gl]
[editor.gl.protocols :refer [GlBind]]
[editor.gl.shader :as shader]
[editor.scene-cache :as scene-cache]
[editor.types :as types]
[internal.util :as util])
(:import
[com.jogamp.common.nio Buffers]
[java.nio ByteBuffer ByteOrder]
[com.jogamp.opengl GL GL2]))
(set! *warn-on-reflection* true)
(def type-sizes
{:ubyte Buffers/SIZEOF_BYTE
:byte Buffers/SIZEOF_BYTE
:ushort Buffers/SIZEOF_SHORT
:short Buffers/SIZEOF_SHORT
:uint Buffers/SIZEOF_INT
:int Buffers/SIZEOF_INT
:float Buffers/SIZEOF_FLOAT
:double Buffers/SIZEOF_DOUBLE})
(def gl-types
{:ubyte GL/GL_UNSIGNED_BYTE
:byte GL/GL_BYTE
:ushort GL/GL_UNSIGNED_SHORT
:short GL/GL_SHORT
:uint GL/GL_UNSIGNED_INT
:int GL2/GL_INT
:float GL/GL_FLOAT
:double GL2/GL_DOUBLE})
(def usage-types
{:static GL2/GL_STATIC_DRAW
:dynamic GL2/GL_DYNAMIC_DRAW})
(defn type->stream-type [type]
(case type
:float :value-type-float32
:ubyte :value-type-uint8
:ushort :value-type-uint16
:uint :value-type-uint32
:byte :value-type-int8
:short :value-type-int16
:int :value-type-int32))
;; TODO: Might need to add support for uint64/int64 in the future.
;; (OpenGL ES 2 doesn't support this currently, but Vulkan might.)
(defn stream-type->type [stream-type]
(case stream-type
:value-type-float32 :float
:value-type-uint8 :ubyte
:value-type-uint16 :ushort
:value-type-uint32 :uint
:value-type-int8 :byte
:value-type-int16 :short
:value-type-int32 :int))
;; VertexBuffer object
(defprotocol IVertexBuffer
(flip! [this] "make this buffer ready for use with OpenGL")
(flipped? [this])
(clear! [this])
(position! [this position])
(version [this]))
(deftype VertexBuffer [vertex-description usage ^ByteBuffer buf ^{:unsynchronized-mutable true} version]
IVertexBuffer
(flip! [this] (.flip buf) (set! version (inc version)) this)
(flipped? [this] (and (= 0 (.position buf))))
(clear! [this] (.clear buf) this)
(position! [this position] (.position buf (int (* position ^long (:size vertex-description)))) this)
(version [this] version)
clojure.lang.Counted
(count [this] (let [bytes (if (pos? (.position buf)) (.position buf) (.limit buf))]
(/ bytes ^long (:size vertex-description)))))
(defn make-vertex-buffer
[vertex-description usage ^long capacity]
(let [nbytes (* capacity ^long (:size vertex-description))
buf (doto (ByteBuffer/allocateDirect nbytes)
(.order ByteOrder/LITTLE_ENDIAN))]
(->VertexBuffer vertex-description usage buf 0)))
;; vertex description
(defn- attribute-sizes
[attributes]
(map (fn [{:keys [^long components type]}] (* components ^long (type-sizes type))) attributes))
(defn- vertex-size
[attributes]
(reduce + (attribute-sizes attributes)))
(defn make-vertex-description
[name attributes]
{:name name
:attributes attributes
:size (vertex-size attributes)})
;; defvertex macro
(defn- attribute-components
[attributes]
(for [{:keys [name components] :as attribute} attributes
n (range components)]
(-> attribute
(update :name str (nth ["-x" "-y" "-z" "-w"] n))
(dissoc :components))))
(defn make-put-fn
[attributes]
(let [args (for [{:keys [name type] :as component} (attribute-components attributes)]
(assoc component :arg (symbol name)))]
`(fn [~(with-meta 'vbuf {:tag `VertexBuffer}) ~@(map :arg args)]
(doto ~(with-meta '(.buf vbuf) {:tag `ByteBuffer})
~@(for [{:keys [arg type]} args]
(let [arg (with-meta arg {:tag (case type
:byte `Byte
:short `Short
:int `Integer
:float `Float
:double `Double
:ubyte `Byte
:ushort `Short
:uint `Integer)})]
(case type
:byte `(.put ~arg)
:short `(.putShort ~arg)
:int `(.putInt ~arg)
:float `(.putFloat ~arg)
:double `(.putDouble ~arg)
:ubyte `(.put (.byteValue (Long. (bit-and ~arg 0xff))))
:ushort `(.putShort (.shortValue (Long. (bit-and ~arg 0xffff))))
:uint `(.putInt (.intValue (Long. (bit-and ~arg 0xffffffff))))))))
~'vbuf)))
(def ^:private type-component-counts
{:vec1 1
:vec2 2
:vec3 3
:vec4 4})
(defn- parse-attribute-definition
[form]
(let [[type nm & [normalized?]] form
[prefix suffix] (str/split (name type) #"\.")
prefix (keyword prefix)
suffix (keyword (or suffix "float"))
num-components (type-component-counts prefix)]
(assert num-components (str type " is not a valid type name. It must start with vec1, vec2, vec3, or vec4."))
(assert (get gl-types suffix) (str type " is not a valid type name. It must end with byte, short, int, float, or double. (Defaults to float if no suffix.)"))
{:components num-components
:type suffix
:name (name nm)
:normalized? (true? normalized?)}))
(defmacro defvertex
[name & attribute-definitions]
(let [attributes (mapv parse-attribute-definition attribute-definitions)
vertex-description (make-vertex-description name attributes)
ctor-name (symbol (str "->" name))
put-name (symbol (str name "-put!"))
gen-put? (not (:no-put (meta name)))]
`(do
(def ~name '~vertex-description)
(defn ~ctor-name
([capacity#]
(make-vertex-buffer '~vertex-description :static capacity#))
([capacity# usage#]
(assert (contains? usage-types usage#) (format "usage must be %s" (str/join " or " (map str (keys usage-types)))))
(make-vertex-buffer '~vertex-description usage# capacity#)))
~(when gen-put?
`(def ~put-name ~(make-put-fn (:attributes vertex-description)))))))
;; GL stuff
(defn- vertex-locate-attribs
[^GL2 gl shader attribs]
(mapv #(shader/get-attrib-location shader gl (:name %)) attribs))
(defn- vertex-attrib-pointer
[^GL2 gl attrib loc stride offset]
(let [{:keys [name components type normalized?]} attrib]
(when (not= -1 loc)
(gl/gl-vertex-attrib-pointer gl ^int loc ^int components ^int (gl-types type) ^boolean normalized? ^int stride ^long offset))))
(defn- vertex-attrib-pointers
[^GL2 gl attribs attrib-locs]
(let [offsets (reductions + 0 (attribute-sizes attribs))
stride (vertex-size attribs)]
(doall
(map
(fn [offset attrib loc]
(vertex-attrib-pointer gl attrib loc stride offset))
offsets attribs attrib-locs))))
(defn- vertex-enable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-enable-vertex-attrib-array gl l)))
(defn- vertex-disable-attribs
[^GL2 gl locs]
(doseq [l locs
:when (not= l -1)]
(gl/gl-disable-vertex-attrib-array gl l)))
(defn- find-attribute-index [attribute-name attributes]
(util/first-index-where (fn [attribute] (= attribute-name (:name attribute)))
attributes))
(defn- request-vbo [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(scene-cache/request-object! ::vbo2 request-id gl {:vertex-buffer vertex-buffer :version (version vertex-buffer) :shader shader}))
(defn- bind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[vbo attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(vertex-attrib-pointers gl (:attributes (.vertex-description vertex-buffer)) attrib-locs)
(vertex-enable-attribs gl attrib-locs)))
(defn- unbind-vertex-buffer-with-shader! [^GL2 gl request-id ^VertexBuffer vertex-buffer shader]
(let [[_ attrib-locs] (request-vbo gl request-id vertex-buffer shader)]
(vertex-disable-attribs gl attrib-locs))
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER 0))
(defrecord VertexBufferShaderLink [request-id ^VertexBuffer vertex-buffer shader]
GlBind
(bind [_this gl render-args]
(bind-vertex-buffer-with-shader! gl request-id vertex-buffer shader))
(unbind [_this gl render-args]
(unbind-vertex-buffer-with-shader! gl request-id vertex-buffer shader)))
(defn use-with
[request-id vertex-buffer shader]
(->VertexBufferShaderLink request-id vertex-buffer shader))
(defn- update-vbo [^GL2 gl [vbo _] data]
(gl/gl-bind-buffer gl GL/GL_ARRAY_BUFFER vbo)
(let [^VertexBuffer vbuf (:vertex-buffer data)
^ByteBuffer buf (.buf vbuf)
shader (:shader data)
attributes (:attributes (.vertex-description vbuf))
attrib-locs (vertex-locate-attribs gl shader attributes)]
(assert (flipped? vbuf) "VertexBuffer must be flipped before use.")
(gl/gl-buffer-data ^GL2 gl GL/GL_ARRAY_BUFFER (.limit buf) buf (usage-types (.usage vbuf)))
[vbo attrib-locs]))
(defn- make-vbo [^GL2 gl data]
(let [vbo (first (gl/gl-gen-buffers gl 1))]
(update-vbo gl [vbo nil] data)))
(defn- destroy-vbos [^GL2 gl objs _]
(apply gl/gl-delete-buffers gl (map first objs)))
(scene-cache/register-object-cache! ::vbo2 make-vbo update-vbo destroy-vbos)
|
[
{
"context": " of their house.\",\n :director \"Tim Burton\",\n :genres [\"Comedy\" \"Fantas",
"end": 264,
"score": 0.9998865723609924,
"start": 254,
"tag": "NAME",
"value": "Tim Burton"
},
{
"context": " :year \"1988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ",
"end": 445,
"score": 0.9998852610588074,
"start": 433,
"tag": "NAME",
"value": "Alec Baldwin"
},
{
"context": "988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ",
"end": 458,
"score": 0.9998624324798584,
"start": 447,
"tag": "NAME",
"value": "Geena Davis"
},
{
"context": " :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n",
"end": 473,
"score": 0.9998608231544495,
"start": 460,
"tag": "NAME",
"value": "Annie McEnroe"
},
{
"context": "ctors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n ",
"end": 487,
"score": 0.9998634457588196,
"start": 475,
"tag": "NAME",
"value": "Maurice Page"
},
{
"context": "de it so famous.\",\n :director \"Francis Ford Coppola\",\n :genres [\"Crime\" \"Drama\" ",
"end": 1007,
"score": 0.999879777431488,
"start": 987,
"tag": "NAME",
"value": "Francis Ford Coppola"
},
{
"context": " :year \"1984\",\n :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n ",
"end": 1197,
"score": 0.99988853931427,
"start": 1185,
"tag": "NAME",
"value": "Richard Gere"
},
{
"context": "984\",\n :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n ",
"end": 1212,
"score": 0.9998543858528137,
"start": 1199,
"tag": "NAME",
"value": "Gregory Hines"
},
{
"context": " :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n :id 2,",
"end": 1224,
"score": 0.9997602701187134,
"start": 1214,
"tag": "NAME",
"value": "Diane Lane"
},
{
"context": "actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n :id 2,\n ",
"end": 1239,
"score": 0.9997575879096985,
"start": 1226,
"tag": "NAME",
"value": "Lonette McKee"
},
{
"context": " common decency.\",\n :director \"Frank Darabont\",\n :genres [\"Crime\" \"Drama\"]",
"end": 1691,
"score": 0.9998939633369446,
"start": 1677,
"tag": "NAME",
"value": "Frank Darabont"
},
{
"context": " :year \"1994\",\n :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n ",
"end": 1881,
"score": 0.9998810291290283,
"start": 1870,
"tag": "NAME",
"value": "Tim Robbins"
},
{
"context": "1994\",\n :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n ",
"end": 1897,
"score": 0.9998647570610046,
"start": 1883,
"tag": "NAME",
"value": "Morgan Freeman"
},
{
"context": " :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n :id 3",
"end": 1909,
"score": 0.999872088432312,
"start": 1899,
"tag": "NAME",
"value": "Bob Gunton"
},
{
"context": "actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n :id 3,\n ",
"end": 1925,
"score": 0.9998757243156433,
"start": 1911,
"tag": "NAME",
"value": "William Sadler"
},
{
"context": "o New York City.\",\n :director \"Peter Faiman\",\n :genres [\"Adventure\" \"Com",
"end": 2381,
"score": 0.9998961687088013,
"start": 2369,
"tag": "NAME",
"value": "Peter Faiman"
},
{
"context": " :year \"1986\",\n :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n",
"end": 2567,
"score": 0.9998904466629028,
"start": 2557,
"tag": "NAME",
"value": "Paul Hogan"
},
{
"context": "\"1986\",\n :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n ",
"end": 2584,
"score": 0.9998461604118347,
"start": 2569,
"tag": "NAME",
"value": "Linda Kozlowski"
},
{
"context": " :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n :id 4",
"end": 2598,
"score": 0.9998698234558105,
"start": 2586,
"tag": "NAME",
"value": "John Meillon"
},
{
"context": "tors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n :id 4,\n ",
"end": 2614,
"score": 0.9998714327812195,
"start": 2600,
"tag": "NAME",
"value": "David Gulpilil"
},
{
"context": "dified Plot again\",\n :director \"Tim Burton\",\n :genres [\"Comedy\" \"Fantasy",
"end": 3350,
"score": 0.9998869299888611,
"start": 3340,
"tag": "NAME",
"value": "Tim Burton"
},
{
"context": " :year \"1988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ",
"end": 3527,
"score": 0.9998650550842285,
"start": 3515,
"tag": "NAME",
"value": "Alec Baldwin"
},
{
"context": "1988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ",
"end": 3540,
"score": 0.9998602867126465,
"start": 3529,
"tag": "NAME",
"value": "Geena Davis"
},
{
"context": " :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n ",
"end": 3555,
"score": 0.9998598098754883,
"start": 3542,
"tag": "NAME",
"value": "Annie McEnroe"
},
{
"context": "ctors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n ",
"end": 3569,
"score": 0.9998389482498169,
"start": 3557,
"tag": "NAME",
"value": "Maurice Page"
}
] | workspace/hello-web-1/src/hello_web_1/movies/service.clj | muthuishere/clojure-workshop-web-template | 0 | (ns hello-web-1.movies.service)
(def movies (atom [{:plot
"A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.",
:director "Tim Burton",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
{:plot
"The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.",
:director "Francis Ford Coppola",
:genres ["Crime" "Drama" "Music"],
:title "The Cotton Club",
:year "1984",
:actors "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee",
:id 2,
:runtime "127",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"}
{:plot
"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
:director "Frank Darabont",
:genres ["Crime" "Drama"],
:title "The Shawshank Redemption",
:year "1994",
:actors "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler",
:id 3,
:runtime "142",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"}
{:plot
"An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.",
:director "Peter Faiman",
:genres ["Adventure" "Comedy"],
:title "Crocodile Dundee",
:year "1986",
:actors "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil",
:id 4,
:runtime "97",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}]
) )
(defn all-movies []
@movies
)
(comment
(->> @movies
(filter #(= 1 (get % :id)))
first
)
(first @movies)
(movie-by-id 7872832)
)
;Exercise
(defn movie-by-id [id]
(->> @movies
(filter #(= id (get % :id)))
(first)
)
)
(defn insert-movie [movie]
(swap! movies conj movie)
movie
)
(comment
(update-movie 1 {:plot
"#9 Modified Plot again",
:director "Tim Burton",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
)
(println (:plot (movie-by-id 1)) )
)
(defn is-same-movie-id [id movie]
(= id (get movie :id))
)
(defn get-updated-movie-if-same-id [id movie-to-be-updated movie]
(if (is-same-movie-id id movie)
(merge movie movie-to-be-updated)
movie)
)
(defn update-movies-in [all-movies id movie-to-be-updated]
(let [partial-update-function (partial get-updated-movie-if-same-id id movie-to-be-updated)]
(->> all-movies
(map partial-update-function)
)
)
)
(defn update-movie [id movie-to-be-updated]
(swap! movies update-movies-in id movie-to-be-updated)
)
(comment
(delete-movie 1)
(println (:plot (movie-by-id 1)) )
)
(defn delete-movie [id]
(->> @movies
(remove #(= (:id %) id))
(reset! movies )
)
) | 90219 | (ns hello-web-1.movies.service)
(def movies (atom [{:plot
"A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.",
:director "<NAME>",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "<NAME>, <NAME>, <NAME>, <NAME>",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
{:plot
"The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.",
:director "<NAME>",
:genres ["Crime" "Drama" "Music"],
:title "The Cotton Club",
:year "1984",
:actors "<NAME>, <NAME>, <NAME>, <NAME>",
:id 2,
:runtime "127",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"}
{:plot
"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
:director "<NAME>",
:genres ["Crime" "Drama"],
:title "The Shawshank Redemption",
:year "1994",
:actors "<NAME>, <NAME>, <NAME>, <NAME>",
:id 3,
:runtime "142",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"}
{:plot
"An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.",
:director "<NAME>",
:genres ["Adventure" "Comedy"],
:title "Crocodile Dundee",
:year "1986",
:actors "<NAME>, <NAME>, <NAME>, <NAME>",
:id 4,
:runtime "97",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}]
) )
(defn all-movies []
@movies
)
(comment
(->> @movies
(filter #(= 1 (get % :id)))
first
)
(first @movies)
(movie-by-id 7872832)
)
;Exercise
(defn movie-by-id [id]
(->> @movies
(filter #(= id (get % :id)))
(first)
)
)
(defn insert-movie [movie]
(swap! movies conj movie)
movie
)
(comment
(update-movie 1 {:plot
"#9 Modified Plot again",
:director "<NAME>",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "<NAME>, <NAME>, <NAME>, <NAME>",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
)
(println (:plot (movie-by-id 1)) )
)
(defn is-same-movie-id [id movie]
(= id (get movie :id))
)
(defn get-updated-movie-if-same-id [id movie-to-be-updated movie]
(if (is-same-movie-id id movie)
(merge movie movie-to-be-updated)
movie)
)
(defn update-movies-in [all-movies id movie-to-be-updated]
(let [partial-update-function (partial get-updated-movie-if-same-id id movie-to-be-updated)]
(->> all-movies
(map partial-update-function)
)
)
)
(defn update-movie [id movie-to-be-updated]
(swap! movies update-movies-in id movie-to-be-updated)
)
(comment
(delete-movie 1)
(println (:plot (movie-by-id 1)) )
)
(defn delete-movie [id]
(->> @movies
(remove #(= (:id %) id))
(reset! movies )
)
) | true | (ns hello-web-1.movies.service)
(def movies (atom [{:plot
"A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.",
:director "PI:NAME:<NAME>END_PI",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
{:plot
"The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.",
:director "PI:NAME:<NAME>END_PI",
:genres ["Crime" "Drama" "Music"],
:title "The Cotton Club",
:year "1984",
:actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:id 2,
:runtime "127",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"}
{:plot
"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
:director "PI:NAME:<NAME>END_PI",
:genres ["Crime" "Drama"],
:title "The Shawshank Redemption",
:year "1994",
:actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:id 3,
:runtime "142",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"}
{:plot
"An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.",
:director "PI:NAME:<NAME>END_PI",
:genres ["Adventure" "Comedy"],
:title "Crocodile Dundee",
:year "1986",
:actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:id 4,
:runtime "97",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}]
) )
(defn all-movies []
@movies
)
(comment
(->> @movies
(filter #(= 1 (get % :id)))
first
)
(first @movies)
(movie-by-id 7872832)
)
;Exercise
(defn movie-by-id [id]
(->> @movies
(filter #(= id (get % :id)))
(first)
)
)
(defn insert-movie [movie]
(swap! movies conj movie)
movie
)
(comment
(update-movie 1 {:plot
"#9 Modified Plot again",
:director "PI:NAME:<NAME>END_PI",
:genres ["Comedy" "Fantasy"],
:title "Beetlejuice",
:year "1988",
:actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI",
:id 1,
:runtime "92",
:posterUrl
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"}
)
(println (:plot (movie-by-id 1)) )
)
(defn is-same-movie-id [id movie]
(= id (get movie :id))
)
(defn get-updated-movie-if-same-id [id movie-to-be-updated movie]
(if (is-same-movie-id id movie)
(merge movie movie-to-be-updated)
movie)
)
(defn update-movies-in [all-movies id movie-to-be-updated]
(let [partial-update-function (partial get-updated-movie-if-same-id id movie-to-be-updated)]
(->> all-movies
(map partial-update-function)
)
)
)
(defn update-movie [id movie-to-be-updated]
(swap! movies update-movies-in id movie-to-be-updated)
)
(comment
(delete-movie 1)
(println (:plot (movie-by-id 1)) )
)
(defn delete-movie [id]
(->> @movies
(remove #(= (:id %) id))
(reset! movies )
)
) |
[
{
"context": "(defproject io.eidel/hcloud \"1.0.0\"\n :author \"Oliver Eidel <http://www.eidel.io>\"\n :description \"Clojure li",
"end": 59,
"score": 0.9998635649681091,
"start": 47,
"tag": "NAME",
"value": "Oliver Eidel"
},
{
"context": "he Hetzner Cloud API.\"\n :url \"https://github.com/olieidel/hcloud\"\n :license {:name \"MIT License\"\n ",
"end": 178,
"score": 0.7803003191947937,
"start": 170,
"tag": "USERNAME",
"value": "olieidel"
}
] | project.clj | olieidel/hcloud | 13 | (defproject io.eidel/hcloud "1.0.0"
:author "Oliver Eidel <http://www.eidel.io>"
:description "Clojure library for the Hetzner Cloud API."
:url "https://github.com/olieidel/hcloud"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo}
:dependencies
[[org.clojure/clojure "1.9.0"]
[clj-http "3.9.1"]
[cheshire "5.8.1"]
[camel-snake-kebab "0.4.0"]]
:profiles
{:dev
{:dependencies
[[http-kit "2.3.0"]
[org.flatland/ordered "1.5.6"]]}}
:plugins
[[lein-ancient "0.6.15"]
[lein-codox "0.10.4"]]
:codox {:metadata {:doc/format :markdown}})
| 84975 | (defproject io.eidel/hcloud "1.0.0"
:author "<NAME> <http://www.eidel.io>"
:description "Clojure library for the Hetzner Cloud API."
:url "https://github.com/olieidel/hcloud"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo}
:dependencies
[[org.clojure/clojure "1.9.0"]
[clj-http "3.9.1"]
[cheshire "5.8.1"]
[camel-snake-kebab "0.4.0"]]
:profiles
{:dev
{:dependencies
[[http-kit "2.3.0"]
[org.flatland/ordered "1.5.6"]]}}
:plugins
[[lein-ancient "0.6.15"]
[lein-codox "0.10.4"]]
:codox {:metadata {:doc/format :markdown}})
| true | (defproject io.eidel/hcloud "1.0.0"
:author "PI:NAME:<NAME>END_PI <http://www.eidel.io>"
:description "Clojure library for the Hetzner Cloud API."
:url "https://github.com/olieidel/hcloud"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:distribution :repo}
:dependencies
[[org.clojure/clojure "1.9.0"]
[clj-http "3.9.1"]
[cheshire "5.8.1"]
[camel-snake-kebab "0.4.0"]]
:profiles
{:dev
{:dependencies
[[http-kit "2.3.0"]
[org.flatland/ordered "1.5.6"]]}}
:plugins
[[lein-ancient "0.6.15"]
[lein-codox "0.10.4"]]
:codox {:metadata {:doc/format :markdown}})
|
[
{
"context": "r the License.\n;\n\n(ns\n ^{:doc \"\"\n :author \"Vladimir Tsanev\"}\n reactor-core.publisher\n (:refer-clojure :exc",
"end": 647,
"score": 0.999852180480957,
"start": 632,
"tag": "NAME",
"value": "Vladimir Tsanev"
}
] | src/reactor_core/publisher.clj | jaju/reactor-core-clojure | 2 | ;
; Copyright 2018 the original author or authors.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns
^{:doc ""
:author "Vladimir Tsanev"}
reactor-core.publisher
(:refer-clojure :exclude [concat delay empty filter map mapcat range reduce take take-while])
(:require
[reactor-core.protocols :as p]
[reactive-streams.jvm]
[reactor-core.util.core :refer [array?]]
[reactor-core.util.function :as f])
(:import
(reactor.core.publisher Flux Mono MonoProcessor)
(org.reactivestreams Subscriber Publisher)
(java.time Duration Instant)
(java.util.stream Stream)
(java.util.concurrent CompletionStage TimeUnit)))
(set! *warn-on-reflection* true)
(defn just
[data]
(Mono/just data))
(defn empty
[]
(Flux/empty))
(defn never
[]
(Flux/never))
(defn error
([error-or-fn]
(Mono/error (if (fn? error-or-fn) (error-or-fn) error-or-fn)))
([error-or-fn when-requested?]
(Flux/error (if (fn? error-or-fn) (error-or-fn) error-or-fn) when-requested?)))
(defn from-dispatch-fn [x]
(if (array? x)
::array
(type x)))
(derive Iterable ::iterable)
(derive Stream ::stream)
(derive CompletionStage ::promise)
(derive Publisher ::publisher)
(derive ::publisher ::mono)
(derive ::publisher ::flux)
(derive Mono ::mono)
(derive Flux ::flux)
(defmulti from "" ^Publisher from-dispatch-fn)
(defmethod from ::iterable [i] (Flux/fromIterable i))
(defmethod from ::stream [s] (Flux/fromStream ^Stream s))
(defmethod from ::array [a] (Flux/fromArray a))
(defmethod from ::promise [f] (Mono/fromCompletionStage f))
(defmethod from ::publisher [p] (Flux/from p))
(defmethod from ::mono [m] m)
(defmethod from ::flux [f] f)
(defmethod p/-zip [::mono 2] ([monos & [combinator]]
(Mono/zip (f/as-function combinator)
^"[Lreactor.core.publisher.Mono;" (to-array monos))))
;; cannot use extend-type because of https://dev.clojure.org/jira/browse/CLJ-825
(extend Flux
p/FlatMapOperator
{:-flat-map
(fn [^Flux flux mapper]
(.flatMap flux (f/as-function mapper)))
:-concat-map
(fn
([^Flux flux mapper] (.concatMap flux (f/as-function mapper)))
([^Flux flux mapper prefetch] (.concatMap flux (f/as-function mapper) prefetch)))})
(extend-type Flux
p/MapOperator
(-map [flux transformer]
(.map flux (f/as-function transformer)))
p/FilterOperator
(-filter [flux predicate] (.filter flux (f/as-predicate predicate)))
p/TakeOperator
(-take [flux n] (.take flux ^long n))
p/SkipOperator
(-skip [flux n] (.skip flux ^long n))
p/ZipOperator
(-zip-with [flux other combinator] (.zipWith flux ^Publisher other (f/as-bi-function combinator)))
p/HideOperator
(-hide [flux] (.hide flux))
p/TakeUntilOperator
(-take-until [flux other] (.takeUntilOther flux other)))
(extend-type Mono
p/MapOperator
(-map [mono transformer]
(.map mono (f/as-function transformer)))
p/FilterOperator
(-filter [mono predicate] (.filter mono (f/as-predicate predicate)))
p/ZipOperator
(-zip-with [mono other combinator] (.zipWith mono other (f/as-bi-function combinator)))
p/HideOperator
(-hide [mono] (.hide mono))
p/TakeUntilOperator
(-take-until [mono other] (.takeUntilOther mono other)))
(defn- inst->delay
"Converts an inst to delay"
[x]
(-> (Instant/ofEpochMilli x)
(.minusMillis (System/currentTimeMillis))))
(defn- duration ^Duration
[d]
(if (instance? Duration d) d (Duration/ofMillis d)))
(defn- delay-duration ^Duration
[delay]
(cond
(inst? delay)
(Duration/ofMillis (inst->delay delay))
:else
(duration delay)))
(defn interval
([period]
(Flux/interval (duration period)))
([delay period]
(Flux/interval (delay-duration delay) (duration period))))
(defn delay
[delay]
(Mono/delay (delay-duration delay)))
(defn concat
[sources]
(Flux/concat ^Iterable sources))
(defn mono-processor
([]
(mono-processor nil))
([source]
(cond (instance? MonoProcessor source) source
(instance? Mono source) (.toProcessor ^Mono source)
(instance? Flux source) (.publishNext ^Flux source)
(nil? source) (MonoProcessor/create))))
(defn create
([emitter]
(create emitter :buffer))
([emitter back-pressure]
(create emitter back-pressure false))
([emitter back-pressure push?]
(let [consumer (f/as-consumer emitter)]
(if push?
(Flux/push consumer)
(Flux/create consumer)))))
(defn zip
([sources zipper]
(cond
(= 2 (count sources))
(p/-zip-with (first sources) (second sources) zipper)
;(Flux/zip ^Publisher (first sources) ^Publisher (second sources) (f/as-bi-function zipper))
:else
(Flux/zip ^Iterable sources (f/as-function zipper))))
([sources zipper prefetch]
(cond
(array? sources)
(Flux/zip (f/as-function zipper) ^int prefetch ^"[Lorg.reactivestreams.Publisher;" (to-array sources))
:else
(Flux/zip ^Iterable sources ^int prefetch (f/as-function zipper)))))
(defn range
[start count]
(Flux/range start count))
;; filtering
(defn filter
[predicate publisher]
(p/-filter publisher predicate))
(defn skip
[skipped publisher]
(p/-skip publisher skipped))
(defn take
[n publisher]
(p/-take publisher n))
;; conditional
(defn take-while
[p ^Flux flux]
(.takeWhile flux (f/as-predicate p)))
;; transforming
(defn map
[mapper publisher]
(p/-map publisher mapper))
(defn mapcat
([mapper publisher]
(p/-concat-map publisher mapper))
([mapper prefetch publisher]
(p/-concat-map publisher mapper prefetch)))
(defn flat-map
[mapper publisher]
(p/-flat-map publisher mapper))
(defn flat-map-sequential
[mapper ^Flux flux]
(.flatMapSequential flux (f/as-function mapper)))
;; utility
(defn hide
[publisher]
(p/-hide publisher))
;; conditional
(defn take-until
[other publisher]
(p/-take-until publisher other))
;; aggregate
(defn reduce
([aggregator ^Flux flux]
(.reduce flux (f/as-bi-function aggregator)))
([accumulator initial ^Flux flux]
(.reduce flux initial (f/as-bi-function accumulator))))
(defn subscribe-with
[^Subscriber s ^Publisher p]
(.subscribe p s)
s)
(defn subscribe
([^Publisher p]
(subscribe nil nil nil p))
([on-next ^Publisher p]
(subscribe on-next nil p))
([on-next on-error ^Publisher p]
(subscribe on-next on-error nil p))
([on-next on-error on-complete ^Publisher p]
(subscribe on-next on-error on-complete nil p))
([on-next on-error on-complete on-subscribe ^Publisher p]
(cond
(instance? Mono p)
(.subscribe ^Mono p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
(instance? Flux p)
(.subscribe ^Flux p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
:else
(subscribe-with (reify Subscriber
(onNext [_ n] (on-next n))
(onError [_ e] (on-error e))
(onComplete [_] (on-complete))
(onSubscribe [_ s] (on-subscribe s))) p))))
| 51754 | ;
; Copyright 2018 the original author or authors.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns
^{:doc ""
:author "<NAME>"}
reactor-core.publisher
(:refer-clojure :exclude [concat delay empty filter map mapcat range reduce take take-while])
(:require
[reactor-core.protocols :as p]
[reactive-streams.jvm]
[reactor-core.util.core :refer [array?]]
[reactor-core.util.function :as f])
(:import
(reactor.core.publisher Flux Mono MonoProcessor)
(org.reactivestreams Subscriber Publisher)
(java.time Duration Instant)
(java.util.stream Stream)
(java.util.concurrent CompletionStage TimeUnit)))
(set! *warn-on-reflection* true)
(defn just
[data]
(Mono/just data))
(defn empty
[]
(Flux/empty))
(defn never
[]
(Flux/never))
(defn error
([error-or-fn]
(Mono/error (if (fn? error-or-fn) (error-or-fn) error-or-fn)))
([error-or-fn when-requested?]
(Flux/error (if (fn? error-or-fn) (error-or-fn) error-or-fn) when-requested?)))
(defn from-dispatch-fn [x]
(if (array? x)
::array
(type x)))
(derive Iterable ::iterable)
(derive Stream ::stream)
(derive CompletionStage ::promise)
(derive Publisher ::publisher)
(derive ::publisher ::mono)
(derive ::publisher ::flux)
(derive Mono ::mono)
(derive Flux ::flux)
(defmulti from "" ^Publisher from-dispatch-fn)
(defmethod from ::iterable [i] (Flux/fromIterable i))
(defmethod from ::stream [s] (Flux/fromStream ^Stream s))
(defmethod from ::array [a] (Flux/fromArray a))
(defmethod from ::promise [f] (Mono/fromCompletionStage f))
(defmethod from ::publisher [p] (Flux/from p))
(defmethod from ::mono [m] m)
(defmethod from ::flux [f] f)
(defmethod p/-zip [::mono 2] ([monos & [combinator]]
(Mono/zip (f/as-function combinator)
^"[Lreactor.core.publisher.Mono;" (to-array monos))))
;; cannot use extend-type because of https://dev.clojure.org/jira/browse/CLJ-825
(extend Flux
p/FlatMapOperator
{:-flat-map
(fn [^Flux flux mapper]
(.flatMap flux (f/as-function mapper)))
:-concat-map
(fn
([^Flux flux mapper] (.concatMap flux (f/as-function mapper)))
([^Flux flux mapper prefetch] (.concatMap flux (f/as-function mapper) prefetch)))})
(extend-type Flux
p/MapOperator
(-map [flux transformer]
(.map flux (f/as-function transformer)))
p/FilterOperator
(-filter [flux predicate] (.filter flux (f/as-predicate predicate)))
p/TakeOperator
(-take [flux n] (.take flux ^long n))
p/SkipOperator
(-skip [flux n] (.skip flux ^long n))
p/ZipOperator
(-zip-with [flux other combinator] (.zipWith flux ^Publisher other (f/as-bi-function combinator)))
p/HideOperator
(-hide [flux] (.hide flux))
p/TakeUntilOperator
(-take-until [flux other] (.takeUntilOther flux other)))
(extend-type Mono
p/MapOperator
(-map [mono transformer]
(.map mono (f/as-function transformer)))
p/FilterOperator
(-filter [mono predicate] (.filter mono (f/as-predicate predicate)))
p/ZipOperator
(-zip-with [mono other combinator] (.zipWith mono other (f/as-bi-function combinator)))
p/HideOperator
(-hide [mono] (.hide mono))
p/TakeUntilOperator
(-take-until [mono other] (.takeUntilOther mono other)))
(defn- inst->delay
"Converts an inst to delay"
[x]
(-> (Instant/ofEpochMilli x)
(.minusMillis (System/currentTimeMillis))))
(defn- duration ^Duration
[d]
(if (instance? Duration d) d (Duration/ofMillis d)))
(defn- delay-duration ^Duration
[delay]
(cond
(inst? delay)
(Duration/ofMillis (inst->delay delay))
:else
(duration delay)))
(defn interval
([period]
(Flux/interval (duration period)))
([delay period]
(Flux/interval (delay-duration delay) (duration period))))
(defn delay
[delay]
(Mono/delay (delay-duration delay)))
(defn concat
[sources]
(Flux/concat ^Iterable sources))
(defn mono-processor
([]
(mono-processor nil))
([source]
(cond (instance? MonoProcessor source) source
(instance? Mono source) (.toProcessor ^Mono source)
(instance? Flux source) (.publishNext ^Flux source)
(nil? source) (MonoProcessor/create))))
(defn create
([emitter]
(create emitter :buffer))
([emitter back-pressure]
(create emitter back-pressure false))
([emitter back-pressure push?]
(let [consumer (f/as-consumer emitter)]
(if push?
(Flux/push consumer)
(Flux/create consumer)))))
(defn zip
([sources zipper]
(cond
(= 2 (count sources))
(p/-zip-with (first sources) (second sources) zipper)
;(Flux/zip ^Publisher (first sources) ^Publisher (second sources) (f/as-bi-function zipper))
:else
(Flux/zip ^Iterable sources (f/as-function zipper))))
([sources zipper prefetch]
(cond
(array? sources)
(Flux/zip (f/as-function zipper) ^int prefetch ^"[Lorg.reactivestreams.Publisher;" (to-array sources))
:else
(Flux/zip ^Iterable sources ^int prefetch (f/as-function zipper)))))
(defn range
[start count]
(Flux/range start count))
;; filtering
(defn filter
[predicate publisher]
(p/-filter publisher predicate))
(defn skip
[skipped publisher]
(p/-skip publisher skipped))
(defn take
[n publisher]
(p/-take publisher n))
;; conditional
(defn take-while
[p ^Flux flux]
(.takeWhile flux (f/as-predicate p)))
;; transforming
(defn map
[mapper publisher]
(p/-map publisher mapper))
(defn mapcat
([mapper publisher]
(p/-concat-map publisher mapper))
([mapper prefetch publisher]
(p/-concat-map publisher mapper prefetch)))
(defn flat-map
[mapper publisher]
(p/-flat-map publisher mapper))
(defn flat-map-sequential
[mapper ^Flux flux]
(.flatMapSequential flux (f/as-function mapper)))
;; utility
(defn hide
[publisher]
(p/-hide publisher))
;; conditional
(defn take-until
[other publisher]
(p/-take-until publisher other))
;; aggregate
(defn reduce
([aggregator ^Flux flux]
(.reduce flux (f/as-bi-function aggregator)))
([accumulator initial ^Flux flux]
(.reduce flux initial (f/as-bi-function accumulator))))
(defn subscribe-with
[^Subscriber s ^Publisher p]
(.subscribe p s)
s)
(defn subscribe
([^Publisher p]
(subscribe nil nil nil p))
([on-next ^Publisher p]
(subscribe on-next nil p))
([on-next on-error ^Publisher p]
(subscribe on-next on-error nil p))
([on-next on-error on-complete ^Publisher p]
(subscribe on-next on-error on-complete nil p))
([on-next on-error on-complete on-subscribe ^Publisher p]
(cond
(instance? Mono p)
(.subscribe ^Mono p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
(instance? Flux p)
(.subscribe ^Flux p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
:else
(subscribe-with (reify Subscriber
(onNext [_ n] (on-next n))
(onError [_ e] (on-error e))
(onComplete [_] (on-complete))
(onSubscribe [_ s] (on-subscribe s))) p))))
| true | ;
; Copyright 2018 the original author or authors.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns
^{:doc ""
:author "PI:NAME:<NAME>END_PI"}
reactor-core.publisher
(:refer-clojure :exclude [concat delay empty filter map mapcat range reduce take take-while])
(:require
[reactor-core.protocols :as p]
[reactive-streams.jvm]
[reactor-core.util.core :refer [array?]]
[reactor-core.util.function :as f])
(:import
(reactor.core.publisher Flux Mono MonoProcessor)
(org.reactivestreams Subscriber Publisher)
(java.time Duration Instant)
(java.util.stream Stream)
(java.util.concurrent CompletionStage TimeUnit)))
(set! *warn-on-reflection* true)
(defn just
[data]
(Mono/just data))
(defn empty
[]
(Flux/empty))
(defn never
[]
(Flux/never))
(defn error
([error-or-fn]
(Mono/error (if (fn? error-or-fn) (error-or-fn) error-or-fn)))
([error-or-fn when-requested?]
(Flux/error (if (fn? error-or-fn) (error-or-fn) error-or-fn) when-requested?)))
(defn from-dispatch-fn [x]
(if (array? x)
::array
(type x)))
(derive Iterable ::iterable)
(derive Stream ::stream)
(derive CompletionStage ::promise)
(derive Publisher ::publisher)
(derive ::publisher ::mono)
(derive ::publisher ::flux)
(derive Mono ::mono)
(derive Flux ::flux)
(defmulti from "" ^Publisher from-dispatch-fn)
(defmethod from ::iterable [i] (Flux/fromIterable i))
(defmethod from ::stream [s] (Flux/fromStream ^Stream s))
(defmethod from ::array [a] (Flux/fromArray a))
(defmethod from ::promise [f] (Mono/fromCompletionStage f))
(defmethod from ::publisher [p] (Flux/from p))
(defmethod from ::mono [m] m)
(defmethod from ::flux [f] f)
(defmethod p/-zip [::mono 2] ([monos & [combinator]]
(Mono/zip (f/as-function combinator)
^"[Lreactor.core.publisher.Mono;" (to-array monos))))
;; cannot use extend-type because of https://dev.clojure.org/jira/browse/CLJ-825
(extend Flux
p/FlatMapOperator
{:-flat-map
(fn [^Flux flux mapper]
(.flatMap flux (f/as-function mapper)))
:-concat-map
(fn
([^Flux flux mapper] (.concatMap flux (f/as-function mapper)))
([^Flux flux mapper prefetch] (.concatMap flux (f/as-function mapper) prefetch)))})
(extend-type Flux
p/MapOperator
(-map [flux transformer]
(.map flux (f/as-function transformer)))
p/FilterOperator
(-filter [flux predicate] (.filter flux (f/as-predicate predicate)))
p/TakeOperator
(-take [flux n] (.take flux ^long n))
p/SkipOperator
(-skip [flux n] (.skip flux ^long n))
p/ZipOperator
(-zip-with [flux other combinator] (.zipWith flux ^Publisher other (f/as-bi-function combinator)))
p/HideOperator
(-hide [flux] (.hide flux))
p/TakeUntilOperator
(-take-until [flux other] (.takeUntilOther flux other)))
(extend-type Mono
p/MapOperator
(-map [mono transformer]
(.map mono (f/as-function transformer)))
p/FilterOperator
(-filter [mono predicate] (.filter mono (f/as-predicate predicate)))
p/ZipOperator
(-zip-with [mono other combinator] (.zipWith mono other (f/as-bi-function combinator)))
p/HideOperator
(-hide [mono] (.hide mono))
p/TakeUntilOperator
(-take-until [mono other] (.takeUntilOther mono other)))
(defn- inst->delay
"Converts an inst to delay"
[x]
(-> (Instant/ofEpochMilli x)
(.minusMillis (System/currentTimeMillis))))
(defn- duration ^Duration
[d]
(if (instance? Duration d) d (Duration/ofMillis d)))
(defn- delay-duration ^Duration
[delay]
(cond
(inst? delay)
(Duration/ofMillis (inst->delay delay))
:else
(duration delay)))
(defn interval
([period]
(Flux/interval (duration period)))
([delay period]
(Flux/interval (delay-duration delay) (duration period))))
(defn delay
[delay]
(Mono/delay (delay-duration delay)))
(defn concat
[sources]
(Flux/concat ^Iterable sources))
(defn mono-processor
([]
(mono-processor nil))
([source]
(cond (instance? MonoProcessor source) source
(instance? Mono source) (.toProcessor ^Mono source)
(instance? Flux source) (.publishNext ^Flux source)
(nil? source) (MonoProcessor/create))))
(defn create
([emitter]
(create emitter :buffer))
([emitter back-pressure]
(create emitter back-pressure false))
([emitter back-pressure push?]
(let [consumer (f/as-consumer emitter)]
(if push?
(Flux/push consumer)
(Flux/create consumer)))))
(defn zip
([sources zipper]
(cond
(= 2 (count sources))
(p/-zip-with (first sources) (second sources) zipper)
;(Flux/zip ^Publisher (first sources) ^Publisher (second sources) (f/as-bi-function zipper))
:else
(Flux/zip ^Iterable sources (f/as-function zipper))))
([sources zipper prefetch]
(cond
(array? sources)
(Flux/zip (f/as-function zipper) ^int prefetch ^"[Lorg.reactivestreams.Publisher;" (to-array sources))
:else
(Flux/zip ^Iterable sources ^int prefetch (f/as-function zipper)))))
(defn range
[start count]
(Flux/range start count))
;; filtering
(defn filter
[predicate publisher]
(p/-filter publisher predicate))
(defn skip
[skipped publisher]
(p/-skip publisher skipped))
(defn take
[n publisher]
(p/-take publisher n))
;; conditional
(defn take-while
[p ^Flux flux]
(.takeWhile flux (f/as-predicate p)))
;; transforming
(defn map
[mapper publisher]
(p/-map publisher mapper))
(defn mapcat
([mapper publisher]
(p/-concat-map publisher mapper))
([mapper prefetch publisher]
(p/-concat-map publisher mapper prefetch)))
(defn flat-map
[mapper publisher]
(p/-flat-map publisher mapper))
(defn flat-map-sequential
[mapper ^Flux flux]
(.flatMapSequential flux (f/as-function mapper)))
;; utility
(defn hide
[publisher]
(p/-hide publisher))
;; conditional
(defn take-until
[other publisher]
(p/-take-until publisher other))
;; aggregate
(defn reduce
([aggregator ^Flux flux]
(.reduce flux (f/as-bi-function aggregator)))
([accumulator initial ^Flux flux]
(.reduce flux initial (f/as-bi-function accumulator))))
(defn subscribe-with
[^Subscriber s ^Publisher p]
(.subscribe p s)
s)
(defn subscribe
([^Publisher p]
(subscribe nil nil nil p))
([on-next ^Publisher p]
(subscribe on-next nil p))
([on-next on-error ^Publisher p]
(subscribe on-next on-error nil p))
([on-next on-error on-complete ^Publisher p]
(subscribe on-next on-error on-complete nil p))
([on-next on-error on-complete on-subscribe ^Publisher p]
(cond
(instance? Mono p)
(.subscribe ^Mono p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
(instance? Flux p)
(.subscribe ^Flux p
(f/as-consumer on-next)
(f/as-consumer on-error)
(f/as-runnable on-complete)
(f/as-consumer on-subscribe))
:else
(subscribe-with (reify Subscriber
(onNext [_ n] (on-next n))
(onError [_ e] (on-error e))
(onComplete [_] (on-complete))
(onSubscribe [_ s] (on-subscribe s))) p))))
|
[
{
"context": " 42\n :name \"A Test Org\"\n :slug ",
"end": 1740,
"score": 0.9172568917274475,
"start": 1739,
"tag": "NAME",
"value": "A"
},
{
"context": " :email \"foo@bar.com\"}]\n :joined [{:id 1\n ",
"end": 5179,
"score": 0.9999030828475952,
"start": 5168,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": " 1\n :name \"Sandy\"\n :email \"sand",
"end": 5277,
"score": 0.999647855758667,
"start": 5272,
"tag": "NAME",
"value": "Sandy"
},
{
"context": "andy\"\n :email \"sandy@nilenso.com\"}]}])))\n (rf/dispatch [::org-events/fetch-me",
"end": 5340,
"score": 0.9999265074729919,
"start": 5323,
"tag": "EMAIL",
"value": "sandy@nilenso.com"
},
{
"context": "anization-id 42\n :email \"foo@bar.com\"}}\n @(rf/subscribe [::org-subs/invite",
"end": 5519,
"score": 0.9999085664749146,
"start": 5508,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "\n (is (= #{{:id 1\n :name \"Sandy\"\n :email \"sandy@nilenso.com\"}}\n ",
"end": 5689,
"score": 0.9996655583381653,
"start": 5684,
"tag": "NAME",
"value": "Sandy"
},
{
"context": " :name \"Sandy\"\n :email \"sandy@nilenso.com\"}}\n @(rf/subscribe [::org-subs/joined",
"end": 5732,
"score": 0.9999193549156189,
"start": 5715,
"tag": "EMAIL",
"value": "sandy@nilenso.com"
},
{
"context": "ization-id 1\n :email \"foo@bar.com\"}])\n (is (= #{{:id 1\n ",
"end": 6718,
"score": 0.9998705983161926,
"start": 6707,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "organization-id 1\n :email \"foo@bar.com\"}}\n @(rf/subscribe [::org-subs/invited-",
"end": 6832,
"score": 0.9998733401298523,
"start": 6821,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": " 1\n :name \"A task\",\n :description \"A Descr",
"end": 10826,
"score": 0.7785625457763672,
"start": 10825,
"tag": "NAME",
"value": "A"
},
{
"context": " 2\n :name \"Another task\",\n :description \"Another",
"end": 11037,
"score": 0.6124598383903503,
"start": 11030,
"tag": "NAME",
"value": "Another"
}
] | test/cljs/chronograph_web/pages/admin/events_test.cljs | nilenso/chronograph | 3 | (ns chronograph-web.pages.admin.events-test
(:require [cljs.test :refer-macros [deftest is testing run-tests use-fixtures]]
[re-frame.core :as rf]
[re-frame.db]
[chronograph-web.pages.admin.events :as org-events]
[chronograph-web.events.tasks :as task-events]
[chronograph-web.pages.admin.subscriptions :as org-subs]
[chronograph-web.subscriptions :as subs]
[chronograph-web.test-utils :as tu]
[chronograph-web.fixtures :as fixtures]
[chronograph-web.routes :as routes]
[chronograph-web.db.organization :as org-db]
[chronograph-web.db.tasks :as db-tasks]))
(use-fixtures :once fixtures/silence-logging fixtures/check-specs)
(deftest organization-page-navigated-test
(tu/rf-test "When the org page is navigated to, the organization and tasks should be fetched"
(let [fetch-org-event (tu/stub-event ::org-events/fetch-organization)
fetch-tasks-event (tu/stub-event ::task-events/fetch-tasks)]
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/organization-page-navigated])
(is (= :admin-page @(rf/subscribe [::subs/page-key])) "the page-key should be set")
(is (= [::org-events/fetch-organization "test-slug"]
@fetch-org-event))
(is (= [::task-events/fetch-tasks "test-slug"]
@fetch-tasks-event)))))
(deftest fetch-organization-test
(testing "When the API call for fetch organization succeeds"
(tu/rf-test "When the user is a member of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug "a-test-org"
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= nil
@dispatched-event)
"The members should not be fetched")))
(tu/rf-test "When the user is an admin of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= [::org-events/fetch-members slug]
@dispatched-event)
"The members should be fetched"))))
(tu/rf-test "When the API call for fetch organization fails"
(let [slug "a-test-org"
error-params (tu/stub-effect :flash-error)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-fail])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest fetch-members-test
(tu/rf-test "When fetch members API calls succeed"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}]
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization-success
organization])
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-succeeded
{:invited [{:id 1
:organization-id 42
:email "foo@bar.com"}]
:joined [{:id 1
:name "Sandy"
:email "sandy@nilenso.com"}]}])))
(rf/dispatch [::org-events/fetch-members slug])
(is (= #{{:id 1
:organization-id 42
:email "foo@bar.com"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited members should be in the DB")
(is (= #{{:id 1
:name "Sandy"
:email "sandy@nilenso.com"}}
@(rf/subscribe [::org-subs/joined-members]))
"The joined members should be in the DB")))
(tu/rf-test "When fetching org members fails"
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-failed])))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/fetch-members ""])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest invite-member-form-test
(tu/rf-test "When the invite member form succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(rf/dispatch [::org-events/invite-member-succeeded
{:id 1
:organization-id 1
:email "foo@bar.com"}])
(is (= #{{:id 1
:organization-id 1
:email "foo@bar.com"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited member should be in the DB"))
(tu/rf-test "When the invite member form fails because the user is already in the organization"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed {:status 409}])
(is (some? @error-params)
"An error message should be flashed.")))
(tu/rf-test "When the invite member form fails for an unknown reason"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest create-task-form-test
(tu/rf-test "When create task fails"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/create-task-failed])
(is (empty? @(rf/subscribe [::org-subs/tasks]))
"There are no tasks for the organization in the db.")
(is (some? @error-params)
"An error message should be flashed."))))
(deftest update-task-form-test
(tu/rf-test "When updating a task succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(swap! re-frame.db/app-db org-db/add-org {:id 1
:name "A Test Org"
:slug "test-slug"
:role "admin"})
(swap! re-frame.db/app-db db-tasks/merge-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Another task",
:description "Another Description"
:organization-id 1
:archived-at nil}])
(let [updated-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Updated name",
:description "Updated description"
:organization-id 1
:archived-at nil}]]
(rf/reg-fx :http-xhrio
(fn [& _]
(rf/dispatch [::task-events/fetch-tasks-success
updated-tasks])))
(rf/dispatch [::org-events/update-task-success 2])
(is (= updated-tasks
@(rf/subscribe [::org-subs/tasks]))
"The tasks in the DB should be updated")
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))
"The task form should be closed")))
(tu/rf-test "When updating a task fails"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/update-task-failure 2])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest show-and-hide-update-task-form-test
(tu/rf-test "When the update form is shown or hidden for a task, the flag should be set accordingly"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(let [task1 {:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
task2 {:id 2
:name "Another task",
:description "Another Description"
:organization-id 1
:archived-at nil}]
(swap! re-frame.db/app-db db-tasks/merge-tasks [task1 task2])
(rf/dispatch [::org-events/show-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is @(rf/subscribe [::org-subs/show-update-task-form? 2]))
(rf/dispatch [::org-events/hide-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))))))
| 101750 | (ns chronograph-web.pages.admin.events-test
(:require [cljs.test :refer-macros [deftest is testing run-tests use-fixtures]]
[re-frame.core :as rf]
[re-frame.db]
[chronograph-web.pages.admin.events :as org-events]
[chronograph-web.events.tasks :as task-events]
[chronograph-web.pages.admin.subscriptions :as org-subs]
[chronograph-web.subscriptions :as subs]
[chronograph-web.test-utils :as tu]
[chronograph-web.fixtures :as fixtures]
[chronograph-web.routes :as routes]
[chronograph-web.db.organization :as org-db]
[chronograph-web.db.tasks :as db-tasks]))
(use-fixtures :once fixtures/silence-logging fixtures/check-specs)
(deftest organization-page-navigated-test
(tu/rf-test "When the org page is navigated to, the organization and tasks should be fetched"
(let [fetch-org-event (tu/stub-event ::org-events/fetch-organization)
fetch-tasks-event (tu/stub-event ::task-events/fetch-tasks)]
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/organization-page-navigated])
(is (= :admin-page @(rf/subscribe [::subs/page-key])) "the page-key should be set")
(is (= [::org-events/fetch-organization "test-slug"]
@fetch-org-event))
(is (= [::task-events/fetch-tasks "test-slug"]
@fetch-tasks-event)))))
(deftest fetch-organization-test
(testing "When the API call for fetch organization succeeds"
(tu/rf-test "When the user is a member of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "<NAME> Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug "a-test-org"
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= nil
@dispatched-event)
"The members should not be fetched")))
(tu/rf-test "When the user is an admin of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= [::org-events/fetch-members slug]
@dispatched-event)
"The members should be fetched"))))
(tu/rf-test "When the API call for fetch organization fails"
(let [slug "a-test-org"
error-params (tu/stub-effect :flash-error)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-fail])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest fetch-members-test
(tu/rf-test "When fetch members API calls succeed"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}]
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization-success
organization])
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-succeeded
{:invited [{:id 1
:organization-id 42
:email "<EMAIL>"}]
:joined [{:id 1
:name "<NAME>"
:email "<EMAIL>"}]}])))
(rf/dispatch [::org-events/fetch-members slug])
(is (= #{{:id 1
:organization-id 42
:email "<EMAIL>"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited members should be in the DB")
(is (= #{{:id 1
:name "<NAME>"
:email "<EMAIL>"}}
@(rf/subscribe [::org-subs/joined-members]))
"The joined members should be in the DB")))
(tu/rf-test "When fetching org members fails"
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-failed])))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/fetch-members ""])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest invite-member-form-test
(tu/rf-test "When the invite member form succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(rf/dispatch [::org-events/invite-member-succeeded
{:id 1
:organization-id 1
:email "<EMAIL>"}])
(is (= #{{:id 1
:organization-id 1
:email "<EMAIL>"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited member should be in the DB"))
(tu/rf-test "When the invite member form fails because the user is already in the organization"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed {:status 409}])
(is (some? @error-params)
"An error message should be flashed.")))
(tu/rf-test "When the invite member form fails for an unknown reason"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest create-task-form-test
(tu/rf-test "When create task fails"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/create-task-failed])
(is (empty? @(rf/subscribe [::org-subs/tasks]))
"There are no tasks for the organization in the db.")
(is (some? @error-params)
"An error message should be flashed."))))
(deftest update-task-form-test
(tu/rf-test "When updating a task succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(swap! re-frame.db/app-db org-db/add-org {:id 1
:name "A Test Org"
:slug "test-slug"
:role "admin"})
(swap! re-frame.db/app-db db-tasks/merge-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Another task",
:description "Another Description"
:organization-id 1
:archived-at nil}])
(let [updated-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Updated name",
:description "Updated description"
:organization-id 1
:archived-at nil}]]
(rf/reg-fx :http-xhrio
(fn [& _]
(rf/dispatch [::task-events/fetch-tasks-success
updated-tasks])))
(rf/dispatch [::org-events/update-task-success 2])
(is (= updated-tasks
@(rf/subscribe [::org-subs/tasks]))
"The tasks in the DB should be updated")
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))
"The task form should be closed")))
(tu/rf-test "When updating a task fails"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/update-task-failure 2])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest show-and-hide-update-task-form-test
(tu/rf-test "When the update form is shown or hidden for a task, the flag should be set accordingly"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(let [task1 {:id 1
:name "<NAME> task",
:description "A Description"
:organization-id 1
:archived-at nil}
task2 {:id 2
:name "<NAME> task",
:description "Another Description"
:organization-id 1
:archived-at nil}]
(swap! re-frame.db/app-db db-tasks/merge-tasks [task1 task2])
(rf/dispatch [::org-events/show-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is @(rf/subscribe [::org-subs/show-update-task-form? 2]))
(rf/dispatch [::org-events/hide-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))))))
| true | (ns chronograph-web.pages.admin.events-test
(:require [cljs.test :refer-macros [deftest is testing run-tests use-fixtures]]
[re-frame.core :as rf]
[re-frame.db]
[chronograph-web.pages.admin.events :as org-events]
[chronograph-web.events.tasks :as task-events]
[chronograph-web.pages.admin.subscriptions :as org-subs]
[chronograph-web.subscriptions :as subs]
[chronograph-web.test-utils :as tu]
[chronograph-web.fixtures :as fixtures]
[chronograph-web.routes :as routes]
[chronograph-web.db.organization :as org-db]
[chronograph-web.db.tasks :as db-tasks]))
(use-fixtures :once fixtures/silence-logging fixtures/check-specs)
(deftest organization-page-navigated-test
(tu/rf-test "When the org page is navigated to, the organization and tasks should be fetched"
(let [fetch-org-event (tu/stub-event ::org-events/fetch-organization)
fetch-tasks-event (tu/stub-event ::task-events/fetch-tasks)]
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/organization-page-navigated])
(is (= :admin-page @(rf/subscribe [::subs/page-key])) "the page-key should be set")
(is (= [::org-events/fetch-organization "test-slug"]
@fetch-org-event))
(is (= [::task-events/fetch-tasks "test-slug"]
@fetch-tasks-event)))))
(deftest fetch-organization-test
(testing "When the API call for fetch organization succeeds"
(tu/rf-test "When the user is a member of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "PI:NAME:<NAME>END_PI Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug "a-test-org"
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= nil
@dispatched-event)
"The members should not be fetched")))
(tu/rf-test "When the user is an admin of the organization"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
dispatched-event (tu/stub-event ::org-events/fetch-members)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-success
organization])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (= {:id 42
:name "A Test Org"
:slug slug
:role "admin"}
@(rf/subscribe [::subs/organization slug]))
"The fetched organization should be in the DB")
(is (= [::org-events/fetch-members slug]
@dispatched-event)
"The members should be fetched"))))
(tu/rf-test "When the API call for fetch organization fails"
(let [slug "a-test-org"
error-params (tu/stub-effect :flash-error)]
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-organization-fail])))
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization slug])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest fetch-members-test
(tu/rf-test "When fetch members API calls succeed"
(let [slug "a-test-org"
organization {:id 42
:name "A Test Org"
:slug slug
:role "member"
:created-at "2020-09-14T14:16:06.402873Z"
:updated-at "2020-09-14T14:16:06.402873Z"}]
(tu/set-token (routes/path-for :admin-page :slug slug))
(rf/dispatch [::org-events/fetch-organization-success
organization])
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-succeeded
{:invited [{:id 1
:organization-id 42
:email "PI:EMAIL:<EMAIL>END_PI"}]
:joined [{:id 1
:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}]}])))
(rf/dispatch [::org-events/fetch-members slug])
(is (= #{{:id 1
:organization-id 42
:email "PI:EMAIL:<EMAIL>END_PI"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited members should be in the DB")
(is (= #{{:id 1
:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}
@(rf/subscribe [::org-subs/joined-members]))
"The joined members should be in the DB")))
(tu/rf-test "When fetching org members fails"
(rf/reg-fx :http-xhrio
(fn [_]
(rf/dispatch [::org-events/fetch-members-failed])))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/fetch-members ""])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest invite-member-form-test
(tu/rf-test "When the invite member form succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(rf/dispatch [::org-events/invite-member-succeeded
{:id 1
:organization-id 1
:email "PI:EMAIL:<EMAIL>END_PI"}])
(is (= #{{:id 1
:organization-id 1
:email "PI:EMAIL:<EMAIL>END_PI"}}
@(rf/subscribe [::org-subs/invited-members]))
"The invited member should be in the DB"))
(tu/rf-test "When the invite member form fails because the user is already in the organization"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed {:status 409}])
(is (some? @error-params)
"An error message should be flashed.")))
(tu/rf-test "When the invite member form fails for an unknown reason"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/invite-member-failed])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest create-task-form-test
(tu/rf-test "When create task fails"
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/create-task-failed])
(is (empty? @(rf/subscribe [::org-subs/tasks]))
"There are no tasks for the organization in the db.")
(is (some? @error-params)
"An error message should be flashed."))))
(deftest update-task-form-test
(tu/rf-test "When updating a task succeeds"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(swap! re-frame.db/app-db org-db/add-org {:id 1
:name "A Test Org"
:slug "test-slug"
:role "admin"})
(swap! re-frame.db/app-db db-tasks/merge-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Another task",
:description "Another Description"
:organization-id 1
:archived-at nil}])
(let [updated-tasks [{:id 1
:name "A task",
:description "A Description"
:organization-id 1
:archived-at nil}
{:id 2
:name "Updated name",
:description "Updated description"
:organization-id 1
:archived-at nil}]]
(rf/reg-fx :http-xhrio
(fn [& _]
(rf/dispatch [::task-events/fetch-tasks-success
updated-tasks])))
(rf/dispatch [::org-events/update-task-success 2])
(is (= updated-tasks
@(rf/subscribe [::org-subs/tasks]))
"The tasks in the DB should be updated")
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))
"The task form should be closed")))
(tu/rf-test "When updating a task fails"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(let [error-params (tu/stub-effect :flash-error)]
(rf/dispatch [::org-events/update-task-failure 2])
(is (some? @error-params)
"An error message should be flashed."))))
(deftest show-and-hide-update-task-form-test
(tu/rf-test "When the update form is shown or hidden for a task, the flag should be set accordingly"
(tu/set-token (routes/path-for :admin-page :slug "test-slug"))
(rf/dispatch [::org-events/fetch-organization-success
{:id 1
:name "A Test Org"
:slug "test-slug"
:role "member"}])
(let [task1 {:id 1
:name "PI:NAME:<NAME>END_PI task",
:description "A Description"
:organization-id 1
:archived-at nil}
task2 {:id 2
:name "PI:NAME:<NAME>END_PI task",
:description "Another Description"
:organization-id 1
:archived-at nil}]
(swap! re-frame.db/app-db db-tasks/merge-tasks [task1 task2])
(rf/dispatch [::org-events/show-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is @(rf/subscribe [::org-subs/show-update-task-form? 2]))
(rf/dispatch [::org-events/hide-update-task-form 2])
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 1])))
(is (not @(rf/subscribe [::org-subs/show-update-task-form? 2]))))))
|
[
{
"context": "fmulti for set intersection testing.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017",
"end": 258,
"score": 0.8434706926345825,
"start": 255,
"tag": "EMAIL",
"value": "pal"
},
{
"context": "lti for set intersection testing.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-0",
"end": 260,
"score": 0.6208605766296387,
"start": 258,
"tag": "NAME",
"value": "is"
},
{
"context": "i for set intersection testing.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-20\"\n :version \"2017-09-09\"}",
"end": 291,
"score": 0.8321163654327393,
"start": 260,
"tag": "EMAIL",
"value": "ades dot lakes at gmail dot com"
}
] | src/main/clojure/palisades/lakes/multix/sets/multi.clj | palisades-lakes/multimethod-experiments | 5 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.multi
{:doc "clojure.core/defmulti for set intersection testing."
:author "palisades dot lakes at gmail dot com"
:since "2017-04-20"
:version "2017-09-09"}
(:refer-clojure :exclude [contains?])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(defmulti ^Double/TYPE diameter
"Max distance between elements. 2 methods."
{}
class)
;;----------------------------------------------------------------
(defmethod diameter java.util.Set ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
(defmethod diameter Set ^double [^Set s] (.diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(defmulti intersects?
"Test for general set intersection. 9 methods."
{}
(fn intersects?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod intersects?
[IntegerInterval IntegerInterval]
[^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval DoubleInterval]
[^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval java.util.Set]
[^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[DoubleInterval IntegerInterval]
[^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[DoubleInterval DoubleInterval]
[^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[DoubleInterval java.util.Set]
[^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[java.util.Set IntegerInterval]
[^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set DoubleInterval]
[^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set java.util.Set]
[^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(defmulti contains?
"Test for general set containment. 43 methods"
(fn contains?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod contains? [java.util.Set Object] [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(defmethod contains? [ByteInterval Byte] [^ByteInterval s ^Byte x] (.contains s x))
(defmethod contains? [ByteInterval Double] [^ByteInterval s ^Double x] (.contains s x))
(defmethod contains? [ByteInterval Float] [^ByteInterval s ^Float x] (.contains s x))
(defmethod contains? [ByteInterval Integer] [^ByteInterval s ^Integer x] (.contains s x))
(defmethod contains? [ByteInterval Long] [^ByteInterval s ^Long x] (.contains s x))
(defmethod contains? [ByteInterval Short] [^ByteInterval s ^Short x] (.contains s x))
(defmethod contains? [ByteInterval Object] [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [DoubleInterval Byte] [^DoubleInterval s ^Byte x] (.contains s x))
(defmethod contains? [DoubleInterval Double] [^DoubleInterval s ^Double x] (.contains s x))
(defmethod contains? [DoubleInterval Float] [^DoubleInterval s ^Float x] (.contains s x))
(defmethod contains? [DoubleInterval Integer] [^DoubleInterval s ^Integer x] (.contains s x))
(defmethod contains? [DoubleInterval Long] [^DoubleInterval s ^Long x] (.contains s x))
(defmethod contains? [DoubleInterval Short] [^DoubleInterval s ^Short x] (.contains s x))
(defmethod contains? [DoubleInterval Object] [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [FloatInterval Byte] [^FloatInterval s ^Byte x] (.contains s x))
(defmethod contains? [FloatInterval Double] [^FloatInterval s ^Double x] (.contains s x))
(defmethod contains? [FloatInterval Float] [^FloatInterval s ^Float x] (.contains s x))
(defmethod contains? [FloatInterval Integer] [^FloatInterval s ^Integer x] (.contains s x))
(defmethod contains? [FloatInterval Long] [^FloatInterval s ^Long x] (.contains s x))
(defmethod contains? [FloatInterval Short] [^FloatInterval s ^Short x] (.contains s x))
(defmethod contains? [FloatInterval Object] [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [IntegerInterval Byte] [^IntegerInterval s ^Byte x] (.contains s x))
(defmethod contains? [IntegerInterval Double] [^IntegerInterval s ^Double x] (.contains s x))
(defmethod contains? [IntegerInterval Float] [^IntegerInterval s ^Float x] (.contains s x))
(defmethod contains? [IntegerInterval Integer] [^IntegerInterval s ^Integer x] (.contains s x))
(defmethod contains? [IntegerInterval Long] [^IntegerInterval s ^Long x] (.contains s x))
(defmethod contains? [IntegerInterval Short] [^IntegerInterval s ^Short x] (.contains s x))
(defmethod contains? [IntegerInterval Object] [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [LongInterval Byte] [^LongInterval s ^Byte x] (.contains s x))
(defmethod contains? [LongInterval Double] [^LongInterval s ^Double x] (.contains s x))
(defmethod contains? [LongInterval Float] [^LongInterval s ^Float x] (.contains s x))
(defmethod contains? [LongInterval Integer] [^LongInterval s ^Integer x] (.contains s x))
(defmethod contains? [LongInterval Long] [^LongInterval s ^Long x] (.contains s x))
(defmethod contains? [LongInterval Short] [^LongInterval s ^Short x] (.contains s x))
(defmethod contains? [LongInterval Object] [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [ShortInterval Byte] [^ShortInterval s ^Byte x] (.contains s x))
(defmethod contains? [ShortInterval Double] [^ShortInterval s ^Double x] (.contains s x))
(defmethod contains? [ShortInterval Float] [^ShortInterval s ^Float x] (.contains s x))
(defmethod contains? [ShortInterval Integer] [^ShortInterval s ^Integer x] (.contains s x))
(defmethod contains? [ShortInterval Long] [^ShortInterval s ^Long x] (.contains s x))
(defmethod contains? [ShortInterval Short] [^ShortInterval s ^Short x] (.contains s x))
(defmethod contains? [ShortInterval Object] [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
| 73961 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.multi
{:doc "clojure.core/defmulti for set intersection testing."
:author "<EMAIL> <NAME> <EMAIL>"
:since "2017-04-20"
:version "2017-09-09"}
(:refer-clojure :exclude [contains?])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(defmulti ^Double/TYPE diameter
"Max distance between elements. 2 methods."
{}
class)
;;----------------------------------------------------------------
(defmethod diameter java.util.Set ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
(defmethod diameter Set ^double [^Set s] (.diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(defmulti intersects?
"Test for general set intersection. 9 methods."
{}
(fn intersects?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod intersects?
[IntegerInterval IntegerInterval]
[^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval DoubleInterval]
[^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval java.util.Set]
[^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[DoubleInterval IntegerInterval]
[^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[DoubleInterval DoubleInterval]
[^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[DoubleInterval java.util.Set]
[^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[java.util.Set IntegerInterval]
[^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set DoubleInterval]
[^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set java.util.Set]
[^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(defmulti contains?
"Test for general set containment. 43 methods"
(fn contains?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod contains? [java.util.Set Object] [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(defmethod contains? [ByteInterval Byte] [^ByteInterval s ^Byte x] (.contains s x))
(defmethod contains? [ByteInterval Double] [^ByteInterval s ^Double x] (.contains s x))
(defmethod contains? [ByteInterval Float] [^ByteInterval s ^Float x] (.contains s x))
(defmethod contains? [ByteInterval Integer] [^ByteInterval s ^Integer x] (.contains s x))
(defmethod contains? [ByteInterval Long] [^ByteInterval s ^Long x] (.contains s x))
(defmethod contains? [ByteInterval Short] [^ByteInterval s ^Short x] (.contains s x))
(defmethod contains? [ByteInterval Object] [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [DoubleInterval Byte] [^DoubleInterval s ^Byte x] (.contains s x))
(defmethod contains? [DoubleInterval Double] [^DoubleInterval s ^Double x] (.contains s x))
(defmethod contains? [DoubleInterval Float] [^DoubleInterval s ^Float x] (.contains s x))
(defmethod contains? [DoubleInterval Integer] [^DoubleInterval s ^Integer x] (.contains s x))
(defmethod contains? [DoubleInterval Long] [^DoubleInterval s ^Long x] (.contains s x))
(defmethod contains? [DoubleInterval Short] [^DoubleInterval s ^Short x] (.contains s x))
(defmethod contains? [DoubleInterval Object] [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [FloatInterval Byte] [^FloatInterval s ^Byte x] (.contains s x))
(defmethod contains? [FloatInterval Double] [^FloatInterval s ^Double x] (.contains s x))
(defmethod contains? [FloatInterval Float] [^FloatInterval s ^Float x] (.contains s x))
(defmethod contains? [FloatInterval Integer] [^FloatInterval s ^Integer x] (.contains s x))
(defmethod contains? [FloatInterval Long] [^FloatInterval s ^Long x] (.contains s x))
(defmethod contains? [FloatInterval Short] [^FloatInterval s ^Short x] (.contains s x))
(defmethod contains? [FloatInterval Object] [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [IntegerInterval Byte] [^IntegerInterval s ^Byte x] (.contains s x))
(defmethod contains? [IntegerInterval Double] [^IntegerInterval s ^Double x] (.contains s x))
(defmethod contains? [IntegerInterval Float] [^IntegerInterval s ^Float x] (.contains s x))
(defmethod contains? [IntegerInterval Integer] [^IntegerInterval s ^Integer x] (.contains s x))
(defmethod contains? [IntegerInterval Long] [^IntegerInterval s ^Long x] (.contains s x))
(defmethod contains? [IntegerInterval Short] [^IntegerInterval s ^Short x] (.contains s x))
(defmethod contains? [IntegerInterval Object] [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [LongInterval Byte] [^LongInterval s ^Byte x] (.contains s x))
(defmethod contains? [LongInterval Double] [^LongInterval s ^Double x] (.contains s x))
(defmethod contains? [LongInterval Float] [^LongInterval s ^Float x] (.contains s x))
(defmethod contains? [LongInterval Integer] [^LongInterval s ^Integer x] (.contains s x))
(defmethod contains? [LongInterval Long] [^LongInterval s ^Long x] (.contains s x))
(defmethod contains? [LongInterval Short] [^LongInterval s ^Short x] (.contains s x))
(defmethod contains? [LongInterval Object] [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [ShortInterval Byte] [^ShortInterval s ^Byte x] (.contains s x))
(defmethod contains? [ShortInterval Double] [^ShortInterval s ^Double x] (.contains s x))
(defmethod contains? [ShortInterval Float] [^ShortInterval s ^Float x] (.contains s x))
(defmethod contains? [ShortInterval Integer] [^ShortInterval s ^Integer x] (.contains s x))
(defmethod contains? [ShortInterval Long] [^ShortInterval s ^Long x] (.contains s x))
(defmethod contains? [ShortInterval Short] [^ShortInterval s ^Short x] (.contains s x))
(defmethod contains? [ShortInterval Object] [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.multi
{:doc "clojure.core/defmulti for set intersection testing."
:author "PI:EMAIL:<EMAIL>END_PI PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI"
:since "2017-04-20"
:version "2017-09-09"}
(:refer-clojure :exclude [contains?])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(defmulti ^Double/TYPE diameter
"Max distance between elements. 2 methods."
{}
class)
;;----------------------------------------------------------------
(defmethod diameter java.util.Set ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
(defmethod diameter Set ^double [^Set s] (.diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(defmulti intersects?
"Test for general set intersection. 9 methods."
{}
(fn intersects?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod intersects?
[IntegerInterval IntegerInterval]
[^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval DoubleInterval]
[^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[IntegerInterval java.util.Set]
[^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[DoubleInterval IntegerInterval]
[^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[DoubleInterval DoubleInterval]
[^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defmethod intersects?
[DoubleInterval java.util.Set]
[^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defmethod intersects?
[java.util.Set IntegerInterval]
[^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set DoubleInterval]
[^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defmethod intersects?
[java.util.Set java.util.Set]
[^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(defmulti contains?
"Test for general set containment. 43 methods"
(fn contains?-dispatch [s0 s1]
[(.getClass ^Object s0) (.getClass ^Object s1)]))
;;----------------------------------------------------------------
(defmethod contains? [java.util.Set Object] [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(defmethod contains? [ByteInterval Byte] [^ByteInterval s ^Byte x] (.contains s x))
(defmethod contains? [ByteInterval Double] [^ByteInterval s ^Double x] (.contains s x))
(defmethod contains? [ByteInterval Float] [^ByteInterval s ^Float x] (.contains s x))
(defmethod contains? [ByteInterval Integer] [^ByteInterval s ^Integer x] (.contains s x))
(defmethod contains? [ByteInterval Long] [^ByteInterval s ^Long x] (.contains s x))
(defmethod contains? [ByteInterval Short] [^ByteInterval s ^Short x] (.contains s x))
(defmethod contains? [ByteInterval Object] [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [DoubleInterval Byte] [^DoubleInterval s ^Byte x] (.contains s x))
(defmethod contains? [DoubleInterval Double] [^DoubleInterval s ^Double x] (.contains s x))
(defmethod contains? [DoubleInterval Float] [^DoubleInterval s ^Float x] (.contains s x))
(defmethod contains? [DoubleInterval Integer] [^DoubleInterval s ^Integer x] (.contains s x))
(defmethod contains? [DoubleInterval Long] [^DoubleInterval s ^Long x] (.contains s x))
(defmethod contains? [DoubleInterval Short] [^DoubleInterval s ^Short x] (.contains s x))
(defmethod contains? [DoubleInterval Object] [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [FloatInterval Byte] [^FloatInterval s ^Byte x] (.contains s x))
(defmethod contains? [FloatInterval Double] [^FloatInterval s ^Double x] (.contains s x))
(defmethod contains? [FloatInterval Float] [^FloatInterval s ^Float x] (.contains s x))
(defmethod contains? [FloatInterval Integer] [^FloatInterval s ^Integer x] (.contains s x))
(defmethod contains? [FloatInterval Long] [^FloatInterval s ^Long x] (.contains s x))
(defmethod contains? [FloatInterval Short] [^FloatInterval s ^Short x] (.contains s x))
(defmethod contains? [FloatInterval Object] [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [IntegerInterval Byte] [^IntegerInterval s ^Byte x] (.contains s x))
(defmethod contains? [IntegerInterval Double] [^IntegerInterval s ^Double x] (.contains s x))
(defmethod contains? [IntegerInterval Float] [^IntegerInterval s ^Float x] (.contains s x))
(defmethod contains? [IntegerInterval Integer] [^IntegerInterval s ^Integer x] (.contains s x))
(defmethod contains? [IntegerInterval Long] [^IntegerInterval s ^Long x] (.contains s x))
(defmethod contains? [IntegerInterval Short] [^IntegerInterval s ^Short x] (.contains s x))
(defmethod contains? [IntegerInterval Object] [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [LongInterval Byte] [^LongInterval s ^Byte x] (.contains s x))
(defmethod contains? [LongInterval Double] [^LongInterval s ^Double x] (.contains s x))
(defmethod contains? [LongInterval Float] [^LongInterval s ^Float x] (.contains s x))
(defmethod contains? [LongInterval Integer] [^LongInterval s ^Integer x] (.contains s x))
(defmethod contains? [LongInterval Long] [^LongInterval s ^Long x] (.contains s x))
(defmethod contains? [LongInterval Short] [^LongInterval s ^Short x] (.contains s x))
(defmethod contains? [LongInterval Object] [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(defmethod contains? [ShortInterval Byte] [^ShortInterval s ^Byte x] (.contains s x))
(defmethod contains? [ShortInterval Double] [^ShortInterval s ^Double x] (.contains s x))
(defmethod contains? [ShortInterval Float] [^ShortInterval s ^Float x] (.contains s x))
(defmethod contains? [ShortInterval Integer] [^ShortInterval s ^Integer x] (.contains s x))
(defmethod contains? [ShortInterval Long] [^ShortInterval s ^Long x] (.contains s x))
(defmethod contains? [ShortInterval Short] [^ShortInterval s ^Short x] (.contains s x))
(defmethod contains? [ShortInterval Object] [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
|
[
{
"context": "\"Project 1\" :description \"Dumb Project 1\" :owner \"Sergey\"}\n {:id 2 :name \"Project 2\" :description \"Dumb ",
"end": 2101,
"score": 0.9982069134712219,
"start": 2095,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "\"Project 2\" :description \"Dumb Project 2\" :owner \"Nika\"}])\n\n(defn project-fetch\n \"Dumb function to illu",
"end": 2174,
"score": 0.9989674687385559,
"start": 2170,
"tag": "NAME",
"value": "Nika"
},
{
"context": "\"Project 1\" :description \"Dumb Project 1\" :owner \"Sergey\"})\n\n(defn task-create\n \"Dumb function to illustr",
"end": 2384,
"score": 0.997312068939209,
"start": 2378,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "comments-for-tasks with id: \" task-id)\n [{:name \"Sergey\" :comment \"Dumb Comment 1!\"}\n {:name \"Sergey\" :",
"end": 3388,
"score": 0.998497486114502,
"start": 3382,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "e \"Sergey\" :comment \"Dumb Comment 1!\"}\n {:name \"Sergey\" :comment \"Dumb Comment 2!\"}\n {:name \"Sergey\" :",
"end": 3435,
"score": 0.9987589716911316,
"start": 3429,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "e \"Sergey\" :comment \"Dumb Comment 2!\"}\n {:name \"Sergey\" :comment \"Dumb Comment 3!\"}\n {:name \"Sergey\" :",
"end": 3482,
"score": 0.9997888207435608,
"start": 3476,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "e \"Sergey\" :comment \"Dumb Comment 3!\"}\n {:name \"Sergey\" :comment \"Dumb Comment 4!\"}\n {:name \"Sergey\" :",
"end": 3529,
"score": 0.9997466206550598,
"start": 3523,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "e \"Sergey\" :comment \"Dumb Comment 4!\"}\n {:name \"Sergey\" :comment \"Dumb Comment 5!\"}])\n\n(defn user-fetch\n",
"end": 3576,
"score": 0.9997504353523254,
"start": 3570,
"tag": "NAME",
"value": "Sergey"
},
{
"context": "ed user-fetch with id: \" user-id)\n {:id 4 :name \"Sergey Shvets\" :email \"sergey@example.com\"})\n\n;; specs!\n;; Guid",
"end": 3717,
"score": 0.9998570084571838,
"start": 3704,
"tag": "NAME",
"value": "Sergey Shvets"
},
{
"context": "\" user-id)\n {:id 4 :name \"Sergey Shvets\" :email \"sergey@example.com\"})\n\n;; specs!\n;; Guide link: https://clojure.org/",
"end": 3745,
"score": 0.9999256134033203,
"start": 3727,
"tag": "EMAIL",
"value": "sergey@example.com"
}
] | src/cljc/cgql/cgql_demo.cljc | bearz/cgql | 4 | (ns cgql.cgql-demo
(:require [clojure.walk :refer [prewalk prewalk-replace]]
[com.stuartsierra.dependency :as dep]
[clojure.spec.alpha :as s]
[clojure.repl :refer [doc]]
[clojure.pprint :refer [pprint]]
[clojure.string :refer [capitalize]]
[bearz.cgql.core :refer [execute-query str-doc cgql-handler]]))
;; NOTE: now all in one file to work out queries etc. read-str should take care of serialization later when it
;; will be broke down to server and client
;; Specs
;; We use clojure.spec to validate all of the inputs and outputs before sending data up and down the wire.
;; Make sure to namespace all the specs with unique names so you can reuse them for more then one value.
;; Rule of thumb: if there are too many specs then you probably not keeping your API consistent.
;; global specs
(s/def ::num-id int?)
;; project specs
(s/def :project-spec/id ::num-id)
(s/def :project-spec/name (s/and string? #(< (count %) 24)))
(s/def :project-spec/owner (s/and string? #(< (count %) 50)))
(s/def :project-spec/project (s/keys :opt-un [:project-spec/id
:project-spec/name
:project-spec/description
:project-spec/owner]))
;; todo some specs can be done as in interface and then just used merge to join
(s/def :task-spec/id ::num-id)
(s/def :task-spec/name (s/and string? #(< (count %) 24)))
(s/def :task-spec/owner (s/and string? #(< (count %) 50)))
(s/def :task-spec/task (s/keys :opt-un [:task-spec/id
:task-spec/name
:task-spec/project-id
:task-spec/owner]))
;; Handlers
;;
;; Functions that are doing the actual job of retrieving and massaging data.
;; Mocks for now, but can do anything in theory
(defn project-list
"Dumb function with no params"
[]
(println "Called project-list")
[{:id 1 :name "Project 1" :description "Dumb Project 1" :owner "Sergey"}
{:id 2 :name "Project 2" :description "Dumb Project 2" :owner "Nika"}])
(defn project-fetch
"Dumb function to illustrate function with param"
[id]
(println (str "Called project-fetch with id: " id))
{:id 7 :name "Project 1" :description "Dumb Project 1" :owner "Sergey"})
(defn task-create
"Dumb function to illustrate mutation with params and relations"
[project-id & params]
(println (str "Called task-create with project-id: " project-id " and params: " params))
{:name "Task 1" :description "Do that!" :status false :project-id 1})
(defn task-list
"Dumb function to illustrate relations with other resource"
[project-id]
(println (str "Called task-list with project-id: " project-id))
[{:id 1 :name "Task 1" :description "Do that!" :status false :project-id 1}
{:id 2 :name "Task 2" :description "Do that!" :status false :project-id 1}
{:id 3 :name "Task 3" :description "Do that!" :status true :project-id 1}])
(defn task-complete
"Dumb function to illustrate update of the single object"
[name]
(println (str "Called task-complete with name: " name))
{:name "Task 1" :description "Do that!" :status true :project-id 1})
(defn comments-for-tasks
[task-id]
(println "Called comments-for-tasks with id: " task-id)
[{:name "Sergey" :comment "Dumb Comment 1!"}
{:name "Sergey" :comment "Dumb Comment 2!"}
{:name "Sergey" :comment "Dumb Comment 3!"}
{:name "Sergey" :comment "Dumb Comment 4!"}
{:name "Sergey" :comment "Dumb Comment 5!"}])
(defn user-fetch
[user-id]
(println "Called user-fetch with id: " user-id)
{:id 4 :name "Sergey Shvets" :email "sergey@example.com"})
;; specs!
;; Guide link: https://clojure.org/guides/spec
;; Data Model
;;
;; Describes Data Model that exists in an application. Description includes:
;; * name — as a keyword to ensure uniqueness.
;; * requests – list of requests defined for this object. Requests later resolved to the actual methods with special map
;;
;; Methods map includes:
;; * doc – for documentation
;; * ret, args – specs for return and arguments. Helps to validate return and later generate responses without actual server involved (reason behind this later.)
;; * impl – to specify method to implement. Note that you can use reader-conditionals if you want to share file between front-end and back-end (useful to do to get auto-docs.)
(def data-model
{:resources {:project {:methods {:list {:doc "Returns a list of available projects for authorized user"
:ret (s/coll-of :project-spec/project)
#?@(:clj [:impl project-list])}
:fetch {:doc "Returns one project details by its id"
:args (s/spec (s/cat :id ::num-id))
:ret :project-spec/project
#?@(:clj [:impl project-fetch])}} ;; how to add optional param validation?
:spec :project-spec/project
:doc "Some sample doc description"}
:task {:methods {:list {:doc "Returns a list of tasks, optionally filtered by some project id"
;; todo add optional args (zero or more)
:ret (s/coll-of :task-spec/task)
#?@(:clj [:impl task-list])}
:create! {#?@(:clj [:impl task-create])}
:complete {#?@(:clj [:impl task-complete])}
:comments {#?@(:clj [:impl comments-for-tasks])}}
:spec :task-spec/task
:doc "Some sample doc description"}
:user {:methods {:fetch {#?@(:clj [:impl user-fetch])}}}}
; todo actions (make upload service as an example)
})
(def api-doc (partial str-doc data-model))
;; Queries
;;
;; You'll need to create a handler with http-server framework of your choice (e.g. Ring). See 'query' function as example.
;;
;; Then you can see examples of a queries that are supported.
;; Start your query with ($cgql) and then add a map that contains actual query. Queries can be nested, but unlike GraphQL, you are free to nest any request underneath. Just use
;; $cgql-parent to refer to a parent response. Also, you can reference other queries by specifying their name in ($cgql-ref) parameter. There is a special parameter $cgql-context
;; that is filled up by a server when you need something from server-side (e.g. user-id from session)
;;
;; Params:
;; * name – name of a query, for internal reference (optional)
;; * query – method to query. Must reflect name inside data-model (see above)
;; * with – params for the method in query. Accepts any Clojure(Script) values as well as references like $cgql-ref, $cgql-parent, $cgql-context.
;; * return – list of fields to return. This one support nesting, just put a map instead of keyword with nested query to do nesting. Nesting can be unlimited (almost!). See examples.
(defn query
[qry]
(cgql-handler {:data-model data-model
:context {:user-id 1}
:bind-to result}
qry
(let [res result]
(println "Query is: " qry)
(println "Result is: " res)
(println)
(println)
res)))
;;; Query to fetch one resource with no params
(query '($cgql {:query [:project :list]}))
;;; Query with filtered fields
(query '($cgql {:query [:project :list]
:return [:id :name]}))
;
;;; Named query
(query '($cgql {:name :project_1
:query [:project :fetch]
:with [2]}))
;
;;; Query with control over the structure
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [1]})})
;
;;; Mutating query
(query '($cgql {:query [:task :create!]
:with [1 "name" "description" false]}))
;;; todo you can clearly see that validation of params needed
;
;;; Query to fetch related resources, passing result of one query to the other
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [7]})
:tasks '($cgql {:name :tasks_list
:query [:task :list]
:with [(:id ($cgql-ref :project_1))]
:return [:id :name :status]})})
;
;;; Query that does some calculations on the server before sending response back.
;(query '(count ($cgql {:query [:project :list]})))
;; query with nested structures!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
]}
)}]}))
;; even more nesting!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
{:comments ($cgql {:query [:task :comments]
:with [(:id ($cgql-parent))]})}]}
)}]}))
;; query with context
(query '($cgql {:query [:user :fetch]
:with [($cgql-context :user-id)]})) | 88829 | (ns cgql.cgql-demo
(:require [clojure.walk :refer [prewalk prewalk-replace]]
[com.stuartsierra.dependency :as dep]
[clojure.spec.alpha :as s]
[clojure.repl :refer [doc]]
[clojure.pprint :refer [pprint]]
[clojure.string :refer [capitalize]]
[bearz.cgql.core :refer [execute-query str-doc cgql-handler]]))
;; NOTE: now all in one file to work out queries etc. read-str should take care of serialization later when it
;; will be broke down to server and client
;; Specs
;; We use clojure.spec to validate all of the inputs and outputs before sending data up and down the wire.
;; Make sure to namespace all the specs with unique names so you can reuse them for more then one value.
;; Rule of thumb: if there are too many specs then you probably not keeping your API consistent.
;; global specs
(s/def ::num-id int?)
;; project specs
(s/def :project-spec/id ::num-id)
(s/def :project-spec/name (s/and string? #(< (count %) 24)))
(s/def :project-spec/owner (s/and string? #(< (count %) 50)))
(s/def :project-spec/project (s/keys :opt-un [:project-spec/id
:project-spec/name
:project-spec/description
:project-spec/owner]))
;; todo some specs can be done as in interface and then just used merge to join
(s/def :task-spec/id ::num-id)
(s/def :task-spec/name (s/and string? #(< (count %) 24)))
(s/def :task-spec/owner (s/and string? #(< (count %) 50)))
(s/def :task-spec/task (s/keys :opt-un [:task-spec/id
:task-spec/name
:task-spec/project-id
:task-spec/owner]))
;; Handlers
;;
;; Functions that are doing the actual job of retrieving and massaging data.
;; Mocks for now, but can do anything in theory
(defn project-list
"Dumb function with no params"
[]
(println "Called project-list")
[{:id 1 :name "Project 1" :description "Dumb Project 1" :owner "<NAME>"}
{:id 2 :name "Project 2" :description "Dumb Project 2" :owner "<NAME>"}])
(defn project-fetch
"Dumb function to illustrate function with param"
[id]
(println (str "Called project-fetch with id: " id))
{:id 7 :name "Project 1" :description "Dumb Project 1" :owner "<NAME>"})
(defn task-create
"Dumb function to illustrate mutation with params and relations"
[project-id & params]
(println (str "Called task-create with project-id: " project-id " and params: " params))
{:name "Task 1" :description "Do that!" :status false :project-id 1})
(defn task-list
"Dumb function to illustrate relations with other resource"
[project-id]
(println (str "Called task-list with project-id: " project-id))
[{:id 1 :name "Task 1" :description "Do that!" :status false :project-id 1}
{:id 2 :name "Task 2" :description "Do that!" :status false :project-id 1}
{:id 3 :name "Task 3" :description "Do that!" :status true :project-id 1}])
(defn task-complete
"Dumb function to illustrate update of the single object"
[name]
(println (str "Called task-complete with name: " name))
{:name "Task 1" :description "Do that!" :status true :project-id 1})
(defn comments-for-tasks
[task-id]
(println "Called comments-for-tasks with id: " task-id)
[{:name "<NAME>" :comment "Dumb Comment 1!"}
{:name "<NAME>" :comment "Dumb Comment 2!"}
{:name "<NAME>" :comment "Dumb Comment 3!"}
{:name "<NAME>" :comment "Dumb Comment 4!"}
{:name "<NAME>" :comment "Dumb Comment 5!"}])
(defn user-fetch
[user-id]
(println "Called user-fetch with id: " user-id)
{:id 4 :name "<NAME>" :email "<EMAIL>"})
;; specs!
;; Guide link: https://clojure.org/guides/spec
;; Data Model
;;
;; Describes Data Model that exists in an application. Description includes:
;; * name — as a keyword to ensure uniqueness.
;; * requests – list of requests defined for this object. Requests later resolved to the actual methods with special map
;;
;; Methods map includes:
;; * doc – for documentation
;; * ret, args – specs for return and arguments. Helps to validate return and later generate responses without actual server involved (reason behind this later.)
;; * impl – to specify method to implement. Note that you can use reader-conditionals if you want to share file between front-end and back-end (useful to do to get auto-docs.)
(def data-model
{:resources {:project {:methods {:list {:doc "Returns a list of available projects for authorized user"
:ret (s/coll-of :project-spec/project)
#?@(:clj [:impl project-list])}
:fetch {:doc "Returns one project details by its id"
:args (s/spec (s/cat :id ::num-id))
:ret :project-spec/project
#?@(:clj [:impl project-fetch])}} ;; how to add optional param validation?
:spec :project-spec/project
:doc "Some sample doc description"}
:task {:methods {:list {:doc "Returns a list of tasks, optionally filtered by some project id"
;; todo add optional args (zero or more)
:ret (s/coll-of :task-spec/task)
#?@(:clj [:impl task-list])}
:create! {#?@(:clj [:impl task-create])}
:complete {#?@(:clj [:impl task-complete])}
:comments {#?@(:clj [:impl comments-for-tasks])}}
:spec :task-spec/task
:doc "Some sample doc description"}
:user {:methods {:fetch {#?@(:clj [:impl user-fetch])}}}}
; todo actions (make upload service as an example)
})
(def api-doc (partial str-doc data-model))
;; Queries
;;
;; You'll need to create a handler with http-server framework of your choice (e.g. Ring). See 'query' function as example.
;;
;; Then you can see examples of a queries that are supported.
;; Start your query with ($cgql) and then add a map that contains actual query. Queries can be nested, but unlike GraphQL, you are free to nest any request underneath. Just use
;; $cgql-parent to refer to a parent response. Also, you can reference other queries by specifying their name in ($cgql-ref) parameter. There is a special parameter $cgql-context
;; that is filled up by a server when you need something from server-side (e.g. user-id from session)
;;
;; Params:
;; * name – name of a query, for internal reference (optional)
;; * query – method to query. Must reflect name inside data-model (see above)
;; * with – params for the method in query. Accepts any Clojure(Script) values as well as references like $cgql-ref, $cgql-parent, $cgql-context.
;; * return – list of fields to return. This one support nesting, just put a map instead of keyword with nested query to do nesting. Nesting can be unlimited (almost!). See examples.
(defn query
[qry]
(cgql-handler {:data-model data-model
:context {:user-id 1}
:bind-to result}
qry
(let [res result]
(println "Query is: " qry)
(println "Result is: " res)
(println)
(println)
res)))
;;; Query to fetch one resource with no params
(query '($cgql {:query [:project :list]}))
;;; Query with filtered fields
(query '($cgql {:query [:project :list]
:return [:id :name]}))
;
;;; Named query
(query '($cgql {:name :project_1
:query [:project :fetch]
:with [2]}))
;
;;; Query with control over the structure
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [1]})})
;
;;; Mutating query
(query '($cgql {:query [:task :create!]
:with [1 "name" "description" false]}))
;;; todo you can clearly see that validation of params needed
;
;;; Query to fetch related resources, passing result of one query to the other
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [7]})
:tasks '($cgql {:name :tasks_list
:query [:task :list]
:with [(:id ($cgql-ref :project_1))]
:return [:id :name :status]})})
;
;;; Query that does some calculations on the server before sending response back.
;(query '(count ($cgql {:query [:project :list]})))
;; query with nested structures!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
]}
)}]}))
;; even more nesting!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
{:comments ($cgql {:query [:task :comments]
:with [(:id ($cgql-parent))]})}]}
)}]}))
;; query with context
(query '($cgql {:query [:user :fetch]
:with [($cgql-context :user-id)]})) | true | (ns cgql.cgql-demo
(:require [clojure.walk :refer [prewalk prewalk-replace]]
[com.stuartsierra.dependency :as dep]
[clojure.spec.alpha :as s]
[clojure.repl :refer [doc]]
[clojure.pprint :refer [pprint]]
[clojure.string :refer [capitalize]]
[bearz.cgql.core :refer [execute-query str-doc cgql-handler]]))
;; NOTE: now all in one file to work out queries etc. read-str should take care of serialization later when it
;; will be broke down to server and client
;; Specs
;; We use clojure.spec to validate all of the inputs and outputs before sending data up and down the wire.
;; Make sure to namespace all the specs with unique names so you can reuse them for more then one value.
;; Rule of thumb: if there are too many specs then you probably not keeping your API consistent.
;; global specs
(s/def ::num-id int?)
;; project specs
(s/def :project-spec/id ::num-id)
(s/def :project-spec/name (s/and string? #(< (count %) 24)))
(s/def :project-spec/owner (s/and string? #(< (count %) 50)))
(s/def :project-spec/project (s/keys :opt-un [:project-spec/id
:project-spec/name
:project-spec/description
:project-spec/owner]))
;; todo some specs can be done as in interface and then just used merge to join
(s/def :task-spec/id ::num-id)
(s/def :task-spec/name (s/and string? #(< (count %) 24)))
(s/def :task-spec/owner (s/and string? #(< (count %) 50)))
(s/def :task-spec/task (s/keys :opt-un [:task-spec/id
:task-spec/name
:task-spec/project-id
:task-spec/owner]))
;; Handlers
;;
;; Functions that are doing the actual job of retrieving and massaging data.
;; Mocks for now, but can do anything in theory
(defn project-list
"Dumb function with no params"
[]
(println "Called project-list")
[{:id 1 :name "Project 1" :description "Dumb Project 1" :owner "PI:NAME:<NAME>END_PI"}
{:id 2 :name "Project 2" :description "Dumb Project 2" :owner "PI:NAME:<NAME>END_PI"}])
(defn project-fetch
"Dumb function to illustrate function with param"
[id]
(println (str "Called project-fetch with id: " id))
{:id 7 :name "Project 1" :description "Dumb Project 1" :owner "PI:NAME:<NAME>END_PI"})
(defn task-create
"Dumb function to illustrate mutation with params and relations"
[project-id & params]
(println (str "Called task-create with project-id: " project-id " and params: " params))
{:name "Task 1" :description "Do that!" :status false :project-id 1})
(defn task-list
"Dumb function to illustrate relations with other resource"
[project-id]
(println (str "Called task-list with project-id: " project-id))
[{:id 1 :name "Task 1" :description "Do that!" :status false :project-id 1}
{:id 2 :name "Task 2" :description "Do that!" :status false :project-id 1}
{:id 3 :name "Task 3" :description "Do that!" :status true :project-id 1}])
(defn task-complete
"Dumb function to illustrate update of the single object"
[name]
(println (str "Called task-complete with name: " name))
{:name "Task 1" :description "Do that!" :status true :project-id 1})
(defn comments-for-tasks
[task-id]
(println "Called comments-for-tasks with id: " task-id)
[{:name "PI:NAME:<NAME>END_PI" :comment "Dumb Comment 1!"}
{:name "PI:NAME:<NAME>END_PI" :comment "Dumb Comment 2!"}
{:name "PI:NAME:<NAME>END_PI" :comment "Dumb Comment 3!"}
{:name "PI:NAME:<NAME>END_PI" :comment "Dumb Comment 4!"}
{:name "PI:NAME:<NAME>END_PI" :comment "Dumb Comment 5!"}])
(defn user-fetch
[user-id]
(println "Called user-fetch with id: " user-id)
{:id 4 :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"})
;; specs!
;; Guide link: https://clojure.org/guides/spec
;; Data Model
;;
;; Describes Data Model that exists in an application. Description includes:
;; * name — as a keyword to ensure uniqueness.
;; * requests – list of requests defined for this object. Requests later resolved to the actual methods with special map
;;
;; Methods map includes:
;; * doc – for documentation
;; * ret, args – specs for return and arguments. Helps to validate return and later generate responses without actual server involved (reason behind this later.)
;; * impl – to specify method to implement. Note that you can use reader-conditionals if you want to share file between front-end and back-end (useful to do to get auto-docs.)
(def data-model
{:resources {:project {:methods {:list {:doc "Returns a list of available projects for authorized user"
:ret (s/coll-of :project-spec/project)
#?@(:clj [:impl project-list])}
:fetch {:doc "Returns one project details by its id"
:args (s/spec (s/cat :id ::num-id))
:ret :project-spec/project
#?@(:clj [:impl project-fetch])}} ;; how to add optional param validation?
:spec :project-spec/project
:doc "Some sample doc description"}
:task {:methods {:list {:doc "Returns a list of tasks, optionally filtered by some project id"
;; todo add optional args (zero or more)
:ret (s/coll-of :task-spec/task)
#?@(:clj [:impl task-list])}
:create! {#?@(:clj [:impl task-create])}
:complete {#?@(:clj [:impl task-complete])}
:comments {#?@(:clj [:impl comments-for-tasks])}}
:spec :task-spec/task
:doc "Some sample doc description"}
:user {:methods {:fetch {#?@(:clj [:impl user-fetch])}}}}
; todo actions (make upload service as an example)
})
(def api-doc (partial str-doc data-model))
;; Queries
;;
;; You'll need to create a handler with http-server framework of your choice (e.g. Ring). See 'query' function as example.
;;
;; Then you can see examples of a queries that are supported.
;; Start your query with ($cgql) and then add a map that contains actual query. Queries can be nested, but unlike GraphQL, you are free to nest any request underneath. Just use
;; $cgql-parent to refer to a parent response. Also, you can reference other queries by specifying their name in ($cgql-ref) parameter. There is a special parameter $cgql-context
;; that is filled up by a server when you need something from server-side (e.g. user-id from session)
;;
;; Params:
;; * name – name of a query, for internal reference (optional)
;; * query – method to query. Must reflect name inside data-model (see above)
;; * with – params for the method in query. Accepts any Clojure(Script) values as well as references like $cgql-ref, $cgql-parent, $cgql-context.
;; * return – list of fields to return. This one support nesting, just put a map instead of keyword with nested query to do nesting. Nesting can be unlimited (almost!). See examples.
(defn query
[qry]
(cgql-handler {:data-model data-model
:context {:user-id 1}
:bind-to result}
qry
(let [res result]
(println "Query is: " qry)
(println "Result is: " res)
(println)
(println)
res)))
;;; Query to fetch one resource with no params
(query '($cgql {:query [:project :list]}))
;;; Query with filtered fields
(query '($cgql {:query [:project :list]
:return [:id :name]}))
;
;;; Named query
(query '($cgql {:name :project_1
:query [:project :fetch]
:with [2]}))
;
;;; Query with control over the structure
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [1]})})
;
;;; Mutating query
(query '($cgql {:query [:task :create!]
:with [1 "name" "description" false]}))
;;; todo you can clearly see that validation of params needed
;
;;; Query to fetch related resources, passing result of one query to the other
(query {:project '($cgql {:name :project_1
:query [:project :fetch]
:with [7]})
:tasks '($cgql {:name :tasks_list
:query [:task :list]
:with [(:id ($cgql-ref :project_1))]
:return [:id :name :status]})})
;
;;; Query that does some calculations on the server before sending response back.
;(query '(count ($cgql {:query [:project :list]})))
;; query with nested structures!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
]}
)}]}))
;; even more nesting!
(query '($cgql {:query [:project :list]
:name :project-query
:return [:id
:name
{:tasks ($cgql {:query [:task :list]
:with [(:id ($cgql-parent))]
:return [:id
:name
{:comments ($cgql {:query [:task :comments]
:with [(:id ($cgql-parent))]})}]}
)}]}))
;; query with context
(query '($cgql {:query [:user :fetch]
:with [($cgql-context :user-id)]})) |
[
{
"context": "with arguments\"\n (is (= \"{say (string:\\\"hae maga\\\",number:5,true:true,false:false,null:null,map:{s",
"end": 380,
"score": 0.5247414708137512,
"start": 379,
"tag": "NAME",
"value": "a"
},
{
"context": "{hello world}}\"\n (query [:say {:string \"hae maga\"\n :number 5\n ",
"end": 556,
"score": 0.6882171630859375,
"start": 548,
"tag": "NAME",
"value": "hae maga"
},
{
"context": "\"query ($id:ID!,$greeting:String!) {say (string:\\\"hae maga\\\",id:$id) {hello (greeting:$greeting) world}}\"\n ",
"end": 999,
"score": 0.80014568567276,
"start": 991,
"tag": "NAME",
"value": "hae maga"
},
{
"context": "orld}}\"\n (query {:query [:say {:string \"hae maga\"\n :id :id} [:hell",
"end": 1097,
"score": 0.7800955772399902,
"start": 1089,
"tag": "NAME",
"value": "hae maga"
}
] | test/graphql_inquiry/main_test.clj | BillFront/graphql-inquiry | 2 | (ns graphql-inquiry.main-test
(:require [clojure.test :refer [is deftest testing]]
[graphql-inquiry.main :refer [query mutation]]))
(deftest query-test
(is (= "{say {hello world}}"
(query [:say [:hello :world]])))
(is (= "{say {hello {world}}}"
(query [:say [:hello [:world]]])))
(testing "with arguments"
(is (= "{say (string:\"hae maga\",number:5,true:true,false:false,null:null,map:{some:\"key\",submap:{a:1}},vector:[\"hi\",1],list:[\"listy\",false]) {hello world}}"
(query [:say {:string "hae maga"
:number 5
:true true
:false false
:null nil
:map {:some "key", :submap {:a 1}}
:vector ["hi", 1]
:list (list "listy" false)}
[:hello :world]]))))
(testing "with variable-defs"
(is (= "query ($id:ID!,$greeting:String!) {say (string:\"hae maga\",id:$id) {hello (greeting:$greeting) world}}"
(query {:query [:say {:string "hae maga"
:id :id} [:hello {:greeting :greeting} :world]]
:variable-defs {:id :ID!
:greeting :String!}}))))
(testing "with aliases"
(is (= "{howdy:say {hello world}}"
(query [:howdy:say [:hello :world]]))))
(testing "with lists and sequences"
(is (= "{say {hello {world}}}"
(query [:say (list :hello (filter identity [:world]))]))))
(testing "metafields"
(is (= "{say {hello world __typename}}"
(query [:say [:hello :world :__typename]]))))
(testing "operation-name"
(is (= "query OperationVittles {say {hello world}}"
(query {:query [:say [:hello :world]]
:operation-name "OperationVittles"})))
(is (= "query OperationNeptuneSpear($id:ID!) {say {hello world}}"
(query {:query [:say [:hello :world]]
:variable-defs {:id :ID!}
:operation-name "OperationNeptuneSpear"})))))
(deftest mutation-test
(is (= "mutation ($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}})))
(testing "operation-name"
(is (= "mutation OperationValkyrie($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}
:operation-name "OperationValkyrie"})))))
| 86855 | (ns graphql-inquiry.main-test
(:require [clojure.test :refer [is deftest testing]]
[graphql-inquiry.main :refer [query mutation]]))
(deftest query-test
(is (= "{say {hello world}}"
(query [:say [:hello :world]])))
(is (= "{say {hello {world}}}"
(query [:say [:hello [:world]]])))
(testing "with arguments"
(is (= "{say (string:\"hae mag<NAME>\",number:5,true:true,false:false,null:null,map:{some:\"key\",submap:{a:1}},vector:[\"hi\",1],list:[\"listy\",false]) {hello world}}"
(query [:say {:string "<NAME>"
:number 5
:true true
:false false
:null nil
:map {:some "key", :submap {:a 1}}
:vector ["hi", 1]
:list (list "listy" false)}
[:hello :world]]))))
(testing "with variable-defs"
(is (= "query ($id:ID!,$greeting:String!) {say (string:\"<NAME>\",id:$id) {hello (greeting:$greeting) world}}"
(query {:query [:say {:string "<NAME>"
:id :id} [:hello {:greeting :greeting} :world]]
:variable-defs {:id :ID!
:greeting :String!}}))))
(testing "with aliases"
(is (= "{howdy:say {hello world}}"
(query [:howdy:say [:hello :world]]))))
(testing "with lists and sequences"
(is (= "{say {hello {world}}}"
(query [:say (list :hello (filter identity [:world]))]))))
(testing "metafields"
(is (= "{say {hello world __typename}}"
(query [:say [:hello :world :__typename]]))))
(testing "operation-name"
(is (= "query OperationVittles {say {hello world}}"
(query {:query [:say [:hello :world]]
:operation-name "OperationVittles"})))
(is (= "query OperationNeptuneSpear($id:ID!) {say {hello world}}"
(query {:query [:say [:hello :world]]
:variable-defs {:id :ID!}
:operation-name "OperationNeptuneSpear"})))))
(deftest mutation-test
(is (= "mutation ($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}})))
(testing "operation-name"
(is (= "mutation OperationValkyrie($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}
:operation-name "OperationValkyrie"})))))
| true | (ns graphql-inquiry.main-test
(:require [clojure.test :refer [is deftest testing]]
[graphql-inquiry.main :refer [query mutation]]))
(deftest query-test
(is (= "{say {hello world}}"
(query [:say [:hello :world]])))
(is (= "{say {hello {world}}}"
(query [:say [:hello [:world]]])))
(testing "with arguments"
(is (= "{say (string:\"hae magPI:NAME:<NAME>END_PI\",number:5,true:true,false:false,null:null,map:{some:\"key\",submap:{a:1}},vector:[\"hi\",1],list:[\"listy\",false]) {hello world}}"
(query [:say {:string "PI:NAME:<NAME>END_PI"
:number 5
:true true
:false false
:null nil
:map {:some "key", :submap {:a 1}}
:vector ["hi", 1]
:list (list "listy" false)}
[:hello :world]]))))
(testing "with variable-defs"
(is (= "query ($id:ID!,$greeting:String!) {say (string:\"PI:NAME:<NAME>END_PI\",id:$id) {hello (greeting:$greeting) world}}"
(query {:query [:say {:string "PI:NAME:<NAME>END_PI"
:id :id} [:hello {:greeting :greeting} :world]]
:variable-defs {:id :ID!
:greeting :String!}}))))
(testing "with aliases"
(is (= "{howdy:say {hello world}}"
(query [:howdy:say [:hello :world]]))))
(testing "with lists and sequences"
(is (= "{say {hello {world}}}"
(query [:say (list :hello (filter identity [:world]))]))))
(testing "metafields"
(is (= "{say {hello world __typename}}"
(query [:say [:hello :world :__typename]]))))
(testing "operation-name"
(is (= "query OperationVittles {say {hello world}}"
(query {:query [:say [:hello :world]]
:operation-name "OperationVittles"})))
(is (= "query OperationNeptuneSpear($id:ID!) {say {hello world}}"
(query {:query [:say [:hello :world]]
:variable-defs {:id :ID!}
:operation-name "OperationNeptuneSpear"})))))
(deftest mutation-test
(is (= "mutation ($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}})))
(testing "operation-name"
(is (= "mutation OperationValkyrie($id:ID!,$customer:Customer!) {updateCustomer (id:$id,customer:$customer) {name email}}"
(mutation {:query [:updateCustomer {:id :id
:customer :customer} [:name :email]]
:variable-defs {:id :ID!
:customer :Customer!}
:operation-name "OperationValkyrie"})))))
|
[
{
"context": ";; Three-Dimensional Orientation Using a Mouse\" by Ken Shoemake\n;;\n;; http://www.talisman.org/~erlkonig/misc/shoe",
"end": 466,
"score": 0.9998504519462585,
"start": 454,
"tag": "NAME",
"value": "Ken Shoemake"
}
] | src/thi/ng/geom/gl/arcball.cljc | gaybro8777/geom | 803 | (ns thi.ng.geom.gl.arcball
#?(:cljs
(:require-macros
[thi.ng.math.macros :as mm]))
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3 V3Y]]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.quaternion :as q]
#?(:clj [thi.ng.math.macros :as mm])))
(declare update-view)
;; Based on "ARCBALL: A User Interface for Specifying
;; Three-Dimensional Orientation Using a Mouse" by Ken Shoemake
;;
;; http://www.talisman.org/~erlkonig/misc/shoemake92-arcball.pdf
(defn arcball
[{:keys [init dist min-dist max-dist radius center] :as ab}]
(let [dist (or dist 2.0)
min-dist (or min-dist (/ dist 2.0))
max-dist (or max-dist (* dist 2.0))
curr-rot (if init (q/quat init) (q/quat-from-axis-angle V3Y m/PI))]
(-> ab
(merge
{:dist dist
:min-dist min-dist
:max-dist max-dist
:radius (or radius 300.0)
:center (or center (vec2 640 360))
:curr-rot curr-rot
:click-rot curr-rot})
update-view)))
;; Helpers
(defn- sphere-position
[{:keys [center radius]} x y]
(let [v (vec3 (mm/subdiv x (v/x center) radius) (mm/subdiv y (v/y center) radius) 0)
m (m/mag-squared v)]
(if (> m 1.0)
(m/normalize v)
(assoc v :z (Math/sqrt (- 1.0 m))))))
;; Event handlers & arcball operations
(defn down
[ab x y]
(-> ab
(assoc :click-pos (sphere-position ab x y)
:click-rot (:curr-rot ab))
update-view))
(defn drag
[{:keys [click-pos] :as ab} x y]
(when click-pos
(let [drag-pos (sphere-position ab x y)
axis (m/cross click-pos drag-pos)
theta (m/dot click-pos drag-pos)
drag-rot (q/quat axis theta)]
(-> ab
(assoc :curr-rot (m/* drag-rot (:click-rot ab)))
update-view))))
(defn up
[ab] (assoc ab :click-pos nil))
(defn resize
[ab w h]
(let [ww (/ w 2)
wh (/ h 2)]
(assoc ab
:radius (* (min ww wh) 2)
:center (vec2 ww wh))))
(defn zoom-delta
[{:keys [min-dist max-dist] :as ab} delta]
(-> ab
(assoc :dist
(m/clamp
(mm/madd delta (mm/subm max-dist min-dist 1e-3) (get ab :dist))
min-dist max-dist))
update-view))
(defn zoom-abs
[ab x] (-> ab (assoc :dist (m/clamp x (:min-dist ab) (:max-dist ab))) update-view))
(defn update-view
[{:keys [curr-rot] :as ab}]
(let [q (q/quat (:xyz curr-rot) (- (:w curr-rot)))
offset (g/transform-vector q (vec3 0 0 (get ab :dist)))
up (g/transform-vector q V3Y)
eye (m/- offset)]
(assoc ab :view (mat/look-at eye (vec3) up))))
(defn get-view
[ab] (or (get ab :view) (get (update-view ab) :view)))
(defn get-rotation
[ab] (get ab :curr-rot))
(defn set-rotation
[ab q] (-> ab (assoc :curr-rot q) update-view))
(defn set-zoom-range
[ab min max] (assoc ab :min-dist min :max-dist max :dist (m/clamp (get ab :dist) min max)))
| 81169 | (ns thi.ng.geom.gl.arcball
#?(:cljs
(:require-macros
[thi.ng.math.macros :as mm]))
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3 V3Y]]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.quaternion :as q]
#?(:clj [thi.ng.math.macros :as mm])))
(declare update-view)
;; Based on "ARCBALL: A User Interface for Specifying
;; Three-Dimensional Orientation Using a Mouse" by <NAME>
;;
;; http://www.talisman.org/~erlkonig/misc/shoemake92-arcball.pdf
(defn arcball
[{:keys [init dist min-dist max-dist radius center] :as ab}]
(let [dist (or dist 2.0)
min-dist (or min-dist (/ dist 2.0))
max-dist (or max-dist (* dist 2.0))
curr-rot (if init (q/quat init) (q/quat-from-axis-angle V3Y m/PI))]
(-> ab
(merge
{:dist dist
:min-dist min-dist
:max-dist max-dist
:radius (or radius 300.0)
:center (or center (vec2 640 360))
:curr-rot curr-rot
:click-rot curr-rot})
update-view)))
;; Helpers
(defn- sphere-position
[{:keys [center radius]} x y]
(let [v (vec3 (mm/subdiv x (v/x center) radius) (mm/subdiv y (v/y center) radius) 0)
m (m/mag-squared v)]
(if (> m 1.0)
(m/normalize v)
(assoc v :z (Math/sqrt (- 1.0 m))))))
;; Event handlers & arcball operations
(defn down
[ab x y]
(-> ab
(assoc :click-pos (sphere-position ab x y)
:click-rot (:curr-rot ab))
update-view))
(defn drag
[{:keys [click-pos] :as ab} x y]
(when click-pos
(let [drag-pos (sphere-position ab x y)
axis (m/cross click-pos drag-pos)
theta (m/dot click-pos drag-pos)
drag-rot (q/quat axis theta)]
(-> ab
(assoc :curr-rot (m/* drag-rot (:click-rot ab)))
update-view))))
(defn up
[ab] (assoc ab :click-pos nil))
(defn resize
[ab w h]
(let [ww (/ w 2)
wh (/ h 2)]
(assoc ab
:radius (* (min ww wh) 2)
:center (vec2 ww wh))))
(defn zoom-delta
[{:keys [min-dist max-dist] :as ab} delta]
(-> ab
(assoc :dist
(m/clamp
(mm/madd delta (mm/subm max-dist min-dist 1e-3) (get ab :dist))
min-dist max-dist))
update-view))
(defn zoom-abs
[ab x] (-> ab (assoc :dist (m/clamp x (:min-dist ab) (:max-dist ab))) update-view))
(defn update-view
[{:keys [curr-rot] :as ab}]
(let [q (q/quat (:xyz curr-rot) (- (:w curr-rot)))
offset (g/transform-vector q (vec3 0 0 (get ab :dist)))
up (g/transform-vector q V3Y)
eye (m/- offset)]
(assoc ab :view (mat/look-at eye (vec3) up))))
(defn get-view
[ab] (or (get ab :view) (get (update-view ab) :view)))
(defn get-rotation
[ab] (get ab :curr-rot))
(defn set-rotation
[ab q] (-> ab (assoc :curr-rot q) update-view))
(defn set-zoom-range
[ab min max] (assoc ab :min-dist min :max-dist max :dist (m/clamp (get ab :dist) min max)))
| true | (ns thi.ng.geom.gl.arcball
#?(:cljs
(:require-macros
[thi.ng.math.macros :as mm]))
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3 V3Y]]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.quaternion :as q]
#?(:clj [thi.ng.math.macros :as mm])))
(declare update-view)
;; Based on "ARCBALL: A User Interface for Specifying
;; Three-Dimensional Orientation Using a Mouse" by PI:NAME:<NAME>END_PI
;;
;; http://www.talisman.org/~erlkonig/misc/shoemake92-arcball.pdf
(defn arcball
[{:keys [init dist min-dist max-dist radius center] :as ab}]
(let [dist (or dist 2.0)
min-dist (or min-dist (/ dist 2.0))
max-dist (or max-dist (* dist 2.0))
curr-rot (if init (q/quat init) (q/quat-from-axis-angle V3Y m/PI))]
(-> ab
(merge
{:dist dist
:min-dist min-dist
:max-dist max-dist
:radius (or radius 300.0)
:center (or center (vec2 640 360))
:curr-rot curr-rot
:click-rot curr-rot})
update-view)))
;; Helpers
(defn- sphere-position
[{:keys [center radius]} x y]
(let [v (vec3 (mm/subdiv x (v/x center) radius) (mm/subdiv y (v/y center) radius) 0)
m (m/mag-squared v)]
(if (> m 1.0)
(m/normalize v)
(assoc v :z (Math/sqrt (- 1.0 m))))))
;; Event handlers & arcball operations
(defn down
[ab x y]
(-> ab
(assoc :click-pos (sphere-position ab x y)
:click-rot (:curr-rot ab))
update-view))
(defn drag
[{:keys [click-pos] :as ab} x y]
(when click-pos
(let [drag-pos (sphere-position ab x y)
axis (m/cross click-pos drag-pos)
theta (m/dot click-pos drag-pos)
drag-rot (q/quat axis theta)]
(-> ab
(assoc :curr-rot (m/* drag-rot (:click-rot ab)))
update-view))))
(defn up
[ab] (assoc ab :click-pos nil))
(defn resize
[ab w h]
(let [ww (/ w 2)
wh (/ h 2)]
(assoc ab
:radius (* (min ww wh) 2)
:center (vec2 ww wh))))
(defn zoom-delta
[{:keys [min-dist max-dist] :as ab} delta]
(-> ab
(assoc :dist
(m/clamp
(mm/madd delta (mm/subm max-dist min-dist 1e-3) (get ab :dist))
min-dist max-dist))
update-view))
(defn zoom-abs
[ab x] (-> ab (assoc :dist (m/clamp x (:min-dist ab) (:max-dist ab))) update-view))
(defn update-view
[{:keys [curr-rot] :as ab}]
(let [q (q/quat (:xyz curr-rot) (- (:w curr-rot)))
offset (g/transform-vector q (vec3 0 0 (get ab :dist)))
up (g/transform-vector q V3Y)
eye (m/- offset)]
(assoc ab :view (mat/look-at eye (vec3) up))))
(defn get-view
[ab] (or (get ab :view) (get (update-view ab) :view)))
(defn get-rotation
[ab] (get ab :curr-rot))
(defn set-rotation
[ab q] (-> ab (assoc :curr-rot q) update-view))
(defn set-zoom-range
[ab min max] (assoc ab :min-dist min :max-dist max :dist (m/clamp (get ab :dist) min max)))
|
[
{
"context": "(ns vlagwt.score\n ^{:author \"Thomas Bock <thomas.bock@ptb.de>\"\n :doc \"Finds the max sco",
"end": 41,
"score": 0.999868631362915,
"start": 30,
"tag": "NAME",
"value": "Thomas Bock"
},
{
"context": "(ns vlagwt.score\n ^{:author \"Thomas Bock <thomas.bock@ptb.de>\"\n :doc \"Finds the max score: the current stat",
"end": 61,
"score": 0.9999209642410278,
"start": 43,
"tag": "EMAIL",
"value": "thomas.bock@ptb.de"
}
] | src/vlagwt/score.clj | wactbprot/vl-agwt | 0 | (ns vlagwt.score
^{:author "Thomas Bock <thomas.bock@ptb.de>"
:doc "Finds the max score: the current state of the calibration
request."}
(:require [vlagwt.config :as c]
[clojure.string :as string]
[vlagwt.utils :as u]))
(defn number-of-calib [v] (:Calibrations (first (filter :Calibrations v))))
(defn all-certs-ready? [v] (= (u/number-of v :Certificate) (number-of-calib v)))
(defn score
"
NEU(10, Neu),
EINGEREICHT(20, Eingereicht),
MESSUNG(30, In Messung),
ANALYSE(40, In Analyse),
ZERTIFIKAT_ERTEILT(50, Zertifikat verfügbar),
KALIBRIERUNG_FEHLER(51, Kalibrierung fehlerhaft),
ZERTIFIKAT_ARCHIVIERT(60, Zertifikat archiviert); set by agwt"
[m]
(cond
(:Planning m) 10
(:Bureaucracy m) 20
(:Measurement m) 30
(:Analysis m) 40
(:Result m) 40
(:Certificate m) 45
(:DCC m) 50
:else 0))
(defn check-certs [v] (if (all-certs-ready? v) 49 45))
(defn max-score [v]
(let [i (apply max (mapv score v))]
(if (= i 45) (check-certs v) i)))
(defn result [req v] (assoc (into {} v) :Score (max-score v)))
(defn id [req m] (assoc m :RequestId (u/sha1-str (u/req->req-id req))))
| 11794 | (ns vlagwt.score
^{:author "<NAME> <<EMAIL>>"
:doc "Finds the max score: the current state of the calibration
request."}
(:require [vlagwt.config :as c]
[clojure.string :as string]
[vlagwt.utils :as u]))
(defn number-of-calib [v] (:Calibrations (first (filter :Calibrations v))))
(defn all-certs-ready? [v] (= (u/number-of v :Certificate) (number-of-calib v)))
(defn score
"
NEU(10, Neu),
EINGEREICHT(20, Eingereicht),
MESSUNG(30, In Messung),
ANALYSE(40, In Analyse),
ZERTIFIKAT_ERTEILT(50, Zertifikat verfügbar),
KALIBRIERUNG_FEHLER(51, Kalibrierung fehlerhaft),
ZERTIFIKAT_ARCHIVIERT(60, Zertifikat archiviert); set by agwt"
[m]
(cond
(:Planning m) 10
(:Bureaucracy m) 20
(:Measurement m) 30
(:Analysis m) 40
(:Result m) 40
(:Certificate m) 45
(:DCC m) 50
:else 0))
(defn check-certs [v] (if (all-certs-ready? v) 49 45))
(defn max-score [v]
(let [i (apply max (mapv score v))]
(if (= i 45) (check-certs v) i)))
(defn result [req v] (assoc (into {} v) :Score (max-score v)))
(defn id [req m] (assoc m :RequestId (u/sha1-str (u/req->req-id req))))
| true | (ns vlagwt.score
^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:doc "Finds the max score: the current state of the calibration
request."}
(:require [vlagwt.config :as c]
[clojure.string :as string]
[vlagwt.utils :as u]))
(defn number-of-calib [v] (:Calibrations (first (filter :Calibrations v))))
(defn all-certs-ready? [v] (= (u/number-of v :Certificate) (number-of-calib v)))
(defn score
"
NEU(10, Neu),
EINGEREICHT(20, Eingereicht),
MESSUNG(30, In Messung),
ANALYSE(40, In Analyse),
ZERTIFIKAT_ERTEILT(50, Zertifikat verfügbar),
KALIBRIERUNG_FEHLER(51, Kalibrierung fehlerhaft),
ZERTIFIKAT_ARCHIVIERT(60, Zertifikat archiviert); set by agwt"
[m]
(cond
(:Planning m) 10
(:Bureaucracy m) 20
(:Measurement m) 30
(:Analysis m) 40
(:Result m) 40
(:Certificate m) 45
(:DCC m) 50
:else 0))
(defn check-certs [v] (if (all-certs-ready? v) 49 45))
(defn max-score [v]
(let [i (apply max (mapv score v))]
(if (= i 45) (check-certs v) i)))
(defn result [req v] (assoc (into {} v) :Score (max-score v)))
(defn id [req m] (assoc m :RequestId (u/sha1-str (u/req->req-id req))))
|
[
{
"context": "ed to Clojars by JUXT)\"\n :url \"http://github.com/weavejester/hiccup\"\n :license {:name \"Eclipse Public License",
"end": 195,
"score": 0.9852139949798584,
"start": 184,
"tag": "USERNAME",
"value": "weavejester"
},
{
"context": " [:developer\n [:id \"weavejester\"]\n [:name \"James Reeves\"]]\n ",
"end": 646,
"score": 0.9994465708732605,
"start": 635,
"tag": "USERNAME",
"value": "weavejester"
},
{
"context": " [:id \"weavejester\"]\n [:name \"James Reeves\"]]\n [:developer\n ",
"end": 688,
"score": 0.9998682141304016,
"start": 676,
"tag": "NAME",
"value": "James Reeves"
}
] | hiccup/hiccup/project.clj | juxt/clojars-mirrors | 0 | (defproject pro.juxt.clojars-mirrors.hiccup/hiccup "2.0.0-alpha2"
:description "A fast library for rendering HTML in Clojure (mirrored to Clojars by JUXT)"
:url "http://github.com/weavejester/hiccup"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [hiccup/hiccup "2.0.0-alpha2"]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "James Reeves"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
| 86149 | (defproject pro.juxt.clojars-mirrors.hiccup/hiccup "2.0.0-alpha2"
:description "A fast library for rendering HTML in Clojure (mirrored to Clojars by JUXT)"
:url "http://github.com/weavejester/hiccup"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [hiccup/hiccup "2.0.0-alpha2"]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "<NAME>"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
| true | (defproject pro.juxt.clojars-mirrors.hiccup/hiccup "2.0.0-alpha2"
:description "A fast library for rendering HTML in Clojure (mirrored to Clojars by JUXT)"
:url "http://github.com/weavejester/hiccup"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [hiccup/hiccup "2.0.0-alpha2"]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "PI:NAME:<NAME>END_PI"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
|
[
{
"context": "token returns empty\"\n (user/create! \"user1\" \"password1\")\n (let [thoughts (take 6 (:results quer",
"end": 3287,
"score": 0.7040624618530273,
"start": 3279,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " other-token (invoke-login {:username \"User1\" :password \"password1\"})\n [response re",
"end": 3526,
"score": 0.788020133972168,
"start": 3521,
"tag": "USERNAME",
"value": "User1"
},
{
"context": "token (invoke-login {:username \"User1\" :password \"password1\"})\n [response result] (get-request (st",
"end": 3548,
"score": 0.9994560480117798,
"start": 3539,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "nvoke-login {:username tdu/ph-username :password tdu/ph-password})\n [_ c1] (post-request \"/api/clusters\" {:",
"end": 4388,
"score": 0.7142906188964844,
"start": 4374,
"tag": "PASSWORD",
"value": "du/ph-password"
},
{
"context": "token returns empty\"\n (user/create! \"user1\" \"password1\")\n (let [other-token (invoke-login {:usernam",
"end": 5382,
"score": 0.7814816236495972,
"start": 5373,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": " (let [other-token (invoke-login {:username \"User1\" :password \"password1\"})\n [response re",
"end": 5440,
"score": 0.9995625615119934,
"start": 5435,
"tag": "USERNAME",
"value": "User1"
},
{
"context": "token (invoke-login {:username \"User1\" :password \"password1\"})\n [response result] (get-request \"/a",
"end": 5462,
"score": 0.9993976950645447,
"start": 5453,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": " other-token (invoke-login {:username \"User1\" :password \"password1\"})\n [_ oc1] (pos",
"end": 5909,
"score": 0.9994736313819885,
"start": 5904,
"tag": "USERNAME",
"value": "User1"
},
{
"context": "en (invoke-login {:username \"User1\" :password \"password1\"})\n [_ oc1] (post-request \"/api/cluste",
"end": 5931,
"score": 0.9994540214538574,
"start": 5922,
"tag": "PASSWORD",
"value": "password1"
},
{
"context": "d})\n other-token (invoke-login {:username \"user1\" :password \"password1\"})\n thoughts (tak",
"end": 6616,
"score": 0.9995205998420715,
"start": 6611,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "token (invoke-login {:username \"user1\" :password \"password1\"})\n thoughts (take 8 (:results query))\n",
"end": 6638,
"score": 0.9994165897369385,
"start": 6629,
"tag": "PASSWORD",
"value": "password1"
}
] | test/clj/memento/test/routes/api/thought_cluster.clj | ricardojmendez/memento | 2 | (ns memento.test.routes.api.thought-cluster
(:require [clojure.test :refer :all]
[clj-time.coerce :as c]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.db.memory :as tdm]
[memento.test.db.user :as tdu]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[memento.db.memory :as memory]
[mount.core :as mount])
(:import (java.util UUID)))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Adding a cluster
;;;
(deftest test-create-cluster
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "Attempting to add a cluster without a token results in a 400"
(let [[response _] (post-request "/api/clusters" {} nil)]
(is (= 400 (:status response)))))
(testing "We cannot add empty clusters"
(let [[response _] (post-request "/api/clusters" [] token)]
(is (= 400 (:status response)))))
(testing "We can create a new cluster"
(let [thoughts (map :id (take 6 (:results query)))
[response record] (post-request "/api/clusters" {:thought-ids thoughts} token)]
(is (= 201 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (str "http://localhost/api/clusters/" (:id record)) (get-in response [:headers "Location"])))))))
(deftest test-cluster-retrieve
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "After adding a cluster, we can retrieve it"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (set thoughts)
(set (:results result))))))
(testing "Attempting to retrieve a cluster with an invalid token fails"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve a cluster with different user's token returns empty"
(user/create! "user1" "password1")
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
other-token (invoke-login {:username "User1" :password "password1"})
[response result] (get-request (str "/api/clusters/" (:id record)) nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))
(testing "Attempting to retrieve a non-existent cluster returns empty"
(let [[response result] (get-request (str "/api/clusters/" (UUID/randomUUID)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))))
(deftest test-get-cluster-list
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})
[_ c1] (post-request "/api/clusters" {:thought-ids (map :id (take 6 (:results query)))} token)
[r1 rc1] (get-request "/api/clusters" nil token)
[_ c2] (post-request "/api/clusters" {:thought-ids (map :id (take 2 (drop 3 (:results query))))} token)
[_ rc2] (get-request "/api/clusters" nil token)]
(testing "After creating a cluster, we can retrieve it"
(is (= 200 (:status r1)))
(is (= "application/transit+json" (get-in r1 [:headers "Content-Type"])))
(is (= [c1] rc1)))
(testing "Clusters are returned in inverse create order"
(is (= [c2 c1] rc2)))
(testing "Attempting to retrieve with an invalid token fails authorization"
(let [[response result] (get-request "/api/clusters" nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve the clusters with different user's token returns empty"
(user/create! "user1" "password1")
(let [other-token (invoke-login {:username "User1" :password "password1"})
[response result] (get-request "/api/clusters" nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (empty? result))))
(testing "Users only view their own clusters"
(tdm/import-placeholder-memories! "user1")
(let [user1-memories (memory/query "user1")
other-token (invoke-login {:username "User1" :password "password1"})
[_ oc1] (post-request "/api/clusters" {:thought-ids (map :id (take 5 (drop 3 (:results user1-memories))))} other-token)
[_ clusters-1] (get-request "/api/clusters" nil token)
[_ clusters-2] (get-request "/api/clusters" nil other-token)]
(is (= [c2 c1] clusters-1))
(is (= [oc1] clusters-2)))
)))
(deftest test-remove-thought
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(user/create! "user1" "password1")
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})
other-token (invoke-login {:username "user1" :password "password1"})
thoughts (take 8 (:results query))
thought-ids (map :id thoughts)
[_ cluster] (post-request "/api/clusters" {:thought-ids thought-ids} token)]
(testing "After adding a cluster, we can remove a thought from it"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response result] (del-request "/api/clusters" (:id cluster) to-delete token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
;; Not testing that we delete the correct thought, already testing
;; for that when I test the base function
(is (= 204 (:status response)))
(is (empty? result))
(is (= 8 (:total thoughts-before)))
(is (= 7 (:total thoughts-after)))))
(testing "Attempting to delete with the wrong token 404s"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response _] (del-request "/api/clusters" (:id cluster) to-delete other-token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 404 (:status response)))
(is (= thoughts-before thoughts-after))))
(testing "Attempting to delete with an invalid token gives a permission error"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
[response _] (del-request "/api/clusters" (:id cluster) (:id cluster) "invalid")
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 401 (:status response)))
(is (= thoughts-before thoughts-after)))))) | 102363 | (ns memento.test.routes.api.thought-cluster
(:require [clojure.test :refer :all]
[clj-time.coerce :as c]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.db.memory :as tdm]
[memento.test.db.user :as tdu]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[memento.db.memory :as memory]
[mount.core :as mount])
(:import (java.util UUID)))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Adding a cluster
;;;
(deftest test-create-cluster
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "Attempting to add a cluster without a token results in a 400"
(let [[response _] (post-request "/api/clusters" {} nil)]
(is (= 400 (:status response)))))
(testing "We cannot add empty clusters"
(let [[response _] (post-request "/api/clusters" [] token)]
(is (= 400 (:status response)))))
(testing "We can create a new cluster"
(let [thoughts (map :id (take 6 (:results query)))
[response record] (post-request "/api/clusters" {:thought-ids thoughts} token)]
(is (= 201 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (str "http://localhost/api/clusters/" (:id record)) (get-in response [:headers "Location"])))))))
(deftest test-cluster-retrieve
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "After adding a cluster, we can retrieve it"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (set thoughts)
(set (:results result))))))
(testing "Attempting to retrieve a cluster with an invalid token fails"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve a cluster with different user's token returns empty"
(user/create! "user1" "<PASSWORD>1")
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
other-token (invoke-login {:username "User1" :password "<PASSWORD>"})
[response result] (get-request (str "/api/clusters/" (:id record)) nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))
(testing "Attempting to retrieve a non-existent cluster returns empty"
(let [[response result] (get-request (str "/api/clusters/" (UUID/randomUUID)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))))
(deftest test-get-cluster-list
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password t<PASSWORD>})
[_ c1] (post-request "/api/clusters" {:thought-ids (map :id (take 6 (:results query)))} token)
[r1 rc1] (get-request "/api/clusters" nil token)
[_ c2] (post-request "/api/clusters" {:thought-ids (map :id (take 2 (drop 3 (:results query))))} token)
[_ rc2] (get-request "/api/clusters" nil token)]
(testing "After creating a cluster, we can retrieve it"
(is (= 200 (:status r1)))
(is (= "application/transit+json" (get-in r1 [:headers "Content-Type"])))
(is (= [c1] rc1)))
(testing "Clusters are returned in inverse create order"
(is (= [c2 c1] rc2)))
(testing "Attempting to retrieve with an invalid token fails authorization"
(let [[response result] (get-request "/api/clusters" nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve the clusters with different user's token returns empty"
(user/create! "user1" "<PASSWORD>")
(let [other-token (invoke-login {:username "User1" :password "<PASSWORD>"})
[response result] (get-request "/api/clusters" nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (empty? result))))
(testing "Users only view their own clusters"
(tdm/import-placeholder-memories! "user1")
(let [user1-memories (memory/query "user1")
other-token (invoke-login {:username "User1" :password "<PASSWORD>"})
[_ oc1] (post-request "/api/clusters" {:thought-ids (map :id (take 5 (drop 3 (:results user1-memories))))} other-token)
[_ clusters-1] (get-request "/api/clusters" nil token)
[_ clusters-2] (get-request "/api/clusters" nil other-token)]
(is (= [c2 c1] clusters-1))
(is (= [oc1] clusters-2)))
)))
(deftest test-remove-thought
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(user/create! "user1" "password1")
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})
other-token (invoke-login {:username "user1" :password "<PASSWORD>"})
thoughts (take 8 (:results query))
thought-ids (map :id thoughts)
[_ cluster] (post-request "/api/clusters" {:thought-ids thought-ids} token)]
(testing "After adding a cluster, we can remove a thought from it"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response result] (del-request "/api/clusters" (:id cluster) to-delete token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
;; Not testing that we delete the correct thought, already testing
;; for that when I test the base function
(is (= 204 (:status response)))
(is (empty? result))
(is (= 8 (:total thoughts-before)))
(is (= 7 (:total thoughts-after)))))
(testing "Attempting to delete with the wrong token 404s"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response _] (del-request "/api/clusters" (:id cluster) to-delete other-token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 404 (:status response)))
(is (= thoughts-before thoughts-after))))
(testing "Attempting to delete with an invalid token gives a permission error"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
[response _] (del-request "/api/clusters" (:id cluster) (:id cluster) "invalid")
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 401 (:status response)))
(is (= thoughts-before thoughts-after)))))) | true | (ns memento.test.routes.api.thought-cluster
(:require [clojure.test :refer :all]
[clj-time.coerce :as c]
[clj-time.core :as t]
[memento.handler :refer [app]]
[memento.config :refer [env]]
[memento.db.user :as user]
[memento.test.db.core :as tdb]
[memento.test.db.memory :as tdm]
[memento.test.db.user :as tdu]
[memento.test.routes.helpers :refer [post-request patch-request get-request put-request del-request invoke-login]]
[memento.db.core :refer [*db*]]
[memento.db.memory :as memory]
[mount.core :as mount])
(:import (java.util UUID)))
(use-fixtures
:once
(fn [f]
(mount/start
#'memento.config/env
#'memento.db.core/*db*)
(f)))
;;;;
;;;; Tests
;;;;
;;;
;;; Adding a cluster
;;;
(deftest test-create-cluster
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "Attempting to add a cluster without a token results in a 400"
(let [[response _] (post-request "/api/clusters" {} nil)]
(is (= 400 (:status response)))))
(testing "We cannot add empty clusters"
(let [[response _] (post-request "/api/clusters" [] token)]
(is (= 400 (:status response)))))
(testing "We can create a new cluster"
(let [thoughts (map :id (take 6 (:results query)))
[response record] (post-request "/api/clusters" {:thought-ids thoughts} token)]
(is (= 201 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (str "http://localhost/api/clusters/" (:id record)) (get-in response [:headers "Location"])))))))
(deftest test-cluster-retrieve
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})]
(testing "After adding a cluster, we can retrieve it"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (map? record))
(is (:id record))
(is (= (set thoughts)
(set (:results result))))))
(testing "Attempting to retrieve a cluster with an invalid token fails"
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
[response result] (get-request (str "/api/clusters/" (:id record)) nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve a cluster with different user's token returns empty"
(user/create! "user1" "PI:PASSWORD:<PASSWORD>END_PI1")
(let [thoughts (take 6 (:results query))
thought-ids (map :id thoughts)
[_ record] (post-request "/api/clusters" {:thought-ids thought-ids} token)
other-token (invoke-login {:username "User1" :password "PI:PASSWORD:<PASSWORD>END_PI"})
[response result] (get-request (str "/api/clusters/" (:id record)) nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))
(testing "Attempting to retrieve a non-existent cluster returns empty"
(let [[response result] (get-request (str "/api/clusters/" (UUID/randomUUID)) nil token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (= tdm/empty-query result))))))
(deftest test-get-cluster-list
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tPI:PASSWORD:<PASSWORD>END_PI})
[_ c1] (post-request "/api/clusters" {:thought-ids (map :id (take 6 (:results query)))} token)
[r1 rc1] (get-request "/api/clusters" nil token)
[_ c2] (post-request "/api/clusters" {:thought-ids (map :id (take 2 (drop 3 (:results query))))} token)
[_ rc2] (get-request "/api/clusters" nil token)]
(testing "After creating a cluster, we can retrieve it"
(is (= 200 (:status r1)))
(is (= "application/transit+json" (get-in r1 [:headers "Content-Type"])))
(is (= [c1] rc1)))
(testing "Clusters are returned in inverse create order"
(is (= [c2 c1] rc2)))
(testing "Attempting to retrieve with an invalid token fails authorization"
(let [[response result] (get-request "/api/clusters" nil "invalid")]
(is (= 401 (:status response)))
(is (= {:error "unauthorized"} result))))
(testing "Attempting to retrieve the clusters with different user's token returns empty"
(user/create! "user1" "PI:PASSWORD:<PASSWORD>END_PI")
(let [other-token (invoke-login {:username "User1" :password "PI:PASSWORD:<PASSWORD>END_PI"})
[response result] (get-request "/api/clusters" nil other-token)]
(is (= 200 (:status response)))
(is (= "application/transit+json" (get-in response [:headers "Content-Type"])))
(is (empty? result))))
(testing "Users only view their own clusters"
(tdm/import-placeholder-memories! "user1")
(let [user1-memories (memory/query "user1")
other-token (invoke-login {:username "User1" :password "PI:PASSWORD:<PASSWORD>END_PI"})
[_ oc1] (post-request "/api/clusters" {:thought-ids (map :id (take 5 (drop 3 (:results user1-memories))))} other-token)
[_ clusters-1] (get-request "/api/clusters" nil token)
[_ clusters-2] (get-request "/api/clusters" nil other-token)]
(is (= [c2 c1] clusters-1))
(is (= [oc1] clusters-2)))
)))
(deftest test-remove-thought
(tdu/init-placeholder-data!)
(tdm/import-placeholder-memories!)
(user/create! "user1" "password1")
(let [query (memory/query tdu/ph-username)
token (invoke-login {:username tdu/ph-username :password tdu/ph-password})
other-token (invoke-login {:username "user1" :password "PI:PASSWORD:<PASSWORD>END_PI"})
thoughts (take 8 (:results query))
thought-ids (map :id thoughts)
[_ cluster] (post-request "/api/clusters" {:thought-ids thought-ids} token)]
(testing "After adding a cluster, we can remove a thought from it"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response result] (del-request "/api/clusters" (:id cluster) to-delete token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
;; Not testing that we delete the correct thought, already testing
;; for that when I test the base function
(is (= 204 (:status response)))
(is (empty? result))
(is (= 8 (:total thoughts-before)))
(is (= 7 (:total thoughts-after)))))
(testing "Attempting to delete with the wrong token 404s"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
to-delete (:id (first (:results thoughts-before)))
[response _] (del-request "/api/clusters" (:id cluster) to-delete other-token)
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 404 (:status response)))
(is (= thoughts-before thoughts-after))))
(testing "Attempting to delete with an invalid token gives a permission error"
(let [[_ thoughts-before] (get-request (str "/api/clusters/" (:id cluster)) nil token)
[response _] (del-request "/api/clusters" (:id cluster) (:id cluster) "invalid")
[_ thoughts-after] (get-request (str "/api/clusters/" (:id cluster)) nil token)]
(is (= 401 (:status response)))
(is (= thoughts-before thoughts-after)))))) |
[
{
"context": "st/chemiclj_scratch.clj\n;;;\n;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.com) All rights\n;;; reserved.\n",
"end": 75,
"score": 0.9998693466186523,
"start": 63,
"tag": "NAME",
"value": "Cyrus Harmon"
},
{
"context": "atch.clj\n;;;\n;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.com) All rights\n;;; reserved.\n;;;\n;;; Redistribution ",
"end": 98,
"score": 0.9999292492866516,
"start": 77,
"tag": "EMAIL",
"value": "ch-lisp@bobobeach.com"
}
] | test/chemiclj_scratch.clj | slyrus/chemiclj | 1 | ;;; file: test/chemiclj_scratch.clj
;;;
;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.com) 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 chemiclj-scratch
(:use [chemiclj.core])
(:require [chemiclj.element :as element]
[chemiclj.smiles :as smiles]
[chemiclj.smiles.write :as write]
[smiles-test :as smiles-test]
[shortcut.graph :as graph]))
(def c1 (make-atom :c "C1"))
(def h1 (make-atom :h "H1"))
(def h2 (make-atom :h "H2"))
(def h3 (make-atom :h "H3"))
(def c2 (make-atom :c "C2"))
(def h4 (make-atom :h "H4"))
(def h5 (make-atom :h "H5"))
(def h6 (make-atom :h "H6"))
(def ethane (make-molecule #{c1 h1 h2 h3 c2 h4 h5 h6}
[[c1 h1]
[c1 h2]
[c1 h3]
[c1 c2]
[c2 h4]
[c2 h5]
[c2 h6]]))
(mass ethane)
(exact-mass ethane)
(add-bond (reduce add-atom (make-molecule) [c1 c2])
(make-bond c1 c2))
(add-bond (reduce add-atom (make-molecule) [c1 c2]) c1 c2)
;;; scratch for writing SMILES strings
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/rank-by second (write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariant-ranks mol)))
;;;
(sort-by first
(map #(vector ((comp name first) %)
((comp inc second) %))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-canonical-labels mol))))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(graph/depth-first-traversal mol
(ffirst (sort-by second labels))))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(ffirst (sort-by second labels)))
(sort-by first
(map #(vector ((comp name first) %)
(second %))
(let [mol (smiles-test/get-molecule
"cubane")]
(write/smiles-canonical-labels mol))))
(smiles/read-smiles-string "Br/C(=C/F)I")
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "F/C=C/F")))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C\\F)/I")))
(= (set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(/I)=C/F"))))
(set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C/F)/I")))))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles-test/get-molecule "tamoxifen")))
;; find the double bonds in tamoxifen:
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))
;; get the names of all the atoms that participate in double bonds in tamoxifen:
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen"))))
;; or
(names
(reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))))
;; now let's get the top atom of each configuration attached to each
;; atom that participates in a double bond:
(let [mol (smiles-test/get-molecule "tamoxifen")]
(map (partial map (comp name :top))
(map second
(let [s (set (reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds mol))))]
(filter #(s (first %)) (configurations mol))))))
;;; oxytocin
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles-test/get-molecule "oxytocin")))
;;;
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "C[C@H](Br)I")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "N1C[C@H]1C")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "[H][C@]1(Br)CCC1")))
;;; names of each non-H atom and its neighbors:
(let [mol (smiles-test/get-molecule "cubane")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(let [mol (smiles-test/get-molecule "serotonin")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tropone"))))
(map (comp names atoms) (bonds (smiles/read-smiles-string "[Na+].[O-]c1ccccc1")))
(map (comp names atoms) (bonds (smiles/read-smiles-string "c1cc([O-].[Na+])ccc1")))
| 112003 | ;;; file: test/chemiclj_scratch.clj
;;;
;;; Copyright (c) 2010 <NAME> (<EMAIL>) All rights
;;; reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 chemiclj-scratch
(:use [chemiclj.core])
(:require [chemiclj.element :as element]
[chemiclj.smiles :as smiles]
[chemiclj.smiles.write :as write]
[smiles-test :as smiles-test]
[shortcut.graph :as graph]))
(def c1 (make-atom :c "C1"))
(def h1 (make-atom :h "H1"))
(def h2 (make-atom :h "H2"))
(def h3 (make-atom :h "H3"))
(def c2 (make-atom :c "C2"))
(def h4 (make-atom :h "H4"))
(def h5 (make-atom :h "H5"))
(def h6 (make-atom :h "H6"))
(def ethane (make-molecule #{c1 h1 h2 h3 c2 h4 h5 h6}
[[c1 h1]
[c1 h2]
[c1 h3]
[c1 c2]
[c2 h4]
[c2 h5]
[c2 h6]]))
(mass ethane)
(exact-mass ethane)
(add-bond (reduce add-atom (make-molecule) [c1 c2])
(make-bond c1 c2))
(add-bond (reduce add-atom (make-molecule) [c1 c2]) c1 c2)
;;; scratch for writing SMILES strings
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/rank-by second (write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariant-ranks mol)))
;;;
(sort-by first
(map #(vector ((comp name first) %)
((comp inc second) %))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-canonical-labels mol))))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(graph/depth-first-traversal mol
(ffirst (sort-by second labels))))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(ffirst (sort-by second labels)))
(sort-by first
(map #(vector ((comp name first) %)
(second %))
(let [mol (smiles-test/get-molecule
"cubane")]
(write/smiles-canonical-labels mol))))
(smiles/read-smiles-string "Br/C(=C/F)I")
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "F/C=C/F")))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C\\F)/I")))
(= (set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(/I)=C/F"))))
(set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C/F)/I")))))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles-test/get-molecule "tamoxifen")))
;; find the double bonds in tamoxifen:
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))
;; get the names of all the atoms that participate in double bonds in tamoxifen:
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen"))))
;; or
(names
(reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))))
;; now let's get the top atom of each configuration attached to each
;; atom that participates in a double bond:
(let [mol (smiles-test/get-molecule "tamoxifen")]
(map (partial map (comp name :top))
(map second
(let [s (set (reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds mol))))]
(filter #(s (first %)) (configurations mol))))))
;;; oxytocin
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles-test/get-molecule "oxytocin")))
;;;
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "C[C@H](Br)I")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "N1C[C@H]1C")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "[H][C@]1(Br)CCC1")))
;;; names of each non-H atom and its neighbors:
(let [mol (smiles-test/get-molecule "cubane")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(let [mol (smiles-test/get-molecule "serotonin")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tropone"))))
(map (comp names atoms) (bonds (smiles/read-smiles-string "[Na+].[O-]c1ccccc1")))
(map (comp names atoms) (bonds (smiles/read-smiles-string "c1cc([O-].[Na+])ccc1")))
| true | ;;; file: test/chemiclj_scratch.clj
;;;
;;; Copyright (c) 2010 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) All rights
;;; reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 chemiclj-scratch
(:use [chemiclj.core])
(:require [chemiclj.element :as element]
[chemiclj.smiles :as smiles]
[chemiclj.smiles.write :as write]
[smiles-test :as smiles-test]
[shortcut.graph :as graph]))
(def c1 (make-atom :c "C1"))
(def h1 (make-atom :h "H1"))
(def h2 (make-atom :h "H2"))
(def h3 (make-atom :h "H3"))
(def c2 (make-atom :c "C2"))
(def h4 (make-atom :h "H4"))
(def h5 (make-atom :h "H5"))
(def h6 (make-atom :h "H6"))
(def ethane (make-molecule #{c1 h1 h2 h3 c2 h4 h5 h6}
[[c1 h1]
[c1 h2]
[c1 h3]
[c1 c2]
[c2 h4]
[c2 h5]
[c2 h6]]))
(mass ethane)
(exact-mass ethane)
(add-bond (reduce add-atom (make-molecule) [c1 c2])
(make-bond c1 c2))
(add-bond (reduce add-atom (make-molecule) [c1 c2]) c1 c2)
;;; scratch for writing SMILES strings
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/rank-by second (write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariants mol)))
(reduce #(assoc %1 ((comp name first) %2) (second %2))
{}
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-atomic-invariant-ranks mol)))
;;;
(sort-by first
(map #(vector ((comp name first) %)
((comp inc second) %))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")]
(write/smiles-canonical-labels mol))))
(let [mol (smiles-test/get-molecule "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(graph/depth-first-traversal mol
(ffirst (sort-by second labels))))
(let [mol (smiles-test/get-molecule
"6-amino-2-ethyl-5-(aminomethyl)-1-hexanol")
labels (write/smiles-canonical-labels mol)]
(ffirst (sort-by second labels)))
(sort-by first
(map #(vector ((comp name first) %)
(second %))
(let [mol (smiles-test/get-molecule
"cubane")]
(write/smiles-canonical-labels mol))))
(smiles/read-smiles-string "Br/C(=C/F)I")
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "F/C=C/F")))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C\\F)/I")))
(= (set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(/I)=C/F"))))
(set
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles/read-smiles-string "Br/C(=C/F)/I")))))
(map (fn [[k v]] [(name k) (map (fn [x] (names [(:top x)
(:bottom x)])) v)])
(configurations (smiles-test/get-molecule "tamoxifen")))
;; find the double bonds in tamoxifen:
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))
;; get the names of all the atoms that participate in double bonds in tamoxifen:
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen"))))
;; or
(names
(reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tamoxifen")))))
;; now let's get the top atom of each configuration attached to each
;; atom that participates in a double bond:
(let [mol (smiles-test/get-molecule "tamoxifen")]
(map (partial map (comp name :top))
(map second
(let [s (set (reduce #(into %1 (atoms %2))
[]
(filter (comp #{2} :order) (bonds mol))))]
(filter #(s (first %)) (configurations mol))))))
;;; oxytocin
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles-test/get-molecule "oxytocin")))
;;;
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "C[C@H](Br)I")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "N1C[C@H]1C")))
(map (fn [[k v]]
[(name k)
(map (fn [x]
(cond (= (class x) chemiclj.core.RelativeVerticalConfiguration)
(names [(:top x) (:bottom x)])
(= (class x) chemiclj.core.TetrahedralAtomConfiguration)
[(name (:center x))
(:direction x)
(names [(:w x) (:x x) (:y x) (:z x)])]))
v)])
(configurations (smiles/read-smiles-string "[H][C@]1(Br)CCC1")))
;;; names of each non-H atom and its neighbors:
(let [mol (smiles-test/get-molecule "cubane")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(let [mol (smiles-test/get-molecule "serotonin")]
(map (fn [a]
[(name a) (names (neighbors mol a))])
(atoms (remove-atoms-of-element mol "H"))))
(map (comp names atoms)
(filter (comp #{2} :order) (bonds (smiles-test/get-molecule "tropone"))))
(map (comp names atoms) (bonds (smiles/read-smiles-string "[Na+].[O-]c1ccccc1")))
(map (comp names atoms) (bonds (smiles/read-smiles-string "c1cc([O-].[Na+])ccc1")))
|
[
{
"context": "(ns clojure_refactoring)\n\n;; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar",
"end": 60,
"score": 0.999657928943634,
"start": 48,
"tag": "NAME",
"value": "Tom Crayford"
}
] | src/clojure_refactoring.clj | tcrayford/clojure-refactoring | 6 | (ns clojure_refactoring)
;; Copyright (c) 2010 Tom Crayford,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
| 32205 | (ns clojure_refactoring)
;; Copyright (c) 2010 <NAME>,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
| true | (ns clojure_refactoring)
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
|
[
{
"context": "lidation (see [[with-two-pass]]).\"\n :author \"Paul Landes\"}\n zensols.model.eval-classifier\n (:require [",
"end": 272,
"score": 0.9998874664306641,
"start": 261,
"tag": "NAME",
"value": "Paul Landes"
},
{
"context": "```\n\n See a [working example](https://github.com/plandes/clj-example-nlp-ml/blob/master/src/clojure/zensol",
"end": 28383,
"score": 0.9790245294570923,
"start": 28376,
"tag": "USERNAME",
"value": "plandes"
}
] | src/clojure/zensols/model/eval_classifier.clj | plandes/clj-ml-model | 6 | (ns ^{:doc
"A *client* entry point library to help with evaluating machine learning
models. This library not only wraps the Weka library but also provides
additional functionality like a two pass cross
validation (see [[with-two-pass]])."
:author "Paul Landes"}
zensols.model.eval-classifier
(:require [clojure.tools.logging :as log]
[clojure.java.io :as io :refer [input-stream output-stream file]]
[clojure.string :as s]
[clojure.stacktrace :refer (print-stack-trace)]
[clojure.data.csv :as csv])
(:require [zensols.tabres.display-results :as dr])
(:require [zensols.model.execute-classifier :refer (model-config) :as exc]
[zensols.model.weka :as weka]
[zensols.model.classifier :as cl]))
(def ^:dynamic *default-set-type*
"The default type of test, which is one of:
* `:cross-validation`: run a N fold cross validation (default)
* `:train-test`: train the classifier and then evaluate"
:cross-validation)
(def ^:dynamic *throw-cross-validate*
"If `true`, throw an exception during cross validation for any errors.
Otherwise, the error is logged and cross-validation continues. This is
useful for when classifiers are used and some choke given the dataset, but
you still want the other results."
false)
(defn- by-set-type-instances [set-type]
(case set-type
:cross-validation (exc/cross-fold-instances)
:train-test (:train-test (exc/train-test-instances))
:test (:test (exc/train-test-instances))
:train (:train (exc/train-test-instances))
true (throw (ex-info "Unknon set type"
{:set-type *default-set-type*}))))
(defn print-model-config
"Pretty print the model configuation set
with [[zensols.model.execute-classifier/with-model-conf]]."
[]
(clojure.pprint/pprint (model-config)))
(defn analysis-file
([]
(analysis-file "%s-data.arff"))
([file-format]
(let [model-conf (model-config)
file-name (format file-format (:name model-conf))]
(io/file (cl/analysis-report-resource) file-name))))
(defn read-arff
"Read the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(read-arff (analysis-file)))
([file]
(cl/read-arff file)))
(defn write-arff
"Write the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(write-arff (analysis-file)))
([file]
(binding [cl/*arff-file* file]
(cl/write-arff (by-set-type-instances :train-test)))
file))
(defn- feature-matrix
"Generate a matrix of features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]]."
[& {:keys [max] :as adb-keys
:or {max Integer/MAX_VALUE}}]
(let [{:keys [feature-metas-fn display-feature-metas-fn
class-feature-meta-fn create-feature-sets-fn]} (model-config)
display-feature-metas-fn (or display-feature-metas-fn feature-metas-fn)
feature-metas (display-feature-metas-fn)
class-feature-meta (class-feature-meta-fn)
adb-keys (if adb-keys
(->> (dissoc adb-keys :max)
(into [])
(apply concat)))
feature-sets (->> (apply create-feature-sets-fn adb-keys)
(take max))]
(let [keys (map first (concat (list class-feature-meta) feature-metas))]
(->> feature-sets
(map (fn [tok]
(map (fn [tkey]
(get tok tkey))
keys)))
(hash-map :column-names (map name keys) :data)))))
(defn display-features
"Display features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]].
**adb-keys** are given to `:create-feature-sets-fn` as described
in [[zensols.model.execute-classifier/with-model-conf]]. In addition it
includes `:max`, which is the maximum number of instances to display."
[& adb-keys]
(let [{:keys [column-names data]} (apply feature-matrix adb-keys)]
(dr/display-results data :column-names column-names)))
(defn features-file
"Return the default file used to create the features output file
with [[write-features]]."
[]
(analysis-file "%s-features.csv"))
(defn write-features
"Write features as configured in a model with [[zensols.model.execute-classifier/with-model-conf]] to a CSV
spreadsheet file.
See [[features-file]] for the default file
For the non-zero-arg form, see [[zensols.model.execute-classifier/with-model-conf]]."
([]
(write-features (features-file)))
([file]
(let [{:keys [column-names data]} (feature-matrix)]
(with-open [writer (io/writer file)]
(->> data
(cons column-names)
(csv/write-csv writer)))
(log/infof "wrote features file: %s" file)
file)))
(defn- cross-validate-results-struct
"Create a data structure with cross validation results."
[classifiers attribs-sets feature-metadata]
(log/debugf "cvr struct classifiers=<%s>, attribs=%s"
(pr-str classifiers) (pr-str attribs-sets))
(letfn [(cr-test [classifier attribs]
(try
(log/infof "classifier: <%s>, %s" classifier (pr-str attribs))
(let [res (cl/cross-validate-tests classifier (map name attribs)
feature-metadata)]
(log/debug (with-out-str (cl/print-results res)))
res)
(catch Exception e
(if *throw-cross-validate*
(do
(log/error e "couldn not cross validate")
(throw e))
(let [msg (format "Can't cross validate classifier %s, attrib: %s: message=%s"
classifier (if attribs (s/join "," attribs))
(.toString e))]
(log/error (str "stack trace: " (print-stack-trace e)))
(log/error e msg)
nil)))))]
(->> classifiers
(map (fn [classifier]
(keep #(cr-test classifier %) attribs-sets)))
(remove empty?)
(apply concat))))
(defn- freeze-feature-metadata [model-conf]
(let [{:keys [feature-metas-fn class-feature-meta-fn]} model-conf
class-feat (class-feature-meta-fn)]
{:feature-metas (into {} (feature-metas-fn))
:class-key (first class-feat)
:class-type (second class-feat)}))
(declare two-pass-config)
(declare executing-two-pass?)
(defn- cross-validate-results
"Cross validate several models in series.
* **classifier-sets** is a key in [[zensols.model.weka/*classifier*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-sets-key]
(log/debugf "cvr struct attrib key=%s" feature-sets-key)
(let [model-conf (model-config)]
(log/debugf "model config keys: %s" (keys model-conf))
(let [classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
instances (exc/cross-fold-instances)
num-inst (.numInstances instances)
folds cl/*cross-fold-count*]
(log/debugf "number of instances: %d, feature-meta-set: <%s>, attribs: %s"
num-inst (pr-str feature-meta-sets)
(->> (weka/attributes-for-instances instances)
(map :name)
pr-str))
(log/tracef "instances class: %s" (-> instances .getClass .getName))
(if-let [id-val (if (and (executing-two-pass?)
(> (.numInstances instances) 0))
(->> (two-pass-config)
:id-key
name
(weka/value instances 0)))]
(if (= "?" id-val)
(-> (format "Key not set yet for two pass cross validation: %s"
(.instance instances 0))
(ex-info {:instance (.instance instances 0)})
throw)))
(if (<= num-inst folds)
(throw (ex-info "Not enough folds"
{:num-inst num-inst
:folds folds}))
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map #(cross-validate-results-struct
(weka/make-classifiers %)
feature-meta-sets
feature-metadata))
(apply concat)
doall))))))
(defn train-test-results
"Test the performance of a model by training on a given set of data
and evaluate on the test data.
See [[train-model]] for parameter details."
[classifier-sets feature-sets-key]
(log/debugf "feature-sets-key=%s, classifier-sets=%s"
feature-sets-key classifier-sets)
(let [model-conf (model-config)
_ (log/debugf "model config keys: %s" (keys model-conf))
classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (log/debugf "feature meta sets: <%s>"
(pr-str feature-meta-sets))
{train-instances :train test-instances :test}
(exc/train-test-instances)]
(assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
(assert train-instances "train-instances")
(assert test-instances "test-instances")
(log/infof "number of train/test instances:(%d, %d)"
(.numInstances train-instances)
(.numInstances test-instances))
(log/debugf "feature metas: %s " (pr-str feature-meta-sets))
(log/tracef "train instances class: %s"
(-> train-instances .getClass .getName))
(log/tracef "test instances class: %s"
(-> test-instances .getClass .getName))
(binding [cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map weka/make-classifiers)
(apply concat)
(map #(cl/train-test-classifier % feature-meta-sets
feature-metadata
train-instances test-instances))
(apply concat)
doall))))
(defn run-tests
"Create result sets useful to functions like [[eval-and-write]]. This
package was designed for most use cases to not have to use this function.
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [test-fn (case *default-set-type*
:cross-validation cross-validate-results
:train-test train-test-results)
res (test-fn classifier-sets feature-set-key)]
(log/debugf "results count %d" (count res))
res))
(defn compile-results
"Run cross-fold validation and compile into a nice results map sorted by
performance.
See [[zensols.model.classifier/compile-results]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-set-key]
(->> (run-tests classifier-sets feature-set-key)
cl/compile-results))
(defn terse-results
"Return terse cross-validation results in an array:
* classifier name
* weighted F-measure
* feature-metas
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
## Keys
* **:only-stats?** if `true` only return statistic data
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key &
{:keys [only-stats?]
:or {only-stats? true}}]
(let [res (compile-results classifier-sets feature-set-key)]
(log/debugf "terse results count %d" (count res))
(map (fn [elt]
(concat [(cl/classifier-name (:classifier elt))
(:wfmeasure elt)]
(if-not only-stats?
[feature-set-key
(:attributes elt)])))
res)))
(defn print-best-results
"Print the highest (best) scored cross validation information.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [comp-res (compile-results classifier-sets feature-set-key)]
(cl/print-results (:result (first comp-res)))))
(defn create-model
"Create a model that can be trained. This runs cross fold validations to
find the best classifier and feature set into a result that can be used
with [[train-model]] and subsequently [[write-model]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(-> (compile-results classifier-sets feature-set-key)
first
(dissoc :result :all-results)
(merge {:name (:name (model-config))
:create-time (java.util.Date.)})))
(defn train-model
"Train a model created from [[create-model]]. The model is trained on the
full available dataset. After the classifier is trained, you can save it to
disk by calling [[write-model]].
* **model** a model that was created with [[create-model]]
See [[*throw-cross-validate*]]."
[model & {:keys [set-type] :or {set-type *default-set-type*}}]
(let [classifier (:classifier model)
attribs (map name (:attributes model))
classify-attrib (first (exc/model-classifier-label))
instances (by-set-type-instances set-type)]
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classify-attrib)]
(log/infof "training model %s classifier %s with %d instances"
(:name (model-config))
(-> classifier .getClass .getName)
(.numInstances instances))
(cl/train-classifier classifier attribs)
model)))
(defn- model-persist-name
"Return the name of the model of the model configuration."
[]
(:name (model-config)))
(defn write-model
"Persist/write the model to disk.
* **model** a model that was trained with [[train-model]]
See [[zensols.model.classifier/model-dir]] for information about to where the
model is written."
([model]
(write-model model (model-persist-name)))
([model name]
(let [model-conf (model-config)
context-fn (:context-fn model-conf)]
(log/tracef "saving classifer %s as %s"
(type (:classifier model)) name)
(let [context (if context-fn (context-fn))
model (if context
(assoc model :context context)
model)]
(cl/write-model name model))
model)))
(defn read-model
"Read a model that was previously persisted to the file system.
See [[zensols.model.classifier/model-dir]] for where the model is read from."
[]
(cl/read-model (model-persist-name)))
(defn evaluations-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(evaluations-file "classification"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.xls" (:name model-conf) fname)))))
(defn eval-and-write-results
"Perform a cross validation and write the results to an Excel formatted file.
The data from **results** is obtained with [[run-tests]].
See [[eval-and-write]] and [[*throw-cross-validate*]]."
([results]
(eval-and-write-results results (evaluations-file)))
([results output-file]
(let [model-conf (model-config)]
(cl/excel-results
[{:sheet-name (format "%s Classification" (s/capitalize (:name model-conf)))
:results results}]
output-file)
(log/infof "wrote results file: %s" output-file)
output-file)))
(defn eval-and-write
"Perform a cross validation and write the results to an Excel formatted file.
See [[zensols.model.classifier/analysis-report-resource]] for where the file is
written.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
This uses [[eval-and-write-results]] to actually write the results.
See [[evaluations-file]] and [[*throw-cross-validate*]]."
([classifier-sets set-key]
(eval-and-write-results (run-tests classifier-sets set-key)))
([classifier-sets set-key file]
(eval-and-write-results (run-tests classifier-sets set-key) file)))
(defn train-test-series
"Test and train with different rations and return the results. The return
data is writable directly as an Excel file. However, you can also save it as
a CSV with [[write-csv-train-test-series]].
The keys are the classifier name and the values are the 2D result matrix.
See [[*throw-cross-validate*]]."
[classifiers meta-set divide-ratio-config]
(let [{:keys [start stop step]} divide-ratio-config
{:keys [divide-by-set]} (model-config)
stat-keys [:instances-trained :instances-tested
:wfmeasure :wprecision :wrecall]
stat-header ["Train" "Test" "F-Measure" "Precision" "Recall"]]
(->> classifiers
(map (fn [classifier]
(->> (range (* start 100) (* stop 100) (* step 100))
(map #(/ % 100))
(map (fn [divide-ratio]
(log/infof "dividing train/test split by %.3f"
divide-ratio)
(divide-by-set divide-ratio)
(binding [*default-set-type* :train-test]
(compile-results (list classifier) meta-set))))
(apply concat)
(map (fn [{:keys [instances-trained instances-tested] :as res}]
(log/infof "trained: %d, tested: %d" instances-trained instances-tested)
(let [name (-> res :classifier cl/classifier-name)]
{:name name
:stats (map #(get res %) stat-keys)})))
(#(hash-map (-> % first :name)
(->> (map :stats %)
(cons stat-header)))))))
(apply merge))))
(defn test-train-series-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(test-train-series-file "train-test-series"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.csv"
(:name model-conf) fname)))))
(defn write-csv-train-test-series
"Write the results produced with [[train-test-series]] as a CSV file to the
analysis directory."
([res]
(write-csv-train-test-series res (test-train-series-file)))
([res out-file]
(->> res
(map (fn [[classifier-name data]]
(with-open [writer (io/writer out-file)]
(csv/write-csv writer data))))
doall)))
;; two pass
(defn two-pass-model
"Don't use this function--instead, use [[with-two-pass]].
Create a two pass model, which should be merged with the model created
with [[zensols.model.execute-classifier/with-model-conf]].
See [[with-two-pass]]."
[model id-key anon-by-id-fn anons-fn]
(let [id-key (-> id-key name symbol)]
(->> model
:feature-sets-set
(map (fn [[k v]]
{k (map #(cons id-key %) v)}))
(apply merge)
(hash-map :two-pass-config
{:anon-by-id-fn anon-by-id-fn
:anons-fn anons-fn
:id-key id-key}
:feature-sets-set)
(merge model))))
(defn- two-pass-config
"Assert and return the two pass configuration."
[& {:keys [nothrow?]}]
(let [conf (:two-pass-config (model-config))]
(if conf
conf
(if-not nothrow?
(-> "No two pass model found--use `two-pass-model`"
(ex-info {:model-config (model-config)})
throw)))))
(defn executing-two-pass?
"Return `true` if we're currently using a two pass cross validation."
[]
(let [tpconf (two-pass-config :nothrow? true)]
(not (nil? tpconf))))
(defn cross-fold-info
"Return information about the current fold for two-pass validations.
See [[weka/*cross-fold-info*]]"
[]
weka/*cross-fold-info*)
(defn- anon-ids-for-instance
"Return IDs as integers found in a `core.weka.Instances`."
[insts id-attrib]
(->> (range (.numInstances insts))
(map (fn [row]
(-> insts
(.instance row)
(.stringValue id-attrib))))))
(defn two-pass-train-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts state org folds fold]
(log/infof "training set: %d, org=%d"
(.numInstances insts)
(.numInstances org))
(let [{:keys [create-two-pass-context-fn create-feature-sets-fn]} (model-config)
_ (assert create-feature-sets-fn)
tpconf (two-pass-config)
_ (assert tpconf)
{:keys [id-key anons-fn]} tpconf
_ (assert id-key)
_ (assert anons-fn)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
_ (assert id-attrib (format "weka attribute for <%s>" id-key-att-name))
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "training %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "anon-ids: %d instances" (count anon-ids))
_ (log/debugf "maybe invoking create context with: %s"
create-two-pass-context-fn)
_ (log/tracef "ids: <%s>" (s/join ", " anon-ids))
context (if create-two-pass-context-fn
(create-two-pass-context-fn :anons-fn anons-fn
:id-set anon-ids))
feature-metas (if context
(exc/model-classifier-feature-types context)
exc/model-classifier-feature-types)
data-maps (create-feature-sets-fn :ids anon-ids :context context)]
(swap! state assoc
:context context
:feature-metas feature-metas)
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defn two-pass-test-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts train-state org folds fold]
(log/debugf "testing set: %d" (.numInstances insts))
(let [{:keys [context feature-metas]} @train-state
{:keys [create-features-fn]} (model-config)
{:keys [id-key anons-fn anon-by-id-fn]} (two-pass-config)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "testing %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "testing instances for ids: <%s>" (s/join ", " anon-ids))
data-maps (->> anon-ids
(map (fn [id]
(log/debugf "creating features for id: %s" id)
(let [anon (anon-by-id-fn id)]
(or anon
(-> (format "No annotation in DB: %d (%s)"
id (type id))
(ex-info {:id id})
throw)))))
(map #(create-features-fn % context)))]
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defmacro with-two-pass
"Like `with-model-conf`, but compute a context state (i.e. statistics needed
by the model) on a per fold when executing a cross fold validation.
The `model-conf` parameter is the same model used
with [[zensols.model.execute-classifier/with-model-conf]].
## Description
Two pass validation is a term used in this library. During cross-validation
the entire data set is evaluated and (usually) statistics or some other
additional modeling happens.
Take for example you want to count words (think Naive Bays spam filter). If
create features for the entire dataset before cross-validation you're
\"cheating\" because the features are based on data not seen from the test
folds.
To get more accurate performance metrics you can provide functions that takes
the current training fold, compute your word counts and create your features.
During the testing phase, the computed data is provided to create features
based on only that (current) fold.
To use two pass validation ever feature set needs a unique key (not needed as
a feature). This key is then given to a function during validation to get
the corresponding feature set that is to be *stitched* in.
**Note** This is *only* useful if:
1. You want to use cross fold validation to test your model.
2. Your model priors (*context* in implementation parlance) is composed of
the dataset preproessing, and thus, needed to get reliable performance
metrics.
## Option Keys
In addition to all keys documented
in [[zensols.model.execute-classifier/with-model-conf]], the **opts** param
is a map that also needs the following key/value pairs:
* **:id-key** a function that takes a key as input and returns a feature set
* **:anon-by-id-fn** is a function that takes a single integer argument of the
annotation to retrieve by ID
* **:anons-fn** is a function that retrieves all annotations
* **:create-two-pass-context-fn** like `:create-context-fn`, as documented
in [[zensols.model.execute-classifier/with-model-conf]] but called for two
pass cross validation; this allows a more general context and a specific two
pass context to be created for the unique needs of the model.
## Example
```
(with-two-pass (create-model-config)
{:id-key sf/id-key
:anon-by-id-fn #(->> % adb/anon-by-id :instance)
:anons-fn adb/anons}
(with-feature-context (sf/create-context :anons-fn adb/anons
:set-type :train-test)
(ec/terse-results [:j48] :set-test-two-pass :only-stats? true)))
```
See a [working example](https://github.com/plandes/clj-example-nlp-ml/blob/master/src/clojure/zensols/example/sa_tp_eval.clj)
for a more comprehensive code listing."
{:style/indent 2}
[model-conf opts & forms]
`(let [opts# (eval ~opts)]
(if-not (eval opts#)
(exc/with-model-conf ~model-conf
~@forms)
(let [id-key# (:id-key opts#)
anon-by-id-fn# (:anon-by-id-fn opts#)
anons-fn# (:anons-fn opts#)
model-conf# (two-pass-model ~model-conf id-key#
anon-by-id-fn# anons-fn#)]
(binding [weka/*missing-values-ok* true
cl/*cross-val-fns* {:train-fn two-pass-train-instances
:test-fn two-pass-test-instances}]
(exc/with-model-conf model-conf#
~@forms))))))
| 64157 | (ns ^{:doc
"A *client* entry point library to help with evaluating machine learning
models. This library not only wraps the Weka library but also provides
additional functionality like a two pass cross
validation (see [[with-two-pass]])."
:author "<NAME>"}
zensols.model.eval-classifier
(:require [clojure.tools.logging :as log]
[clojure.java.io :as io :refer [input-stream output-stream file]]
[clojure.string :as s]
[clojure.stacktrace :refer (print-stack-trace)]
[clojure.data.csv :as csv])
(:require [zensols.tabres.display-results :as dr])
(:require [zensols.model.execute-classifier :refer (model-config) :as exc]
[zensols.model.weka :as weka]
[zensols.model.classifier :as cl]))
(def ^:dynamic *default-set-type*
"The default type of test, which is one of:
* `:cross-validation`: run a N fold cross validation (default)
* `:train-test`: train the classifier and then evaluate"
:cross-validation)
(def ^:dynamic *throw-cross-validate*
"If `true`, throw an exception during cross validation for any errors.
Otherwise, the error is logged and cross-validation continues. This is
useful for when classifiers are used and some choke given the dataset, but
you still want the other results."
false)
(defn- by-set-type-instances [set-type]
(case set-type
:cross-validation (exc/cross-fold-instances)
:train-test (:train-test (exc/train-test-instances))
:test (:test (exc/train-test-instances))
:train (:train (exc/train-test-instances))
true (throw (ex-info "Unknon set type"
{:set-type *default-set-type*}))))
(defn print-model-config
"Pretty print the model configuation set
with [[zensols.model.execute-classifier/with-model-conf]]."
[]
(clojure.pprint/pprint (model-config)))
(defn analysis-file
([]
(analysis-file "%s-data.arff"))
([file-format]
(let [model-conf (model-config)
file-name (format file-format (:name model-conf))]
(io/file (cl/analysis-report-resource) file-name))))
(defn read-arff
"Read the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(read-arff (analysis-file)))
([file]
(cl/read-arff file)))
(defn write-arff
"Write the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(write-arff (analysis-file)))
([file]
(binding [cl/*arff-file* file]
(cl/write-arff (by-set-type-instances :train-test)))
file))
(defn- feature-matrix
"Generate a matrix of features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]]."
[& {:keys [max] :as adb-keys
:or {max Integer/MAX_VALUE}}]
(let [{:keys [feature-metas-fn display-feature-metas-fn
class-feature-meta-fn create-feature-sets-fn]} (model-config)
display-feature-metas-fn (or display-feature-metas-fn feature-metas-fn)
feature-metas (display-feature-metas-fn)
class-feature-meta (class-feature-meta-fn)
adb-keys (if adb-keys
(->> (dissoc adb-keys :max)
(into [])
(apply concat)))
feature-sets (->> (apply create-feature-sets-fn adb-keys)
(take max))]
(let [keys (map first (concat (list class-feature-meta) feature-metas))]
(->> feature-sets
(map (fn [tok]
(map (fn [tkey]
(get tok tkey))
keys)))
(hash-map :column-names (map name keys) :data)))))
(defn display-features
"Display features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]].
**adb-keys** are given to `:create-feature-sets-fn` as described
in [[zensols.model.execute-classifier/with-model-conf]]. In addition it
includes `:max`, which is the maximum number of instances to display."
[& adb-keys]
(let [{:keys [column-names data]} (apply feature-matrix adb-keys)]
(dr/display-results data :column-names column-names)))
(defn features-file
"Return the default file used to create the features output file
with [[write-features]]."
[]
(analysis-file "%s-features.csv"))
(defn write-features
"Write features as configured in a model with [[zensols.model.execute-classifier/with-model-conf]] to a CSV
spreadsheet file.
See [[features-file]] for the default file
For the non-zero-arg form, see [[zensols.model.execute-classifier/with-model-conf]]."
([]
(write-features (features-file)))
([file]
(let [{:keys [column-names data]} (feature-matrix)]
(with-open [writer (io/writer file)]
(->> data
(cons column-names)
(csv/write-csv writer)))
(log/infof "wrote features file: %s" file)
file)))
(defn- cross-validate-results-struct
"Create a data structure with cross validation results."
[classifiers attribs-sets feature-metadata]
(log/debugf "cvr struct classifiers=<%s>, attribs=%s"
(pr-str classifiers) (pr-str attribs-sets))
(letfn [(cr-test [classifier attribs]
(try
(log/infof "classifier: <%s>, %s" classifier (pr-str attribs))
(let [res (cl/cross-validate-tests classifier (map name attribs)
feature-metadata)]
(log/debug (with-out-str (cl/print-results res)))
res)
(catch Exception e
(if *throw-cross-validate*
(do
(log/error e "couldn not cross validate")
(throw e))
(let [msg (format "Can't cross validate classifier %s, attrib: %s: message=%s"
classifier (if attribs (s/join "," attribs))
(.toString e))]
(log/error (str "stack trace: " (print-stack-trace e)))
(log/error e msg)
nil)))))]
(->> classifiers
(map (fn [classifier]
(keep #(cr-test classifier %) attribs-sets)))
(remove empty?)
(apply concat))))
(defn- freeze-feature-metadata [model-conf]
(let [{:keys [feature-metas-fn class-feature-meta-fn]} model-conf
class-feat (class-feature-meta-fn)]
{:feature-metas (into {} (feature-metas-fn))
:class-key (first class-feat)
:class-type (second class-feat)}))
(declare two-pass-config)
(declare executing-two-pass?)
(defn- cross-validate-results
"Cross validate several models in series.
* **classifier-sets** is a key in [[zensols.model.weka/*classifier*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-sets-key]
(log/debugf "cvr struct attrib key=%s" feature-sets-key)
(let [model-conf (model-config)]
(log/debugf "model config keys: %s" (keys model-conf))
(let [classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
instances (exc/cross-fold-instances)
num-inst (.numInstances instances)
folds cl/*cross-fold-count*]
(log/debugf "number of instances: %d, feature-meta-set: <%s>, attribs: %s"
num-inst (pr-str feature-meta-sets)
(->> (weka/attributes-for-instances instances)
(map :name)
pr-str))
(log/tracef "instances class: %s" (-> instances .getClass .getName))
(if-let [id-val (if (and (executing-two-pass?)
(> (.numInstances instances) 0))
(->> (two-pass-config)
:id-key
name
(weka/value instances 0)))]
(if (= "?" id-val)
(-> (format "Key not set yet for two pass cross validation: %s"
(.instance instances 0))
(ex-info {:instance (.instance instances 0)})
throw)))
(if (<= num-inst folds)
(throw (ex-info "Not enough folds"
{:num-inst num-inst
:folds folds}))
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map #(cross-validate-results-struct
(weka/make-classifiers %)
feature-meta-sets
feature-metadata))
(apply concat)
doall))))))
(defn train-test-results
"Test the performance of a model by training on a given set of data
and evaluate on the test data.
See [[train-model]] for parameter details."
[classifier-sets feature-sets-key]
(log/debugf "feature-sets-key=%s, classifier-sets=%s"
feature-sets-key classifier-sets)
(let [model-conf (model-config)
_ (log/debugf "model config keys: %s" (keys model-conf))
classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (log/debugf "feature meta sets: <%s>"
(pr-str feature-meta-sets))
{train-instances :train test-instances :test}
(exc/train-test-instances)]
(assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
(assert train-instances "train-instances")
(assert test-instances "test-instances")
(log/infof "number of train/test instances:(%d, %d)"
(.numInstances train-instances)
(.numInstances test-instances))
(log/debugf "feature metas: %s " (pr-str feature-meta-sets))
(log/tracef "train instances class: %s"
(-> train-instances .getClass .getName))
(log/tracef "test instances class: %s"
(-> test-instances .getClass .getName))
(binding [cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map weka/make-classifiers)
(apply concat)
(map #(cl/train-test-classifier % feature-meta-sets
feature-metadata
train-instances test-instances))
(apply concat)
doall))))
(defn run-tests
"Create result sets useful to functions like [[eval-and-write]]. This
package was designed for most use cases to not have to use this function.
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [test-fn (case *default-set-type*
:cross-validation cross-validate-results
:train-test train-test-results)
res (test-fn classifier-sets feature-set-key)]
(log/debugf "results count %d" (count res))
res))
(defn compile-results
"Run cross-fold validation and compile into a nice results map sorted by
performance.
See [[zensols.model.classifier/compile-results]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-set-key]
(->> (run-tests classifier-sets feature-set-key)
cl/compile-results))
(defn terse-results
"Return terse cross-validation results in an array:
* classifier name
* weighted F-measure
* feature-metas
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
## Keys
* **:only-stats?** if `true` only return statistic data
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key &
{:keys [only-stats?]
:or {only-stats? true}}]
(let [res (compile-results classifier-sets feature-set-key)]
(log/debugf "terse results count %d" (count res))
(map (fn [elt]
(concat [(cl/classifier-name (:classifier elt))
(:wfmeasure elt)]
(if-not only-stats?
[feature-set-key
(:attributes elt)])))
res)))
(defn print-best-results
"Print the highest (best) scored cross validation information.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [comp-res (compile-results classifier-sets feature-set-key)]
(cl/print-results (:result (first comp-res)))))
(defn create-model
"Create a model that can be trained. This runs cross fold validations to
find the best classifier and feature set into a result that can be used
with [[train-model]] and subsequently [[write-model]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(-> (compile-results classifier-sets feature-set-key)
first
(dissoc :result :all-results)
(merge {:name (:name (model-config))
:create-time (java.util.Date.)})))
(defn train-model
"Train a model created from [[create-model]]. The model is trained on the
full available dataset. After the classifier is trained, you can save it to
disk by calling [[write-model]].
* **model** a model that was created with [[create-model]]
See [[*throw-cross-validate*]]."
[model & {:keys [set-type] :or {set-type *default-set-type*}}]
(let [classifier (:classifier model)
attribs (map name (:attributes model))
classify-attrib (first (exc/model-classifier-label))
instances (by-set-type-instances set-type)]
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classify-attrib)]
(log/infof "training model %s classifier %s with %d instances"
(:name (model-config))
(-> classifier .getClass .getName)
(.numInstances instances))
(cl/train-classifier classifier attribs)
model)))
(defn- model-persist-name
"Return the name of the model of the model configuration."
[]
(:name (model-config)))
(defn write-model
"Persist/write the model to disk.
* **model** a model that was trained with [[train-model]]
See [[zensols.model.classifier/model-dir]] for information about to where the
model is written."
([model]
(write-model model (model-persist-name)))
([model name]
(let [model-conf (model-config)
context-fn (:context-fn model-conf)]
(log/tracef "saving classifer %s as %s"
(type (:classifier model)) name)
(let [context (if context-fn (context-fn))
model (if context
(assoc model :context context)
model)]
(cl/write-model name model))
model)))
(defn read-model
"Read a model that was previously persisted to the file system.
See [[zensols.model.classifier/model-dir]] for where the model is read from."
[]
(cl/read-model (model-persist-name)))
(defn evaluations-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(evaluations-file "classification"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.xls" (:name model-conf) fname)))))
(defn eval-and-write-results
"Perform a cross validation and write the results to an Excel formatted file.
The data from **results** is obtained with [[run-tests]].
See [[eval-and-write]] and [[*throw-cross-validate*]]."
([results]
(eval-and-write-results results (evaluations-file)))
([results output-file]
(let [model-conf (model-config)]
(cl/excel-results
[{:sheet-name (format "%s Classification" (s/capitalize (:name model-conf)))
:results results}]
output-file)
(log/infof "wrote results file: %s" output-file)
output-file)))
(defn eval-and-write
"Perform a cross validation and write the results to an Excel formatted file.
See [[zensols.model.classifier/analysis-report-resource]] for where the file is
written.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
This uses [[eval-and-write-results]] to actually write the results.
See [[evaluations-file]] and [[*throw-cross-validate*]]."
([classifier-sets set-key]
(eval-and-write-results (run-tests classifier-sets set-key)))
([classifier-sets set-key file]
(eval-and-write-results (run-tests classifier-sets set-key) file)))
(defn train-test-series
"Test and train with different rations and return the results. The return
data is writable directly as an Excel file. However, you can also save it as
a CSV with [[write-csv-train-test-series]].
The keys are the classifier name and the values are the 2D result matrix.
See [[*throw-cross-validate*]]."
[classifiers meta-set divide-ratio-config]
(let [{:keys [start stop step]} divide-ratio-config
{:keys [divide-by-set]} (model-config)
stat-keys [:instances-trained :instances-tested
:wfmeasure :wprecision :wrecall]
stat-header ["Train" "Test" "F-Measure" "Precision" "Recall"]]
(->> classifiers
(map (fn [classifier]
(->> (range (* start 100) (* stop 100) (* step 100))
(map #(/ % 100))
(map (fn [divide-ratio]
(log/infof "dividing train/test split by %.3f"
divide-ratio)
(divide-by-set divide-ratio)
(binding [*default-set-type* :train-test]
(compile-results (list classifier) meta-set))))
(apply concat)
(map (fn [{:keys [instances-trained instances-tested] :as res}]
(log/infof "trained: %d, tested: %d" instances-trained instances-tested)
(let [name (-> res :classifier cl/classifier-name)]
{:name name
:stats (map #(get res %) stat-keys)})))
(#(hash-map (-> % first :name)
(->> (map :stats %)
(cons stat-header)))))))
(apply merge))))
(defn test-train-series-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(test-train-series-file "train-test-series"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.csv"
(:name model-conf) fname)))))
(defn write-csv-train-test-series
"Write the results produced with [[train-test-series]] as a CSV file to the
analysis directory."
([res]
(write-csv-train-test-series res (test-train-series-file)))
([res out-file]
(->> res
(map (fn [[classifier-name data]]
(with-open [writer (io/writer out-file)]
(csv/write-csv writer data))))
doall)))
;; two pass
(defn two-pass-model
"Don't use this function--instead, use [[with-two-pass]].
Create a two pass model, which should be merged with the model created
with [[zensols.model.execute-classifier/with-model-conf]].
See [[with-two-pass]]."
[model id-key anon-by-id-fn anons-fn]
(let [id-key (-> id-key name symbol)]
(->> model
:feature-sets-set
(map (fn [[k v]]
{k (map #(cons id-key %) v)}))
(apply merge)
(hash-map :two-pass-config
{:anon-by-id-fn anon-by-id-fn
:anons-fn anons-fn
:id-key id-key}
:feature-sets-set)
(merge model))))
(defn- two-pass-config
"Assert and return the two pass configuration."
[& {:keys [nothrow?]}]
(let [conf (:two-pass-config (model-config))]
(if conf
conf
(if-not nothrow?
(-> "No two pass model found--use `two-pass-model`"
(ex-info {:model-config (model-config)})
throw)))))
(defn executing-two-pass?
"Return `true` if we're currently using a two pass cross validation."
[]
(let [tpconf (two-pass-config :nothrow? true)]
(not (nil? tpconf))))
(defn cross-fold-info
"Return information about the current fold for two-pass validations.
See [[weka/*cross-fold-info*]]"
[]
weka/*cross-fold-info*)
(defn- anon-ids-for-instance
"Return IDs as integers found in a `core.weka.Instances`."
[insts id-attrib]
(->> (range (.numInstances insts))
(map (fn [row]
(-> insts
(.instance row)
(.stringValue id-attrib))))))
(defn two-pass-train-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts state org folds fold]
(log/infof "training set: %d, org=%d"
(.numInstances insts)
(.numInstances org))
(let [{:keys [create-two-pass-context-fn create-feature-sets-fn]} (model-config)
_ (assert create-feature-sets-fn)
tpconf (two-pass-config)
_ (assert tpconf)
{:keys [id-key anons-fn]} tpconf
_ (assert id-key)
_ (assert anons-fn)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
_ (assert id-attrib (format "weka attribute for <%s>" id-key-att-name))
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "training %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "anon-ids: %d instances" (count anon-ids))
_ (log/debugf "maybe invoking create context with: %s"
create-two-pass-context-fn)
_ (log/tracef "ids: <%s>" (s/join ", " anon-ids))
context (if create-two-pass-context-fn
(create-two-pass-context-fn :anons-fn anons-fn
:id-set anon-ids))
feature-metas (if context
(exc/model-classifier-feature-types context)
exc/model-classifier-feature-types)
data-maps (create-feature-sets-fn :ids anon-ids :context context)]
(swap! state assoc
:context context
:feature-metas feature-metas)
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defn two-pass-test-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts train-state org folds fold]
(log/debugf "testing set: %d" (.numInstances insts))
(let [{:keys [context feature-metas]} @train-state
{:keys [create-features-fn]} (model-config)
{:keys [id-key anons-fn anon-by-id-fn]} (two-pass-config)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "testing %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "testing instances for ids: <%s>" (s/join ", " anon-ids))
data-maps (->> anon-ids
(map (fn [id]
(log/debugf "creating features for id: %s" id)
(let [anon (anon-by-id-fn id)]
(or anon
(-> (format "No annotation in DB: %d (%s)"
id (type id))
(ex-info {:id id})
throw)))))
(map #(create-features-fn % context)))]
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defmacro with-two-pass
"Like `with-model-conf`, but compute a context state (i.e. statistics needed
by the model) on a per fold when executing a cross fold validation.
The `model-conf` parameter is the same model used
with [[zensols.model.execute-classifier/with-model-conf]].
## Description
Two pass validation is a term used in this library. During cross-validation
the entire data set is evaluated and (usually) statistics or some other
additional modeling happens.
Take for example you want to count words (think Naive Bays spam filter). If
create features for the entire dataset before cross-validation you're
\"cheating\" because the features are based on data not seen from the test
folds.
To get more accurate performance metrics you can provide functions that takes
the current training fold, compute your word counts and create your features.
During the testing phase, the computed data is provided to create features
based on only that (current) fold.
To use two pass validation ever feature set needs a unique key (not needed as
a feature). This key is then given to a function during validation to get
the corresponding feature set that is to be *stitched* in.
**Note** This is *only* useful if:
1. You want to use cross fold validation to test your model.
2. Your model priors (*context* in implementation parlance) is composed of
the dataset preproessing, and thus, needed to get reliable performance
metrics.
## Option Keys
In addition to all keys documented
in [[zensols.model.execute-classifier/with-model-conf]], the **opts** param
is a map that also needs the following key/value pairs:
* **:id-key** a function that takes a key as input and returns a feature set
* **:anon-by-id-fn** is a function that takes a single integer argument of the
annotation to retrieve by ID
* **:anons-fn** is a function that retrieves all annotations
* **:create-two-pass-context-fn** like `:create-context-fn`, as documented
in [[zensols.model.execute-classifier/with-model-conf]] but called for two
pass cross validation; this allows a more general context and a specific two
pass context to be created for the unique needs of the model.
## Example
```
(with-two-pass (create-model-config)
{:id-key sf/id-key
:anon-by-id-fn #(->> % adb/anon-by-id :instance)
:anons-fn adb/anons}
(with-feature-context (sf/create-context :anons-fn adb/anons
:set-type :train-test)
(ec/terse-results [:j48] :set-test-two-pass :only-stats? true)))
```
See a [working example](https://github.com/plandes/clj-example-nlp-ml/blob/master/src/clojure/zensols/example/sa_tp_eval.clj)
for a more comprehensive code listing."
{:style/indent 2}
[model-conf opts & forms]
`(let [opts# (eval ~opts)]
(if-not (eval opts#)
(exc/with-model-conf ~model-conf
~@forms)
(let [id-key# (:id-key opts#)
anon-by-id-fn# (:anon-by-id-fn opts#)
anons-fn# (:anons-fn opts#)
model-conf# (two-pass-model ~model-conf id-key#
anon-by-id-fn# anons-fn#)]
(binding [weka/*missing-values-ok* true
cl/*cross-val-fns* {:train-fn two-pass-train-instances
:test-fn two-pass-test-instances}]
(exc/with-model-conf model-conf#
~@forms))))))
| true | (ns ^{:doc
"A *client* entry point library to help with evaluating machine learning
models. This library not only wraps the Weka library but also provides
additional functionality like a two pass cross
validation (see [[with-two-pass]])."
:author "PI:NAME:<NAME>END_PI"}
zensols.model.eval-classifier
(:require [clojure.tools.logging :as log]
[clojure.java.io :as io :refer [input-stream output-stream file]]
[clojure.string :as s]
[clojure.stacktrace :refer (print-stack-trace)]
[clojure.data.csv :as csv])
(:require [zensols.tabres.display-results :as dr])
(:require [zensols.model.execute-classifier :refer (model-config) :as exc]
[zensols.model.weka :as weka]
[zensols.model.classifier :as cl]))
(def ^:dynamic *default-set-type*
"The default type of test, which is one of:
* `:cross-validation`: run a N fold cross validation (default)
* `:train-test`: train the classifier and then evaluate"
:cross-validation)
(def ^:dynamic *throw-cross-validate*
"If `true`, throw an exception during cross validation for any errors.
Otherwise, the error is logged and cross-validation continues. This is
useful for when classifiers are used and some choke given the dataset, but
you still want the other results."
false)
(defn- by-set-type-instances [set-type]
(case set-type
:cross-validation (exc/cross-fold-instances)
:train-test (:train-test (exc/train-test-instances))
:test (:test (exc/train-test-instances))
:train (:train (exc/train-test-instances))
true (throw (ex-info "Unknon set type"
{:set-type *default-set-type*}))))
(defn print-model-config
"Pretty print the model configuation set
with [[zensols.model.execute-classifier/with-model-conf]]."
[]
(clojure.pprint/pprint (model-config)))
(defn analysis-file
([]
(analysis-file "%s-data.arff"))
([file-format]
(let [model-conf (model-config)
file-name (format file-format (:name model-conf))]
(io/file (cl/analysis-report-resource) file-name))))
(defn read-arff
"Read the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(read-arff (analysis-file)))
([file]
(cl/read-arff file)))
(defn write-arff
"Write the ARFF file configured
with [[zensols.model.execute-classifier/with-model-conf]]. If **file** is
given, use that file instead of getting it
from [[zensols.model.classifier/analysis-report-resource]]."
([]
(write-arff (analysis-file)))
([file]
(binding [cl/*arff-file* file]
(cl/write-arff (by-set-type-instances :train-test)))
file))
(defn- feature-matrix
"Generate a matrix of features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]]."
[& {:keys [max] :as adb-keys
:or {max Integer/MAX_VALUE}}]
(let [{:keys [feature-metas-fn display-feature-metas-fn
class-feature-meta-fn create-feature-sets-fn]} (model-config)
display-feature-metas-fn (or display-feature-metas-fn feature-metas-fn)
feature-metas (display-feature-metas-fn)
class-feature-meta (class-feature-meta-fn)
adb-keys (if adb-keys
(->> (dissoc adb-keys :max)
(into [])
(apply concat)))
feature-sets (->> (apply create-feature-sets-fn adb-keys)
(take max))]
(let [keys (map first (concat (list class-feature-meta) feature-metas))]
(->> feature-sets
(map (fn [tok]
(map (fn [tkey]
(get tok tkey))
keys)))
(hash-map :column-names (map name keys) :data)))))
(defn display-features
"Display features as configured in a model with
[[zensols.model.execute-classifier/with-model-conf]].
**adb-keys** are given to `:create-feature-sets-fn` as described
in [[zensols.model.execute-classifier/with-model-conf]]. In addition it
includes `:max`, which is the maximum number of instances to display."
[& adb-keys]
(let [{:keys [column-names data]} (apply feature-matrix adb-keys)]
(dr/display-results data :column-names column-names)))
(defn features-file
"Return the default file used to create the features output file
with [[write-features]]."
[]
(analysis-file "%s-features.csv"))
(defn write-features
"Write features as configured in a model with [[zensols.model.execute-classifier/with-model-conf]] to a CSV
spreadsheet file.
See [[features-file]] for the default file
For the non-zero-arg form, see [[zensols.model.execute-classifier/with-model-conf]]."
([]
(write-features (features-file)))
([file]
(let [{:keys [column-names data]} (feature-matrix)]
(with-open [writer (io/writer file)]
(->> data
(cons column-names)
(csv/write-csv writer)))
(log/infof "wrote features file: %s" file)
file)))
(defn- cross-validate-results-struct
"Create a data structure with cross validation results."
[classifiers attribs-sets feature-metadata]
(log/debugf "cvr struct classifiers=<%s>, attribs=%s"
(pr-str classifiers) (pr-str attribs-sets))
(letfn [(cr-test [classifier attribs]
(try
(log/infof "classifier: <%s>, %s" classifier (pr-str attribs))
(let [res (cl/cross-validate-tests classifier (map name attribs)
feature-metadata)]
(log/debug (with-out-str (cl/print-results res)))
res)
(catch Exception e
(if *throw-cross-validate*
(do
(log/error e "couldn not cross validate")
(throw e))
(let [msg (format "Can't cross validate classifier %s, attrib: %s: message=%s"
classifier (if attribs (s/join "," attribs))
(.toString e))]
(log/error (str "stack trace: " (print-stack-trace e)))
(log/error e msg)
nil)))))]
(->> classifiers
(map (fn [classifier]
(keep #(cr-test classifier %) attribs-sets)))
(remove empty?)
(apply concat))))
(defn- freeze-feature-metadata [model-conf]
(let [{:keys [feature-metas-fn class-feature-meta-fn]} model-conf
class-feat (class-feature-meta-fn)]
{:feature-metas (into {} (feature-metas-fn))
:class-key (first class-feat)
:class-type (second class-feat)}))
(declare two-pass-config)
(declare executing-two-pass?)
(defn- cross-validate-results
"Cross validate several models in series.
* **classifier-sets** is a key in [[zensols.model.weka/*classifier*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-sets-key]
(log/debugf "cvr struct attrib key=%s" feature-sets-key)
(let [model-conf (model-config)]
(log/debugf "model config keys: %s" (keys model-conf))
(let [classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
instances (exc/cross-fold-instances)
num-inst (.numInstances instances)
folds cl/*cross-fold-count*]
(log/debugf "number of instances: %d, feature-meta-set: <%s>, attribs: %s"
num-inst (pr-str feature-meta-sets)
(->> (weka/attributes-for-instances instances)
(map :name)
pr-str))
(log/tracef "instances class: %s" (-> instances .getClass .getName))
(if-let [id-val (if (and (executing-two-pass?)
(> (.numInstances instances) 0))
(->> (two-pass-config)
:id-key
name
(weka/value instances 0)))]
(if (= "?" id-val)
(-> (format "Key not set yet for two pass cross validation: %s"
(.instance instances 0))
(ex-info {:instance (.instance instances 0)})
throw)))
(if (<= num-inst folds)
(throw (ex-info "Not enough folds"
{:num-inst num-inst
:folds folds}))
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map #(cross-validate-results-struct
(weka/make-classifiers %)
feature-meta-sets
feature-metadata))
(apply concat)
doall))))))
(defn train-test-results
"Test the performance of a model by training on a given set of data
and evaluate on the test data.
See [[train-model]] for parameter details."
[classifier-sets feature-sets-key]
(log/debugf "feature-sets-key=%s, classifier-sets=%s"
feature-sets-key classifier-sets)
(let [model-conf (model-config)
_ (log/debugf "model config keys: %s" (keys model-conf))
classifier-attrib (first (exc/model-classifier-label))
feature-meta-sets (get (:feature-sets-set model-conf)
feature-sets-key)
feature-metadata (freeze-feature-metadata model-conf)
_ (log/debugf "feature meta sets: <%s>"
(pr-str feature-meta-sets))
{train-instances :train test-instances :test}
(exc/train-test-instances)]
(assert feature-meta-sets (format "no such feature meta set: <%s>"
feature-sets-key))
(assert train-instances "train-instances")
(assert test-instances "test-instances")
(log/infof "number of train/test instances:(%d, %d)"
(.numInstances train-instances)
(.numInstances test-instances))
(log/debugf "feature metas: %s " (pr-str feature-meta-sets))
(log/tracef "train instances class: %s"
(-> train-instances .getClass .getName))
(log/tracef "test instances class: %s"
(-> test-instances .getClass .getName))
(binding [cl/*class-feature-meta* (name classifier-attrib)]
(->> classifier-sets
(map weka/make-classifiers)
(apply concat)
(map #(cl/train-test-classifier % feature-meta-sets
feature-metadata
train-instances test-instances))
(apply concat)
doall))))
(defn run-tests
"Create result sets useful to functions like [[eval-and-write]]. This
package was designed for most use cases to not have to use this function.
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [test-fn (case *default-set-type*
:cross-validation cross-validate-results
:train-test train-test-results)
res (test-fn classifier-sets feature-set-key)]
(log/debugf "results count %d" (count res))
res))
(defn compile-results
"Run cross-fold validation and compile into a nice results map sorted by
performance.
See [[zensols.model.classifier/compile-results]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])"
[classifier-sets feature-set-key]
(->> (run-tests classifier-sets feature-set-key)
cl/compile-results))
(defn terse-results
"Return terse cross-validation results in an array:
* classifier name
* weighted F-measure
* feature-metas
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
## Keys
* **:only-stats?** if `true` only return statistic data
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key &
{:keys [only-stats?]
:or {only-stats? true}}]
(let [res (compile-results classifier-sets feature-set-key)]
(log/debugf "terse results count %d" (count res))
(map (fn [elt]
(concat [(cl/classifier-name (:classifier elt))
(:wfmeasure elt)]
(if-not only-stats?
[feature-set-key
(:attributes elt)])))
res)))
(defn print-best-results
"Print the highest (best) scored cross validation information.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(let [comp-res (compile-results classifier-sets feature-set-key)]
(cl/print-results (:result (first comp-res)))))
(defn create-model
"Create a model that can be trained. This runs cross fold validations to
find the best classifier and feature set into a result that can be used
with [[train-model]] and subsequently [[write-model]].
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
See [[*throw-cross-validate*]]."
[classifier-sets feature-set-key]
(-> (compile-results classifier-sets feature-set-key)
first
(dissoc :result :all-results)
(merge {:name (:name (model-config))
:create-time (java.util.Date.)})))
(defn train-model
"Train a model created from [[create-model]]. The model is trained on the
full available dataset. After the classifier is trained, you can save it to
disk by calling [[write-model]].
* **model** a model that was created with [[create-model]]
See [[*throw-cross-validate*]]."
[model & {:keys [set-type] :or {set-type *default-set-type*}}]
(let [classifier (:classifier model)
attribs (map name (:attributes model))
classify-attrib (first (exc/model-classifier-label))
instances (by-set-type-instances set-type)]
(binding [cl/*get-data-fn* #(identity instances)
cl/*class-feature-meta* (name classify-attrib)]
(log/infof "training model %s classifier %s with %d instances"
(:name (model-config))
(-> classifier .getClass .getName)
(.numInstances instances))
(cl/train-classifier classifier attribs)
model)))
(defn- model-persist-name
"Return the name of the model of the model configuration."
[]
(:name (model-config)))
(defn write-model
"Persist/write the model to disk.
* **model** a model that was trained with [[train-model]]
See [[zensols.model.classifier/model-dir]] for information about to where the
model is written."
([model]
(write-model model (model-persist-name)))
([model name]
(let [model-conf (model-config)
context-fn (:context-fn model-conf)]
(log/tracef "saving classifer %s as %s"
(type (:classifier model)) name)
(let [context (if context-fn (context-fn))
model (if context
(assoc model :context context)
model)]
(cl/write-model name model))
model)))
(defn read-model
"Read a model that was previously persisted to the file system.
See [[zensols.model.classifier/model-dir]] for where the model is read from."
[]
(cl/read-model (model-persist-name)))
(defn evaluations-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(evaluations-file "classification"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.xls" (:name model-conf) fname)))))
(defn eval-and-write-results
"Perform a cross validation and write the results to an Excel formatted file.
The data from **results** is obtained with [[run-tests]].
See [[eval-and-write]] and [[*throw-cross-validate*]]."
([results]
(eval-and-write-results results (evaluations-file)))
([results output-file]
(let [model-conf (model-config)]
(cl/excel-results
[{:sheet-name (format "%s Classification" (s/capitalize (:name model-conf)))
:results results}]
output-file)
(log/infof "wrote results file: %s" output-file)
output-file)))
(defn eval-and-write
"Perform a cross validation and write the results to an Excel formatted file.
See [[zensols.model.classifier/analysis-report-resource]] for where the file is
written.
* **classifier-sets** is a key in [[zensols.model.weka/*classifiers*]] or a
constructed classifier (see [[zensols.model.weka/make-classifiers]])
* **feature-sets-key** identifies what feature set (see
**:feature-sets-set** in [[zensols.model.execute-classifier/with-model-conf]])
This uses [[eval-and-write-results]] to actually write the results.
See [[evaluations-file]] and [[*throw-cross-validate*]]."
([classifier-sets set-key]
(eval-and-write-results (run-tests classifier-sets set-key)))
([classifier-sets set-key file]
(eval-and-write-results (run-tests classifier-sets set-key) file)))
(defn train-test-series
"Test and train with different rations and return the results. The return
data is writable directly as an Excel file. However, you can also save it as
a CSV with [[write-csv-train-test-series]].
The keys are the classifier name and the values are the 2D result matrix.
See [[*throw-cross-validate*]]."
[classifiers meta-set divide-ratio-config]
(let [{:keys [start stop step]} divide-ratio-config
{:keys [divide-by-set]} (model-config)
stat-keys [:instances-trained :instances-tested
:wfmeasure :wprecision :wrecall]
stat-header ["Train" "Test" "F-Measure" "Precision" "Recall"]]
(->> classifiers
(map (fn [classifier]
(->> (range (* start 100) (* stop 100) (* step 100))
(map #(/ % 100))
(map (fn [divide-ratio]
(log/infof "dividing train/test split by %.3f"
divide-ratio)
(divide-by-set divide-ratio)
(binding [*default-set-type* :train-test]
(compile-results (list classifier) meta-set))))
(apply concat)
(map (fn [{:keys [instances-trained instances-tested] :as res}]
(log/infof "trained: %d, tested: %d" instances-trained instances-tested)
(let [name (-> res :classifier cl/classifier-name)]
{:name name
:stats (map #(get res %) stat-keys)})))
(#(hash-map (-> % first :name)
(->> (map :stats %)
(cons stat-header)))))))
(apply merge))))
(defn test-train-series-file
"Return the default file used to create an evaluations file
with [[eval-and-write]]."
([]
(test-train-series-file "train-test-series"))
([fname]
(let [model-conf (model-config)]
(io/file (cl/analysis-report-resource)
(format "%s-%s.csv"
(:name model-conf) fname)))))
(defn write-csv-train-test-series
"Write the results produced with [[train-test-series]] as a CSV file to the
analysis directory."
([res]
(write-csv-train-test-series res (test-train-series-file)))
([res out-file]
(->> res
(map (fn [[classifier-name data]]
(with-open [writer (io/writer out-file)]
(csv/write-csv writer data))))
doall)))
;; two pass
(defn two-pass-model
"Don't use this function--instead, use [[with-two-pass]].
Create a two pass model, which should be merged with the model created
with [[zensols.model.execute-classifier/with-model-conf]].
See [[with-two-pass]]."
[model id-key anon-by-id-fn anons-fn]
(let [id-key (-> id-key name symbol)]
(->> model
:feature-sets-set
(map (fn [[k v]]
{k (map #(cons id-key %) v)}))
(apply merge)
(hash-map :two-pass-config
{:anon-by-id-fn anon-by-id-fn
:anons-fn anons-fn
:id-key id-key}
:feature-sets-set)
(merge model))))
(defn- two-pass-config
"Assert and return the two pass configuration."
[& {:keys [nothrow?]}]
(let [conf (:two-pass-config (model-config))]
(if conf
conf
(if-not nothrow?
(-> "No two pass model found--use `two-pass-model`"
(ex-info {:model-config (model-config)})
throw)))))
(defn executing-two-pass?
"Return `true` if we're currently using a two pass cross validation."
[]
(let [tpconf (two-pass-config :nothrow? true)]
(not (nil? tpconf))))
(defn cross-fold-info
"Return information about the current fold for two-pass validations.
See [[weka/*cross-fold-info*]]"
[]
weka/*cross-fold-info*)
(defn- anon-ids-for-instance
"Return IDs as integers found in a `core.weka.Instances`."
[insts id-attrib]
(->> (range (.numInstances insts))
(map (fn [row]
(-> insts
(.instance row)
(.stringValue id-attrib))))))
(defn two-pass-train-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts state org folds fold]
(log/infof "training set: %d, org=%d"
(.numInstances insts)
(.numInstances org))
(let [{:keys [create-two-pass-context-fn create-feature-sets-fn]} (model-config)
_ (assert create-feature-sets-fn)
tpconf (two-pass-config)
_ (assert tpconf)
{:keys [id-key anons-fn]} tpconf
_ (assert id-key)
_ (assert anons-fn)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
_ (assert id-attrib (format "weka attribute for <%s>" id-key-att-name))
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "training %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "anon-ids: %d instances" (count anon-ids))
_ (log/debugf "maybe invoking create context with: %s"
create-two-pass-context-fn)
_ (log/tracef "ids: <%s>" (s/join ", " anon-ids))
context (if create-two-pass-context-fn
(create-two-pass-context-fn :anons-fn anons-fn
:id-set anon-ids))
feature-metas (if context
(exc/model-classifier-feature-types context)
exc/model-classifier-feature-types)
data-maps (create-feature-sets-fn :ids anon-ids :context context)]
(swap! state assoc
:context context
:feature-metas feature-metas)
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defn two-pass-test-instances
"Don't use this function--instead, use [[with-two-pass]].
This is called by the [[zensols.model.weka]] namespace."
[insts train-state org folds fold]
(log/debugf "testing set: %d" (.numInstances insts))
(let [{:keys [context feature-metas]} @train-state
{:keys [create-features-fn]} (model-config)
{:keys [id-key anons-fn anon-by-id-fn]} (two-pass-config)
id-key-att-name (name id-key)
id-attrib (weka/attribute-by-name insts id-key-att-name)
anon-ids (anon-ids-for-instance insts id-attrib)
_ (log/infof "testing %d instances for fold %d of %d"
(count anon-ids) (inc fold) folds)
_ (log/debugf "testing instances for ids: <%s>" (s/join ", " anon-ids))
data-maps (->> anon-ids
(map (fn [id]
(log/debugf "creating features for id: %s" id)
(let [anon (anon-by-id-fn id)]
(or anon
(-> (format "No annotation in DB: %d (%s)"
id (type id))
(ex-info {:id id})
throw)))))
(map #(create-features-fn % context)))]
(-> insts
(weka/remove-attributes [id-key-att-name])
(weka/populate-instances feature-metas data-maps))))
(defmacro with-two-pass
"Like `with-model-conf`, but compute a context state (i.e. statistics needed
by the model) on a per fold when executing a cross fold validation.
The `model-conf` parameter is the same model used
with [[zensols.model.execute-classifier/with-model-conf]].
## Description
Two pass validation is a term used in this library. During cross-validation
the entire data set is evaluated and (usually) statistics or some other
additional modeling happens.
Take for example you want to count words (think Naive Bays spam filter). If
create features for the entire dataset before cross-validation you're
\"cheating\" because the features are based on data not seen from the test
folds.
To get more accurate performance metrics you can provide functions that takes
the current training fold, compute your word counts and create your features.
During the testing phase, the computed data is provided to create features
based on only that (current) fold.
To use two pass validation ever feature set needs a unique key (not needed as
a feature). This key is then given to a function during validation to get
the corresponding feature set that is to be *stitched* in.
**Note** This is *only* useful if:
1. You want to use cross fold validation to test your model.
2. Your model priors (*context* in implementation parlance) is composed of
the dataset preproessing, and thus, needed to get reliable performance
metrics.
## Option Keys
In addition to all keys documented
in [[zensols.model.execute-classifier/with-model-conf]], the **opts** param
is a map that also needs the following key/value pairs:
* **:id-key** a function that takes a key as input and returns a feature set
* **:anon-by-id-fn** is a function that takes a single integer argument of the
annotation to retrieve by ID
* **:anons-fn** is a function that retrieves all annotations
* **:create-two-pass-context-fn** like `:create-context-fn`, as documented
in [[zensols.model.execute-classifier/with-model-conf]] but called for two
pass cross validation; this allows a more general context and a specific two
pass context to be created for the unique needs of the model.
## Example
```
(with-two-pass (create-model-config)
{:id-key sf/id-key
:anon-by-id-fn #(->> % adb/anon-by-id :instance)
:anons-fn adb/anons}
(with-feature-context (sf/create-context :anons-fn adb/anons
:set-type :train-test)
(ec/terse-results [:j48] :set-test-two-pass :only-stats? true)))
```
See a [working example](https://github.com/plandes/clj-example-nlp-ml/blob/master/src/clojure/zensols/example/sa_tp_eval.clj)
for a more comprehensive code listing."
{:style/indent 2}
[model-conf opts & forms]
`(let [opts# (eval ~opts)]
(if-not (eval opts#)
(exc/with-model-conf ~model-conf
~@forms)
(let [id-key# (:id-key opts#)
anon-by-id-fn# (:anon-by-id-fn opts#)
anons-fn# (:anons-fn opts#)
model-conf# (two-pass-model ~model-conf id-key#
anon-by-id-fn# anons-fn#)]
(binding [weka/*missing-values-ok* true
cl/*cross-val-fns* {:train-fn two-pass-train-instances
:test-fn two-pass-test-instances}]
(exc/with-model-conf model-conf#
~@forms))))))
|
[
{
"context": " :user \"us&r\"\n :password \"p&ssw@rd\"\n :database \"database\"}]\n (w",
"end": 347,
"score": 0.9993882775306702,
"start": 339,
"tag": "PASSWORD",
"value": "p&ssw@rd"
}
] | test/vip/data_processor/db/postgres_test.clj | votinginfoproject/data-processor | 10 | (ns vip.data-processor.db.postgres-test
(:require [vip.data-processor.db.postgres :refer :all]
[turbovote.resource-config :refer [config]]
[clojure.test :refer :all]))
(deftest url-test
(let [db-spec-1 {:host "host"
:port "5678"
:user "us&r"
:password "p&ssw@rd"
:database "database"}]
(with-redefs [config (constantly db-spec-1)]
(is (= "jdbc:postgresql://host:5678/database?user=us%26r&password=p%26ssw%40rd"
(url))
"Percent encoding is done for username and password values"))))
(deftest build-public-id-test
(testing "builds public ids with as much information as it has"
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id nil "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" nil "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" nil 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" nil nil 4)))
(is (= "federal-4" (build-public-id nil "federal" nil 4)))
(is (= "Ohio-4" (build-public-id nil nil "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" "" "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" "" 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" "" "" 4)))
(is (= "federal-4" (build-public-id "" "federal" "" 4)))
(is (= "Ohio-4" (build-public-id "" "" "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "6/18/2015" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "//////" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal " "Ohio " 4))))
(testing "gives an 'invalid' named id if all of date, election-type and state are nil"
(is (= "invalid-4" (build-public-id nil nil nil 4)))
(is (= "invalid-4" (build-public-id "" nil "" 4))))
(testing "most punctuation and any non-ascii characters are stripped"
(is (= "1969-06-20-a-space-race-pal-11" (build-public-id "6/20/1969" "a space" "race, pal!" 11)))
(is (= "2017-01-05-jalapenos-42" (build-public-id "1/5/2017" "jalapeños" nil 42)))))
(deftest coerce-identifier-test
(testing "coerces valid identifiers"
(is (= global-identifier (coerce-identifier :global)))
(is (= (BigDecimal. 4) (coerce-identifier "4")))
(is (= 5 (coerce-identifier 5)))
(is (nil? (coerce-identifier nil))))
(testing "uses the invalid-identifier when given an invalid identifier"
(is (= invalid-identifier (coerce-identifier :garbage)))
(is (= invalid-identifier (coerce-identifier '(a list))))
(is (= invalid-identifier (coerce-identifier "ABC")))))
(deftest election-id-test
(testing "election-id generation"
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA" "GENERAL")))
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA " "GENERAL")))
(is (nil? (build-election-id "2015-10-10" "LOUISIANA" nil)))
(is (nil? (build-election-id "2015-10-10" "" "GENERAL")))))
(deftest v5-summary-branch-test
(let [v3-ctx {:pipeline []
:spec-version "3.0"
:spec-family "3.0"}
v5-ctx {:pipeline []
:spec-version "5.1.2"
:spec-family "5.2"}
v3-out-ctx (v5-summary-branch v3-ctx)
v5-out-ctx (v5-summary-branch v5-ctx)]
(is (= (count (v3-out-ctx :pipeline)) 0))
(is (= (count (v5-out-ctx :pipeline)) 4))))
| 86270 | (ns vip.data-processor.db.postgres-test
(:require [vip.data-processor.db.postgres :refer :all]
[turbovote.resource-config :refer [config]]
[clojure.test :refer :all]))
(deftest url-test
(let [db-spec-1 {:host "host"
:port "5678"
:user "us&r"
:password "<PASSWORD>"
:database "database"}]
(with-redefs [config (constantly db-spec-1)]
(is (= "jdbc:postgresql://host:5678/database?user=us%26r&password=p%26ssw%40rd"
(url))
"Percent encoding is done for username and password values"))))
(deftest build-public-id-test
(testing "builds public ids with as much information as it has"
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id nil "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" nil "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" nil 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" nil nil 4)))
(is (= "federal-4" (build-public-id nil "federal" nil 4)))
(is (= "Ohio-4" (build-public-id nil nil "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" "" "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" "" 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" "" "" 4)))
(is (= "federal-4" (build-public-id "" "federal" "" 4)))
(is (= "Ohio-4" (build-public-id "" "" "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "6/18/2015" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "//////" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal " "Ohio " 4))))
(testing "gives an 'invalid' named id if all of date, election-type and state are nil"
(is (= "invalid-4" (build-public-id nil nil nil 4)))
(is (= "invalid-4" (build-public-id "" nil "" 4))))
(testing "most punctuation and any non-ascii characters are stripped"
(is (= "1969-06-20-a-space-race-pal-11" (build-public-id "6/20/1969" "a space" "race, pal!" 11)))
(is (= "2017-01-05-jalapenos-42" (build-public-id "1/5/2017" "jalapeños" nil 42)))))
(deftest coerce-identifier-test
(testing "coerces valid identifiers"
(is (= global-identifier (coerce-identifier :global)))
(is (= (BigDecimal. 4) (coerce-identifier "4")))
(is (= 5 (coerce-identifier 5)))
(is (nil? (coerce-identifier nil))))
(testing "uses the invalid-identifier when given an invalid identifier"
(is (= invalid-identifier (coerce-identifier :garbage)))
(is (= invalid-identifier (coerce-identifier '(a list))))
(is (= invalid-identifier (coerce-identifier "ABC")))))
(deftest election-id-test
(testing "election-id generation"
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA" "GENERAL")))
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA " "GENERAL")))
(is (nil? (build-election-id "2015-10-10" "LOUISIANA" nil)))
(is (nil? (build-election-id "2015-10-10" "" "GENERAL")))))
(deftest v5-summary-branch-test
(let [v3-ctx {:pipeline []
:spec-version "3.0"
:spec-family "3.0"}
v5-ctx {:pipeline []
:spec-version "5.1.2"
:spec-family "5.2"}
v3-out-ctx (v5-summary-branch v3-ctx)
v5-out-ctx (v5-summary-branch v5-ctx)]
(is (= (count (v3-out-ctx :pipeline)) 0))
(is (= (count (v5-out-ctx :pipeline)) 4))))
| true | (ns vip.data-processor.db.postgres-test
(:require [vip.data-processor.db.postgres :refer :all]
[turbovote.resource-config :refer [config]]
[clojure.test :refer :all]))
(deftest url-test
(let [db-spec-1 {:host "host"
:port "5678"
:user "us&r"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:database "database"}]
(with-redefs [config (constantly db-spec-1)]
(is (= "jdbc:postgresql://host:5678/database?user=us%26r&password=p%26ssw%40rd"
(url))
"Percent encoding is done for username and password values"))))
(deftest build-public-id-test
(testing "builds public ids with as much information as it has"
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id nil "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" nil "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" nil 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" nil nil 4)))
(is (= "federal-4" (build-public-id nil "federal" nil 4)))
(is (= "Ohio-4" (build-public-id nil nil "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "2015-06-18" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal" "Ohio" 4)))
(is (= "2015-06-18-Ohio-4" (build-public-id "2015-06-18" "" "Ohio" 4)))
(is (= "2015-06-18-federal-4" (build-public-id "2015-06-18" "federal" "" 4)))
(is (= "2015-06-18-4" (build-public-id "2015-06-18" "" "" 4)))
(is (= "federal-4" (build-public-id "" "federal" "" 4)))
(is (= "Ohio-4" (build-public-id "" "" "Ohio" 4)))
(is (= "2015-06-18-federal-Ohio-4" (build-public-id "6/18/2015" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "//////" "federal" "Ohio" 4)))
(is (= "federal-Ohio-4" (build-public-id "" "federal " "Ohio " 4))))
(testing "gives an 'invalid' named id if all of date, election-type and state are nil"
(is (= "invalid-4" (build-public-id nil nil nil 4)))
(is (= "invalid-4" (build-public-id "" nil "" 4))))
(testing "most punctuation and any non-ascii characters are stripped"
(is (= "1969-06-20-a-space-race-pal-11" (build-public-id "6/20/1969" "a space" "race, pal!" 11)))
(is (= "2017-01-05-jalapenos-42" (build-public-id "1/5/2017" "jalapeños" nil 42)))))
(deftest coerce-identifier-test
(testing "coerces valid identifiers"
(is (= global-identifier (coerce-identifier :global)))
(is (= (BigDecimal. 4) (coerce-identifier "4")))
(is (= 5 (coerce-identifier 5)))
(is (nil? (coerce-identifier nil))))
(testing "uses the invalid-identifier when given an invalid identifier"
(is (= invalid-identifier (coerce-identifier :garbage)))
(is (= invalid-identifier (coerce-identifier '(a list))))
(is (= invalid-identifier (coerce-identifier "ABC")))))
(deftest election-id-test
(testing "election-id generation"
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA" "GENERAL")))
(is (= "2015-10-10-LOUISIANA-GENERAL"
(build-election-id "2015-10-10" "LOUISIANA " "GENERAL")))
(is (nil? (build-election-id "2015-10-10" "LOUISIANA" nil)))
(is (nil? (build-election-id "2015-10-10" "" "GENERAL")))))
(deftest v5-summary-branch-test
(let [v3-ctx {:pipeline []
:spec-version "3.0"
:spec-family "3.0"}
v5-ctx {:pipeline []
:spec-version "5.1.2"
:spec-family "5.2"}
v3-out-ctx (v5-summary-branch v3-ctx)
v5-out-ctx (v5-summary-branch v5-ctx)]
(is (= (count (v3-out-ctx :pipeline)) 0))
(is (= (count (v5-out-ctx :pipeline)) 4))))
|
[
{
"context": "Lat1 [10 5 foo] ; => 1\n;isLat [] ; => 1\n;isLat [Jack [Sprat] could eat no chicken fat] ; => 0\n;isLat ",
"end": 8447,
"score": 0.9853264093399048,
"start": 8443,
"tag": "NAME",
"value": "Jack"
},
{
"context": "Sprat] could eat no chicken fat] ; => 0\n;isLat [[Jack] Sprat could eat no chicken fat] ; => 0\n;isLat [",
"end": 8503,
"score": 0.9402377009391785,
"start": 8499,
"tag": "NAME",
"value": "Jack"
},
{
"context": "] Sprat could eat no chicken fat] ; => 0\n;isLat [Jack Sprat could eat no chicken fat] ; => 1\n\n;def isL",
"end": 8557,
"score": 0.953024685382843,
"start": 8553,
"tag": "NAME",
"value": "Jack"
}
] | src/TLS.clj | berndblasius/Bracket.jl | 1 | ; Functions from The Little Schemer ...
; ... and translation to Bracket
; *************************************************
; subst: substitute all occurrences
;substar orange' banana' [ [brandy banana]
; [bread]
; [sherbet [[banana] cream] [[ice banana]]]]
; => [[brandy orange] [bread] [sherbet [[orange] cream] [[ice orange]]]]
def substar' \[new old l] ; --- Bracket ---
[eval if isNull l` [[]]
[eval if isAtom car l'
[eval if eq car l' old`
[cons new` substar new` old` cdr l']
[cons car l' substar new` old` cdr l'] ]
[cons substar new` old` car l'
substar new` old` cdr l']]]
;(define subst* ; --- Scheme ---
; (lambda (new old l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l))
; (cond
; ((eq? (car l) old)
; (cons new
; (subst* new old (cdr l))))
; (else (cons (car l)
; (subst* new old
; (cdr l))))))
; (else
; (cons (subst* new old (car l))
; (subst* new old (cdr l)))))))
; *************************************************
; remberStar: remove all occurrences of atom from list
;remberStar sauce' [[sauce [[flying] and]]
; [sauce [bean]]
; [[sauce tomato]]]
; => [[[[flying] and]] [[bean]] [[tomato]]]
;def remberStar' \[a l] ; --- Bracket ---
; [eval if isNull l` [[]]
; [eval if isAtom car l'
; [eval if eq car l' a`
; [remberStar a` cdr l']
; [cons car l' remberStar a` cdr l']]
; [cons remberStar a` car l' remberStar a` cdr l']]]
;(define rember* ; --- Scheme ---
; (lambda (a l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l})
; (cond
; ((eq? (car l) a)
; (rember* a (cdr l)))
; (else (cons (car l)
; (rember* a (cdr l))))))
; (else (cons (rember* a (car l})
; (rember* a (cdr l)))))))
; *************************************************
; rempick: remove nth atom from list
;rempick 3 [pie salty meringue lemon] ; => [pie meringue lemon]
def rempick' \[n lat] ; --- Bracket ---
[eval if isone n [cdr lat']
[cons car lat' rempick sub1 n cdr lat']]
def isone' \[n] [eq n 1]
;(define one? ; --- Scheme ---
; (lambda (n)
; (= n 1)))
;
;(define rempick
; (lambda (n lat) ; --- Scheme ---
; (cond
; ((one? n) (cdr lat))
; (else (cons (car lat)
; (rempick (sub1 n)
; (cdr lat)))))))
; *************************************************
; eqan: check if two atoms are the same arguments
;(define eqan?
; (lambda (a1 a2)
; (cond
; ((and (number? a1 ) (number? a2))
; (= a1 a2))
; ((or (number? a1 ) (number? a2)) #f)
; (else (eq? a1 a2)))))
; *************************************************
; length
;length [rye on cheese and ham]
;def length' \[lat] ; --- Bracket ---
; [eval if isNull lat` [0]
; [add1 length cdr lat']]
;(define length ; --- Scheme ---
; (lambda (lat)
; (cond
; ((null? lat) 0)
; (else (add1 (length (cdr lat)))))))
; *************************************************
; tupplus
;tupplus [7 3] [1 8 6 4] ; => [1 8 13 7]
;def tupplus' \[tup1 tup2] ; --- Bracket ---
; [eval if isNull tup1` [tup2`]
; [eval if isNull tup2` [tup1`]
; [cons myplus car tup1' car tup2'
; tupplus cdr tup1' cdr tup2']]]
;(define tupplus ; --- Scheme ---
; (lambda (tup1 tup2)
; (cond
; ((null? tup1) tup2)
; ((null? tup2) tup1) (else
; (cons (myplus (car tup1) (car tup2))
; (tupplus
; (cdr tup1) (cdr tup2)))))))
; *************************************************
; mymult
;mymult 12 3 ; => 36
;def mymult' \[n m] ;; --- Bracket ---
; [eval if isZero m [0]
; [myplus n mymult n sub1 m]]
;(define mymult ;; --- Scheme --
; (lambda (n m)
; (cond
; ((zeroP m) 0)
; (else (myplus n (mymult n (sub1 m)))))))
; *************************************************
; myminus
;myminus 14 3 ; => 11
;def myminus' \[n m] ;; --- Bracket ---
; [eval if isZero m [n]
; [sub1 - n sub1 m]]
;(define myminus ;; --- in Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (sub1 (- n (sub1 m)))))))
; *************************************************
; myplus
;myplus 46 12 ; => 58
def myplus' \[n m] ;; --- Bracket ---
[eval if isZero m [n]
[add1 myplus n sub1 m]]
;(define myplus ;; --- Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (add1 (myplus n (sub1 m)))))))
; *************************************************
; multiple remove atom from list of atoms
;multrember cup' [cup hick and cup tea and cup coffee]
; => [[[hick and tea and coffee]
;def multrember' \[a lat] ; currently symbol names have max 10 characters
; [eval if isNull lat` [[]]
; [eval if eq car lat' a`
; [multrember a` cdr lat']
; [cons car lat' multrember a`cdr lat']]]
;(define multirember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) a)
; (multirember a (cdr lat)))
; (else (cons (car lat)
; (multirember a
; (cdr lat)))))))))
; *************************************************
; insert new at first occurrence of old in list of atoms
;insertR topping' fudge' [desert for fudge with creame ice]
; => [desert for topping fudge with creame ice]
;insertR a' b' [d b c] ;=> [d a b c]
;def insertR' \[new old lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' old`
; [cons old`cons new` cdr lat']
; [cons car lat' insertR new` old` cdr lat']]]
;(define insertR ;; --- in Scheme ---
; (lambda (new old lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) old)
; (cons old
; (cons new (cdr lat))))
; (else (cons (car lat)
; (insertR new old (cdr lat)))))))))
; *************************************************
; list of first elements of a list
;firsts [[[five plums] four] [eleven green oranges] [no [more]]] ; => [four oranges [more]]
; firsts [] ; => []
;firsts [[a b] [c d] [e f]] ; => [b d f]
;def firsts' \[l] ;; --- in Bracket ---
; [eval if isNull l` [[]]
; [cons car car l' firsts cdr l']]
;(define firsts ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) . . .)
; (else (cons (car (car l))
; (firsts (cdr l)))))))
; *************************************************
; remove a member from list
;rember cup' [coffee cup tea cup and hick cup] ; => [coffee cup tea cup and hick]
;rember toast' [bacon lettuce and tomato] ; => [bacon lettuce and tomato]
;rember mint' [lamb chops and mint flavored mint jelly] ; => [lamb chops and mint flavored jelly]
; remember first element is jelly
;rember mint' [lamb chops and mint jelly] ; => [lamb chops and jelly
;rember and' [bacon lettuce and tomato] ; => [bacon lettuce tomato]
;def rember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' a` [cdr lat']
; [cons car lat' rember a` cdr lat']]]
; (define rember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; ((eq? (car lat) a) (cdr lat))
; (else (cons (car lat)
; (rember a (cdr lat)))))))
; *************************************************
;isMember1 poached' [fried eggs and scrambled eggs] ; => 0
;isMember1 tea' [coffee tea or milk] ; => 1
;def isMember1' \[a lat] ;; --- in Bracket (a bit shorter) ---
; [eval if isNull lat` [0]
; [or isMember1 a` swap eq a` car lat`]]
;def isMember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [0]
; [or eq car lat' a`
; isMember a` cdr lat']]
;define member? ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) #f)
; (else (or (eq? (car lat) a)
; (member? a (cdr lat)))))))
; *************************************************
; is list of atoms
;isLat1 [10 5 foo] ; => 1
;isLat [] ; => 1
;isLat [Jack [Sprat] could eat no chicken fat] ; => 0
;isLat [[Jack] Sprat could eat no chicken fat] ; => 0
;isLat [Jack Sprat could eat no chicken fat] ; => 1
;def isLat' \[l] ;; --- in Bracket ---
; [eval if isNull l` [1]
; [eval if isAtom car l' [isLat cdr l'] [0]]]
;(define lat? ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) #t)
; ((atom? (car l)) (lat? (cdr l)))
; (else #f))))
; *************************************************
def sub1' \[n]
[- n 1]
def add1' \[n]
[+ n 1]
def isNull'
[not]
def isZero'
[eq 0]
def isAtom'
[not isList]
def isList'
[or eq [] swap or eq 4 typ swap eq 5 typ dup dup] | 87903 | ; Functions from The Little Schemer ...
; ... and translation to Bracket
; *************************************************
; subst: substitute all occurrences
;substar orange' banana' [ [brandy banana]
; [bread]
; [sherbet [[banana] cream] [[ice banana]]]]
; => [[brandy orange] [bread] [sherbet [[orange] cream] [[ice orange]]]]
def substar' \[new old l] ; --- Bracket ---
[eval if isNull l` [[]]
[eval if isAtom car l'
[eval if eq car l' old`
[cons new` substar new` old` cdr l']
[cons car l' substar new` old` cdr l'] ]
[cons substar new` old` car l'
substar new` old` cdr l']]]
;(define subst* ; --- Scheme ---
; (lambda (new old l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l))
; (cond
; ((eq? (car l) old)
; (cons new
; (subst* new old (cdr l))))
; (else (cons (car l)
; (subst* new old
; (cdr l))))))
; (else
; (cons (subst* new old (car l))
; (subst* new old (cdr l)))))))
; *************************************************
; remberStar: remove all occurrences of atom from list
;remberStar sauce' [[sauce [[flying] and]]
; [sauce [bean]]
; [[sauce tomato]]]
; => [[[[flying] and]] [[bean]] [[tomato]]]
;def remberStar' \[a l] ; --- Bracket ---
; [eval if isNull l` [[]]
; [eval if isAtom car l'
; [eval if eq car l' a`
; [remberStar a` cdr l']
; [cons car l' remberStar a` cdr l']]
; [cons remberStar a` car l' remberStar a` cdr l']]]
;(define rember* ; --- Scheme ---
; (lambda (a l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l})
; (cond
; ((eq? (car l) a)
; (rember* a (cdr l)))
; (else (cons (car l)
; (rember* a (cdr l))))))
; (else (cons (rember* a (car l})
; (rember* a (cdr l)))))))
; *************************************************
; rempick: remove nth atom from list
;rempick 3 [pie salty meringue lemon] ; => [pie meringue lemon]
def rempick' \[n lat] ; --- Bracket ---
[eval if isone n [cdr lat']
[cons car lat' rempick sub1 n cdr lat']]
def isone' \[n] [eq n 1]
;(define one? ; --- Scheme ---
; (lambda (n)
; (= n 1)))
;
;(define rempick
; (lambda (n lat) ; --- Scheme ---
; (cond
; ((one? n) (cdr lat))
; (else (cons (car lat)
; (rempick (sub1 n)
; (cdr lat)))))))
; *************************************************
; eqan: check if two atoms are the same arguments
;(define eqan?
; (lambda (a1 a2)
; (cond
; ((and (number? a1 ) (number? a2))
; (= a1 a2))
; ((or (number? a1 ) (number? a2)) #f)
; (else (eq? a1 a2)))))
; *************************************************
; length
;length [rye on cheese and ham]
;def length' \[lat] ; --- Bracket ---
; [eval if isNull lat` [0]
; [add1 length cdr lat']]
;(define length ; --- Scheme ---
; (lambda (lat)
; (cond
; ((null? lat) 0)
; (else (add1 (length (cdr lat)))))))
; *************************************************
; tupplus
;tupplus [7 3] [1 8 6 4] ; => [1 8 13 7]
;def tupplus' \[tup1 tup2] ; --- Bracket ---
; [eval if isNull tup1` [tup2`]
; [eval if isNull tup2` [tup1`]
; [cons myplus car tup1' car tup2'
; tupplus cdr tup1' cdr tup2']]]
;(define tupplus ; --- Scheme ---
; (lambda (tup1 tup2)
; (cond
; ((null? tup1) tup2)
; ((null? tup2) tup1) (else
; (cons (myplus (car tup1) (car tup2))
; (tupplus
; (cdr tup1) (cdr tup2)))))))
; *************************************************
; mymult
;mymult 12 3 ; => 36
;def mymult' \[n m] ;; --- Bracket ---
; [eval if isZero m [0]
; [myplus n mymult n sub1 m]]
;(define mymult ;; --- Scheme --
; (lambda (n m)
; (cond
; ((zeroP m) 0)
; (else (myplus n (mymult n (sub1 m)))))))
; *************************************************
; myminus
;myminus 14 3 ; => 11
;def myminus' \[n m] ;; --- Bracket ---
; [eval if isZero m [n]
; [sub1 - n sub1 m]]
;(define myminus ;; --- in Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (sub1 (- n (sub1 m)))))))
; *************************************************
; myplus
;myplus 46 12 ; => 58
def myplus' \[n m] ;; --- Bracket ---
[eval if isZero m [n]
[add1 myplus n sub1 m]]
;(define myplus ;; --- Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (add1 (myplus n (sub1 m)))))))
; *************************************************
; multiple remove atom from list of atoms
;multrember cup' [cup hick and cup tea and cup coffee]
; => [[[hick and tea and coffee]
;def multrember' \[a lat] ; currently symbol names have max 10 characters
; [eval if isNull lat` [[]]
; [eval if eq car lat' a`
; [multrember a` cdr lat']
; [cons car lat' multrember a`cdr lat']]]
;(define multirember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) a)
; (multirember a (cdr lat)))
; (else (cons (car lat)
; (multirember a
; (cdr lat)))))))))
; *************************************************
; insert new at first occurrence of old in list of atoms
;insertR topping' fudge' [desert for fudge with creame ice]
; => [desert for topping fudge with creame ice]
;insertR a' b' [d b c] ;=> [d a b c]
;def insertR' \[new old lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' old`
; [cons old`cons new` cdr lat']
; [cons car lat' insertR new` old` cdr lat']]]
;(define insertR ;; --- in Scheme ---
; (lambda (new old lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) old)
; (cons old
; (cons new (cdr lat))))
; (else (cons (car lat)
; (insertR new old (cdr lat)))))))))
; *************************************************
; list of first elements of a list
;firsts [[[five plums] four] [eleven green oranges] [no [more]]] ; => [four oranges [more]]
; firsts [] ; => []
;firsts [[a b] [c d] [e f]] ; => [b d f]
;def firsts' \[l] ;; --- in Bracket ---
; [eval if isNull l` [[]]
; [cons car car l' firsts cdr l']]
;(define firsts ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) . . .)
; (else (cons (car (car l))
; (firsts (cdr l)))))))
; *************************************************
; remove a member from list
;rember cup' [coffee cup tea cup and hick cup] ; => [coffee cup tea cup and hick]
;rember toast' [bacon lettuce and tomato] ; => [bacon lettuce and tomato]
;rember mint' [lamb chops and mint flavored mint jelly] ; => [lamb chops and mint flavored jelly]
; remember first element is jelly
;rember mint' [lamb chops and mint jelly] ; => [lamb chops and jelly
;rember and' [bacon lettuce and tomato] ; => [bacon lettuce tomato]
;def rember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' a` [cdr lat']
; [cons car lat' rember a` cdr lat']]]
; (define rember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; ((eq? (car lat) a) (cdr lat))
; (else (cons (car lat)
; (rember a (cdr lat)))))))
; *************************************************
;isMember1 poached' [fried eggs and scrambled eggs] ; => 0
;isMember1 tea' [coffee tea or milk] ; => 1
;def isMember1' \[a lat] ;; --- in Bracket (a bit shorter) ---
; [eval if isNull lat` [0]
; [or isMember1 a` swap eq a` car lat`]]
;def isMember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [0]
; [or eq car lat' a`
; isMember a` cdr lat']]
;define member? ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) #f)
; (else (or (eq? (car lat) a)
; (member? a (cdr lat)))))))
; *************************************************
; is list of atoms
;isLat1 [10 5 foo] ; => 1
;isLat [] ; => 1
;isLat [<NAME> [Sprat] could eat no chicken fat] ; => 0
;isLat [[<NAME>] Sprat could eat no chicken fat] ; => 0
;isLat [<NAME> Sprat could eat no chicken fat] ; => 1
;def isLat' \[l] ;; --- in Bracket ---
; [eval if isNull l` [1]
; [eval if isAtom car l' [isLat cdr l'] [0]]]
;(define lat? ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) #t)
; ((atom? (car l)) (lat? (cdr l)))
; (else #f))))
; *************************************************
def sub1' \[n]
[- n 1]
def add1' \[n]
[+ n 1]
def isNull'
[not]
def isZero'
[eq 0]
def isAtom'
[not isList]
def isList'
[or eq [] swap or eq 4 typ swap eq 5 typ dup dup] | true | ; Functions from The Little Schemer ...
; ... and translation to Bracket
; *************************************************
; subst: substitute all occurrences
;substar orange' banana' [ [brandy banana]
; [bread]
; [sherbet [[banana] cream] [[ice banana]]]]
; => [[brandy orange] [bread] [sherbet [[orange] cream] [[ice orange]]]]
def substar' \[new old l] ; --- Bracket ---
[eval if isNull l` [[]]
[eval if isAtom car l'
[eval if eq car l' old`
[cons new` substar new` old` cdr l']
[cons car l' substar new` old` cdr l'] ]
[cons substar new` old` car l'
substar new` old` cdr l']]]
;(define subst* ; --- Scheme ---
; (lambda (new old l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l))
; (cond
; ((eq? (car l) old)
; (cons new
; (subst* new old (cdr l))))
; (else (cons (car l)
; (subst* new old
; (cdr l))))))
; (else
; (cons (subst* new old (car l))
; (subst* new old (cdr l)))))))
; *************************************************
; remberStar: remove all occurrences of atom from list
;remberStar sauce' [[sauce [[flying] and]]
; [sauce [bean]]
; [[sauce tomato]]]
; => [[[[flying] and]] [[bean]] [[tomato]]]
;def remberStar' \[a l] ; --- Bracket ---
; [eval if isNull l` [[]]
; [eval if isAtom car l'
; [eval if eq car l' a`
; [remberStar a` cdr l']
; [cons car l' remberStar a` cdr l']]
; [cons remberStar a` car l' remberStar a` cdr l']]]
;(define rember* ; --- Scheme ---
; (lambda (a l)
; (cond
; ((null? l) (quote ()))
; ((atom? (car l})
; (cond
; ((eq? (car l) a)
; (rember* a (cdr l)))
; (else (cons (car l)
; (rember* a (cdr l))))))
; (else (cons (rember* a (car l})
; (rember* a (cdr l)))))))
; *************************************************
; rempick: remove nth atom from list
;rempick 3 [pie salty meringue lemon] ; => [pie meringue lemon]
def rempick' \[n lat] ; --- Bracket ---
[eval if isone n [cdr lat']
[cons car lat' rempick sub1 n cdr lat']]
def isone' \[n] [eq n 1]
;(define one? ; --- Scheme ---
; (lambda (n)
; (= n 1)))
;
;(define rempick
; (lambda (n lat) ; --- Scheme ---
; (cond
; ((one? n) (cdr lat))
; (else (cons (car lat)
; (rempick (sub1 n)
; (cdr lat)))))))
; *************************************************
; eqan: check if two atoms are the same arguments
;(define eqan?
; (lambda (a1 a2)
; (cond
; ((and (number? a1 ) (number? a2))
; (= a1 a2))
; ((or (number? a1 ) (number? a2)) #f)
; (else (eq? a1 a2)))))
; *************************************************
; length
;length [rye on cheese and ham]
;def length' \[lat] ; --- Bracket ---
; [eval if isNull lat` [0]
; [add1 length cdr lat']]
;(define length ; --- Scheme ---
; (lambda (lat)
; (cond
; ((null? lat) 0)
; (else (add1 (length (cdr lat)))))))
; *************************************************
; tupplus
;tupplus [7 3] [1 8 6 4] ; => [1 8 13 7]
;def tupplus' \[tup1 tup2] ; --- Bracket ---
; [eval if isNull tup1` [tup2`]
; [eval if isNull tup2` [tup1`]
; [cons myplus car tup1' car tup2'
; tupplus cdr tup1' cdr tup2']]]
;(define tupplus ; --- Scheme ---
; (lambda (tup1 tup2)
; (cond
; ((null? tup1) tup2)
; ((null? tup2) tup1) (else
; (cons (myplus (car tup1) (car tup2))
; (tupplus
; (cdr tup1) (cdr tup2)))))))
; *************************************************
; mymult
;mymult 12 3 ; => 36
;def mymult' \[n m] ;; --- Bracket ---
; [eval if isZero m [0]
; [myplus n mymult n sub1 m]]
;(define mymult ;; --- Scheme --
; (lambda (n m)
; (cond
; ((zeroP m) 0)
; (else (myplus n (mymult n (sub1 m)))))))
; *************************************************
; myminus
;myminus 14 3 ; => 11
;def myminus' \[n m] ;; --- Bracket ---
; [eval if isZero m [n]
; [sub1 - n sub1 m]]
;(define myminus ;; --- in Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (sub1 (- n (sub1 m)))))))
; *************************************************
; myplus
;myplus 46 12 ; => 58
def myplus' \[n m] ;; --- Bracket ---
[eval if isZero m [n]
[add1 myplus n sub1 m]]
;(define myplus ;; --- Scheme ---
; (lambda (n m)
; (cond
; ((zero? m) n)
; (else (add1 (myplus n (sub1 m)))))))
; *************************************************
; multiple remove atom from list of atoms
;multrember cup' [cup hick and cup tea and cup coffee]
; => [[[hick and tea and coffee]
;def multrember' \[a lat] ; currently symbol names have max 10 characters
; [eval if isNull lat` [[]]
; [eval if eq car lat' a`
; [multrember a` cdr lat']
; [cons car lat' multrember a`cdr lat']]]
;(define multirember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) a)
; (multirember a (cdr lat)))
; (else (cons (car lat)
; (multirember a
; (cdr lat)))))))))
; *************************************************
; insert new at first occurrence of old in list of atoms
;insertR topping' fudge' [desert for fudge with creame ice]
; => [desert for topping fudge with creame ice]
;insertR a' b' [d b c] ;=> [d a b c]
;def insertR' \[new old lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' old`
; [cons old`cons new` cdr lat']
; [cons car lat' insertR new` old` cdr lat']]]
;(define insertR ;; --- in Scheme ---
; (lambda (new old lat)
; (cond
; ((null? lat) (quote ()))
; (else
; (cond
; ((eq? (car lat) old)
; (cons old
; (cons new (cdr lat))))
; (else (cons (car lat)
; (insertR new old (cdr lat)))))))))
; *************************************************
; list of first elements of a list
;firsts [[[five plums] four] [eleven green oranges] [no [more]]] ; => [four oranges [more]]
; firsts [] ; => []
;firsts [[a b] [c d] [e f]] ; => [b d f]
;def firsts' \[l] ;; --- in Bracket ---
; [eval if isNull l` [[]]
; [cons car car l' firsts cdr l']]
;(define firsts ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) . . .)
; (else (cons (car (car l))
; (firsts (cdr l)))))))
; *************************************************
; remove a member from list
;rember cup' [coffee cup tea cup and hick cup] ; => [coffee cup tea cup and hick]
;rember toast' [bacon lettuce and tomato] ; => [bacon lettuce and tomato]
;rember mint' [lamb chops and mint flavored mint jelly] ; => [lamb chops and mint flavored jelly]
; remember first element is jelly
;rember mint' [lamb chops and mint jelly] ; => [lamb chops and jelly
;rember and' [bacon lettuce and tomato] ; => [bacon lettuce tomato]
;def rember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [[]]
; [eval if eq car lat' a` [cdr lat']
; [cons car lat' rember a` cdr lat']]]
; (define rember ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) (quote ()))
; ((eq? (car lat) a) (cdr lat))
; (else (cons (car lat)
; (rember a (cdr lat)))))))
; *************************************************
;isMember1 poached' [fried eggs and scrambled eggs] ; => 0
;isMember1 tea' [coffee tea or milk] ; => 1
;def isMember1' \[a lat] ;; --- in Bracket (a bit shorter) ---
; [eval if isNull lat` [0]
; [or isMember1 a` swap eq a` car lat`]]
;def isMember' \[a lat] ;; --- in Bracket ---
; [eval if isNull lat` [0]
; [or eq car lat' a`
; isMember a` cdr lat']]
;define member? ;; --- in Scheme ---
; (lambda (a lat)
; (cond
; ((null? lat) #f)
; (else (or (eq? (car lat) a)
; (member? a (cdr lat)))))))
; *************************************************
; is list of atoms
;isLat1 [10 5 foo] ; => 1
;isLat [] ; => 1
;isLat [PI:NAME:<NAME>END_PI [Sprat] could eat no chicken fat] ; => 0
;isLat [[PI:NAME:<NAME>END_PI] Sprat could eat no chicken fat] ; => 0
;isLat [PI:NAME:<NAME>END_PI Sprat could eat no chicken fat] ; => 1
;def isLat' \[l] ;; --- in Bracket ---
; [eval if isNull l` [1]
; [eval if isAtom car l' [isLat cdr l'] [0]]]
;(define lat? ;; --- in Scheme ---
; (lambda (l)
; (cond
; ((null? l) #t)
; ((atom? (car l)) (lat? (cdr l)))
; (else #f))))
; *************************************************
def sub1' \[n]
[- n 1]
def add1' \[n]
[+ n 1]
def isNull'
[not]
def isZero'
[eq 0]
def isAtom'
[not isList]
def isList'
[or eq [] swap or eq 4 typ swap eq 5 typ dup dup] |
[
{
"context": " [:div\n [:div.form-group\n [:label {:for \"username\"} \"User name\"]\n [:input#username.form-control",
"end": 1944,
"score": 0.9992753863334656,
"start": 1936,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username.form-control {:type \"text\" :placeholder \"username\"}]]\n [:div.form-group\n [:label {:for \"pass",
"end": 2031,
"score": 0.9994192123413086,
"start": 2023,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (fn [root]\n (let [user (.-value (dom/by-id \"username\"))\n pass (.-value (dom/by-id \"password\"",
"end": 2251,
"score": 0.9975812435150146,
"start": 2243,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (dom/clear! root))))\n (.focus (dom/by-id \"username\")))\n\n(defn register-dialog\n [bus]\n (modal/modal",
"end": 2399,
"score": 0.6911750435829163,
"start": 2391,
"tag": "USERNAME",
"value": "username"
},
{
"context": "mail\"}]]\n [:div.form-group\n [:label {:for \"username\"} \"User name\"]\n [:input#username.form-control",
"end": 2805,
"score": 0.9984422326087952,
"start": 2797,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username.form-control {:type \"text\" :placeholder \"username\"}]]\n [:div.form-group\n [:label {:for \"pass",
"end": 2892,
"score": 0.9991132616996765,
"start": 2884,
"tag": "USERNAME",
"value": "username"
},
{
"context": "id %)))\n [\"fullname\" \"email\" \"username\" \"pass1\" \"pass2\"])]\n (info :form form)\n ",
"end": 3318,
"score": 0.9816312193870544,
"start": 3310,
"tag": "USERNAME",
"value": "username"
},
{
"context": " [\"fullname\" \"email\" \"username\" \"pass1\" \"pass2\"])]\n (info :form form)\n (hand",
"end": 3326,
"score": 0.9201719760894775,
"start": 3321,
"tag": "PASSWORD",
"value": "pass1"
},
{
"context": " [\"fullname\" \"email\" \"username\" \"pass1\" \"pass2\"])]\n (info :form form)\n (handle-regis",
"end": 3334,
"score": 0.9950253963470459,
"start": 3329,
"tag": "PASSWORD",
"value": "pass2"
}
] | src-cljs/imago/login.cljs | thi-ng/imago | 1 | (ns imago.login
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[imago.config :as config]
[imago.modal :as modal]
[imago.alerts :as alerts]
[thi.ng.domus.async :as async]
[thi.ng.domus.log :refer [debug info warn]]
[thi.ng.domus.io :as io]
[thi.ng.domus.router :as router]
[thi.ng.domus.utils :as utils]
[thi.ng.domus.core :as dom]
[cljs.core.async :refer [<! alts! timeout]]))
(defn handle-register
[bus data]
(io/request
{:uri (config/api-route :register)
:method :put
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :register-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :register-fail (:body body)))}))
(defn handle-login
[bus user pass]
(let [data {:user user :pass pass}]
(io/request
{:uri (config/api-route :login)
:method :post
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :login-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :login-fail (:body body)))})))
(defn handle-logout
[bus]
(io/request
{:uri (config/api-route :logout)
:method :post
:edn? true
:success (fn [status body]
(info :success-response status body)
(async/publish bus :logout-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :logout-fail (:body body)))}))
(defn login-dialog
[bus]
(modal/modal-dialog
"Login"
[:div
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "password"} "Password"]
[:input#password.form-control {:type "password" :placeholder "password"}]]]
"Login"
(fn [root]
(let [user (.-value (dom/by-id "username"))
pass (.-value (dom/by-id "password"))]
(handle-login bus user pass)
(dom/clear! root))))
(.focus (dom/by-id "username")))
(defn register-dialog
[bus]
(modal/modal-dialog
"Register new user"
[:div
[:div.form-group
[:label {:for "name"} "Name"]
[:input#fullname.form-control {:type "text" :placeholder "your name"}]]
[:div.form-group
[:label {:for "email"} "Email"]
[:input#email.form-control {:type "email" :placeholder "your email"}]]
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "pass1"} "Password"]
[:input#pass1.form-control {:type "password" :placeholder "password"}]]
[:div.form-group
[:label {:for "pass2"} "Password (verify)"]
[:input#pass2.form-control {:type "password" :placeholder "password"}]]]
"Register"
(fn [root]
(let [form (map #(vector % (.-value (dom/by-id %)))
["fullname" "email" "username" "pass1" "pass2"])]
(info :form form)
(handle-register bus form)
(dom/clear! root))))
(.focus (dom/by-id "fullname")))
(defn login-watcher
[bus state]
(let [subs (async/subscription-channels
bus [:login-success :login-fail :logout-success :logout-fail])
chans (vec (vals subs))]
(go-loop []
(let [[[_ user] ch] (alts! chans)]
(condp = ch
(:login-success subs) (do
(info :user-logged-in user)
(swap! state assoc :user user)
(router/set-route! "users" (:user-name user)))
(:login-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Login failed!"] " Please try again..."]
(:app-root config/app)))
(:logout-success subs) (do
(info :user-logged-out)
(swap! state assoc :user user)
(router/set-route! "/"))
(:logout-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Logout failed!"] " Please try again..."]
(:app-root config/app))))
(recur)))))
| 110749 | (ns imago.login
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[imago.config :as config]
[imago.modal :as modal]
[imago.alerts :as alerts]
[thi.ng.domus.async :as async]
[thi.ng.domus.log :refer [debug info warn]]
[thi.ng.domus.io :as io]
[thi.ng.domus.router :as router]
[thi.ng.domus.utils :as utils]
[thi.ng.domus.core :as dom]
[cljs.core.async :refer [<! alts! timeout]]))
(defn handle-register
[bus data]
(io/request
{:uri (config/api-route :register)
:method :put
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :register-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :register-fail (:body body)))}))
(defn handle-login
[bus user pass]
(let [data {:user user :pass pass}]
(io/request
{:uri (config/api-route :login)
:method :post
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :login-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :login-fail (:body body)))})))
(defn handle-logout
[bus]
(io/request
{:uri (config/api-route :logout)
:method :post
:edn? true
:success (fn [status body]
(info :success-response status body)
(async/publish bus :logout-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :logout-fail (:body body)))}))
(defn login-dialog
[bus]
(modal/modal-dialog
"Login"
[:div
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "password"} "Password"]
[:input#password.form-control {:type "password" :placeholder "password"}]]]
"Login"
(fn [root]
(let [user (.-value (dom/by-id "username"))
pass (.-value (dom/by-id "password"))]
(handle-login bus user pass)
(dom/clear! root))))
(.focus (dom/by-id "username")))
(defn register-dialog
[bus]
(modal/modal-dialog
"Register new user"
[:div
[:div.form-group
[:label {:for "name"} "Name"]
[:input#fullname.form-control {:type "text" :placeholder "your name"}]]
[:div.form-group
[:label {:for "email"} "Email"]
[:input#email.form-control {:type "email" :placeholder "your email"}]]
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "pass1"} "Password"]
[:input#pass1.form-control {:type "password" :placeholder "password"}]]
[:div.form-group
[:label {:for "pass2"} "Password (verify)"]
[:input#pass2.form-control {:type "password" :placeholder "password"}]]]
"Register"
(fn [root]
(let [form (map #(vector % (.-value (dom/by-id %)))
["fullname" "email" "username" "<PASSWORD>" "<PASSWORD>"])]
(info :form form)
(handle-register bus form)
(dom/clear! root))))
(.focus (dom/by-id "fullname")))
(defn login-watcher
[bus state]
(let [subs (async/subscription-channels
bus [:login-success :login-fail :logout-success :logout-fail])
chans (vec (vals subs))]
(go-loop []
(let [[[_ user] ch] (alts! chans)]
(condp = ch
(:login-success subs) (do
(info :user-logged-in user)
(swap! state assoc :user user)
(router/set-route! "users" (:user-name user)))
(:login-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Login failed!"] " Please try again..."]
(:app-root config/app)))
(:logout-success subs) (do
(info :user-logged-out)
(swap! state assoc :user user)
(router/set-route! "/"))
(:logout-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Logout failed!"] " Please try again..."]
(:app-root config/app))))
(recur)))))
| true | (ns imago.login
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[imago.config :as config]
[imago.modal :as modal]
[imago.alerts :as alerts]
[thi.ng.domus.async :as async]
[thi.ng.domus.log :refer [debug info warn]]
[thi.ng.domus.io :as io]
[thi.ng.domus.router :as router]
[thi.ng.domus.utils :as utils]
[thi.ng.domus.core :as dom]
[cljs.core.async :refer [<! alts! timeout]]))
(defn handle-register
[bus data]
(io/request
{:uri (config/api-route :register)
:method :put
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :register-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :register-fail (:body body)))}))
(defn handle-login
[bus user pass]
(let [data {:user user :pass pass}]
(io/request
{:uri (config/api-route :login)
:method :post
:data (config/inject-api-request-data data)
:success (fn [status body]
(info :success-response status body)
(async/publish bus :login-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :login-fail (:body body)))})))
(defn handle-logout
[bus]
(io/request
{:uri (config/api-route :logout)
:method :post
:edn? true
:success (fn [status body]
(info :success-response status body)
(async/publish bus :logout-success (:body body)))
:error (fn [status body]
(warn :error-response status body)
(async/publish bus :logout-fail (:body body)))}))
(defn login-dialog
[bus]
(modal/modal-dialog
"Login"
[:div
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "password"} "Password"]
[:input#password.form-control {:type "password" :placeholder "password"}]]]
"Login"
(fn [root]
(let [user (.-value (dom/by-id "username"))
pass (.-value (dom/by-id "password"))]
(handle-login bus user pass)
(dom/clear! root))))
(.focus (dom/by-id "username")))
(defn register-dialog
[bus]
(modal/modal-dialog
"Register new user"
[:div
[:div.form-group
[:label {:for "name"} "Name"]
[:input#fullname.form-control {:type "text" :placeholder "your name"}]]
[:div.form-group
[:label {:for "email"} "Email"]
[:input#email.form-control {:type "email" :placeholder "your email"}]]
[:div.form-group
[:label {:for "username"} "User name"]
[:input#username.form-control {:type "text" :placeholder "username"}]]
[:div.form-group
[:label {:for "pass1"} "Password"]
[:input#pass1.form-control {:type "password" :placeholder "password"}]]
[:div.form-group
[:label {:for "pass2"} "Password (verify)"]
[:input#pass2.form-control {:type "password" :placeholder "password"}]]]
"Register"
(fn [root]
(let [form (map #(vector % (.-value (dom/by-id %)))
["fullname" "email" "username" "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI"])]
(info :form form)
(handle-register bus form)
(dom/clear! root))))
(.focus (dom/by-id "fullname")))
(defn login-watcher
[bus state]
(let [subs (async/subscription-channels
bus [:login-success :login-fail :logout-success :logout-fail])
chans (vec (vals subs))]
(go-loop []
(let [[[_ user] ch] (alts! chans)]
(condp = ch
(:login-success subs) (do
(info :user-logged-in user)
(swap! state assoc :user user)
(router/set-route! "users" (:user-name user)))
(:login-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Login failed!"] " Please try again..."]
(:app-root config/app)))
(:logout-success subs) (do
(info :user-logged-out)
(swap! state assoc :user user)
(router/set-route! "/"))
(:logout-fail subs) (do
(alerts/alert
:danger
[:div [:strong "Logout failed!"] " Please try again..."]
(:app-root config/app))))
(recur)))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998192191123962,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | chat-demo/cljs/bc/dom-helpers.cljs | PoshHsu/clj-browserchannel | 10 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns bc.dom-helpers
(:require [clojure.string :as string]
[goog.style :as style]
[goog.dom :as dom]
[goog.dom.classes :as classes]
[goog.dom.forms :as forms]
[goog.fx :as fx]
[goog.fx.dom :as fx-dom]
[goog.Timer :as timer]
))
(defn get-element
"Return the element with the passed id."
[id]
(dom/getElement (name id)))
(defn show-element [e b]
(style/showElement e b))
(defn add-remove-class [e add-classes remove-classes]
(classes/addRemove e remove-classes add-classes))
(defn get-radio-value [form-name name]
(forms/getValueByName (get-element form-name) name))
(defn value [element]
(forms/getValue element))
(defn set-value [element]
(forms/setValue element))
(defn set-disabled [element disabled]
(forms/setDisabled element disabled))
(defn append
"Append all children to parent."
[parent & children]
(do (doseq [child children]
(dom/appendChild parent child))
parent))
(defn set-text
"Set the text content for the passed element returning the
element. If a keyword is passed in the place of e, the element with
that id will be used and returned."
[e s]
(let [e (if (or (keyword? e) (string? e)) (get-element e) e)]
(doto e
(dom/setTextContent s))))
(defn normalize-args [tag args]
(let [parts (string/split tag #"(\.|#)")
[tag attrs] [(first parts)
(apply hash-map (map #(cond (= % ".") :class
(= % "#") :id
:else %)
(rest parts)))]]
(if (map? (first args))
[tag (merge attrs (first args)) (rest args)]
[tag attrs args])))
;; TODO: replace call to .strobj with whatever we come up with for
;; creating js objects from Clojure maps.
(defn element
"Create a dom element using a keyword for the element name and a map
for the attributes. Append all children to parent. If the first
child is a string then the string will be set as the text content of
the parent and all remaining children will be appended."
[tag & args]
(let [[tag attrs children] (normalize-args tag args)
;; keyword/string mangling screws up (name tag)
parent (dom/createDom (subs tag 1)
(. (reduce (fn [m [k v]]
(assoc m k v))
{}
(map #(vector (name %1) %2)
(keys attrs)
(vals attrs))) -strobj))
[parent children] (if (string? (first children))
[(set-text (element tag attrs) (first children))
(rest children)]
[parent children])]
(apply append parent children)))
(defn remove-children
"Remove all children from the element with the passed id."
[parent-el]
(dom/removeChildren parent-el))
(defn html
"Create a dom element from an html string."
[s]
(dom/htmlToDocumentFragment s))
(defn- element-arg? [x]
(or (keyword? x)
(map? x)
(string? x)))
(defn build
"Build up a dom element from nested vectors."
[x]
(if (vector? x)
(let [[parent children] (if (keyword? (first x))
[(apply element (take-while element-arg? x))
(drop-while element-arg? x)]
[(first x) (rest x)])
children (map build children)]
(apply append parent children))
x))
(defn insert-at
"Insert a child element at a specific location."
[parent child index]
(dom/insertChildAt parent child index))
(defn set-timeout [func ttime]
(timer/callOnce func ttime))
(defn set-position [e x y]
(style/setPosition e x y))
(defn get-position [e]
(style/getPosition e))
(defn toggle-class [el classname]
(classes/toggle el classname))
(defn add-class [el classname]
(classes/add el classname))
(defn remove-class [el classname]
(classes/remove el classname))
| 91338 | ; 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 bc.dom-helpers
(:require [clojure.string :as string]
[goog.style :as style]
[goog.dom :as dom]
[goog.dom.classes :as classes]
[goog.dom.forms :as forms]
[goog.fx :as fx]
[goog.fx.dom :as fx-dom]
[goog.Timer :as timer]
))
(defn get-element
"Return the element with the passed id."
[id]
(dom/getElement (name id)))
(defn show-element [e b]
(style/showElement e b))
(defn add-remove-class [e add-classes remove-classes]
(classes/addRemove e remove-classes add-classes))
(defn get-radio-value [form-name name]
(forms/getValueByName (get-element form-name) name))
(defn value [element]
(forms/getValue element))
(defn set-value [element]
(forms/setValue element))
(defn set-disabled [element disabled]
(forms/setDisabled element disabled))
(defn append
"Append all children to parent."
[parent & children]
(do (doseq [child children]
(dom/appendChild parent child))
parent))
(defn set-text
"Set the text content for the passed element returning the
element. If a keyword is passed in the place of e, the element with
that id will be used and returned."
[e s]
(let [e (if (or (keyword? e) (string? e)) (get-element e) e)]
(doto e
(dom/setTextContent s))))
(defn normalize-args [tag args]
(let [parts (string/split tag #"(\.|#)")
[tag attrs] [(first parts)
(apply hash-map (map #(cond (= % ".") :class
(= % "#") :id
:else %)
(rest parts)))]]
(if (map? (first args))
[tag (merge attrs (first args)) (rest args)]
[tag attrs args])))
;; TODO: replace call to .strobj with whatever we come up with for
;; creating js objects from Clojure maps.
(defn element
"Create a dom element using a keyword for the element name and a map
for the attributes. Append all children to parent. If the first
child is a string then the string will be set as the text content of
the parent and all remaining children will be appended."
[tag & args]
(let [[tag attrs children] (normalize-args tag args)
;; keyword/string mangling screws up (name tag)
parent (dom/createDom (subs tag 1)
(. (reduce (fn [m [k v]]
(assoc m k v))
{}
(map #(vector (name %1) %2)
(keys attrs)
(vals attrs))) -strobj))
[parent children] (if (string? (first children))
[(set-text (element tag attrs) (first children))
(rest children)]
[parent children])]
(apply append parent children)))
(defn remove-children
"Remove all children from the element with the passed id."
[parent-el]
(dom/removeChildren parent-el))
(defn html
"Create a dom element from an html string."
[s]
(dom/htmlToDocumentFragment s))
(defn- element-arg? [x]
(or (keyword? x)
(map? x)
(string? x)))
(defn build
"Build up a dom element from nested vectors."
[x]
(if (vector? x)
(let [[parent children] (if (keyword? (first x))
[(apply element (take-while element-arg? x))
(drop-while element-arg? x)]
[(first x) (rest x)])
children (map build children)]
(apply append parent children))
x))
(defn insert-at
"Insert a child element at a specific location."
[parent child index]
(dom/insertChildAt parent child index))
(defn set-timeout [func ttime]
(timer/callOnce func ttime))
(defn set-position [e x y]
(style/setPosition e x y))
(defn get-position [e]
(style/getPosition e))
(defn toggle-class [el classname]
(classes/toggle el classname))
(defn add-class [el classname]
(classes/add el classname))
(defn remove-class [el classname]
(classes/remove el classname))
| 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 bc.dom-helpers
(:require [clojure.string :as string]
[goog.style :as style]
[goog.dom :as dom]
[goog.dom.classes :as classes]
[goog.dom.forms :as forms]
[goog.fx :as fx]
[goog.fx.dom :as fx-dom]
[goog.Timer :as timer]
))
(defn get-element
"Return the element with the passed id."
[id]
(dom/getElement (name id)))
(defn show-element [e b]
(style/showElement e b))
(defn add-remove-class [e add-classes remove-classes]
(classes/addRemove e remove-classes add-classes))
(defn get-radio-value [form-name name]
(forms/getValueByName (get-element form-name) name))
(defn value [element]
(forms/getValue element))
(defn set-value [element]
(forms/setValue element))
(defn set-disabled [element disabled]
(forms/setDisabled element disabled))
(defn append
"Append all children to parent."
[parent & children]
(do (doseq [child children]
(dom/appendChild parent child))
parent))
(defn set-text
"Set the text content for the passed element returning the
element. If a keyword is passed in the place of e, the element with
that id will be used and returned."
[e s]
(let [e (if (or (keyword? e) (string? e)) (get-element e) e)]
(doto e
(dom/setTextContent s))))
(defn normalize-args [tag args]
(let [parts (string/split tag #"(\.|#)")
[tag attrs] [(first parts)
(apply hash-map (map #(cond (= % ".") :class
(= % "#") :id
:else %)
(rest parts)))]]
(if (map? (first args))
[tag (merge attrs (first args)) (rest args)]
[tag attrs args])))
;; TODO: replace call to .strobj with whatever we come up with for
;; creating js objects from Clojure maps.
(defn element
"Create a dom element using a keyword for the element name and a map
for the attributes. Append all children to parent. If the first
child is a string then the string will be set as the text content of
the parent and all remaining children will be appended."
[tag & args]
(let [[tag attrs children] (normalize-args tag args)
;; keyword/string mangling screws up (name tag)
parent (dom/createDom (subs tag 1)
(. (reduce (fn [m [k v]]
(assoc m k v))
{}
(map #(vector (name %1) %2)
(keys attrs)
(vals attrs))) -strobj))
[parent children] (if (string? (first children))
[(set-text (element tag attrs) (first children))
(rest children)]
[parent children])]
(apply append parent children)))
(defn remove-children
"Remove all children from the element with the passed id."
[parent-el]
(dom/removeChildren parent-el))
(defn html
"Create a dom element from an html string."
[s]
(dom/htmlToDocumentFragment s))
(defn- element-arg? [x]
(or (keyword? x)
(map? x)
(string? x)))
(defn build
"Build up a dom element from nested vectors."
[x]
(if (vector? x)
(let [[parent children] (if (keyword? (first x))
[(apply element (take-while element-arg? x))
(drop-while element-arg? x)]
[(first x) (rest x)])
children (map build children)]
(apply append parent children))
x))
(defn insert-at
"Insert a child element at a specific location."
[parent child index]
(dom/insertChildAt parent child index))
(defn set-timeout [func ttime]
(timer/callOnce func ttime))
(defn set-position [e x y]
(style/setPosition e x y))
(defn get-position [e]
(style/getPosition e))
(defn toggle-class [el classname]
(classes/toggle el classname))
(defn add-class [el classname]
(classes/add el classname))
(defn remove-class [el classname]
(classes/remove el classname))
|
[
{
"context": " -- Combinatory logic specs\n\n; Copyright (c) 2019 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 86,
"score": 0.9998664259910583,
"start": 72,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] | src/lwb/cl/spec.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Combinatory logic specs
; Copyright (c) 2019 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.cl.spec
(:require [clojure.spec.alpha :as s]))
; -----------------------------------------------------------------------------
;; # Specification of the syntax of combinatory logic
;; A combinator is a symbol whose first character is upper case
(s/def ::combinator (s/and symbol?
#(Character/isUpperCase ^char (first (name %)))))
;; A variable is a symbol whose first character is lower case
(s/def ::variable (s/and symbol?
#(Character/isLowerCase ^char (first (name %)))))
;; A simple expression is a combinator or a variable
(s/def ::simpl-expr (s/or :combinator ::combinator
:variable ::variable))
;; A complex expression is a nested list of complex or simple expression
(s/def ::compl-expr (s/and list? #(> (count %) 1) (s/+ (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; A term is a vector of simple or complex expressions
(s/def ::term (s/and vector? (s/* (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; An application expression is a nested list of applications
(s/def ::appl-expr (s/and list? #(= (count %) 2) (s/+ (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))))
;; A sterm is a simple expression or a nested list of sterms with simple expressions as leaves
(s/def ::sterm (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))
; -----------------------------------------------------------------------------
;; # Specification of options for weak-reduce
;; The limit is the maximal number of steps performed in the run of weak-reduce
(s/def ::limit pos-int?)
;; Timout is the number of milli seconds for the maximal length of a run of weak-reduce
(s/def ::timeout pos-int?)
;; The entry for `:cycle` determines whether cycle detection is on or off
(s/def ::cycle boolean?)
;; the entry for `:trace` determines whether intermediate steps are reported.
(s/def ::trace boolean?)
;; Options for weak-reduce
(s/def ::options (s/keys :opt-un [::limit ::timeout ::cycle ::trace]))
| 68039 | ; lwb Logic WorkBench -- Combinatory logic specs
; Copyright (c) 2019 <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.cl.spec
(:require [clojure.spec.alpha :as s]))
; -----------------------------------------------------------------------------
;; # Specification of the syntax of combinatory logic
;; A combinator is a symbol whose first character is upper case
(s/def ::combinator (s/and symbol?
#(Character/isUpperCase ^char (first (name %)))))
;; A variable is a symbol whose first character is lower case
(s/def ::variable (s/and symbol?
#(Character/isLowerCase ^char (first (name %)))))
;; A simple expression is a combinator or a variable
(s/def ::simpl-expr (s/or :combinator ::combinator
:variable ::variable))
;; A complex expression is a nested list of complex or simple expression
(s/def ::compl-expr (s/and list? #(> (count %) 1) (s/+ (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; A term is a vector of simple or complex expressions
(s/def ::term (s/and vector? (s/* (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; An application expression is a nested list of applications
(s/def ::appl-expr (s/and list? #(= (count %) 2) (s/+ (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))))
;; A sterm is a simple expression or a nested list of sterms with simple expressions as leaves
(s/def ::sterm (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))
; -----------------------------------------------------------------------------
;; # Specification of options for weak-reduce
;; The limit is the maximal number of steps performed in the run of weak-reduce
(s/def ::limit pos-int?)
;; Timout is the number of milli seconds for the maximal length of a run of weak-reduce
(s/def ::timeout pos-int?)
;; The entry for `:cycle` determines whether cycle detection is on or off
(s/def ::cycle boolean?)
;; the entry for `:trace` determines whether intermediate steps are reported.
(s/def ::trace boolean?)
;; Options for weak-reduce
(s/def ::options (s/keys :opt-un [::limit ::timeout ::cycle ::trace]))
| true | ; lwb Logic WorkBench -- Combinatory logic specs
; Copyright (c) 2019 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.cl.spec
(:require [clojure.spec.alpha :as s]))
; -----------------------------------------------------------------------------
;; # Specification of the syntax of combinatory logic
;; A combinator is a symbol whose first character is upper case
(s/def ::combinator (s/and symbol?
#(Character/isUpperCase ^char (first (name %)))))
;; A variable is a symbol whose first character is lower case
(s/def ::variable (s/and symbol?
#(Character/isLowerCase ^char (first (name %)))))
;; A simple expression is a combinator or a variable
(s/def ::simpl-expr (s/or :combinator ::combinator
:variable ::variable))
;; A complex expression is a nested list of complex or simple expression
(s/def ::compl-expr (s/and list? #(> (count %) 1) (s/+ (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; A term is a vector of simple or complex expressions
(s/def ::term (s/and vector? (s/* (s/or :simpl-expr ::simpl-expr
:compl-expr ::compl-expr))))
;; An application expression is a nested list of applications
(s/def ::appl-expr (s/and list? #(= (count %) 2) (s/+ (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))))
;; A sterm is a simple expression or a nested list of sterms with simple expressions as leaves
(s/def ::sterm (s/or :simpl-expr ::simpl-expr
:appl-expr ::appl-expr))
; -----------------------------------------------------------------------------
;; # Specification of options for weak-reduce
;; The limit is the maximal number of steps performed in the run of weak-reduce
(s/def ::limit pos-int?)
;; Timout is the number of milli seconds for the maximal length of a run of weak-reduce
(s/def ::timeout pos-int?)
;; The entry for `:cycle` determines whether cycle detection is on or off
(s/def ::cycle boolean?)
;; the entry for `:trace` determines whether intermediate steps are reported.
(s/def ::trace boolean?)
;; Options for weak-reduce
(s/def ::options (s/keys :opt-un [::limit ::timeout ::cycle ::trace]))
|
[
{
"context": "t strips HTML comments from strings.\"\n (is (= \"Bob\" (strip-html-comments \"Bob\")))\n (is (empty? (s",
"end": 545,
"score": 0.9855422377586365,
"start": 542,
"tag": "NAME",
"value": "Bob"
},
{
"context": " strings.\"\n (is (= \"Bob\" (strip-html-comments \"Bob\")))\n (is (empty? (strip-html-comments \"\")))\n ",
"end": 572,
"score": 0.9922532439231873,
"start": 569,
"tag": "NAME",
"value": "Bob"
},
{
"context": "is (empty? (strip-html-comments \"\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob Alice\")))\n (is (= \"",
"end": 641,
"score": 0.99903404712677,
"start": 632,
"tag": "NAME",
"value": "Bob Alice"
},
{
"context": "\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"",
"end": 674,
"score": 0.9972550868988037,
"start": 665,
"tag": "NAME",
"value": "Bob Alice"
},
{
"context": "\" (strip-html-comments \"Bob Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!--No End Space-->Ali",
"end": 700,
"score": 0.9989043474197388,
"start": 691,
"tag": "NAME",
"value": "Bob Alice"
},
{
"context": "\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!--No End Space-->Alice\")))\n (is (= \"Bob Alic",
"end": 727,
"score": 0.9971602559089661,
"start": 724,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ice\" (strip-html-comments \"Bob <!--No End Space-->Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"",
"end": 752,
"score": 0.9773948788642883,
"start": 747,
"tag": "NAME",
"value": "Alice"
},
{
"context": "nts \"Bob <!--No End Space-->Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!-- -->Alice\")))\n ",
"end": 778,
"score": 0.9991830587387085,
"start": 769,
"tag": "NAME",
"value": "Bob Alice"
},
{
"context": "\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!-- -->Alice\")))\n (is (= \"Bob Alice\" (strip-h",
"end": 805,
"score": 0.9988895654678345,
"start": 802,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (= \"Bob Alice\" (strip-html-comments \"Bob <!-- -->Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"",
"end": 819,
"score": 0.9914537668228149,
"start": 814,
"tag": "NAME",
"value": "Alice"
},
{
"context": "-html-comments \"Bob <!-- -->Alice\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!-- A comment with a ",
"end": 845,
"score": 0.9989674091339111,
"start": 836,
"tag": "NAME",
"value": "Bob Alice"
},
{
"context": "\")))\n (is (= \"Bob Alice\" (strip-html-comments \"Bob <!-- A comment with a <tag>tag</tag> in it -->Ali",
"end": 872,
"score": 0.9970241189002991,
"start": 869,
"tag": "NAME",
"value": "Bob"
},
{
"context": "Bob <!-- A comment with a <tag>tag</tag> in it -->Alice\")))))\n\n(deftest replace-tabs-with-spaces-test\n (",
"end": 924,
"score": 0.9931917190551758,
"start": 919,
"tag": "NAME",
"value": "Alice"
},
{
"context": "\"))))\n (testing \"Tabs between words\"\n (is (= \"Bob Carol Ted\" (replace-tabs-with-spaces \"Bob\\tCarol\\tTed\"))))\n",
"end": 1182,
"score": 0.9976130723953247,
"start": 1169,
"tag": "NAME",
"value": "Bob Carol Ted"
},
{
"context": "(is (= \"Bob Carol Ted\" (replace-tabs-with-spaces \"Bob\\tCarol\\tTed\"))))\n (testing \"Works across newline",
"end": 1214,
"score": 0.9539676904678345,
"start": 1211,
"tag": "NAME",
"value": "Bob"
},
{
"context": "Bob Carol Ted\" (replace-tabs-with-spaces \"Bob\\tCarol\\tTed\"))))\n (testing \"Works across newlines\"\n ",
"end": 1221,
"score": 0.9304040670394897,
"start": 1219,
"tag": "NAME",
"value": "ol"
},
{
"context": "Carol Ted\" (replace-tabs-with-spaces \"Bob\\tCarol\\tTed\"))))\n (testing \"Works across newlines\"\n (is (",
"end": 1226,
"score": 0.7369085550308228,
"start": 1223,
"tag": "NAME",
"value": "Ted"
},
{
"context": "))\n (testing \"Works across newlines\"\n (is (= \"Bob Carol\\nTed Alice\" (replace-tabs-with-spaces \"Bob\\tCarol",
"end": 1288,
"score": 0.9992932677268982,
"start": 1279,
"tag": "NAME",
"value": "Bob Carol"
},
{
"context": "ng \"Works across newlines\"\n (is (= \"Bob Carol\\nTed Alice\" (replace-tabs-with-spaces \"Bob\\tCarol\\nTed\\tAlic",
"end": 1299,
"score": 0.916980504989624,
"start": 1290,
"tag": "NAME",
"value": "Ted Alice"
},
{
"context": "\"Bob Carol\\nTed Alice\" (replace-tabs-with-spaces \"Bob\\tCarol\\nTed\\tAlice\")))))\n\n(deftest strip-images-t",
"end": 1331,
"score": 0.9955404996871948,
"start": 1328,
"tag": "NAME",
"value": "Bob"
},
{
"context": "Carol\\nTed Alice\" (replace-tabs-with-spaces \"Bob\\tCarol\\nTed\\tAlice\")))))\n\n(deftest strip-images-test\n (",
"end": 1338,
"score": 0.8174774050712585,
"start": 1333,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ed Alice\" (replace-tabs-with-spaces \"Bob\\tCarol\\nTed\\tAlice\")))))\n\n(deftest strip-images-test\n (testi",
"end": 1343,
"score": 0.972269594669342,
"start": 1341,
"tag": "NAME",
"value": "ed"
},
{
"context": "lice\" (replace-tabs-with-spaces \"Bob\\tCarol\\nTed\\tAlice\")))))\n\n(deftest strip-images-test\n (testing \"Rem",
"end": 1350,
"score": 0.9766632914543152,
"start": 1345,
"tag": "NAME",
"value": "Alice"
}
] | test/clj/cwiki/test/util/wc.clj | clartaq/cwiki | 3 | ;;;
;;; This namespace provides tests for the functions used to count
;;; words in a piece of Markdown text.
;;;
;;; NOTE: These tests have special knowledge of how things are replaced
;;; by spaces or not. Changes in the implementation of the counting
;;; functions may require alteration of the expected test results.
;;;
(ns cwiki.test.util.wc
(:require [clojure.test :refer :all]
[cwiki.util.wc :refer :all]))
(deftest strip-html-comments-test
(testing "The function that strips HTML comments from strings."
(is (= "Bob" (strip-html-comments "Bob")))
(is (empty? (strip-html-comments "")))
(is (= "Bob Alice" (strip-html-comments "Bob Alice")))
(is (= "Bob Alice" (strip-html-comments "Bob <!--No End Space-->Alice")))
(is (= "Bob Alice" (strip-html-comments "Bob <!-- -->Alice")))
(is (= "Bob Alice" (strip-html-comments "Bob <!-- A comment with a <tag>tag</tag> in it -->Alice")))))
(deftest replace-tabs-with-spaces-test
(testing "An empty string"
(is (empty? (replace-tabs-with-spaces ""))))
(testing "A single tab"
(is (= " " (replace-tabs-with-spaces "\t"))))
(testing "Tabs between words"
(is (= "Bob Carol Ted" (replace-tabs-with-spaces "Bob\tCarol\tTed"))))
(testing "Works across newlines"
(is (= "Bob Carol\nTed Alice" (replace-tabs-with-spaces "Bob\tCarol\nTed\tAlice")))))
(deftest strip-images-test
(testing "Removing images"
(is (= "Links to images like these:\n\n\n\n\n\nShould go away."
(strip-images "Links to images like these:\n\n\n\n\n\nShould go away.")))))
;; Note that the headers actually contain a leading a trailing newline when
;; the header indicators are removed.
(deftest extract-markdown-headers-test
;; atx style headers
(testing "Header 1"
(is (= "\nHeader 1\n" (extract-markdown-headers "# Header 1 #\n"))))
(testing "Header 2 with mismatched trailing markers"
(is (= "\nHeader 2\n" (extract-markdown-headers "## Header 2 ####\n"))))
(testing "Header 6"
(is (= "\nHeader 6\n" (extract-markdown-headers "###### Header 6 ###### \n"))))
(testing "Only markers before title"
(is (= "\nHeader 3\n" (extract-markdown-headers "### Header 3 \n"))))
(testing "Header without space after marker is not really a Header"
(is (= "#Header 1#\n" (extract-markdown-headers "#Header 1#\n"))))
(testing "Trailing markers should be left alone"
(is (= "Header 1#\n" (extract-markdown-headers "Header 1#\n")))
(is (= "Header 1 #\n" (extract-markdown-headers "Header 1 #\n"))))
;;; setext style headers
(testing "Setext style headers"
(is (= "\nAn H1 header\n" (extract-markdown-headers "An H1 header\n=============\n")))
(is (= "\nAn H2 header\n" (extract-markdown-headers "An H2 header\n-------------\n")))))
(deftest extract-link-text-test
(testing "A plain ole link"
(is (= "A link here" (extract-link-text "A [link](http://example.com) here"))))
(testing "Two links"
;; Note the double spaces around "first" and "second".
(is (= "A first link and a second one"
(extract-link-text "A [first](http://example.com) link and a [second](https://example.com) one")))))
(deftest extract-wikilink-text-test
(testing "Empty wikilink"
(is (= " " (extract-wikilink-text "[[]]"))))
(testing "Malformed links"
(is (= "Some [text]] here" (extract-wikilink-text "Some [text]] here")))
(is (= "Some [[text] here" (extract-wikilink-text "Some [[text] here"))))
(testing "Simple, single word wikilink"
(is (= " wikilink " (extract-wikilink-text "[[wikilink]]"))))
(testing "Multi-word wikilink"
(is (= " Some Random Text " (extract-wikilink-text "[[Some Random Text]]"))))
(testing "A two-part link"
; Note the _two_ spaces before "link"
(is (= "A link ?" (extract-wikilink-text "A [[two part|link]]?")))))
(deftest replace-html-tags-with-spaces-test
(testing "A regular string with no tag"
(is (= "A regular string" (replace-html-tags-with-spaces "A regular string"))))
(testing "A single tag element"
;; Note three spaces after break
(is (= "A break here" (replace-html-tags-with-spaces "A break </ br> here"))))
(testing "Multiple tags"
(is (= "Some bold and underlined elements" (replace-html-tags-with-spaces "Some <b>bold</b> and <u>underlined</u> elements")))))
(def footnote-test-text "Here's a simple footnote,[^1] and here's a longer one.[^bignote]
[^1]: This is the first footnote.
[^bignote]: Here's one with multiple paragraphs and code.")
(def footnote-result-text
"Here's a simple footnote, and here's a longer one.
This is the first footnote.
Here's one with multiple paragraphs and code.")
(deftest strip-footnote-references-test
(testing "Footnote removal"
(is (= footnote-result-text
(strip-footnote-references footnote-test-text)))))
(deftest strip-mathjax-test
(testing "Stripping inline LaTeX"
;; Note double space before "and".
(is (= "Some math inline and"
(strip-mathjax "Some math inline $\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}$ and"))))
(testing "Stripping inline LaTeX symbol"
;; Note double space before "symbol".
(is (= "The symbol inline" (strip-mathjax "The $\\rm\\LaTeX$ symbol inline"))))
(testing "Display equation with no content"
(is (empty? (strip-mathjax "$$$$"))))
(testing "Display equation with only spaces for content"
(is (empty? (strip-mathjax "$$ $$"))))
(testing "The LaTeX symbol"
(is (= "LaTeX symbol\n\n\n\n" (strip-mathjax "LaTeX symbol\n\n$$\\rm\\LaTeX$$\n\n"))))
(testing "Display equation with internal newlines (not the LaTeX \\newline)"
(is (empty? (strip-mathjax "$$\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\n$$"))))
(testing "Display equation with internal Unicode 'nextline' character \u0085"
(is (empty? (strip-mathjax "$$\u0085\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0085$$"))))
(testing "Display equation with internal Unicode 'line-separatpr' character \u2028"
(is (empty? (strip-mathjax "$$\u2028\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2028$$"))))
(testing "Display equation with internal Unicode 'nex-paragraph' character \u2029"
(is (empty? (strip-mathjax "$$\u2029\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2029$$"))))
(testing "Display equation with internal Unicode Greek 'Omega' character \u03A9"
(is (empty? (strip-mathjax "$$\u0349\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0349$$"))))
(testing "Stripping standalone LaTeX equation with internal newlines"
(is (= "on it's own line:\n\n\n\nLooks good, huh?"
(strip-mathjax "on it's own line:\n\n$$\\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\\n$$\n\nLooks good, huh?")))))
(deftest strip-special-characters-test
(testing "An empty string"
(is (empty? (strip-special-characters ""))))
(testing "Just the special characters"
(is (empty? (strip-special-characters "#*`~–^=<>+|/:"))))
(testing "Characters and words"
(is (= "AWordInTheMiddleOfTheCharsThatShouldBeRemovedNow"
(strip-special-characters "#A*Word`In~The–Middle^Of=The<Chars>That+Should|Be/Removed:Now")))))
(deftest strip-standalone-punctuation-test
(testing "No punctuation string"
(is (= "A string" (strip-standalone-punctuation "A string")))
(is (= " Another String " (strip-standalone-punctuation " Another String "))))
(testing "Interposed punctuation"
(is (= "A comma period qmark" (strip-standalone-punctuation "A , comma . period ? qmark"))))
(testing "At the beginning of a line"
(is (= " At beginning" (strip-standalone-punctuation "\n! At beginning"))))
(testing "At the end of a line"
(is (= "At end " (strip-standalone-punctuation "At end ;\n"))))
(testing "At both ends"
(is (= " At both ends " (strip-standalone-punctuation "\t! At both / ends\t/\n")))))
(deftest strip-standalone-numbers-test
(testing "Multi-line, no numbers"
(is (= "First item\nSecond Item\nThird item\n"
(strip-standalone-numbers "First item\nSecond Item\nThird item\n"))))
(testing "Numbered list"
(is (= "A Numbered List First item Second Item Third item\n"
(strip-standalone-numbers "A Numbered List\n1. First item\n2. Second Item\n3. Third item\n"))))
(testing "Numbers in words"
(is (= "An identifier is an_id_21c."
(strip-standalone-numbers "An identifier is an_id_21c."))))
(testing "Things with prices"
(is (= "Pears cost $1.34 per pound."
(strip-standalone-numbers "Pears cost $1.34 per pound."))))) | 56921 | ;;;
;;; This namespace provides tests for the functions used to count
;;; words in a piece of Markdown text.
;;;
;;; NOTE: These tests have special knowledge of how things are replaced
;;; by spaces or not. Changes in the implementation of the counting
;;; functions may require alteration of the expected test results.
;;;
(ns cwiki.test.util.wc
(:require [clojure.test :refer :all]
[cwiki.util.wc :refer :all]))
(deftest strip-html-comments-test
(testing "The function that strips HTML comments from strings."
(is (= "<NAME>" (strip-html-comments "<NAME>")))
(is (empty? (strip-html-comments "")))
(is (= "<NAME>" (strip-html-comments "<NAME>")))
(is (= "<NAME>" (strip-html-comments "<NAME> <!--No End Space--><NAME>")))
(is (= "<NAME>" (strip-html-comments "<NAME> <!-- --><NAME>")))
(is (= "<NAME>" (strip-html-comments "<NAME> <!-- A comment with a <tag>tag</tag> in it --><NAME>")))))
(deftest replace-tabs-with-spaces-test
(testing "An empty string"
(is (empty? (replace-tabs-with-spaces ""))))
(testing "A single tab"
(is (= " " (replace-tabs-with-spaces "\t"))))
(testing "Tabs between words"
(is (= "<NAME>" (replace-tabs-with-spaces "<NAME>\tCar<NAME>\t<NAME>"))))
(testing "Works across newlines"
(is (= "<NAME>\n<NAME>" (replace-tabs-with-spaces "<NAME>\t<NAME>\nT<NAME>\t<NAME>")))))
(deftest strip-images-test
(testing "Removing images"
(is (= "Links to images like these:\n\n\n\n\n\nShould go away."
(strip-images "Links to images like these:\n\n\n\n\n\nShould go away.")))))
;; Note that the headers actually contain a leading a trailing newline when
;; the header indicators are removed.
(deftest extract-markdown-headers-test
;; atx style headers
(testing "Header 1"
(is (= "\nHeader 1\n" (extract-markdown-headers "# Header 1 #\n"))))
(testing "Header 2 with mismatched trailing markers"
(is (= "\nHeader 2\n" (extract-markdown-headers "## Header 2 ####\n"))))
(testing "Header 6"
(is (= "\nHeader 6\n" (extract-markdown-headers "###### Header 6 ###### \n"))))
(testing "Only markers before title"
(is (= "\nHeader 3\n" (extract-markdown-headers "### Header 3 \n"))))
(testing "Header without space after marker is not really a Header"
(is (= "#Header 1#\n" (extract-markdown-headers "#Header 1#\n"))))
(testing "Trailing markers should be left alone"
(is (= "Header 1#\n" (extract-markdown-headers "Header 1#\n")))
(is (= "Header 1 #\n" (extract-markdown-headers "Header 1 #\n"))))
;;; setext style headers
(testing "Setext style headers"
(is (= "\nAn H1 header\n" (extract-markdown-headers "An H1 header\n=============\n")))
(is (= "\nAn H2 header\n" (extract-markdown-headers "An H2 header\n-------------\n")))))
(deftest extract-link-text-test
(testing "A plain ole link"
(is (= "A link here" (extract-link-text "A [link](http://example.com) here"))))
(testing "Two links"
;; Note the double spaces around "first" and "second".
(is (= "A first link and a second one"
(extract-link-text "A [first](http://example.com) link and a [second](https://example.com) one")))))
(deftest extract-wikilink-text-test
(testing "Empty wikilink"
(is (= " " (extract-wikilink-text "[[]]"))))
(testing "Malformed links"
(is (= "Some [text]] here" (extract-wikilink-text "Some [text]] here")))
(is (= "Some [[text] here" (extract-wikilink-text "Some [[text] here"))))
(testing "Simple, single word wikilink"
(is (= " wikilink " (extract-wikilink-text "[[wikilink]]"))))
(testing "Multi-word wikilink"
(is (= " Some Random Text " (extract-wikilink-text "[[Some Random Text]]"))))
(testing "A two-part link"
; Note the _two_ spaces before "link"
(is (= "A link ?" (extract-wikilink-text "A [[two part|link]]?")))))
(deftest replace-html-tags-with-spaces-test
(testing "A regular string with no tag"
(is (= "A regular string" (replace-html-tags-with-spaces "A regular string"))))
(testing "A single tag element"
;; Note three spaces after break
(is (= "A break here" (replace-html-tags-with-spaces "A break </ br> here"))))
(testing "Multiple tags"
(is (= "Some bold and underlined elements" (replace-html-tags-with-spaces "Some <b>bold</b> and <u>underlined</u> elements")))))
(def footnote-test-text "Here's a simple footnote,[^1] and here's a longer one.[^bignote]
[^1]: This is the first footnote.
[^bignote]: Here's one with multiple paragraphs and code.")
(def footnote-result-text
"Here's a simple footnote, and here's a longer one.
This is the first footnote.
Here's one with multiple paragraphs and code.")
(deftest strip-footnote-references-test
(testing "Footnote removal"
(is (= footnote-result-text
(strip-footnote-references footnote-test-text)))))
(deftest strip-mathjax-test
(testing "Stripping inline LaTeX"
;; Note double space before "and".
(is (= "Some math inline and"
(strip-mathjax "Some math inline $\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}$ and"))))
(testing "Stripping inline LaTeX symbol"
;; Note double space before "symbol".
(is (= "The symbol inline" (strip-mathjax "The $\\rm\\LaTeX$ symbol inline"))))
(testing "Display equation with no content"
(is (empty? (strip-mathjax "$$$$"))))
(testing "Display equation with only spaces for content"
(is (empty? (strip-mathjax "$$ $$"))))
(testing "The LaTeX symbol"
(is (= "LaTeX symbol\n\n\n\n" (strip-mathjax "LaTeX symbol\n\n$$\\rm\\LaTeX$$\n\n"))))
(testing "Display equation with internal newlines (not the LaTeX \\newline)"
(is (empty? (strip-mathjax "$$\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\n$$"))))
(testing "Display equation with internal Unicode 'nextline' character \u0085"
(is (empty? (strip-mathjax "$$\u0085\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0085$$"))))
(testing "Display equation with internal Unicode 'line-separatpr' character \u2028"
(is (empty? (strip-mathjax "$$\u2028\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2028$$"))))
(testing "Display equation with internal Unicode 'nex-paragraph' character \u2029"
(is (empty? (strip-mathjax "$$\u2029\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2029$$"))))
(testing "Display equation with internal Unicode Greek 'Omega' character \u03A9"
(is (empty? (strip-mathjax "$$\u0349\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0349$$"))))
(testing "Stripping standalone LaTeX equation with internal newlines"
(is (= "on it's own line:\n\n\n\nLooks good, huh?"
(strip-mathjax "on it's own line:\n\n$$\\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\\n$$\n\nLooks good, huh?")))))
(deftest strip-special-characters-test
(testing "An empty string"
(is (empty? (strip-special-characters ""))))
(testing "Just the special characters"
(is (empty? (strip-special-characters "#*`~–^=<>+|/:"))))
(testing "Characters and words"
(is (= "AWordInTheMiddleOfTheCharsThatShouldBeRemovedNow"
(strip-special-characters "#A*Word`In~The–Middle^Of=The<Chars>That+Should|Be/Removed:Now")))))
(deftest strip-standalone-punctuation-test
(testing "No punctuation string"
(is (= "A string" (strip-standalone-punctuation "A string")))
(is (= " Another String " (strip-standalone-punctuation " Another String "))))
(testing "Interposed punctuation"
(is (= "A comma period qmark" (strip-standalone-punctuation "A , comma . period ? qmark"))))
(testing "At the beginning of a line"
(is (= " At beginning" (strip-standalone-punctuation "\n! At beginning"))))
(testing "At the end of a line"
(is (= "At end " (strip-standalone-punctuation "At end ;\n"))))
(testing "At both ends"
(is (= " At both ends " (strip-standalone-punctuation "\t! At both / ends\t/\n")))))
(deftest strip-standalone-numbers-test
(testing "Multi-line, no numbers"
(is (= "First item\nSecond Item\nThird item\n"
(strip-standalone-numbers "First item\nSecond Item\nThird item\n"))))
(testing "Numbered list"
(is (= "A Numbered List First item Second Item Third item\n"
(strip-standalone-numbers "A Numbered List\n1. First item\n2. Second Item\n3. Third item\n"))))
(testing "Numbers in words"
(is (= "An identifier is an_id_21c."
(strip-standalone-numbers "An identifier is an_id_21c."))))
(testing "Things with prices"
(is (= "Pears cost $1.34 per pound."
(strip-standalone-numbers "Pears cost $1.34 per pound."))))) | true | ;;;
;;; This namespace provides tests for the functions used to count
;;; words in a piece of Markdown text.
;;;
;;; NOTE: These tests have special knowledge of how things are replaced
;;; by spaces or not. Changes in the implementation of the counting
;;; functions may require alteration of the expected test results.
;;;
(ns cwiki.test.util.wc
(:require [clojure.test :refer :all]
[cwiki.util.wc :refer :all]))
(deftest strip-html-comments-test
(testing "The function that strips HTML comments from strings."
(is (= "PI:NAME:<NAME>END_PI" (strip-html-comments "PI:NAME:<NAME>END_PI")))
(is (empty? (strip-html-comments "")))
(is (= "PI:NAME:<NAME>END_PI" (strip-html-comments "PI:NAME:<NAME>END_PI")))
(is (= "PI:NAME:<NAME>END_PI" (strip-html-comments "PI:NAME:<NAME>END_PI <!--No End Space-->PI:NAME:<NAME>END_PI")))
(is (= "PI:NAME:<NAME>END_PI" (strip-html-comments "PI:NAME:<NAME>END_PI <!-- -->PI:NAME:<NAME>END_PI")))
(is (= "PI:NAME:<NAME>END_PI" (strip-html-comments "PI:NAME:<NAME>END_PI <!-- A comment with a <tag>tag</tag> in it -->PI:NAME:<NAME>END_PI")))))
(deftest replace-tabs-with-spaces-test
(testing "An empty string"
(is (empty? (replace-tabs-with-spaces ""))))
(testing "A single tab"
(is (= " " (replace-tabs-with-spaces "\t"))))
(testing "Tabs between words"
(is (= "PI:NAME:<NAME>END_PI" (replace-tabs-with-spaces "PI:NAME:<NAME>END_PI\tCarPI:NAME:<NAME>END_PI\tPI:NAME:<NAME>END_PI"))))
(testing "Works across newlines"
(is (= "PI:NAME:<NAME>END_PI\nPI:NAME:<NAME>END_PI" (replace-tabs-with-spaces "PI:NAME:<NAME>END_PI\tPI:NAME:<NAME>END_PI\nTPI:NAME:<NAME>END_PI\tPI:NAME:<NAME>END_PI")))))
(deftest strip-images-test
(testing "Removing images"
(is (= "Links to images like these:\n\n\n\n\n\nShould go away."
(strip-images "Links to images like these:\n\n\n\n\n\nShould go away.")))))
;; Note that the headers actually contain a leading a trailing newline when
;; the header indicators are removed.
(deftest extract-markdown-headers-test
;; atx style headers
(testing "Header 1"
(is (= "\nHeader 1\n" (extract-markdown-headers "# Header 1 #\n"))))
(testing "Header 2 with mismatched trailing markers"
(is (= "\nHeader 2\n" (extract-markdown-headers "## Header 2 ####\n"))))
(testing "Header 6"
(is (= "\nHeader 6\n" (extract-markdown-headers "###### Header 6 ###### \n"))))
(testing "Only markers before title"
(is (= "\nHeader 3\n" (extract-markdown-headers "### Header 3 \n"))))
(testing "Header without space after marker is not really a Header"
(is (= "#Header 1#\n" (extract-markdown-headers "#Header 1#\n"))))
(testing "Trailing markers should be left alone"
(is (= "Header 1#\n" (extract-markdown-headers "Header 1#\n")))
(is (= "Header 1 #\n" (extract-markdown-headers "Header 1 #\n"))))
;;; setext style headers
(testing "Setext style headers"
(is (= "\nAn H1 header\n" (extract-markdown-headers "An H1 header\n=============\n")))
(is (= "\nAn H2 header\n" (extract-markdown-headers "An H2 header\n-------------\n")))))
(deftest extract-link-text-test
(testing "A plain ole link"
(is (= "A link here" (extract-link-text "A [link](http://example.com) here"))))
(testing "Two links"
;; Note the double spaces around "first" and "second".
(is (= "A first link and a second one"
(extract-link-text "A [first](http://example.com) link and a [second](https://example.com) one")))))
(deftest extract-wikilink-text-test
(testing "Empty wikilink"
(is (= " " (extract-wikilink-text "[[]]"))))
(testing "Malformed links"
(is (= "Some [text]] here" (extract-wikilink-text "Some [text]] here")))
(is (= "Some [[text] here" (extract-wikilink-text "Some [[text] here"))))
(testing "Simple, single word wikilink"
(is (= " wikilink " (extract-wikilink-text "[[wikilink]]"))))
(testing "Multi-word wikilink"
(is (= " Some Random Text " (extract-wikilink-text "[[Some Random Text]]"))))
(testing "A two-part link"
; Note the _two_ spaces before "link"
(is (= "A link ?" (extract-wikilink-text "A [[two part|link]]?")))))
(deftest replace-html-tags-with-spaces-test
(testing "A regular string with no tag"
(is (= "A regular string" (replace-html-tags-with-spaces "A regular string"))))
(testing "A single tag element"
;; Note three spaces after break
(is (= "A break here" (replace-html-tags-with-spaces "A break </ br> here"))))
(testing "Multiple tags"
(is (= "Some bold and underlined elements" (replace-html-tags-with-spaces "Some <b>bold</b> and <u>underlined</u> elements")))))
(def footnote-test-text "Here's a simple footnote,[^1] and here's a longer one.[^bignote]
[^1]: This is the first footnote.
[^bignote]: Here's one with multiple paragraphs and code.")
(def footnote-result-text
"Here's a simple footnote, and here's a longer one.
This is the first footnote.
Here's one with multiple paragraphs and code.")
(deftest strip-footnote-references-test
(testing "Footnote removal"
(is (= footnote-result-text
(strip-footnote-references footnote-test-text)))))
(deftest strip-mathjax-test
(testing "Stripping inline LaTeX"
;; Note double space before "and".
(is (= "Some math inline and"
(strip-mathjax "Some math inline $\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}$ and"))))
(testing "Stripping inline LaTeX symbol"
;; Note double space before "symbol".
(is (= "The symbol inline" (strip-mathjax "The $\\rm\\LaTeX$ symbol inline"))))
(testing "Display equation with no content"
(is (empty? (strip-mathjax "$$$$"))))
(testing "Display equation with only spaces for content"
(is (empty? (strip-mathjax "$$ $$"))))
(testing "The LaTeX symbol"
(is (= "LaTeX symbol\n\n\n\n" (strip-mathjax "LaTeX symbol\n\n$$\\rm\\LaTeX$$\n\n"))))
(testing "Display equation with internal newlines (not the LaTeX \\newline)"
(is (empty? (strip-mathjax "$$\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\n$$"))))
(testing "Display equation with internal Unicode 'nextline' character \u0085"
(is (empty? (strip-mathjax "$$\u0085\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0085$$"))))
(testing "Display equation with internal Unicode 'line-separatpr' character \u2028"
(is (empty? (strip-mathjax "$$\u2028\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2028$$"))))
(testing "Display equation with internal Unicode 'nex-paragraph' character \u2029"
(is (empty? (strip-mathjax "$$\u2029\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u2029$$"))))
(testing "Display equation with internal Unicode Greek 'Omega' character \u03A9"
(is (empty? (strip-mathjax "$$\u0349\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\u0349$$"))))
(testing "Stripping standalone LaTeX equation with internal newlines"
(is (= "on it's own line:\n\n\n\nLooks good, huh?"
(strip-mathjax "on it's own line:\n\n$$\\n\\sigma = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^N (x_i -\\mu)^2}\\n$$\n\nLooks good, huh?")))))
(deftest strip-special-characters-test
(testing "An empty string"
(is (empty? (strip-special-characters ""))))
(testing "Just the special characters"
(is (empty? (strip-special-characters "#*`~–^=<>+|/:"))))
(testing "Characters and words"
(is (= "AWordInTheMiddleOfTheCharsThatShouldBeRemovedNow"
(strip-special-characters "#A*Word`In~The–Middle^Of=The<Chars>That+Should|Be/Removed:Now")))))
(deftest strip-standalone-punctuation-test
(testing "No punctuation string"
(is (= "A string" (strip-standalone-punctuation "A string")))
(is (= " Another String " (strip-standalone-punctuation " Another String "))))
(testing "Interposed punctuation"
(is (= "A comma period qmark" (strip-standalone-punctuation "A , comma . period ? qmark"))))
(testing "At the beginning of a line"
(is (= " At beginning" (strip-standalone-punctuation "\n! At beginning"))))
(testing "At the end of a line"
(is (= "At end " (strip-standalone-punctuation "At end ;\n"))))
(testing "At both ends"
(is (= " At both ends " (strip-standalone-punctuation "\t! At both / ends\t/\n")))))
(deftest strip-standalone-numbers-test
(testing "Multi-line, no numbers"
(is (= "First item\nSecond Item\nThird item\n"
(strip-standalone-numbers "First item\nSecond Item\nThird item\n"))))
(testing "Numbered list"
(is (= "A Numbered List First item Second Item Third item\n"
(strip-standalone-numbers "A Numbered List\n1. First item\n2. Second Item\n3. Third item\n"))))
(testing "Numbers in words"
(is (= "An identifier is an_id_21c."
(strip-standalone-numbers "An identifier is an_id_21c."))))
(testing "Things with prices"
(is (= "Pears cost $1.34 per pound."
(strip-standalone-numbers "Pears cost $1.34 per pound."))))) |
[
{
"context": "ostagga and milestones.\n;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech>\n\n(ns tasks.parser-rules)\n\n;;mil",
"end": 153,
"score": 0.9998812079429626,
"start": 139,
"tag": "NAME",
"value": "Rafik NACCACHE"
},
{
"context": "tones.\n;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech>\n\n(ns tasks.parser-rules)\n\n;;milestone\n#_:milesto",
"end": 170,
"score": 0.999927818775177,
"start": 155,
"tag": "EMAIL",
"value": "rafik@fekr.tech"
}
] | js/compiled/out/tasks/parser_rules.cljs | fekr/tasks | 1 | ;; A set of rules for the parser to be used with tasks- the demo website showcasing postagga and milestones.
;; Copyright (C) 2016 , Rafik NACCACHE <rafik@fekr.tech>
(ns tasks.parser-rules)
;;milestone
#_:milestone-id
#_:task-name
#_:predecessors
;;task
#_:predecessors
#_:resource-id
#_:duration
#_:priority
#_:task-id
#_:task-name
(def rules
[{:id :milestone ;;milestone 5 : goal reached when tasks 2, 3 are complete.
:optional-steps [:punct :predecessors-end]
:rule [:milestone-id
#{#{"NN"}}
#{:get-value #{"CD"}}
:punct
#{#{":"}}
:task-name
#{:get-value #{"NN"}}
#{:get-value #{"VVN"}}
:predecessors
#{#{"WRB"}}
#{#{"NNS"}}
#{:get-value :multi #{"CD"}}
:predecessors-end
#{#{"VBP"}}
#{#{"JJ"}}
]}])
| 33212 | ;; A set of rules for the parser to be used with tasks- the demo website showcasing postagga and milestones.
;; Copyright (C) 2016 , <NAME> <<EMAIL>>
(ns tasks.parser-rules)
;;milestone
#_:milestone-id
#_:task-name
#_:predecessors
;;task
#_:predecessors
#_:resource-id
#_:duration
#_:priority
#_:task-id
#_:task-name
(def rules
[{:id :milestone ;;milestone 5 : goal reached when tasks 2, 3 are complete.
:optional-steps [:punct :predecessors-end]
:rule [:milestone-id
#{#{"NN"}}
#{:get-value #{"CD"}}
:punct
#{#{":"}}
:task-name
#{:get-value #{"NN"}}
#{:get-value #{"VVN"}}
:predecessors
#{#{"WRB"}}
#{#{"NNS"}}
#{:get-value :multi #{"CD"}}
:predecessors-end
#{#{"VBP"}}
#{#{"JJ"}}
]}])
| true | ;; A set of rules for the parser to be used with tasks- the demo website showcasing postagga and milestones.
;; Copyright (C) 2016 , PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(ns tasks.parser-rules)
;;milestone
#_:milestone-id
#_:task-name
#_:predecessors
;;task
#_:predecessors
#_:resource-id
#_:duration
#_:priority
#_:task-id
#_:task-name
(def rules
[{:id :milestone ;;milestone 5 : goal reached when tasks 2, 3 are complete.
:optional-steps [:punct :predecessors-end]
:rule [:milestone-id
#{#{"NN"}}
#{:get-value #{"CD"}}
:punct
#{#{":"}}
:task-name
#{:get-value #{"NN"}}
#{:get-value #{"VVN"}}
:predecessors
#{#{"WRB"}}
#{#{"NNS"}}
#{:get-value :multi #{"CD"}}
:predecessors-end
#{#{"VBP"}}
#{#{"JJ"}}
]}])
|
[
{
"context": "[parent windowy _windowx]\n (let [l1 \"Notcurses by Nick Black et al\"\n l2 \"Zig lang by Andrew Kelley & co",
"end": 6585,
"score": 0.9998868703842163,
"start": 6575,
"tag": "NAME",
"value": "Nick Black"
},
{
"context": "urses by Nick Black et al\"\n l2 \"Zig lang by Andrew Kelley & community\"\n l3 \"Liz lang & demo by Jakub",
"end": 6630,
"score": 0.9998934268951416,
"start": 6617,
"tag": "NAME",
"value": "Andrew Kelley"
},
{
"context": "Kelley & community\"\n l3 \"Liz lang & demo by Jakub Dundalek\"\n l4 \"Press q to quit\"\n rows (+ 5 2",
"end": 6689,
"score": 0.9998983144760132,
"start": 6675,
"tag": "NAME",
"value": "Jakub Dundalek"
}
] | src/clj/demo/main.clj | dundalek/notcurses-clojure-example | 13 | (ns demo.main
(:gen-class)
(:import (com.dundalek.notcurses.swig NC notcurses_options ncplane_options NCConstants)
(cz.adamh.utils NativeUtils)
(java.util.concurrent.locks LockSupport)))
(set! *warn-on-reflection* true)
(def BOX_NUM 10)
(def c_red 0xd72c2f)
(def c_yel 0xffd029)
(def c_blu 0x3c497f)
(def c_whi 0xfefefe)
(def box_colors
[c_red
c_whi
c_yel
c_whi
c_blu
c_whi
c_blu
c_yel
c_red
c_whi])
(defmacro nc-err [form]
`(when (< ~form 0)
(throw (RuntimeException. ~(str "Notcurses error calling: " (name (first form)))))))
(defn ncchannel_set [channel rgb]
(if (> channel 0xffffff)
(throw (IllegalArgumentException.))
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
rgb)))
(defn ncchannel_set_alpha [channel alpha]
(if-not (zero? (bit-and-not alpha NCConstants/NC_BG_ALPHA_MASK))
(throw (IllegalArgumentException.))
(bit-or alpha
(bit-and-not channel NCConstants/NC_BG_ALPHA_MASK)
(if (not= alpha NCConstants/NCALPHA_OPAQUE)
NC/NC_BGDEFAULT_MASK
0))))
(defn ncchannels_set_fchannel [channels channel]
(bit-or (bit-and channels 0xffffffff)
(bit-shift-left channel 32)))
(defn ncchannels_set_bchannel [channels channel]
(bit-or (bit-and channels (bit-shift-left 0xffffffff 32))
channel))
(defn ncchannels_set_fg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_fchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_fchannel channels channel)))
(defn ncchannels_set_bg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_bchannel channels channel)))
(defn ncchannels_set_bg_alpha [channels alpha]
(if (= alpha NCConstants/NCALPHA_HIGHCONTRAST) ; forbidden for background alpha
(throw (IllegalArgumentException.))
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set_alpha alpha))]
(ncchannels_set_bchannel channels channel))))
(defn ncchannel_set_rgb8_clipped [channel ^long r ^long g ^long b]
(let [r (Math/max 0 (Math/min r 255))
g (Math/max 0 (Math/min g 255))
b (Math/max 0 (Math/min b 255))
c (bit-or (bit-shift-left r 16)
(bit-shift-left g 8)
b)]
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
c)))
(defn- linear_transition [start end duration diff]
(+ start (Math/round (double (* (- end start)
(/ diff duration))))))
(defn- transition_rgb [start end duration diff]
(let [r (linear_transition (NC/channel_r start) (NC/channel_r end) duration diff)
g (linear_transition (NC/channel_g start) (NC/channel_g end) duration diff)
b (linear_transition (NC/channel_b start) (NC/channel_b end) duration diff)]
(ncchannel_set_rgb8_clipped 0 r g b)))
(defn- transition_box [start_box end_box duration diff]
(mapv (fn [start end]
(linear_transition start end duration diff))
start_box
end_box))
(defn- make_boxes_start [_dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y -1
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_bottom_out [dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y (+ dimy 4)
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_arranged [dimy dimx]
(let [x0 2
x1 (-> dimx (* 40) (quot 100))
x2 (-> dimx (* 55) (quot 100))
x3 (-> dimx (* 85) (quot 100))
x4 dimx
y0 1
y1 (-> dimy (* 18) (quot 100))
y2 (-> dimy (* 22) (quot 100))
y3 (-> dimy (* 35) (quot 100))
y4 (-> dimy (* 55) (quot 100))
y5 (-> dimy (* 70) (quot 100))
y6 dimy]
[[y0 x0 y5 x1]
[y5 x0 y6 x1]
[y0 x1 y2 x2]
[y2 x1 y5 x2]
[y5 x1 y6 x2]
[y0 x2 y3 x3]
[y3 x2 y4 x3]
[y4 x2 y6 x4]
[y0 x3 y1 x4]
[y1 x3 y4 x4]]))
(defn- make_boxes_grid [dimy dimx]
(let [boxh (quot dimy 5)
boxw (* boxh 2)
y0 (-> dimy (* 20) (quot 100))
x0 (-> dimx (* 20) (quot 100))]
(->> (range BOX_NUM)
(mapv (fn [i]
(let [row (quot i 5)
col (mod i 5)
shifted (zero? (mod col 2))
y (+ y0
(* row (+ boxh (quot boxh 2)))
(if shifted (+ (quot boxh 2) 1) 0))
x (+ x0
(* col (+ boxw 2)))]
[y x (+ y boxh) (+ x boxw)]))))))
(defn- box_ylen [box]
(- (get box 2) (get box 0) 1))
(defn- box_xlen [box]
(- (get box 3) (get box 1) 2))
(defn make_box_planes [parent n]
(let [opts (doto (ncplane_options.)
(.setRows 1)
(.setCols 1))]
(->> (range n)
(mapv (fn [_]
(NC/ncplane_create parent opts))))))
(defn- draw_boxes_colored [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [chans (ncchannels_set_bg_rgb 0 color)]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(defn- draw_boxes_gradients [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [ur (bit-or 0xffffff NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or color NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or color NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or 0x000000 NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(defn- draw_boxes_bordered [planes]
(doseq [plane planes]
(NC/ncplane_erase plane)
(nc-err (NC/ncplane_cursor_move_yx plane 0 0))
;; Ignoring error (e.g. the dimensions are too small), when the box fits it will be re-drawn in future frames
(NC/ncplane_rounded_box plane 0 0 (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)))
(defn- reposition_plane [plane box]
(nc-err (NC/ncplane_move_yx plane (get box 0) (get box 1)))
(nc-err (NC/ncplane_resize_simple plane (box_ylen box) (box_xlen box))))
(defn- reposition_planes [planes boxes]
(doseq [[plane box] (map list planes boxes)]
(reposition_plane plane box)))
(defn- make_message_box [parent windowy _windowx]
(let [l1 "Notcurses by Nick Black et al"
l2 "Zig lang by Andrew Kelley & community"
l3 "Liz lang & demo by Jakub Dundalek"
l4 "Press q to quit"
rows (+ 5 2)
opts (doto (ncplane_options.)
(.setRows rows)
(.setCols (-> (count l2) (+ 4)))
(.setX 4)
(.setY (- windowy rows 2)))
plane (NC/ncplane_create parent opts)
chans (-> 0
(ncchannels_set_bg_rgb 0x000000)
(ncchannels_set_bg_alpha NCConstants/NCALPHA_BLEND))
_ (nc-err (NC/ncplane_set_base plane " " 0 chans))
border_chans (ncchannels_set_fg_rgb 0 c_red)]
(NC/ncplane_rounded_box plane 0 border_chans (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)
(nc-err (NC/ncplane_putstr_yx plane 1 2 l1))
(nc-err (NC/ncplane_putstr_yx plane 2 2 l2))
(nc-err (NC/ncplane_putstr_yx plane 3 2 l3))
(nc-err (NC/ncplane_putstr_yx plane 5 2 l4))
plane))
(def NANOSECS_IN_SEC 1000000000)
(def step_ns (/ NANOSECS_IN_SEC 60))
(defn sleep_until_ns [ns]
(let [sleep_ns (- ns (System/nanoTime))]
(when (pos? sleep_ns)
(LockSupport/parkNanos sleep_ns))))
(defn- run_transition [ncs duration ctx render]
(let [time_start (System/nanoTime)]
(loop []
(let [t (System/nanoTime)]
(when (< t (+ time_start duration))
(render ctx (- t time_start) duration)
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))
(recur))))
(render ctx duration duration)
(nc-err (NC/notcurses_render ncs))))
(defn- run_serial_transition [ncs duration render]
(dotimes [i BOX_NUM]
(run_transition ncs duration i render)))
(defn -main []
(NativeUtils/loadLibraryFromJar (str "/" (System/mapLibraryName "notcurses-jni")))
(let [opts (doto (notcurses_options.)
#_(.setFlags NCConstants/NCOPTION_SUPPRESS_BANNERS)
#_(.setLoglevel ncloglevel_e/NCLOGLEVEL_ERROR))
ncs (NC/notcurses_core_init opts nil)
plane (NC/notcurses_stdplane ncs)
dimx (Math/max (NC/ncplane_dim_x plane) (int 80))
dimy (Math/max (NC/ncplane_dim_y plane) (int 25))
box_planes (make_box_planes plane BOX_NUM)
boxes_start (make_boxes_start dimy dimx)
;;boxes_bottom_out (make_boxes_bottom_out dimy dimx)
boxes_grid (make_boxes_grid dimy dimx)
boxes_arranged (make_boxes_arranged dimy dimx)
std_chans (ncchannels_set_bg_rgb 0 0x000000)]
(NC/ncplane_set_base plane " " 0 std_chans)
;;(reposition_planes box_planes boxes_arranged)
(run_serial_transition ncs 300e6
(fn render [i diff duration]
(reposition_plane (get box_planes i) (transition_box (get boxes_start i) (get boxes_grid i) duration diff))
(draw_boxes_bordered box_planes)))
(run_transition ncs 1000e6 nil
(fn render [_ctx diff duration]
(dotimes [i BOX_NUM]
(reposition_plane (get box_planes i) (transition_box (get boxes_grid i) (get boxes_arranged i) duration diff))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (-> 0
(ncchannels_set_bchannel (transition_rgb 0x333333 0x000000 duration diff))
(ncchannels_set_fchannel (transition_rgb 0xF2F2F2 0x000000 duration diff)))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (ncchannels_set_bchannel 0 (transition_rgb 0x000000 (get box_colors i) duration diff))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
ur (bit-or (transition_rgb (get box_colors i) 0xffffff duration diff) NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or (transition_rgb (get box_colors i) 0x000000 duration diff) NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(let [message_box (make_message_box plane dimy dimx)]
(run_transition ncs 300e6 {:from (- (NC/ncplane_dim_x message_box))
:to (NC/ncplane_x message_box)}
(fn render [{:keys [from to]} diff duration]
(let [x (linear_transition from to duration diff)]
(nc-err (NC/ncplane_move_yx message_box (NC/ncplane_y message_box) x))))))
;;(draw_boxes_gradients box_planes)
;;(nc-err (NC/notcurses_render ncs))
;;(NC/notcurses_getc_blocking ncs nil)
;;(Thread/sleep 1000)
(let [duration 1000e6]
(loop [iter 0
time_start (System/nanoTime)]
(let [t (System/nanoTime)]
(dotimes [i BOX_NUM]
(let [plane (get box_planes i)
colors [(get box_colors i)
0xffffff
(get box_colors i)
0x000000]
corners (vec (for [j (range 4)]
(bit-or NCConstants/NC_BGDEFAULT_MASK
(transition_rgb (get colors (mod (+ iter j) 4))
(get colors (mod (+ j iter 1) 4))
duration
(- t time_start)))))]
(nc-err (NC/ncplane_highgradient plane
(get corners 0)
(get corners 1)
(get corners 3)
(get corners 2)
(dec (NC/ncplane_dim_y plane))
(dec (NC/ncplane_dim_x plane))))
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))))
(let [keypress (NC/notcurses_getc_nblock ncs nil)]
(when (not= keypress (int \q))
(if (< t (+ time_start duration))
(recur iter time_start)
(recur (inc iter) (System/nanoTime))))))))
(NC/notcurses_stop ncs)))
| 7646 | (ns demo.main
(:gen-class)
(:import (com.dundalek.notcurses.swig NC notcurses_options ncplane_options NCConstants)
(cz.adamh.utils NativeUtils)
(java.util.concurrent.locks LockSupport)))
(set! *warn-on-reflection* true)
(def BOX_NUM 10)
(def c_red 0xd72c2f)
(def c_yel 0xffd029)
(def c_blu 0x3c497f)
(def c_whi 0xfefefe)
(def box_colors
[c_red
c_whi
c_yel
c_whi
c_blu
c_whi
c_blu
c_yel
c_red
c_whi])
(defmacro nc-err [form]
`(when (< ~form 0)
(throw (RuntimeException. ~(str "Notcurses error calling: " (name (first form)))))))
(defn ncchannel_set [channel rgb]
(if (> channel 0xffffff)
(throw (IllegalArgumentException.))
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
rgb)))
(defn ncchannel_set_alpha [channel alpha]
(if-not (zero? (bit-and-not alpha NCConstants/NC_BG_ALPHA_MASK))
(throw (IllegalArgumentException.))
(bit-or alpha
(bit-and-not channel NCConstants/NC_BG_ALPHA_MASK)
(if (not= alpha NCConstants/NCALPHA_OPAQUE)
NC/NC_BGDEFAULT_MASK
0))))
(defn ncchannels_set_fchannel [channels channel]
(bit-or (bit-and channels 0xffffffff)
(bit-shift-left channel 32)))
(defn ncchannels_set_bchannel [channels channel]
(bit-or (bit-and channels (bit-shift-left 0xffffffff 32))
channel))
(defn ncchannels_set_fg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_fchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_fchannel channels channel)))
(defn ncchannels_set_bg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_bchannel channels channel)))
(defn ncchannels_set_bg_alpha [channels alpha]
(if (= alpha NCConstants/NCALPHA_HIGHCONTRAST) ; forbidden for background alpha
(throw (IllegalArgumentException.))
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set_alpha alpha))]
(ncchannels_set_bchannel channels channel))))
(defn ncchannel_set_rgb8_clipped [channel ^long r ^long g ^long b]
(let [r (Math/max 0 (Math/min r 255))
g (Math/max 0 (Math/min g 255))
b (Math/max 0 (Math/min b 255))
c (bit-or (bit-shift-left r 16)
(bit-shift-left g 8)
b)]
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
c)))
(defn- linear_transition [start end duration diff]
(+ start (Math/round (double (* (- end start)
(/ diff duration))))))
(defn- transition_rgb [start end duration diff]
(let [r (linear_transition (NC/channel_r start) (NC/channel_r end) duration diff)
g (linear_transition (NC/channel_g start) (NC/channel_g end) duration diff)
b (linear_transition (NC/channel_b start) (NC/channel_b end) duration diff)]
(ncchannel_set_rgb8_clipped 0 r g b)))
(defn- transition_box [start_box end_box duration diff]
(mapv (fn [start end]
(linear_transition start end duration diff))
start_box
end_box))
(defn- make_boxes_start [_dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y -1
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_bottom_out [dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y (+ dimy 4)
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_arranged [dimy dimx]
(let [x0 2
x1 (-> dimx (* 40) (quot 100))
x2 (-> dimx (* 55) (quot 100))
x3 (-> dimx (* 85) (quot 100))
x4 dimx
y0 1
y1 (-> dimy (* 18) (quot 100))
y2 (-> dimy (* 22) (quot 100))
y3 (-> dimy (* 35) (quot 100))
y4 (-> dimy (* 55) (quot 100))
y5 (-> dimy (* 70) (quot 100))
y6 dimy]
[[y0 x0 y5 x1]
[y5 x0 y6 x1]
[y0 x1 y2 x2]
[y2 x1 y5 x2]
[y5 x1 y6 x2]
[y0 x2 y3 x3]
[y3 x2 y4 x3]
[y4 x2 y6 x4]
[y0 x3 y1 x4]
[y1 x3 y4 x4]]))
(defn- make_boxes_grid [dimy dimx]
(let [boxh (quot dimy 5)
boxw (* boxh 2)
y0 (-> dimy (* 20) (quot 100))
x0 (-> dimx (* 20) (quot 100))]
(->> (range BOX_NUM)
(mapv (fn [i]
(let [row (quot i 5)
col (mod i 5)
shifted (zero? (mod col 2))
y (+ y0
(* row (+ boxh (quot boxh 2)))
(if shifted (+ (quot boxh 2) 1) 0))
x (+ x0
(* col (+ boxw 2)))]
[y x (+ y boxh) (+ x boxw)]))))))
(defn- box_ylen [box]
(- (get box 2) (get box 0) 1))
(defn- box_xlen [box]
(- (get box 3) (get box 1) 2))
(defn make_box_planes [parent n]
(let [opts (doto (ncplane_options.)
(.setRows 1)
(.setCols 1))]
(->> (range n)
(mapv (fn [_]
(NC/ncplane_create parent opts))))))
(defn- draw_boxes_colored [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [chans (ncchannels_set_bg_rgb 0 color)]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(defn- draw_boxes_gradients [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [ur (bit-or 0xffffff NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or color NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or color NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or 0x000000 NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(defn- draw_boxes_bordered [planes]
(doseq [plane planes]
(NC/ncplane_erase plane)
(nc-err (NC/ncplane_cursor_move_yx plane 0 0))
;; Ignoring error (e.g. the dimensions are too small), when the box fits it will be re-drawn in future frames
(NC/ncplane_rounded_box plane 0 0 (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)))
(defn- reposition_plane [plane box]
(nc-err (NC/ncplane_move_yx plane (get box 0) (get box 1)))
(nc-err (NC/ncplane_resize_simple plane (box_ylen box) (box_xlen box))))
(defn- reposition_planes [planes boxes]
(doseq [[plane box] (map list planes boxes)]
(reposition_plane plane box)))
(defn- make_message_box [parent windowy _windowx]
(let [l1 "Notcurses by <NAME> et al"
l2 "Zig lang by <NAME> & community"
l3 "Liz lang & demo by <NAME>"
l4 "Press q to quit"
rows (+ 5 2)
opts (doto (ncplane_options.)
(.setRows rows)
(.setCols (-> (count l2) (+ 4)))
(.setX 4)
(.setY (- windowy rows 2)))
plane (NC/ncplane_create parent opts)
chans (-> 0
(ncchannels_set_bg_rgb 0x000000)
(ncchannels_set_bg_alpha NCConstants/NCALPHA_BLEND))
_ (nc-err (NC/ncplane_set_base plane " " 0 chans))
border_chans (ncchannels_set_fg_rgb 0 c_red)]
(NC/ncplane_rounded_box plane 0 border_chans (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)
(nc-err (NC/ncplane_putstr_yx plane 1 2 l1))
(nc-err (NC/ncplane_putstr_yx plane 2 2 l2))
(nc-err (NC/ncplane_putstr_yx plane 3 2 l3))
(nc-err (NC/ncplane_putstr_yx plane 5 2 l4))
plane))
(def NANOSECS_IN_SEC 1000000000)
(def step_ns (/ NANOSECS_IN_SEC 60))
(defn sleep_until_ns [ns]
(let [sleep_ns (- ns (System/nanoTime))]
(when (pos? sleep_ns)
(LockSupport/parkNanos sleep_ns))))
(defn- run_transition [ncs duration ctx render]
(let [time_start (System/nanoTime)]
(loop []
(let [t (System/nanoTime)]
(when (< t (+ time_start duration))
(render ctx (- t time_start) duration)
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))
(recur))))
(render ctx duration duration)
(nc-err (NC/notcurses_render ncs))))
(defn- run_serial_transition [ncs duration render]
(dotimes [i BOX_NUM]
(run_transition ncs duration i render)))
(defn -main []
(NativeUtils/loadLibraryFromJar (str "/" (System/mapLibraryName "notcurses-jni")))
(let [opts (doto (notcurses_options.)
#_(.setFlags NCConstants/NCOPTION_SUPPRESS_BANNERS)
#_(.setLoglevel ncloglevel_e/NCLOGLEVEL_ERROR))
ncs (NC/notcurses_core_init opts nil)
plane (NC/notcurses_stdplane ncs)
dimx (Math/max (NC/ncplane_dim_x plane) (int 80))
dimy (Math/max (NC/ncplane_dim_y plane) (int 25))
box_planes (make_box_planes plane BOX_NUM)
boxes_start (make_boxes_start dimy dimx)
;;boxes_bottom_out (make_boxes_bottom_out dimy dimx)
boxes_grid (make_boxes_grid dimy dimx)
boxes_arranged (make_boxes_arranged dimy dimx)
std_chans (ncchannels_set_bg_rgb 0 0x000000)]
(NC/ncplane_set_base plane " " 0 std_chans)
;;(reposition_planes box_planes boxes_arranged)
(run_serial_transition ncs 300e6
(fn render [i diff duration]
(reposition_plane (get box_planes i) (transition_box (get boxes_start i) (get boxes_grid i) duration diff))
(draw_boxes_bordered box_planes)))
(run_transition ncs 1000e6 nil
(fn render [_ctx diff duration]
(dotimes [i BOX_NUM]
(reposition_plane (get box_planes i) (transition_box (get boxes_grid i) (get boxes_arranged i) duration diff))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (-> 0
(ncchannels_set_bchannel (transition_rgb 0x333333 0x000000 duration diff))
(ncchannels_set_fchannel (transition_rgb 0xF2F2F2 0x000000 duration diff)))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (ncchannels_set_bchannel 0 (transition_rgb 0x000000 (get box_colors i) duration diff))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
ur (bit-or (transition_rgb (get box_colors i) 0xffffff duration diff) NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or (transition_rgb (get box_colors i) 0x000000 duration diff) NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(let [message_box (make_message_box plane dimy dimx)]
(run_transition ncs 300e6 {:from (- (NC/ncplane_dim_x message_box))
:to (NC/ncplane_x message_box)}
(fn render [{:keys [from to]} diff duration]
(let [x (linear_transition from to duration diff)]
(nc-err (NC/ncplane_move_yx message_box (NC/ncplane_y message_box) x))))))
;;(draw_boxes_gradients box_planes)
;;(nc-err (NC/notcurses_render ncs))
;;(NC/notcurses_getc_blocking ncs nil)
;;(Thread/sleep 1000)
(let [duration 1000e6]
(loop [iter 0
time_start (System/nanoTime)]
(let [t (System/nanoTime)]
(dotimes [i BOX_NUM]
(let [plane (get box_planes i)
colors [(get box_colors i)
0xffffff
(get box_colors i)
0x000000]
corners (vec (for [j (range 4)]
(bit-or NCConstants/NC_BGDEFAULT_MASK
(transition_rgb (get colors (mod (+ iter j) 4))
(get colors (mod (+ j iter 1) 4))
duration
(- t time_start)))))]
(nc-err (NC/ncplane_highgradient plane
(get corners 0)
(get corners 1)
(get corners 3)
(get corners 2)
(dec (NC/ncplane_dim_y plane))
(dec (NC/ncplane_dim_x plane))))
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))))
(let [keypress (NC/notcurses_getc_nblock ncs nil)]
(when (not= keypress (int \q))
(if (< t (+ time_start duration))
(recur iter time_start)
(recur (inc iter) (System/nanoTime))))))))
(NC/notcurses_stop ncs)))
| true | (ns demo.main
(:gen-class)
(:import (com.dundalek.notcurses.swig NC notcurses_options ncplane_options NCConstants)
(cz.adamh.utils NativeUtils)
(java.util.concurrent.locks LockSupport)))
(set! *warn-on-reflection* true)
(def BOX_NUM 10)
(def c_red 0xd72c2f)
(def c_yel 0xffd029)
(def c_blu 0x3c497f)
(def c_whi 0xfefefe)
(def box_colors
[c_red
c_whi
c_yel
c_whi
c_blu
c_whi
c_blu
c_yel
c_red
c_whi])
(defmacro nc-err [form]
`(when (< ~form 0)
(throw (RuntimeException. ~(str "Notcurses error calling: " (name (first form)))))))
(defn ncchannel_set [channel rgb]
(if (> channel 0xffffff)
(throw (IllegalArgumentException.))
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
rgb)))
(defn ncchannel_set_alpha [channel alpha]
(if-not (zero? (bit-and-not alpha NCConstants/NC_BG_ALPHA_MASK))
(throw (IllegalArgumentException.))
(bit-or alpha
(bit-and-not channel NCConstants/NC_BG_ALPHA_MASK)
(if (not= alpha NCConstants/NCALPHA_OPAQUE)
NC/NC_BGDEFAULT_MASK
0))))
(defn ncchannels_set_fchannel [channels channel]
(bit-or (bit-and channels 0xffffffff)
(bit-shift-left channel 32)))
(defn ncchannels_set_bchannel [channels channel]
(bit-or (bit-and channels (bit-shift-left 0xffffffff 32))
channel))
(defn ncchannels_set_fg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_fchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_fchannel channels channel)))
(defn ncchannels_set_bg_rgb [channels rgb]
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set rgb))]
(ncchannels_set_bchannel channels channel)))
(defn ncchannels_set_bg_alpha [channels alpha]
(if (= alpha NCConstants/NCALPHA_HIGHCONTRAST) ; forbidden for background alpha
(throw (IllegalArgumentException.))
(let [channel (-> (NC/ncchannels_bchannel channels)
(ncchannel_set_alpha alpha))]
(ncchannels_set_bchannel channels channel))))
(defn ncchannel_set_rgb8_clipped [channel ^long r ^long g ^long b]
(let [r (Math/max 0 (Math/min r 255))
g (Math/max 0 (Math/min g 255))
b (Math/max 0 (Math/min b 255))
c (bit-or (bit-shift-left r 16)
(bit-shift-left g 8)
b)]
(bit-or (bit-and-not channel NCConstants/NC_BG_RGB_MASK)
NCConstants/NC_BGDEFAULT_MASK
c)))
(defn- linear_transition [start end duration diff]
(+ start (Math/round (double (* (- end start)
(/ diff duration))))))
(defn- transition_rgb [start end duration diff]
(let [r (linear_transition (NC/channel_r start) (NC/channel_r end) duration diff)
g (linear_transition (NC/channel_g start) (NC/channel_g end) duration diff)
b (linear_transition (NC/channel_b start) (NC/channel_b end) duration diff)]
(ncchannel_set_rgb8_clipped 0 r g b)))
(defn- transition_box [start_box end_box duration diff]
(mapv (fn [start end]
(linear_transition start end duration diff))
start_box
end_box))
(defn- make_boxes_start [_dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y -1
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_bottom_out [dimy dimx]
(->> (range BOX_NUM)
(mapv (fn [_]
(let [y (+ dimy 4)
x (quot dimx 2)]
[y x (+ y 2) (+ x 4)])))))
(defn- make_boxes_arranged [dimy dimx]
(let [x0 2
x1 (-> dimx (* 40) (quot 100))
x2 (-> dimx (* 55) (quot 100))
x3 (-> dimx (* 85) (quot 100))
x4 dimx
y0 1
y1 (-> dimy (* 18) (quot 100))
y2 (-> dimy (* 22) (quot 100))
y3 (-> dimy (* 35) (quot 100))
y4 (-> dimy (* 55) (quot 100))
y5 (-> dimy (* 70) (quot 100))
y6 dimy]
[[y0 x0 y5 x1]
[y5 x0 y6 x1]
[y0 x1 y2 x2]
[y2 x1 y5 x2]
[y5 x1 y6 x2]
[y0 x2 y3 x3]
[y3 x2 y4 x3]
[y4 x2 y6 x4]
[y0 x3 y1 x4]
[y1 x3 y4 x4]]))
(defn- make_boxes_grid [dimy dimx]
(let [boxh (quot dimy 5)
boxw (* boxh 2)
y0 (-> dimy (* 20) (quot 100))
x0 (-> dimx (* 20) (quot 100))]
(->> (range BOX_NUM)
(mapv (fn [i]
(let [row (quot i 5)
col (mod i 5)
shifted (zero? (mod col 2))
y (+ y0
(* row (+ boxh (quot boxh 2)))
(if shifted (+ (quot boxh 2) 1) 0))
x (+ x0
(* col (+ boxw 2)))]
[y x (+ y boxh) (+ x boxw)]))))))
(defn- box_ylen [box]
(- (get box 2) (get box 0) 1))
(defn- box_xlen [box]
(- (get box 3) (get box 1) 2))
(defn make_box_planes [parent n]
(let [opts (doto (ncplane_options.)
(.setRows 1)
(.setCols 1))]
(->> (range n)
(mapv (fn [_]
(NC/ncplane_create parent opts))))))
(defn- draw_boxes_colored [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [chans (ncchannels_set_bg_rgb 0 color)]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(defn- draw_boxes_gradients [planes]
(doseq [[plane color] (map list planes box_colors)]
(let [ur (bit-or 0xffffff NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or color NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or color NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or 0x000000 NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(defn- draw_boxes_bordered [planes]
(doseq [plane planes]
(NC/ncplane_erase plane)
(nc-err (NC/ncplane_cursor_move_yx plane 0 0))
;; Ignoring error (e.g. the dimensions are too small), when the box fits it will be re-drawn in future frames
(NC/ncplane_rounded_box plane 0 0 (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)))
(defn- reposition_plane [plane box]
(nc-err (NC/ncplane_move_yx plane (get box 0) (get box 1)))
(nc-err (NC/ncplane_resize_simple plane (box_ylen box) (box_xlen box))))
(defn- reposition_planes [planes boxes]
(doseq [[plane box] (map list planes boxes)]
(reposition_plane plane box)))
(defn- make_message_box [parent windowy _windowx]
(let [l1 "Notcurses by PI:NAME:<NAME>END_PI et al"
l2 "Zig lang by PI:NAME:<NAME>END_PI & community"
l3 "Liz lang & demo by PI:NAME:<NAME>END_PI"
l4 "Press q to quit"
rows (+ 5 2)
opts (doto (ncplane_options.)
(.setRows rows)
(.setCols (-> (count l2) (+ 4)))
(.setX 4)
(.setY (- windowy rows 2)))
plane (NC/ncplane_create parent opts)
chans (-> 0
(ncchannels_set_bg_rgb 0x000000)
(ncchannels_set_bg_alpha NCConstants/NCALPHA_BLEND))
_ (nc-err (NC/ncplane_set_base plane " " 0 chans))
border_chans (ncchannels_set_fg_rgb 0 c_red)]
(NC/ncplane_rounded_box plane 0 border_chans (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)) 0)
(nc-err (NC/ncplane_putstr_yx plane 1 2 l1))
(nc-err (NC/ncplane_putstr_yx plane 2 2 l2))
(nc-err (NC/ncplane_putstr_yx plane 3 2 l3))
(nc-err (NC/ncplane_putstr_yx plane 5 2 l4))
plane))
(def NANOSECS_IN_SEC 1000000000)
(def step_ns (/ NANOSECS_IN_SEC 60))
(defn sleep_until_ns [ns]
(let [sleep_ns (- ns (System/nanoTime))]
(when (pos? sleep_ns)
(LockSupport/parkNanos sleep_ns))))
(defn- run_transition [ncs duration ctx render]
(let [time_start (System/nanoTime)]
(loop []
(let [t (System/nanoTime)]
(when (< t (+ time_start duration))
(render ctx (- t time_start) duration)
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))
(recur))))
(render ctx duration duration)
(nc-err (NC/notcurses_render ncs))))
(defn- run_serial_transition [ncs duration render]
(dotimes [i BOX_NUM]
(run_transition ncs duration i render)))
(defn -main []
(NativeUtils/loadLibraryFromJar (str "/" (System/mapLibraryName "notcurses-jni")))
(let [opts (doto (notcurses_options.)
#_(.setFlags NCConstants/NCOPTION_SUPPRESS_BANNERS)
#_(.setLoglevel ncloglevel_e/NCLOGLEVEL_ERROR))
ncs (NC/notcurses_core_init opts nil)
plane (NC/notcurses_stdplane ncs)
dimx (Math/max (NC/ncplane_dim_x plane) (int 80))
dimy (Math/max (NC/ncplane_dim_y plane) (int 25))
box_planes (make_box_planes plane BOX_NUM)
boxes_start (make_boxes_start dimy dimx)
;;boxes_bottom_out (make_boxes_bottom_out dimy dimx)
boxes_grid (make_boxes_grid dimy dimx)
boxes_arranged (make_boxes_arranged dimy dimx)
std_chans (ncchannels_set_bg_rgb 0 0x000000)]
(NC/ncplane_set_base plane " " 0 std_chans)
;;(reposition_planes box_planes boxes_arranged)
(run_serial_transition ncs 300e6
(fn render [i diff duration]
(reposition_plane (get box_planes i) (transition_box (get boxes_start i) (get boxes_grid i) duration diff))
(draw_boxes_bordered box_planes)))
(run_transition ncs 1000e6 nil
(fn render [_ctx diff duration]
(dotimes [i BOX_NUM]
(reposition_plane (get box_planes i) (transition_box (get boxes_grid i) (get boxes_arranged i) duration diff))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (-> 0
(ncchannels_set_bchannel (transition_rgb 0x333333 0x000000 duration diff))
(ncchannels_set_fchannel (transition_rgb 0xF2F2F2 0x000000 duration diff)))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(draw_boxes_bordered box_planes))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
chans (ncchannels_set_bchannel 0 (transition_rgb 0x000000 (get box_colors i) duration diff))]
(nc-err (NC/ncplane_set_base plane " " 0 chans))
(NC/ncplane_erase plane))))
(run_serial_transition ncs 150e6
(fn render [i diff duration]
(let [plane (get box_planes i)
ur (bit-or (transition_rgb (get box_colors i) 0xffffff duration diff) NCConstants/NC_BGDEFAULT_MASK)
ul (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
lr (bit-or (get box_colors i) NCConstants/NC_BGDEFAULT_MASK)
ll (bit-or (transition_rgb (get box_colors i) 0x000000 duration diff) NCConstants/NC_BGDEFAULT_MASK)]
(nc-err (NC/ncplane_highgradient plane ul ur ll lr (dec (NC/ncplane_dim_y plane)) (dec (NC/ncplane_dim_x plane)))))))
(let [message_box (make_message_box plane dimy dimx)]
(run_transition ncs 300e6 {:from (- (NC/ncplane_dim_x message_box))
:to (NC/ncplane_x message_box)}
(fn render [{:keys [from to]} diff duration]
(let [x (linear_transition from to duration diff)]
(nc-err (NC/ncplane_move_yx message_box (NC/ncplane_y message_box) x))))))
;;(draw_boxes_gradients box_planes)
;;(nc-err (NC/notcurses_render ncs))
;;(NC/notcurses_getc_blocking ncs nil)
;;(Thread/sleep 1000)
(let [duration 1000e6]
(loop [iter 0
time_start (System/nanoTime)]
(let [t (System/nanoTime)]
(dotimes [i BOX_NUM]
(let [plane (get box_planes i)
colors [(get box_colors i)
0xffffff
(get box_colors i)
0x000000]
corners (vec (for [j (range 4)]
(bit-or NCConstants/NC_BGDEFAULT_MASK
(transition_rgb (get colors (mod (+ iter j) 4))
(get colors (mod (+ j iter 1) 4))
duration
(- t time_start)))))]
(nc-err (NC/ncplane_highgradient plane
(get corners 0)
(get corners 1)
(get corners 3)
(get corners 2)
(dec (NC/ncplane_dim_y plane))
(dec (NC/ncplane_dim_x plane))))
(nc-err (NC/notcurses_render ncs))
(sleep_until_ns (+ t step_ns))))
(let [keypress (NC/notcurses_getc_nblock ncs nil)]
(when (not= keypress (int \q))
(if (< t (+ time_start duration))
(recur iter time_start)
(recur (inc iter) (System/nanoTime))))))))
(NC/notcurses_stop ncs)))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9997984170913696,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | data/clojure/4afcd83dfeebd356d472cc59a6564ef5_core_deftype.clj | maxim5/code-inspector | 5 | ; 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.
(in-ns 'clojure.core)
;;;;;;;;;;;;;;;;;;;;;;;;;;;; definterface ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;for now, built on gen-interface
(defmacro definterface
[name & sigs]
(let [tag (fn [x] (or (:tag (meta x)) Object))
psig (fn [[name [& args]]]
(vector name (vec (map tag args)) (tag name)))]
`(gen-interface :name ~(symbol (str *ns* "." name)) :methods ~(vec (map psig sigs)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; reify/deftype ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- parse-opts [s]
(loop [opts {} [k v & rs :as s] s]
(if (keyword? k)
(recur (assoc opts k v) rs)
[opts s])))
(defn- parse-impls [specs]
(loop [ret {} s specs]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret)))
(defn- parse-opts+specs [opts+specs]
(let [[opts specs] (parse-opts opts+specs)
impls (parse-impls specs)
interfaces (-> (map #(if (var? (resolve %))
(:on (deref (resolve %)))
%)
(keys impls))
set
(disj 'Object 'java.lang.Object)
vec)
methods (mapcat #(map (fn [[nm [& args] & body]]
`(~nm [~(:as opts) ~@args] ~@body)) %)
(vals impls))]
[interfaces methods opts]))
(defmacro reify
"reify is a macro with the following structure:
(reify options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of the protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
The return type can be indicated by a type hint on the method name,
and arg types can be indicated by a type hint on arg names. If you
leave out all hints, reify will try to match on same name/arity
method in the protocol(s)/interface(s) - this is preferred. If you
supply any hints at all, no inference is done, so all hints (or
default of Object) must be correct, for both arguments and return
type. If a method is overloaded in a protocol/interface, multiple
independent method definitions must be supplied. If overloaded with
same arity in an interface you must specify complete hints to
disambiguate - a missing hint implies Object.
recur works to method heads The method bodies of reify are lexical
closures, and can refer to the surrounding local scope:
(str (let [f \"foo\"]
(reify Object
(toString [] f))))
== \"foo\"
(seq (let [f \"foo\"]
(reify clojure.lang.Seqable
(seq [] (seq f)))))
== (\\f \\o \\o))"
[& opts+specs]
(let [[interfaces methods] (parse-opts+specs opts+specs)]
`(reify* ~interfaces ~@methods)))
(defn hash-combine [x y]
(clojure.lang.Util/hashCombine x (clojure.lang.Util/hash y)))
(defn munge [s]
((if (symbol? s) symbol str) (clojure.lang.Compiler/munge (str s))))
(defn- emit-deftype*
"Do not use this directly - use deftype"
[tagname name fields interfaces methods]
(let [tag (keyword (str *ns*) (str tagname))
classname (symbol (str *ns* "." name))
interfaces (vec interfaces)
interface-set (set (map resolve interfaces))
methodname-set (set (map first methods))
dynamic-type (contains? interface-set clojure.lang.IDynamicType)
implement? (fn [iface] (not (contains? interface-set iface)))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap)]
(letfn
[(eqhash [[i m]]
(if (not (or (contains? methodname-set 'equals) (contains? methodname-set 'hashCode)))
[i
(conj m
`(hashCode [~'this] (-> ~tag hash ~@(map #(list `hash-combine %) (remove #{'__meta} fields))))
`(equals [~'this ~'o]
(boolean
(or (identical? ~'this ~'o)
(when (instance? clojure.lang.IDynamicType ~'o)
(let [~'o ~(with-meta 'o {:tag 'clojure.lang.IDynamicType})]
(and (= ~tag (.getDynamicType ~'o))
~@(map (fn [fld] `(= ~fld (.getDynamicField ~'o ~(keyword fld) ~'this))) base-fields)
(= ~'__extmap (.getExtensionMap ~'o)))))))))]
[i m]))
(iobj [[i m]]
(if (and (implement? clojure.lang.IObj) (implement? clojure.lang.IMeta))
[(conj i 'clojure.lang.IObj)
(conj m `(meta [~'this] ~'__meta)
`(withMeta [~'this ~'m] (new ~tagname ~@(replace {'__meta 'm} fields))))]
[i m]))
(ilookup [[i m]]
(if (not (methodname-set 'valAt))
[(conj i 'clojure.lang.ILookup 'clojure.lang.IKeywordLookup)
(conj m `(valAt [~'this k#] (.valAt ~'this k# nil))
`(valAt [~'this k# else#]
(case k# ~@(mapcat (fn [fld] [(keyword fld) fld])
base-fields)
(get ~'__extmap k# else#)))
`(getLookupThunk [~'this k#]
(case k#
~@(mapcat
(fn [fld]
(let [cstr (str (clojure.core/name classname) "$__lookup__" (clojure.core/name fld))]
[(keyword fld)
`(-> ~cstr (Class/forName) (.newInstance))]))
base-fields)
nil)))]
[i m]))
(idynamictype [[i m]]
[(conj i 'clojure.lang.IDynamicType)
(conj m
`(getDynamicType [~'this] ~tag)
`(getExtensionMap [~'this] ~'__extmap)
`(getDynamicField [~'this k# else#]
(condp identical? k# ~@(mapcat (fn [fld] [(keyword fld) fld]) base-fields)
(get ~'__extmap k# else#))))])
(imap [[i m]]
(if (and (interface-set clojure.lang.IPersistentMap) (not (methodname-set 'assoc)))
[i
(conj m
`(count [~'this] (+ ~(count base-fields) (count ~'__extmap)))
`(empty [~'this] (throw (UnsupportedOperationException. (str "Can't create empty: " ~(str classname)))))
`(cons [~'this e#] (let [[k# v#] e#] (.assoc ~'this k# v#)))
`(equiv [~'this o#] (.equals ~'this o#))
`(containsKey [~'this k#] (not (identical? ~'this (.valAt ~'this k# ~'this))))
`(entryAt [~'this k#] (let [v# (.valAt ~'this k# ~'this)]
(when-not (identical? ~'this v#)
(clojure.lang.MapEntry. k# v#))))
`(seq [~'this] (concat [~@(map #(list `new `clojure.lang.MapEntry (keyword %) %) base-fields)]
~'__extmap))
(let [gk (gensym) gv (gensym)]
`(assoc [~'this ~gk ~gv]
(condp identical? ~gk
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gv} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap} fields) (assoc ~'__extmap ~gk ~gv)))))
`(without [~'this k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} ~'this) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap} fields)
(not-empty (dissoc ~'__extmap k#))))))]
[i m]))]
(let [[i m] (-> [interfaces methods] eqhash iobj ilookup imap idynamictype)]
`(deftype* ~tagname ~classname ~(conj hinted-fields '__meta '__extmap)
:implements ~(vec i)
~@m)))))
(defmacro deftype
"Alpha - subject to change
(deftype name [fields*] options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of a protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Dynamically generates compiled bytecode for an anonymous class with
the given fields, and, optionally, methods for protocols and/or
interfaces. The Name will be used to create a dynamic type tag
keyword of the form :current.ns/Name. This tag will be returned
from (type an-instance).
A factory function of current.ns/Name will be defined,
overloaded on 2 arities, the first taking the designated fields in
the same order specified, and the second taking the fields followed
by a metadata map (nil for none) and an extension field map (nil for
none).
The class will have the (by default, immutable) fields named by
fields, which can have type hints. Protocols/interfaces and methods
are optional. The only methods that can be supplied are those
declared in the protocols/interfaces. Note that method bodies are
not closures, the local environment includes only the named fields,
and those fields can be accessed directy. Fields can be qualified
with the metadata :volatile-mutable true or :unsynchronized-mutable
true, at which point (set! afield aval) will be supported in method
bodies. Note well that mutable fields are extremely difficult to use
correctly, and are present only to facilitate the building of higher
level constructs, such as Clojure's reference types, in Clojure
itself. They are for experts only - if the semantics and
implications of :volatile-mutable or :unsynchronized-mutable are not
immediately apparent to you, you should not be using them.
Method definitions take the form:
(methodname [args*] body)
The argument and return types can be hinted on the arg and
methodname symbols. If not supplied, they will be inferred, so type
hints should be reserved for disambiguation.
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
In the method bodies, the (unqualified) name can be used to name the
class (for calls to new, instance? etc).
The class will have implementations of two (clojure.lang) interfaces
generated automatically: IObj (metadata support), ILookup (get and
keyword lookup for fields). If you specify IPersistentMap as an
interface, but don't define methods for it, an implementation will
be generated automatically.
In addition, unless you supply a version of hashCode or equals,
deftype/class will define type-and-value-based equality and
hashCode.
When AOT compiling, generates compiled bytecode for a class with the
given name (a symbol), prepends the current ns as the package, and
writes the .class file to the *compile-path* directory.
Two constructors will be defined, one taking the designated fields
followed by a metadata map (nil for none) and an extension field
map (nil for none), and one taking only the fields (using nil for
meta and extension fields).
When dynamically evaluated, the class will have a generated name."
[name [& fields] & opts+specs]
(let [gname (if *compile-files* name (gensym (str name "__")))
[interfaces methods opts] (parse-opts+specs opts+specs)
classname (symbol (str *ns* "." gname))
tag (keyword (str *ns*) (str name))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))]
`(do
~(emit-deftype* name gname (vec hinted-fields) (vec interfaces) methods)
(defmethod print-method ~tag [o# w#]
((var print-deftype) ~(vec (map #(-> % str keyword) fields)) o# w#))
(defn ~name
([~@fields] (new ~classname ~@fields nil nil))
([~@fields meta# extmap#] (new ~classname ~@fields meta# extmap#))))))
(defn- print-deftype [fields, #^clojure.lang.IDynamicType o, #^Writer w]
(print-meta o w)
(.write w "#:")
(.write w (str (name (.getDynamicType o))))
(print-map
(concat
(map #(clojure.lang.MapEntry. % (.getDynamicField o % nil)) fields)
(.getExtensionMap o))
pr-on w))
;;;;;;;;;;;;;;;;;;;;;;; protocols ;;;;;;;;;;;;;;;;;;;;;;;;
(defn dtype
"Returns the dynamic type of x, or its Class if none"
[x]
(if (instance? clojure.lang.IDynamicType x)
(let [x #^ clojure.lang.IDynamicType x]
(.getDynamicType x))
(class x)))
(defn- expand-method-impl-cache [#^clojure.lang.MethodImplCache cache c f]
(let [cs (into {} (remove (fn [[c f]] (nil? f)) (map vec (partition 2 (.table cache)))))
cs (assoc cs c f)
[shift mask] (min-hash (keys cs))
table (make-array Object (* 2 (inc mask)))
table (reduce (fn [#^objects t [c f]]
(let [i (* 2 (int (shift-mask shift mask (hash c))))]
(aset t i c)
(aset t (inc i) f)
t))
table cs)]
(clojure.lang.MethodImplCache. (.protocol cache) (.methodk cache) shift mask table)))
(defn- super-chain [#^Class c]
(when c
(cons c (super-chain (.getSuperclass c)))))
(defn find-protocol-impl [protocol x]
(if (and (:on-interface protocol) (instance? (:on-interface protocol) x))
x
(let [t (dtype x)
c (class x)
impl #(get (:impls protocol) %)]
(or (impl t)
(impl c)
(and c (or (first (remove nil? (map impl (butlast (super-chain c)))))
(first (remove nil? (map impl (disj (supers c) Object))))
(impl Object)))))))
(defn find-protocol-method [protocol methodk x]
(get (find-protocol-impl protocol x) methodk))
(defn extends?
"Returns true if atype explicitly extends protocol"
[protocol atype]
(when (get (:impls protocol) atype) true))
(defn extenders
"Returns a collection of the types explicitly extending protocol"
[protocol]
(keys (:impls protocol)))
(defn satisfies?
"Returns true if x satisfies the protocol"
[protocol x]
(when
(or (and (:on-interface protocol) (instance? (:on-interface protocol) x))
(find-protocol-impl protocol x))
true))
(defn -cache-protocol-fn [#^clojure.lang.AFunction pf x]
(let [cache (.__methodImplCache pf)
f (find-protocol-method (.protocol cache) (.methodk cache) x)]
(when-not f
(throw (IllegalArgumentException. (str "No implementation of method: " (.methodk cache)
" of protocol: " (:var (.protocol cache))
" found for class: " (if (nil? x) "nil" (.getName (class x)))))))
(set! (.__methodImplCache pf) (expand-method-impl-cache cache (class x) f))
f))
(defn- emit-method-builder [on-interface method on-method arglists]
(let [methodk (keyword method)
gthis (with-meta (gensym) {:tag 'clojure.lang.AFunction})]
`(fn [cache#]
(let [#^clojure.lang.AFunction f#
(fn ~gthis
~@(map
(fn [args]
(let [gargs (map #(gensym (str "g__" % "__")) args)
target (first gargs)]
`([~@gargs]
(~@(if on-interface
`(if (instance? ~on-interface ~target)
(. ~(with-meta target {:tag on-interface}) ~(or on-method method) ~@(rest gargs)))
`(do))
(let [cache# (.__methodImplCache ~gthis)]
(if (clojure.lang.Util/identical (clojure.lang.Util/classOf ~target)
(.lastClass cache#))
((.lastImpl cache#) ~@gargs)
(let [f# (or (.fnFor cache# (clojure.lang.Util/classOf ~target))
(-cache-protocol-fn ~gthis ~target))]
(f# ~@gargs))))))))
arglists))]
(set! (.__methodImplCache f#) cache#)
f#))))
(defn -reset-methods [protocol]
(doseq [[#^clojure.lang.Var v build] (:method-builders protocol)]
(let [cache (clojure.lang.MethodImplCache. protocol (keyword (.sym v)))]
(.bindRoot v (build cache)))))
(defn- assert-same-protocol [protocol-var method-syms]
(doseq [m method-syms]
(let [v (resolve m)
p (:protocol (meta v))]
(when-not (or (nil? v) (= protocol-var p))
(binding [*out* *err*]
(println "Warning: protocol" protocol-var "is overwriting"
(if p
(str "method " (.sym v) " of protocol " (.sym p))
(str "function " (.sym v)))))))))
(defn- emit-protocol [name opts+sigs]
(let [iname (symbol (str (munge *ns*) "." (munge name)))
[opts sigs]
(loop [opts {:on (list 'quote iname) :on-interface iname} sigs opts+sigs]
(condp #(%1 %2) (first sigs)
string? (recur (assoc opts :doc (first sigs)) (next sigs))
keyword? (recur (assoc opts (first sigs) (second sigs)) (nnext sigs))
[opts sigs]))
sigs (reduce (fn [m s]
(let [mname (with-meta (first s) nil)
[arglists doc]
(loop [as [] rs (rest s)]
(if (vector? (first rs))
(recur (conj as (first rs)) (next rs))
[(seq as) (first rs)]))]
(when (some #{0} (map count arglists))
(throw (IllegalArgumentException. (str "Protocol fn: " mname " must take at least one arg"))))
(assoc m (keyword mname)
{:name (vary-meta mname assoc :doc doc :arglists arglists)
:arglists arglists
:doc doc})))
{} sigs)
meths (mapcat (fn [sig]
(let [m (munge (:name sig))]
(map #(vector m (vec (repeat (dec (count %))'Object)) 'Object)
(:arglists sig))))
(vals sigs))]
`(do
(defonce ~name {})
(gen-interface :name ~iname :methods ~meths)
(alter-meta! (var ~name) assoc :doc ~(:doc opts))
(#'assert-same-protocol (var ~name) '~(map :name (vals sigs)))
(alter-var-root (var ~name) merge
(assoc ~opts
:sigs '~sigs
:var (var ~name)
:method-map
~(and (:on opts)
(apply hash-map
(mapcat
(fn [s]
[(keyword (:name s)) (keyword (or (:on s) (:name s)))])
(vals sigs))))
:method-builders
~(apply hash-map
(mapcat
(fn [s]
[`(intern *ns* (with-meta '~(:name s) {:protocol (var ~name)}))
(emit-method-builder (:on-interface opts) (:name s) (:on s) (:arglists s))])
(vals sigs)))))
(-reset-methods ~name)
'~name)))
(defmacro defprotocol
"A protocol is a named set of named methods and their signatures:
(defprotocol AProtocolName
;optional doc string
\"A doc string for AProtocol abstraction\"
;method signatures
(bar [a b] \"bar docs\")
(baz [a] [a b] [a b c] \"baz docs\"))
No implementations are provided. Docs can be specified for the
protocol overall and for each method. The above yields a set of
polymorphic functions and a protocol object. All are
namespace-qualified by the ns enclosing the definition The resulting
functions dispatch on the type of their first argument, and thus
must have at least one argument. defprotocol is dynamic, has no
special compile-time effect, and defines no new types or classes
Implementations of the protocol methods can be provided using
extend.
defprotocol will automatically generate a corresponding interface,
with the same name as the protocol, i.e. given a protocol:
my.ns/Protocol, an interface: my.ns.Protocol. The interface will
have methods corresponding to the protocol functions, and the
protocol will automatically work with instances of the interface.
Note that you should not use this interface with deftype or
reify, as they support the protocol directly:
(defprotocol P
(foo [x])
(bar-me [x] [x y]))
(deftype Foo [a b c]
P
(foo [] a)
(bar-me [] b)
(bar-me [y] (+ c y)))
(bar-me (Foo 1 2 3) 42)
(foo
(let [x 42]
(reify P
(foo [] 17)
(bar-me [] x)
(bar-me [y] x))))"
[name & opts+sigs]
(emit-protocol name opts+sigs))
(defn extend
"Implementations of protocol methods can be provided using the extend construct:
(extend ::AType ;or AClass or AnInterface
AProtocol
{:foo an-existing-fn
:bar (fn [a b] ...)
:baz (fn ([a]...) ([a b] ...)...)}
BProtocol
{...}
...)
extend takes a type/class (or interface, see below), and one or more
protocol + method map pairs. It will extend the polymorphism of the
protocol's methods to call the supplied methods when an AType is
provided as the first argument. Note that deftype types are specified
using their keyword tags:
::MyType or :my.ns/MyType
Method maps are maps of the keyword-ized method names to ordinary
fns. This facilitates easy reuse of existing fns and fn maps, for
code reuse/mixins without derivation or composition. You can extend
an interface to a protocol. This is primarily to facilitate interop
with the host (e.g. Java) but opens the door to incidental multiple
inheritance of implementation since a class can inherit from more
than one interface, both of which extend the protocol. It is TBD how
to specify which impl to use. You can extend a protocol on nil.
If you are supplying the definitions explicitly (i.e. not reusing
exsting functions or mixin maps), you may find it more convenient to
use the extend-type, extend-class or extend-protocol macros.
Note that multiple independent extend clauses can exist for the same
type, not all protocols need be defined in a single extend call.
See also:
extends?, satisfies?, extenders"
[atype & proto+mmaps]
(doseq [[proto mmap] (partition 2 proto+mmaps)]
(-reset-methods (alter-var-root (:var proto) assoc-in [:impls atype] mmap))))
(defn- emit-impl [[p fs]]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (drop 1 %)) fs))])
(defn- emit-hinted-impl [c [p fs]]
(let [hint (fn [specs]
(let [specs (if (vector? (first specs))
(list specs)
specs)]
(map (fn [[[target & args] & body]]
(cons (apply vector (vary-meta target assoc :tag c) args)
body))
specs)))]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (hint (drop 1 %))) fs))]))
(defn- emit-extend-type [t specs]
(let [impls (parse-impls specs)]
`(extend ~t
~@(mapcat emit-impl impls))))
(defn- emit-extend-class [c specs]
(let [impls (parse-impls specs)]
`(extend ~c
~@(mapcat (partial emit-hinted-impl c) impls))))
(defmacro extend-type
"A macro that expands into an extend call. Useful when you are
supplying the definitions explicitly inline, extend-type
automatically creates the maps required by extend.
(extend-type ::MyType
Countable
(cnt [c] ...)
Foo
(bar [x y] ...)
(baz ([x] ...) ([x y & zs] ...)))
expands into:
(extend ::MyType
Countable
{:cnt (fn [c] ...)}
Foo
{:baz (fn ([x] ...) ([x y & zs] ...))
:bar (fn [x y] ...)})"
[t & specs]
(emit-extend-type t specs))
(defmacro extend-class
"Like extend-type, for the case when the extended type is a
class. Propagates the class as a type hint on the first argument of
all fns"
[c & specs]
(emit-extend-class c specs))
(defn- emit-extend-protocol [p specs]
(let [impls (parse-impls specs)]
`(do
~@(map (fn [[t fs]]
(if (symbol? t)
`(extend-class ~t ~p ~@fs)
`(extend-type ~t ~p ~@fs)))
impls))))
(defmacro extend-protocol
"Useful when you want to provide several implementations of the same
protocol all at once. Takes a single protocol and the implementation
of that protocol for one or more types. Expands into calls to
extend-type and extend-class:
(extend-protocol Protocol
::AType
(foo [x] ...)
(bar [x y] ...)
::BType
(foo [x] ...)
(bar [x y] ...)
AClass
(foo [x] ...)
(bar [x y] ...)
nil
(foo [x] ...)
(bar [x y] ...))
expands into:
(do
(clojure.core/extend-type ::AType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type ::BType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-class AClass Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type nil Protocol
(foo [x] ...)
(bar [x y] ...)))"
[p & specs]
(emit-extend-protocol p specs))
| 111036 | ; 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.
(in-ns 'clojure.core)
;;;;;;;;;;;;;;;;;;;;;;;;;;;; definterface ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;for now, built on gen-interface
(defmacro definterface
[name & sigs]
(let [tag (fn [x] (or (:tag (meta x)) Object))
psig (fn [[name [& args]]]
(vector name (vec (map tag args)) (tag name)))]
`(gen-interface :name ~(symbol (str *ns* "." name)) :methods ~(vec (map psig sigs)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; reify/deftype ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- parse-opts [s]
(loop [opts {} [k v & rs :as s] s]
(if (keyword? k)
(recur (assoc opts k v) rs)
[opts s])))
(defn- parse-impls [specs]
(loop [ret {} s specs]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret)))
(defn- parse-opts+specs [opts+specs]
(let [[opts specs] (parse-opts opts+specs)
impls (parse-impls specs)
interfaces (-> (map #(if (var? (resolve %))
(:on (deref (resolve %)))
%)
(keys impls))
set
(disj 'Object 'java.lang.Object)
vec)
methods (mapcat #(map (fn [[nm [& args] & body]]
`(~nm [~(:as opts) ~@args] ~@body)) %)
(vals impls))]
[interfaces methods opts]))
(defmacro reify
"reify is a macro with the following structure:
(reify options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of the protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
The return type can be indicated by a type hint on the method name,
and arg types can be indicated by a type hint on arg names. If you
leave out all hints, reify will try to match on same name/arity
method in the protocol(s)/interface(s) - this is preferred. If you
supply any hints at all, no inference is done, so all hints (or
default of Object) must be correct, for both arguments and return
type. If a method is overloaded in a protocol/interface, multiple
independent method definitions must be supplied. If overloaded with
same arity in an interface you must specify complete hints to
disambiguate - a missing hint implies Object.
recur works to method heads The method bodies of reify are lexical
closures, and can refer to the surrounding local scope:
(str (let [f \"foo\"]
(reify Object
(toString [] f))))
== \"foo\"
(seq (let [f \"foo\"]
(reify clojure.lang.Seqable
(seq [] (seq f)))))
== (\\f \\o \\o))"
[& opts+specs]
(let [[interfaces methods] (parse-opts+specs opts+specs)]
`(reify* ~interfaces ~@methods)))
(defn hash-combine [x y]
(clojure.lang.Util/hashCombine x (clojure.lang.Util/hash y)))
(defn munge [s]
((if (symbol? s) symbol str) (clojure.lang.Compiler/munge (str s))))
(defn- emit-deftype*
"Do not use this directly - use deftype"
[tagname name fields interfaces methods]
(let [tag (keyword (str *ns*) (str tagname))
classname (symbol (str *ns* "." name))
interfaces (vec interfaces)
interface-set (set (map resolve interfaces))
methodname-set (set (map first methods))
dynamic-type (contains? interface-set clojure.lang.IDynamicType)
implement? (fn [iface] (not (contains? interface-set iface)))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap)]
(letfn
[(eqhash [[i m]]
(if (not (or (contains? methodname-set 'equals) (contains? methodname-set 'hashCode)))
[i
(conj m
`(hashCode [~'this] (-> ~tag hash ~@(map #(list `hash-combine %) (remove #{'__meta} fields))))
`(equals [~'this ~'o]
(boolean
(or (identical? ~'this ~'o)
(when (instance? clojure.lang.IDynamicType ~'o)
(let [~'o ~(with-meta 'o {:tag 'clojure.lang.IDynamicType})]
(and (= ~tag (.getDynamicType ~'o))
~@(map (fn [fld] `(= ~fld (.getDynamicField ~'o ~(keyword fld) ~'this))) base-fields)
(= ~'__extmap (.getExtensionMap ~'o)))))))))]
[i m]))
(iobj [[i m]]
(if (and (implement? clojure.lang.IObj) (implement? clojure.lang.IMeta))
[(conj i 'clojure.lang.IObj)
(conj m `(meta [~'this] ~'__meta)
`(withMeta [~'this ~'m] (new ~tagname ~@(replace {'__meta 'm} fields))))]
[i m]))
(ilookup [[i m]]
(if (not (methodname-set 'valAt))
[(conj i 'clojure.lang.ILookup 'clojure.lang.IKeywordLookup)
(conj m `(valAt [~'this k#] (.valAt ~'this k# nil))
`(valAt [~'this k# else#]
(case k# ~@(mapcat (fn [fld] [(keyword fld) fld])
base-fields)
(get ~'__extmap k# else#)))
`(getLookupThunk [~'this k#]
(case k#
~@(mapcat
(fn [fld]
(let [cstr (str (clojure.core/name classname) "$__lookup__" (clojure.core/name fld))]
[(keyword fld)
`(-> ~cstr (Class/forName) (.newInstance))]))
base-fields)
nil)))]
[i m]))
(idynamictype [[i m]]
[(conj i 'clojure.lang.IDynamicType)
(conj m
`(getDynamicType [~'this] ~tag)
`(getExtensionMap [~'this] ~'__extmap)
`(getDynamicField [~'this k# else#]
(condp identical? k# ~@(mapcat (fn [fld] [(keyword fld) fld]) base-fields)
(get ~'__extmap k# else#))))])
(imap [[i m]]
(if (and (interface-set clojure.lang.IPersistentMap) (not (methodname-set 'assoc)))
[i
(conj m
`(count [~'this] (+ ~(count base-fields) (count ~'__extmap)))
`(empty [~'this] (throw (UnsupportedOperationException. (str "Can't create empty: " ~(str classname)))))
`(cons [~'this e#] (let [[k# v#] e#] (.assoc ~'this k# v#)))
`(equiv [~'this o#] (.equals ~'this o#))
`(containsKey [~'this k#] (not (identical? ~'this (.valAt ~'this k# ~'this))))
`(entryAt [~'this k#] (let [v# (.valAt ~'this k# ~'this)]
(when-not (identical? ~'this v#)
(clojure.lang.MapEntry. k# v#))))
`(seq [~'this] (concat [~@(map #(list `new `clojure.lang.MapEntry (keyword %) %) base-fields)]
~'__extmap))
(let [gk (gensym) gv (gensym)]
`(assoc [~'this ~gk ~gv]
(condp identical? ~gk
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gv} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap} fields) (assoc ~'__extmap ~gk ~gv)))))
`(without [~'this k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} ~'this) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap} fields)
(not-empty (dissoc ~'__extmap k#))))))]
[i m]))]
(let [[i m] (-> [interfaces methods] eqhash iobj ilookup imap idynamictype)]
`(deftype* ~tagname ~classname ~(conj hinted-fields '__meta '__extmap)
:implements ~(vec i)
~@m)))))
(defmacro deftype
"Alpha - subject to change
(deftype name [fields*] options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of a protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Dynamically generates compiled bytecode for an anonymous class with
the given fields, and, optionally, methods for protocols and/or
interfaces. The Name will be used to create a dynamic type tag
keyword of the form :current.ns/Name. This tag will be returned
from (type an-instance).
A factory function of current.ns/Name will be defined,
overloaded on 2 arities, the first taking the designated fields in
the same order specified, and the second taking the fields followed
by a metadata map (nil for none) and an extension field map (nil for
none).
The class will have the (by default, immutable) fields named by
fields, which can have type hints. Protocols/interfaces and methods
are optional. The only methods that can be supplied are those
declared in the protocols/interfaces. Note that method bodies are
not closures, the local environment includes only the named fields,
and those fields can be accessed directy. Fields can be qualified
with the metadata :volatile-mutable true or :unsynchronized-mutable
true, at which point (set! afield aval) will be supported in method
bodies. Note well that mutable fields are extremely difficult to use
correctly, and are present only to facilitate the building of higher
level constructs, such as Clojure's reference types, in Clojure
itself. They are for experts only - if the semantics and
implications of :volatile-mutable or :unsynchronized-mutable are not
immediately apparent to you, you should not be using them.
Method definitions take the form:
(methodname [args*] body)
The argument and return types can be hinted on the arg and
methodname symbols. If not supplied, they will be inferred, so type
hints should be reserved for disambiguation.
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
In the method bodies, the (unqualified) name can be used to name the
class (for calls to new, instance? etc).
The class will have implementations of two (clojure.lang) interfaces
generated automatically: IObj (metadata support), ILookup (get and
keyword lookup for fields). If you specify IPersistentMap as an
interface, but don't define methods for it, an implementation will
be generated automatically.
In addition, unless you supply a version of hashCode or equals,
deftype/class will define type-and-value-based equality and
hashCode.
When AOT compiling, generates compiled bytecode for a class with the
given name (a symbol), prepends the current ns as the package, and
writes the .class file to the *compile-path* directory.
Two constructors will be defined, one taking the designated fields
followed by a metadata map (nil for none) and an extension field
map (nil for none), and one taking only the fields (using nil for
meta and extension fields).
When dynamically evaluated, the class will have a generated name."
[name [& fields] & opts+specs]
(let [gname (if *compile-files* name (gensym (str name "__")))
[interfaces methods opts] (parse-opts+specs opts+specs)
classname (symbol (str *ns* "." gname))
tag (keyword (str *ns*) (str name))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))]
`(do
~(emit-deftype* name gname (vec hinted-fields) (vec interfaces) methods)
(defmethod print-method ~tag [o# w#]
((var print-deftype) ~(vec (map #(-> % str keyword) fields)) o# w#))
(defn ~name
([~@fields] (new ~classname ~@fields nil nil))
([~@fields meta# extmap#] (new ~classname ~@fields meta# extmap#))))))
(defn- print-deftype [fields, #^clojure.lang.IDynamicType o, #^Writer w]
(print-meta o w)
(.write w "#:")
(.write w (str (name (.getDynamicType o))))
(print-map
(concat
(map #(clojure.lang.MapEntry. % (.getDynamicField o % nil)) fields)
(.getExtensionMap o))
pr-on w))
;;;;;;;;;;;;;;;;;;;;;;; protocols ;;;;;;;;;;;;;;;;;;;;;;;;
(defn dtype
"Returns the dynamic type of x, or its Class if none"
[x]
(if (instance? clojure.lang.IDynamicType x)
(let [x #^ clojure.lang.IDynamicType x]
(.getDynamicType x))
(class x)))
(defn- expand-method-impl-cache [#^clojure.lang.MethodImplCache cache c f]
(let [cs (into {} (remove (fn [[c f]] (nil? f)) (map vec (partition 2 (.table cache)))))
cs (assoc cs c f)
[shift mask] (min-hash (keys cs))
table (make-array Object (* 2 (inc mask)))
table (reduce (fn [#^objects t [c f]]
(let [i (* 2 (int (shift-mask shift mask (hash c))))]
(aset t i c)
(aset t (inc i) f)
t))
table cs)]
(clojure.lang.MethodImplCache. (.protocol cache) (.methodk cache) shift mask table)))
(defn- super-chain [#^Class c]
(when c
(cons c (super-chain (.getSuperclass c)))))
(defn find-protocol-impl [protocol x]
(if (and (:on-interface protocol) (instance? (:on-interface protocol) x))
x
(let [t (dtype x)
c (class x)
impl #(get (:impls protocol) %)]
(or (impl t)
(impl c)
(and c (or (first (remove nil? (map impl (butlast (super-chain c)))))
(first (remove nil? (map impl (disj (supers c) Object))))
(impl Object)))))))
(defn find-protocol-method [protocol methodk x]
(get (find-protocol-impl protocol x) methodk))
(defn extends?
"Returns true if atype explicitly extends protocol"
[protocol atype]
(when (get (:impls protocol) atype) true))
(defn extenders
"Returns a collection of the types explicitly extending protocol"
[protocol]
(keys (:impls protocol)))
(defn satisfies?
"Returns true if x satisfies the protocol"
[protocol x]
(when
(or (and (:on-interface protocol) (instance? (:on-interface protocol) x))
(find-protocol-impl protocol x))
true))
(defn -cache-protocol-fn [#^clojure.lang.AFunction pf x]
(let [cache (.__methodImplCache pf)
f (find-protocol-method (.protocol cache) (.methodk cache) x)]
(when-not f
(throw (IllegalArgumentException. (str "No implementation of method: " (.methodk cache)
" of protocol: " (:var (.protocol cache))
" found for class: " (if (nil? x) "nil" (.getName (class x)))))))
(set! (.__methodImplCache pf) (expand-method-impl-cache cache (class x) f))
f))
(defn- emit-method-builder [on-interface method on-method arglists]
(let [methodk (keyword method)
gthis (with-meta (gensym) {:tag 'clojure.lang.AFunction})]
`(fn [cache#]
(let [#^clojure.lang.AFunction f#
(fn ~gthis
~@(map
(fn [args]
(let [gargs (map #(gensym (str "g__" % "__")) args)
target (first gargs)]
`([~@gargs]
(~@(if on-interface
`(if (instance? ~on-interface ~target)
(. ~(with-meta target {:tag on-interface}) ~(or on-method method) ~@(rest gargs)))
`(do))
(let [cache# (.__methodImplCache ~gthis)]
(if (clojure.lang.Util/identical (clojure.lang.Util/classOf ~target)
(.lastClass cache#))
((.lastImpl cache#) ~@gargs)
(let [f# (or (.fnFor cache# (clojure.lang.Util/classOf ~target))
(-cache-protocol-fn ~gthis ~target))]
(f# ~@gargs))))))))
arglists))]
(set! (.__methodImplCache f#) cache#)
f#))))
(defn -reset-methods [protocol]
(doseq [[#^clojure.lang.Var v build] (:method-builders protocol)]
(let [cache (clojure.lang.MethodImplCache. protocol (keyword (.sym v)))]
(.bindRoot v (build cache)))))
(defn- assert-same-protocol [protocol-var method-syms]
(doseq [m method-syms]
(let [v (resolve m)
p (:protocol (meta v))]
(when-not (or (nil? v) (= protocol-var p))
(binding [*out* *err*]
(println "Warning: protocol" protocol-var "is overwriting"
(if p
(str "method " (.sym v) " of protocol " (.sym p))
(str "function " (.sym v)))))))))
(defn- emit-protocol [name opts+sigs]
(let [iname (symbol (str (munge *ns*) "." (munge name)))
[opts sigs]
(loop [opts {:on (list 'quote iname) :on-interface iname} sigs opts+sigs]
(condp #(%1 %2) (first sigs)
string? (recur (assoc opts :doc (first sigs)) (next sigs))
keyword? (recur (assoc opts (first sigs) (second sigs)) (nnext sigs))
[opts sigs]))
sigs (reduce (fn [m s]
(let [mname (with-meta (first s) nil)
[arglists doc]
(loop [as [] rs (rest s)]
(if (vector? (first rs))
(recur (conj as (first rs)) (next rs))
[(seq as) (first rs)]))]
(when (some #{0} (map count arglists))
(throw (IllegalArgumentException. (str "Protocol fn: " mname " must take at least one arg"))))
(assoc m (keyword mname)
{:name (vary-meta mname assoc :doc doc :arglists arglists)
:arglists arglists
:doc doc})))
{} sigs)
meths (mapcat (fn [sig]
(let [m (munge (:name sig))]
(map #(vector m (vec (repeat (dec (count %))'Object)) 'Object)
(:arglists sig))))
(vals sigs))]
`(do
(defonce ~name {})
(gen-interface :name ~iname :methods ~meths)
(alter-meta! (var ~name) assoc :doc ~(:doc opts))
(#'assert-same-protocol (var ~name) '~(map :name (vals sigs)))
(alter-var-root (var ~name) merge
(assoc ~opts
:sigs '~sigs
:var (var ~name)
:method-map
~(and (:on opts)
(apply hash-map
(mapcat
(fn [s]
[(keyword (:name s)) (keyword (or (:on s) (:name s)))])
(vals sigs))))
:method-builders
~(apply hash-map
(mapcat
(fn [s]
[`(intern *ns* (with-meta '~(:name s) {:protocol (var ~name)}))
(emit-method-builder (:on-interface opts) (:name s) (:on s) (:arglists s))])
(vals sigs)))))
(-reset-methods ~name)
'~name)))
(defmacro defprotocol
"A protocol is a named set of named methods and their signatures:
(defprotocol AProtocolName
;optional doc string
\"A doc string for AProtocol abstraction\"
;method signatures
(bar [a b] \"bar docs\")
(baz [a] [a b] [a b c] \"baz docs\"))
No implementations are provided. Docs can be specified for the
protocol overall and for each method. The above yields a set of
polymorphic functions and a protocol object. All are
namespace-qualified by the ns enclosing the definition The resulting
functions dispatch on the type of their first argument, and thus
must have at least one argument. defprotocol is dynamic, has no
special compile-time effect, and defines no new types or classes
Implementations of the protocol methods can be provided using
extend.
defprotocol will automatically generate a corresponding interface,
with the same name as the protocol, i.e. given a protocol:
my.ns/Protocol, an interface: my.ns.Protocol. The interface will
have methods corresponding to the protocol functions, and the
protocol will automatically work with instances of the interface.
Note that you should not use this interface with deftype or
reify, as they support the protocol directly:
(defprotocol P
(foo [x])
(bar-me [x] [x y]))
(deftype Foo [a b c]
P
(foo [] a)
(bar-me [] b)
(bar-me [y] (+ c y)))
(bar-me (Foo 1 2 3) 42)
(foo
(let [x 42]
(reify P
(foo [] 17)
(bar-me [] x)
(bar-me [y] x))))"
[name & opts+sigs]
(emit-protocol name opts+sigs))
(defn extend
"Implementations of protocol methods can be provided using the extend construct:
(extend ::AType ;or AClass or AnInterface
AProtocol
{:foo an-existing-fn
:bar (fn [a b] ...)
:baz (fn ([a]...) ([a b] ...)...)}
BProtocol
{...}
...)
extend takes a type/class (or interface, see below), and one or more
protocol + method map pairs. It will extend the polymorphism of the
protocol's methods to call the supplied methods when an AType is
provided as the first argument. Note that deftype types are specified
using their keyword tags:
::MyType or :my.ns/MyType
Method maps are maps of the keyword-ized method names to ordinary
fns. This facilitates easy reuse of existing fns and fn maps, for
code reuse/mixins without derivation or composition. You can extend
an interface to a protocol. This is primarily to facilitate interop
with the host (e.g. Java) but opens the door to incidental multiple
inheritance of implementation since a class can inherit from more
than one interface, both of which extend the protocol. It is TBD how
to specify which impl to use. You can extend a protocol on nil.
If you are supplying the definitions explicitly (i.e. not reusing
exsting functions or mixin maps), you may find it more convenient to
use the extend-type, extend-class or extend-protocol macros.
Note that multiple independent extend clauses can exist for the same
type, not all protocols need be defined in a single extend call.
See also:
extends?, satisfies?, extenders"
[atype & proto+mmaps]
(doseq [[proto mmap] (partition 2 proto+mmaps)]
(-reset-methods (alter-var-root (:var proto) assoc-in [:impls atype] mmap))))
(defn- emit-impl [[p fs]]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (drop 1 %)) fs))])
(defn- emit-hinted-impl [c [p fs]]
(let [hint (fn [specs]
(let [specs (if (vector? (first specs))
(list specs)
specs)]
(map (fn [[[target & args] & body]]
(cons (apply vector (vary-meta target assoc :tag c) args)
body))
specs)))]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (hint (drop 1 %))) fs))]))
(defn- emit-extend-type [t specs]
(let [impls (parse-impls specs)]
`(extend ~t
~@(mapcat emit-impl impls))))
(defn- emit-extend-class [c specs]
(let [impls (parse-impls specs)]
`(extend ~c
~@(mapcat (partial emit-hinted-impl c) impls))))
(defmacro extend-type
"A macro that expands into an extend call. Useful when you are
supplying the definitions explicitly inline, extend-type
automatically creates the maps required by extend.
(extend-type ::MyType
Countable
(cnt [c] ...)
Foo
(bar [x y] ...)
(baz ([x] ...) ([x y & zs] ...)))
expands into:
(extend ::MyType
Countable
{:cnt (fn [c] ...)}
Foo
{:baz (fn ([x] ...) ([x y & zs] ...))
:bar (fn [x y] ...)})"
[t & specs]
(emit-extend-type t specs))
(defmacro extend-class
"Like extend-type, for the case when the extended type is a
class. Propagates the class as a type hint on the first argument of
all fns"
[c & specs]
(emit-extend-class c specs))
(defn- emit-extend-protocol [p specs]
(let [impls (parse-impls specs)]
`(do
~@(map (fn [[t fs]]
(if (symbol? t)
`(extend-class ~t ~p ~@fs)
`(extend-type ~t ~p ~@fs)))
impls))))
(defmacro extend-protocol
"Useful when you want to provide several implementations of the same
protocol all at once. Takes a single protocol and the implementation
of that protocol for one or more types. Expands into calls to
extend-type and extend-class:
(extend-protocol Protocol
::AType
(foo [x] ...)
(bar [x y] ...)
::BType
(foo [x] ...)
(bar [x y] ...)
AClass
(foo [x] ...)
(bar [x y] ...)
nil
(foo [x] ...)
(bar [x y] ...))
expands into:
(do
(clojure.core/extend-type ::AType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type ::BType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-class AClass Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type nil Protocol
(foo [x] ...)
(bar [x y] ...)))"
[p & specs]
(emit-extend-protocol p specs))
| 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.
(in-ns 'clojure.core)
;;;;;;;;;;;;;;;;;;;;;;;;;;;; definterface ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;for now, built on gen-interface
(defmacro definterface
[name & sigs]
(let [tag (fn [x] (or (:tag (meta x)) Object))
psig (fn [[name [& args]]]
(vector name (vec (map tag args)) (tag name)))]
`(gen-interface :name ~(symbol (str *ns* "." name)) :methods ~(vec (map psig sigs)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; reify/deftype ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- parse-opts [s]
(loop [opts {} [k v & rs :as s] s]
(if (keyword? k)
(recur (assoc opts k v) rs)
[opts s])))
(defn- parse-impls [specs]
(loop [ret {} s specs]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret)))
(defn- parse-opts+specs [opts+specs]
(let [[opts specs] (parse-opts opts+specs)
impls (parse-impls specs)
interfaces (-> (map #(if (var? (resolve %))
(:on (deref (resolve %)))
%)
(keys impls))
set
(disj 'Object 'java.lang.Object)
vec)
methods (mapcat #(map (fn [[nm [& args] & body]]
`(~nm [~(:as opts) ~@args] ~@body)) %)
(vals impls))]
[interfaces methods opts]))
(defmacro reify
"reify is a macro with the following structure:
(reify options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of the protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
The return type can be indicated by a type hint on the method name,
and arg types can be indicated by a type hint on arg names. If you
leave out all hints, reify will try to match on same name/arity
method in the protocol(s)/interface(s) - this is preferred. If you
supply any hints at all, no inference is done, so all hints (or
default of Object) must be correct, for both arguments and return
type. If a method is overloaded in a protocol/interface, multiple
independent method definitions must be supplied. If overloaded with
same arity in an interface you must specify complete hints to
disambiguate - a missing hint implies Object.
recur works to method heads The method bodies of reify are lexical
closures, and can refer to the surrounding local scope:
(str (let [f \"foo\"]
(reify Object
(toString [] f))))
== \"foo\"
(seq (let [f \"foo\"]
(reify clojure.lang.Seqable
(seq [] (seq f)))))
== (\\f \\o \\o))"
[& opts+specs]
(let [[interfaces methods] (parse-opts+specs opts+specs)]
`(reify* ~interfaces ~@methods)))
(defn hash-combine [x y]
(clojure.lang.Util/hashCombine x (clojure.lang.Util/hash y)))
(defn munge [s]
((if (symbol? s) symbol str) (clojure.lang.Compiler/munge (str s))))
(defn- emit-deftype*
"Do not use this directly - use deftype"
[tagname name fields interfaces methods]
(let [tag (keyword (str *ns*) (str tagname))
classname (symbol (str *ns* "." name))
interfaces (vec interfaces)
interface-set (set (map resolve interfaces))
methodname-set (set (map first methods))
dynamic-type (contains? interface-set clojure.lang.IDynamicType)
implement? (fn [iface] (not (contains? interface-set iface)))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap)]
(letfn
[(eqhash [[i m]]
(if (not (or (contains? methodname-set 'equals) (contains? methodname-set 'hashCode)))
[i
(conj m
`(hashCode [~'this] (-> ~tag hash ~@(map #(list `hash-combine %) (remove #{'__meta} fields))))
`(equals [~'this ~'o]
(boolean
(or (identical? ~'this ~'o)
(when (instance? clojure.lang.IDynamicType ~'o)
(let [~'o ~(with-meta 'o {:tag 'clojure.lang.IDynamicType})]
(and (= ~tag (.getDynamicType ~'o))
~@(map (fn [fld] `(= ~fld (.getDynamicField ~'o ~(keyword fld) ~'this))) base-fields)
(= ~'__extmap (.getExtensionMap ~'o)))))))))]
[i m]))
(iobj [[i m]]
(if (and (implement? clojure.lang.IObj) (implement? clojure.lang.IMeta))
[(conj i 'clojure.lang.IObj)
(conj m `(meta [~'this] ~'__meta)
`(withMeta [~'this ~'m] (new ~tagname ~@(replace {'__meta 'm} fields))))]
[i m]))
(ilookup [[i m]]
(if (not (methodname-set 'valAt))
[(conj i 'clojure.lang.ILookup 'clojure.lang.IKeywordLookup)
(conj m `(valAt [~'this k#] (.valAt ~'this k# nil))
`(valAt [~'this k# else#]
(case k# ~@(mapcat (fn [fld] [(keyword fld) fld])
base-fields)
(get ~'__extmap k# else#)))
`(getLookupThunk [~'this k#]
(case k#
~@(mapcat
(fn [fld]
(let [cstr (str (clojure.core/name classname) "$__lookup__" (clojure.core/name fld))]
[(keyword fld)
`(-> ~cstr (Class/forName) (.newInstance))]))
base-fields)
nil)))]
[i m]))
(idynamictype [[i m]]
[(conj i 'clojure.lang.IDynamicType)
(conj m
`(getDynamicType [~'this] ~tag)
`(getExtensionMap [~'this] ~'__extmap)
`(getDynamicField [~'this k# else#]
(condp identical? k# ~@(mapcat (fn [fld] [(keyword fld) fld]) base-fields)
(get ~'__extmap k# else#))))])
(imap [[i m]]
(if (and (interface-set clojure.lang.IPersistentMap) (not (methodname-set 'assoc)))
[i
(conj m
`(count [~'this] (+ ~(count base-fields) (count ~'__extmap)))
`(empty [~'this] (throw (UnsupportedOperationException. (str "Can't create empty: " ~(str classname)))))
`(cons [~'this e#] (let [[k# v#] e#] (.assoc ~'this k# v#)))
`(equiv [~'this o#] (.equals ~'this o#))
`(containsKey [~'this k#] (not (identical? ~'this (.valAt ~'this k# ~'this))))
`(entryAt [~'this k#] (let [v# (.valAt ~'this k# ~'this)]
(when-not (identical? ~'this v#)
(clojure.lang.MapEntry. k# v#))))
`(seq [~'this] (concat [~@(map #(list `new `clojure.lang.MapEntry (keyword %) %) base-fields)]
~'__extmap))
(let [gk (gensym) gv (gensym)]
`(assoc [~'this ~gk ~gv]
(condp identical? ~gk
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gv} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap} fields) (assoc ~'__extmap ~gk ~gv)))))
`(without [~'this k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} ~'this) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap} fields)
(not-empty (dissoc ~'__extmap k#))))))]
[i m]))]
(let [[i m] (-> [interfaces methods] eqhash iobj ilookup imap idynamictype)]
`(deftype* ~tagname ~classname ~(conj hinted-fields '__meta '__extmap)
:implements ~(vec i)
~@m)))))
(defmacro deftype
"Alpha - subject to change
(deftype name [fields*] options* specs*)
Currently there is only one option:
:as this-name
which can be used to provide a name to refer to the target
object ('this' in Java/C# parlance) within the method bodies, if
needed.
Each spec consists of a protocol or interface name followed by zero
or more method bodies:
protocol-or-interface-or-Object
(methodName [args*] body)*
Dynamically generates compiled bytecode for an anonymous class with
the given fields, and, optionally, methods for protocols and/or
interfaces. The Name will be used to create a dynamic type tag
keyword of the form :current.ns/Name. This tag will be returned
from (type an-instance).
A factory function of current.ns/Name will be defined,
overloaded on 2 arities, the first taking the designated fields in
the same order specified, and the second taking the fields followed
by a metadata map (nil for none) and an extension field map (nil for
none).
The class will have the (by default, immutable) fields named by
fields, which can have type hints. Protocols/interfaces and methods
are optional. The only methods that can be supplied are those
declared in the protocols/interfaces. Note that method bodies are
not closures, the local environment includes only the named fields,
and those fields can be accessed directy. Fields can be qualified
with the metadata :volatile-mutable true or :unsynchronized-mutable
true, at which point (set! afield aval) will be supported in method
bodies. Note well that mutable fields are extremely difficult to use
correctly, and are present only to facilitate the building of higher
level constructs, such as Clojure's reference types, in Clojure
itself. They are for experts only - if the semantics and
implications of :volatile-mutable or :unsynchronized-mutable are not
immediately apparent to you, you should not be using them.
Method definitions take the form:
(methodname [args*] body)
The argument and return types can be hinted on the arg and
methodname symbols. If not supplied, they will be inferred, so type
hints should be reserved for disambiguation.
Methods should be supplied for all methods of the desired
protocol(s) and interface(s). You can also define overrides for
methods of Object. Note that no parameter is supplied to correspond
to the target object ('this' in Java parlance). Thus methods for
protocols will take one fewer arguments than do the
protocol functions.
In the method bodies, the (unqualified) name can be used to name the
class (for calls to new, instance? etc).
The class will have implementations of two (clojure.lang) interfaces
generated automatically: IObj (metadata support), ILookup (get and
keyword lookup for fields). If you specify IPersistentMap as an
interface, but don't define methods for it, an implementation will
be generated automatically.
In addition, unless you supply a version of hashCode or equals,
deftype/class will define type-and-value-based equality and
hashCode.
When AOT compiling, generates compiled bytecode for a class with the
given name (a symbol), prepends the current ns as the package, and
writes the .class file to the *compile-path* directory.
Two constructors will be defined, one taking the designated fields
followed by a metadata map (nil for none) and an extension field
map (nil for none), and one taking only the fields (using nil for
meta and extension fields).
When dynamically evaluated, the class will have a generated name."
[name [& fields] & opts+specs]
(let [gname (if *compile-files* name (gensym (str name "__")))
[interfaces methods opts] (parse-opts+specs opts+specs)
classname (symbol (str *ns* "." gname))
tag (keyword (str *ns*) (str name))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))]
`(do
~(emit-deftype* name gname (vec hinted-fields) (vec interfaces) methods)
(defmethod print-method ~tag [o# w#]
((var print-deftype) ~(vec (map #(-> % str keyword) fields)) o# w#))
(defn ~name
([~@fields] (new ~classname ~@fields nil nil))
([~@fields meta# extmap#] (new ~classname ~@fields meta# extmap#))))))
(defn- print-deftype [fields, #^clojure.lang.IDynamicType o, #^Writer w]
(print-meta o w)
(.write w "#:")
(.write w (str (name (.getDynamicType o))))
(print-map
(concat
(map #(clojure.lang.MapEntry. % (.getDynamicField o % nil)) fields)
(.getExtensionMap o))
pr-on w))
;;;;;;;;;;;;;;;;;;;;;;; protocols ;;;;;;;;;;;;;;;;;;;;;;;;
(defn dtype
"Returns the dynamic type of x, or its Class if none"
[x]
(if (instance? clojure.lang.IDynamicType x)
(let [x #^ clojure.lang.IDynamicType x]
(.getDynamicType x))
(class x)))
(defn- expand-method-impl-cache [#^clojure.lang.MethodImplCache cache c f]
(let [cs (into {} (remove (fn [[c f]] (nil? f)) (map vec (partition 2 (.table cache)))))
cs (assoc cs c f)
[shift mask] (min-hash (keys cs))
table (make-array Object (* 2 (inc mask)))
table (reduce (fn [#^objects t [c f]]
(let [i (* 2 (int (shift-mask shift mask (hash c))))]
(aset t i c)
(aset t (inc i) f)
t))
table cs)]
(clojure.lang.MethodImplCache. (.protocol cache) (.methodk cache) shift mask table)))
(defn- super-chain [#^Class c]
(when c
(cons c (super-chain (.getSuperclass c)))))
(defn find-protocol-impl [protocol x]
(if (and (:on-interface protocol) (instance? (:on-interface protocol) x))
x
(let [t (dtype x)
c (class x)
impl #(get (:impls protocol) %)]
(or (impl t)
(impl c)
(and c (or (first (remove nil? (map impl (butlast (super-chain c)))))
(first (remove nil? (map impl (disj (supers c) Object))))
(impl Object)))))))
(defn find-protocol-method [protocol methodk x]
(get (find-protocol-impl protocol x) methodk))
(defn extends?
"Returns true if atype explicitly extends protocol"
[protocol atype]
(when (get (:impls protocol) atype) true))
(defn extenders
"Returns a collection of the types explicitly extending protocol"
[protocol]
(keys (:impls protocol)))
(defn satisfies?
"Returns true if x satisfies the protocol"
[protocol x]
(when
(or (and (:on-interface protocol) (instance? (:on-interface protocol) x))
(find-protocol-impl protocol x))
true))
(defn -cache-protocol-fn [#^clojure.lang.AFunction pf x]
(let [cache (.__methodImplCache pf)
f (find-protocol-method (.protocol cache) (.methodk cache) x)]
(when-not f
(throw (IllegalArgumentException. (str "No implementation of method: " (.methodk cache)
" of protocol: " (:var (.protocol cache))
" found for class: " (if (nil? x) "nil" (.getName (class x)))))))
(set! (.__methodImplCache pf) (expand-method-impl-cache cache (class x) f))
f))
(defn- emit-method-builder [on-interface method on-method arglists]
(let [methodk (keyword method)
gthis (with-meta (gensym) {:tag 'clojure.lang.AFunction})]
`(fn [cache#]
(let [#^clojure.lang.AFunction f#
(fn ~gthis
~@(map
(fn [args]
(let [gargs (map #(gensym (str "g__" % "__")) args)
target (first gargs)]
`([~@gargs]
(~@(if on-interface
`(if (instance? ~on-interface ~target)
(. ~(with-meta target {:tag on-interface}) ~(or on-method method) ~@(rest gargs)))
`(do))
(let [cache# (.__methodImplCache ~gthis)]
(if (clojure.lang.Util/identical (clojure.lang.Util/classOf ~target)
(.lastClass cache#))
((.lastImpl cache#) ~@gargs)
(let [f# (or (.fnFor cache# (clojure.lang.Util/classOf ~target))
(-cache-protocol-fn ~gthis ~target))]
(f# ~@gargs))))))))
arglists))]
(set! (.__methodImplCache f#) cache#)
f#))))
(defn -reset-methods [protocol]
(doseq [[#^clojure.lang.Var v build] (:method-builders protocol)]
(let [cache (clojure.lang.MethodImplCache. protocol (keyword (.sym v)))]
(.bindRoot v (build cache)))))
(defn- assert-same-protocol [protocol-var method-syms]
(doseq [m method-syms]
(let [v (resolve m)
p (:protocol (meta v))]
(when-not (or (nil? v) (= protocol-var p))
(binding [*out* *err*]
(println "Warning: protocol" protocol-var "is overwriting"
(if p
(str "method " (.sym v) " of protocol " (.sym p))
(str "function " (.sym v)))))))))
(defn- emit-protocol [name opts+sigs]
(let [iname (symbol (str (munge *ns*) "." (munge name)))
[opts sigs]
(loop [opts {:on (list 'quote iname) :on-interface iname} sigs opts+sigs]
(condp #(%1 %2) (first sigs)
string? (recur (assoc opts :doc (first sigs)) (next sigs))
keyword? (recur (assoc opts (first sigs) (second sigs)) (nnext sigs))
[opts sigs]))
sigs (reduce (fn [m s]
(let [mname (with-meta (first s) nil)
[arglists doc]
(loop [as [] rs (rest s)]
(if (vector? (first rs))
(recur (conj as (first rs)) (next rs))
[(seq as) (first rs)]))]
(when (some #{0} (map count arglists))
(throw (IllegalArgumentException. (str "Protocol fn: " mname " must take at least one arg"))))
(assoc m (keyword mname)
{:name (vary-meta mname assoc :doc doc :arglists arglists)
:arglists arglists
:doc doc})))
{} sigs)
meths (mapcat (fn [sig]
(let [m (munge (:name sig))]
(map #(vector m (vec (repeat (dec (count %))'Object)) 'Object)
(:arglists sig))))
(vals sigs))]
`(do
(defonce ~name {})
(gen-interface :name ~iname :methods ~meths)
(alter-meta! (var ~name) assoc :doc ~(:doc opts))
(#'assert-same-protocol (var ~name) '~(map :name (vals sigs)))
(alter-var-root (var ~name) merge
(assoc ~opts
:sigs '~sigs
:var (var ~name)
:method-map
~(and (:on opts)
(apply hash-map
(mapcat
(fn [s]
[(keyword (:name s)) (keyword (or (:on s) (:name s)))])
(vals sigs))))
:method-builders
~(apply hash-map
(mapcat
(fn [s]
[`(intern *ns* (with-meta '~(:name s) {:protocol (var ~name)}))
(emit-method-builder (:on-interface opts) (:name s) (:on s) (:arglists s))])
(vals sigs)))))
(-reset-methods ~name)
'~name)))
(defmacro defprotocol
"A protocol is a named set of named methods and their signatures:
(defprotocol AProtocolName
;optional doc string
\"A doc string for AProtocol abstraction\"
;method signatures
(bar [a b] \"bar docs\")
(baz [a] [a b] [a b c] \"baz docs\"))
No implementations are provided. Docs can be specified for the
protocol overall and for each method. The above yields a set of
polymorphic functions and a protocol object. All are
namespace-qualified by the ns enclosing the definition The resulting
functions dispatch on the type of their first argument, and thus
must have at least one argument. defprotocol is dynamic, has no
special compile-time effect, and defines no new types or classes
Implementations of the protocol methods can be provided using
extend.
defprotocol will automatically generate a corresponding interface,
with the same name as the protocol, i.e. given a protocol:
my.ns/Protocol, an interface: my.ns.Protocol. The interface will
have methods corresponding to the protocol functions, and the
protocol will automatically work with instances of the interface.
Note that you should not use this interface with deftype or
reify, as they support the protocol directly:
(defprotocol P
(foo [x])
(bar-me [x] [x y]))
(deftype Foo [a b c]
P
(foo [] a)
(bar-me [] b)
(bar-me [y] (+ c y)))
(bar-me (Foo 1 2 3) 42)
(foo
(let [x 42]
(reify P
(foo [] 17)
(bar-me [] x)
(bar-me [y] x))))"
[name & opts+sigs]
(emit-protocol name opts+sigs))
(defn extend
"Implementations of protocol methods can be provided using the extend construct:
(extend ::AType ;or AClass or AnInterface
AProtocol
{:foo an-existing-fn
:bar (fn [a b] ...)
:baz (fn ([a]...) ([a b] ...)...)}
BProtocol
{...}
...)
extend takes a type/class (or interface, see below), and one or more
protocol + method map pairs. It will extend the polymorphism of the
protocol's methods to call the supplied methods when an AType is
provided as the first argument. Note that deftype types are specified
using their keyword tags:
::MyType or :my.ns/MyType
Method maps are maps of the keyword-ized method names to ordinary
fns. This facilitates easy reuse of existing fns and fn maps, for
code reuse/mixins without derivation or composition. You can extend
an interface to a protocol. This is primarily to facilitate interop
with the host (e.g. Java) but opens the door to incidental multiple
inheritance of implementation since a class can inherit from more
than one interface, both of which extend the protocol. It is TBD how
to specify which impl to use. You can extend a protocol on nil.
If you are supplying the definitions explicitly (i.e. not reusing
exsting functions or mixin maps), you may find it more convenient to
use the extend-type, extend-class or extend-protocol macros.
Note that multiple independent extend clauses can exist for the same
type, not all protocols need be defined in a single extend call.
See also:
extends?, satisfies?, extenders"
[atype & proto+mmaps]
(doseq [[proto mmap] (partition 2 proto+mmaps)]
(-reset-methods (alter-var-root (:var proto) assoc-in [:impls atype] mmap))))
(defn- emit-impl [[p fs]]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (drop 1 %)) fs))])
(defn- emit-hinted-impl [c [p fs]]
(let [hint (fn [specs]
(let [specs (if (vector? (first specs))
(list specs)
specs)]
(map (fn [[[target & args] & body]]
(cons (apply vector (vary-meta target assoc :tag c) args)
body))
specs)))]
[p (zipmap (map #(-> % first keyword) fs)
(map #(cons 'fn (hint (drop 1 %))) fs))]))
(defn- emit-extend-type [t specs]
(let [impls (parse-impls specs)]
`(extend ~t
~@(mapcat emit-impl impls))))
(defn- emit-extend-class [c specs]
(let [impls (parse-impls specs)]
`(extend ~c
~@(mapcat (partial emit-hinted-impl c) impls))))
(defmacro extend-type
"A macro that expands into an extend call. Useful when you are
supplying the definitions explicitly inline, extend-type
automatically creates the maps required by extend.
(extend-type ::MyType
Countable
(cnt [c] ...)
Foo
(bar [x y] ...)
(baz ([x] ...) ([x y & zs] ...)))
expands into:
(extend ::MyType
Countable
{:cnt (fn [c] ...)}
Foo
{:baz (fn ([x] ...) ([x y & zs] ...))
:bar (fn [x y] ...)})"
[t & specs]
(emit-extend-type t specs))
(defmacro extend-class
"Like extend-type, for the case when the extended type is a
class. Propagates the class as a type hint on the first argument of
all fns"
[c & specs]
(emit-extend-class c specs))
(defn- emit-extend-protocol [p specs]
(let [impls (parse-impls specs)]
`(do
~@(map (fn [[t fs]]
(if (symbol? t)
`(extend-class ~t ~p ~@fs)
`(extend-type ~t ~p ~@fs)))
impls))))
(defmacro extend-protocol
"Useful when you want to provide several implementations of the same
protocol all at once. Takes a single protocol and the implementation
of that protocol for one or more types. Expands into calls to
extend-type and extend-class:
(extend-protocol Protocol
::AType
(foo [x] ...)
(bar [x y] ...)
::BType
(foo [x] ...)
(bar [x y] ...)
AClass
(foo [x] ...)
(bar [x y] ...)
nil
(foo [x] ...)
(bar [x y] ...))
expands into:
(do
(clojure.core/extend-type ::AType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type ::BType Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-class AClass Protocol
(foo [x] ...)
(bar [x y] ...))
(clojure.core/extend-type nil Protocol
(foo [x] ...)
(bar [x y] ...)))"
[p & specs]
(emit-extend-protocol p specs))
|
[
{
"context": " via \"\n [:a {:href \"https://www.patreon.com/sekao\" :target \"_blank\"}\n \"my patreon\"]]]]\n [",
"end": 7764,
"score": 0.9995418787002563,
"start": 7759,
"tag": "USERNAME",
"value": "sekao"
},
{
"context": ":a {:href \"https://sekao.net/\" :target \"_blank\"} \"Zach Oakes\"]]\n [:p \"Feedback and discussion welcome on ",
"end": 9258,
"score": 0.9997397065162659,
"start": 9248,
"tag": "NAME",
"value": "Zach Oakes"
}
] | src/cljs/nightcoders/core.cljs | ClojureBridgeAmsterdam/Nightcoders.net | 3 | (ns nightcoders.core
(:require [reagent.core :as r]
[cljs.reader :refer [read-string]]
[cljsjs.material-ui]
[cljs-react-material-ui.core :refer [get-mui-theme]]
[cljs-react-material-ui.reagent :as ui]
[nightcoders.auth :as auth]
[goog.object])
(:import goog.net.XhrIo))
(defonce *state (r/atom {}))
(auth/set-sign-in (fn [success? user]
(when success?
(swap! *state assoc
:signed-in? true
:user (read-string user)))))
(auth/load (fn [auth2]
(when-not auth2
(swap! *state assoc :blocked? true))))
(defn signin-signout []
[:div {:class "signin-signout"}
[:div {:class "g-signin2"
:data-onsuccess "signIn"
:style {:display (if (:signed-in? @*state) "none" "block")}}]
[ui/raised-button {:on-click (fn []
(auth/sign-out #(swap! *state assoc :signed-in? false)))
:style {:display (if (:signed-in? @*state) "block" "none")}}
"Sign Out"]])
(defn new-project [project-name template]
(.send XhrIo
"/new-project"
(fn [e]
(when (.isSuccess (.-target e))
(set! (.-location js/window) (.. e -target getResponseText))))
"POST"
(pr-str {:project-type template
:project-name project-name})))
(defn delete-user []
(.send XhrIo
"/delete-user"
(fn []
(auth/sign-out #(.reload js/window.location)))
"POST"))
(defn delete-project [project-id]
(.send XhrIo
"/delete-project"
#(.reload js/window.location)
"POST"
(pr-str {:project-id project-id})))
(defn new-project-dialog []
(let [project-name (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :new-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(new-project @project-name (:new-project-template @*state))
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:disabled (not (seq @project-name))
:style {:margin "10px"}}
"Create Project"])]}
[ui/text-field
{:floating-label-text "Choose a name for your project"
:full-width true
:on-change #(reset! project-name (.-value (.-target %)))}]])))
(defn delete-project-dialog []
(let [email (r/atom nil)]
(fn []
(when-let [{:keys [project-name project-id]} (:project @*state)]
[ui/dialog {:modal true
:open (= :delete-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :project)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-project project-id)
(swap! *state dissoc :dialog :project)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Project"])]}
[ui/text-field
{:floating-label-text (str "Enter your email to confirm you want to delete " project-name)
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]]))))
(defn delete-user-dialog []
(let [email (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :delete-user (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-user)
(swap! *state dissoc :dialog)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Account"])]}
[ui/text-field
{:floating-label-text "Enter your email to confirm you want to delete your entire account"
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]])))
(defn templates []
[:div {:class "card-group"}
[:div {:style {:margin "10px"}}
[:center
[:h3 "Create a new project:"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :reagent)}
"Web App"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :play-cljs)}
"Game"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :edna)}
"Music"]
(when (seq (-> @*state :user :projects))
[:div
[:h3 "Open an existing project:"]
(for [{:keys [url project-name project-id] :as project} (-> @*state :user :projects)]
[:div
[ui/chip {:key project-id
:style {:margin "5px"
:display "inline-flex"}
:on-click #(set! (.-location js/window) url)
:on-request-delete #(swap! *state assoc :dialog :delete-project :project project)}
[:div {:style {:min-width "100px"}}
project-name]]])])]]])
(defn intro []
[:div {:class "card-group"}
[:div {:style {:margin "10px"
:text-align "center"}}
[:p "Build web apps and games with ClojureScript, entirely in your browser."]
[:p "Sign in with your Google account and start coding for free."]
(when (:blocked? @*state)
[:p [:b [:i "It looks like something in your browser is blocking the Google sign on!"]]])
[:img {:src "screenshot.png"
:style {:width "95%"
:margin-bottom "10px"}}]]])
(defn app []
[ui/mui-theme-provider
{:mui-theme (get-mui-theme (goog.object/get js/MaterialUIStyles "DarkRawTheme"))}
[:div
[signin-signout]
[new-project-dialog]
[delete-project-dialog]
[delete-user-dialog]
(if (:signed-in? @*state)
[templates]
[intro])
[:div {:class "card-group"}
[:center
[:p "You can support this website via "
[:a {:href "https://www.patreon.com/sekao" :target "_blank"}
"my patreon"]]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Bring in libraries"]]
[:p "You can add any ClojureScript library you want — including popular ones like core.async and Reagent."]
[:img {:src "libraries.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Take it offline"]]
[:p
"Download your project at any time. It'll come with "
[:a {:href "https://sekao.net/nightlight/" :target "_blank"} "Nightlight"]
", an offline version of this website."]
[:img {:src "export.png"
:class "small-img"}]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Reload instantly"]]
[:p "Write your code in one tab, and see your app in another. Changes are pushed down without refreshing."]
[:img {:src "reload.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Fire up a REPL"]]
[:p "For even more interactivity, you can start the REPL to poke and prod your app as you develop it."]
[:img {:src "repl.png"
:class "small-img"}]]]
[:div
[:center
(when (:signed-in? @*state)
[:p [:a {:href "#" :on-click #(swap! *state assoc :dialog :delete-user)}
"Delete your entire account"]])
[:p]
[:p "Made by "
[:a {:href "https://sekao.net/" :target "_blank"} "Zach Oakes"]]
[:p "Feedback and discussion welcome on "
[:a {:href "https://www.reddit.com/r/Nightcode/" :target "_blank"} "/r/Nightcode"]]]]]])
(r/render-component [app] (.querySelector js/document "#app"))
| 64374 | (ns nightcoders.core
(:require [reagent.core :as r]
[cljs.reader :refer [read-string]]
[cljsjs.material-ui]
[cljs-react-material-ui.core :refer [get-mui-theme]]
[cljs-react-material-ui.reagent :as ui]
[nightcoders.auth :as auth]
[goog.object])
(:import goog.net.XhrIo))
(defonce *state (r/atom {}))
(auth/set-sign-in (fn [success? user]
(when success?
(swap! *state assoc
:signed-in? true
:user (read-string user)))))
(auth/load (fn [auth2]
(when-not auth2
(swap! *state assoc :blocked? true))))
(defn signin-signout []
[:div {:class "signin-signout"}
[:div {:class "g-signin2"
:data-onsuccess "signIn"
:style {:display (if (:signed-in? @*state) "none" "block")}}]
[ui/raised-button {:on-click (fn []
(auth/sign-out #(swap! *state assoc :signed-in? false)))
:style {:display (if (:signed-in? @*state) "block" "none")}}
"Sign Out"]])
(defn new-project [project-name template]
(.send XhrIo
"/new-project"
(fn [e]
(when (.isSuccess (.-target e))
(set! (.-location js/window) (.. e -target getResponseText))))
"POST"
(pr-str {:project-type template
:project-name project-name})))
(defn delete-user []
(.send XhrIo
"/delete-user"
(fn []
(auth/sign-out #(.reload js/window.location)))
"POST"))
(defn delete-project [project-id]
(.send XhrIo
"/delete-project"
#(.reload js/window.location)
"POST"
(pr-str {:project-id project-id})))
(defn new-project-dialog []
(let [project-name (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :new-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(new-project @project-name (:new-project-template @*state))
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:disabled (not (seq @project-name))
:style {:margin "10px"}}
"Create Project"])]}
[ui/text-field
{:floating-label-text "Choose a name for your project"
:full-width true
:on-change #(reset! project-name (.-value (.-target %)))}]])))
(defn delete-project-dialog []
(let [email (r/atom nil)]
(fn []
(when-let [{:keys [project-name project-id]} (:project @*state)]
[ui/dialog {:modal true
:open (= :delete-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :project)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-project project-id)
(swap! *state dissoc :dialog :project)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Project"])]}
[ui/text-field
{:floating-label-text (str "Enter your email to confirm you want to delete " project-name)
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]]))))
(defn delete-user-dialog []
(let [email (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :delete-user (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-user)
(swap! *state dissoc :dialog)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Account"])]}
[ui/text-field
{:floating-label-text "Enter your email to confirm you want to delete your entire account"
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]])))
(defn templates []
[:div {:class "card-group"}
[:div {:style {:margin "10px"}}
[:center
[:h3 "Create a new project:"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :reagent)}
"Web App"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :play-cljs)}
"Game"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :edna)}
"Music"]
(when (seq (-> @*state :user :projects))
[:div
[:h3 "Open an existing project:"]
(for [{:keys [url project-name project-id] :as project} (-> @*state :user :projects)]
[:div
[ui/chip {:key project-id
:style {:margin "5px"
:display "inline-flex"}
:on-click #(set! (.-location js/window) url)
:on-request-delete #(swap! *state assoc :dialog :delete-project :project project)}
[:div {:style {:min-width "100px"}}
project-name]]])])]]])
(defn intro []
[:div {:class "card-group"}
[:div {:style {:margin "10px"
:text-align "center"}}
[:p "Build web apps and games with ClojureScript, entirely in your browser."]
[:p "Sign in with your Google account and start coding for free."]
(when (:blocked? @*state)
[:p [:b [:i "It looks like something in your browser is blocking the Google sign on!"]]])
[:img {:src "screenshot.png"
:style {:width "95%"
:margin-bottom "10px"}}]]])
(defn app []
[ui/mui-theme-provider
{:mui-theme (get-mui-theme (goog.object/get js/MaterialUIStyles "DarkRawTheme"))}
[:div
[signin-signout]
[new-project-dialog]
[delete-project-dialog]
[delete-user-dialog]
(if (:signed-in? @*state)
[templates]
[intro])
[:div {:class "card-group"}
[:center
[:p "You can support this website via "
[:a {:href "https://www.patreon.com/sekao" :target "_blank"}
"my patreon"]]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Bring in libraries"]]
[:p "You can add any ClojureScript library you want — including popular ones like core.async and Reagent."]
[:img {:src "libraries.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Take it offline"]]
[:p
"Download your project at any time. It'll come with "
[:a {:href "https://sekao.net/nightlight/" :target "_blank"} "Nightlight"]
", an offline version of this website."]
[:img {:src "export.png"
:class "small-img"}]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Reload instantly"]]
[:p "Write your code in one tab, and see your app in another. Changes are pushed down without refreshing."]
[:img {:src "reload.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Fire up a REPL"]]
[:p "For even more interactivity, you can start the REPL to poke and prod your app as you develop it."]
[:img {:src "repl.png"
:class "small-img"}]]]
[:div
[:center
(when (:signed-in? @*state)
[:p [:a {:href "#" :on-click #(swap! *state assoc :dialog :delete-user)}
"Delete your entire account"]])
[:p]
[:p "Made by "
[:a {:href "https://sekao.net/" :target "_blank"} "<NAME>"]]
[:p "Feedback and discussion welcome on "
[:a {:href "https://www.reddit.com/r/Nightcode/" :target "_blank"} "/r/Nightcode"]]]]]])
(r/render-component [app] (.querySelector js/document "#app"))
| true | (ns nightcoders.core
(:require [reagent.core :as r]
[cljs.reader :refer [read-string]]
[cljsjs.material-ui]
[cljs-react-material-ui.core :refer [get-mui-theme]]
[cljs-react-material-ui.reagent :as ui]
[nightcoders.auth :as auth]
[goog.object])
(:import goog.net.XhrIo))
(defonce *state (r/atom {}))
(auth/set-sign-in (fn [success? user]
(when success?
(swap! *state assoc
:signed-in? true
:user (read-string user)))))
(auth/load (fn [auth2]
(when-not auth2
(swap! *state assoc :blocked? true))))
(defn signin-signout []
[:div {:class "signin-signout"}
[:div {:class "g-signin2"
:data-onsuccess "signIn"
:style {:display (if (:signed-in? @*state) "none" "block")}}]
[ui/raised-button {:on-click (fn []
(auth/sign-out #(swap! *state assoc :signed-in? false)))
:style {:display (if (:signed-in? @*state) "block" "none")}}
"Sign Out"]])
(defn new-project [project-name template]
(.send XhrIo
"/new-project"
(fn [e]
(when (.isSuccess (.-target e))
(set! (.-location js/window) (.. e -target getResponseText))))
"POST"
(pr-str {:project-type template
:project-name project-name})))
(defn delete-user []
(.send XhrIo
"/delete-user"
(fn []
(auth/sign-out #(.reload js/window.location)))
"POST"))
(defn delete-project [project-id]
(.send XhrIo
"/delete-project"
#(.reload js/window.location)
"POST"
(pr-str {:project-id project-id})))
(defn new-project-dialog []
(let [project-name (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :new-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(new-project @project-name (:new-project-template @*state))
(swap! *state dissoc :dialog :new-project-template)
(reset! project-name nil))
:disabled (not (seq @project-name))
:style {:margin "10px"}}
"Create Project"])]}
[ui/text-field
{:floating-label-text "Choose a name for your project"
:full-width true
:on-change #(reset! project-name (.-value (.-target %)))}]])))
(defn delete-project-dialog []
(let [email (r/atom nil)]
(fn []
(when-let [{:keys [project-name project-id]} (:project @*state)]
[ui/dialog {:modal true
:open (= :delete-project (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog :project)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-project project-id)
(swap! *state dissoc :dialog :project)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Project"])]}
[ui/text-field
{:floating-label-text (str "Enter your email to confirm you want to delete " project-name)
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]]))))
(defn delete-user-dialog []
(let [email (r/atom nil)]
(fn []
[ui/dialog {:modal true
:open (= :delete-user (:dialog @*state))
:actions
[(r/as-element
[ui/flat-button {:on-click (fn []
(swap! *state dissoc :dialog)
(reset! email nil))
:style {:margin "10px"}}
"Cancel"])
(r/as-element
[ui/flat-button {:on-click (fn []
(delete-user)
(swap! *state dissoc :dialog)
(reset! email nil))
:disabled (not= @email (-> @*state :user :email))
:style {:margin "10px"}}
"Delete Account"])]}
[ui/text-field
{:floating-label-text "Enter your email to confirm you want to delete your entire account"
:full-width true
:on-change #(reset! email (.-value (.-target %)))}]])))
(defn templates []
[:div {:class "card-group"}
[:div {:style {:margin "10px"}}
[:center
[:h3 "Create a new project:"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :reagent)}
"Web App"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :play-cljs)}
"Game"]
[ui/raised-button {:class "btn"
:on-click #(swap! *state assoc :dialog :new-project :new-project-template :edna)}
"Music"]
(when (seq (-> @*state :user :projects))
[:div
[:h3 "Open an existing project:"]
(for [{:keys [url project-name project-id] :as project} (-> @*state :user :projects)]
[:div
[ui/chip {:key project-id
:style {:margin "5px"
:display "inline-flex"}
:on-click #(set! (.-location js/window) url)
:on-request-delete #(swap! *state assoc :dialog :delete-project :project project)}
[:div {:style {:min-width "100px"}}
project-name]]])])]]])
(defn intro []
[:div {:class "card-group"}
[:div {:style {:margin "10px"
:text-align "center"}}
[:p "Build web apps and games with ClojureScript, entirely in your browser."]
[:p "Sign in with your Google account and start coding for free."]
(when (:blocked? @*state)
[:p [:b [:i "It looks like something in your browser is blocking the Google sign on!"]]])
[:img {:src "screenshot.png"
:style {:width "95%"
:margin-bottom "10px"}}]]])
(defn app []
[ui/mui-theme-provider
{:mui-theme (get-mui-theme (goog.object/get js/MaterialUIStyles "DarkRawTheme"))}
[:div
[signin-signout]
[new-project-dialog]
[delete-project-dialog]
[delete-user-dialog]
(if (:signed-in? @*state)
[templates]
[intro])
[:div {:class "card-group"}
[:center
[:p "You can support this website via "
[:a {:href "https://www.patreon.com/sekao" :target "_blank"}
"my patreon"]]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Bring in libraries"]]
[:p "You can add any ClojureScript library you want — including popular ones like core.async and Reagent."]
[:img {:src "libraries.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Take it offline"]]
[:p
"Download your project at any time. It'll come with "
[:a {:href "https://sekao.net/nightlight/" :target "_blank"} "Nightlight"]
", an offline version of this website."]
[:img {:src "export.png"
:class "small-img"}]]]
[:div {:class "card-group"}
[:div {:class "small-card"}
[:center [:h2 "Reload instantly"]]
[:p "Write your code in one tab, and see your app in another. Changes are pushed down without refreshing."]
[:img {:src "reload.png"
:class "small-img"}]]
[:div {:class "small-card"}
[:center [:h2 "Fire up a REPL"]]
[:p "For even more interactivity, you can start the REPL to poke and prod your app as you develop it."]
[:img {:src "repl.png"
:class "small-img"}]]]
[:div
[:center
(when (:signed-in? @*state)
[:p [:a {:href "#" :on-click #(swap! *state assoc :dialog :delete-user)}
"Delete your entire account"]])
[:p]
[:p "Made by "
[:a {:href "https://sekao.net/" :target "_blank"} "PI:NAME:<NAME>END_PI"]]
[:p "Feedback and discussion welcome on "
[:a {:href "https://www.reddit.com/r/Nightcode/" :target "_blank"} "/r/Nightcode"]]]]]])
(r/render-component [app] (.querySelector js/document "#app"))
|
[
{
"context": " :initial_token \"123XYZ\"\n :auto_bootstrap ",
"end": 1462,
"score": 0.991226077079773,
"start": 1456,
"tag": "KEY",
"value": "123XYZ"
},
{
"context": " :initial_token \"123XYZ\"\n :auto_bootstrap ",
"end": 3039,
"score": 0.9527432918548584,
"start": 3033,
"tag": "PASSWORD",
"value": "123XYZ"
},
{
"context": " :initial_token \"123XYZ\"\n :auto_bootstrap ",
"end": 5785,
"score": 0.8849213719367981,
"start": 5779,
"tag": "KEY",
"value": "123XYZ"
},
{
"context": " :initial_token \"123XYZ\"\n :auto_b",
"end": 11661,
"score": 0.5592978000640869,
"start": 11655,
"tag": "PASSWORD",
"value": "123XYZ"
},
{
"context": " :initial_token \"123XYZ\"\n :auto_boo",
"end": 14568,
"score": 0.9612195491790771,
"start": 14562,
"tag": "KEY",
"value": "123XYZ"
}
] | test/com/datastax/configbuilder/build_config_test.clj | XN137/cass-config-builder | 0 | ;; Copyright DataStax, Inc.
;; Please see the included license file for details.
(ns com.datastax.configbuilder.build-config-test
(:require [clojure.test :refer :all]
[com.datastax.configbuilder.test-data :as test-data]
[com.datastax.configbuilder.test-helpers :as helper]
[com.datastax.configbuilder.build-config :as bc]
[com.datastax.configbuilder.definitions :as d]
[slingshot.test :refer :all]))
(deftest test-with-defaults
(let [configs
(bc/with-defaults (test-data/get-definitions-data helper/default-dse-version)
{})]
;; Check the total number of config files
(is (= 22 (count configs)))
;; Check some random default values
(is (= "/var/lib/cassandra/commitlog"
(get-in configs [:cassandra-yaml :commitlog_directory])))
(is (= 128 (get-in configs [:cassandra-yaml :io_global_queue_depth])))))
(deftest test-allow-custom-seed-provider
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "123XYZ"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:seed_provider [{:class_name "org.apache.cassandra.locator.K8SeedProvider"
:parameters [{:seeds "1,2,3"}]}]}})]
(is (= "org.apache.cassandra.locator.K8SeedProvider" (get-in built-configs [:cassandra-yaml :seed_provider 0 :class_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))))
(deftest test-build-configs-for-oss-cassandra
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "123XYZ"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:num_tokens 201}})]
(testing "does anything at all work even a little bit"
(is (= 201 (get-in built-configs [:cassandra-yaml :num_tokens]))))
(testing "do we use rpc_address instead of DSE's new config name native_transport_address"
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :rpc_address]))))))
(deftest test-ensure-correct-address-field-names
(let [expected-old {:rpc_address "1.1.1.1"
:broadcast_rpc_address "2.2.2.2"
:some_other_prop "some value"}
expected-new {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}
fields {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}]
(testing "DSE 6.0.0+ uses new names"
(is (= (bc/ensure-correct-address-field-names "dse" "6.0.0" fields)
expected-new)))
(testing "DSE 5.0.0 uses old names"
(is (= (bc/ensure-correct-address-field-names "dse" "5.0.0" fields)
expected-old)))
(testing "Cassandra uses old names"
(is (= (bc/ensure-correct-address-field-names "cassandra" "7.0.0" fields)
expected-old)))))
(deftest test-build-configs
(testing "for package installs"
(let [datacenter-info {:name "dc-1"
:graph-enabled 1
:spark-enabled 0
:solr-enabled 0}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "123XYZ"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cluster-info (assoc cluster-info :datastax-version helper/default-dse-version)
:node-info node-info
:datacenter-info datacenter-info
:dse-env-sh {:dse-log-root "/foo/log"
:cassandra-log-dir "/foo/log/cassandra"}})]
(testing "- cassandra.yaml"
(testing "default values"
(is (= 128 (get-in built-configs [:cassandra-yaml :io_global_queue_depth]))))
(testing "ignored fields"
(is (nil? (get-in built-configs [:cassandra-yaml :rack]))))
(testing "enriched fields"
(doseq [[field-name field-val] (dissoc node-info :name :rack)]
(is (= field-val (get-in built-configs [:cassandra-yaml field-name]))
(format "Missing or incorrect value for field %s" field-name)))
(is (= "test-cluster-1" (get-in built-configs [:cassandra-yaml :cluster_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :native_transport_address])))
(is (= "1.1.1.4" (get-in built-configs [:cassandra-yaml :native_transport_broadcast_address])))
(is (every? nil? (map (:cassandra-yaml built-configs) [:rpc_address :broadcast_rpc_address])))))
(testing "- cassandra-env.sh"
(is (true? (get-in built-configs [:cassandra-env-sh :enable_on_out_of_memory_error])))
(is (= "kill -9 %p" (get-in built-configs [:cassandra-env-sh :on_out_of_memory_error])))
(is (= 7199
(get-in built-configs [:jvm-options :jmx-port]) ;; source
(get-in built-configs [:cassandra-env-sh :jmx-port]))))
(testing "- dse.default"
(is (= (select-keys datacenter-info bc/workload-keys)
(select-keys (:dse-default built-configs) bc/workload-keys)))
(is (= {:cassandra-user "cassandra"
:cassandra-group "cassandra"}
(select-keys (get built-configs :dse-default)
[:cassandra-user
:cassandra-group]))))
(testing "- cassandra-rackdc.properties"
(is (= {:dc "dc-1" :rack "rack-1"}
(:cassandra-rackdc-properties built-configs))))
(testing "- dse-env.sh"
(is (= "/foo/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir]))))
(testing "Dependent fields should not be present unless their condition is satisfied"
(is (false? (get-in built-configs [:dse-yaml :spark_cluster_info_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :spark_cluster_info_options :refresh_rate_ms]
:missing)))
;; Try a nested dict with a dependency. Use not instead of false? because this
;; enabled field is a ternary_boolean with nil default value.
(is (not (get-in built-configs [:dse-yaml :dsefs_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :dsefs_options :gossip_options]
:missing))))))
(testing "for tarball installs"
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:install-options {:install-type "tarball"
:install-directory "/home/targ/dse"}
:dse-env-sh {:dse-log-root "log"
:cassandra-log-dir "log/cassandra"}})]
(testing "- dse.yaml"
(is (= "/home/targ/dse/resources/dse/conf"
(get-in built-configs [:dse-yaml :system_key_directory]))))
(testing "- dse-env.sh"
(is (= "/home/targ/dse/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir])))))))
(deftest test-unmanage-config-file
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
;; we should be able to unmanage a file based on config-file-id
{:cassandra-yaml {:lcm-manage--cassandra-yaml false}})]
(is (= true (contains? built-configs :dse-yaml)))
(is (= false (contains? built-configs :cassandra-yaml)))))
(deftest test-build-configs-no-enrichment
(testing "configs with no enrichment"
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "123XYZ"
:auto_bootstrap true}}
enriched-keys #{:cassandra-yaml
:cassandra-env-sh
:dse-default
:cassandra-rackdc-properties
:dse-in-sh}
definitions-data (test-data/get-definitions-data helper/default-dse-version)
config-data-with-defaults (bc/with-defaults definitions-data config-data)
enriched-config-data (bc/build-configs definitions-data config-data)
unmodified-configs (apply dissoc enriched-config-data
(concat enriched-keys bc/model-info-keys))]
(doseq [[config-key config-value] unmodified-configs]
;; If this fails, an enriched config may have been added. If this is the
;; case, add it's config-key to enriched-keys above.
(is (= (get config-data-with-defaults config-key) config-value)
(str "Expected config to be unmodified, but it has been enriched: " config-key)))
;; If this fails and the actual count is...
;; a) Greater than expected - a new config-key has likely been added to the config-data map, and
;; that key is not being enriched. Either it should be enriched, or the expected count
;; should be incremented.
;; b) Less than expected - a key that used to be unmodified has either been removed or is
;; now an enriched config. In the former case, decrement the expected count. For the
;; latter, add it's config-key to the enriched-keys set above.
(is (= 17 (count unmodified-configs))))))
(deftest test-build-configs-bad-keys
;; What happens when a key exists in config-data for which there is no corresponding key
;; in definitions? The answer - an exception is thrown!
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "123XYZ"
:auto_bootstrap true}
:bad-config {:a 12}}
definitions-data (test-data/get-definitions-data helper/default-dse-version)]
(is (thrown+? [:type :InvalidConfigKeys]
(bc/build-configs definitions-data config-data)))))
(deftest test-build-configs-file-paths
(let [built-configs (bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cassandra-yaml {}
:address-yaml {}})]
(is (= "/etc/dse/cassandra/cassandra.yaml"
(get-in built-configs [:node-info :file-paths :cassandra-yaml])))
(is (= (:package-path bc/address-yaml-paths)
(get-in built-configs [:node-info :file-paths :address-yaml])))))
(deftest test-get-configured-paths
(let [configured-paths
(get-in
(bc/get-configured-paths
{:definitions
{:foobie
{:display-name "foobie.yaml"
:properties
{:blah_dirs {:type "list"
:value_type "string"
:default_value ["/blah/default"]
:is_directory true}
:foo_dir {:type "string"
:default_value "/foo/default"
:is_file true}
:bar_dir {:type "string"
:is_directory true}}}}}
:foobie
{:foobie {:blah_dirs ["/a/b/c" "/d/e/f"]
:foo_dir "/foo/default"
:bar_dir "/j/k/l"}})
[:node-info :configured-paths])]
(is (= 4 (count configured-paths)))
(doseq [configured-path configured-paths]
(is (= "foobie.yaml" (:config-file configured-path)))
(condp = (:key configured-path)
[:blah_dirs]
(do
(is (#{"/a/b/c" "/d/e/f"} (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
[:foo_dir]
(do
(is (= "/foo/default" (:path configured-path)))
(is (false? (:custom? configured-path)))
(is (false? (:directory? configured-path))))
[:bar_dir]
(do
(is (= "/j/k/l" (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
(do
(is (= "Unexpected value" configured-path))))))
(testing "for tarball installs"
(let [definitions-data (update (test-data/get-definitions-data helper/default-dse-version)
:definitions
d/use-tarball-defaults)
[configured-path]
(get-in
(bc/get-configured-paths definitions-data
:dse-yaml
{:dse-yaml {:system_key_directory "resources/dse/conf"}})
[:node-info :configured-paths])]
(is configured-path)
(is (= "resources/dse/conf" (:path configured-path)))
(is (false? (:custom? configured-path))))))
(deftest test-fully-qualify-paths
(let [definitions-data (test-data/get-definitions-data)
config-key :cassandra-yaml]
(testing "No-op for package installs"
(let [config-data {:install-options
{:install-type "package"}
:cassandra-yaml
{:data_file_directories ["/var/data1" "/var/data2"]
:commitlog_directory "/var/commitlog"
:client_encryption_options
{:enabled true
:keystore "/etc/dse/keystore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= result config-data)
"Should not modify paths for package install")))
(testing "Tarball installs"
(let [config-data {:install-options
{:install-type "tarball"
:install-directory "/opt/dse"}
:cassandra-yaml
{:data_file_directories ["var/data1" "var/data2" "/var/data3"]
:commitlog_directory "var/commitlog"
:client_encryption_options
{:enabled true
:keystore "etc/dse/keystore"
:truststore "/etc/dse/truststore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= ["/opt/dse/var/data1"
"/opt/dse/var/data2"
"/var/data3"]
(get-in result [:cassandra-yaml :data_file_directories]))
"Should fully-qualify relative paths in vectors")
(is (= "/opt/dse/var/commitlog"
(get-in result [:cassandra-yaml :commitlog_directory]))
"Should fully-qualify relative directory paths")
(is (= "/opt/dse/etc/dse/keystore"
(get-in result [:cassandra-yaml :client_encryption_options :keystore]))
"Should fully-qualify relative file paths")
(is (= "/etc/dse/truststore"
(get-in result [:cassandra-yaml :client_encryption_options :truststore]))
"Should not transform paths that are already absolute")))))
(deftest test-get-install-directory
(testing "Non-empty install-directory"
(is (= "/a/b/c"
(bc/get-install-directory {:install-options
{:install-directory "/a/b/c"}}))))
(testing "Empty install-directory"
(is (= "/d/e/f"
(bc/get-install-directory {:install-options
{:install-directory ""}
:node-info
{:facts
{:run-context
{:install-options
{:install-directory "/d/e/f"}}}}})))))
| 54302 | ;; Copyright DataStax, Inc.
;; Please see the included license file for details.
(ns com.datastax.configbuilder.build-config-test
(:require [clojure.test :refer :all]
[com.datastax.configbuilder.test-data :as test-data]
[com.datastax.configbuilder.test-helpers :as helper]
[com.datastax.configbuilder.build-config :as bc]
[com.datastax.configbuilder.definitions :as d]
[slingshot.test :refer :all]))
(deftest test-with-defaults
(let [configs
(bc/with-defaults (test-data/get-definitions-data helper/default-dse-version)
{})]
;; Check the total number of config files
(is (= 22 (count configs)))
;; Check some random default values
(is (= "/var/lib/cassandra/commitlog"
(get-in configs [:cassandra-yaml :commitlog_directory])))
(is (= 128 (get-in configs [:cassandra-yaml :io_global_queue_depth])))))
(deftest test-allow-custom-seed-provider
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "<KEY>"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:seed_provider [{:class_name "org.apache.cassandra.locator.K8SeedProvider"
:parameters [{:seeds "1,2,3"}]}]}})]
(is (= "org.apache.cassandra.locator.K8SeedProvider" (get-in built-configs [:cassandra-yaml :seed_provider 0 :class_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))))
(deftest test-build-configs-for-oss-cassandra
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "<KEY>"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:num_tokens 201}})]
(testing "does anything at all work even a little bit"
(is (= 201 (get-in built-configs [:cassandra-yaml :num_tokens]))))
(testing "do we use rpc_address instead of DSE's new config name native_transport_address"
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :rpc_address]))))))
(deftest test-ensure-correct-address-field-names
(let [expected-old {:rpc_address "1.1.1.1"
:broadcast_rpc_address "2.2.2.2"
:some_other_prop "some value"}
expected-new {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}
fields {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}]
(testing "DSE 6.0.0+ uses new names"
(is (= (bc/ensure-correct-address-field-names "dse" "6.0.0" fields)
expected-new)))
(testing "DSE 5.0.0 uses old names"
(is (= (bc/ensure-correct-address-field-names "dse" "5.0.0" fields)
expected-old)))
(testing "Cassandra uses old names"
(is (= (bc/ensure-correct-address-field-names "cassandra" "7.0.0" fields)
expected-old)))))
(deftest test-build-configs
(testing "for package installs"
(let [datacenter-info {:name "dc-1"
:graph-enabled 1
:spark-enabled 0
:solr-enabled 0}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "<KEY>"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cluster-info (assoc cluster-info :datastax-version helper/default-dse-version)
:node-info node-info
:datacenter-info datacenter-info
:dse-env-sh {:dse-log-root "/foo/log"
:cassandra-log-dir "/foo/log/cassandra"}})]
(testing "- cassandra.yaml"
(testing "default values"
(is (= 128 (get-in built-configs [:cassandra-yaml :io_global_queue_depth]))))
(testing "ignored fields"
(is (nil? (get-in built-configs [:cassandra-yaml :rack]))))
(testing "enriched fields"
(doseq [[field-name field-val] (dissoc node-info :name :rack)]
(is (= field-val (get-in built-configs [:cassandra-yaml field-name]))
(format "Missing or incorrect value for field %s" field-name)))
(is (= "test-cluster-1" (get-in built-configs [:cassandra-yaml :cluster_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :native_transport_address])))
(is (= "1.1.1.4" (get-in built-configs [:cassandra-yaml :native_transport_broadcast_address])))
(is (every? nil? (map (:cassandra-yaml built-configs) [:rpc_address :broadcast_rpc_address])))))
(testing "- cassandra-env.sh"
(is (true? (get-in built-configs [:cassandra-env-sh :enable_on_out_of_memory_error])))
(is (= "kill -9 %p" (get-in built-configs [:cassandra-env-sh :on_out_of_memory_error])))
(is (= 7199
(get-in built-configs [:jvm-options :jmx-port]) ;; source
(get-in built-configs [:cassandra-env-sh :jmx-port]))))
(testing "- dse.default"
(is (= (select-keys datacenter-info bc/workload-keys)
(select-keys (:dse-default built-configs) bc/workload-keys)))
(is (= {:cassandra-user "cassandra"
:cassandra-group "cassandra"}
(select-keys (get built-configs :dse-default)
[:cassandra-user
:cassandra-group]))))
(testing "- cassandra-rackdc.properties"
(is (= {:dc "dc-1" :rack "rack-1"}
(:cassandra-rackdc-properties built-configs))))
(testing "- dse-env.sh"
(is (= "/foo/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir]))))
(testing "Dependent fields should not be present unless their condition is satisfied"
(is (false? (get-in built-configs [:dse-yaml :spark_cluster_info_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :spark_cluster_info_options :refresh_rate_ms]
:missing)))
;; Try a nested dict with a dependency. Use not instead of false? because this
;; enabled field is a ternary_boolean with nil default value.
(is (not (get-in built-configs [:dse-yaml :dsefs_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :dsefs_options :gossip_options]
:missing))))))
(testing "for tarball installs"
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:install-options {:install-type "tarball"
:install-directory "/home/targ/dse"}
:dse-env-sh {:dse-log-root "log"
:cassandra-log-dir "log/cassandra"}})]
(testing "- dse.yaml"
(is (= "/home/targ/dse/resources/dse/conf"
(get-in built-configs [:dse-yaml :system_key_directory]))))
(testing "- dse-env.sh"
(is (= "/home/targ/dse/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir])))))))
(deftest test-unmanage-config-file
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
;; we should be able to unmanage a file based on config-file-id
{:cassandra-yaml {:lcm-manage--cassandra-yaml false}})]
(is (= true (contains? built-configs :dse-yaml)))
(is (= false (contains? built-configs :cassandra-yaml)))))
(deftest test-build-configs-no-enrichment
(testing "configs with no enrichment"
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "<KEY>"
:auto_bootstrap true}}
enriched-keys #{:cassandra-yaml
:cassandra-env-sh
:dse-default
:cassandra-rackdc-properties
:dse-in-sh}
definitions-data (test-data/get-definitions-data helper/default-dse-version)
config-data-with-defaults (bc/with-defaults definitions-data config-data)
enriched-config-data (bc/build-configs definitions-data config-data)
unmodified-configs (apply dissoc enriched-config-data
(concat enriched-keys bc/model-info-keys))]
(doseq [[config-key config-value] unmodified-configs]
;; If this fails, an enriched config may have been added. If this is the
;; case, add it's config-key to enriched-keys above.
(is (= (get config-data-with-defaults config-key) config-value)
(str "Expected config to be unmodified, but it has been enriched: " config-key)))
;; If this fails and the actual count is...
;; a) Greater than expected - a new config-key has likely been added to the config-data map, and
;; that key is not being enriched. Either it should be enriched, or the expected count
;; should be incremented.
;; b) Less than expected - a key that used to be unmodified has either been removed or is
;; now an enriched config. In the former case, decrement the expected count. For the
;; latter, add it's config-key to the enriched-keys set above.
(is (= 17 (count unmodified-configs))))))
(deftest test-build-configs-bad-keys
;; What happens when a key exists in config-data for which there is no corresponding key
;; in definitions? The answer - an exception is thrown!
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "<KEY>"
:auto_bootstrap true}
:bad-config {:a 12}}
definitions-data (test-data/get-definitions-data helper/default-dse-version)]
(is (thrown+? [:type :InvalidConfigKeys]
(bc/build-configs definitions-data config-data)))))
(deftest test-build-configs-file-paths
(let [built-configs (bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cassandra-yaml {}
:address-yaml {}})]
(is (= "/etc/dse/cassandra/cassandra.yaml"
(get-in built-configs [:node-info :file-paths :cassandra-yaml])))
(is (= (:package-path bc/address-yaml-paths)
(get-in built-configs [:node-info :file-paths :address-yaml])))))
(deftest test-get-configured-paths
(let [configured-paths
(get-in
(bc/get-configured-paths
{:definitions
{:foobie
{:display-name "foobie.yaml"
:properties
{:blah_dirs {:type "list"
:value_type "string"
:default_value ["/blah/default"]
:is_directory true}
:foo_dir {:type "string"
:default_value "/foo/default"
:is_file true}
:bar_dir {:type "string"
:is_directory true}}}}}
:foobie
{:foobie {:blah_dirs ["/a/b/c" "/d/e/f"]
:foo_dir "/foo/default"
:bar_dir "/j/k/l"}})
[:node-info :configured-paths])]
(is (= 4 (count configured-paths)))
(doseq [configured-path configured-paths]
(is (= "foobie.yaml" (:config-file configured-path)))
(condp = (:key configured-path)
[:blah_dirs]
(do
(is (#{"/a/b/c" "/d/e/f"} (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
[:foo_dir]
(do
(is (= "/foo/default" (:path configured-path)))
(is (false? (:custom? configured-path)))
(is (false? (:directory? configured-path))))
[:bar_dir]
(do
(is (= "/j/k/l" (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
(do
(is (= "Unexpected value" configured-path))))))
(testing "for tarball installs"
(let [definitions-data (update (test-data/get-definitions-data helper/default-dse-version)
:definitions
d/use-tarball-defaults)
[configured-path]
(get-in
(bc/get-configured-paths definitions-data
:dse-yaml
{:dse-yaml {:system_key_directory "resources/dse/conf"}})
[:node-info :configured-paths])]
(is configured-path)
(is (= "resources/dse/conf" (:path configured-path)))
(is (false? (:custom? configured-path))))))
(deftest test-fully-qualify-paths
(let [definitions-data (test-data/get-definitions-data)
config-key :cassandra-yaml]
(testing "No-op for package installs"
(let [config-data {:install-options
{:install-type "package"}
:cassandra-yaml
{:data_file_directories ["/var/data1" "/var/data2"]
:commitlog_directory "/var/commitlog"
:client_encryption_options
{:enabled true
:keystore "/etc/dse/keystore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= result config-data)
"Should not modify paths for package install")))
(testing "Tarball installs"
(let [config-data {:install-options
{:install-type "tarball"
:install-directory "/opt/dse"}
:cassandra-yaml
{:data_file_directories ["var/data1" "var/data2" "/var/data3"]
:commitlog_directory "var/commitlog"
:client_encryption_options
{:enabled true
:keystore "etc/dse/keystore"
:truststore "/etc/dse/truststore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= ["/opt/dse/var/data1"
"/opt/dse/var/data2"
"/var/data3"]
(get-in result [:cassandra-yaml :data_file_directories]))
"Should fully-qualify relative paths in vectors")
(is (= "/opt/dse/var/commitlog"
(get-in result [:cassandra-yaml :commitlog_directory]))
"Should fully-qualify relative directory paths")
(is (= "/opt/dse/etc/dse/keystore"
(get-in result [:cassandra-yaml :client_encryption_options :keystore]))
"Should fully-qualify relative file paths")
(is (= "/etc/dse/truststore"
(get-in result [:cassandra-yaml :client_encryption_options :truststore]))
"Should not transform paths that are already absolute")))))
(deftest test-get-install-directory
(testing "Non-empty install-directory"
(is (= "/a/b/c"
(bc/get-install-directory {:install-options
{:install-directory "/a/b/c"}}))))
(testing "Empty install-directory"
(is (= "/d/e/f"
(bc/get-install-directory {:install-options
{:install-directory ""}
:node-info
{:facts
{:run-context
{:install-options
{:install-directory "/d/e/f"}}}}})))))
| true | ;; Copyright DataStax, Inc.
;; Please see the included license file for details.
(ns com.datastax.configbuilder.build-config-test
(:require [clojure.test :refer :all]
[com.datastax.configbuilder.test-data :as test-data]
[com.datastax.configbuilder.test-helpers :as helper]
[com.datastax.configbuilder.build-config :as bc]
[com.datastax.configbuilder.definitions :as d]
[slingshot.test :refer :all]))
(deftest test-with-defaults
(let [configs
(bc/with-defaults (test-data/get-definitions-data helper/default-dse-version)
{})]
;; Check the total number of config files
(is (= 22 (count configs)))
;; Check some random default values
(is (= "/var/lib/cassandra/commitlog"
(get-in configs [:cassandra-yaml :commitlog_directory])))
(is (= 128 (get-in configs [:cassandra-yaml :io_global_queue_depth])))))
(deftest test-allow-custom-seed-provider
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "PI:KEY:<KEY>END_PI"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:seed_provider [{:class_name "org.apache.cassandra.locator.K8SeedProvider"
:parameters [{:seeds "1,2,3"}]}]}})]
(is (= "org.apache.cassandra.locator.K8SeedProvider" (get-in built-configs [:cassandra-yaml :seed_provider 0 :class_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))))
(deftest test-build-configs-for-oss-cassandra
(let [datacenter-info {:name "dc-1"}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "PI:PASSWORD:<KEY>END_PI"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
definitions-data (test-data/get-definitions-data "cassandra" helper/default-cassandra-version)
built-configs (bc/build-configs definitions-data
{:cluster-info (assoc cluster-info :product "cassandra" :datastax-version helper/default-cassandra-version)
:node-info node-info
:datacenter-info datacenter-info
:cassandra-yaml {:num_tokens 201}})]
(testing "does anything at all work even a little bit"
(is (= 201 (get-in built-configs [:cassandra-yaml :num_tokens]))))
(testing "do we use rpc_address instead of DSE's new config name native_transport_address"
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :rpc_address]))))))
(deftest test-ensure-correct-address-field-names
(let [expected-old {:rpc_address "1.1.1.1"
:broadcast_rpc_address "2.2.2.2"
:some_other_prop "some value"}
expected-new {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}
fields {:native_transport_address "1.1.1.1"
:native_transport_broadcast_address "2.2.2.2"
:some_other_prop "some value"}]
(testing "DSE 6.0.0+ uses new names"
(is (= (bc/ensure-correct-address-field-names "dse" "6.0.0" fields)
expected-new)))
(testing "DSE 5.0.0 uses old names"
(is (= (bc/ensure-correct-address-field-names "dse" "5.0.0" fields)
expected-old)))
(testing "Cassandra uses old names"
(is (= (bc/ensure-correct-address-field-names "cassandra" "7.0.0" fields)
expected-old)))))
(deftest test-build-configs
(testing "for package installs"
(let [datacenter-info {:name "dc-1"
:graph-enabled 1
:spark-enabled 0
:solr-enabled 0}
node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "PI:KEY:<KEY>END_PI"
:auto_bootstrap true}
cluster-info {:name "test-cluster-1"
:seeds "1,2,3"}
built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cluster-info (assoc cluster-info :datastax-version helper/default-dse-version)
:node-info node-info
:datacenter-info datacenter-info
:dse-env-sh {:dse-log-root "/foo/log"
:cassandra-log-dir "/foo/log/cassandra"}})]
(testing "- cassandra.yaml"
(testing "default values"
(is (= 128 (get-in built-configs [:cassandra-yaml :io_global_queue_depth]))))
(testing "ignored fields"
(is (nil? (get-in built-configs [:cassandra-yaml :rack]))))
(testing "enriched fields"
(doseq [[field-name field-val] (dissoc node-info :name :rack)]
(is (= field-val (get-in built-configs [:cassandra-yaml field-name]))
(format "Missing or incorrect value for field %s" field-name)))
(is (= "test-cluster-1" (get-in built-configs [:cassandra-yaml :cluster_name])))
(is (= "1,2,3" (get-in built-configs [:cassandra-yaml :seed_provider 0 :parameters 0 :seeds])))
(is (= "1.1.1.3" (get-in built-configs [:cassandra-yaml :native_transport_address])))
(is (= "1.1.1.4" (get-in built-configs [:cassandra-yaml :native_transport_broadcast_address])))
(is (every? nil? (map (:cassandra-yaml built-configs) [:rpc_address :broadcast_rpc_address])))))
(testing "- cassandra-env.sh"
(is (true? (get-in built-configs [:cassandra-env-sh :enable_on_out_of_memory_error])))
(is (= "kill -9 %p" (get-in built-configs [:cassandra-env-sh :on_out_of_memory_error])))
(is (= 7199
(get-in built-configs [:jvm-options :jmx-port]) ;; source
(get-in built-configs [:cassandra-env-sh :jmx-port]))))
(testing "- dse.default"
(is (= (select-keys datacenter-info bc/workload-keys)
(select-keys (:dse-default built-configs) bc/workload-keys)))
(is (= {:cassandra-user "cassandra"
:cassandra-group "cassandra"}
(select-keys (get built-configs :dse-default)
[:cassandra-user
:cassandra-group]))))
(testing "- cassandra-rackdc.properties"
(is (= {:dc "dc-1" :rack "rack-1"}
(:cassandra-rackdc-properties built-configs))))
(testing "- dse-env.sh"
(is (= "/foo/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir]))))
(testing "Dependent fields should not be present unless their condition is satisfied"
(is (false? (get-in built-configs [:dse-yaml :spark_cluster_info_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :spark_cluster_info_options :refresh_rate_ms]
:missing)))
;; Try a nested dict with a dependency. Use not instead of false? because this
;; enabled field is a ternary_boolean with nil default value.
(is (not (get-in built-configs [:dse-yaml :dsefs_options :enabled])))
(is (= :missing (get-in built-configs
[:dse-yaml :dsefs_options :gossip_options]
:missing))))))
(testing "for tarball installs"
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:install-options {:install-type "tarball"
:install-directory "/home/targ/dse"}
:dse-env-sh {:dse-log-root "log"
:cassandra-log-dir "log/cassandra"}})]
(testing "- dse.yaml"
(is (= "/home/targ/dse/resources/dse/conf"
(get-in built-configs [:dse-yaml :system_key_directory]))))
(testing "- dse-env.sh"
(is (= "/home/targ/dse/log/cassandra" (get-in built-configs [:dse-env-sh :cassandra-log-dir])))))))
(deftest test-unmanage-config-file
(let [built-configs
(bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
;; we should be able to unmanage a file based on config-file-id
{:cassandra-yaml {:lcm-manage--cassandra-yaml false}})]
(is (= true (contains? built-configs :dse-yaml)))
(is (= false (contains? built-configs :cassandra-yaml)))))
(deftest test-build-configs-no-enrichment
(testing "configs with no enrichment"
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "PI:PASSWORD:<KEY>END_PI"
:auto_bootstrap true}}
enriched-keys #{:cassandra-yaml
:cassandra-env-sh
:dse-default
:cassandra-rackdc-properties
:dse-in-sh}
definitions-data (test-data/get-definitions-data helper/default-dse-version)
config-data-with-defaults (bc/with-defaults definitions-data config-data)
enriched-config-data (bc/build-configs definitions-data config-data)
unmodified-configs (apply dissoc enriched-config-data
(concat enriched-keys bc/model-info-keys))]
(doseq [[config-key config-value] unmodified-configs]
;; If this fails, an enriched config may have been added. If this is the
;; case, add it's config-key to enriched-keys above.
(is (= (get config-data-with-defaults config-key) config-value)
(str "Expected config to be unmodified, but it has been enriched: " config-key)))
;; If this fails and the actual count is...
;; a) Greater than expected - a new config-key has likely been added to the config-data map, and
;; that key is not being enriched. Either it should be enriched, or the expected count
;; should be incremented.
;; b) Less than expected - a key that used to be unmodified has either been removed or is
;; now an enriched config. In the former case, decrement the expected count. For the
;; latter, add it's config-key to the enriched-keys set above.
(is (= 17 (count unmodified-configs))))))
(deftest test-build-configs-bad-keys
;; What happens when a key exists in config-data for which there is no corresponding key
;; in definitions? The answer - an exception is thrown!
(let [config-data {:cluster-info {:name "test-cluster-1"
:datastax-version helper/default-dse-version
:seeds "1,2,3"}
:datacenter-info {:name "test-dc-1"
:graph-enabled true
:spark-enabled false
:solr-enabled false}
:node-info {:name "node-1"
:rack "rack-1"
:listen_address "1.1.1.1"
:broadcast_address "1.1.1.2"
:native_transport_address "1.1.1.3"
:native_transport_broadcast_address "1.1.1.4"
:initial_token "PI:KEY:<KEY>END_PI"
:auto_bootstrap true}
:bad-config {:a 12}}
definitions-data (test-data/get-definitions-data helper/default-dse-version)]
(is (thrown+? [:type :InvalidConfigKeys]
(bc/build-configs definitions-data config-data)))))
(deftest test-build-configs-file-paths
(let [built-configs (bc/build-configs (test-data/get-definitions-data helper/default-dse-version)
{:cassandra-yaml {}
:address-yaml {}})]
(is (= "/etc/dse/cassandra/cassandra.yaml"
(get-in built-configs [:node-info :file-paths :cassandra-yaml])))
(is (= (:package-path bc/address-yaml-paths)
(get-in built-configs [:node-info :file-paths :address-yaml])))))
(deftest test-get-configured-paths
(let [configured-paths
(get-in
(bc/get-configured-paths
{:definitions
{:foobie
{:display-name "foobie.yaml"
:properties
{:blah_dirs {:type "list"
:value_type "string"
:default_value ["/blah/default"]
:is_directory true}
:foo_dir {:type "string"
:default_value "/foo/default"
:is_file true}
:bar_dir {:type "string"
:is_directory true}}}}}
:foobie
{:foobie {:blah_dirs ["/a/b/c" "/d/e/f"]
:foo_dir "/foo/default"
:bar_dir "/j/k/l"}})
[:node-info :configured-paths])]
(is (= 4 (count configured-paths)))
(doseq [configured-path configured-paths]
(is (= "foobie.yaml" (:config-file configured-path)))
(condp = (:key configured-path)
[:blah_dirs]
(do
(is (#{"/a/b/c" "/d/e/f"} (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
[:foo_dir]
(do
(is (= "/foo/default" (:path configured-path)))
(is (false? (:custom? configured-path)))
(is (false? (:directory? configured-path))))
[:bar_dir]
(do
(is (= "/j/k/l" (:path configured-path)))
(is (:custom? configured-path))
(is (:directory? configured-path)))
(do
(is (= "Unexpected value" configured-path))))))
(testing "for tarball installs"
(let [definitions-data (update (test-data/get-definitions-data helper/default-dse-version)
:definitions
d/use-tarball-defaults)
[configured-path]
(get-in
(bc/get-configured-paths definitions-data
:dse-yaml
{:dse-yaml {:system_key_directory "resources/dse/conf"}})
[:node-info :configured-paths])]
(is configured-path)
(is (= "resources/dse/conf" (:path configured-path)))
(is (false? (:custom? configured-path))))))
(deftest test-fully-qualify-paths
(let [definitions-data (test-data/get-definitions-data)
config-key :cassandra-yaml]
(testing "No-op for package installs"
(let [config-data {:install-options
{:install-type "package"}
:cassandra-yaml
{:data_file_directories ["/var/data1" "/var/data2"]
:commitlog_directory "/var/commitlog"
:client_encryption_options
{:enabled true
:keystore "/etc/dse/keystore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= result config-data)
"Should not modify paths for package install")))
(testing "Tarball installs"
(let [config-data {:install-options
{:install-type "tarball"
:install-directory "/opt/dse"}
:cassandra-yaml
{:data_file_directories ["var/data1" "var/data2" "/var/data3"]
:commitlog_directory "var/commitlog"
:client_encryption_options
{:enabled true
:keystore "etc/dse/keystore"
:truststore "/etc/dse/truststore"}}}
result (bc/fully-qualify-paths definitions-data config-key config-data)]
(is (= ["/opt/dse/var/data1"
"/opt/dse/var/data2"
"/var/data3"]
(get-in result [:cassandra-yaml :data_file_directories]))
"Should fully-qualify relative paths in vectors")
(is (= "/opt/dse/var/commitlog"
(get-in result [:cassandra-yaml :commitlog_directory]))
"Should fully-qualify relative directory paths")
(is (= "/opt/dse/etc/dse/keystore"
(get-in result [:cassandra-yaml :client_encryption_options :keystore]))
"Should fully-qualify relative file paths")
(is (= "/etc/dse/truststore"
(get-in result [:cassandra-yaml :client_encryption_options :truststore]))
"Should not transform paths that are already absolute")))))
(deftest test-get-install-directory
(testing "Non-empty install-directory"
(is (= "/a/b/c"
(bc/get-install-directory {:install-options
{:install-directory "/a/b/c"}}))))
(testing "Empty install-directory"
(is (= "/d/e/f"
(bc/get-install-directory {:install-options
{:install-directory ""}
:node-info
{:facts
{:run-context
{:install-options
{:install-directory "/d/e/f"}}}}})))))
|
[
{
"context": "nt library in clojure\"\n :url \"https://github.com/aterreno/etcd-clojure\"\n :lein-release {:deploy-via :cloja",
"end": 116,
"score": 0.9995353817939758,
"start": 108,
"tag": "USERNAME",
"value": "aterreno"
},
{
"context": "w.apache.org/licenses/LICENSE-2.0\"}\n :scm {:url \"git@github.com:aterreno/etcd-clojure.git\"}\n :dependencies [[org",
"end": 306,
"score": 0.9991976022720337,
"start": 292,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "censes/LICENSE-2.0\"}\n :scm {:url \"git@github.com:aterreno/etcd-clojure.git\"}\n :dependencies [[org.clojure/",
"end": 315,
"score": 0.9993362426757812,
"start": 307,
"tag": "USERNAME",
"value": "aterreno"
}
] | project.clj | uswitch/etcd-clojure | 1 | (defproject etcd-clojure "0.2.0"
:description "etcd client library in clojure"
:url "https://github.com/aterreno/etcd-clojure"
:lein-release {:deploy-via :clojars}
:license {:name "Apache license version 2"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:url "git@github.com:aterreno/etcd-clojure.git"}
:dependencies [[org.clojure/clojure "1.5.1"]
[cheshire "5.3.1"]
[clj-http "0.9.1"]])
| 48653 | (defproject etcd-clojure "0.2.0"
:description "etcd client library in clojure"
:url "https://github.com/aterreno/etcd-clojure"
:lein-release {:deploy-via :clojars}
:license {:name "Apache license version 2"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:url "<EMAIL>:aterreno/etcd-clojure.git"}
:dependencies [[org.clojure/clojure "1.5.1"]
[cheshire "5.3.1"]
[clj-http "0.9.1"]])
| true | (defproject etcd-clojure "0.2.0"
:description "etcd client library in clojure"
:url "https://github.com/aterreno/etcd-clojure"
:lein-release {:deploy-via :clojars}
:license {:name "Apache license version 2"
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:url "PI:EMAIL:<EMAIL>END_PI:aterreno/etcd-clojure.git"}
:dependencies [[org.clojure/clojure "1.5.1"]
[cheshire "5.3.1"]
[clj-http "0.9.1"]])
|
[
{
"context": "st/keystore.jks\"\n :key-password \"password\"}\n (let [response (http/get \"https://localho",
"end": 1097,
"score": 0.9994999170303345,
"start": 1089,
"tag": "PASSWORD",
"value": "password"
}
] | ring-jetty-adapter/test/ring/adapter/test/jetty.clj | orend/ring | 147 | (ns ring.adapter.test.jetty
(:use clojure.test
ring.adapter.jetty)
(:require [clj-http.client :as http])
(:import (org.eclipse.jetty.util.thread QueuedThreadPool)
(org.eclipse.jetty.server Server Request)
(org.eclipse.jetty.server.handler AbstractHandler)))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defmacro with-server [options & body]
`(let [server# (run-jetty hello-world ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(deftest test-run-jetty
(testing "HTTP server"
(with-server {:port 4347}
(let [response (http/get "http://localhost:4347")]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server {:port 4347
:ssl-port 4348
:keystore "test/keystore.jks"
:key-password "password"}
(let [response (http/get "https://localhost:4348" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response]))
threadPool (QueuedThreadPool. ({} :max-threads max-threads))
configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler))
server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server))))
| 92386 | (ns ring.adapter.test.jetty
(:use clojure.test
ring.adapter.jetty)
(:require [clj-http.client :as http])
(:import (org.eclipse.jetty.util.thread QueuedThreadPool)
(org.eclipse.jetty.server Server Request)
(org.eclipse.jetty.server.handler AbstractHandler)))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defmacro with-server [options & body]
`(let [server# (run-jetty hello-world ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(deftest test-run-jetty
(testing "HTTP server"
(with-server {:port 4347}
(let [response (http/get "http://localhost:4347")]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server {:port 4347
:ssl-port 4348
:keystore "test/keystore.jks"
:key-password "<PASSWORD>"}
(let [response (http/get "https://localhost:4348" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response]))
threadPool (QueuedThreadPool. ({} :max-threads max-threads))
configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler))
server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server))))
| true | (ns ring.adapter.test.jetty
(:use clojure.test
ring.adapter.jetty)
(:require [clj-http.client :as http])
(:import (org.eclipse.jetty.util.thread QueuedThreadPool)
(org.eclipse.jetty.server Server Request)
(org.eclipse.jetty.server.handler AbstractHandler)))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defmacro with-server [options & body]
`(let [server# (run-jetty hello-world ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(deftest test-run-jetty
(testing "HTTP server"
(with-server {:port 4347}
(let [response (http/get "http://localhost:4347")]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server {:port 4347
:ssl-port 4348
:keystore "test/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"}
(let [response (http/get "https://localhost:4348" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response]))
threadPool (QueuedThreadPool. ({} :max-threads max-threads))
configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler))
server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server))))
|
[
{
"context": " email\n :password hashed-password}]\n :returning [:id]})\n {:",
"end": 2570,
"score": 0.7692859172821045,
"start": 2555,
"tag": "PASSWORD",
"value": "hashed-password"
}
] | src/main/app/model/session.clj | eccentric-j/skeljo | 0 | (ns app.model.session
(:require
[app.model.database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[buddy.hashers :as hs]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [{::db/keys [pool] :as env} {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [user (db/execute-one! pool
{:select [:email :password]
:from [:account]
:where [:= :email username]})
{expected-email :account/email
expected-password :account/password} user]
(if (and (= username expected-email) (hs/check password expected-password))
(response-updating-session
env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [{::db/keys [pool] :as env} {:keys [email password]}]
{::pc/output [:signup/result]}
(log/info "Signing Up" email)
(let [hashed-password (hs/derive password)]
(db/execute-one! pool
{:insert-into :account
:values [{:email email
:password hashed-password}]
:returning [:id]})
{:signup/result "OK"}))
(def resolvers [current-session-resolver login logout signup!])
| 65089 | (ns app.model.session
(:require
[app.model.database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[buddy.hashers :as hs]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [{::db/keys [pool] :as env} {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [user (db/execute-one! pool
{:select [:email :password]
:from [:account]
:where [:= :email username]})
{expected-email :account/email
expected-password :account/password} user]
(if (and (= username expected-email) (hs/check password expected-password))
(response-updating-session
env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [{::db/keys [pool] :as env} {:keys [email password]}]
{::pc/output [:signup/result]}
(log/info "Signing Up" email)
(let [hashed-password (hs/derive password)]
(db/execute-one! pool
{:insert-into :account
:values [{:email email
:password <PASSWORD>}]
:returning [:id]})
{:signup/result "OK"}))
(def resolvers [current-session-resolver login logout signup!])
| true | (ns app.model.session
(:require
[app.model.database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[buddy.hashers :as hs]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [{::db/keys [pool] :as env} {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [user (db/execute-one! pool
{:select [:email :password]
:from [:account]
:where [:= :email username]})
{expected-email :account/email
expected-password :account/password} user]
(if (and (= username expected-email) (hs/check password expected-password))
(response-updating-session
env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [{::db/keys [pool] :as env} {:keys [email password]}]
{::pc/output [:signup/result]}
(log/info "Signing Up" email)
(let [hashed-password (hs/derive password)]
(db/execute-one! pool
{:insert-into :account
:values [{:email email
:password PI:PASSWORD:<PASSWORD>END_PI}]
:returning [:id]})
{:signup/result "OK"}))
(def resolvers [current-session-resolver login logout signup!])
|
[
{
"context": "3:45\"}]\n :restaurant/location {:location/addres \"Rua Ribeirão Claro\"\n :location/number 192\n ",
"end": 1796,
"score": 0.9997081756591797,
"start": 1778,
"tag": "NAME",
"value": "Rua Ribeirão Claro"
},
{
"context": "2\n :location/neighborhood \"Vila Olimpia\"\n :location/city 5",
"end": 1895,
"score": 0.64129239320755,
"start": 1891,
"tag": "NAME",
"value": "Vila"
},
{
"context": " :location/neighborhood \"Vila Olimpia\"\n :location/city 5270\n ",
"end": 1903,
"score": 0.6559765934944153,
"start": 1897,
"tag": "NAME",
"value": "limpia"
},
{
"context": " :closing \"23:45\"}]\n :location {:addres \"Rua Ribeirão Claro\"\n :number 192\n :neighborh",
"end": 4615,
"score": 0.9986010789871216,
"start": 4597,
"tag": "NAME",
"value": "Rua Ribeirão Claro"
}
] | test/foodship_restaurant/helpers/keywords_test.clj | eronalves/foodship-restaurant | 5 | (ns foodship-restaurant.helpers.keywords-test
(:require
[clojure.test :refer :all]
[foodship-restaurant.helpers.keywords :as keywords]))
(def complex-keywords-map
{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "Rua Ribeirão Claro"
:location/number 192
:location/neighborhood "Vila Olimpia"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}})
(def simple-keywords-map
{:id 1
:name "Mexicaníssimo"
:tags ["mexican"]
:preparation-time {:min 45
:max 60}
:business-hours [{:day-of-week :monday
:opening "18:00"
:closing "23:45"}
{:day-of-week :tuesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :wednesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :thursday
:opening "18:00"
:closing "23:45"}
{:day-of-week :friday
:opening "18:00"
:closing "23:45"}
{:day-of-week :saturday
:opening "12:00"
:closing "23:45"}
{:day-of-week :sunday
:opening "12:00"
:closing "23:45"}]
:location {:addres "Rua Ribeirão Claro"
:number 192
:neighborhood "Vila Olimpia"
:city 5270
:state 26
:country 76
:zipcode "04549-050"}
:menu [{:title "Tostitacos"
:category :appetizer
:description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:ingredients ["farinha de trigo", "carne", "alface"]
:price 25.9
:serves 1}
{:title "Quesadilla de queijo"
:category :principal
:description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:ingredients ["farinha de trigo", "queijo"]
:price 22.9
:serves 1}
{:title "Molcajete tradicional"
:category :principal
:description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:price 46.9
:serves 3}]
:banking {:agency "xxxx"
:account "xxxx"
:digit 1}})
(deftest transform-keywords
(testing "must be transform complex keywords to a more simple with last splitted with slash"
(is (= simple-keywords-map (keywords/transform-keywords complex-keywords-map))))) | 98941 | (ns foodship-restaurant.helpers.keywords-test
(:require
[clojure.test :refer :all]
[foodship-restaurant.helpers.keywords :as keywords]))
(def complex-keywords-map
{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "<NAME>"
:location/number 192
:location/neighborhood "<NAME> O<NAME>"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}})
(def simple-keywords-map
{:id 1
:name "Mexicaníssimo"
:tags ["mexican"]
:preparation-time {:min 45
:max 60}
:business-hours [{:day-of-week :monday
:opening "18:00"
:closing "23:45"}
{:day-of-week :tuesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :wednesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :thursday
:opening "18:00"
:closing "23:45"}
{:day-of-week :friday
:opening "18:00"
:closing "23:45"}
{:day-of-week :saturday
:opening "12:00"
:closing "23:45"}
{:day-of-week :sunday
:opening "12:00"
:closing "23:45"}]
:location {:addres "<NAME>"
:number 192
:neighborhood "Vila Olimpia"
:city 5270
:state 26
:country 76
:zipcode "04549-050"}
:menu [{:title "Tostitacos"
:category :appetizer
:description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:ingredients ["farinha de trigo", "carne", "alface"]
:price 25.9
:serves 1}
{:title "Quesadilla de queijo"
:category :principal
:description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:ingredients ["farinha de trigo", "queijo"]
:price 22.9
:serves 1}
{:title "Molcajete tradicional"
:category :principal
:description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:price 46.9
:serves 3}]
:banking {:agency "xxxx"
:account "xxxx"
:digit 1}})
(deftest transform-keywords
(testing "must be transform complex keywords to a more simple with last splitted with slash"
(is (= simple-keywords-map (keywords/transform-keywords complex-keywords-map))))) | true | (ns foodship-restaurant.helpers.keywords-test
(:require
[clojure.test :refer :all]
[foodship-restaurant.helpers.keywords :as keywords]))
(def complex-keywords-map
{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "PI:NAME:<NAME>END_PI"
:location/number 192
:location/neighborhood "PI:NAME:<NAME>END_PI OPI:NAME:<NAME>END_PI"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}})
(def simple-keywords-map
{:id 1
:name "Mexicaníssimo"
:tags ["mexican"]
:preparation-time {:min 45
:max 60}
:business-hours [{:day-of-week :monday
:opening "18:00"
:closing "23:45"}
{:day-of-week :tuesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :wednesday
:opening "18:00"
:closing "23:45"}
{:day-of-week :thursday
:opening "18:00"
:closing "23:45"}
{:day-of-week :friday
:opening "18:00"
:closing "23:45"}
{:day-of-week :saturday
:opening "12:00"
:closing "23:45"}
{:day-of-week :sunday
:opening "12:00"
:closing "23:45"}]
:location {:addres "PI:NAME:<NAME>END_PI"
:number 192
:neighborhood "Vila Olimpia"
:city 5270
:state 26
:country 76
:zipcode "04549-050"}
:menu [{:title "Tostitacos"
:category :appetizer
:description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:ingredients ["farinha de trigo", "carne", "alface"]
:price 25.9
:serves 1}
{:title "Quesadilla de queijo"
:category :principal
:description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:ingredients ["farinha de trigo", "queijo"]
:price 22.9
:serves 1}
{:title "Molcajete tradicional"
:category :principal
:description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:price 46.9
:serves 3}]
:banking {:agency "xxxx"
:account "xxxx"
:digit 1}})
(deftest transform-keywords
(testing "must be transform complex keywords to a more simple with last splitted with slash"
(is (= simple-keywords-map (keywords/transform-keywords complex-keywords-map))))) |
[
{
"context": "e max before exponentiating prevents overflow. See Goodfellow, Bengio, and Courville\n ; (2016), pg. 179.",
"end": 36202,
"score": 0.9478124380111694,
"start": 36192,
"tag": "NAME",
"value": "Goodfellow"
},
{
"context": " exponentiating prevents overflow. See Goodfellow, Bengio, and Courville\n ; (2016), pg. 179.\n ",
"end": 36210,
"score": 0.9851793646812439,
"start": 36204,
"tag": "NAME",
"value": "Bengio"
},
{
"context": "ing prevents overflow. See Goodfellow, Bengio, and Courville\n ; (2016), pg. 179.\n max-correcte",
"end": 36225,
"score": 0.9059569835662842,
"start": 36216,
"tag": "NAME",
"value": "Courville"
}
] | src/neurojure/core.clj | cguenthner/neurojure | 0 | (ns neurojure.core
(:require [clojure.set :as set]
[neurojure.utils :as u :refer [def- -?> -?>>]]
[ranvier.core :as r :refer [G]]
[tensure.core :as m]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initializers
;;
;; Initializers are functions that take a single argument, a tensor shape, and return a tensor of that shape,
;; with elements set to values determined by the initializer. Except for `zeros` and `ones`, the initializers
;; are generated by factory functions that return initializers with properties based on the parameters they
;; receive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TODO: Test this
(defn- get-axis-size
"Given a vector representing a tensor `shape` and either a single `axis` index or vector of axis indices,
returns the product of the sizes of the specified axes."
[shape axis]
(let [axes (if (number? axis)
[axis]
axis)
rank (count shape)]
(reduce (fn [size i]
(when (>= i rank)
(u/throw-str "Invalid axis for a tensor of shape '" shape "'."))
(* size (nth shape i)))
1
axes)))
(defn zeros-initializer
"Returns a tensor of `shape` filled with 0's."
[shape]
(m/zeros shape))
(defn ones-initializer
"Returns a tensor of `shape` filled with 1's."
[shape]
(m/ones shape))
(defn make-fill-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with `constant`."
[constant]
(fn [shape]
(m/filled shape constant)))
(defn make-constant-initializer
"Returns a function that takes a shape and will return the tensor `constant` of that shape. Throws an
exception if the constant does not have the shape."
[constant]
(let [constant (if (m/array? constant)
constant
(m/array constant))
constant-shape (m/shape constant)]
(fn [shape]
(when (not= constant-shape shape)
(u/throw-str "Attempt to initialize a tensor of shape '" shape "' with a constant of shape '"
constant-shape "'."))
constant)))
(defn make-uniform-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values uniformly distributed in [min, max). `min` and `max` can be either numbers or functions that when
applied to the shape will return numbers."
([]
(make-uniform-random-initializer -0.01 0.01))
([min max]
(fn [shape]
(let [nd (m/sample-uniform shape)
min (m/array (if (fn? min) (min shape) min))
max (m/array (if (fn? max) (max shape) max))]
(m/add (m/mul (m/sub max min) nd) min)))))
(defn make-normal-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev`. `mean` and `stdev` can be either
numbers or functions that return the numbers when applied to the shape."
([]
(make-normal-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [nd (m/sample-normal shape)
stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))]
(m/add (m/mul stdev nd) mean)))))
(defn make-truncated-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev` but with no values >2 SD's from
the mean. `mean` and `stdev` can be either numbers or functions that return the numbers when applied to
the shape."
([]
(make-truncated-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))
result-element-count (apply * shape)
get-element-seq (fn next [batch-size]
(lazy-cat (m/eseq (m/sample-normal [batch-size]))
(next (max 128 (* batch-size 0.05)))))
result (->> (get-element-seq result-element-count)
(filter #(and (> % -2) (< % 2)))
(take result-element-count)
m/array)]
(m/mul! result stdev)
(m/add! result mean)
(m/reshape result shape)))))
(defn make-variance-scaling-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around 0. The standard deviation will be `sqrt(scale / axis-sum)` where
`axis-sum` is the sum of the sizes of all axes in `axis`. `axis` can be either a vector of axes or an
integer indicating a single axis. The distribution is truncted such that no values >2 SD's from 0 are
included."
([]
(make-variance-scaling-initializer 1))
([scale]
(make-variance-scaling-initializer scale 1))
([scale axis]
(let [axes (if (number? axis) [axis] axis)]
(fn [shape]
(for [axis axes]
(when (>= axis (count shape))
(u/throw-str "Cannot initialize tensor of shape " shape " with variance scaled on axis "
axis ", because axis is out of bounds.")))
((make-truncated-random-initializer
0
(Math/sqrt (/ scale (apply + (map #(nth shape %) axes)))))
shape)))))
(defn make-lecun-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(3 / m), sqrt(3 / m))`, where m is the size of the `input-axes`, either
a single axis index or vector of axis indices (defaults to 1)."
([]
(make-lecun-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 3 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-lecun-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(1 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated
at +/- 2 SD's."
([]
(make-lecun-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 1 (get-axis-size % input-axes))))))
(defn make-he-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / m), sqrt(6 / m))`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1)."
([]
(make-he-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 6 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-he-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated at
+/- 2 SD's."
([]
(make-he-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (get-axis-size % input-axes))))))
(defn make-xavier-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / (m + n)), sqrt(6 / (m + n)))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0)."
([]
(make-xavier-uniform-initializer 1 0))
([input-axes output-axes]
(let [bound-fn #(Math/sqrt (/ 6 (+ (get-axis-size % input-axes) (get-axis-size % output-axes))))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-xavier-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / (m + n))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0). The distribution is truncated
at +/- 2 SD's."
([]
(make-xavier-normal-initializer 1 0))
([input-axes output-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (+ (get-axis-size % input-axes) (get-axis-size % output-axes)))))))
; TODO: Test this.
(defn- get-layer-initializer
"Returns an initializer (function that takes a shape and returns an initialized tensor of that shape),
given:
- `initializer-selector` - an initializer function or keyword
- `input-axes` - the axes of the tensor being initialized that span 'input values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `output-axes` - the axes of the tensor being initialized that span 'output values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `layer-type` - keyword or string identifying the layer (used to provide more descriptive error
message)
If `initializer-selector` is a function, it's just returned. If it's a keyword, then the corresponding
factory function is looked up and used to construct a new initializer. The product of the sizes of the
`input-axes` should correspond to the 'fan in' of the layer (the number of input values that contribute to
any single value in the output), while the product of the sizes of the `output-axes` should correspond to
the 'fan out' of the layer (the number of output values that contribute to any single input value to the
next layer). If the notion of 'fan in' or 'fan out' does not apply to a layer or cannot be calculated
from the parameter shape, then `input-axes` or `output-axes` can be set to `nil`. Selecting an initializer
that does not apply to a layer will cause an Exception."
[initializer-selector input-axes output-axes layer-type]
(if (fn? initializer-selector)
initializer-selector
(let [throw-invalid-initializer #(u/throw-str "Invalid initializer for '" layer-type "' layer: '"
initializer-selector "'.")]
(when (and (nil? input-axes) (#{:lecun-uniform :luecn-normal :he-uniform :he-normal
:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(when (and (nil? output-axes) (#{:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(case initializer-selector
:zeros zeros-initializer
:ones ones-initializer
:uniform (make-uniform-random-initializer)
:normal (make-normal-random-initializer)
:truncated (make-truncated-random-initializer)
:variance-scaling (make-variance-scaling-initializer)
:lecun-uniform (make-lecun-uniform-initializer input-axes)
:lecun-normal (make-lecun-normal-initializer input-axes)
:he-uniform (make-he-uniform-initializer input-axes)
:he-normal (make-he-normal-initializer input-axes)
:xavier-uniform (make-xavier-uniform-initializer input-axes output-axes)
:xavier-normal (make-xavier-normal-initializer input-axes output-axes)
(throw-invalid-initializer)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layer helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map of layer type (a string) to the number of times `gen-layer-name` has been called with that string
; as the `layer-type` argument.
(def- layer-type-counters (atom {}))
(defn- gen-layer-name
"Given `layer-type` (a keyword or string), returns a new unique keyword identifier for a layer of that type.
E.g. `(gen-layer-name :dense)` will return 'dense0', `:dense1', ':dense2', etc. on each call."
[layer-type]
(let [type-str (name layer-type)]
(if (contains? @layer-type-counters type-str)
(swap! layer-type-counters update type-str inc)
(swap! layer-type-counters assoc type-str 0))
(keyword (str type-str (get @layer-type-counters type-str)))))
(defn- gen-param-name
"Given a `layer-name` and a `param-name` (both either keywords or strings), returns a unique keyword
identifier for the parameter. E.g. `(gen-param-name 'dense0' :W)` returns 'dense0_W'."
[layer-name param-name]
(if layer-name
(keyword (str (name layer-name) "_" (name param-name)))
param-name))
(defn- tag-layer-nodes-recursive
[g input-set layer-name]
(let [operands (r/get-node-operands g)]
(if (input-set g)
g
(->> (mapv #(tag-layer-nodes-recursive % input-set layer-name) operands)
(r/update-node g
:data (update (r/get-node-data g) :layers #(conj (or % []) layer-name))
:operands)))))
(defn- tag-layer-nodes
"Traverses computation graph `g`, conj'ing `layer-name` into the :layers vector in the node's :data but
ommitting all nodes in `input-nodes` (seq of nodes or any object that can be constructed into a node) and
all their descendents."
[g input-nodes layer-name]
(let [input-set (->> (map r/construct-operand input-nodes)
(into #{}))
node-data (r/get-node-data g)]
(r/update-node (tag-layer-nodes-recursive g input-set layer-name)
:data (assoc node-data
:layers (conj (get node-data :layers []) layer-name)
:entry-to-layer layer-name))))
(defn- create-layer
[layer-name input-nodes g]
(tag-layer-nodes g input-nodes layer-name))
(defn- make-input-node
"Returns an input node for a layer, given:
- `input-name` - the keyword name of the input
- `layer-name` - the keyword name of the layer
- `initializer` - an initializer function, which must receive a map of node names to values at the time
of initialization and return the initialized value of the node
- `data` - an arbitrary map of additional data
The values for layer inputs must be either 1) provided (e.g. passed in from a model's data), or 2)
generated by the initialization function. For non-parameter/state inputs whose values are not provided,
the node will be re-initialized with every iteration. For inputs that should be optimized, use
`make-parameter-node`, and for inputs whose values should persist from iteration to iteration, use
`make-state-node`."
([input-name layer-name]
(make-input-node input-name layer-name nil))
([input-name layer-name initializer]
(make-input-node input-name layer-name initializer {}))
([input-name layer-name initializer data]
(r/input (gen-param-name layer-name input-name) initializer (assoc data
:parameter false
:trainable false))))
(defn- make-parameter-node
"Like `make-input-node`, but returns a node for a parameter input. Parameters are passed in the `param-map`
to the optimizer--their values can be changed by the optimizer with every iteration."
([param-name layer-name]
(make-parameter-node param-name layer-name nil))
([param-name layer-name initializer]
(make-parameter-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable true))))
(defn- make-state-node
"Like `make-input-node`, but returns an input node for a 'state' input--i.e. a value that can change
during an iteration and whose values are persisted between iterations."
([param-name layer-name]
(make-state-node param-name layer-name nil))
([param-name layer-name initializer]
(make-state-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable false))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regularizers
;;
;; Regulariers are functions that receive two arguments:
;; - a computation graph node that is assumed to be cost (though in practice it can be any node)
;; - a parameter node for which to apply regularization
;; They must return a new computation graph node with regularization for the given parameter applied. They
;; are generally constructed using a make-* function that returns a regularizer with properties specified
;; by the arguments to the make-* function.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-l2-regularizer
"Returns an L2 regularizer:
`cost + regularization-weight / 2m * (sum of squares of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l2-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l2-regularizer)
[g num-examples parameter-node :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (pow parameter-node 2)))
#_(report (make-value-reporter "reg: ") (make-print-logger)))))
:regularizer-for (r/get-node-name parameter-node))))))
(defn make-l1-regularizer
"Returns an L1 regularizer:
`cost + regularization-weight / 2m * (sum of absolute value of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l1-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l1-regularizer)
[g parameter-node num-examples :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (abs parameter-node))))))
:regularizer-for (r/get-node-name parameter-node))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Layers
;;
(defn regularize
[g]
(->> (r/get-all-graph-nodes g)
distinct
(reduce (fn [regularized-graph node]
(if-let [regularizer (->> node r/get-node-data :regularizer)]
(regularizer regularized-graph node)
regularized-graph))
g)))
(defn sigmoid-cross-entropy
"Computes the sum over all elements of the result of
`max(predicted, 0) - predicted * actual + log (1 + e^-abs(predicted))`. This is roughly equivalent to the
total logistic loss `actual * -log(sigmoid(predicted)) + (1 - actual) * -log(1 - sigmoid(predicted))`, but
with some modifications for numerical stability. Based on the TensorFlow implementation
(https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits)."
[predicted actual]
(G (esum
(+ (max predicted 0)
(* (- predicted) actual)
(log (+ 1 (exp (- (abs predicted)))))))))
; TODO: Add axis option.
(defn dropout
"Masks a fraction of elements in `g` and scales up remaining elements to maintain a constant sum:
- `:frequency` (required) - frequency of elements to drop out (on average)
- `:exact` (default true) - boolean indicating whether scaling of other options in `g` must be exact
(i.e. proportional to the number of elements actually dropped out, which may vary randomly from run to
run) or approximate (proportional to `:frequency`). The results for `:exact == true` and
`:exact == false` converge when the size of `g` is large, but the `:exact` computation is more
expensive."
[g options]
(u/check-key-validity options [:frequency] [:exact])
(let [frequency (:frequency options)
exact (if (contains? options :exact)
(:exact options)
true)
keep-vec (G (>= (random-uniform (shape g))
frequency))
scaling-factor (if exact
(G (/ (size g)
(esum keep-vec)))
(/ 1 (- 1 frequency)))]
(create-layer
(gen-layer-name :dropout)
[g :training]
(G (tensor-if :training
(* keep-vec g scaling-factor)
g)))))
(defn mean
"Calculates the arithmetic mean of `g` along some axes/axes. `options` can include:
- `:axis` (optional) - a scalar or vector indicating the axes across which the mean should be taken; if
ommitted, the mean of all elements in `g` will be returned.
- `:collapse` (optional) - boolean indicating if the dimensions specified in `:axis` should be removed.
If false, dimensions will be maintained with a size of 1."
([g]
(mean g {}))
([g options]
(u/check-key-validity options [] [:axis :collapse])
(let [{:keys [axis collapse]} options]
(create-layer
(gen-layer-name :mean)
[g]
(G (/ (sum-along g {:axis axis
:collapse (clojure.core/or collapse false)})
(size g {:axis axis})))))))
(defn normalize
"Calculates baseline-corrected-g / variance, where baseline-correcred-g is g - mean(g), and variance is
sum(base-line-corrected-g^2) / size(baseline-corrected-g). Options can include `:axis`, a single axis or
a vector of axes over which to perform the `sum`, `size`, and `mean` operations. If `:axis` is not
provided, normalization will be done over the entire tensor `g`. The returned result is the same shape as
`g`."
([g]
(normalize g {}))
([g options]
(u/check-key-validity options [] [:axis])
(let [axis (get options :axis 0)
opts {:axis axis
:collapse false}
mean (mean g opts)
baseline-corrected (G (- g mean))
variance (G (/ (sum-along (pow baseline-corrected 2) opts)
(size baseline-corrected {:axis axis})))]
(create-layer
(gen-layer-name :normalize)
[g]
(G (/ baseline-corrected
variance))))))
(defn relu
"Computes `min(g, 0)`."
[g]
(create-layer
(gen-layer-name :relu)
[g]
(G (max g 0))))
(defn logistic
"Computes `1 / (1 + e^-g)`."
[g]
(G (/ 1 (+ 1 (exp (- g))))))
(defn logistic-binary-classifier
"Returns a boolean tensor representing `1 / (1 + e^-`g`) >= 0.5`."
[g]
(G (>= (logistic g) 0.5)))
(defn dense
"Given an `operand` matrix of shape [m input-size], computes `operand . W + b`, where `.` is matrix
multiplication, W is a parameter matrix of shape [input-size units], and b is a parameter matrix of shape
[1 units]. Options include:
- `:units` (required) - scalar number of 'units' to include in the layer
- `:initializer` (optional, default xavier normal) - single initializer for both W and b
- `:W-intializer` (optional) - initializer for W, used instead of that specified in `:initializer` if
both are provided (default xavier normal)
- `:b-initializer` (optional) - like `:W-initializer` but for b (default zeros)
- `:regularizer` (optional) - default `nil`"
[operand options]
(u/check-key-validity options [:units] [:initializer :W-initializer :b-initializer :regularizer])
(let [{:keys [units regularizer initializer W-initializer b-initializer]} options
W-initializer (get-layer-initializer (or W-initializer initializer :xavier-normal) 0 1 :dense)
b-initializer (get-layer-initializer (or b-initializer initializer :zeros) 0 1 :dense)
input-node (r/construct-operand operand)
layer-name (gen-layer-name :dense)
input-dimension (when (r/is-const? input-node)
(m/column-count (r/get-node-value input-node)))
input-name (r/get-node-name input-node)
W-initializer-fn (fn [input-map]
(W-initializer [(or input-dimension
(m/column-count (get input-map input-name)))
units]))
b-initializer-fn (fn [input-map]
(b-initializer [1 units]))
W (make-parameter-node :W layer-name W-initializer-fn {:regularizer regularizer})
b (make-parameter-node :b layer-name b-initializer-fn)]
(create-layer
layer-name
[input-node]
(G (+ (mmul input-node W) b)))))
(r/defop- pool2d
"Given tensor `nd` of shape [m, height, width, channels], vector `pool-size` of shape
[pool-rows, pool-columns], and vector `strides` of shape [vstride, hstride], returns a tensor of shape
[m, floor((height - pool-rows) / vstride) + 1, floor((width - pool-cols) / hstride) + 1,
pool-rows * pool-columns * channels]. In the returned tensor, the vector [k, i, j, :all] (i.e. the elements
along the last dimension at a given point), consists of the elements of `nd` in selection
[i * vstride...(i * vstride + pool-rows - 1), j * hstride...(j * hstride + pool-cols - 1), :all-channels]
linearized in order row, col, channel. That is, channel changes fastest, and row changes slowest."
[^:nd nd pool-size strides]
:v (let [[kh kw] pool-size
[m height width chs] (m/shape nd)
[vstride hstride] strides
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))]
(when (or (zero? unstrided-result-height)
(zero? unstrided-result-width))
(u/throw-str "Cannot perform 2d convolution of a tensor of shape '" (m/shape nd) "' with a kernel of "
"shape '" pool-size "'. The kernel width and height cannot exceed the width and "
"height of an input tensor."))
(->> (for [i (range kh)
j (range kw)]
(m/select-range nd
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all))
(apply m/join-along 3)))
:dnd (let [[kh kw] pool-size
nd-shape (m/shape nd)
[_ height width chs] nd-shape
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))
[vstride hstride] strides
result (m/zeros nd-shape)]
(doseq [i (range kh)
j (range kw)
:let [k (* chs (+ (* i kw) j))]]
(m/add! (m/select-range result
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all)
(m/select-range dv :all :all :all [k (+ k chs)])))
result))
; TODO: Research other possible implementations of this to see if this can be made faster. (e.g. doing
; it in frequency space).
(defn conv2d
"Given tensor `nd` of shape [m, height, width, channels], a `kernel` of shape
[output-chs, kernel-height, kernel-width, input-chs], and a vector of strides like `[row-stride,
column-stride]`, returns a tensor of shape [m, floor((height - kernel-height + 1) / row-stride),
floor(width - kernel-width + 1) / column-stride), output-chs] that is the product of convolving each
of m examples with the kernel."
[nd kernel strides]
(let [[kout_chs kh kw] (mapv #(G (size kernel {:axis %})) (range 3))
pooled-nd (G (pool2d nd (make-shape kh kw) strides))
[m height width linear-kernel-size] (mapv #(G (size pooled-nd {:axis %})) (range 4))
reshaped-kernel (G (transpose (reshape kernel (make-shape kout_chs linear-kernel-size))))]
; We reshape `pooled-nd` into a matrix, before calculating the product with `reshaped-kernel`, because
; backpropagation of `mmul` is much faster for matrices than for tensors.
(G (-> (reshape pooled-nd (make-shape (* m height width) linear-kernel-size))
(mmul reshaped-kernel)
(reshape (make-shape m height width kout_chs))))))
(defn- get-2d-padding
"Given a padding option accepted by a 2d pooling or convolutional layer, returns a full padding vector for
a 4d tensor accepted by that layer. Throws an exception if `padding-option` is not valid. See `conv2d` and
`max-pooling2d`."
[padding-option window-size]
(let [padding-dimensionality (u/vector-dimensionality padding-option)]
(cond (nil? padding-option) nil
(= :same padding-option) (let [[padding-h padding-w] (mapv #(/ (dec %) 2) window-size)]
[[0 0]
[(int (Math/ceil padding-h)) (int (Math/floor padding-h))]
[(int (Math/ceil padding-w)) (int (Math/floor padding-w))]
[0 0]])
(number? padding-option) [0 padding-option padding-option 0]
(= padding-dimensionality 1) [0 (first padding-option) (second padding-option) 0]
(= padding-dimensionality 2) [[0 0] (first padding-option) (second padding-option) [0 0]]
:else (u/throw-str "Invalid 2d padding: '" padding-option "'. Padding must be a valid argument to "
"`pad-with` for a matrix."))))
(defn max-pooling2d
"Returns a new tensor containing the maximum elements of `nd` in a window sliding along two dimensions.
`nd` must a tensor of shape [m, height, width, channels]. Options include:
- `:pool-size` (required) - [height, width] of the sliding window
- `:strides` (optional, defaults to `:pool-size`) - the [vertical, horizontal] step sizes to use when
sliding the window.
- `:padding` (optional) - an argument accepted by `pad-with`.
The returned tensor is of shape [m, floor((height + vertical-padding - pool-height + 1) / vertical-stride),
floor((width + horizontal-padding - pool-width + 1) / horizontal-stride), channels]. For a given slice
through the first dimension (typically a training example) and channel, each (i, j) in the result is the
maximum element in ((k * vertical-stride)...(k * vertical-stride + pool-height),
(l * horizontal-stride)...(l * horizontal-stride + pool-width)) from `nd`."
[nd options]
(u/check-key-validity options [:pool-size] [:strides :padding])
(let [{:keys [pool-size strides padding]} options
_ (when-not (and (= 2 (count pool-size)))
(u/throw-str "Invalid pool size provided to `max-pooling2d`: '" pool-size "'. Pool size must be "
"a two-element vector."))
padding (get-2d-padding padding pool-size)
padded-input (if padding
(G (pad nd padding))
nd)
strides (or strides pool-size)
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `max-pooling2d`: '" strides "' . Strides must be a "
"2-element seq."))
pool-element-count (apply * pool-size)
pooled (pool2d padded-input pool-size strides)
pooled-height (G (size pooled {:axis 1}))
pooled-width (G (size pooled {:axis 2}))
m (G (size nd {:axis 0}))
chs (G (size nd {:axis 3}))]
(G (-> pooled
(reshape (make-shape m pooled-height pooled-width pool-element-count chs))
(max-along {:axis 3 :collapse true})))))
; Padding can be :same, a vector of paddings for each dimension, or a scalar
(defn conv2d-layer
"Returns the 2d convolution of `operand` with kernels of specified properties. `options` include:
- `:kernel-size` (required) - A two-element vector specifying the kernel [height width].
- `:output-channels` (required) - Number of output channels (equal to the number of kernels that will be
convolved with `operand`).
- `:strides` (optional, default [1 1]) - The [vertical horizontal] step sizes to use when sliding the
kernel over `operand`.
- `:initializer` (optional, default xavier normal) - used for both the kernel and the bias if
initializers specific to those parameters are not given
- `:kernel-iniitializer` (optional)
- `:bias-initializer` (optional)
- `:padding` (optional) - an argument accepted by `pad-with`. `operand` is padded with zeros before
convolution.
See `conv2d` for the structures of the input and output tensors."
[operand options]
(u/check-key-validity options [:kernel-size :output-channels] [:strides :padding :regularizer :initializer
:kernel-initializer :bias-initializer])
(let [{:keys [kernel-size output-channels strides initializer padding regularizer
kernel-initializer bias-initializer]} options
_ (when-not (and (= 2 (count kernel-size)))
(u/throw-str "Invalid kernel provided to conv2d layer: '" kernel-size "'. Kernel size must be "
"a two-element vector."))
padding (get-2d-padding padding kernel-size)
kernel-initializer (get-layer-initializer (or kernel-initializer initializer :lecun-normal)
[1 2 3] nil :conv2d)
bias-initializer (get-layer-initializer (or bias-initializer initializer :zeros) nil nil :conv2d)
strides (or strides [1 1])
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `conv2d`: '" strides "' . Strides must be a 2-element "
"seq."))
input-node (r/construct-operand operand)
input-name (r/get-node-name input-node)
kernel-initializer-fn (fn [input-map]
(let [input-channels (m/dimension-count (get input-map input-name) 3)]
(kernel-initializer (concat [output-channels]
kernel-size
[input-channels]))))
bias-initializer-fn (fn [_] (bias-initializer [1 1 1 output-channels]))
layer-name (gen-layer-name :conv2d)
kernel (make-parameter-node :kernel layer-name kernel-initializer-fn {:regularizer regularizer})
bias (make-parameter-node :bias layer-name bias-initializer-fn)
padded-input (if padding
(G (pad input-node padding))
input-node)]
(create-layer
layer-name
[input-node]
(G (+ (conv2d padded-input kernel strides) bias)))))
(defn softmax
([operand]
(softmax operand {}))
([operand options]
(u/check-key-validity options [] [:axis])
(let [axis (:axis options)
; Subtracting the max before exponentiating prevents overflow. See Goodfellow, Bengio, and Courville
; (2016), pg. 179.
max-corrected (G (->> (max-along operand {:axis axis :collapse false})
(- operand)
exp))]
(G (/ max-corrected
(sum-along max-corrected {:axis axis :collapse false}))))))
(defn cross-entropy
"Computes `-esum(actual * log (predicted + eps))`, where `esum` is the sum over all elements and `eps` is
a small value added for numerical stabilitiy."
[predicted actual]
(let [epsilon (m/array 1e-7)]
(G (-> (+ predicted epsilon)
log
(* actual)
esum
negate))))
(defn binary-cross-entropy
"Computes binary cross entropy:
`-esum(actual * log (predicted + eps) + (1 - actual) * log (1 - predicted + eps)`, where `esum` is the sum
over all elements and `eps` is a small value added for numerical stabilitiy.`"
[predicted actual]
(G (+ (cross-entropy predicted actual)
(cross-entropy (- 1 predicted) (- 1 actual)))))
(defn recurrent
"Simple recurrent layer. `operand` must be a tensor of shape `[example-count example-size timepoint-count]`.
Required options are:
- `:hidden-units` - size of hidden state
- `:output-units` - output dimensionality
Additional options are:
- `:initializer` - weight/bias initializer for the internal `dense` layer
- `:W-initializer` - weight initializer for the internal `dnese` layer
- `:b-initializer` - bias initializer for the internal `dense` layer
- `:state-initializer` - initializer for the hidden state matrix
- `:regularizer` - regularizer for output and recurrent dense layer (fallback if `:output-regularizer`
or `:recurrent-regularizer` isn't provided)
- `:output-regularizer` - regularizer for the output `dense` layer
- `:recurrent-regularizer` - regularizer for the recurrent `dense` layer
- `recurrent-activation` - activation function for the recurrent connection
- `:stateful` (default `false`) - boolean indicating if state should be maintained between iterations
- `:mask` - boolean matrix of shape `[example-count timepoint-count]`. If provided, then state and output
for a given example is updated at all timepoints where the `:mask` is true (1.0). Where the `:mask` is
false (0.0), the previous state and output value are maintained.
The output is of shape `[example-count output-units timepoint-count]`."
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer :regularizer
:output-regularizer :recurrent-activation :recurrent-regularizer :stateful
:mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :recurrent)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
layer-name (gen-layer-name :recurrent)
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
updated-state (G (-> (join-along 1 state timepoint-input)
(dense (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options)
:regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* mask-input updated-state)
(* (- 1 mask-input) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
(defn gru
"Gated recurrent unit layer. Input, output, and options are the same as for a `recurrent` layer, with
the following additional options:
- `:relevance-gate-initializer`
- `:relevance-gate-regularizer`
- `:update-gate-initializer`
- `:update-gate-regularizer`"
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer
:recurrent-activation :relevance-gate-initializer :update-gate-initializer
:regularizer :relevance-gate-regularizer :update-gate-regularizer
:recurrent-regularizer :output-regularizer :stateful :mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
layer-name (gen-layer-name :gru)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :gru)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
dense-options (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options))
relevance-gate-regularizer (or (:regularizer options) (:relevance-gate-regularizer options))
update-gate-regularizer (or (:regularizer options) (:update-gate-regularizer options))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
state-input (G (join-along 1 state timepoint-input))
relevance-gate (G (-> state-input
(dense (assoc dense-options :regularizer relevance-gate-regularizer))
logistic))
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
; num-examples x num-hidden-units
update-gate (G (-> state-input
(dense (assoc dense-options :regularizer update-gate-regularizer))
logistic
(* mask-input)))
candidate-next-state (G (-> (join-along 1 (* relevance-gate state) timepoint-input)
(dense (assoc dense-options :regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* update-gate candidate-next-state)
(* (- 1 update-gate) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NN-specific reporters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-multiclass-accuracy-reporter
"Returns a reporter function for the accuracy of predictions for a multi-class classification problem.
The returned function receives arguments [predicted actual], where `predicted` is a tensor containing
probabilities for each class along one axis and samples along all other axes. `actual` is a binary tensor
of the same structure containing the true class memberships represented in one-hot form. `options` can
include:
- `:class-axis`: the index of the axis spanning classes"
([]
(make-multiclass-accuracy-reporter {:class-axis 1}))
([options]
(u/check-key-validity options [:class-axis] [])
(let [class-axis (:class-axis options)]
(fn [predicted actual]
#_(println "predicted:" (first (m/slices predicted)))
#_(println "actual: " (first (m/slices actual)))
(-> predicted
(r/tensure-max-mask class-axis)
(m/mul actual)
m/esum
m/scalar->number
(/ (apply * (assoc (m/shape predicted) class-axis 1)))
(* 100)
(r/make-datapoint "Accuracy" :percent))))))
; TODO: Test this (this has not been tested at all)
(defn make-binary-classifier-reporter
"Returns a reporter function for the accuracy of predictions for a binary classification problem. The
returned function receives arguments [predicted actual], where `predicted` is a tensor where each element
is a probability of that sample belonging to one class, and `actual` is a binary tensor of the same shape
representing the true class memberships."
[]
(fn [predicted actual]
(-> (m/ge predicted (m/array 0.5))
(m/eq actual)
m/esum
m/->int
(/ (m/ecount actual))
(* 100.0)
(r/make-datapoint "Accuracy" :percent))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Model
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def reserved-node-names #{:training :predicting :testing})
(defn make-model
"Cosntructs a model, given:
- `:data` (required) - A map of maps (dataset-name -> variable-name -> data). The common case is to have
multiple datasets for different uses (e.g. `:training`, `:dev`, and `:test`), each with the same
variables (e.g. `:x` and `:y`).
- `:graph` (required) - A computation graph for the model.
- `:optimizer` (optional, defaults to gradient-descent-optimizer)
- `:optimizer-options` (optional) - Map of options to pass to `:optimizer`
- `:constants` (optional) - A map of name to value for graph inputs that do not change (i.e. that are
constant cross datasets).
- `:parameters` (optional) - A map of name to value for graph parameters. This can be excluded if all
parameters have initialization functions specified."
[& {:as options}]
(u/check-key-validity options [:graph :data] [:constants :parameters :optimizer :optimizer-options
; This is a private piece of data used to keep track of
; prior optimization results.
::prev-optimizer-results])
(let [{:keys [graph constants parameters optimizer optimizer-options data]
:or {constants {}
parameters {}
optimizer r/gradient-descent-optimizer
optimizer-options {}}} options
all-input-keys (into #{} (mapcat keys (vals data)))
;; data (u/update-vals data (fn [dataset]
;; (u/update-vals dataset #(if (m/array? %) % (m/array %)))))
]
(when-let [invalid-input-names (seq (set/intersection reserved-node-names all-input-keys))]
(u/throw-str "Invalid input names: '" invalid-input-names "'. These names are reserved."))
(when-let [invalid-constant-names (seq (set/intersection reserved-node-names
(into #{} (keys constants))))]
(u/throw-str "Invalid constant names: '" invalid-constant-names "'. These names are reserved."))
{:graph graph
:constants constants
:parameters parameters
:optimizer optimizer
:optimizer-options optimizer-options
:data data
::prev-optimizer-results (get options ::prev-optimizer-results {})}))
(defn update-model
[model & {:as updates}]
(apply make-model (apply concat (merge model updates))))
(defn update-prev-optimizer-results
[model dataset-or-name optimizer-result]
(assoc-in model [::prev-optimizer-results dataset-or-name] optimizer-result))
(defn get-previous-optimizer-result
[model dataset-or-name]
(get-in model [::prev-optimizer-results dataset-or-name]))
(defn get-model-constants
[model]
(:constants model))
(defn get-model-parameters
[model]
(:parameters model))
(defn get-model-optimizer
[model]
(:optimizer model))
(defn get-model-optimizer-options
[model]
(:optimizer-options model))
(defn get-model-graph
"Returns `model`'s computation graph."
[model]
(:graph model))
(defn get-model-dataset
"If `dataset-or-name` is a map (assumed to contain variable-name -> value), just returns the map;
otherwise looks up the dataset by the provided name in the model's associated data and returns the
corresponding map of variable-name -> value."
[model dataset-or-name]
(if (map? dataset-or-name)
dataset-or-name
(let [data (:data model)
dataset (get data dataset-or-name)]
(when-not dataset
(u/throw-str "Could not locate dataset '" dataset-or-name "'. Model only has datasets: '"
(keep (fn [[k v]] (when v k)) data) "'."))
dataset)))
(defn get-model-data
"Returns data for a given dataset and variable name. For example, `(get-model-data :training :x)`. Throws
exceptions if the model doesn't have a dataset or variable of the given name."
[model dataset-name varname]
(let [dataset (get-model-dataset model dataset-name)
var-data (get dataset varname)]
(when-not var-data
(u/throw-str "Could not locate data for variable '" varname "' in dataset '" dataset-name
"'. Dataset only has variables: '" (keep (fn [[k v]] (when v k)) dataset) "'."))
var-data))
(defn get-model-input-map
"Returns all a map of all model graph inputs (constants and vars from `dataset-or-name`)."
[model dataset-or-name]
(merge (get-model-dataset model dataset-or-name)
(get-model-constants model)))
(defn- get-all-model-parameter-nodes
"Returns a seq of all distinct input nodes in `model`'s graph that are parameters (either have `:parameter`
in their data set to `true` or are in the model`s `:parameters` map."
[model]
(let [specified-params (into #{} (keys (get-model-parameters model)))]
(->> (get-model-graph model)
r/get-all-graph-inputs
distinct
(filter #(or (-> % r/get-node-data :parameter)
(specified-params (r/get-node-name %)))))))
(defn- get-all-model-parameter-names
"Like `get-all-model-parameter-nodes` but returns a seq of names instead of a seq of nodes."
[model]
(map r/get-node-name (get-all-model-parameter-nodes model)))
(defn- get-all-model-parameter-values
"Returns a map of parameter name->value for all parameters of the given graph and dataset. Will include
`nil` values for parameters that have not been initialized."
[model]
(let [graph (get-model-graph model)
parameters (get-model-parameters model)
uninitialized-parameter-names (set/difference (into #{} (get-all-model-parameter-names model))
(into #{} (keys parameters)))
uninitialized-parameter-map (->> (map (juxt identity (constantly nil)) uninitialized-parameter-names)
(into {}))]
(merge parameters
uninitialized-parameter-map)))
(defn- get-trainable-parameter-name-set
[model]
(->> (get-all-model-parameter-nodes model)
(keep #(when (:trainable (r/get-node-data %))
(r/get-node-name %)))
(into #{})))
;; TODO: Get rid of `:training`, `:testing`, `:predicting` flags and just allow the user to pass these in
;; (e.g. either directly in the dataset, or through some option that allows additional inputs to be provided).
(defn evaluate-model
"Returns the result of running `model` on `dataset-or-name`. For example,
`(evaluate-model model :training)` will return the model's output for the `:training` dataset. Options
include:
- `:training` - boolean indicating if the `:training` input should be set to `true`
- `:testing` - boolean indicating if the `:testing` input should be set to `true`
If neither `:training` nor `:testing` is specified, the `:predicting` flag is set to true."
([model dataset-or-name]
(evaluate-model model dataset-or-name {}))
([model dataset-or-name options]
(u/check-key-validity options [] [:training :testing])
(let [extra-inputs (cond (:training options) {:training 1 :predicting 0 :testing 0}
(:testing options) {:training 0 :predicting 0 :testing 1}
:else {:training 0 :predicting 1 :testing 0})
graph (get-model-graph model)]
(->> (merge (get-all-model-parameter-values model)
extra-inputs
(get-model-input-map model dataset-or-name))
(r/evaluate graph)))))
(defn- make-optimized-model
"Returns a new model derived from `model` but with all properties updated based on `optimizer-result`."
[model dataset-or-name optimizer-result]
(let [untrained-parameters (r/get-optimized-state optimizer-result)
trained-parameters (r/get-optimized-params optimizer-result)]
(-> (update-model model
:graph (r/get-optimized-graph optimizer-result)
:parameters (merge trained-parameters
untrained-parameters))
(update-prev-optimizer-results dataset-or-name (r/reset-optimizer-reporting optimizer-result)))))
(defn- optimize-model
[model dataset-or-name iterations async?]
(let [optimizer (get-model-optimizer model)
optimizer-options (as-> (get-model-optimizer-options model) optimizer-options
(if (and #_(= optimizer r/gradient-descent-optimizer)
(:batch-size optimizer-options)
(not (:batch-inputs optimizer-options)))
(let [default-batch-inputs (->> (get-model-dataset model dataset-or-name)
keys
(mapv #(vector % 0))
(into {}))]
(assoc optimizer-options :batch-inputs default-batch-inputs))
optimizer-options)
(assoc optimizer-options :iterations iterations))
optimize-fn (if async?
r/optimize-async
r/optimize)]
(if-let [prev-result (get-previous-optimizer-result model dataset-or-name)]
(optimize-fn optimizer prev-result optimizer-options)
(let [graph (get-model-graph model)
all-param-map (get-all-model-parameter-values model)
trainable-param-name-set (get-trainable-parameter-name-set model)
trainable-param-map (select-keys all-param-map trainable-param-name-set)
state-param-map (apply dissoc all-param-map trainable-param-name-set)
extra-inputs {:training 1
:predicting 0
:testing 0}
input-map (merge extra-inputs
(get-model-input-map model dataset-or-name))]
(optimize-fn optimizer graph input-map trainable-param-map state-param-map optimizer-options)))))
(defn train-model
"Fits `model` to data in `dataset-or-name` by running the model's optimizer for `iterations` iterations.
Defaults to running 1 iteration on the `:training` data. Blocks until complete."
([model]
(train-model model 1))
([model iterations]
(train-model model :training iterations))
([model dataset-or-name iterations]
(let [optimizer-result (optimize-model model dataset-or-name iterations false)]
(make-optimized-model model dataset-or-name optimizer-result))))
(defn train-model-async
"Fits `model` to data in `dataset-or-name` (default `:training`) by running the model's optimizer for
`iterations` (defaults to infinite). Launches optimization in a new thread and immediately returns a
0-arity function, `stop`, that when called will immediately return the trained model from the last complete
iteration and terminate the optimization process after the next iteration is complete."
([model]
(train-model-async model nil))
([model iterations-or-dataset-or-name]
(let [[iterations dataset-or-name] (if (or (nil? iterations-or-dataset-or-name)
(number? iterations-or-dataset-or-name))
[iterations-or-dataset-or-name :training]
[nil iterations-or-dataset-or-name])]
(train-model-async model dataset-or-name iterations)))
([model dataset-or-name iterations]
(let [stop-optimizing (optimize-model model dataset-or-name iterations true)]
(fn stop
[]
(let [optimizer-result (stop-optimizing)]
(make-optimized-model model dataset-or-name optimizer-result))))))
; TODO:
; Improvements
; - Remove `data` from model. It makes more sense to keep the model and data completely separate.
; - This will also simplify all the `dataset-or-name` arguments where the supplied data can be either a
; map of data or a dataset name.
; - Could add a separate set of functions for managing datasets (e.g. bundling together sets of training
; and test data as the model does now).
; - Consider adding a set of required input names to model so datasets can be validated to ensure they have
; the required inputs (probably not possible to validate that _all_ inputs exist due to `if` branches--
; some graphs might not require some inputs, depending on conditional branching).
; - Add validation to make sure regularization is applied (an easy mistake is to pass a regularizer
; as an option for some layer and then to not pass the cost node through regularization layer). We can
; check that if any nodes have regularization, there must be a `regularize` node and, if not, we can
; throw an Exception. It's difficult to automatically inclue the `regularize` node, because it's
; difficult to know where in the graph it should go if there are conditional branches.
; - Figure out better way to handle print logging -- right now it's necessary to manually flush output
; if the last logging statement doesn't have a newline (which triggers a flush). Somehow always flush the
; print logger after the last iteration.
; - Be able to lazily load batches into memory.
; - Allow simple-optimize-like options for the model's optimizer-options
; Additional features
; - Serialization - be able to save and load models from/to disk
; - Periodic backups - be able to persist model data during training periodically, so if training gets
; interrupted, not all progress is lost.
; - More layers
; - Mean squared error (e.g. used in book reviews example)
; Quality
; - Tests:
; - to ensure regularization is not applied more than once for each regularized node (this was a
; previous bug that has since been fixed, but tests were not added to catch it).
; - of one-hot encoding functions
; - of softmax layer
; - of cross-entropy layer
; - of complete reporting and logging framework
; - of the layer initialization framework
; - Figure out how to handle evaluation with stateful recurrent layers when batching. It is currently
; possible to have batches that need state of different sizes, but if state is maintained between
; iterations, this causes an excpetion. Remove state before evaluating?
; - Reset recurrent netowrk state between epochs?
; - Standardize names of arguments of the same type/meaning (e.g. sometimes "nd" is used for a tensor node,
; and other times "operand" is used).
; - Automatically add '' around non-strings in throw-str
| 9256 | (ns neurojure.core
(:require [clojure.set :as set]
[neurojure.utils :as u :refer [def- -?> -?>>]]
[ranvier.core :as r :refer [G]]
[tensure.core :as m]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initializers
;;
;; Initializers are functions that take a single argument, a tensor shape, and return a tensor of that shape,
;; with elements set to values determined by the initializer. Except for `zeros` and `ones`, the initializers
;; are generated by factory functions that return initializers with properties based on the parameters they
;; receive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TODO: Test this
(defn- get-axis-size
"Given a vector representing a tensor `shape` and either a single `axis` index or vector of axis indices,
returns the product of the sizes of the specified axes."
[shape axis]
(let [axes (if (number? axis)
[axis]
axis)
rank (count shape)]
(reduce (fn [size i]
(when (>= i rank)
(u/throw-str "Invalid axis for a tensor of shape '" shape "'."))
(* size (nth shape i)))
1
axes)))
(defn zeros-initializer
"Returns a tensor of `shape` filled with 0's."
[shape]
(m/zeros shape))
(defn ones-initializer
"Returns a tensor of `shape` filled with 1's."
[shape]
(m/ones shape))
(defn make-fill-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with `constant`."
[constant]
(fn [shape]
(m/filled shape constant)))
(defn make-constant-initializer
"Returns a function that takes a shape and will return the tensor `constant` of that shape. Throws an
exception if the constant does not have the shape."
[constant]
(let [constant (if (m/array? constant)
constant
(m/array constant))
constant-shape (m/shape constant)]
(fn [shape]
(when (not= constant-shape shape)
(u/throw-str "Attempt to initialize a tensor of shape '" shape "' with a constant of shape '"
constant-shape "'."))
constant)))
(defn make-uniform-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values uniformly distributed in [min, max). `min` and `max` can be either numbers or functions that when
applied to the shape will return numbers."
([]
(make-uniform-random-initializer -0.01 0.01))
([min max]
(fn [shape]
(let [nd (m/sample-uniform shape)
min (m/array (if (fn? min) (min shape) min))
max (m/array (if (fn? max) (max shape) max))]
(m/add (m/mul (m/sub max min) nd) min)))))
(defn make-normal-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev`. `mean` and `stdev` can be either
numbers or functions that return the numbers when applied to the shape."
([]
(make-normal-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [nd (m/sample-normal shape)
stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))]
(m/add (m/mul stdev nd) mean)))))
(defn make-truncated-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev` but with no values >2 SD's from
the mean. `mean` and `stdev` can be either numbers or functions that return the numbers when applied to
the shape."
([]
(make-truncated-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))
result-element-count (apply * shape)
get-element-seq (fn next [batch-size]
(lazy-cat (m/eseq (m/sample-normal [batch-size]))
(next (max 128 (* batch-size 0.05)))))
result (->> (get-element-seq result-element-count)
(filter #(and (> % -2) (< % 2)))
(take result-element-count)
m/array)]
(m/mul! result stdev)
(m/add! result mean)
(m/reshape result shape)))))
(defn make-variance-scaling-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around 0. The standard deviation will be `sqrt(scale / axis-sum)` where
`axis-sum` is the sum of the sizes of all axes in `axis`. `axis` can be either a vector of axes or an
integer indicating a single axis. The distribution is truncted such that no values >2 SD's from 0 are
included."
([]
(make-variance-scaling-initializer 1))
([scale]
(make-variance-scaling-initializer scale 1))
([scale axis]
(let [axes (if (number? axis) [axis] axis)]
(fn [shape]
(for [axis axes]
(when (>= axis (count shape))
(u/throw-str "Cannot initialize tensor of shape " shape " with variance scaled on axis "
axis ", because axis is out of bounds.")))
((make-truncated-random-initializer
0
(Math/sqrt (/ scale (apply + (map #(nth shape %) axes)))))
shape)))))
(defn make-lecun-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(3 / m), sqrt(3 / m))`, where m is the size of the `input-axes`, either
a single axis index or vector of axis indices (defaults to 1)."
([]
(make-lecun-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 3 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-lecun-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(1 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated
at +/- 2 SD's."
([]
(make-lecun-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 1 (get-axis-size % input-axes))))))
(defn make-he-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / m), sqrt(6 / m))`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1)."
([]
(make-he-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 6 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-he-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated at
+/- 2 SD's."
([]
(make-he-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (get-axis-size % input-axes))))))
(defn make-xavier-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / (m + n)), sqrt(6 / (m + n)))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0)."
([]
(make-xavier-uniform-initializer 1 0))
([input-axes output-axes]
(let [bound-fn #(Math/sqrt (/ 6 (+ (get-axis-size % input-axes) (get-axis-size % output-axes))))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-xavier-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / (m + n))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0). The distribution is truncated
at +/- 2 SD's."
([]
(make-xavier-normal-initializer 1 0))
([input-axes output-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (+ (get-axis-size % input-axes) (get-axis-size % output-axes)))))))
; TODO: Test this.
(defn- get-layer-initializer
"Returns an initializer (function that takes a shape and returns an initialized tensor of that shape),
given:
- `initializer-selector` - an initializer function or keyword
- `input-axes` - the axes of the tensor being initialized that span 'input values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `output-axes` - the axes of the tensor being initialized that span 'output values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `layer-type` - keyword or string identifying the layer (used to provide more descriptive error
message)
If `initializer-selector` is a function, it's just returned. If it's a keyword, then the corresponding
factory function is looked up and used to construct a new initializer. The product of the sizes of the
`input-axes` should correspond to the 'fan in' of the layer (the number of input values that contribute to
any single value in the output), while the product of the sizes of the `output-axes` should correspond to
the 'fan out' of the layer (the number of output values that contribute to any single input value to the
next layer). If the notion of 'fan in' or 'fan out' does not apply to a layer or cannot be calculated
from the parameter shape, then `input-axes` or `output-axes` can be set to `nil`. Selecting an initializer
that does not apply to a layer will cause an Exception."
[initializer-selector input-axes output-axes layer-type]
(if (fn? initializer-selector)
initializer-selector
(let [throw-invalid-initializer #(u/throw-str "Invalid initializer for '" layer-type "' layer: '"
initializer-selector "'.")]
(when (and (nil? input-axes) (#{:lecun-uniform :luecn-normal :he-uniform :he-normal
:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(when (and (nil? output-axes) (#{:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(case initializer-selector
:zeros zeros-initializer
:ones ones-initializer
:uniform (make-uniform-random-initializer)
:normal (make-normal-random-initializer)
:truncated (make-truncated-random-initializer)
:variance-scaling (make-variance-scaling-initializer)
:lecun-uniform (make-lecun-uniform-initializer input-axes)
:lecun-normal (make-lecun-normal-initializer input-axes)
:he-uniform (make-he-uniform-initializer input-axes)
:he-normal (make-he-normal-initializer input-axes)
:xavier-uniform (make-xavier-uniform-initializer input-axes output-axes)
:xavier-normal (make-xavier-normal-initializer input-axes output-axes)
(throw-invalid-initializer)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layer helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map of layer type (a string) to the number of times `gen-layer-name` has been called with that string
; as the `layer-type` argument.
(def- layer-type-counters (atom {}))
(defn- gen-layer-name
"Given `layer-type` (a keyword or string), returns a new unique keyword identifier for a layer of that type.
E.g. `(gen-layer-name :dense)` will return 'dense0', `:dense1', ':dense2', etc. on each call."
[layer-type]
(let [type-str (name layer-type)]
(if (contains? @layer-type-counters type-str)
(swap! layer-type-counters update type-str inc)
(swap! layer-type-counters assoc type-str 0))
(keyword (str type-str (get @layer-type-counters type-str)))))
(defn- gen-param-name
"Given a `layer-name` and a `param-name` (both either keywords or strings), returns a unique keyword
identifier for the parameter. E.g. `(gen-param-name 'dense0' :W)` returns 'dense0_W'."
[layer-name param-name]
(if layer-name
(keyword (str (name layer-name) "_" (name param-name)))
param-name))
(defn- tag-layer-nodes-recursive
[g input-set layer-name]
(let [operands (r/get-node-operands g)]
(if (input-set g)
g
(->> (mapv #(tag-layer-nodes-recursive % input-set layer-name) operands)
(r/update-node g
:data (update (r/get-node-data g) :layers #(conj (or % []) layer-name))
:operands)))))
(defn- tag-layer-nodes
"Traverses computation graph `g`, conj'ing `layer-name` into the :layers vector in the node's :data but
ommitting all nodes in `input-nodes` (seq of nodes or any object that can be constructed into a node) and
all their descendents."
[g input-nodes layer-name]
(let [input-set (->> (map r/construct-operand input-nodes)
(into #{}))
node-data (r/get-node-data g)]
(r/update-node (tag-layer-nodes-recursive g input-set layer-name)
:data (assoc node-data
:layers (conj (get node-data :layers []) layer-name)
:entry-to-layer layer-name))))
(defn- create-layer
[layer-name input-nodes g]
(tag-layer-nodes g input-nodes layer-name))
(defn- make-input-node
"Returns an input node for a layer, given:
- `input-name` - the keyword name of the input
- `layer-name` - the keyword name of the layer
- `initializer` - an initializer function, which must receive a map of node names to values at the time
of initialization and return the initialized value of the node
- `data` - an arbitrary map of additional data
The values for layer inputs must be either 1) provided (e.g. passed in from a model's data), or 2)
generated by the initialization function. For non-parameter/state inputs whose values are not provided,
the node will be re-initialized with every iteration. For inputs that should be optimized, use
`make-parameter-node`, and for inputs whose values should persist from iteration to iteration, use
`make-state-node`."
([input-name layer-name]
(make-input-node input-name layer-name nil))
([input-name layer-name initializer]
(make-input-node input-name layer-name initializer {}))
([input-name layer-name initializer data]
(r/input (gen-param-name layer-name input-name) initializer (assoc data
:parameter false
:trainable false))))
(defn- make-parameter-node
"Like `make-input-node`, but returns a node for a parameter input. Parameters are passed in the `param-map`
to the optimizer--their values can be changed by the optimizer with every iteration."
([param-name layer-name]
(make-parameter-node param-name layer-name nil))
([param-name layer-name initializer]
(make-parameter-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable true))))
(defn- make-state-node
"Like `make-input-node`, but returns an input node for a 'state' input--i.e. a value that can change
during an iteration and whose values are persisted between iterations."
([param-name layer-name]
(make-state-node param-name layer-name nil))
([param-name layer-name initializer]
(make-state-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable false))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regularizers
;;
;; Regulariers are functions that receive two arguments:
;; - a computation graph node that is assumed to be cost (though in practice it can be any node)
;; - a parameter node for which to apply regularization
;; They must return a new computation graph node with regularization for the given parameter applied. They
;; are generally constructed using a make-* function that returns a regularizer with properties specified
;; by the arguments to the make-* function.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-l2-regularizer
"Returns an L2 regularizer:
`cost + regularization-weight / 2m * (sum of squares of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l2-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l2-regularizer)
[g num-examples parameter-node :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (pow parameter-node 2)))
#_(report (make-value-reporter "reg: ") (make-print-logger)))))
:regularizer-for (r/get-node-name parameter-node))))))
(defn make-l1-regularizer
"Returns an L1 regularizer:
`cost + regularization-weight / 2m * (sum of absolute value of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l1-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l1-regularizer)
[g parameter-node num-examples :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (abs parameter-node))))))
:regularizer-for (r/get-node-name parameter-node))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Layers
;;
(defn regularize
[g]
(->> (r/get-all-graph-nodes g)
distinct
(reduce (fn [regularized-graph node]
(if-let [regularizer (->> node r/get-node-data :regularizer)]
(regularizer regularized-graph node)
regularized-graph))
g)))
(defn sigmoid-cross-entropy
"Computes the sum over all elements of the result of
`max(predicted, 0) - predicted * actual + log (1 + e^-abs(predicted))`. This is roughly equivalent to the
total logistic loss `actual * -log(sigmoid(predicted)) + (1 - actual) * -log(1 - sigmoid(predicted))`, but
with some modifications for numerical stability. Based on the TensorFlow implementation
(https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits)."
[predicted actual]
(G (esum
(+ (max predicted 0)
(* (- predicted) actual)
(log (+ 1 (exp (- (abs predicted)))))))))
; TODO: Add axis option.
(defn dropout
"Masks a fraction of elements in `g` and scales up remaining elements to maintain a constant sum:
- `:frequency` (required) - frequency of elements to drop out (on average)
- `:exact` (default true) - boolean indicating whether scaling of other options in `g` must be exact
(i.e. proportional to the number of elements actually dropped out, which may vary randomly from run to
run) or approximate (proportional to `:frequency`). The results for `:exact == true` and
`:exact == false` converge when the size of `g` is large, but the `:exact` computation is more
expensive."
[g options]
(u/check-key-validity options [:frequency] [:exact])
(let [frequency (:frequency options)
exact (if (contains? options :exact)
(:exact options)
true)
keep-vec (G (>= (random-uniform (shape g))
frequency))
scaling-factor (if exact
(G (/ (size g)
(esum keep-vec)))
(/ 1 (- 1 frequency)))]
(create-layer
(gen-layer-name :dropout)
[g :training]
(G (tensor-if :training
(* keep-vec g scaling-factor)
g)))))
(defn mean
"Calculates the arithmetic mean of `g` along some axes/axes. `options` can include:
- `:axis` (optional) - a scalar or vector indicating the axes across which the mean should be taken; if
ommitted, the mean of all elements in `g` will be returned.
- `:collapse` (optional) - boolean indicating if the dimensions specified in `:axis` should be removed.
If false, dimensions will be maintained with a size of 1."
([g]
(mean g {}))
([g options]
(u/check-key-validity options [] [:axis :collapse])
(let [{:keys [axis collapse]} options]
(create-layer
(gen-layer-name :mean)
[g]
(G (/ (sum-along g {:axis axis
:collapse (clojure.core/or collapse false)})
(size g {:axis axis})))))))
(defn normalize
"Calculates baseline-corrected-g / variance, where baseline-correcred-g is g - mean(g), and variance is
sum(base-line-corrected-g^2) / size(baseline-corrected-g). Options can include `:axis`, a single axis or
a vector of axes over which to perform the `sum`, `size`, and `mean` operations. If `:axis` is not
provided, normalization will be done over the entire tensor `g`. The returned result is the same shape as
`g`."
([g]
(normalize g {}))
([g options]
(u/check-key-validity options [] [:axis])
(let [axis (get options :axis 0)
opts {:axis axis
:collapse false}
mean (mean g opts)
baseline-corrected (G (- g mean))
variance (G (/ (sum-along (pow baseline-corrected 2) opts)
(size baseline-corrected {:axis axis})))]
(create-layer
(gen-layer-name :normalize)
[g]
(G (/ baseline-corrected
variance))))))
(defn relu
"Computes `min(g, 0)`."
[g]
(create-layer
(gen-layer-name :relu)
[g]
(G (max g 0))))
(defn logistic
"Computes `1 / (1 + e^-g)`."
[g]
(G (/ 1 (+ 1 (exp (- g))))))
(defn logistic-binary-classifier
"Returns a boolean tensor representing `1 / (1 + e^-`g`) >= 0.5`."
[g]
(G (>= (logistic g) 0.5)))
(defn dense
"Given an `operand` matrix of shape [m input-size], computes `operand . W + b`, where `.` is matrix
multiplication, W is a parameter matrix of shape [input-size units], and b is a parameter matrix of shape
[1 units]. Options include:
- `:units` (required) - scalar number of 'units' to include in the layer
- `:initializer` (optional, default xavier normal) - single initializer for both W and b
- `:W-intializer` (optional) - initializer for W, used instead of that specified in `:initializer` if
both are provided (default xavier normal)
- `:b-initializer` (optional) - like `:W-initializer` but for b (default zeros)
- `:regularizer` (optional) - default `nil`"
[operand options]
(u/check-key-validity options [:units] [:initializer :W-initializer :b-initializer :regularizer])
(let [{:keys [units regularizer initializer W-initializer b-initializer]} options
W-initializer (get-layer-initializer (or W-initializer initializer :xavier-normal) 0 1 :dense)
b-initializer (get-layer-initializer (or b-initializer initializer :zeros) 0 1 :dense)
input-node (r/construct-operand operand)
layer-name (gen-layer-name :dense)
input-dimension (when (r/is-const? input-node)
(m/column-count (r/get-node-value input-node)))
input-name (r/get-node-name input-node)
W-initializer-fn (fn [input-map]
(W-initializer [(or input-dimension
(m/column-count (get input-map input-name)))
units]))
b-initializer-fn (fn [input-map]
(b-initializer [1 units]))
W (make-parameter-node :W layer-name W-initializer-fn {:regularizer regularizer})
b (make-parameter-node :b layer-name b-initializer-fn)]
(create-layer
layer-name
[input-node]
(G (+ (mmul input-node W) b)))))
(r/defop- pool2d
"Given tensor `nd` of shape [m, height, width, channels], vector `pool-size` of shape
[pool-rows, pool-columns], and vector `strides` of shape [vstride, hstride], returns a tensor of shape
[m, floor((height - pool-rows) / vstride) + 1, floor((width - pool-cols) / hstride) + 1,
pool-rows * pool-columns * channels]. In the returned tensor, the vector [k, i, j, :all] (i.e. the elements
along the last dimension at a given point), consists of the elements of `nd` in selection
[i * vstride...(i * vstride + pool-rows - 1), j * hstride...(j * hstride + pool-cols - 1), :all-channels]
linearized in order row, col, channel. That is, channel changes fastest, and row changes slowest."
[^:nd nd pool-size strides]
:v (let [[kh kw] pool-size
[m height width chs] (m/shape nd)
[vstride hstride] strides
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))]
(when (or (zero? unstrided-result-height)
(zero? unstrided-result-width))
(u/throw-str "Cannot perform 2d convolution of a tensor of shape '" (m/shape nd) "' with a kernel of "
"shape '" pool-size "'. The kernel width and height cannot exceed the width and "
"height of an input tensor."))
(->> (for [i (range kh)
j (range kw)]
(m/select-range nd
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all))
(apply m/join-along 3)))
:dnd (let [[kh kw] pool-size
nd-shape (m/shape nd)
[_ height width chs] nd-shape
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))
[vstride hstride] strides
result (m/zeros nd-shape)]
(doseq [i (range kh)
j (range kw)
:let [k (* chs (+ (* i kw) j))]]
(m/add! (m/select-range result
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all)
(m/select-range dv :all :all :all [k (+ k chs)])))
result))
; TODO: Research other possible implementations of this to see if this can be made faster. (e.g. doing
; it in frequency space).
(defn conv2d
"Given tensor `nd` of shape [m, height, width, channels], a `kernel` of shape
[output-chs, kernel-height, kernel-width, input-chs], and a vector of strides like `[row-stride,
column-stride]`, returns a tensor of shape [m, floor((height - kernel-height + 1) / row-stride),
floor(width - kernel-width + 1) / column-stride), output-chs] that is the product of convolving each
of m examples with the kernel."
[nd kernel strides]
(let [[kout_chs kh kw] (mapv #(G (size kernel {:axis %})) (range 3))
pooled-nd (G (pool2d nd (make-shape kh kw) strides))
[m height width linear-kernel-size] (mapv #(G (size pooled-nd {:axis %})) (range 4))
reshaped-kernel (G (transpose (reshape kernel (make-shape kout_chs linear-kernel-size))))]
; We reshape `pooled-nd` into a matrix, before calculating the product with `reshaped-kernel`, because
; backpropagation of `mmul` is much faster for matrices than for tensors.
(G (-> (reshape pooled-nd (make-shape (* m height width) linear-kernel-size))
(mmul reshaped-kernel)
(reshape (make-shape m height width kout_chs))))))
(defn- get-2d-padding
"Given a padding option accepted by a 2d pooling or convolutional layer, returns a full padding vector for
a 4d tensor accepted by that layer. Throws an exception if `padding-option` is not valid. See `conv2d` and
`max-pooling2d`."
[padding-option window-size]
(let [padding-dimensionality (u/vector-dimensionality padding-option)]
(cond (nil? padding-option) nil
(= :same padding-option) (let [[padding-h padding-w] (mapv #(/ (dec %) 2) window-size)]
[[0 0]
[(int (Math/ceil padding-h)) (int (Math/floor padding-h))]
[(int (Math/ceil padding-w)) (int (Math/floor padding-w))]
[0 0]])
(number? padding-option) [0 padding-option padding-option 0]
(= padding-dimensionality 1) [0 (first padding-option) (second padding-option) 0]
(= padding-dimensionality 2) [[0 0] (first padding-option) (second padding-option) [0 0]]
:else (u/throw-str "Invalid 2d padding: '" padding-option "'. Padding must be a valid argument to "
"`pad-with` for a matrix."))))
(defn max-pooling2d
"Returns a new tensor containing the maximum elements of `nd` in a window sliding along two dimensions.
`nd` must a tensor of shape [m, height, width, channels]. Options include:
- `:pool-size` (required) - [height, width] of the sliding window
- `:strides` (optional, defaults to `:pool-size`) - the [vertical, horizontal] step sizes to use when
sliding the window.
- `:padding` (optional) - an argument accepted by `pad-with`.
The returned tensor is of shape [m, floor((height + vertical-padding - pool-height + 1) / vertical-stride),
floor((width + horizontal-padding - pool-width + 1) / horizontal-stride), channels]. For a given slice
through the first dimension (typically a training example) and channel, each (i, j) in the result is the
maximum element in ((k * vertical-stride)...(k * vertical-stride + pool-height),
(l * horizontal-stride)...(l * horizontal-stride + pool-width)) from `nd`."
[nd options]
(u/check-key-validity options [:pool-size] [:strides :padding])
(let [{:keys [pool-size strides padding]} options
_ (when-not (and (= 2 (count pool-size)))
(u/throw-str "Invalid pool size provided to `max-pooling2d`: '" pool-size "'. Pool size must be "
"a two-element vector."))
padding (get-2d-padding padding pool-size)
padded-input (if padding
(G (pad nd padding))
nd)
strides (or strides pool-size)
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `max-pooling2d`: '" strides "' . Strides must be a "
"2-element seq."))
pool-element-count (apply * pool-size)
pooled (pool2d padded-input pool-size strides)
pooled-height (G (size pooled {:axis 1}))
pooled-width (G (size pooled {:axis 2}))
m (G (size nd {:axis 0}))
chs (G (size nd {:axis 3}))]
(G (-> pooled
(reshape (make-shape m pooled-height pooled-width pool-element-count chs))
(max-along {:axis 3 :collapse true})))))
; Padding can be :same, a vector of paddings for each dimension, or a scalar
(defn conv2d-layer
"Returns the 2d convolution of `operand` with kernels of specified properties. `options` include:
- `:kernel-size` (required) - A two-element vector specifying the kernel [height width].
- `:output-channels` (required) - Number of output channels (equal to the number of kernels that will be
convolved with `operand`).
- `:strides` (optional, default [1 1]) - The [vertical horizontal] step sizes to use when sliding the
kernel over `operand`.
- `:initializer` (optional, default xavier normal) - used for both the kernel and the bias if
initializers specific to those parameters are not given
- `:kernel-iniitializer` (optional)
- `:bias-initializer` (optional)
- `:padding` (optional) - an argument accepted by `pad-with`. `operand` is padded with zeros before
convolution.
See `conv2d` for the structures of the input and output tensors."
[operand options]
(u/check-key-validity options [:kernel-size :output-channels] [:strides :padding :regularizer :initializer
:kernel-initializer :bias-initializer])
(let [{:keys [kernel-size output-channels strides initializer padding regularizer
kernel-initializer bias-initializer]} options
_ (when-not (and (= 2 (count kernel-size)))
(u/throw-str "Invalid kernel provided to conv2d layer: '" kernel-size "'. Kernel size must be "
"a two-element vector."))
padding (get-2d-padding padding kernel-size)
kernel-initializer (get-layer-initializer (or kernel-initializer initializer :lecun-normal)
[1 2 3] nil :conv2d)
bias-initializer (get-layer-initializer (or bias-initializer initializer :zeros) nil nil :conv2d)
strides (or strides [1 1])
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `conv2d`: '" strides "' . Strides must be a 2-element "
"seq."))
input-node (r/construct-operand operand)
input-name (r/get-node-name input-node)
kernel-initializer-fn (fn [input-map]
(let [input-channels (m/dimension-count (get input-map input-name) 3)]
(kernel-initializer (concat [output-channels]
kernel-size
[input-channels]))))
bias-initializer-fn (fn [_] (bias-initializer [1 1 1 output-channels]))
layer-name (gen-layer-name :conv2d)
kernel (make-parameter-node :kernel layer-name kernel-initializer-fn {:regularizer regularizer})
bias (make-parameter-node :bias layer-name bias-initializer-fn)
padded-input (if padding
(G (pad input-node padding))
input-node)]
(create-layer
layer-name
[input-node]
(G (+ (conv2d padded-input kernel strides) bias)))))
(defn softmax
([operand]
(softmax operand {}))
([operand options]
(u/check-key-validity options [] [:axis])
(let [axis (:axis options)
; Subtracting the max before exponentiating prevents overflow. See <NAME>, <NAME>, and <NAME>
; (2016), pg. 179.
max-corrected (G (->> (max-along operand {:axis axis :collapse false})
(- operand)
exp))]
(G (/ max-corrected
(sum-along max-corrected {:axis axis :collapse false}))))))
(defn cross-entropy
"Computes `-esum(actual * log (predicted + eps))`, where `esum` is the sum over all elements and `eps` is
a small value added for numerical stabilitiy."
[predicted actual]
(let [epsilon (m/array 1e-7)]
(G (-> (+ predicted epsilon)
log
(* actual)
esum
negate))))
(defn binary-cross-entropy
"Computes binary cross entropy:
`-esum(actual * log (predicted + eps) + (1 - actual) * log (1 - predicted + eps)`, where `esum` is the sum
over all elements and `eps` is a small value added for numerical stabilitiy.`"
[predicted actual]
(G (+ (cross-entropy predicted actual)
(cross-entropy (- 1 predicted) (- 1 actual)))))
(defn recurrent
"Simple recurrent layer. `operand` must be a tensor of shape `[example-count example-size timepoint-count]`.
Required options are:
- `:hidden-units` - size of hidden state
- `:output-units` - output dimensionality
Additional options are:
- `:initializer` - weight/bias initializer for the internal `dense` layer
- `:W-initializer` - weight initializer for the internal `dnese` layer
- `:b-initializer` - bias initializer for the internal `dense` layer
- `:state-initializer` - initializer for the hidden state matrix
- `:regularizer` - regularizer for output and recurrent dense layer (fallback if `:output-regularizer`
or `:recurrent-regularizer` isn't provided)
- `:output-regularizer` - regularizer for the output `dense` layer
- `:recurrent-regularizer` - regularizer for the recurrent `dense` layer
- `recurrent-activation` - activation function for the recurrent connection
- `:stateful` (default `false`) - boolean indicating if state should be maintained between iterations
- `:mask` - boolean matrix of shape `[example-count timepoint-count]`. If provided, then state and output
for a given example is updated at all timepoints where the `:mask` is true (1.0). Where the `:mask` is
false (0.0), the previous state and output value are maintained.
The output is of shape `[example-count output-units timepoint-count]`."
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer :regularizer
:output-regularizer :recurrent-activation :recurrent-regularizer :stateful
:mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :recurrent)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
layer-name (gen-layer-name :recurrent)
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
updated-state (G (-> (join-along 1 state timepoint-input)
(dense (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options)
:regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* mask-input updated-state)
(* (- 1 mask-input) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
(defn gru
"Gated recurrent unit layer. Input, output, and options are the same as for a `recurrent` layer, with
the following additional options:
- `:relevance-gate-initializer`
- `:relevance-gate-regularizer`
- `:update-gate-initializer`
- `:update-gate-regularizer`"
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer
:recurrent-activation :relevance-gate-initializer :update-gate-initializer
:regularizer :relevance-gate-regularizer :update-gate-regularizer
:recurrent-regularizer :output-regularizer :stateful :mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
layer-name (gen-layer-name :gru)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :gru)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
dense-options (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options))
relevance-gate-regularizer (or (:regularizer options) (:relevance-gate-regularizer options))
update-gate-regularizer (or (:regularizer options) (:update-gate-regularizer options))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
state-input (G (join-along 1 state timepoint-input))
relevance-gate (G (-> state-input
(dense (assoc dense-options :regularizer relevance-gate-regularizer))
logistic))
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
; num-examples x num-hidden-units
update-gate (G (-> state-input
(dense (assoc dense-options :regularizer update-gate-regularizer))
logistic
(* mask-input)))
candidate-next-state (G (-> (join-along 1 (* relevance-gate state) timepoint-input)
(dense (assoc dense-options :regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* update-gate candidate-next-state)
(* (- 1 update-gate) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NN-specific reporters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-multiclass-accuracy-reporter
"Returns a reporter function for the accuracy of predictions for a multi-class classification problem.
The returned function receives arguments [predicted actual], where `predicted` is a tensor containing
probabilities for each class along one axis and samples along all other axes. `actual` is a binary tensor
of the same structure containing the true class memberships represented in one-hot form. `options` can
include:
- `:class-axis`: the index of the axis spanning classes"
([]
(make-multiclass-accuracy-reporter {:class-axis 1}))
([options]
(u/check-key-validity options [:class-axis] [])
(let [class-axis (:class-axis options)]
(fn [predicted actual]
#_(println "predicted:" (first (m/slices predicted)))
#_(println "actual: " (first (m/slices actual)))
(-> predicted
(r/tensure-max-mask class-axis)
(m/mul actual)
m/esum
m/scalar->number
(/ (apply * (assoc (m/shape predicted) class-axis 1)))
(* 100)
(r/make-datapoint "Accuracy" :percent))))))
; TODO: Test this (this has not been tested at all)
(defn make-binary-classifier-reporter
"Returns a reporter function for the accuracy of predictions for a binary classification problem. The
returned function receives arguments [predicted actual], where `predicted` is a tensor where each element
is a probability of that sample belonging to one class, and `actual` is a binary tensor of the same shape
representing the true class memberships."
[]
(fn [predicted actual]
(-> (m/ge predicted (m/array 0.5))
(m/eq actual)
m/esum
m/->int
(/ (m/ecount actual))
(* 100.0)
(r/make-datapoint "Accuracy" :percent))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Model
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def reserved-node-names #{:training :predicting :testing})
(defn make-model
"Cosntructs a model, given:
- `:data` (required) - A map of maps (dataset-name -> variable-name -> data). The common case is to have
multiple datasets for different uses (e.g. `:training`, `:dev`, and `:test`), each with the same
variables (e.g. `:x` and `:y`).
- `:graph` (required) - A computation graph for the model.
- `:optimizer` (optional, defaults to gradient-descent-optimizer)
- `:optimizer-options` (optional) - Map of options to pass to `:optimizer`
- `:constants` (optional) - A map of name to value for graph inputs that do not change (i.e. that are
constant cross datasets).
- `:parameters` (optional) - A map of name to value for graph parameters. This can be excluded if all
parameters have initialization functions specified."
[& {:as options}]
(u/check-key-validity options [:graph :data] [:constants :parameters :optimizer :optimizer-options
; This is a private piece of data used to keep track of
; prior optimization results.
::prev-optimizer-results])
(let [{:keys [graph constants parameters optimizer optimizer-options data]
:or {constants {}
parameters {}
optimizer r/gradient-descent-optimizer
optimizer-options {}}} options
all-input-keys (into #{} (mapcat keys (vals data)))
;; data (u/update-vals data (fn [dataset]
;; (u/update-vals dataset #(if (m/array? %) % (m/array %)))))
]
(when-let [invalid-input-names (seq (set/intersection reserved-node-names all-input-keys))]
(u/throw-str "Invalid input names: '" invalid-input-names "'. These names are reserved."))
(when-let [invalid-constant-names (seq (set/intersection reserved-node-names
(into #{} (keys constants))))]
(u/throw-str "Invalid constant names: '" invalid-constant-names "'. These names are reserved."))
{:graph graph
:constants constants
:parameters parameters
:optimizer optimizer
:optimizer-options optimizer-options
:data data
::prev-optimizer-results (get options ::prev-optimizer-results {})}))
(defn update-model
[model & {:as updates}]
(apply make-model (apply concat (merge model updates))))
(defn update-prev-optimizer-results
[model dataset-or-name optimizer-result]
(assoc-in model [::prev-optimizer-results dataset-or-name] optimizer-result))
(defn get-previous-optimizer-result
[model dataset-or-name]
(get-in model [::prev-optimizer-results dataset-or-name]))
(defn get-model-constants
[model]
(:constants model))
(defn get-model-parameters
[model]
(:parameters model))
(defn get-model-optimizer
[model]
(:optimizer model))
(defn get-model-optimizer-options
[model]
(:optimizer-options model))
(defn get-model-graph
"Returns `model`'s computation graph."
[model]
(:graph model))
(defn get-model-dataset
"If `dataset-or-name` is a map (assumed to contain variable-name -> value), just returns the map;
otherwise looks up the dataset by the provided name in the model's associated data and returns the
corresponding map of variable-name -> value."
[model dataset-or-name]
(if (map? dataset-or-name)
dataset-or-name
(let [data (:data model)
dataset (get data dataset-or-name)]
(when-not dataset
(u/throw-str "Could not locate dataset '" dataset-or-name "'. Model only has datasets: '"
(keep (fn [[k v]] (when v k)) data) "'."))
dataset)))
(defn get-model-data
"Returns data for a given dataset and variable name. For example, `(get-model-data :training :x)`. Throws
exceptions if the model doesn't have a dataset or variable of the given name."
[model dataset-name varname]
(let [dataset (get-model-dataset model dataset-name)
var-data (get dataset varname)]
(when-not var-data
(u/throw-str "Could not locate data for variable '" varname "' in dataset '" dataset-name
"'. Dataset only has variables: '" (keep (fn [[k v]] (when v k)) dataset) "'."))
var-data))
(defn get-model-input-map
"Returns all a map of all model graph inputs (constants and vars from `dataset-or-name`)."
[model dataset-or-name]
(merge (get-model-dataset model dataset-or-name)
(get-model-constants model)))
(defn- get-all-model-parameter-nodes
"Returns a seq of all distinct input nodes in `model`'s graph that are parameters (either have `:parameter`
in their data set to `true` or are in the model`s `:parameters` map."
[model]
(let [specified-params (into #{} (keys (get-model-parameters model)))]
(->> (get-model-graph model)
r/get-all-graph-inputs
distinct
(filter #(or (-> % r/get-node-data :parameter)
(specified-params (r/get-node-name %)))))))
(defn- get-all-model-parameter-names
"Like `get-all-model-parameter-nodes` but returns a seq of names instead of a seq of nodes."
[model]
(map r/get-node-name (get-all-model-parameter-nodes model)))
(defn- get-all-model-parameter-values
"Returns a map of parameter name->value for all parameters of the given graph and dataset. Will include
`nil` values for parameters that have not been initialized."
[model]
(let [graph (get-model-graph model)
parameters (get-model-parameters model)
uninitialized-parameter-names (set/difference (into #{} (get-all-model-parameter-names model))
(into #{} (keys parameters)))
uninitialized-parameter-map (->> (map (juxt identity (constantly nil)) uninitialized-parameter-names)
(into {}))]
(merge parameters
uninitialized-parameter-map)))
(defn- get-trainable-parameter-name-set
[model]
(->> (get-all-model-parameter-nodes model)
(keep #(when (:trainable (r/get-node-data %))
(r/get-node-name %)))
(into #{})))
;; TODO: Get rid of `:training`, `:testing`, `:predicting` flags and just allow the user to pass these in
;; (e.g. either directly in the dataset, or through some option that allows additional inputs to be provided).
(defn evaluate-model
"Returns the result of running `model` on `dataset-or-name`. For example,
`(evaluate-model model :training)` will return the model's output for the `:training` dataset. Options
include:
- `:training` - boolean indicating if the `:training` input should be set to `true`
- `:testing` - boolean indicating if the `:testing` input should be set to `true`
If neither `:training` nor `:testing` is specified, the `:predicting` flag is set to true."
([model dataset-or-name]
(evaluate-model model dataset-or-name {}))
([model dataset-or-name options]
(u/check-key-validity options [] [:training :testing])
(let [extra-inputs (cond (:training options) {:training 1 :predicting 0 :testing 0}
(:testing options) {:training 0 :predicting 0 :testing 1}
:else {:training 0 :predicting 1 :testing 0})
graph (get-model-graph model)]
(->> (merge (get-all-model-parameter-values model)
extra-inputs
(get-model-input-map model dataset-or-name))
(r/evaluate graph)))))
(defn- make-optimized-model
"Returns a new model derived from `model` but with all properties updated based on `optimizer-result`."
[model dataset-or-name optimizer-result]
(let [untrained-parameters (r/get-optimized-state optimizer-result)
trained-parameters (r/get-optimized-params optimizer-result)]
(-> (update-model model
:graph (r/get-optimized-graph optimizer-result)
:parameters (merge trained-parameters
untrained-parameters))
(update-prev-optimizer-results dataset-or-name (r/reset-optimizer-reporting optimizer-result)))))
(defn- optimize-model
[model dataset-or-name iterations async?]
(let [optimizer (get-model-optimizer model)
optimizer-options (as-> (get-model-optimizer-options model) optimizer-options
(if (and #_(= optimizer r/gradient-descent-optimizer)
(:batch-size optimizer-options)
(not (:batch-inputs optimizer-options)))
(let [default-batch-inputs (->> (get-model-dataset model dataset-or-name)
keys
(mapv #(vector % 0))
(into {}))]
(assoc optimizer-options :batch-inputs default-batch-inputs))
optimizer-options)
(assoc optimizer-options :iterations iterations))
optimize-fn (if async?
r/optimize-async
r/optimize)]
(if-let [prev-result (get-previous-optimizer-result model dataset-or-name)]
(optimize-fn optimizer prev-result optimizer-options)
(let [graph (get-model-graph model)
all-param-map (get-all-model-parameter-values model)
trainable-param-name-set (get-trainable-parameter-name-set model)
trainable-param-map (select-keys all-param-map trainable-param-name-set)
state-param-map (apply dissoc all-param-map trainable-param-name-set)
extra-inputs {:training 1
:predicting 0
:testing 0}
input-map (merge extra-inputs
(get-model-input-map model dataset-or-name))]
(optimize-fn optimizer graph input-map trainable-param-map state-param-map optimizer-options)))))
(defn train-model
"Fits `model` to data in `dataset-or-name` by running the model's optimizer for `iterations` iterations.
Defaults to running 1 iteration on the `:training` data. Blocks until complete."
([model]
(train-model model 1))
([model iterations]
(train-model model :training iterations))
([model dataset-or-name iterations]
(let [optimizer-result (optimize-model model dataset-or-name iterations false)]
(make-optimized-model model dataset-or-name optimizer-result))))
(defn train-model-async
"Fits `model` to data in `dataset-or-name` (default `:training`) by running the model's optimizer for
`iterations` (defaults to infinite). Launches optimization in a new thread and immediately returns a
0-arity function, `stop`, that when called will immediately return the trained model from the last complete
iteration and terminate the optimization process after the next iteration is complete."
([model]
(train-model-async model nil))
([model iterations-or-dataset-or-name]
(let [[iterations dataset-or-name] (if (or (nil? iterations-or-dataset-or-name)
(number? iterations-or-dataset-or-name))
[iterations-or-dataset-or-name :training]
[nil iterations-or-dataset-or-name])]
(train-model-async model dataset-or-name iterations)))
([model dataset-or-name iterations]
(let [stop-optimizing (optimize-model model dataset-or-name iterations true)]
(fn stop
[]
(let [optimizer-result (stop-optimizing)]
(make-optimized-model model dataset-or-name optimizer-result))))))
; TODO:
; Improvements
; - Remove `data` from model. It makes more sense to keep the model and data completely separate.
; - This will also simplify all the `dataset-or-name` arguments where the supplied data can be either a
; map of data or a dataset name.
; - Could add a separate set of functions for managing datasets (e.g. bundling together sets of training
; and test data as the model does now).
; - Consider adding a set of required input names to model so datasets can be validated to ensure they have
; the required inputs (probably not possible to validate that _all_ inputs exist due to `if` branches--
; some graphs might not require some inputs, depending on conditional branching).
; - Add validation to make sure regularization is applied (an easy mistake is to pass a regularizer
; as an option for some layer and then to not pass the cost node through regularization layer). We can
; check that if any nodes have regularization, there must be a `regularize` node and, if not, we can
; throw an Exception. It's difficult to automatically inclue the `regularize` node, because it's
; difficult to know where in the graph it should go if there are conditional branches.
; - Figure out better way to handle print logging -- right now it's necessary to manually flush output
; if the last logging statement doesn't have a newline (which triggers a flush). Somehow always flush the
; print logger after the last iteration.
; - Be able to lazily load batches into memory.
; - Allow simple-optimize-like options for the model's optimizer-options
; Additional features
; - Serialization - be able to save and load models from/to disk
; - Periodic backups - be able to persist model data during training periodically, so if training gets
; interrupted, not all progress is lost.
; - More layers
; - Mean squared error (e.g. used in book reviews example)
; Quality
; - Tests:
; - to ensure regularization is not applied more than once for each regularized node (this was a
; previous bug that has since been fixed, but tests were not added to catch it).
; - of one-hot encoding functions
; - of softmax layer
; - of cross-entropy layer
; - of complete reporting and logging framework
; - of the layer initialization framework
; - Figure out how to handle evaluation with stateful recurrent layers when batching. It is currently
; possible to have batches that need state of different sizes, but if state is maintained between
; iterations, this causes an excpetion. Remove state before evaluating?
; - Reset recurrent netowrk state between epochs?
; - Standardize names of arguments of the same type/meaning (e.g. sometimes "nd" is used for a tensor node,
; and other times "operand" is used).
; - Automatically add '' around non-strings in throw-str
| true | (ns neurojure.core
(:require [clojure.set :as set]
[neurojure.utils :as u :refer [def- -?> -?>>]]
[ranvier.core :as r :refer [G]]
[tensure.core :as m]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initializers
;;
;; Initializers are functions that take a single argument, a tensor shape, and return a tensor of that shape,
;; with elements set to values determined by the initializer. Except for `zeros` and `ones`, the initializers
;; are generated by factory functions that return initializers with properties based on the parameters they
;; receive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TODO: Test this
(defn- get-axis-size
"Given a vector representing a tensor `shape` and either a single `axis` index or vector of axis indices,
returns the product of the sizes of the specified axes."
[shape axis]
(let [axes (if (number? axis)
[axis]
axis)
rank (count shape)]
(reduce (fn [size i]
(when (>= i rank)
(u/throw-str "Invalid axis for a tensor of shape '" shape "'."))
(* size (nth shape i)))
1
axes)))
(defn zeros-initializer
"Returns a tensor of `shape` filled with 0's."
[shape]
(m/zeros shape))
(defn ones-initializer
"Returns a tensor of `shape` filled with 1's."
[shape]
(m/ones shape))
(defn make-fill-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with `constant`."
[constant]
(fn [shape]
(m/filled shape constant)))
(defn make-constant-initializer
"Returns a function that takes a shape and will return the tensor `constant` of that shape. Throws an
exception if the constant does not have the shape."
[constant]
(let [constant (if (m/array? constant)
constant
(m/array constant))
constant-shape (m/shape constant)]
(fn [shape]
(when (not= constant-shape shape)
(u/throw-str "Attempt to initialize a tensor of shape '" shape "' with a constant of shape '"
constant-shape "'."))
constant)))
(defn make-uniform-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values uniformly distributed in [min, max). `min` and `max` can be either numbers or functions that when
applied to the shape will return numbers."
([]
(make-uniform-random-initializer -0.01 0.01))
([min max]
(fn [shape]
(let [nd (m/sample-uniform shape)
min (m/array (if (fn? min) (min shape) min))
max (m/array (if (fn? max) (max shape) max))]
(m/add (m/mul (m/sub max min) nd) min)))))
(defn make-normal-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev`. `mean` and `stdev` can be either
numbers or functions that return the numbers when applied to the shape."
([]
(make-normal-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [nd (m/sample-normal shape)
stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))]
(m/add (m/mul stdev nd) mean)))))
(defn make-truncated-random-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around `mean` with standard deviation `stdev` but with no values >2 SD's from
the mean. `mean` and `stdev` can be either numbers or functions that return the numbers when applied to
the shape."
([]
(make-truncated-random-initializer 0 0.01))
([mean stdev]
(fn [shape]
(let [stdev (m/array (if (fn? stdev) (stdev shape) stdev))
mean (m/array (if (fn? mean) (mean shape) mean))
result-element-count (apply * shape)
get-element-seq (fn next [batch-size]
(lazy-cat (m/eseq (m/sample-normal [batch-size]))
(next (max 128 (* batch-size 0.05)))))
result (->> (get-element-seq result-element-count)
(filter #(and (> % -2) (< % 2)))
(take result-element-count)
m/array)]
(m/mul! result stdev)
(m/add! result mean)
(m/reshape result shape)))))
(defn make-variance-scaling-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with random
values normally distributed around 0. The standard deviation will be `sqrt(scale / axis-sum)` where
`axis-sum` is the sum of the sizes of all axes in `axis`. `axis` can be either a vector of axes or an
integer indicating a single axis. The distribution is truncted such that no values >2 SD's from 0 are
included."
([]
(make-variance-scaling-initializer 1))
([scale]
(make-variance-scaling-initializer scale 1))
([scale axis]
(let [axes (if (number? axis) [axis] axis)]
(fn [shape]
(for [axis axes]
(when (>= axis (count shape))
(u/throw-str "Cannot initialize tensor of shape " shape " with variance scaled on axis "
axis ", because axis is out of bounds.")))
((make-truncated-random-initializer
0
(Math/sqrt (/ scale (apply + (map #(nth shape %) axes)))))
shape)))))
(defn make-lecun-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(3 / m), sqrt(3 / m))`, where m is the size of the `input-axes`, either
a single axis index or vector of axis indices (defaults to 1)."
([]
(make-lecun-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 3 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-lecun-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(1 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated
at +/- 2 SD's."
([]
(make-lecun-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 1 (get-axis-size % input-axes))))))
(defn make-he-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / m), sqrt(6 / m))`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1)."
([]
(make-he-uniform-initializer 1))
([input-axes]
(let [bound-fn #(Math/sqrt (/ 6 (get-axis-size % input-axes)))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-he-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / m)`, where m is the size of the `input-axes`,
either a single axis index or vector of axis indices (defaults to 1). The distribution is truncated at
+/- 2 SD's."
([]
(make-he-normal-initializer 1))
([input-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (get-axis-size % input-axes))))))
(defn make-xavier-uniform-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
uniformly distributed in `[-sqrt(6 / (m + n)), sqrt(6 / (m + n)))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0)."
([]
(make-xavier-uniform-initializer 1 0))
([input-axes output-axes]
(let [bound-fn #(Math/sqrt (/ 6 (+ (get-axis-size % input-axes) (get-axis-size % output-axes))))]
(make-uniform-random-initializer
#(- (bound-fn %))
bound-fn))))
(defn make-xavier-normal-initializer
"Returns a function that when applied to a shape will return a tensor of that shape filled with values
drawn from a truncated normal distribution with SD `sqrt(2 / (m + n))`, where m and n are the sizes of the
`input-axes` and `output-axes`, respectively (defaults to 1 and 0). The distribution is truncated
at +/- 2 SD's."
([]
(make-xavier-normal-initializer 1 0))
([input-axes output-axes]
(make-truncated-random-initializer
0
#(Math/sqrt (/ 2 (+ (get-axis-size % input-axes) (get-axis-size % output-axes)))))))
; TODO: Test this.
(defn- get-layer-initializer
"Returns an initializer (function that takes a shape and returns an initialized tensor of that shape),
given:
- `initializer-selector` - an initializer function or keyword
- `input-axes` - the axes of the tensor being initialized that span 'input values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `output-axes` - the axes of the tensor being initialized that span 'output values' (either a single
axis index or vector of axis indices or `nil` if this does not apply)
- `layer-type` - keyword or string identifying the layer (used to provide more descriptive error
message)
If `initializer-selector` is a function, it's just returned. If it's a keyword, then the corresponding
factory function is looked up and used to construct a new initializer. The product of the sizes of the
`input-axes` should correspond to the 'fan in' of the layer (the number of input values that contribute to
any single value in the output), while the product of the sizes of the `output-axes` should correspond to
the 'fan out' of the layer (the number of output values that contribute to any single input value to the
next layer). If the notion of 'fan in' or 'fan out' does not apply to a layer or cannot be calculated
from the parameter shape, then `input-axes` or `output-axes` can be set to `nil`. Selecting an initializer
that does not apply to a layer will cause an Exception."
[initializer-selector input-axes output-axes layer-type]
(if (fn? initializer-selector)
initializer-selector
(let [throw-invalid-initializer #(u/throw-str "Invalid initializer for '" layer-type "' layer: '"
initializer-selector "'.")]
(when (and (nil? input-axes) (#{:lecun-uniform :luecn-normal :he-uniform :he-normal
:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(when (and (nil? output-axes) (#{:xavier-uniform :savier-normal} initializer-selector))
(throw-invalid-initializer))
(case initializer-selector
:zeros zeros-initializer
:ones ones-initializer
:uniform (make-uniform-random-initializer)
:normal (make-normal-random-initializer)
:truncated (make-truncated-random-initializer)
:variance-scaling (make-variance-scaling-initializer)
:lecun-uniform (make-lecun-uniform-initializer input-axes)
:lecun-normal (make-lecun-normal-initializer input-axes)
:he-uniform (make-he-uniform-initializer input-axes)
:he-normal (make-he-normal-initializer input-axes)
:xavier-uniform (make-xavier-uniform-initializer input-axes output-axes)
:xavier-normal (make-xavier-normal-initializer input-axes output-axes)
(throw-invalid-initializer)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layer helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map of layer type (a string) to the number of times `gen-layer-name` has been called with that string
; as the `layer-type` argument.
(def- layer-type-counters (atom {}))
(defn- gen-layer-name
"Given `layer-type` (a keyword or string), returns a new unique keyword identifier for a layer of that type.
E.g. `(gen-layer-name :dense)` will return 'dense0', `:dense1', ':dense2', etc. on each call."
[layer-type]
(let [type-str (name layer-type)]
(if (contains? @layer-type-counters type-str)
(swap! layer-type-counters update type-str inc)
(swap! layer-type-counters assoc type-str 0))
(keyword (str type-str (get @layer-type-counters type-str)))))
(defn- gen-param-name
"Given a `layer-name` and a `param-name` (both either keywords or strings), returns a unique keyword
identifier for the parameter. E.g. `(gen-param-name 'dense0' :W)` returns 'dense0_W'."
[layer-name param-name]
(if layer-name
(keyword (str (name layer-name) "_" (name param-name)))
param-name))
(defn- tag-layer-nodes-recursive
[g input-set layer-name]
(let [operands (r/get-node-operands g)]
(if (input-set g)
g
(->> (mapv #(tag-layer-nodes-recursive % input-set layer-name) operands)
(r/update-node g
:data (update (r/get-node-data g) :layers #(conj (or % []) layer-name))
:operands)))))
(defn- tag-layer-nodes
"Traverses computation graph `g`, conj'ing `layer-name` into the :layers vector in the node's :data but
ommitting all nodes in `input-nodes` (seq of nodes or any object that can be constructed into a node) and
all their descendents."
[g input-nodes layer-name]
(let [input-set (->> (map r/construct-operand input-nodes)
(into #{}))
node-data (r/get-node-data g)]
(r/update-node (tag-layer-nodes-recursive g input-set layer-name)
:data (assoc node-data
:layers (conj (get node-data :layers []) layer-name)
:entry-to-layer layer-name))))
(defn- create-layer
[layer-name input-nodes g]
(tag-layer-nodes g input-nodes layer-name))
(defn- make-input-node
"Returns an input node for a layer, given:
- `input-name` - the keyword name of the input
- `layer-name` - the keyword name of the layer
- `initializer` - an initializer function, which must receive a map of node names to values at the time
of initialization and return the initialized value of the node
- `data` - an arbitrary map of additional data
The values for layer inputs must be either 1) provided (e.g. passed in from a model's data), or 2)
generated by the initialization function. For non-parameter/state inputs whose values are not provided,
the node will be re-initialized with every iteration. For inputs that should be optimized, use
`make-parameter-node`, and for inputs whose values should persist from iteration to iteration, use
`make-state-node`."
([input-name layer-name]
(make-input-node input-name layer-name nil))
([input-name layer-name initializer]
(make-input-node input-name layer-name initializer {}))
([input-name layer-name initializer data]
(r/input (gen-param-name layer-name input-name) initializer (assoc data
:parameter false
:trainable false))))
(defn- make-parameter-node
"Like `make-input-node`, but returns a node for a parameter input. Parameters are passed in the `param-map`
to the optimizer--their values can be changed by the optimizer with every iteration."
([param-name layer-name]
(make-parameter-node param-name layer-name nil))
([param-name layer-name initializer]
(make-parameter-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable true))))
(defn- make-state-node
"Like `make-input-node`, but returns an input node for a 'state' input--i.e. a value that can change
during an iteration and whose values are persisted between iterations."
([param-name layer-name]
(make-state-node param-name layer-name nil))
([param-name layer-name initializer]
(make-state-node param-name layer-name initializer {}))
([param-name layer-name initializer data]
(r/input (gen-param-name layer-name param-name) initializer (assoc data
:parameter true
:trainable false))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regularizers
;;
;; Regulariers are functions that receive two arguments:
;; - a computation graph node that is assumed to be cost (though in practice it can be any node)
;; - a parameter node for which to apply regularization
;; They must return a new computation graph node with regularization for the given parameter applied. They
;; are generally constructed using a make-* function that returns a regularizer with properties specified
;; by the arguments to the make-* function.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-l2-regularizer
"Returns an L2 regularizer:
`cost + regularization-weight / 2m * (sum of squares of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l2-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l2-regularizer)
[g num-examples parameter-node :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (pow parameter-node 2)))
#_(report (make-value-reporter "reg: ") (make-print-logger)))))
:regularizer-for (r/get-node-name parameter-node))))))
(defn make-l1-regularizer
"Returns an L1 regularizer:
`cost + regularization-weight / 2m * (sum of absolute value of all elements in parameter tensor)`
where `m` is the number of training examples included in the cost calculation."
([num-examples]
(make-l1-regularizer num-examples 0.001))
([num-examples regularization-weight]
(fn [g parameter-node]
(create-layer
(gen-layer-name :l1-regularizer)
[g parameter-node num-examples :predicting]
(r/assoc-node-data
(G (tensor-if :predicting
g
(+ g (* (/ regularization-weight (* 2 num-examples))
(esum (abs parameter-node))))))
:regularizer-for (r/get-node-name parameter-node))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Layers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Layers
;;
(defn regularize
[g]
(->> (r/get-all-graph-nodes g)
distinct
(reduce (fn [regularized-graph node]
(if-let [regularizer (->> node r/get-node-data :regularizer)]
(regularizer regularized-graph node)
regularized-graph))
g)))
(defn sigmoid-cross-entropy
"Computes the sum over all elements of the result of
`max(predicted, 0) - predicted * actual + log (1 + e^-abs(predicted))`. This is roughly equivalent to the
total logistic loss `actual * -log(sigmoid(predicted)) + (1 - actual) * -log(1 - sigmoid(predicted))`, but
with some modifications for numerical stability. Based on the TensorFlow implementation
(https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits)."
[predicted actual]
(G (esum
(+ (max predicted 0)
(* (- predicted) actual)
(log (+ 1 (exp (- (abs predicted)))))))))
; TODO: Add axis option.
(defn dropout
"Masks a fraction of elements in `g` and scales up remaining elements to maintain a constant sum:
- `:frequency` (required) - frequency of elements to drop out (on average)
- `:exact` (default true) - boolean indicating whether scaling of other options in `g` must be exact
(i.e. proportional to the number of elements actually dropped out, which may vary randomly from run to
run) or approximate (proportional to `:frequency`). The results for `:exact == true` and
`:exact == false` converge when the size of `g` is large, but the `:exact` computation is more
expensive."
[g options]
(u/check-key-validity options [:frequency] [:exact])
(let [frequency (:frequency options)
exact (if (contains? options :exact)
(:exact options)
true)
keep-vec (G (>= (random-uniform (shape g))
frequency))
scaling-factor (if exact
(G (/ (size g)
(esum keep-vec)))
(/ 1 (- 1 frequency)))]
(create-layer
(gen-layer-name :dropout)
[g :training]
(G (tensor-if :training
(* keep-vec g scaling-factor)
g)))))
(defn mean
"Calculates the arithmetic mean of `g` along some axes/axes. `options` can include:
- `:axis` (optional) - a scalar or vector indicating the axes across which the mean should be taken; if
ommitted, the mean of all elements in `g` will be returned.
- `:collapse` (optional) - boolean indicating if the dimensions specified in `:axis` should be removed.
If false, dimensions will be maintained with a size of 1."
([g]
(mean g {}))
([g options]
(u/check-key-validity options [] [:axis :collapse])
(let [{:keys [axis collapse]} options]
(create-layer
(gen-layer-name :mean)
[g]
(G (/ (sum-along g {:axis axis
:collapse (clojure.core/or collapse false)})
(size g {:axis axis})))))))
(defn normalize
"Calculates baseline-corrected-g / variance, where baseline-correcred-g is g - mean(g), and variance is
sum(base-line-corrected-g^2) / size(baseline-corrected-g). Options can include `:axis`, a single axis or
a vector of axes over which to perform the `sum`, `size`, and `mean` operations. If `:axis` is not
provided, normalization will be done over the entire tensor `g`. The returned result is the same shape as
`g`."
([g]
(normalize g {}))
([g options]
(u/check-key-validity options [] [:axis])
(let [axis (get options :axis 0)
opts {:axis axis
:collapse false}
mean (mean g opts)
baseline-corrected (G (- g mean))
variance (G (/ (sum-along (pow baseline-corrected 2) opts)
(size baseline-corrected {:axis axis})))]
(create-layer
(gen-layer-name :normalize)
[g]
(G (/ baseline-corrected
variance))))))
(defn relu
"Computes `min(g, 0)`."
[g]
(create-layer
(gen-layer-name :relu)
[g]
(G (max g 0))))
(defn logistic
"Computes `1 / (1 + e^-g)`."
[g]
(G (/ 1 (+ 1 (exp (- g))))))
(defn logistic-binary-classifier
"Returns a boolean tensor representing `1 / (1 + e^-`g`) >= 0.5`."
[g]
(G (>= (logistic g) 0.5)))
(defn dense
"Given an `operand` matrix of shape [m input-size], computes `operand . W + b`, where `.` is matrix
multiplication, W is a parameter matrix of shape [input-size units], and b is a parameter matrix of shape
[1 units]. Options include:
- `:units` (required) - scalar number of 'units' to include in the layer
- `:initializer` (optional, default xavier normal) - single initializer for both W and b
- `:W-intializer` (optional) - initializer for W, used instead of that specified in `:initializer` if
both are provided (default xavier normal)
- `:b-initializer` (optional) - like `:W-initializer` but for b (default zeros)
- `:regularizer` (optional) - default `nil`"
[operand options]
(u/check-key-validity options [:units] [:initializer :W-initializer :b-initializer :regularizer])
(let [{:keys [units regularizer initializer W-initializer b-initializer]} options
W-initializer (get-layer-initializer (or W-initializer initializer :xavier-normal) 0 1 :dense)
b-initializer (get-layer-initializer (or b-initializer initializer :zeros) 0 1 :dense)
input-node (r/construct-operand operand)
layer-name (gen-layer-name :dense)
input-dimension (when (r/is-const? input-node)
(m/column-count (r/get-node-value input-node)))
input-name (r/get-node-name input-node)
W-initializer-fn (fn [input-map]
(W-initializer [(or input-dimension
(m/column-count (get input-map input-name)))
units]))
b-initializer-fn (fn [input-map]
(b-initializer [1 units]))
W (make-parameter-node :W layer-name W-initializer-fn {:regularizer regularizer})
b (make-parameter-node :b layer-name b-initializer-fn)]
(create-layer
layer-name
[input-node]
(G (+ (mmul input-node W) b)))))
(r/defop- pool2d
"Given tensor `nd` of shape [m, height, width, channels], vector `pool-size` of shape
[pool-rows, pool-columns], and vector `strides` of shape [vstride, hstride], returns a tensor of shape
[m, floor((height - pool-rows) / vstride) + 1, floor((width - pool-cols) / hstride) + 1,
pool-rows * pool-columns * channels]. In the returned tensor, the vector [k, i, j, :all] (i.e. the elements
along the last dimension at a given point), consists of the elements of `nd` in selection
[i * vstride...(i * vstride + pool-rows - 1), j * hstride...(j * hstride + pool-cols - 1), :all-channels]
linearized in order row, col, channel. That is, channel changes fastest, and row changes slowest."
[^:nd nd pool-size strides]
:v (let [[kh kw] pool-size
[m height width chs] (m/shape nd)
[vstride hstride] strides
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))]
(when (or (zero? unstrided-result-height)
(zero? unstrided-result-width))
(u/throw-str "Cannot perform 2d convolution of a tensor of shape '" (m/shape nd) "' with a kernel of "
"shape '" pool-size "'. The kernel width and height cannot exceed the width and "
"height of an input tensor."))
(->> (for [i (range kh)
j (range kw)]
(m/select-range nd
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all))
(apply m/join-along 3)))
:dnd (let [[kh kw] pool-size
nd-shape (m/shape nd)
[_ height width chs] nd-shape
unstrided-result-height (inc (- height kh))
unstrided-result-width (inc (- width kw))
[vstride hstride] strides
result (m/zeros nd-shape)]
(doseq [i (range kh)
j (range kw)
:let [k (* chs (+ (* i kw) j))]]
(m/add! (m/select-range result
:all
[i (+ unstrided-result-height i) vstride]
[j (+ unstrided-result-width j) hstride]
:all)
(m/select-range dv :all :all :all [k (+ k chs)])))
result))
; TODO: Research other possible implementations of this to see if this can be made faster. (e.g. doing
; it in frequency space).
(defn conv2d
"Given tensor `nd` of shape [m, height, width, channels], a `kernel` of shape
[output-chs, kernel-height, kernel-width, input-chs], and a vector of strides like `[row-stride,
column-stride]`, returns a tensor of shape [m, floor((height - kernel-height + 1) / row-stride),
floor(width - kernel-width + 1) / column-stride), output-chs] that is the product of convolving each
of m examples with the kernel."
[nd kernel strides]
(let [[kout_chs kh kw] (mapv #(G (size kernel {:axis %})) (range 3))
pooled-nd (G (pool2d nd (make-shape kh kw) strides))
[m height width linear-kernel-size] (mapv #(G (size pooled-nd {:axis %})) (range 4))
reshaped-kernel (G (transpose (reshape kernel (make-shape kout_chs linear-kernel-size))))]
; We reshape `pooled-nd` into a matrix, before calculating the product with `reshaped-kernel`, because
; backpropagation of `mmul` is much faster for matrices than for tensors.
(G (-> (reshape pooled-nd (make-shape (* m height width) linear-kernel-size))
(mmul reshaped-kernel)
(reshape (make-shape m height width kout_chs))))))
(defn- get-2d-padding
"Given a padding option accepted by a 2d pooling or convolutional layer, returns a full padding vector for
a 4d tensor accepted by that layer. Throws an exception if `padding-option` is not valid. See `conv2d` and
`max-pooling2d`."
[padding-option window-size]
(let [padding-dimensionality (u/vector-dimensionality padding-option)]
(cond (nil? padding-option) nil
(= :same padding-option) (let [[padding-h padding-w] (mapv #(/ (dec %) 2) window-size)]
[[0 0]
[(int (Math/ceil padding-h)) (int (Math/floor padding-h))]
[(int (Math/ceil padding-w)) (int (Math/floor padding-w))]
[0 0]])
(number? padding-option) [0 padding-option padding-option 0]
(= padding-dimensionality 1) [0 (first padding-option) (second padding-option) 0]
(= padding-dimensionality 2) [[0 0] (first padding-option) (second padding-option) [0 0]]
:else (u/throw-str "Invalid 2d padding: '" padding-option "'. Padding must be a valid argument to "
"`pad-with` for a matrix."))))
(defn max-pooling2d
"Returns a new tensor containing the maximum elements of `nd` in a window sliding along two dimensions.
`nd` must a tensor of shape [m, height, width, channels]. Options include:
- `:pool-size` (required) - [height, width] of the sliding window
- `:strides` (optional, defaults to `:pool-size`) - the [vertical, horizontal] step sizes to use when
sliding the window.
- `:padding` (optional) - an argument accepted by `pad-with`.
The returned tensor is of shape [m, floor((height + vertical-padding - pool-height + 1) / vertical-stride),
floor((width + horizontal-padding - pool-width + 1) / horizontal-stride), channels]. For a given slice
through the first dimension (typically a training example) and channel, each (i, j) in the result is the
maximum element in ((k * vertical-stride)...(k * vertical-stride + pool-height),
(l * horizontal-stride)...(l * horizontal-stride + pool-width)) from `nd`."
[nd options]
(u/check-key-validity options [:pool-size] [:strides :padding])
(let [{:keys [pool-size strides padding]} options
_ (when-not (and (= 2 (count pool-size)))
(u/throw-str "Invalid pool size provided to `max-pooling2d`: '" pool-size "'. Pool size must be "
"a two-element vector."))
padding (get-2d-padding padding pool-size)
padded-input (if padding
(G (pad nd padding))
nd)
strides (or strides pool-size)
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `max-pooling2d`: '" strides "' . Strides must be a "
"2-element seq."))
pool-element-count (apply * pool-size)
pooled (pool2d padded-input pool-size strides)
pooled-height (G (size pooled {:axis 1}))
pooled-width (G (size pooled {:axis 2}))
m (G (size nd {:axis 0}))
chs (G (size nd {:axis 3}))]
(G (-> pooled
(reshape (make-shape m pooled-height pooled-width pool-element-count chs))
(max-along {:axis 3 :collapse true})))))
; Padding can be :same, a vector of paddings for each dimension, or a scalar
(defn conv2d-layer
"Returns the 2d convolution of `operand` with kernels of specified properties. `options` include:
- `:kernel-size` (required) - A two-element vector specifying the kernel [height width].
- `:output-channels` (required) - Number of output channels (equal to the number of kernels that will be
convolved with `operand`).
- `:strides` (optional, default [1 1]) - The [vertical horizontal] step sizes to use when sliding the
kernel over `operand`.
- `:initializer` (optional, default xavier normal) - used for both the kernel and the bias if
initializers specific to those parameters are not given
- `:kernel-iniitializer` (optional)
- `:bias-initializer` (optional)
- `:padding` (optional) - an argument accepted by `pad-with`. `operand` is padded with zeros before
convolution.
See `conv2d` for the structures of the input and output tensors."
[operand options]
(u/check-key-validity options [:kernel-size :output-channels] [:strides :padding :regularizer :initializer
:kernel-initializer :bias-initializer])
(let [{:keys [kernel-size output-channels strides initializer padding regularizer
kernel-initializer bias-initializer]} options
_ (when-not (and (= 2 (count kernel-size)))
(u/throw-str "Invalid kernel provided to conv2d layer: '" kernel-size "'. Kernel size must be "
"a two-element vector."))
padding (get-2d-padding padding kernel-size)
kernel-initializer (get-layer-initializer (or kernel-initializer initializer :lecun-normal)
[1 2 3] nil :conv2d)
bias-initializer (get-layer-initializer (or bias-initializer initializer :zeros) nil nil :conv2d)
strides (or strides [1 1])
_ (when-not (= (count strides) 2)
(u/throw-str "Invalid :strides provided to `conv2d`: '" strides "' . Strides must be a 2-element "
"seq."))
input-node (r/construct-operand operand)
input-name (r/get-node-name input-node)
kernel-initializer-fn (fn [input-map]
(let [input-channels (m/dimension-count (get input-map input-name) 3)]
(kernel-initializer (concat [output-channels]
kernel-size
[input-channels]))))
bias-initializer-fn (fn [_] (bias-initializer [1 1 1 output-channels]))
layer-name (gen-layer-name :conv2d)
kernel (make-parameter-node :kernel layer-name kernel-initializer-fn {:regularizer regularizer})
bias (make-parameter-node :bias layer-name bias-initializer-fn)
padded-input (if padding
(G (pad input-node padding))
input-node)]
(create-layer
layer-name
[input-node]
(G (+ (conv2d padded-input kernel strides) bias)))))
(defn softmax
([operand]
(softmax operand {}))
([operand options]
(u/check-key-validity options [] [:axis])
(let [axis (:axis options)
; Subtracting the max before exponentiating prevents overflow. See PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI
; (2016), pg. 179.
max-corrected (G (->> (max-along operand {:axis axis :collapse false})
(- operand)
exp))]
(G (/ max-corrected
(sum-along max-corrected {:axis axis :collapse false}))))))
(defn cross-entropy
"Computes `-esum(actual * log (predicted + eps))`, where `esum` is the sum over all elements and `eps` is
a small value added for numerical stabilitiy."
[predicted actual]
(let [epsilon (m/array 1e-7)]
(G (-> (+ predicted epsilon)
log
(* actual)
esum
negate))))
(defn binary-cross-entropy
"Computes binary cross entropy:
`-esum(actual * log (predicted + eps) + (1 - actual) * log (1 - predicted + eps)`, where `esum` is the sum
over all elements and `eps` is a small value added for numerical stabilitiy.`"
[predicted actual]
(G (+ (cross-entropy predicted actual)
(cross-entropy (- 1 predicted) (- 1 actual)))))
(defn recurrent
"Simple recurrent layer. `operand` must be a tensor of shape `[example-count example-size timepoint-count]`.
Required options are:
- `:hidden-units` - size of hidden state
- `:output-units` - output dimensionality
Additional options are:
- `:initializer` - weight/bias initializer for the internal `dense` layer
- `:W-initializer` - weight initializer for the internal `dnese` layer
- `:b-initializer` - bias initializer for the internal `dense` layer
- `:state-initializer` - initializer for the hidden state matrix
- `:regularizer` - regularizer for output and recurrent dense layer (fallback if `:output-regularizer`
or `:recurrent-regularizer` isn't provided)
- `:output-regularizer` - regularizer for the output `dense` layer
- `:recurrent-regularizer` - regularizer for the recurrent `dense` layer
- `recurrent-activation` - activation function for the recurrent connection
- `:stateful` (default `false`) - boolean indicating if state should be maintained between iterations
- `:mask` - boolean matrix of shape `[example-count timepoint-count]`. If provided, then state and output
for a given example is updated at all timepoints where the `:mask` is true (1.0). Where the `:mask` is
false (0.0), the previous state and output value are maintained.
The output is of shape `[example-count output-units timepoint-count]`."
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer :regularizer
:output-regularizer :recurrent-activation :recurrent-regularizer :stateful
:mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :recurrent)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
layer-name (gen-layer-name :recurrent)
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
updated-state (G (-> (join-along 1 state timepoint-input)
(dense (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options)
:regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* mask-input updated-state)
(* (- 1 mask-input) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
(defn gru
"Gated recurrent unit layer. Input, output, and options are the same as for a `recurrent` layer, with
the following additional options:
- `:relevance-gate-initializer`
- `:relevance-gate-regularizer`
- `:update-gate-initializer`
- `:update-gate-regularizer`"
[operand options]
(u/check-key-validity options [:hidden-units :output-units]
[:initializer :W-initializer :b-initializer :state-initializer
:recurrent-activation :relevance-gate-initializer :update-gate-initializer
:regularizer :relevance-gate-regularizer :update-gate-regularizer
:recurrent-regularizer :output-regularizer :stateful :mask])
(let [input-node (r/construct-operand operand)
input-node-name (r/get-node-name input-node)
num-units (:hidden-units options)
layer-name (gen-layer-name :gru)
recurrent-activation (or (:recurrent-activation options) identity)
state-initializer (get-layer-initializer (or (:state-initializer options) :zeros) nil 0 :gru)
state-initializer-fn (fn [input-map]
(let [num-examples (first (m/shape (get input-map input-node-name)))]
(state-initializer [num-examples num-units])))
state (if (:stateful options)
(make-state-node :state layer-name state-initializer-fn)
(make-input-node :state layer-name state-initializer-fn))
dense-options (assoc (select-keys options [:initializer :W-initializer :b-initializer])
:units (:hidden-units options))
relevance-gate-regularizer (or (:regularizer options) (:relevance-gate-regularizer options))
update-gate-regularizer (or (:regularizer options) (:update-gate-regularizer options))
recurrent-regularizer (or (:regularizer options) (:recurrent-regularizer options))
output-regularizer (or (:regularizer options) (:output-regularizer options))
timepoint-input (make-input-node :timepoint-input layer-name)
state-input (G (join-along 1 state timepoint-input))
relevance-gate (G (-> state-input
(dense (assoc dense-options :regularizer relevance-gate-regularizer))
logistic))
mask (when-let [mask (:mask options)]
(r/construct-operand mask))
mask-input (make-input-node :mask layer-name)
; num-examples x num-hidden-units
update-gate (G (-> state-input
(dense (assoc dense-options :regularizer update-gate-regularizer))
logistic
(* mask-input)))
candidate-next-state (G (-> (join-along 1 (* relevance-gate state) timepoint-input)
(dense (assoc dense-options :regularizer recurrent-regularizer))
recurrent-activation))
next-state (G (+ (* update-gate candidate-next-state)
(* (- 1 update-gate) state)))]
(create-layer
layer-name
(keep identity [input-node mask])
(G (fork [timepoint-input (slices input-node 2)
mask-input (if mask
(partition-along (r/construct-operand mask) 1)
(-> input-node (size {:axis 2}) make-shape ones slices))]
[state state]
(dense next-state {:units (:output-units options)
:regularizer output-regularizer})
[next-state]
{:output-time-axis 2})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NN-specific reporters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-multiclass-accuracy-reporter
"Returns a reporter function for the accuracy of predictions for a multi-class classification problem.
The returned function receives arguments [predicted actual], where `predicted` is a tensor containing
probabilities for each class along one axis and samples along all other axes. `actual` is a binary tensor
of the same structure containing the true class memberships represented in one-hot form. `options` can
include:
- `:class-axis`: the index of the axis spanning classes"
([]
(make-multiclass-accuracy-reporter {:class-axis 1}))
([options]
(u/check-key-validity options [:class-axis] [])
(let [class-axis (:class-axis options)]
(fn [predicted actual]
#_(println "predicted:" (first (m/slices predicted)))
#_(println "actual: " (first (m/slices actual)))
(-> predicted
(r/tensure-max-mask class-axis)
(m/mul actual)
m/esum
m/scalar->number
(/ (apply * (assoc (m/shape predicted) class-axis 1)))
(* 100)
(r/make-datapoint "Accuracy" :percent))))))
; TODO: Test this (this has not been tested at all)
(defn make-binary-classifier-reporter
"Returns a reporter function for the accuracy of predictions for a binary classification problem. The
returned function receives arguments [predicted actual], where `predicted` is a tensor where each element
is a probability of that sample belonging to one class, and `actual` is a binary tensor of the same shape
representing the true class memberships."
[]
(fn [predicted actual]
(-> (m/ge predicted (m/array 0.5))
(m/eq actual)
m/esum
m/->int
(/ (m/ecount actual))
(* 100.0)
(r/make-datapoint "Accuracy" :percent))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Model
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def reserved-node-names #{:training :predicting :testing})
(defn make-model
"Cosntructs a model, given:
- `:data` (required) - A map of maps (dataset-name -> variable-name -> data). The common case is to have
multiple datasets for different uses (e.g. `:training`, `:dev`, and `:test`), each with the same
variables (e.g. `:x` and `:y`).
- `:graph` (required) - A computation graph for the model.
- `:optimizer` (optional, defaults to gradient-descent-optimizer)
- `:optimizer-options` (optional) - Map of options to pass to `:optimizer`
- `:constants` (optional) - A map of name to value for graph inputs that do not change (i.e. that are
constant cross datasets).
- `:parameters` (optional) - A map of name to value for graph parameters. This can be excluded if all
parameters have initialization functions specified."
[& {:as options}]
(u/check-key-validity options [:graph :data] [:constants :parameters :optimizer :optimizer-options
; This is a private piece of data used to keep track of
; prior optimization results.
::prev-optimizer-results])
(let [{:keys [graph constants parameters optimizer optimizer-options data]
:or {constants {}
parameters {}
optimizer r/gradient-descent-optimizer
optimizer-options {}}} options
all-input-keys (into #{} (mapcat keys (vals data)))
;; data (u/update-vals data (fn [dataset]
;; (u/update-vals dataset #(if (m/array? %) % (m/array %)))))
]
(when-let [invalid-input-names (seq (set/intersection reserved-node-names all-input-keys))]
(u/throw-str "Invalid input names: '" invalid-input-names "'. These names are reserved."))
(when-let [invalid-constant-names (seq (set/intersection reserved-node-names
(into #{} (keys constants))))]
(u/throw-str "Invalid constant names: '" invalid-constant-names "'. These names are reserved."))
{:graph graph
:constants constants
:parameters parameters
:optimizer optimizer
:optimizer-options optimizer-options
:data data
::prev-optimizer-results (get options ::prev-optimizer-results {})}))
(defn update-model
[model & {:as updates}]
(apply make-model (apply concat (merge model updates))))
(defn update-prev-optimizer-results
[model dataset-or-name optimizer-result]
(assoc-in model [::prev-optimizer-results dataset-or-name] optimizer-result))
(defn get-previous-optimizer-result
[model dataset-or-name]
(get-in model [::prev-optimizer-results dataset-or-name]))
(defn get-model-constants
[model]
(:constants model))
(defn get-model-parameters
[model]
(:parameters model))
(defn get-model-optimizer
[model]
(:optimizer model))
(defn get-model-optimizer-options
[model]
(:optimizer-options model))
(defn get-model-graph
"Returns `model`'s computation graph."
[model]
(:graph model))
(defn get-model-dataset
"If `dataset-or-name` is a map (assumed to contain variable-name -> value), just returns the map;
otherwise looks up the dataset by the provided name in the model's associated data and returns the
corresponding map of variable-name -> value."
[model dataset-or-name]
(if (map? dataset-or-name)
dataset-or-name
(let [data (:data model)
dataset (get data dataset-or-name)]
(when-not dataset
(u/throw-str "Could not locate dataset '" dataset-or-name "'. Model only has datasets: '"
(keep (fn [[k v]] (when v k)) data) "'."))
dataset)))
(defn get-model-data
"Returns data for a given dataset and variable name. For example, `(get-model-data :training :x)`. Throws
exceptions if the model doesn't have a dataset or variable of the given name."
[model dataset-name varname]
(let [dataset (get-model-dataset model dataset-name)
var-data (get dataset varname)]
(when-not var-data
(u/throw-str "Could not locate data for variable '" varname "' in dataset '" dataset-name
"'. Dataset only has variables: '" (keep (fn [[k v]] (when v k)) dataset) "'."))
var-data))
(defn get-model-input-map
"Returns all a map of all model graph inputs (constants and vars from `dataset-or-name`)."
[model dataset-or-name]
(merge (get-model-dataset model dataset-or-name)
(get-model-constants model)))
(defn- get-all-model-parameter-nodes
"Returns a seq of all distinct input nodes in `model`'s graph that are parameters (either have `:parameter`
in their data set to `true` or are in the model`s `:parameters` map."
[model]
(let [specified-params (into #{} (keys (get-model-parameters model)))]
(->> (get-model-graph model)
r/get-all-graph-inputs
distinct
(filter #(or (-> % r/get-node-data :parameter)
(specified-params (r/get-node-name %)))))))
(defn- get-all-model-parameter-names
"Like `get-all-model-parameter-nodes` but returns a seq of names instead of a seq of nodes."
[model]
(map r/get-node-name (get-all-model-parameter-nodes model)))
(defn- get-all-model-parameter-values
"Returns a map of parameter name->value for all parameters of the given graph and dataset. Will include
`nil` values for parameters that have not been initialized."
[model]
(let [graph (get-model-graph model)
parameters (get-model-parameters model)
uninitialized-parameter-names (set/difference (into #{} (get-all-model-parameter-names model))
(into #{} (keys parameters)))
uninitialized-parameter-map (->> (map (juxt identity (constantly nil)) uninitialized-parameter-names)
(into {}))]
(merge parameters
uninitialized-parameter-map)))
(defn- get-trainable-parameter-name-set
[model]
(->> (get-all-model-parameter-nodes model)
(keep #(when (:trainable (r/get-node-data %))
(r/get-node-name %)))
(into #{})))
;; TODO: Get rid of `:training`, `:testing`, `:predicting` flags and just allow the user to pass these in
;; (e.g. either directly in the dataset, or through some option that allows additional inputs to be provided).
(defn evaluate-model
"Returns the result of running `model` on `dataset-or-name`. For example,
`(evaluate-model model :training)` will return the model's output for the `:training` dataset. Options
include:
- `:training` - boolean indicating if the `:training` input should be set to `true`
- `:testing` - boolean indicating if the `:testing` input should be set to `true`
If neither `:training` nor `:testing` is specified, the `:predicting` flag is set to true."
([model dataset-or-name]
(evaluate-model model dataset-or-name {}))
([model dataset-or-name options]
(u/check-key-validity options [] [:training :testing])
(let [extra-inputs (cond (:training options) {:training 1 :predicting 0 :testing 0}
(:testing options) {:training 0 :predicting 0 :testing 1}
:else {:training 0 :predicting 1 :testing 0})
graph (get-model-graph model)]
(->> (merge (get-all-model-parameter-values model)
extra-inputs
(get-model-input-map model dataset-or-name))
(r/evaluate graph)))))
(defn- make-optimized-model
"Returns a new model derived from `model` but with all properties updated based on `optimizer-result`."
[model dataset-or-name optimizer-result]
(let [untrained-parameters (r/get-optimized-state optimizer-result)
trained-parameters (r/get-optimized-params optimizer-result)]
(-> (update-model model
:graph (r/get-optimized-graph optimizer-result)
:parameters (merge trained-parameters
untrained-parameters))
(update-prev-optimizer-results dataset-or-name (r/reset-optimizer-reporting optimizer-result)))))
(defn- optimize-model
[model dataset-or-name iterations async?]
(let [optimizer (get-model-optimizer model)
optimizer-options (as-> (get-model-optimizer-options model) optimizer-options
(if (and #_(= optimizer r/gradient-descent-optimizer)
(:batch-size optimizer-options)
(not (:batch-inputs optimizer-options)))
(let [default-batch-inputs (->> (get-model-dataset model dataset-or-name)
keys
(mapv #(vector % 0))
(into {}))]
(assoc optimizer-options :batch-inputs default-batch-inputs))
optimizer-options)
(assoc optimizer-options :iterations iterations))
optimize-fn (if async?
r/optimize-async
r/optimize)]
(if-let [prev-result (get-previous-optimizer-result model dataset-or-name)]
(optimize-fn optimizer prev-result optimizer-options)
(let [graph (get-model-graph model)
all-param-map (get-all-model-parameter-values model)
trainable-param-name-set (get-trainable-parameter-name-set model)
trainable-param-map (select-keys all-param-map trainable-param-name-set)
state-param-map (apply dissoc all-param-map trainable-param-name-set)
extra-inputs {:training 1
:predicting 0
:testing 0}
input-map (merge extra-inputs
(get-model-input-map model dataset-or-name))]
(optimize-fn optimizer graph input-map trainable-param-map state-param-map optimizer-options)))))
(defn train-model
"Fits `model` to data in `dataset-or-name` by running the model's optimizer for `iterations` iterations.
Defaults to running 1 iteration on the `:training` data. Blocks until complete."
([model]
(train-model model 1))
([model iterations]
(train-model model :training iterations))
([model dataset-or-name iterations]
(let [optimizer-result (optimize-model model dataset-or-name iterations false)]
(make-optimized-model model dataset-or-name optimizer-result))))
(defn train-model-async
"Fits `model` to data in `dataset-or-name` (default `:training`) by running the model's optimizer for
`iterations` (defaults to infinite). Launches optimization in a new thread and immediately returns a
0-arity function, `stop`, that when called will immediately return the trained model from the last complete
iteration and terminate the optimization process after the next iteration is complete."
([model]
(train-model-async model nil))
([model iterations-or-dataset-or-name]
(let [[iterations dataset-or-name] (if (or (nil? iterations-or-dataset-or-name)
(number? iterations-or-dataset-or-name))
[iterations-or-dataset-or-name :training]
[nil iterations-or-dataset-or-name])]
(train-model-async model dataset-or-name iterations)))
([model dataset-or-name iterations]
(let [stop-optimizing (optimize-model model dataset-or-name iterations true)]
(fn stop
[]
(let [optimizer-result (stop-optimizing)]
(make-optimized-model model dataset-or-name optimizer-result))))))
; TODO:
; Improvements
; - Remove `data` from model. It makes more sense to keep the model and data completely separate.
; - This will also simplify all the `dataset-or-name` arguments where the supplied data can be either a
; map of data or a dataset name.
; - Could add a separate set of functions for managing datasets (e.g. bundling together sets of training
; and test data as the model does now).
; - Consider adding a set of required input names to model so datasets can be validated to ensure they have
; the required inputs (probably not possible to validate that _all_ inputs exist due to `if` branches--
; some graphs might not require some inputs, depending on conditional branching).
; - Add validation to make sure regularization is applied (an easy mistake is to pass a regularizer
; as an option for some layer and then to not pass the cost node through regularization layer). We can
; check that if any nodes have regularization, there must be a `regularize` node and, if not, we can
; throw an Exception. It's difficult to automatically inclue the `regularize` node, because it's
; difficult to know where in the graph it should go if there are conditional branches.
; - Figure out better way to handle print logging -- right now it's necessary to manually flush output
; if the last logging statement doesn't have a newline (which triggers a flush). Somehow always flush the
; print logger after the last iteration.
; - Be able to lazily load batches into memory.
; - Allow simple-optimize-like options for the model's optimizer-options
; Additional features
; - Serialization - be able to save and load models from/to disk
; - Periodic backups - be able to persist model data during training periodically, so if training gets
; interrupted, not all progress is lost.
; - More layers
; - Mean squared error (e.g. used in book reviews example)
; Quality
; - Tests:
; - to ensure regularization is not applied more than once for each regularized node (this was a
; previous bug that has since been fixed, but tests were not added to catch it).
; - of one-hot encoding functions
; - of softmax layer
; - of cross-entropy layer
; - of complete reporting and logging framework
; - of the layer initialization framework
; - Figure out how to handle evaluation with stateful recurrent layers when batching. It is currently
; possible to have batches that need state of different sizes, but if state is maintained between
; iterations, this causes an excpetion. Remove state before evaluating?
; - Reset recurrent netowrk state between epochs?
; - Standardize names of arguments of the same type/meaning (e.g. sometimes "nd" is used for a tensor node,
; and other times "operand" is used).
; - Automatically add '' around non-strings in throw-str
|
[
{
"context": "\n {:text \"They hand out Chicken McNuggets but they're stone cold.\"}\n ",
"end": 2182,
"score": 0.7309207320213318,
"start": 2165,
"tag": "NAME",
"value": "Chicken McNuggets"
},
{
"context": " {:text \"The judge is dressed like Dr. Frankenfurter.\"}\n {:text \"You're uns",
"end": 2288,
"score": 0.9984397292137146,
"start": 2275,
"tag": "NAME",
"value": "Frankenfurter"
},
{
"context": "text \"It sounds like someone with a cold is eating Rice Krispies.\" }\n {:text \"A hollow ",
"end": 10805,
"score": 0.9818514585494995,
"start": 10792,
"tag": "NAME",
"value": "Rice Krispies"
},
{
"context": "ur's head floats lonely nearby.\"}]}}\n\n {:text \"sauna\"\n :type :interior\n :article \"a\"\n :pre",
"end": 40106,
"score": 0.9822124242782593,
"start": 40101,
"tag": "NAME",
"value": "sauna"
},
{
"context": "\"at\" \"near\" \"behind\" \"in front of\"]}\n\n {:text \"ravine\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 40747,
"score": 0.9832721948623657,
"start": 40741,
"tag": "NAME",
"value": "ravine"
},
{
"context": "tti sauce runs down the middle.\"}]}}\n\n {:text \"ditch\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 41143,
"score": 0.9802772998809814,
"start": 41138,
"tag": "NAME",
"value": "ditch"
},
{
"context": "n't been tended for some time.\"}]}}\n\n {:text \"grotto\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 44157,
"score": 0.7908893823623657,
"start": 44152,
"tag": "NAME",
"value": "rotto"
},
{
"context": "ere's a pile of clothes nearby.\"}]}}\n\n {:text \"McDonald's\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 45507,
"score": 0.9970973134040833,
"start": 45497,
"tag": "NAME",
"value": "McDonald's"
},
{
"context": " \"It smells squarely delicious.\"}]}}\n\n {:text \"Taco Bell\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 45926,
"score": 0.9997016787528992,
"start": 45917,
"tag": "NAME",
"value": "Taco Bell"
},
{
"context": "oom is almost full of balloons.\"}]}}\n\n {:text \"Luby's\"\n :type :exterior\n :article \"a\"\n :pre",
"end": 54658,
"score": 0.984773576259613,
"start": 54652,
"tag": "NAME",
"value": "Luby's"
},
{
"context": "s place to the ground.'\"}\n {:text \"mumbles, 'Skrillex ruined it all for everybody.'\"}\n {:text \"mumbl",
"end": 56117,
"score": 0.7597757577896118,
"start": 56111,
"tag": "NAME",
"value": "rillex"
},
{
"context": "ugh.'\"}\n {:text \"says, 'I'm addicted to Kitty Lick III.'\"}\n {:text \"says, 'Looks like I'm not hav",
"end": 56863,
"score": 0.6633517146110535,
"start": 56860,
"tag": "NAME",
"value": "ick"
},
{
"context": "me for me to deal with the fact that I'll never be Ed Begley, Jr.'\"}\n {:text \"says, 'So I guess Kevin Space",
"end": 57394,
"score": 0.9963890314102173,
"start": 57385,
"tag": "NAME",
"value": "Ed Begley"
},
{
"context": "be Ed Begley, Jr.'\"}\n {:text \"says, 'So I guess Kevin Spacey is going to be a thing now.'\"}\n {:text \"says, ",
"end": 57445,
"score": 0.9991491436958313,
"start": 57433,
"tag": "NAME",
"value": "Kevin Spacey"
},
{
"context": "city hall.\"}]})\n\n(def signs\n {:signs\n [{:text \"Burma shave!\"}\n {:text \"It's time to pay the price.\"",
"end": 60765,
"score": 0.8179598450660706,
"start": 60760,
"tag": "NAME",
"value": "Burma"
},
{
"context": "thwest\"}]})\n\n(def persons\n {:persons\n [{:text \"Samuel L. Jackson\"\n :gender :male}\n\n {:text \"Rob Lowe\"\n ",
"end": 63058,
"score": 0.9998500347137451,
"start": 63041,
"tag": "NAME",
"value": "Samuel L. Jackson"
},
{
"context": "muel L. Jackson\"\n :gender :male}\n\n {:text \"Rob Lowe\"\n :gender :male}\n\n {:text \"Lloyd Braun\"\n ",
"end": 63101,
"score": 0.9998747706413269,
"start": 63093,
"tag": "NAME",
"value": "Rob Lowe"
},
{
"context": ":text \"Rob Lowe\"\n :gender :male}\n\n {:text \"Lloyd Braun\"\n :gender :male}\n\n {:text \"Bradley Whitfor",
"end": 63147,
"score": 0.999868631362915,
"start": 63136,
"tag": "NAME",
"value": "Lloyd Braun"
},
{
"context": "xt \"Lloyd Braun\"\n :gender :male}\n\n {:text \"Bradley Whitford\"\n :gender :male}\n\n {:text \"Josh Malina\"\n ",
"end": 63198,
"score": 0.9998757243156433,
"start": 63182,
"tag": "NAME",
"value": "Bradley Whitford"
},
{
"context": "radley Whitford\"\n :gender :male}\n\n {:text \"Josh Malina\"\n :gender :male}\n\n {:text \"David Lynch\"\n ",
"end": 63244,
"score": 0.9998809099197388,
"start": 63233,
"tag": "NAME",
"value": "Josh Malina"
},
{
"context": "xt \"Josh Malina\"\n :gender :male}\n\n {:text \"David Lynch\"\n :gender :male}\n\n {:text \"Allison Janney\"",
"end": 63290,
"score": 0.999872088432312,
"start": 63279,
"tag": "NAME",
"value": "David Lynch"
},
{
"context": "xt \"David Lynch\"\n :gender :male}\n\n {:text \"Allison Janney\"\n :gender :female}\n\n {:text \"Stephen Fry\"\n",
"end": 63339,
"score": 0.9998812675476074,
"start": 63325,
"tag": "NAME",
"value": "Allison Janney"
},
{
"context": "llison Janney\"\n :gender :female}\n\n {:text \"Stephen Fry\"\n :gender :male}\n\n {:text \"Hugh Laurie\"\n ",
"end": 63387,
"score": 0.9998520612716675,
"start": 63376,
"tag": "NAME",
"value": "Stephen Fry"
},
{
"context": "xt \"Stephen Fry\"\n :gender :male}\n\n {:text \"Hugh Laurie\"\n :gender :male}\n\n {:text \"Stephen Colbert",
"end": 63433,
"score": 0.9998838305473328,
"start": 63422,
"tag": "NAME",
"value": "Hugh Laurie"
},
{
"context": "xt \"Hugh Laurie\"\n :gender :male}\n\n {:text \"Stephen Colbert\"\n :gender :male}\n\n {:text \"Frances McDorma",
"end": 63483,
"score": 0.9998468160629272,
"start": 63468,
"tag": "NAME",
"value": "Stephen Colbert"
},
{
"context": "Stephen Colbert\"\n :gender :male}\n\n {:text \"Frances McDormand\"\n :gender :female}\n\n {:text \"Whoopi Goldbe",
"end": 63535,
"score": 0.9998683929443359,
"start": 63518,
"tag": "NAME",
"value": "Frances McDormand"
},
{
"context": "ces McDormand\"\n :gender :female}\n\n {:text \"Whoopi Goldberg\"\n :gender :female}\n\n {:text \"Katy Perry\"\n ",
"end": 63587,
"score": 0.9998582601547241,
"start": 63572,
"tag": "NAME",
"value": "Whoopi Goldberg"
},
{
"context": "oopi Goldberg\"\n :gender :female}\n\n {:text \"Katy Perry\"\n :gender :female}\n\n {:text \"Justin Bieber",
"end": 63634,
"score": 0.9998611211776733,
"start": 63624,
"tag": "NAME",
"value": "Katy Perry"
},
{
"context": "t \"Katy Perry\"\n :gender :female}\n\n {:text \"Justin Bieber\"\n :gender :male}\n\n {:text \"Neil deGrasse T",
"end": 63684,
"score": 0.9998655319213867,
"start": 63671,
"tag": "NAME",
"value": "Justin Bieber"
},
{
"context": " \"Justin Bieber\"\n :gender :male}\n\n {:text \"Neil deGrasse Tyson\"\n :gender :male}\n\n {:text \"Tim Heidecker\"\n",
"end": 63738,
"score": 0.9998618364334106,
"start": 63719,
"tag": "NAME",
"value": "Neil deGrasse Tyson"
},
{
"context": " deGrasse Tyson\"\n :gender :male}\n\n {:text \"Tim Heidecker\"\n :gender :male}\n\n {:text \"Eric Wareheim\"\n",
"end": 63786,
"score": 0.9998597502708435,
"start": 63773,
"tag": "NAME",
"value": "Tim Heidecker"
},
{
"context": " \"Tim Heidecker\"\n :gender :male}\n\n {:text \"Eric Wareheim\"\n :gender :male}\n\n {:text \"Jim J. Bullock\"",
"end": 63834,
"score": 0.9998646974563599,
"start": 63821,
"tag": "NAME",
"value": "Eric Wareheim"
},
{
"context": " \"Eric Wareheim\"\n :gender :male}\n\n {:text \"Jim J. Bullock\"\n :gender :male}\n\n {:text \"Johnny Cash\"\n ",
"end": 63883,
"score": 0.9998576641082764,
"start": 63869,
"tag": "NAME",
"value": "Jim J. Bullock"
},
{
"context": "\"Jim J. Bullock\"\n :gender :male}\n\n {:text \"Johnny Cash\"\n :gender :male}\n\n {:text \"a police office",
"end": 63929,
"score": 0.9998701214790344,
"start": 63918,
"tag": "NAME",
"value": "Johnny Cash"
},
{
"context": " police officer\"\n :gender :male}\n\n {:text \"Alex Trebek\"\n :gender :male}\n\n {:text \"Craig Ferguson\"",
"end": 64026,
"score": 0.9998785257339478,
"start": 64015,
"tag": "NAME",
"value": "Alex Trebek"
},
{
"context": "xt \"Alex Trebek\"\n :gender :male}\n\n {:text \"Craig Ferguson\"\n :gender :male}\n\n {:text \"Geoff Petersen\"",
"end": 64075,
"score": 0.9998683929443359,
"start": 64061,
"tag": "NAME",
"value": "Craig Ferguson"
},
{
"context": "\"Craig Ferguson\"\n :gender :male}\n\n {:text \"Geoff Petersen\"\n :gender :male}\n\n {:text \"Nancy Grace\"\n ",
"end": 64124,
"score": 0.9998588562011719,
"start": 64110,
"tag": "NAME",
"value": "Geoff Petersen"
},
{
"context": "\"Geoff Petersen\"\n :gender :male}\n\n {:text \"Nancy Grace\"\n :gender :female}\n\n {:text \"Lindsay Lohan",
"end": 64170,
"score": 0.9998624920845032,
"start": 64159,
"tag": "NAME",
"value": "Nancy Grace"
},
{
"context": " \"Nancy Grace\"\n :gender :female}\n\n {:text \"Lindsay Lohan\"\n :gender :female}\n\n {:text \"Ruth Buzzi\"\n ",
"end": 64220,
"score": 0.9998647570610046,
"start": 64207,
"tag": "NAME",
"value": "Lindsay Lohan"
},
{
"context": "Lindsay Lohan\"\n :gender :female}\n\n {:text \"Ruth Buzzi\"\n :gender :female}\n\n {:text \"Jennifer Lawr",
"end": 64267,
"score": 0.9998592138290405,
"start": 64257,
"tag": "NAME",
"value": "Ruth Buzzi"
},
{
"context": "t \"Ruth Buzzi\"\n :gender :female}\n\n {:text \"Jennifer Lawrence\"\n :gender :female}\n\n {:text \"Tilda Swinton",
"end": 64321,
"score": 0.9998456835746765,
"start": 64304,
"tag": "NAME",
"value": "Jennifer Lawrence"
},
{
"context": "ifer Lawrence\"\n :gender :female}\n\n {:text \"Tilda Swinton\"\n :gender :female}\n\n {:text \"Peter Dinklag",
"end": 64371,
"score": 0.9998421669006348,
"start": 64358,
"tag": "NAME",
"value": "Tilda Swinton"
},
{
"context": "Tilda Swinton\"\n :gender :female}\n\n {:text \"Peter Dinklage\"\n :gender :male}\n\n {:text \"Brad Pitt\"\n ",
"end": 64422,
"score": 0.9998356103897095,
"start": 64408,
"tag": "NAME",
"value": "Peter Dinklage"
},
{
"context": "\"Peter Dinklage\"\n :gender :male}\n\n {:text \"Brad Pitt\"\n :gender :male}\n\n {:text \"Bill Maher\"\n ",
"end": 64466,
"score": 0.9998408555984497,
"start": 64457,
"tag": "NAME",
"value": "Brad Pitt"
},
{
"context": "text \"Brad Pitt\"\n :gender :male}\n\n {:text \"Bill Maher\"\n :gender :male}\n\n {:text \"Grace Jones\"\n ",
"end": 64511,
"score": 0.9998334646224976,
"start": 64501,
"tag": "NAME",
"value": "Bill Maher"
},
{
"context": "ext \"Bill Maher\"\n :gender :male}\n\n {:text \"Grace Jones\"\n :gender :female}\n\n {:text \"Bill Murray\"\n",
"end": 64557,
"score": 0.9998359680175781,
"start": 64546,
"tag": "NAME",
"value": "Grace Jones"
},
{
"context": " \"Grace Jones\"\n :gender :female}\n\n {:text \"Bill Murray\"\n :gender :male}\n\n {:text \"your mom\"\n ",
"end": 64605,
"score": 0.999821126461029,
"start": 64594,
"tag": "NAME",
"value": "Bill Murray"
},
{
"context": "ga enthusiasts\"\n :gender :group}\n\n {:text \"George Clooney\"\n :gender :male}\n\n {:text \"James Franco\"\n ",
"end": 64813,
"score": 0.9998493194580078,
"start": 64799,
"tag": "NAME",
"value": "George Clooney"
},
{
"context": "\"George Clooney\"\n :gender :male}\n\n {:text \"James Franco\"\n :gender :male}\n\n {:text \"Jonah Hill\"\n ",
"end": 64860,
"score": 0.9998368620872498,
"start": 64848,
"tag": "NAME",
"value": "James Franco"
},
{
"context": "t \"James Franco\"\n :gender :male}\n\n {:text \"Jonah Hill\"\n :gender :male}\n\n {:text \"a gas station a",
"end": 64905,
"score": 0.9998462796211243,
"start": 64895,
"tag": "NAME",
"value": "Jonah Hill"
},
{
"context": "ation attendant\"\n :gender :male}\n\n {:text \"Craig T. Nelson\"\n :gender :male}\n\n {:text \"Thomas Pynchon\"",
"end": 65013,
"score": 0.9998430609703064,
"start": 64998,
"tag": "NAME",
"value": "Craig T. Nelson"
},
{
"context": "Craig T. Nelson\"\n :gender :male}\n\n {:text \"Thomas Pynchon\"\n :gender :male}\n\n {:text \"Drew Olanoff\"\n ",
"end": 65062,
"score": 0.9998249411582947,
"start": 65048,
"tag": "NAME",
"value": "Thomas Pynchon"
},
{
"context": "\"Thomas Pynchon\"\n :gender :male}\n\n {:text \"Drew Olanoff\"\n :gender :male}\n\n {:text \"Louis Gray\"\n ",
"end": 65109,
"score": 0.99983149766922,
"start": 65097,
"tag": "NAME",
"value": "Drew Olanoff"
},
{
"context": "t \"Drew Olanoff\"\n :gender :male}\n\n {:text \"Louis Gray\"\n :gender :male}\n\n {:text \"@akiva\"\n :g",
"end": 65154,
"score": 0.9998276233673096,
"start": 65144,
"tag": "NAME",
"value": "Louis Gray"
},
{
"context": ":text \"Louis Gray\"\n :gender :male}\n\n {:text \"@akiva\"\n :gender :male}\n\n {:text \"@jimminy\"\n ",
"end": 65195,
"score": 0.9987815022468567,
"start": 65188,
"tag": "USERNAME",
"value": "\"@akiva"
},
{
"context": " {:text \"@akiva\"\n :gender :male}\n\n {:text \"@jimminy\"\n :gender :male}\n\n {:text \"@veo_\"\n :ge",
"end": 65238,
"score": 0.9993065595626831,
"start": 65229,
"tag": "USERNAME",
"value": "\"@jimminy"
},
{
"context": " {:text \"@jimminy\"\n :gender :male}\n\n {:text \"@veo_\"\n :gender :male}\n\n {:text \"@vmcny\"\n :ge",
"end": 65278,
"score": 0.9996280074119568,
"start": 65272,
"tag": "USERNAME",
"value": "\"@veo_"
},
{
"context": " {:text \"@veo_\"\n :gender :male}\n\n {:text \"@vmcny\"\n :gender :male}\n\n {:text \"@KamenPrime\"\n ",
"end": 65319,
"score": 0.9996868371963501,
"start": 65312,
"tag": "USERNAME",
"value": "\"@vmcny"
},
{
"context": " {:text \"@vmcny\"\n :gender :male}\n\n {:text \"@KamenPrime\"\n :gender :male}\n\n {:text \"@ActuallySparky",
"end": 65365,
"score": 0.9996623992919922,
"start": 65353,
"tag": "USERNAME",
"value": "\"@KamenPrime"
},
{
"context": "text \"@KamenPrime\"\n :gender :male}\n\n {:text \"@ActuallySparky\"\n :gender :male}\n\n {:text \"@neonbubble\"\n ",
"end": 65415,
"score": 0.999691903591156,
"start": 65399,
"tag": "USERNAME",
"value": "\"@ActuallySparky"
},
{
"context": " \"@ActuallySparky\"\n :gender :male}\n\n {:text \"@neonbubble\"\n :gender :male}\n\n {:text \"@micahwittman\"\n",
"end": 65461,
"score": 0.999666154384613,
"start": 65449,
"tag": "USERNAME",
"value": "\"@neonbubble"
},
{
"context": "text \"@neonbubble\"\n :gender :male}\n\n {:text \"@micahwittman\"\n :gender :male}\n\n {:text \"@itafroma\"\n ",
"end": 65509,
"score": 0.999704897403717,
"start": 65495,
"tag": "USERNAME",
"value": "\"@micahwittman"
},
{
"context": "xt \"@micahwittman\"\n :gender :male}\n\n {:text \"@itafroma\"\n :gender :male}\n\n {:text \"@clive\"\n :g",
"end": 65553,
"score": 0.9996917247772217,
"start": 65543,
"tag": "USERNAME",
"value": "\"@itafroma"
},
{
"context": "{:text \"@itafroma\"\n :gender :male}\n\n {:text \"@clive\"\n :gender :male}\n\n {:text \"@mokargas\"\n ",
"end": 65594,
"score": 0.999664306640625,
"start": 65587,
"tag": "USERNAME",
"value": "\"@clive"
},
{
"context": " {:text \"@clive\"\n :gender :male}\n\n {:text \"@mokargas\"\n :gender :male}\n\n {:text \"@drew\"\n :ge",
"end": 65638,
"score": 0.999686062335968,
"start": 65628,
"tag": "USERNAME",
"value": "\"@mokargas"
},
{
"context": "{:text \"@mokargas\"\n :gender :male}\n\n {:text \"@drew\"\n :gender :male}\n\n {:text \"Bob Sacamano\"\n ",
"end": 65678,
"score": 0.999664843082428,
"start": 65672,
"tag": "USERNAME",
"value": "\"@drew"
},
{
"context": " {:text \"@drew\"\n :gender :male}\n\n {:text \"Bob Sacamano\"\n :gender :male}\n\n {:text \"Zombie Hunter T",
"end": 65725,
"score": 0.9998685121536255,
"start": 65713,
"tag": "NAME",
"value": "Bob Sacamano"
},
{
"context": "t \"Bob Sacamano\"\n :gender :male}\n\n {:text \"Zombie Hunter Thompson\"\n :gender :male}\n\n {:text \"Zombie Carl Sag",
"end": 65782,
"score": 0.9998617768287659,
"start": 65760,
"tag": "NAME",
"value": "Zombie Hunter Thompson"
},
{
"context": "Hunter Thompson\"\n :gender :male}\n\n {:text \"Zombie Carl Sagan\"\n :gender :male}]})\n\n(def actions\n {:actions",
"end": 65834,
"score": 0.9998390078544617,
"start": 65817,
"tag": "NAME",
"value": "Zombie Carl Sagan"
},
{
"context": " :article \"a bag of\"}\n\n {:text \"fat-soluble Jesus\"\n :article \"a bottle of\"}\n\n {:text \"llama ",
"end": 70131,
"score": 0.9851178526878357,
"start": 70126,
"tag": "NAME",
"value": "Jesus"
},
{
"context": "\"bucket of corks\"\n :article \"a\"}\n\n {:text \"jean shorts\"\n :article \"a pair of\"}\n\n {:text \"non-Eucl",
"end": 70744,
"score": 0.7267599105834961,
"start": 70733,
"tag": "NAME",
"value": "jean shorts"
},
{
"context": " :article \"a\"}\n\n {:text \"signed photograph of Richard Moll\"\n :article \"a\"}\n\n {:text \"hipster t-shirt\"",
"end": 71965,
"score": 0.9988519549369812,
"start": 71953,
"tag": "NAME",
"value": "Richard Moll"
},
{
"context": "\"]\n :adjectives [\"quacking\"]}\n\n {:text \"marmot\"\n :article \"a\"}\n\n {:text \"tiger\"\n :art",
"end": 72751,
"score": 0.717065155506134,
"start": 72748,
"tag": "NAME",
"value": "mot"
},
{
"context": " dogs going all the way to the moon\"}\n {:text \"Steve Buscemi's grin\"}\n {:text \"an obstinant balloon expert\"}\n",
"end": 74355,
"score": 0.9992068409919739,
"start": 74340,
"tag": "NAME",
"value": "Steve Buscemi's"
},
{
"context": " \"dubstep\"}\n {:text \"a 404 error\"}\n {:text \"Adam Sandler's career\"}\n {:text \"that awful man\"}\n {:tex",
"end": 74802,
"score": 0.9916146397590637,
"start": 74790,
"tag": "NAME",
"value": "Adam Sandler"
},
{
"context": "up\"}\n {:text \"a giant cat tongue\"}\n {:text \"George Lucas' neck\"}\n {:text \"Ruby On Rails\"}\n {:text \"s",
"end": 75064,
"score": 0.8736621141433716,
"start": 75052,
"tag": "NAME",
"value": "George Lucas"
}
] | src/xyzzwhy/text.clj | akivascript/xyzzwhy | 0 | (ns xyzzwhy.text)
;; This text presents source material for xyzzwhy's original corpus. Each
;; class (such as :location-events or :obstacles) is a map containing map
;; fragments the minimal requirement of which is a :text key.
;;
;; A fragment's :text value can contain a number of substitutions represented
;; by %0-%n. These require a :subs map which contains a key for each substitution.
;; These must contain at least a :class reference which is keyed to another
;; class. These are randomly chosen by xyzzwhy and then interpolated into the
;; fragment's :text. A substitution can also contain a :config map which has
;; options to skip the automatic prepending of prepositions and/or articles; and
;; the ability to ensure that an actor sub is a single person and not a group.
;; More config options will be added later.
;;
;; A fragment may also have follow-ups which may be marked as :optional?. A list of
;; options follows which is a vector of fragments which themselves may have :subs.
;; These subs must begin their %x count +1 from what's in the parent fragment's :text.
;; Each follow-up option's sub may contain a :ref key which allows it to refer to
;; a substitution from the parent fragment's text. For example, to use a pronoun
;; for a person class substitution at %0, the follow-up's substitution would :ref 0.
;;
;; Object classes and locations also have an :article and :preps for prepositions.
;; Locations have a :type which is either :interior or :exterior.
;; Actors have a :gender (:male, :female, or :group).
;;
;; Animals have :sounds (e.g., a kitten might purr or meow) and :adjectives
;; such as a 'whimpering' for a puppy.
;;
;; Future classes might have their own special keys and options.
(def events
{:events [:location-event :action-event]})
(def location-events
{:location-events
[{:text "You have entered %0."
:subs {0 {:class :location
:config #{:no-prep}}}}
{:text "You are serving jury duty."
:follow-ups {:optional? false
:options [{:text "The prosecuting attorney insists on speaking through a broken bullhorn."}
{:text "They hand out Chicken McNuggets but they're stone cold."}
{:text "The judge is dressed like Dr. Frankenfurter."}
{:text "You're unsure why they insist the jury sit in a vat of carbonated %0."
:subs {0 {:class :drink :config #{:no-article}}}}]}}
{:text "After %0 at your %1, you are relocated by FEMA to %2."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep :no-article}}
2 {:class :location :config #{:no-prep}}}}
{:text "You arrive for your first day at college only to find your roommate is %0."
:subs {0 {:class :actor}}}
{:text "You try to go %0 but your way is blocked by %1."
:subs {0 {:class :direction}
1 {:class :obstacle}}}
{:text "%0 prevents you from going %1 to %2."
:subs {0 {:class :obstacle}
1 {:class :direction}
2 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and find yourself at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and emerge %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You walk %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You cripwalk %0 to %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You strut %0 and end up %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "A double bounce on a trampoline lands you %0."
:subs {0 {:class :location}}}
{:text "You head %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "Google Maps leads you to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow %0 to %1."
:subs {0 {:class :actor}
1 {:class :location :config #{:no-prep}}}}
{:text "You are %0."
:subs {0 {:class :location}}}
{:text "You're %0."
:subs {0 {:class :location}}}
{:text "You run screaming into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You tunnel through the soil and pop up %0."
:subs {0 {:class :location}}}
{:text "You emerge %0."
:subs {0 {:class :location}}}
{:text "You arrive %0."
:subs {0 {:class :location}}}
{:text "You are magically teleported to %0!"
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The drugs are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "The spell effects are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "You are standing %0 of %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You stumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You come across %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow the treasure map to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You wake up from an odd dream. You are %0."
:subs {0 {:class :location}}}
{:text "You open the secret door only to see %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You find yourself %0."
:subs {0 {:class :location}}}
{:text "Dazed, you climb out of the dryer. You are %0."
:subs {0 {:class :location}}}
{:text "After the shoot-out, you make your escape to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The bridge game turned violent so you went to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You start doing the worm until you find yourself %0."
:subs {0 {:class :location}}}
{:text "You wake up %0."
:subs {0 {:class :location}}}
{:text "You climb down a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "You climb up a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "The taxi driver randomly drops you off %0."
:subs {0 {:class :location}}}
{:text "The metro bus unceremoniously dumps you %0."
:subs {0 {:class :location}}}
{:text "The fog clears and you find yourself %0."
:subs {0 {:class :location}}}
{:text "Your parachute gently plops you %0."
:subs {0 {:class :location}}}
{:text "You jump out of a moving car, roll down a hill, and find yourself %0."
:subs {0 {:class :location}}}
{:text "After walking for a long time, you find yourself %0."
:subs {0 {:class :location}}}
{:text "You find your way blindly and end up %0."
:subs {0 {:class :location}}}
{:text "No matter how hard you try, you still end up %0."
:subs {0 {:class :location}}}
{:text "You climb out of the treasure chest. You are now %0."
:subs {0 {:class :location}}}
{:text "You come to %0."
:subs {0 {:class :location}}}
{:text "You follow a winding path %0 only to find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You follow a sloping path %0. You find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You climb up a flight of stairs. You are now %0."
:subs {0 {:class :location}}}
{:text "You shuffle down a flight of stairs and enter %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You fall down a flight of stairs and into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The elevator doors open to reveal %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "Using a vine to swing across the pit, you land %0."
:subs {0 {:class :location}}}
{:text "The trapdoor drops open beneath you and you land %0."
:subs {0 {:class :location}}}
{:text "You flip the Game Select selector and find yourself %0."
:subs {0 {:class :location}}}
{:text "You blow into the cartridge too hard and are teleported to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You step through a magic mirror and end up %0."
:subs {0 {:class :location}}}
{:text "You get tangled up in a revolving door. You stumble out into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "After scrambling through some dense underbrush, you find yourself %0."
:subs {0 {:class :location}}}
{:text "After pushing your way through a dense crowd, you arrive %0."
:subs {0 {:class :location}}}
{:text "You squeeze out of the sewage outflow and tumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "A tornado deposits you %0."
:subs {0 {:class :location}}}
{:text "Right on cue, you pop up out of the jack-in-the-box. You're %0."
:subs {0 {:class :location}}}
{:text "After being shot out of a cannon, you land %0."
:subs {0 {:class :location}}}
{:text "You slide down a fireman's pole and land %0."
:subs {0 {:class :location}}}
{:text "Hands on your hips, you survey %0 %1."
:subs {0 {:class :location :config #{:no-prep}}
1 {:class :adverb}}}
{:text "You wake up in front of %0's house. You have no clue how you got there."
:subs {0 {:class :person}}}
{:text "You ride %0 to %1."
:subs {0 {:class :animal}
1 {:class :location :config #{:no-prep}}}}
{:text "You fall through the ceiling and land %0."
:subs {0 {:class :location}}}
{:text "The drugs are starting to take hold. Casually you saunter over to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The merry-go-round spins faster and faster until you're flung off and land %0."
:subs {0 {:class :location}}}]})
(def action-events
{:action-events
[{:text "You awake from a nightmare. You saw yourself %0. The corpse of %1 was there, holding %2."
:subs {0 {:class :location}
1 {:class :person :config #{:no-groups}}
2 {:class :item}}}
{:text "%0 arrives from the %1, carrying %2."
:subs {0 {:class :actor :config #{:no-groups}}
1 {:class :direction}
2 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You pick up %0 and hold it close to your chest."
:subs {0 {:class :item}}}
{:text "The radio crackles to life."
:follow-ups {:optional? false
:options [{:text "It sounds like someone with a cold is eating Rice Krispies." }
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Ketchup begins seeping through the speaker holes."}
{:text "It continues to crackle to life. It's still crackling. It's on fire."}
{:text "An announcer shouts, 'They found rice on Mars!"}
{:text "A news report is on about %0 %1."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep}}}}
{:text "%0 solemnly '%1'"}]}}
{:text "%0 drops %1, looks at you %2, then leaves."
:subs {0 {:class :actor}
1 {:class :item}
2 {:class :adverb}}}
{:text "You check your messages."
:follow-ups {:optional? false
:options [{:text "%0 %1"
:subs {0 {:class :person :config #{:no-groups}}
1 {:class :dialogue}}}]}}
{:text "You read morning paper."
:follow-ups {:optional? false
:options {:text "%0"
:subs {0 {:class :news}}}}}
{:text "%0 gently places %1 on the ground and then backs away slowly."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 %1 %2."
:subs {0 {:class :actor}
1 {:class :action}
2 {:class :actor}}}
{:text "%0 %1 you."
:subs {0 {:class :actor}
1 {:class :action}}}
{:text "%0 drops %1 here."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 does a little jig. 'Bidibidibidi, wanna dance?'"
:subs {0 {:class :actor}}}
{:text "%0 marches up to you and says, 'Hello please.'"
:subs {0 {:class :person}}}
{:text "%0 starts breakdancing and won't stop no matter how much you scream."
:subs {0 {:class :person}}}
{:text "%0 attacks you and knocks you out. You awake sometime later %1."
:subs {0 {:class :actor}
1 {:class :location}}}
{:text "%0 attacks you but you fight back with %1,"
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "winning the battle."}
{:text "taking only a hit to your pride."}]}}
{:text "%0 attacks you but you fight back with %1."
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "It isn't enough: you lose."}
{:text "This scares the shit out of %2. %3 runs away."
:subs {2 {:ref 0
:class :gender
:case :objective}
3 {:ref 0
:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You execute %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "You are victorious!"}
{:text "You have been killed."}
{:text "You have been slain!"}
{:text "%0 keels over all dead and stuff."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You respond with %2. You are defeated."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}}
{:text "%0 attacks with %1. You strike back with %2. FATALITY. But who?!"
:subs {0 {:class :actor}
1 {:class :attack}}}
{:text "%0 attacks with %1. You with %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "Look at you what with the killing and all."}
{:text "%0 is a bloodstain."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "Suddenly you're in freeze-frame as the credits roll."}
{:text "%0 appears in a puff of smoke, %1"
:subs {0 {:class :person}
1 {:class :actor-action}}}
{:text "You startle %0 who drops %1 and runs away."
:subs {0 {:class :person}
1 {:class :item}}}
{:text "%0 slams down a half-empty glass of %1."
:subs {0 {:class :person}
1 {:class :drink :config #{:no-prep :no-article}}}
:follow-ups {:optional? false
:options [{:text "'All this nonsense about %0 needs to stop! I can't take it anymore!'"
:subs {0 {:class :item}}}
{:text "'They're making plans for Nigel! They want what's best for him!'"}
{:text "'You can't go up against city hall!'"}
{:text "'I just can't take you seriously anymore!'"}
{:text "'MOM?!'"}]}}
{:text "%0 suddenly shrieks."
:subs {0 {:class :person}}}
{:text "%0 makes a rude noise, points surreptitiously to %1 nearby."
:subs {0 {:class :person}
1 {:class :animal}}}
{:text "You get tired of waiting for";
:follow-ups {:optional? false
:options [{:text "your Uber and decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "your private jet so you decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "the all-you-can-eat-buffet to open so you walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}]}}
{:text "The phone rings."
:follow-ups {:optional? false
:options [{:text "%0 stares at it %1. Eventually the ringing stops."
:subs {0 {:class :person}
1 {:class :adverb}}}
{:text "%0 watches as it starts to melt, the sound of the ring slowing and burbling to a stop."
:subs {0 {:class :person}}}
{:text "%0 picks it up, listens a moment, shrieks, and slams the phone down again."
:subs {0 {:class :person}}}
{:text "%0 picks it up, says, 'It's for you,' but you're longer there."
:subs {0 {:class :person}}}]}}
{:text "You start eating %0 and don't stop until you're done."
:subs {0 {:class :food}}}
{:text "You eat %0."
:subs {0 {:class :food}}
:follow-ups {:optional? true
:options [{:text "%0 looks on %1."
:subs {0 {:class :actor}
1 {:class :adverb}}}]}}
{:text "You think to yourself, '%0'"
:subs {0 {:class :thought}}}
{:text "You pause and think, '%0'"
:subs {0 {:class :thought}}}
{:text "You feel a little famished so you eat %0."
:subs {0 {:class :food}}}
{:text "You take a sip of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "You check your inventory."
:follow-ups {:optional? true
:options [{:text "You are empty-handed."}
{:text "You are carrying %0, %1, and %2."
:subs {0 {:class :item}
1 {:class :item}
2 {:class :item}}}
{:text "You have %0 and %1."
:subs {0 {:class :item}
1 {:class :item}}}]}}
{:text "You open up %0."
:subs {0 {:class :book}}
:follow-ups {:optional? false
:options [{:text "Someone has scribbled all over the margins. You throw it down on the floor in disgust."}
{:text "Someone has left a recipe for beef stew inside."}
{:text "You read a bit before tossing it over your shoulder and then doing the electric slide."}]}}
{:text "%0 suddenly appears out of the shadows and"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "hisses at you, then scrambles away like a spider."}
{:text "says, 'Oh, sorry about that,' then retreats back into the shadows."}
{:text "says, '%0 will see you now,' then slowly retreats back into the shadows."
:subs {0 {:class :actor}}}]}}
{:text "%0 picks up %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "An overhead loudspeaker crackles to life,"
:follow-ups {:optional? false
:options [{:text "'Citizen! Report immediately to the nearest oddly-angled inner tube.'"}
{:text "'Citizen! Report immediately to the nearest self-incrimination booth.'"}
{:text "'Citizen! Report immediately to the nearest Java stacktrace.'"}
{:text "'Citizen! Report immediately to the bean simulator.'"}
{:text "'Citizen! Report immediately to the nearest certified manhole.'"}
{:text "'Citizen! Report immediately to the National Baby Oil Slip-n-Slide.'"}
{:text "'Citizen! Report immediately to the Hall of Uncomfortable Touching.'"}
{:text "'Citizen! Report immediately to the Bakery of Unravelled Cinnamon Buns.'"}
{:text "'Citizen! Stop that.'"}
{:text "'Citizen! Report immediately to the Readers' Digest Condensation Camp.'"}
{:text "'Citizen! Open up your textbook and turn to the chapter concerning your death.'"}
{:text "'Citizen! Report immediately to the Out-of-Control Rototiller Museum.'"}
{:text "'Citizen! Report immediately to the nearest mandatory prison hug.'"}
{:text "'Citizen! Report immediately to the nearest sanctioned dogpile.'"}
{:text "'Citizen! Report immediately to the nearest full-contact Bible study group.'"}
{:text "'Citizen! Report immediately to the mannequin factory.'"}
{:text "'Citizen! Report immediately to The Garbagerie.'"}
{:text "'Citizen! Report immediately to Stall #3.'"}
{:text "'Citizen! Just shut up already.'"}]}}
{:text "An overhead loudspeaker crackles to life. The announcement is completely garbled. The loudspeaker switches off with a squawk."}
{:text "You start spinning around and around."
:follow-ups {:optional? false
:options [{:text "%0 looks unimpressed."
:subs {0 {:class :person}}}
{:text "%0 faints."
:subs {0 {:class :person}}}
{:text "You drill straight into the crust of the earth."}
{:text "You gracefully lift off into a blue sky."}
{:text "You gracefully lift off into a blue sky never to be seen again."}
{:text "You gracefully lift off, go sideways, and crash into a building."}]}}
{:text "You start spinning around and around while"
:follow-ups {:optional? false
:options [{:text "%0 claps and cheers."
:subs {0 {:class :person}}}
{:text "%0 cries and points."
:subs {0 {:class :person}}}
{:text "%0 writes furiously on a clipboard."
:subs {0 {:class :person}}}
{:text "%0 beams with pride."
:subs {0 {:class :person}}}]}}
{:text "%0 is calling from %1 asking for %2."
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}
2 {:class :item}}}
{:text "%0 is calling from %1"
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}}
:follow-ups {:optional? false
:options [{:text "asking if %2 can come out and play."
:subs {2 {:class :person}}}]}}
{:text "You peek out the window."
:follow-ups {:optional? true
:options [{:text "%0 is messing around with your mailbox. You crouch in fear."
:subs {0 {:class :person}}}
{:text "%0 is laying facedown in your flowerbed. You sink to your knees with worry."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's on fire."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's covered in bees."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. The line stretches around the block."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand across the street. You feel oddly jealous."
:subs {0 {:class :person}}}
{:text "%0 is struggling to start a chainsaw while staring at you. You bite your knuckle."
:subs {0 {:class :person}}}
{:text "%0 is standing in your yard, painting a portrait of you peeking out the window."
:subs {0 {:class :person}}}
{:text "Your entire house has been encased in a giant stone column."}]}}
{:text "In the distance,"
:follow-ups {:optional? false
:options [{:text "you hear %0 let the bass drop."
:subs {0 {:class :person}}}
{:text "you hear %0 drop the mic."
:subs {0 {:class :person}}}
{:text "you hear %0 get wicked."
:subs {0 {:class :person}}}
{:text "you hear %0 shake it off."
:subs {0 {:class :person}}}]}}
{:text "A magician saws you in half... lengthwise."}
{:text "You check your health: you are %0."
:subs {0 {:class :diagnose}}}
{:text "You find yourself being slowly teleported away. Very slowly. People are beginning to stare."}]})
(def secondary-events
{:secondary-events
[{:text "You see %0 here."
:subs {0 {:class :item}}}
{:text "You see %0 here. It looks oddly familiar."
:subs {0 {:class :item}}}
{:text "There is %0 here."
:subs {0 {:class :item}}}
{:text "You pick up %0. It's covered in dust."
:subs {0 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You drop %0 here."
:subs {0 {:class :item}}
:follow-ups {:optional? true
:options [{:text "It bursts into flames."}
{:text "It turns into a wisp of smoke."}
{:text "And then some really bad CGI happens."}
{:text "It pierces the crust of the Earth."}
{:text "It bounces right back into your hand."}]}}
{:text "You find %0 here. You back away %1."
:subs {0 {:class :item}
1 {:class :adjective}}}
{:text "%0 is here."
:subs {0 {:class :actor}}}
{:text "%0 is here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "You find %0 here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "%0 %1"
:subs {0 {:class :person}
1 {:class :dialogue}}}
{:text "%0 is here searching for %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 is here with %1. They look %2."
:subs {0 {:class :actor}
1 {:class :actor}
2 {:class :adjective}}}
{:text "%0 follows you."
:subs {0 {:class :actor}}}
{:text "%0 slinks up behind you."
:subs {0 {:class :actor}}}
{:text "%0 wanders by,"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "doing algebra and shit."}
{:text "playing a recorder."}
{:text "jamming on a mouth organ."}
{:text "wearing a cape."}
{:text "casually on fire."}
{:text "followed by a classy balloon."}
{:text "whistling the theme to the Andy Griffith Show."}
{:text "whistling the theme to the Garry Shandling Show."}]}}
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Something smells %0 here."
:subs {0 {:class :scent}}}
{:text "It smells %0."
:subs {0 {:class :scent}}}
{:text "You hear %0 in the distance."
:subs {0 {:class :noise}}}
{:text "You hear the sound of %0 nearby."
:subs {0 {:class :noise}}}
{:text "The wind howls in the distance."}
{:text "It appears abandoned."}
{:text "Someone has been here recently."}
{:text "There are fresh footprints here."}
{:text "It seems that no one has been here for a long time."}
{:text "Someone has attached marionnette wires to your hands, feet, and head."}
{:text "Someone has left a running bulldozer here."}
{:text "The words 'eat dulp' are spray-painted on a wall here."}
{:text "The words 'Knifekitten lives!' are spray-painted on a wall here."}
{:text "The words 'Hammerdog lives!' are spray-painted on a wall here."}
{:text "Spray-painted on the wall here are the words 'Alice?! Alice?! Who the f...'. The rest is illegible."}
{:text "An ice cream truck goes by. It's on fire."}
{:text "A fire truck goes by. It's covered in ice."}
{:text "There has been significant damage from %0."
:subs {0 {:class :disaster}}}
{:text "You see a sign here. On it is written '%0'"
:subs {0 {:class :sign}}}]})
(def tertiary-events
{:tertiary-events
[{:text "You aren't wearing any clothes."}
{:text "Your clothes feel too small."}
{:text "Your clothes feel too loose."}
{:text "You're certain these aren't your clothes."}
{:text "Your shoes are on the wrong feet."}
{:text "Your tie feels uneven."}
{:text "You're wearing two bowties for some reason."}
{:text "You're not wearing any underwear."}
{:text "You're wearing two pairs of underwear."}
{:text "Someone is struggling with warped Tupperware nearby."}
{:text "You do a little jig and then whistle."}
{:text "You clap once."}
{:text "You have socks on your hands."}
{:text "You slowly slide your hands into your pockets. You regret this immediately."}
{:text "You feel serene."}
{:text "You feel nervous."}
{:text "You feel anxious."}
{:text "You feel cold."}
{:text "You feel warm."}
{:text "You aren't alone."}
{:text "You blink really slowly."}
{:text "You find yourself humming the theme to Too Many Cooks."}
{:text "You hear gunfire in the distance."}
{:text "You hear a party in the distance."}
{:text "You hear a toilet flush nearby."}
{:text "Someone is having fun against their will nearby."}
{:text "You yawn."}
{:text "You sneeze."}
{:text "You cough."}
{:text "You chuckle to yourself."}
{:text "You practice frowning for awhile."}
{:text "You begin to smile uncontrollably."}
{:text "You wish you had your grandpappy's harmonica."}
{:text "You are starting to feel sleepy."}
{:text "You glance at your watch; you're running 15 minutes late."}
{:text "You glance at your watch; somehow, you're still on time."}
{:text "You glance at your watch; you're a little ahead of schedule."}
{:text "You spend a few moments thinking fondly about your teeth."}
{:text "You feel as if you're being followed."}
{:text "A warm breeze blows by."}
{:text "A cool breeze blows by."}
{:text "It starts to rain."}
{:text "It starts to snow."}
{:text "Thunder coughs gently in the distance."}
{:text "A basketball bounces by."}
{:text "Something nearby is on fire."}
{:text "You can smell something burning in the distance."}
{:text "You look around nervously."}
{:text "You spot a balloon stuck in a tree."}
{:text "You spot a kitten stuck in a tree."}
{:text "You spot an office desk in a tree."}
{:text "You spot a bonsai tree stuck in a regular tree."}
{:text "You see a pair of sneakers dangling on a utility line overhead."}
{:text "Someone nearby is repeatedly zipping and unzipping a duffel bag."}
{:text "Somehow, you've lost your %0."
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "You hear someone nearby typing away on a manual typewriter."}
{:text "You're catching your second wind."}
{:text "You are starting to feel thirsty."}
{:text "You feel better."}
{:text "You have died."}
{:text "You are starting to feel hungry."}]})
(def actor-actions
{:actor-actions
[{:text "looking %0."
:subs {0 {:class :adjective}}}
{:text "being chased by a swarm of balloon animals."}
{:text "being chased by %0."
:subs {0 {:class :person}}}
{:text "being chased by %0 which is attached to them by a string."
:subs {0 {:class :item}}}
{:text "dancing furiously."}
{:text "dancing extremely slowly."}
{:text "shouting at an imaginary helicopter."}
{:text "doing the Kenosha Kid."}
{:text "thinking %0 about %1."
:subs {0 {:class :adverb}
1 {:class :actor}}}
{:text "being chased around by a bee."}
{:text "defiantly eating Scrabble tiles, one by one."}
{:text "%0 playing the organ."
:subs {0 {:class :adverb}}}
{:text "organizing matches."}
{:text "having a Guru Meditation Error."}
{:text "juggling some balls."}
{:text "dancing in a little circle."}
{:text "stooping up and down like a rapper in concert."}
{:text "drooling uncontrollably."}
{:text "clutching a DVD of Dot & the Kangaroo."}
{:text "clutching a DVD of BMX Bandits."}
{:text "wearing an eyepatch."}
{:text "wearing two eyepatches and stumbling around blindly."}
{:text "hiding under a table."}
{:text "hiding under a sofa."}
{:text "hiding in the bushes."}
{:text "munching on %0."
:subs {0 {:class :food}}}
{:text "pretending to be invisible."}
{:text "having a coughing fit."}
{:text "having a sneezing fit."}
{:text "being menaced by %0."
:subs {0 {:class :animal}}}
{:text "ready to start some shit."}
{:text "examining %0 with great confusion."
:subs {0 {:class :item}}}]})
(def locations
{:locations
[{:text "dead-end"
:type :interior
:article "a"
:preps ["at" "in front of"]
:follow-ups {:optional? true
:options [{:text "You start to moonwalk away."}
{:text "Someone has painted a giant sad face here."}]}}
{:text "ice skating rink"
:type :exterior
:article "an"
:preps ["at" "in front of" "on"]
:follow-ups {:optional? true
:options [{:text "It's currently on fire."}
{:text "Unfortunately, it's made of dry ice."}
{:text "A solid-gold curling stone is nearby."}
{:text "There are three hungry-looking zambonies here."}]}}
{:text "movie set"
:type :exterior
:article "a"
:preps ["on"]
:follow-ups {:optional? true
:options [{:text "The crafts table is covered with another, smaller crafts table."}
{:text "A nude man strolls by."}
{:text "A hundred tiny dogs are here, looking menacing."}]}}
{:text "particle board storage facility"
:type :interior
:article "a"
:preps ["at" "near" "in front of" "behind" "inside"]}
{:text "tire fire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is warm and welcoming."}
{:text "Someone had been roasting marshmallows here."}
{:text "The air here is black with despair and entropy."}
{:text "The sky is darkened by the hellish smoke."}]}}
{:text "dildo bonfire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "You look closely but don't recognize any of them."}
{:text "The plastic hisses and creaks in the blaze."}
{:text "The smoke smells of vanilla."}
{:text "The air is dense with the echoes of unreached orgasms."}]}}
{:text "hot tub"
:type :interior
:article "a"
:preps ["in near"]
:follow-ups {:optional? true
:options [{:text "The water roils and steams like water roils and steams."}
{:text "It's frozen solid."}
{:text "A basketball dances on the bubbles."}
{:text "You see a staircase beneath the water."}
{:text "Is it water or is it hydrocarbons?"}
{:text "It smells delicious because someone filled it with chicken soup."} ]}}
{:text "maze of twisty little passages, all alike"
:type :interior
:article "a"
:preps ["in"]}
{:text "Burning Man"
:type :exterior
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "Oddly, no one appears to be here."}
{:text "A tumbleweed made out of human hair stumbles by."}
{:text "A dust storm is approaching."}
{:text "It looks like it might rain soon."}
{:text "Snow is gently falling."}
{:text "%0 is here, looking %1."
:subs {0 {:class :person}
1 {:class :adjective}}}
{:text "Clearly the drugs have begun to take hold."}]}}
{:text "Shrim Healing Center"
:type :exterior
:article "a"
:preps ["in" "at" "in front of" "behind"]
:follow-ups {:optional? true
:options [{:text "There are TVs in the window, all turned off."}
{:text "Someone has spray-painted 'I crave brown baths' here."}
{:text "Inside you hear the sound of repulsed joy."}
{:text "The door has been boarded up."}
{:text "%0 is patiently waiting in line by %1."
:subs {0 {:class :person}
1 {:class :gender
:case :compound}}}
{:text "The building looks like it has been condemned."}]}}
{:text "quicksand"
:type :exterior
:article "some"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Briefly, you see a fin rise up and cruise back and forth."}
{:text "The surface quicksand gently sways, beckoning you..."}
{:text "Oddly, it smells like freshly cooked oatmeal."}]}}
{:text "swimming pool"
:type :exterior
:article "a"
:preps ["in" "at" "near"]
:follow-ups {:optional? true
:options [{:text "The surface of the pool is almost entirely still. You are afraid to disturb it."}
{:text "The water has turned slightly murky; it does not look inviting."}
{:text "The surface of the pool is littered with leaves."}
{:text "The pool is empty."}
{:text "The pool is empty. A broken skateboard is nearby."}
{:text "A dead bird floats by."}
{:text "An abandoned plastic float with a dinosaur's head floats lonely nearby."}]}}
{:text "sauna"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The wood paneling sweats sweetly in the oppressive heat."}
{:text "Great thunderheads of steam rise up from the rock basin, making it hard to see."}
{:text "The room is cold and dark. No one has been here in years."}
{:text "The floor is covered with cute little mushrooms."}]}}
{:text "New York Public Library"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]}
{:text "ravine"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It stretches out in front of you, meandering as if drunk."}
{:text "A giant marshmallow avalanche blocks the way ahead."}
{:text "A small trickle of spaghetti sauce runs down the middle."}]}}
{:text "ditch"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The dusty stench of aged sewage gives you a hug."}
{:text "It is completely blocked here by a giant boulder."}
{:text "A trickle of clear water runs down the middle of it."}]}}
{:text "dump"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "In the distance, you see a hazy castle."}
{:text "The hill of trash shifts dangerously beneath your feet."}]}}
{:text "dump truck"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "It's covered with a patina of black filth."}
{:text "Fresh off the line, it gleams bright red."}
{:text "The engine rumbles roughly to itself. The doors are locked."}]}}
{:text "Starbucks"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is packed tightly with hipsters."}
{:text "There is a surprising lack of hipsters here."}
{:text "It reeks of slightly burnt coffee here."}]}}
{:text "park restroom stall"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The door has been torn off its hinges."}
{:text "The walls are covered with violent scratches."}
{:text "The toilet is made of solid gold."}
{:text "A garden gnome greets you from the bowl."}
{:text "The toilet is missing."}
{:text "There's a basketball in the bowl."}
{:text "Suddenly the lights go out."}
{:text "The lingering scents of lemon and Lysol haunt the air."}
{:text "Someone has scratched your name and number on the wall."}]}}
{:text "all-you-can-eat buffet"
:type :interior
:article "an"
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "It looks abandoned."}
{:text "Bullet time means more eggrolls."}
{:text "Steam crowds the air."}
{:text "It's all gluten-free and vegan. You leave immediately."}
{:text "It smells of freedom and gluttony."}
{:text "All of the food has been replaced with wax replicas."}
{:text "It's in complete disarray and hasn't been tended for some time."}]}}
{:text "grotto"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The ceiling is sparkling with reflected light."}
{:text "The water is darkened with greenish-gray algae."}
{:text "The pool of water seems unusually deep. A lean, black fish swims in a circle."}]}}
{:text "bedroom"
:type :interior
:article "your"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It hasn't been cleaned in a long time."}
{:text "There's a pleasantly disgusting smell here."}
{:text "It's small and lightly furnished. The bed is unmade."}
{:text "There is nothing special about it."}
{:text "You notice an unusual stain in the carpet."}
{:text "There's an unusual stain in the carpet next to a usual stain."}
{:text "The ceiling fan is spinning dangerously fast."}
{:text "The walls are covered with %0 posters."
:subs {0 {:class :person}}}
{:text "There's a pile of clothes nearby."}]}}
{:text "McDonald's"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "White Castle"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It's white and vaguely castle-shaped."}
{:text "It smells squarely delicious."}]}}
{:text "Taco Bell"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "dark area"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is pitch black here. You're likely to be eaten by %0."
:subs {0 {:class :actor}}}
{:text "It's really dark here. Like... REALLY dark."}
{:text "It just got slightly darker somehow."}
{:text "It's so dark you can taste it. Tastes like dark."}
{:text "It's dark here. DARK AS YOUR SOUL."}]}}
{:text "breezy cave"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "There's a constant breeze rising up from the depths."}
{:text "Wide and low, the cave gently slopes %0-%1 here."
:subs {0 {:class :direction}
1 {:class :direction}}}
{:text "It smells of warm packing peanuts."}
{:text "It's really breezy. Gale-force breezy."}
{:text "It's seems over-oxygenated. You get light-headed."}
{:text "The cave seems to be breathing rapidly."}]}}
{:text "forest"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is a dense, dark, and tangled choke of gnarled trees, thorny underbrush, and spiky thickets."}
{:text "Shot through with shafts of light, the forest before you looks serene."}
{:text "The trees, mostly oak and spruce, sway gently in the occasional breeze."}
{:text "It's currently on fire."}
{:text "The trees are all inflated plastic."}
{:text "The trees ignore your incessant crying."}
{:text "Birds are chirping and rodents scamper through the underbrush."}]}}
{:text "riverbed"
:type :exterior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "It's dry and littered with rocks and branches."}
{:text "The water steadfastedly refuses to flow. It just sits there."}
{:text "Nearby two bears are standing on the water, defiantly."}
{:text "The river immediately parts and just keeps on parting."}
{:text "It's mostly dry, the flow of the water blocked by a beaver dams upstream."}]}}
{:text "AT&T Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "Apple Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "ballpit"
:type :interior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Oddly, all of the balls here are the same color: orange."}
{:text "The ballpit seems unusually deep. You can't feel the bottom."}
{:text "It's been filled with Rubik's Cubes."}
{:text "It's empty except for one orange ball at the bottom."}
{:text "It contains only one ball: orange and 12' across."}
{:text "You get the feeling someone is swimming around in there."}]}}
{:text "airplane"
:type :interior
:article "an"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "There's no one else on board."}
{:text "You hear strange noises coming from the restroom."}
{:text "Somehow you have a dozen packets of pretzels."}
{:text "Someone drank your Fresca while you were napping."}
{:text "It's pitch black outside. Can grues fly?"}
{:text "The pilot says, 'We've reached our cruising altitude of 30 feet.'"}
{:text "The plane has been going straight up for hours now."}]}}
{:text "trunk of a car"
:type :interior
:article "the"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "A tire iron is digging into your back a little bit."}
{:text "There's a half-eaten bag of Bugles here."}
{:text "With all the trash in here, there's barely any room for you."}
{:text "It's pitch black. No room for a grue, luckily."}]}}
{:text "coffin"
:type :interior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "It smells of cotton candy in here for some reason."}
{:text "It smells of Aquanet in here. Makes sense."}
{:text "It's pitch black. It probably doesn't matter if ther's a grue here."}]}}
{:text "hugbox"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "You feel at home again."}
{:text "It's very warm in here. Perhaps too warm."}
{:text "It smells of stale sweat and lies, lies, lies..."}]}}
{:text "haunted house"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The house shrugs under its own entropy."}
{:text "An orange light wanders from window to window."}
{:text "A sign here reads: 'As seen on TV."}
{:text "Endless amounts of blood pour from the windows."}
{:text "Looks inviting except for the corpses littering the lawn."}]}}
{:text "graveyard"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "There is a freshly laid grave nearby."}
{:text "There is an open grave nearby. It's empty."}
{:text "There is an open grave nearby. There's a phone book in it."}
{:text "There is an open grave nearby. It's full of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "There are fresh footprints here."}
{:text "A lazy mist drifts amongst the tombstones."}
{:text "The tombstones have been replaced by durable plastic bricks."}
{:text "All the graves are filled with Mr. Bubbles."}
{:text "The Christmas lights sure make it look festive."}
{:text "A disco ball spins lonely from a gnarled tree."}]}}
{:text "playground"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The equipment looks like it's never been used."}
{:text "Most of the equipment is missing or broken."}
{:text "You hear the sound of children laughing but no one else is here."}]}}
{:text "pile of diapers"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "Some of these look awfully familiar."}]}}
{:text "meeting"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The room is crowded by tripods holding colorful charts."}
{:text "The projector is on, showing random photos of cats at play."}
{:text "The table is covered with a chalk outline."}
{:text "The chairs are all occupied by cobweb-encrusted skeletons."}
{:text "The room is almost full of balloons."}]}}
{:text "Luby's"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "full-contact Bible study group"
:type :interior
:article "a"
:preps ["near" "behind" "in front of" "in"]
:follow-ups {:optional? true
:options [{:text "No one is here."}
{:text "They stare at you and begin to crowl."}
{:text "They're all covered with cuts and bruises."}
{:text "They're currently scrumming over a Bible."}]}}]})
(def dialogues
{:dialogues
[{:text "asks, 'Have you ever seen an elephant throw up?'"}
{:text "asks, 'Why am I holding this pitchfork?'"}
{:text "asks, 'How long is a man?'"}
{:text "asks, 'Where have you been?'"}
{:text "asks, 'Would you like to see my collection of tiny ceiling fans?'"}
{:text "asks, 'Which one are you?'"}
{:text "asks, 'Can I have a hug?'"}
{:text "asks, 'Are you following me?'"}
{:text "asks, 'Does it smell like %0 in here to you?'"
:subs {0 {:class :food}}}
{:text "asks, 'Have you got a flag?'"}
{:text "asks, 'Have you ever seen a grown man naked?'"}
{:text "asks, 'May I use your FAX machine?'"}
{:text "chants, 'It's time to pay the price.'"}
{:text "mumbles, 'You can't go up against city hall.'"}
{:text "mumbles, 'One day I'm going to burn this place to the ground.'"}
{:text "mumbles, 'Skrillex ruined it all for everybody.'"}
{:text "mumbles, 'I've never been to Belize.'"}
{:text "says, 'It's true: the boot is the best McNugget shape.'"}
{:text "says, 'Wrong answer, chief.'"}
{:text "says, 'This is giving me the freak-out.'"}
{:text "says, 'How unfortunate.'"}
{:text "says, 'Well that really scrambles my eggs.'"}
{:text "says, 'I've been waiting for you.'"}
{:text "says, 'I can't find my heirloom clown suit.'"}
{:text "says, 'I can't find my %0.'"
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "says, 'No money? No hamburger!'"}
{:text "says, 'It's like drinking a meatloaf!'"}
{:text "says, 'Took you long enough.'"}
{:text "says, 'I'm addicted to Kitty Lick III.'"}
{:text "says, 'Looks like I'm not having any mayonnaise.'"}
{:text "says, 'I'm a brown-belt in speed tai chi.'"}
{:text "says, 'I'm stuck in a poo loop.'"}
{:text "says, 'Well, that's a dead give away.'"}
{:text "says, 'If you asked me to have sex with you, I wouldn't say \"no\".'"}
{:text "says, 'I'm not an actor but I play one on television.'"}
{:text "says, 'That dog rode on a bus by itself."}
{:text "says, 'The time has come for me to deal with the fact that I'll never be Ed Begley, Jr.'"}
{:text "says, 'So I guess Kevin Spacey is going to be a thing now.'"}
{:text "says, 'I'm going to button up the top of my polo shirt to demonstrate I don't want to talk to you.'"}
{:text "says, 'I'm in a poo trance.'"}
{:text "says, 'I'm a source of fiber.'"}
{:text "says, 'Surrealism is the scourage of butane.'"}
{:text "says, 'This drink tastes like Sears!'"}
{:text "says, 'This teenager salad tastes like a slowly closing door.'"}
{:text "says, 'It never hurts to have a corpse open the door for you.'"}
{:text "says, 'The Swanson TV Dinner heard 'round the world.'"}
{:text "says, 'The membership card is edible.'"}
{:text "says, 'That bisexual really jazzed up my latte.'"}
{:text "shouts, 'You can't go up against city hall!'"}
{:text "shouts, 'You can't fold a cat!'"}
{:text "shouts, 'It keeps happening!'"}
{:text "shouts, 'They're having a brownout in Lagos!'"}
{:text "shouts, 'Don Quixote! Swingin' from a pipe!'"}
{:text "shrieks, 'What's this shit I keep hearing about erections?!'"}
{:text "shrieks, 'I'm living on the edge!'"}
{:text "shrieks, 'Boiled soil!'"}
{:text "shriefs, 'Baby-oil covered balloon animals for all!"}
{:text "sighs, 'I liked you better before the hip-replacement surgery.'"}
{:text "snarls, 'Siddown before ya fall down!'"}
{:text "whispers, 'Why are you talking in all lowercase?'"}
{:text "whispers, 'It puts the lotion on its skin...'"}
{:text "whispers, 'I've always wanted to be a creepy uncle.'"}
{:text "whispers, 'Fee was a Buddhist prodigy.'"}
{:text "whispers, 'There squats the brown clown.'"}
{:text "whispers, 'Sleep is unproductive and a waste of time.'"}
{:text "whispers, 'You just lost the game.'"}
{:text "yells, 'I warned you about stairs, bro! I told ya, dawg!'"}]})
(def thoughts
{:thoughts
[{:text "Why don't they put mayo in the can with the tuna?"}
{:text "%0 never has a second cup of coffee at home..."
:subs {0 {:class :person}}}
{:text "You can't go up against city hall."}
{:text "I've made a huge mistake."}
{:text "It's time to pay the price."}
{:text "Why don't they have Double Stuf Nutter Butters?"}
{:text "This'll all end in tears."}
{:text "Hey! But I didn't eat the mousse!"}
{:text "%0 still owes me a backrub."
:subs {0 {:class :person}}}
{:text "I wonder if I could forge us a Group 6 Access..."}]})
(def intonations
{:intonations
[{:text "Toast goes in the toaster."}
{:text "These pretzels are making me thirsty."}
{:text "For those who can make the journey, there is a place."}
{:text "Slightly uncomfortable pleasures."}
{:text "It is a winning cake."}
{:text "POKE 1024,0."}
{:text "Coitus?"}
{:text "Pave Canada."}
{:text "Your pilikia is all pau."}
{:text "The owls are not what they seem."}
{:text "Plugh."}
{:text "Zzyzx."}
{:text "Guch."}
{:text "Spigot."}
{:text "You sank my battleship."}
{:text "Sorry, but it couldn't be helped."}
{:text "Clean up in aisle 8A."}
{:text "Rabbit feces."}
{:text "Don't panic."}
{:text "Don't panic. Oh, all right. You can panic a little bit."}
{:text "Consider deeply the baked ham."}
{:text "You can't go up against city hall."}]})
(def signs
{:signs
[{:text "Burma shave!"}
{:text "It's time to pay the price."}
{:text "You can't go up against city hall."}
{:text "For those who can make the journey, there is a place."}
{:text "Here lies Hammerdog, a dog made of hammers."}
{:text "Here lies Knifekitten, a kitten made of knives."}
{:text "When you're not reading this, it's written in Spanish."}
{:text "Now you know how hard it is to say \"Irish wristwatch\"."}]})
(def books
{:books
[{:text "the Bible"
:preps ["a copy of"]}
{:text "Catcher in the Rye"
:preps ["a copy of"]}
{:text "Infinite Jest"
:preps ["a copy of"]}
{:text "Gravity's Rainbow"
:preps ["a copy of"]}
{:text "A Prayer for Owen Meany"
:preps ["a copy of"]}
{:text "The Hitchhiker's Guide to the Galaxy"
:preps ["a copy of"]}]})
(def attacks
{:attacks
[{:text "%0"
:subs {0 {:class :actor}}}
{:text "%0"
:subs {0 {:class :item}}}
{:text "a judo chop"}
{:text "a Judeo chop"}
{:text "a filthy soap slap"}
{:text "a rough kitty lick"}
{:text "a high clownkick"}
{:text "a sad testicle tug"}
{:text "a sushi pants special"}
{:text "a rub cut"}
{:text "a rusty trombone"}
{:text "an antiparticle dildo"}
{:text "a Cleveland steamer"}
{:text "a wet hug"}
{:text "a prison hug"}
{:text "a reverse hug"}
{:text "Canadian disapproval"}
{:text "a dangling participle"}
{:text "a fancy uppercut"}
{:text "a flurry of tiny kisses"}
{:text "a forlorn sigh"}
{:text "a balloon"}
{:text "a spontaneous coma"}
{:text "a smug kidney punch"}
{:text "a bit of the ol' in-out"}
{:text "a atomic wedge"}
{:text "Vogon poetry"}
{:text "a bad British accent"}
{:text "poor grammar"}
{:text "Conservative politics"}
{:text "Liberal politics"}
{:text "secret.jpg"}
{:text "tubgirl.jpg"}
{:text "cute kittens"}
{:text "tumbly puppies"}
{:text "a weaponized beard"}
{:text "an apathetic hipster"}]})
(def directions
{:directions
[{:text "north"}
{:text "northeast"}
{:text "east"}
{:text "southeast"}
{:text "south"}
{:text "southwest"}
{:text "west"}
{:text "northwest"}]})
(def persons
{:persons
[{:text "Samuel L. Jackson"
:gender :male}
{:text "Rob Lowe"
:gender :male}
{:text "Lloyd Braun"
:gender :male}
{:text "Bradley Whitford"
:gender :male}
{:text "Josh Malina"
:gender :male}
{:text "David Lynch"
:gender :male}
{:text "Allison Janney"
:gender :female}
{:text "Stephen Fry"
:gender :male}
{:text "Hugh Laurie"
:gender :male}
{:text "Stephen Colbert"
:gender :male}
{:text "Frances McDormand"
:gender :female}
{:text "Whoopi Goldberg"
:gender :female}
{:text "Katy Perry"
:gender :female}
{:text "Justin Bieber"
:gender :male}
{:text "Neil deGrasse Tyson"
:gender :male}
{:text "Tim Heidecker"
:gender :male}
{:text "Eric Wareheim"
:gender :male}
{:text "Jim J. Bullock"
:gender :male}
{:text "Johnny Cash"
:gender :male}
{:text "a police officer"
:gender :male}
{:text "Alex Trebek"
:gender :male}
{:text "Craig Ferguson"
:gender :male}
{:text "Geoff Petersen"
:gender :male}
{:text "Nancy Grace"
:gender :female}
{:text "Lindsay Lohan"
:gender :female}
{:text "Ruth Buzzi"
:gender :female}
{:text "Jennifer Lawrence"
:gender :female}
{:text "Tilda Swinton"
:gender :female}
{:text "Peter Dinklage"
:gender :male}
{:text "Brad Pitt"
:gender :male}
{:text "Bill Maher"
:gender :male}
{:text "Grace Jones"
:gender :female}
{:text "Bill Murray"
:gender :male}
{:text "your mom"
:gender :female}
{:text "a bunch of kids"
:gender :group}
{:text "a crowd of Yoga enthusiasts"
:gender :group}
{:text "George Clooney"
:gender :male}
{:text "James Franco"
:gender :male}
{:text "Jonah Hill"
:gender :male}
{:text "a gas station attendant"
:gender :male}
{:text "Craig T. Nelson"
:gender :male}
{:text "Thomas Pynchon"
:gender :male}
{:text "Drew Olanoff"
:gender :male}
{:text "Louis Gray"
:gender :male}
{:text "@akiva"
:gender :male}
{:text "@jimminy"
:gender :male}
{:text "@veo_"
:gender :male}
{:text "@vmcny"
:gender :male}
{:text "@KamenPrime"
:gender :male}
{:text "@ActuallySparky"
:gender :male}
{:text "@neonbubble"
:gender :male}
{:text "@micahwittman"
:gender :male}
{:text "@itafroma"
:gender :male}
{:text "@clive"
:gender :male}
{:text "@mokargas"
:gender :male}
{:text "@drew"
:gender :male}
{:text "Bob Sacamano"
:gender :male}
{:text "Zombie Hunter Thompson"
:gender :male}
{:text "Zombie Carl Sagan"
:gender :male}]})
(def actions
{:actions
[{:text "attacks"}
{:text "sneezes on"}
{:text "ignores"}
{:text "tickles"}
{:text "stands uncomfortably close to"}
{:text "violently points at"}
{:text "imitates"}
{:text "pets"}
{:text "examines"}
{:text "flirts with"}]})
(def adjectives
{:adjectives
[{:text "worried"}
{:text "relieved"}
{:text "aroused"}
{:text "afraid"}
{:text "nonplussed"}
{:text "sleepy"}
{:text "hungry"}
{:text "thirsty"}
{:text "bored"}
{:text "hopeful"}
{:text "sad"}
{:text "happy"}
{:text "forlorn"}
{:text "angry"}]})
(def adverbs
{:adverbs
[{:text "carefully"}
{:text "wistfully"}
{:text "uncertainly"}
{:text "willfully"}
{:text "lustfully"}
{:text "warily"}
{:text "solemnly"}
{:text "mournfully"}
{:text "proudly"}
{:text "bravely"}
{:text "sadly"}
{:text "happily"}
{:text "balefully"}]})
(def scents
{:scents
[{:text "acrid"}
{:text "sweet"}
{:text "sour"}
{:text "rotten"}
{:text "nice"}
{:text "foul"}
{:text "of feet"}
{:text "of your grandfather's hair cream"}
{:text "of warm peanut butter"}
{:text "bitter"}
{:text "smoky"}
{:text "gross"}
{:text "pleasant"}]})
(def diagnoses
{:diagnoses
[{:text "feeling great"}
{:text "feeling gross"}
{:text "absurdly sticky"}
{:text "lightly wounded"}
{:text "moderately wounded"}
{:text "heavily wounded"}
{:text "near death"}
{:text "sleepy"}
{:text "drunk"}
{:text "stoned"}
{:text "confused"}
{:text "hungry"}
{:text "thirsty"}
{:text "temporarily blind"}
{:text "temporarily deaf"}
{:text "covered in bees"}]})
(def foods
{:foods
[{:text "burrito"
:article "a"}
{:text "weaponized cornbread"
:article "some"}
{:text "persecution sandwich"
:article "a"}
{:text "tooth burger"
:article "a"}
{:text "bouquet of corndogs"
:article "a"}
{:text "corndog"
:article "a"}
{:text "pancakes"
:article "some"}
{:text "cake"
:article "a"}
{:text "cake"
:article "a slice of"}
{:text "kumquat"
:article "a"}
{:text "salad"
:article "a"}
{:text "Rice Chex"
:article "a bowl of"}
{:text "Reese's Peanut Butter Cup"
:article "a"}
{:text "apple pocket"
:article "an"}
{:text "block of cheese"
:article "a"}
{:text "wedge of cheese with some mold on it"
:article "a"}
{:text "slice of fried spam"
:article "a"}
{:text "delicious churro"
:article "a"}
{:text "chocolate bobka"
:article "a"}
{:text "sweetroll"
:article "a"}
{:text "Cinnabon"
:article "a"}
{:text "duck confit"
:article "some"}
{:text "pasta"
:article "some"}
{:text "uncooked rice"
:article "some"}
{:text "Fritos"
:article "some"}
{:text "sushi"
:article "some"}
{:text "apple cinnamon Pop Tart"
:article "an"}]})
(def drinks
{:drinks
[{:text "steaming gravy"
:article "a cup of"}
{:text "milk"
:article "a gallon of"}
{:text "orange juice"
:article "a glass of"}
{:text "tea"
:article "some"}
{:text "soda"
:article "some"}
{:text "water"
:article "some"}
{:text "beef broth"
:article "some"}
{:text "scotch"
:article "a"}]})
(def garments
{:garments
[{:text "hat"
:article "a"}
{:text "pants"
:article "some"}
{:text "shirt"
:article "a"}
{:text "gloves"
:article "some"}
{:text "shoes"
:article "some"}
{:text "belt"
:article "a"}
{:text "socks"
:article "some"}
{:text "coat"
:article "a"}
{:text "jacket"
:article "a"}
{:text "underwear"
:article "some"}
{:text "dress"
:article "a"}
{:text "skirt"
:article "a"}
{:text "schizophrenic mood ring"
:article "a"}
{:text "sweater"
:article "a"}
{:text "watch"
:article "a"}]})
(def items
{:items
[{:text "skinny jeans"
:article "a pair of"}
{:text "slick pellets"
:article "a bag of"}
{:text "fat-soluble Jesus"
:article "a bottle of"}
{:text "llama treats"
:article "a bag of"}
{:text "parachute pants"
:article "a pair of"}
{:text "Breakin' 2: Electric Boogaloo"
:article "a Laserdisc copy of"}
{:text "magic scroll"
:article "a"}
{:text "no tea"}
{:text "Snausages"
:article "some"}
{:text "slide rule"
:article "a"}
{:text "pinecone"
:article "a"}
{:text "sweat-incrusted trilby"
:article "a"}
{:text "vitamins"
:plural true
:article "some"}
{:text "bucket of corks"
:article "a"}
{:text "jean shorts"
:article "a pair of"}
{:text "non-Euclidian Lego"
:article "a"}
{:text "spray-on bacon"
:article "a can of"}
{:text "spackle"
:article "a can of"}
{:text "unfamiliar briefcase"
:article "an"}
{:text "towel from the Las Vegas Radisson"
:article "a"}
{:text "receipt from a bunny outfit rental"
:article "a"}
{:text "floppy disk"
:article "a"}
{:text "pencil"
:article "a"}
{:text "lantern"
:article "a"}
{:text "elven sword"
:article "an"}
{:text "books"
:article "some"}
{:text "movie ticket"
:article "a"}
{:text "newspaper"
:article "a"}
{:text "kitten"
:article "a"}
{:text "puppy"
:article "a"}
{:text "bag of potatoes"
:article "a"}
{:text "bag of rice"
:article "a"}
{:text "giant styrofoam peanut"
:article "a"}
{:text "phone book"
:article "a"}
{:text "pyramid of tennis balls"
:article "a"}
{:text "deflated soccer ball"
:article "a"}
{:text "fourth grade report card"
:article "your"}
{:text "half-eaten sandwich"
:article "a"}
{:text "signed photograph of Richard Moll"
:article "a"}
{:text "hipster t-shirt"
:article "a"}
{:text "pile of discarded puppets"
:article "a"}
{:text "wet Lincoln Log"
:article "a"}
{:text "VHS tape covered in blood"
:article "a"}]})
(def animals
{:animals
[{:text "kitten"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "cat"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "puppy"
:article "a"
:sounds ["pants" "barks" "growls" "whimpers"]
:adjectives ["panting" "barking" "growling" "whimpering"]}
{:text "duck"
:article "a"
:sounds ["quacks"]
:adjectives ["quacking"]}
{:text "marmot"
:article "a"}
{:text "tiger"
:article "a"
:sounds ["roars"]
:adjectives ["roaring"]}
{:text "hamster"
:article "a"}
{:text "gerbil"
:article "a"}
{:text "hedgehog"
:article "a"}]})
(def noises
{:noises
[{:text "foghorn"
:article "a"}
{:text "laughter"
:article "some"}
{:text "laughing"
:article "somebody"}
{:text "chuckling"
:article "someone"}
{:text "cackling"
:article "someone"}
{:text "crying"
:article "someone"}
{:text "sobbing"
:article "someone"}
{:text "sneeze"
:article "a"}
{:text "wolves howling"}
{:text "ice cream truck"
:article "an"}
{:text "door slam"
:article "a"}
{:text "sinister chuckle"
:article "a"}]})
(def disasters
{:disasters
[{:text "fire"
:article "a"}
{:text "tornado"
:article "a"}
{:text "hurricane"
:article "a"}
{:text "flood"
:article "a"}
{:text "tsunami"
:article "a"}
{:text "landslide"
:article "a"}
{:text "avalanche"
:article "an"}
{:text "radioactive leak"
:article "a"}
{:text "lava flow"
:article "a"}
{:text "sandstorm"
:article "a"}
{:text "lightning strike"
:article "a"}
{:text "plague of locusts"
:article "a"}
{:text "snowstorm"
:article "a"}
{:text "duststorm"
:article "a"}]})
(def obstacles
{:obstacles
[{:text "a black comb on the ground"}
{:text "a stack of dogs going all the way to the moon"}
{:text "Steve Buscemi's grin"}
{:text "an obstinant balloon expert"}
{:text "a pile of corroded Ewoks"}
{:text "a horrible taste in your mouth"}
{:text "a movie being shown in the wrong aspect ratio"}
{:text "someone who has never listened to Neutral Milk Hotel"}
{:text "the thing your aunt gave you which you don't know what it is"}
{:text "an aquarium full of milk"}
{:text "dubstep"}
{:text "a 404 error"}
{:text "Adam Sandler's career"}
{:text "that awful man"}
{:text "a dude who insists on putting his hand in his girlfriend's back pocket"}
{:text "a maelstrom of hipster beards"}
{:text "a wall of tepid soup"}
{:text "a giant cat tongue"}
{:text "George Lucas' neck"}
{:text "Ruby On Rails"}
{:text "someone who takes too many selfies"}
{:text "a cat who has been pet against the grain"}
{:text "substandard prequels"}
{:text "the Scut Farkus Affair"}
{:text "a lack of retweets"}
{:text "a sweaty 486DX4 chip"}
{:text "a convenient reclosing tab"}
{:text "a lengthy German noun"}
{:text "your own unwillingness to improve yourself"}
{:text "%0's sheer force of will"
:subs {0 {:class :person}}}
{:text "%0's birthday party"
:subs {0 {:class :person}}}
{:text "a delicious Nutter Butter"}
{:text "double-double Animal style"}
{:text "someone who doesn’t know how to eat a goddamned Oreo properly"}]})
(def news
{:news
[{:text "Shamer Claims Bullying from Shame Shamers"}]})
(def games
{:games
[{:text "Agricola"
:type :tabletop}
{:text "Advanced Squad Leader"
:type :tabletop}
{:text "Carcassonne"
:type :tabletop}
{:text "World in Flames"
:type :tabletop}
{:text "Monopoly"
:type :tabletop}
{:text "World of Warcraft"
:type :video}
{:text "Civilization V"
:type :video}
{:text "Grand Theft Auto V"
:type :video}]})
(def classes
["events"
"location-events"
"action-events"
"secondary-events"
"tertiary-events"
"actor-actions"
"locations"
"dialogues"
"intonations"
"books"
"directions"
"persons"
"actions"
"adjectives"
"adverbs"
"scents"
"diagnoses"
"foods"
"drinks"
"signs"
"obstacles"
"garments"
"items"
"animals"
"noises"
"attacks"
"games"
"thoughts"
"news"
"disasters"])
| 118350 | (ns xyzzwhy.text)
;; This text presents source material for xyzzwhy's original corpus. Each
;; class (such as :location-events or :obstacles) is a map containing map
;; fragments the minimal requirement of which is a :text key.
;;
;; A fragment's :text value can contain a number of substitutions represented
;; by %0-%n. These require a :subs map which contains a key for each substitution.
;; These must contain at least a :class reference which is keyed to another
;; class. These are randomly chosen by xyzzwhy and then interpolated into the
;; fragment's :text. A substitution can also contain a :config map which has
;; options to skip the automatic prepending of prepositions and/or articles; and
;; the ability to ensure that an actor sub is a single person and not a group.
;; More config options will be added later.
;;
;; A fragment may also have follow-ups which may be marked as :optional?. A list of
;; options follows which is a vector of fragments which themselves may have :subs.
;; These subs must begin their %x count +1 from what's in the parent fragment's :text.
;; Each follow-up option's sub may contain a :ref key which allows it to refer to
;; a substitution from the parent fragment's text. For example, to use a pronoun
;; for a person class substitution at %0, the follow-up's substitution would :ref 0.
;;
;; Object classes and locations also have an :article and :preps for prepositions.
;; Locations have a :type which is either :interior or :exterior.
;; Actors have a :gender (:male, :female, or :group).
;;
;; Animals have :sounds (e.g., a kitten might purr or meow) and :adjectives
;; such as a 'whimpering' for a puppy.
;;
;; Future classes might have their own special keys and options.
(def events
{:events [:location-event :action-event]})
(def location-events
{:location-events
[{:text "You have entered %0."
:subs {0 {:class :location
:config #{:no-prep}}}}
{:text "You are serving jury duty."
:follow-ups {:optional? false
:options [{:text "The prosecuting attorney insists on speaking through a broken bullhorn."}
{:text "They hand out <NAME> but they're stone cold."}
{:text "The judge is dressed like Dr. <NAME>."}
{:text "You're unsure why they insist the jury sit in a vat of carbonated %0."
:subs {0 {:class :drink :config #{:no-article}}}}]}}
{:text "After %0 at your %1, you are relocated by FEMA to %2."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep :no-article}}
2 {:class :location :config #{:no-prep}}}}
{:text "You arrive for your first day at college only to find your roommate is %0."
:subs {0 {:class :actor}}}
{:text "You try to go %0 but your way is blocked by %1."
:subs {0 {:class :direction}
1 {:class :obstacle}}}
{:text "%0 prevents you from going %1 to %2."
:subs {0 {:class :obstacle}
1 {:class :direction}
2 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and find yourself at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and emerge %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You walk %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You cripwalk %0 to %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You strut %0 and end up %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "A double bounce on a trampoline lands you %0."
:subs {0 {:class :location}}}
{:text "You head %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "Google Maps leads you to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow %0 to %1."
:subs {0 {:class :actor}
1 {:class :location :config #{:no-prep}}}}
{:text "You are %0."
:subs {0 {:class :location}}}
{:text "You're %0."
:subs {0 {:class :location}}}
{:text "You run screaming into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You tunnel through the soil and pop up %0."
:subs {0 {:class :location}}}
{:text "You emerge %0."
:subs {0 {:class :location}}}
{:text "You arrive %0."
:subs {0 {:class :location}}}
{:text "You are magically teleported to %0!"
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The drugs are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "The spell effects are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "You are standing %0 of %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You stumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You come across %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow the treasure map to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You wake up from an odd dream. You are %0."
:subs {0 {:class :location}}}
{:text "You open the secret door only to see %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You find yourself %0."
:subs {0 {:class :location}}}
{:text "Dazed, you climb out of the dryer. You are %0."
:subs {0 {:class :location}}}
{:text "After the shoot-out, you make your escape to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The bridge game turned violent so you went to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You start doing the worm until you find yourself %0."
:subs {0 {:class :location}}}
{:text "You wake up %0."
:subs {0 {:class :location}}}
{:text "You climb down a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "You climb up a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "The taxi driver randomly drops you off %0."
:subs {0 {:class :location}}}
{:text "The metro bus unceremoniously dumps you %0."
:subs {0 {:class :location}}}
{:text "The fog clears and you find yourself %0."
:subs {0 {:class :location}}}
{:text "Your parachute gently plops you %0."
:subs {0 {:class :location}}}
{:text "You jump out of a moving car, roll down a hill, and find yourself %0."
:subs {0 {:class :location}}}
{:text "After walking for a long time, you find yourself %0."
:subs {0 {:class :location}}}
{:text "You find your way blindly and end up %0."
:subs {0 {:class :location}}}
{:text "No matter how hard you try, you still end up %0."
:subs {0 {:class :location}}}
{:text "You climb out of the treasure chest. You are now %0."
:subs {0 {:class :location}}}
{:text "You come to %0."
:subs {0 {:class :location}}}
{:text "You follow a winding path %0 only to find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You follow a sloping path %0. You find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You climb up a flight of stairs. You are now %0."
:subs {0 {:class :location}}}
{:text "You shuffle down a flight of stairs and enter %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You fall down a flight of stairs and into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The elevator doors open to reveal %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "Using a vine to swing across the pit, you land %0."
:subs {0 {:class :location}}}
{:text "The trapdoor drops open beneath you and you land %0."
:subs {0 {:class :location}}}
{:text "You flip the Game Select selector and find yourself %0."
:subs {0 {:class :location}}}
{:text "You blow into the cartridge too hard and are teleported to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You step through a magic mirror and end up %0."
:subs {0 {:class :location}}}
{:text "You get tangled up in a revolving door. You stumble out into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "After scrambling through some dense underbrush, you find yourself %0."
:subs {0 {:class :location}}}
{:text "After pushing your way through a dense crowd, you arrive %0."
:subs {0 {:class :location}}}
{:text "You squeeze out of the sewage outflow and tumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "A tornado deposits you %0."
:subs {0 {:class :location}}}
{:text "Right on cue, you pop up out of the jack-in-the-box. You're %0."
:subs {0 {:class :location}}}
{:text "After being shot out of a cannon, you land %0."
:subs {0 {:class :location}}}
{:text "You slide down a fireman's pole and land %0."
:subs {0 {:class :location}}}
{:text "Hands on your hips, you survey %0 %1."
:subs {0 {:class :location :config #{:no-prep}}
1 {:class :adverb}}}
{:text "You wake up in front of %0's house. You have no clue how you got there."
:subs {0 {:class :person}}}
{:text "You ride %0 to %1."
:subs {0 {:class :animal}
1 {:class :location :config #{:no-prep}}}}
{:text "You fall through the ceiling and land %0."
:subs {0 {:class :location}}}
{:text "The drugs are starting to take hold. Casually you saunter over to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The merry-go-round spins faster and faster until you're flung off and land %0."
:subs {0 {:class :location}}}]})
(def action-events
{:action-events
[{:text "You awake from a nightmare. You saw yourself %0. The corpse of %1 was there, holding %2."
:subs {0 {:class :location}
1 {:class :person :config #{:no-groups}}
2 {:class :item}}}
{:text "%0 arrives from the %1, carrying %2."
:subs {0 {:class :actor :config #{:no-groups}}
1 {:class :direction}
2 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You pick up %0 and hold it close to your chest."
:subs {0 {:class :item}}}
{:text "The radio crackles to life."
:follow-ups {:optional? false
:options [{:text "It sounds like someone with a cold is eating <NAME>." }
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Ketchup begins seeping through the speaker holes."}
{:text "It continues to crackle to life. It's still crackling. It's on fire."}
{:text "An announcer shouts, 'They found rice on Mars!"}
{:text "A news report is on about %0 %1."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep}}}}
{:text "%0 solemnly '%1'"}]}}
{:text "%0 drops %1, looks at you %2, then leaves."
:subs {0 {:class :actor}
1 {:class :item}
2 {:class :adverb}}}
{:text "You check your messages."
:follow-ups {:optional? false
:options [{:text "%0 %1"
:subs {0 {:class :person :config #{:no-groups}}
1 {:class :dialogue}}}]}}
{:text "You read morning paper."
:follow-ups {:optional? false
:options {:text "%0"
:subs {0 {:class :news}}}}}
{:text "%0 gently places %1 on the ground and then backs away slowly."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 %1 %2."
:subs {0 {:class :actor}
1 {:class :action}
2 {:class :actor}}}
{:text "%0 %1 you."
:subs {0 {:class :actor}
1 {:class :action}}}
{:text "%0 drops %1 here."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 does a little jig. 'Bidibidibidi, wanna dance?'"
:subs {0 {:class :actor}}}
{:text "%0 marches up to you and says, 'Hello please.'"
:subs {0 {:class :person}}}
{:text "%0 starts breakdancing and won't stop no matter how much you scream."
:subs {0 {:class :person}}}
{:text "%0 attacks you and knocks you out. You awake sometime later %1."
:subs {0 {:class :actor}
1 {:class :location}}}
{:text "%0 attacks you but you fight back with %1,"
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "winning the battle."}
{:text "taking only a hit to your pride."}]}}
{:text "%0 attacks you but you fight back with %1."
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "It isn't enough: you lose."}
{:text "This scares the shit out of %2. %3 runs away."
:subs {2 {:ref 0
:class :gender
:case :objective}
3 {:ref 0
:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You execute %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "You are victorious!"}
{:text "You have been killed."}
{:text "You have been slain!"}
{:text "%0 keels over all dead and stuff."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You respond with %2. You are defeated."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}}
{:text "%0 attacks with %1. You strike back with %2. FATALITY. But who?!"
:subs {0 {:class :actor}
1 {:class :attack}}}
{:text "%0 attacks with %1. You with %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "Look at you what with the killing and all."}
{:text "%0 is a bloodstain."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "Suddenly you're in freeze-frame as the credits roll."}
{:text "%0 appears in a puff of smoke, %1"
:subs {0 {:class :person}
1 {:class :actor-action}}}
{:text "You startle %0 who drops %1 and runs away."
:subs {0 {:class :person}
1 {:class :item}}}
{:text "%0 slams down a half-empty glass of %1."
:subs {0 {:class :person}
1 {:class :drink :config #{:no-prep :no-article}}}
:follow-ups {:optional? false
:options [{:text "'All this nonsense about %0 needs to stop! I can't take it anymore!'"
:subs {0 {:class :item}}}
{:text "'They're making plans for Nigel! They want what's best for him!'"}
{:text "'You can't go up against city hall!'"}
{:text "'I just can't take you seriously anymore!'"}
{:text "'MOM?!'"}]}}
{:text "%0 suddenly shrieks."
:subs {0 {:class :person}}}
{:text "%0 makes a rude noise, points surreptitiously to %1 nearby."
:subs {0 {:class :person}
1 {:class :animal}}}
{:text "You get tired of waiting for";
:follow-ups {:optional? false
:options [{:text "your Uber and decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "your private jet so you decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "the all-you-can-eat-buffet to open so you walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}]}}
{:text "The phone rings."
:follow-ups {:optional? false
:options [{:text "%0 stares at it %1. Eventually the ringing stops."
:subs {0 {:class :person}
1 {:class :adverb}}}
{:text "%0 watches as it starts to melt, the sound of the ring slowing and burbling to a stop."
:subs {0 {:class :person}}}
{:text "%0 picks it up, listens a moment, shrieks, and slams the phone down again."
:subs {0 {:class :person}}}
{:text "%0 picks it up, says, 'It's for you,' but you're longer there."
:subs {0 {:class :person}}}]}}
{:text "You start eating %0 and don't stop until you're done."
:subs {0 {:class :food}}}
{:text "You eat %0."
:subs {0 {:class :food}}
:follow-ups {:optional? true
:options [{:text "%0 looks on %1."
:subs {0 {:class :actor}
1 {:class :adverb}}}]}}
{:text "You think to yourself, '%0'"
:subs {0 {:class :thought}}}
{:text "You pause and think, '%0'"
:subs {0 {:class :thought}}}
{:text "You feel a little famished so you eat %0."
:subs {0 {:class :food}}}
{:text "You take a sip of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "You check your inventory."
:follow-ups {:optional? true
:options [{:text "You are empty-handed."}
{:text "You are carrying %0, %1, and %2."
:subs {0 {:class :item}
1 {:class :item}
2 {:class :item}}}
{:text "You have %0 and %1."
:subs {0 {:class :item}
1 {:class :item}}}]}}
{:text "You open up %0."
:subs {0 {:class :book}}
:follow-ups {:optional? false
:options [{:text "Someone has scribbled all over the margins. You throw it down on the floor in disgust."}
{:text "Someone has left a recipe for beef stew inside."}
{:text "You read a bit before tossing it over your shoulder and then doing the electric slide."}]}}
{:text "%0 suddenly appears out of the shadows and"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "hisses at you, then scrambles away like a spider."}
{:text "says, 'Oh, sorry about that,' then retreats back into the shadows."}
{:text "says, '%0 will see you now,' then slowly retreats back into the shadows."
:subs {0 {:class :actor}}}]}}
{:text "%0 picks up %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "An overhead loudspeaker crackles to life,"
:follow-ups {:optional? false
:options [{:text "'Citizen! Report immediately to the nearest oddly-angled inner tube.'"}
{:text "'Citizen! Report immediately to the nearest self-incrimination booth.'"}
{:text "'Citizen! Report immediately to the nearest Java stacktrace.'"}
{:text "'Citizen! Report immediately to the bean simulator.'"}
{:text "'Citizen! Report immediately to the nearest certified manhole.'"}
{:text "'Citizen! Report immediately to the National Baby Oil Slip-n-Slide.'"}
{:text "'Citizen! Report immediately to the Hall of Uncomfortable Touching.'"}
{:text "'Citizen! Report immediately to the Bakery of Unravelled Cinnamon Buns.'"}
{:text "'Citizen! Stop that.'"}
{:text "'Citizen! Report immediately to the Readers' Digest Condensation Camp.'"}
{:text "'Citizen! Open up your textbook and turn to the chapter concerning your death.'"}
{:text "'Citizen! Report immediately to the Out-of-Control Rototiller Museum.'"}
{:text "'Citizen! Report immediately to the nearest mandatory prison hug.'"}
{:text "'Citizen! Report immediately to the nearest sanctioned dogpile.'"}
{:text "'Citizen! Report immediately to the nearest full-contact Bible study group.'"}
{:text "'Citizen! Report immediately to the mannequin factory.'"}
{:text "'Citizen! Report immediately to The Garbagerie.'"}
{:text "'Citizen! Report immediately to Stall #3.'"}
{:text "'Citizen! Just shut up already.'"}]}}
{:text "An overhead loudspeaker crackles to life. The announcement is completely garbled. The loudspeaker switches off with a squawk."}
{:text "You start spinning around and around."
:follow-ups {:optional? false
:options [{:text "%0 looks unimpressed."
:subs {0 {:class :person}}}
{:text "%0 faints."
:subs {0 {:class :person}}}
{:text "You drill straight into the crust of the earth."}
{:text "You gracefully lift off into a blue sky."}
{:text "You gracefully lift off into a blue sky never to be seen again."}
{:text "You gracefully lift off, go sideways, and crash into a building."}]}}
{:text "You start spinning around and around while"
:follow-ups {:optional? false
:options [{:text "%0 claps and cheers."
:subs {0 {:class :person}}}
{:text "%0 cries and points."
:subs {0 {:class :person}}}
{:text "%0 writes furiously on a clipboard."
:subs {0 {:class :person}}}
{:text "%0 beams with pride."
:subs {0 {:class :person}}}]}}
{:text "%0 is calling from %1 asking for %2."
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}
2 {:class :item}}}
{:text "%0 is calling from %1"
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}}
:follow-ups {:optional? false
:options [{:text "asking if %2 can come out and play."
:subs {2 {:class :person}}}]}}
{:text "You peek out the window."
:follow-ups {:optional? true
:options [{:text "%0 is messing around with your mailbox. You crouch in fear."
:subs {0 {:class :person}}}
{:text "%0 is laying facedown in your flowerbed. You sink to your knees with worry."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's on fire."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's covered in bees."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. The line stretches around the block."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand across the street. You feel oddly jealous."
:subs {0 {:class :person}}}
{:text "%0 is struggling to start a chainsaw while staring at you. You bite your knuckle."
:subs {0 {:class :person}}}
{:text "%0 is standing in your yard, painting a portrait of you peeking out the window."
:subs {0 {:class :person}}}
{:text "Your entire house has been encased in a giant stone column."}]}}
{:text "In the distance,"
:follow-ups {:optional? false
:options [{:text "you hear %0 let the bass drop."
:subs {0 {:class :person}}}
{:text "you hear %0 drop the mic."
:subs {0 {:class :person}}}
{:text "you hear %0 get wicked."
:subs {0 {:class :person}}}
{:text "you hear %0 shake it off."
:subs {0 {:class :person}}}]}}
{:text "A magician saws you in half... lengthwise."}
{:text "You check your health: you are %0."
:subs {0 {:class :diagnose}}}
{:text "You find yourself being slowly teleported away. Very slowly. People are beginning to stare."}]})
(def secondary-events
{:secondary-events
[{:text "You see %0 here."
:subs {0 {:class :item}}}
{:text "You see %0 here. It looks oddly familiar."
:subs {0 {:class :item}}}
{:text "There is %0 here."
:subs {0 {:class :item}}}
{:text "You pick up %0. It's covered in dust."
:subs {0 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You drop %0 here."
:subs {0 {:class :item}}
:follow-ups {:optional? true
:options [{:text "It bursts into flames."}
{:text "It turns into a wisp of smoke."}
{:text "And then some really bad CGI happens."}
{:text "It pierces the crust of the Earth."}
{:text "It bounces right back into your hand."}]}}
{:text "You find %0 here. You back away %1."
:subs {0 {:class :item}
1 {:class :adjective}}}
{:text "%0 is here."
:subs {0 {:class :actor}}}
{:text "%0 is here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "You find %0 here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "%0 %1"
:subs {0 {:class :person}
1 {:class :dialogue}}}
{:text "%0 is here searching for %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 is here with %1. They look %2."
:subs {0 {:class :actor}
1 {:class :actor}
2 {:class :adjective}}}
{:text "%0 follows you."
:subs {0 {:class :actor}}}
{:text "%0 slinks up behind you."
:subs {0 {:class :actor}}}
{:text "%0 wanders by,"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "doing algebra and shit."}
{:text "playing a recorder."}
{:text "jamming on a mouth organ."}
{:text "wearing a cape."}
{:text "casually on fire."}
{:text "followed by a classy balloon."}
{:text "whistling the theme to the Andy Griffith Show."}
{:text "whistling the theme to the Garry Shandling Show."}]}}
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Something smells %0 here."
:subs {0 {:class :scent}}}
{:text "It smells %0."
:subs {0 {:class :scent}}}
{:text "You hear %0 in the distance."
:subs {0 {:class :noise}}}
{:text "You hear the sound of %0 nearby."
:subs {0 {:class :noise}}}
{:text "The wind howls in the distance."}
{:text "It appears abandoned."}
{:text "Someone has been here recently."}
{:text "There are fresh footprints here."}
{:text "It seems that no one has been here for a long time."}
{:text "Someone has attached marionnette wires to your hands, feet, and head."}
{:text "Someone has left a running bulldozer here."}
{:text "The words 'eat dulp' are spray-painted on a wall here."}
{:text "The words 'Knifekitten lives!' are spray-painted on a wall here."}
{:text "The words 'Hammerdog lives!' are spray-painted on a wall here."}
{:text "Spray-painted on the wall here are the words 'Alice?! Alice?! Who the f...'. The rest is illegible."}
{:text "An ice cream truck goes by. It's on fire."}
{:text "A fire truck goes by. It's covered in ice."}
{:text "There has been significant damage from %0."
:subs {0 {:class :disaster}}}
{:text "You see a sign here. On it is written '%0'"
:subs {0 {:class :sign}}}]})
(def tertiary-events
{:tertiary-events
[{:text "You aren't wearing any clothes."}
{:text "Your clothes feel too small."}
{:text "Your clothes feel too loose."}
{:text "You're certain these aren't your clothes."}
{:text "Your shoes are on the wrong feet."}
{:text "Your tie feels uneven."}
{:text "You're wearing two bowties for some reason."}
{:text "You're not wearing any underwear."}
{:text "You're wearing two pairs of underwear."}
{:text "Someone is struggling with warped Tupperware nearby."}
{:text "You do a little jig and then whistle."}
{:text "You clap once."}
{:text "You have socks on your hands."}
{:text "You slowly slide your hands into your pockets. You regret this immediately."}
{:text "You feel serene."}
{:text "You feel nervous."}
{:text "You feel anxious."}
{:text "You feel cold."}
{:text "You feel warm."}
{:text "You aren't alone."}
{:text "You blink really slowly."}
{:text "You find yourself humming the theme to Too Many Cooks."}
{:text "You hear gunfire in the distance."}
{:text "You hear a party in the distance."}
{:text "You hear a toilet flush nearby."}
{:text "Someone is having fun against their will nearby."}
{:text "You yawn."}
{:text "You sneeze."}
{:text "You cough."}
{:text "You chuckle to yourself."}
{:text "You practice frowning for awhile."}
{:text "You begin to smile uncontrollably."}
{:text "You wish you had your grandpappy's harmonica."}
{:text "You are starting to feel sleepy."}
{:text "You glance at your watch; you're running 15 minutes late."}
{:text "You glance at your watch; somehow, you're still on time."}
{:text "You glance at your watch; you're a little ahead of schedule."}
{:text "You spend a few moments thinking fondly about your teeth."}
{:text "You feel as if you're being followed."}
{:text "A warm breeze blows by."}
{:text "A cool breeze blows by."}
{:text "It starts to rain."}
{:text "It starts to snow."}
{:text "Thunder coughs gently in the distance."}
{:text "A basketball bounces by."}
{:text "Something nearby is on fire."}
{:text "You can smell something burning in the distance."}
{:text "You look around nervously."}
{:text "You spot a balloon stuck in a tree."}
{:text "You spot a kitten stuck in a tree."}
{:text "You spot an office desk in a tree."}
{:text "You spot a bonsai tree stuck in a regular tree."}
{:text "You see a pair of sneakers dangling on a utility line overhead."}
{:text "Someone nearby is repeatedly zipping and unzipping a duffel bag."}
{:text "Somehow, you've lost your %0."
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "You hear someone nearby typing away on a manual typewriter."}
{:text "You're catching your second wind."}
{:text "You are starting to feel thirsty."}
{:text "You feel better."}
{:text "You have died."}
{:text "You are starting to feel hungry."}]})
(def actor-actions
{:actor-actions
[{:text "looking %0."
:subs {0 {:class :adjective}}}
{:text "being chased by a swarm of balloon animals."}
{:text "being chased by %0."
:subs {0 {:class :person}}}
{:text "being chased by %0 which is attached to them by a string."
:subs {0 {:class :item}}}
{:text "dancing furiously."}
{:text "dancing extremely slowly."}
{:text "shouting at an imaginary helicopter."}
{:text "doing the Kenosha Kid."}
{:text "thinking %0 about %1."
:subs {0 {:class :adverb}
1 {:class :actor}}}
{:text "being chased around by a bee."}
{:text "defiantly eating Scrabble tiles, one by one."}
{:text "%0 playing the organ."
:subs {0 {:class :adverb}}}
{:text "organizing matches."}
{:text "having a Guru Meditation Error."}
{:text "juggling some balls."}
{:text "dancing in a little circle."}
{:text "stooping up and down like a rapper in concert."}
{:text "drooling uncontrollably."}
{:text "clutching a DVD of Dot & the Kangaroo."}
{:text "clutching a DVD of BMX Bandits."}
{:text "wearing an eyepatch."}
{:text "wearing two eyepatches and stumbling around blindly."}
{:text "hiding under a table."}
{:text "hiding under a sofa."}
{:text "hiding in the bushes."}
{:text "munching on %0."
:subs {0 {:class :food}}}
{:text "pretending to be invisible."}
{:text "having a coughing fit."}
{:text "having a sneezing fit."}
{:text "being menaced by %0."
:subs {0 {:class :animal}}}
{:text "ready to start some shit."}
{:text "examining %0 with great confusion."
:subs {0 {:class :item}}}]})
(def locations
{:locations
[{:text "dead-end"
:type :interior
:article "a"
:preps ["at" "in front of"]
:follow-ups {:optional? true
:options [{:text "You start to moonwalk away."}
{:text "Someone has painted a giant sad face here."}]}}
{:text "ice skating rink"
:type :exterior
:article "an"
:preps ["at" "in front of" "on"]
:follow-ups {:optional? true
:options [{:text "It's currently on fire."}
{:text "Unfortunately, it's made of dry ice."}
{:text "A solid-gold curling stone is nearby."}
{:text "There are three hungry-looking zambonies here."}]}}
{:text "movie set"
:type :exterior
:article "a"
:preps ["on"]
:follow-ups {:optional? true
:options [{:text "The crafts table is covered with another, smaller crafts table."}
{:text "A nude man strolls by."}
{:text "A hundred tiny dogs are here, looking menacing."}]}}
{:text "particle board storage facility"
:type :interior
:article "a"
:preps ["at" "near" "in front of" "behind" "inside"]}
{:text "tire fire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is warm and welcoming."}
{:text "Someone had been roasting marshmallows here."}
{:text "The air here is black with despair and entropy."}
{:text "The sky is darkened by the hellish smoke."}]}}
{:text "dildo bonfire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "You look closely but don't recognize any of them."}
{:text "The plastic hisses and creaks in the blaze."}
{:text "The smoke smells of vanilla."}
{:text "The air is dense with the echoes of unreached orgasms."}]}}
{:text "hot tub"
:type :interior
:article "a"
:preps ["in near"]
:follow-ups {:optional? true
:options [{:text "The water roils and steams like water roils and steams."}
{:text "It's frozen solid."}
{:text "A basketball dances on the bubbles."}
{:text "You see a staircase beneath the water."}
{:text "Is it water or is it hydrocarbons?"}
{:text "It smells delicious because someone filled it with chicken soup."} ]}}
{:text "maze of twisty little passages, all alike"
:type :interior
:article "a"
:preps ["in"]}
{:text "Burning Man"
:type :exterior
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "Oddly, no one appears to be here."}
{:text "A tumbleweed made out of human hair stumbles by."}
{:text "A dust storm is approaching."}
{:text "It looks like it might rain soon."}
{:text "Snow is gently falling."}
{:text "%0 is here, looking %1."
:subs {0 {:class :person}
1 {:class :adjective}}}
{:text "Clearly the drugs have begun to take hold."}]}}
{:text "Shrim Healing Center"
:type :exterior
:article "a"
:preps ["in" "at" "in front of" "behind"]
:follow-ups {:optional? true
:options [{:text "There are TVs in the window, all turned off."}
{:text "Someone has spray-painted 'I crave brown baths' here."}
{:text "Inside you hear the sound of repulsed joy."}
{:text "The door has been boarded up."}
{:text "%0 is patiently waiting in line by %1."
:subs {0 {:class :person}
1 {:class :gender
:case :compound}}}
{:text "The building looks like it has been condemned."}]}}
{:text "quicksand"
:type :exterior
:article "some"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Briefly, you see a fin rise up and cruise back and forth."}
{:text "The surface quicksand gently sways, beckoning you..."}
{:text "Oddly, it smells like freshly cooked oatmeal."}]}}
{:text "swimming pool"
:type :exterior
:article "a"
:preps ["in" "at" "near"]
:follow-ups {:optional? true
:options [{:text "The surface of the pool is almost entirely still. You are afraid to disturb it."}
{:text "The water has turned slightly murky; it does not look inviting."}
{:text "The surface of the pool is littered with leaves."}
{:text "The pool is empty."}
{:text "The pool is empty. A broken skateboard is nearby."}
{:text "A dead bird floats by."}
{:text "An abandoned plastic float with a dinosaur's head floats lonely nearby."}]}}
{:text "<NAME>"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The wood paneling sweats sweetly in the oppressive heat."}
{:text "Great thunderheads of steam rise up from the rock basin, making it hard to see."}
{:text "The room is cold and dark. No one has been here in years."}
{:text "The floor is covered with cute little mushrooms."}]}}
{:text "New York Public Library"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]}
{:text "<NAME>"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It stretches out in front of you, meandering as if drunk."}
{:text "A giant marshmallow avalanche blocks the way ahead."}
{:text "A small trickle of spaghetti sauce runs down the middle."}]}}
{:text "<NAME>"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The dusty stench of aged sewage gives you a hug."}
{:text "It is completely blocked here by a giant boulder."}
{:text "A trickle of clear water runs down the middle of it."}]}}
{:text "dump"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "In the distance, you see a hazy castle."}
{:text "The hill of trash shifts dangerously beneath your feet."}]}}
{:text "dump truck"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "It's covered with a patina of black filth."}
{:text "Fresh off the line, it gleams bright red."}
{:text "The engine rumbles roughly to itself. The doors are locked."}]}}
{:text "Starbucks"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is packed tightly with hipsters."}
{:text "There is a surprising lack of hipsters here."}
{:text "It reeks of slightly burnt coffee here."}]}}
{:text "park restroom stall"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The door has been torn off its hinges."}
{:text "The walls are covered with violent scratches."}
{:text "The toilet is made of solid gold."}
{:text "A garden gnome greets you from the bowl."}
{:text "The toilet is missing."}
{:text "There's a basketball in the bowl."}
{:text "Suddenly the lights go out."}
{:text "The lingering scents of lemon and Lysol haunt the air."}
{:text "Someone has scratched your name and number on the wall."}]}}
{:text "all-you-can-eat buffet"
:type :interior
:article "an"
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "It looks abandoned."}
{:text "Bullet time means more eggrolls."}
{:text "Steam crowds the air."}
{:text "It's all gluten-free and vegan. You leave immediately."}
{:text "It smells of freedom and gluttony."}
{:text "All of the food has been replaced with wax replicas."}
{:text "It's in complete disarray and hasn't been tended for some time."}]}}
{:text "g<NAME>"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The ceiling is sparkling with reflected light."}
{:text "The water is darkened with greenish-gray algae."}
{:text "The pool of water seems unusually deep. A lean, black fish swims in a circle."}]}}
{:text "bedroom"
:type :interior
:article "your"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It hasn't been cleaned in a long time."}
{:text "There's a pleasantly disgusting smell here."}
{:text "It's small and lightly furnished. The bed is unmade."}
{:text "There is nothing special about it."}
{:text "You notice an unusual stain in the carpet."}
{:text "There's an unusual stain in the carpet next to a usual stain."}
{:text "The ceiling fan is spinning dangerously fast."}
{:text "The walls are covered with %0 posters."
:subs {0 {:class :person}}}
{:text "There's a pile of clothes nearby."}]}}
{:text "<NAME>"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "White Castle"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It's white and vaguely castle-shaped."}
{:text "It smells squarely delicious."}]}}
{:text "<NAME>"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "dark area"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is pitch black here. You're likely to be eaten by %0."
:subs {0 {:class :actor}}}
{:text "It's really dark here. Like... REALLY dark."}
{:text "It just got slightly darker somehow."}
{:text "It's so dark you can taste it. Tastes like dark."}
{:text "It's dark here. DARK AS YOUR SOUL."}]}}
{:text "breezy cave"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "There's a constant breeze rising up from the depths."}
{:text "Wide and low, the cave gently slopes %0-%1 here."
:subs {0 {:class :direction}
1 {:class :direction}}}
{:text "It smells of warm packing peanuts."}
{:text "It's really breezy. Gale-force breezy."}
{:text "It's seems over-oxygenated. You get light-headed."}
{:text "The cave seems to be breathing rapidly."}]}}
{:text "forest"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is a dense, dark, and tangled choke of gnarled trees, thorny underbrush, and spiky thickets."}
{:text "Shot through with shafts of light, the forest before you looks serene."}
{:text "The trees, mostly oak and spruce, sway gently in the occasional breeze."}
{:text "It's currently on fire."}
{:text "The trees are all inflated plastic."}
{:text "The trees ignore your incessant crying."}
{:text "Birds are chirping and rodents scamper through the underbrush."}]}}
{:text "riverbed"
:type :exterior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "It's dry and littered with rocks and branches."}
{:text "The water steadfastedly refuses to flow. It just sits there."}
{:text "Nearby two bears are standing on the water, defiantly."}
{:text "The river immediately parts and just keeps on parting."}
{:text "It's mostly dry, the flow of the water blocked by a beaver dams upstream."}]}}
{:text "AT&T Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "Apple Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "ballpit"
:type :interior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Oddly, all of the balls here are the same color: orange."}
{:text "The ballpit seems unusually deep. You can't feel the bottom."}
{:text "It's been filled with Rubik's Cubes."}
{:text "It's empty except for one orange ball at the bottom."}
{:text "It contains only one ball: orange and 12' across."}
{:text "You get the feeling someone is swimming around in there."}]}}
{:text "airplane"
:type :interior
:article "an"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "There's no one else on board."}
{:text "You hear strange noises coming from the restroom."}
{:text "Somehow you have a dozen packets of pretzels."}
{:text "Someone drank your Fresca while you were napping."}
{:text "It's pitch black outside. Can grues fly?"}
{:text "The pilot says, 'We've reached our cruising altitude of 30 feet.'"}
{:text "The plane has been going straight up for hours now."}]}}
{:text "trunk of a car"
:type :interior
:article "the"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "A tire iron is digging into your back a little bit."}
{:text "There's a half-eaten bag of Bugles here."}
{:text "With all the trash in here, there's barely any room for you."}
{:text "It's pitch black. No room for a grue, luckily."}]}}
{:text "coffin"
:type :interior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "It smells of cotton candy in here for some reason."}
{:text "It smells of Aquanet in here. Makes sense."}
{:text "It's pitch black. It probably doesn't matter if ther's a grue here."}]}}
{:text "hugbox"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "You feel at home again."}
{:text "It's very warm in here. Perhaps too warm."}
{:text "It smells of stale sweat and lies, lies, lies..."}]}}
{:text "haunted house"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The house shrugs under its own entropy."}
{:text "An orange light wanders from window to window."}
{:text "A sign here reads: 'As seen on TV."}
{:text "Endless amounts of blood pour from the windows."}
{:text "Looks inviting except for the corpses littering the lawn."}]}}
{:text "graveyard"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "There is a freshly laid grave nearby."}
{:text "There is an open grave nearby. It's empty."}
{:text "There is an open grave nearby. There's a phone book in it."}
{:text "There is an open grave nearby. It's full of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "There are fresh footprints here."}
{:text "A lazy mist drifts amongst the tombstones."}
{:text "The tombstones have been replaced by durable plastic bricks."}
{:text "All the graves are filled with Mr. Bubbles."}
{:text "The Christmas lights sure make it look festive."}
{:text "A disco ball spins lonely from a gnarled tree."}]}}
{:text "playground"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The equipment looks like it's never been used."}
{:text "Most of the equipment is missing or broken."}
{:text "You hear the sound of children laughing but no one else is here."}]}}
{:text "pile of diapers"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "Some of these look awfully familiar."}]}}
{:text "meeting"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The room is crowded by tripods holding colorful charts."}
{:text "The projector is on, showing random photos of cats at play."}
{:text "The table is covered with a chalk outline."}
{:text "The chairs are all occupied by cobweb-encrusted skeletons."}
{:text "The room is almost full of balloons."}]}}
{:text "<NAME>"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "full-contact Bible study group"
:type :interior
:article "a"
:preps ["near" "behind" "in front of" "in"]
:follow-ups {:optional? true
:options [{:text "No one is here."}
{:text "They stare at you and begin to crowl."}
{:text "They're all covered with cuts and bruises."}
{:text "They're currently scrumming over a Bible."}]}}]})
(def dialogues
{:dialogues
[{:text "asks, 'Have you ever seen an elephant throw up?'"}
{:text "asks, 'Why am I holding this pitchfork?'"}
{:text "asks, 'How long is a man?'"}
{:text "asks, 'Where have you been?'"}
{:text "asks, 'Would you like to see my collection of tiny ceiling fans?'"}
{:text "asks, 'Which one are you?'"}
{:text "asks, 'Can I have a hug?'"}
{:text "asks, 'Are you following me?'"}
{:text "asks, 'Does it smell like %0 in here to you?'"
:subs {0 {:class :food}}}
{:text "asks, 'Have you got a flag?'"}
{:text "asks, 'Have you ever seen a grown man naked?'"}
{:text "asks, 'May I use your FAX machine?'"}
{:text "chants, 'It's time to pay the price.'"}
{:text "mumbles, 'You can't go up against city hall.'"}
{:text "mumbles, 'One day I'm going to burn this place to the ground.'"}
{:text "mumbles, 'Sk<NAME> ruined it all for everybody.'"}
{:text "mumbles, 'I've never been to Belize.'"}
{:text "says, 'It's true: the boot is the best McNugget shape.'"}
{:text "says, 'Wrong answer, chief.'"}
{:text "says, 'This is giving me the freak-out.'"}
{:text "says, 'How unfortunate.'"}
{:text "says, 'Well that really scrambles my eggs.'"}
{:text "says, 'I've been waiting for you.'"}
{:text "says, 'I can't find my heirloom clown suit.'"}
{:text "says, 'I can't find my %0.'"
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "says, 'No money? No hamburger!'"}
{:text "says, 'It's like drinking a meatloaf!'"}
{:text "says, 'Took you long enough.'"}
{:text "says, 'I'm addicted to Kitty L<NAME> III.'"}
{:text "says, 'Looks like I'm not having any mayonnaise.'"}
{:text "says, 'I'm a brown-belt in speed tai chi.'"}
{:text "says, 'I'm stuck in a poo loop.'"}
{:text "says, 'Well, that's a dead give away.'"}
{:text "says, 'If you asked me to have sex with you, I wouldn't say \"no\".'"}
{:text "says, 'I'm not an actor but I play one on television.'"}
{:text "says, 'That dog rode on a bus by itself."}
{:text "says, 'The time has come for me to deal with the fact that I'll never be <NAME>, Jr.'"}
{:text "says, 'So I guess <NAME> is going to be a thing now.'"}
{:text "says, 'I'm going to button up the top of my polo shirt to demonstrate I don't want to talk to you.'"}
{:text "says, 'I'm in a poo trance.'"}
{:text "says, 'I'm a source of fiber.'"}
{:text "says, 'Surrealism is the scourage of butane.'"}
{:text "says, 'This drink tastes like Sears!'"}
{:text "says, 'This teenager salad tastes like a slowly closing door.'"}
{:text "says, 'It never hurts to have a corpse open the door for you.'"}
{:text "says, 'The Swanson TV Dinner heard 'round the world.'"}
{:text "says, 'The membership card is edible.'"}
{:text "says, 'That bisexual really jazzed up my latte.'"}
{:text "shouts, 'You can't go up against city hall!'"}
{:text "shouts, 'You can't fold a cat!'"}
{:text "shouts, 'It keeps happening!'"}
{:text "shouts, 'They're having a brownout in Lagos!'"}
{:text "shouts, 'Don Quixote! Swingin' from a pipe!'"}
{:text "shrieks, 'What's this shit I keep hearing about erections?!'"}
{:text "shrieks, 'I'm living on the edge!'"}
{:text "shrieks, 'Boiled soil!'"}
{:text "shriefs, 'Baby-oil covered balloon animals for all!"}
{:text "sighs, 'I liked you better before the hip-replacement surgery.'"}
{:text "snarls, 'Siddown before ya fall down!'"}
{:text "whispers, 'Why are you talking in all lowercase?'"}
{:text "whispers, 'It puts the lotion on its skin...'"}
{:text "whispers, 'I've always wanted to be a creepy uncle.'"}
{:text "whispers, 'Fee was a Buddhist prodigy.'"}
{:text "whispers, 'There squats the brown clown.'"}
{:text "whispers, 'Sleep is unproductive and a waste of time.'"}
{:text "whispers, 'You just lost the game.'"}
{:text "yells, 'I warned you about stairs, bro! I told ya, dawg!'"}]})
(def thoughts
{:thoughts
[{:text "Why don't they put mayo in the can with the tuna?"}
{:text "%0 never has a second cup of coffee at home..."
:subs {0 {:class :person}}}
{:text "You can't go up against city hall."}
{:text "I've made a huge mistake."}
{:text "It's time to pay the price."}
{:text "Why don't they have Double Stuf Nutter Butters?"}
{:text "This'll all end in tears."}
{:text "Hey! But I didn't eat the mousse!"}
{:text "%0 still owes me a backrub."
:subs {0 {:class :person}}}
{:text "I wonder if I could forge us a Group 6 Access..."}]})
(def intonations
{:intonations
[{:text "Toast goes in the toaster."}
{:text "These pretzels are making me thirsty."}
{:text "For those who can make the journey, there is a place."}
{:text "Slightly uncomfortable pleasures."}
{:text "It is a winning cake."}
{:text "POKE 1024,0."}
{:text "Coitus?"}
{:text "Pave Canada."}
{:text "Your pilikia is all pau."}
{:text "The owls are not what they seem."}
{:text "Plugh."}
{:text "Zzyzx."}
{:text "Guch."}
{:text "Spigot."}
{:text "You sank my battleship."}
{:text "Sorry, but it couldn't be helped."}
{:text "Clean up in aisle 8A."}
{:text "Rabbit feces."}
{:text "Don't panic."}
{:text "Don't panic. Oh, all right. You can panic a little bit."}
{:text "Consider deeply the baked ham."}
{:text "You can't go up against city hall."}]})
(def signs
{:signs
[{:text "<NAME> shave!"}
{:text "It's time to pay the price."}
{:text "You can't go up against city hall."}
{:text "For those who can make the journey, there is a place."}
{:text "Here lies Hammerdog, a dog made of hammers."}
{:text "Here lies Knifekitten, a kitten made of knives."}
{:text "When you're not reading this, it's written in Spanish."}
{:text "Now you know how hard it is to say \"Irish wristwatch\"."}]})
(def books
{:books
[{:text "the Bible"
:preps ["a copy of"]}
{:text "Catcher in the Rye"
:preps ["a copy of"]}
{:text "Infinite Jest"
:preps ["a copy of"]}
{:text "Gravity's Rainbow"
:preps ["a copy of"]}
{:text "A Prayer for Owen Meany"
:preps ["a copy of"]}
{:text "The Hitchhiker's Guide to the Galaxy"
:preps ["a copy of"]}]})
(def attacks
{:attacks
[{:text "%0"
:subs {0 {:class :actor}}}
{:text "%0"
:subs {0 {:class :item}}}
{:text "a judo chop"}
{:text "a Judeo chop"}
{:text "a filthy soap slap"}
{:text "a rough kitty lick"}
{:text "a high clownkick"}
{:text "a sad testicle tug"}
{:text "a sushi pants special"}
{:text "a rub cut"}
{:text "a rusty trombone"}
{:text "an antiparticle dildo"}
{:text "a Cleveland steamer"}
{:text "a wet hug"}
{:text "a prison hug"}
{:text "a reverse hug"}
{:text "Canadian disapproval"}
{:text "a dangling participle"}
{:text "a fancy uppercut"}
{:text "a flurry of tiny kisses"}
{:text "a forlorn sigh"}
{:text "a balloon"}
{:text "a spontaneous coma"}
{:text "a smug kidney punch"}
{:text "a bit of the ol' in-out"}
{:text "a atomic wedge"}
{:text "Vogon poetry"}
{:text "a bad British accent"}
{:text "poor grammar"}
{:text "Conservative politics"}
{:text "Liberal politics"}
{:text "secret.jpg"}
{:text "tubgirl.jpg"}
{:text "cute kittens"}
{:text "tumbly puppies"}
{:text "a weaponized beard"}
{:text "an apathetic hipster"}]})
(def directions
{:directions
[{:text "north"}
{:text "northeast"}
{:text "east"}
{:text "southeast"}
{:text "south"}
{:text "southwest"}
{:text "west"}
{:text "northwest"}]})
(def persons
{:persons
[{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "a police officer"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :female}
{:text "<NAME>"
:gender :male}
{:text "your mom"
:gender :female}
{:text "a bunch of kids"
:gender :group}
{:text "a crowd of Yoga enthusiasts"
:gender :group}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "a gas station attendant"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "@akiva"
:gender :male}
{:text "@jimminy"
:gender :male}
{:text "@veo_"
:gender :male}
{:text "@vmcny"
:gender :male}
{:text "@KamenPrime"
:gender :male}
{:text "@ActuallySparky"
:gender :male}
{:text "@neonbubble"
:gender :male}
{:text "@micahwittman"
:gender :male}
{:text "@itafroma"
:gender :male}
{:text "@clive"
:gender :male}
{:text "@mokargas"
:gender :male}
{:text "@drew"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}
{:text "<NAME>"
:gender :male}]})
(def actions
{:actions
[{:text "attacks"}
{:text "sneezes on"}
{:text "ignores"}
{:text "tickles"}
{:text "stands uncomfortably close to"}
{:text "violently points at"}
{:text "imitates"}
{:text "pets"}
{:text "examines"}
{:text "flirts with"}]})
(def adjectives
{:adjectives
[{:text "worried"}
{:text "relieved"}
{:text "aroused"}
{:text "afraid"}
{:text "nonplussed"}
{:text "sleepy"}
{:text "hungry"}
{:text "thirsty"}
{:text "bored"}
{:text "hopeful"}
{:text "sad"}
{:text "happy"}
{:text "forlorn"}
{:text "angry"}]})
(def adverbs
{:adverbs
[{:text "carefully"}
{:text "wistfully"}
{:text "uncertainly"}
{:text "willfully"}
{:text "lustfully"}
{:text "warily"}
{:text "solemnly"}
{:text "mournfully"}
{:text "proudly"}
{:text "bravely"}
{:text "sadly"}
{:text "happily"}
{:text "balefully"}]})
(def scents
{:scents
[{:text "acrid"}
{:text "sweet"}
{:text "sour"}
{:text "rotten"}
{:text "nice"}
{:text "foul"}
{:text "of feet"}
{:text "of your grandfather's hair cream"}
{:text "of warm peanut butter"}
{:text "bitter"}
{:text "smoky"}
{:text "gross"}
{:text "pleasant"}]})
(def diagnoses
{:diagnoses
[{:text "feeling great"}
{:text "feeling gross"}
{:text "absurdly sticky"}
{:text "lightly wounded"}
{:text "moderately wounded"}
{:text "heavily wounded"}
{:text "near death"}
{:text "sleepy"}
{:text "drunk"}
{:text "stoned"}
{:text "confused"}
{:text "hungry"}
{:text "thirsty"}
{:text "temporarily blind"}
{:text "temporarily deaf"}
{:text "covered in bees"}]})
(def foods
{:foods
[{:text "burrito"
:article "a"}
{:text "weaponized cornbread"
:article "some"}
{:text "persecution sandwich"
:article "a"}
{:text "tooth burger"
:article "a"}
{:text "bouquet of corndogs"
:article "a"}
{:text "corndog"
:article "a"}
{:text "pancakes"
:article "some"}
{:text "cake"
:article "a"}
{:text "cake"
:article "a slice of"}
{:text "kumquat"
:article "a"}
{:text "salad"
:article "a"}
{:text "Rice Chex"
:article "a bowl of"}
{:text "Reese's Peanut Butter Cup"
:article "a"}
{:text "apple pocket"
:article "an"}
{:text "block of cheese"
:article "a"}
{:text "wedge of cheese with some mold on it"
:article "a"}
{:text "slice of fried spam"
:article "a"}
{:text "delicious churro"
:article "a"}
{:text "chocolate bobka"
:article "a"}
{:text "sweetroll"
:article "a"}
{:text "Cinnabon"
:article "a"}
{:text "duck confit"
:article "some"}
{:text "pasta"
:article "some"}
{:text "uncooked rice"
:article "some"}
{:text "Fritos"
:article "some"}
{:text "sushi"
:article "some"}
{:text "apple cinnamon Pop Tart"
:article "an"}]})
(def drinks
{:drinks
[{:text "steaming gravy"
:article "a cup of"}
{:text "milk"
:article "a gallon of"}
{:text "orange juice"
:article "a glass of"}
{:text "tea"
:article "some"}
{:text "soda"
:article "some"}
{:text "water"
:article "some"}
{:text "beef broth"
:article "some"}
{:text "scotch"
:article "a"}]})
(def garments
{:garments
[{:text "hat"
:article "a"}
{:text "pants"
:article "some"}
{:text "shirt"
:article "a"}
{:text "gloves"
:article "some"}
{:text "shoes"
:article "some"}
{:text "belt"
:article "a"}
{:text "socks"
:article "some"}
{:text "coat"
:article "a"}
{:text "jacket"
:article "a"}
{:text "underwear"
:article "some"}
{:text "dress"
:article "a"}
{:text "skirt"
:article "a"}
{:text "schizophrenic mood ring"
:article "a"}
{:text "sweater"
:article "a"}
{:text "watch"
:article "a"}]})
(def items
{:items
[{:text "skinny jeans"
:article "a pair of"}
{:text "slick pellets"
:article "a bag of"}
{:text "fat-soluble <NAME>"
:article "a bottle of"}
{:text "llama treats"
:article "a bag of"}
{:text "parachute pants"
:article "a pair of"}
{:text "Breakin' 2: Electric Boogaloo"
:article "a Laserdisc copy of"}
{:text "magic scroll"
:article "a"}
{:text "no tea"}
{:text "Snausages"
:article "some"}
{:text "slide rule"
:article "a"}
{:text "pinecone"
:article "a"}
{:text "sweat-incrusted trilby"
:article "a"}
{:text "vitamins"
:plural true
:article "some"}
{:text "bucket of corks"
:article "a"}
{:text "<NAME>"
:article "a pair of"}
{:text "non-Euclidian Lego"
:article "a"}
{:text "spray-on bacon"
:article "a can of"}
{:text "spackle"
:article "a can of"}
{:text "unfamiliar briefcase"
:article "an"}
{:text "towel from the Las Vegas Radisson"
:article "a"}
{:text "receipt from a bunny outfit rental"
:article "a"}
{:text "floppy disk"
:article "a"}
{:text "pencil"
:article "a"}
{:text "lantern"
:article "a"}
{:text "elven sword"
:article "an"}
{:text "books"
:article "some"}
{:text "movie ticket"
:article "a"}
{:text "newspaper"
:article "a"}
{:text "kitten"
:article "a"}
{:text "puppy"
:article "a"}
{:text "bag of potatoes"
:article "a"}
{:text "bag of rice"
:article "a"}
{:text "giant styrofoam peanut"
:article "a"}
{:text "phone book"
:article "a"}
{:text "pyramid of tennis balls"
:article "a"}
{:text "deflated soccer ball"
:article "a"}
{:text "fourth grade report card"
:article "your"}
{:text "half-eaten sandwich"
:article "a"}
{:text "signed photograph of <NAME>"
:article "a"}
{:text "hipster t-shirt"
:article "a"}
{:text "pile of discarded puppets"
:article "a"}
{:text "wet Lincoln Log"
:article "a"}
{:text "VHS tape covered in blood"
:article "a"}]})
(def animals
{:animals
[{:text "kitten"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "cat"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "puppy"
:article "a"
:sounds ["pants" "barks" "growls" "whimpers"]
:adjectives ["panting" "barking" "growling" "whimpering"]}
{:text "duck"
:article "a"
:sounds ["quacks"]
:adjectives ["quacking"]}
{:text "mar<NAME>"
:article "a"}
{:text "tiger"
:article "a"
:sounds ["roars"]
:adjectives ["roaring"]}
{:text "hamster"
:article "a"}
{:text "gerbil"
:article "a"}
{:text "hedgehog"
:article "a"}]})
(def noises
{:noises
[{:text "foghorn"
:article "a"}
{:text "laughter"
:article "some"}
{:text "laughing"
:article "somebody"}
{:text "chuckling"
:article "someone"}
{:text "cackling"
:article "someone"}
{:text "crying"
:article "someone"}
{:text "sobbing"
:article "someone"}
{:text "sneeze"
:article "a"}
{:text "wolves howling"}
{:text "ice cream truck"
:article "an"}
{:text "door slam"
:article "a"}
{:text "sinister chuckle"
:article "a"}]})
(def disasters
{:disasters
[{:text "fire"
:article "a"}
{:text "tornado"
:article "a"}
{:text "hurricane"
:article "a"}
{:text "flood"
:article "a"}
{:text "tsunami"
:article "a"}
{:text "landslide"
:article "a"}
{:text "avalanche"
:article "an"}
{:text "radioactive leak"
:article "a"}
{:text "lava flow"
:article "a"}
{:text "sandstorm"
:article "a"}
{:text "lightning strike"
:article "a"}
{:text "plague of locusts"
:article "a"}
{:text "snowstorm"
:article "a"}
{:text "duststorm"
:article "a"}]})
(def obstacles
{:obstacles
[{:text "a black comb on the ground"}
{:text "a stack of dogs going all the way to the moon"}
{:text "<NAME> grin"}
{:text "an obstinant balloon expert"}
{:text "a pile of corroded Ewoks"}
{:text "a horrible taste in your mouth"}
{:text "a movie being shown in the wrong aspect ratio"}
{:text "someone who has never listened to Neutral Milk Hotel"}
{:text "the thing your aunt gave you which you don't know what it is"}
{:text "an aquarium full of milk"}
{:text "dubstep"}
{:text "a 404 error"}
{:text "<NAME>'s career"}
{:text "that awful man"}
{:text "a dude who insists on putting his hand in his girlfriend's back pocket"}
{:text "a maelstrom of hipster beards"}
{:text "a wall of tepid soup"}
{:text "a giant cat tongue"}
{:text "<NAME>' neck"}
{:text "Ruby On Rails"}
{:text "someone who takes too many selfies"}
{:text "a cat who has been pet against the grain"}
{:text "substandard prequels"}
{:text "the Scut Farkus Affair"}
{:text "a lack of retweets"}
{:text "a sweaty 486DX4 chip"}
{:text "a convenient reclosing tab"}
{:text "a lengthy German noun"}
{:text "your own unwillingness to improve yourself"}
{:text "%0's sheer force of will"
:subs {0 {:class :person}}}
{:text "%0's birthday party"
:subs {0 {:class :person}}}
{:text "a delicious Nutter Butter"}
{:text "double-double Animal style"}
{:text "someone who doesn’t know how to eat a goddamned Oreo properly"}]})
(def news
{:news
[{:text "Shamer Claims Bullying from Shame Shamers"}]})
(def games
{:games
[{:text "Agricola"
:type :tabletop}
{:text "Advanced Squad Leader"
:type :tabletop}
{:text "Carcassonne"
:type :tabletop}
{:text "World in Flames"
:type :tabletop}
{:text "Monopoly"
:type :tabletop}
{:text "World of Warcraft"
:type :video}
{:text "Civilization V"
:type :video}
{:text "Grand Theft Auto V"
:type :video}]})
(def classes
["events"
"location-events"
"action-events"
"secondary-events"
"tertiary-events"
"actor-actions"
"locations"
"dialogues"
"intonations"
"books"
"directions"
"persons"
"actions"
"adjectives"
"adverbs"
"scents"
"diagnoses"
"foods"
"drinks"
"signs"
"obstacles"
"garments"
"items"
"animals"
"noises"
"attacks"
"games"
"thoughts"
"news"
"disasters"])
| true | (ns xyzzwhy.text)
;; This text presents source material for xyzzwhy's original corpus. Each
;; class (such as :location-events or :obstacles) is a map containing map
;; fragments the minimal requirement of which is a :text key.
;;
;; A fragment's :text value can contain a number of substitutions represented
;; by %0-%n. These require a :subs map which contains a key for each substitution.
;; These must contain at least a :class reference which is keyed to another
;; class. These are randomly chosen by xyzzwhy and then interpolated into the
;; fragment's :text. A substitution can also contain a :config map which has
;; options to skip the automatic prepending of prepositions and/or articles; and
;; the ability to ensure that an actor sub is a single person and not a group.
;; More config options will be added later.
;;
;; A fragment may also have follow-ups which may be marked as :optional?. A list of
;; options follows which is a vector of fragments which themselves may have :subs.
;; These subs must begin their %x count +1 from what's in the parent fragment's :text.
;; Each follow-up option's sub may contain a :ref key which allows it to refer to
;; a substitution from the parent fragment's text. For example, to use a pronoun
;; for a person class substitution at %0, the follow-up's substitution would :ref 0.
;;
;; Object classes and locations also have an :article and :preps for prepositions.
;; Locations have a :type which is either :interior or :exterior.
;; Actors have a :gender (:male, :female, or :group).
;;
;; Animals have :sounds (e.g., a kitten might purr or meow) and :adjectives
;; such as a 'whimpering' for a puppy.
;;
;; Future classes might have their own special keys and options.
(def events
{:events [:location-event :action-event]})
(def location-events
{:location-events
[{:text "You have entered %0."
:subs {0 {:class :location
:config #{:no-prep}}}}
{:text "You are serving jury duty."
:follow-ups {:optional? false
:options [{:text "The prosecuting attorney insists on speaking through a broken bullhorn."}
{:text "They hand out PI:NAME:<NAME>END_PI but they're stone cold."}
{:text "The judge is dressed like Dr. PI:NAME:<NAME>END_PI."}
{:text "You're unsure why they insist the jury sit in a vat of carbonated %0."
:subs {0 {:class :drink :config #{:no-article}}}}]}}
{:text "After %0 at your %1, you are relocated by FEMA to %2."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep :no-article}}
2 {:class :location :config #{:no-prep}}}}
{:text "You arrive for your first day at college only to find your roommate is %0."
:subs {0 {:class :actor}}}
{:text "You try to go %0 but your way is blocked by %1."
:subs {0 {:class :direction}
1 {:class :obstacle}}}
{:text "%0 prevents you from going %1 to %2."
:subs {0 {:class :obstacle}
1 {:class :direction}
2 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and find yourself at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You go %0 and emerge %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You walk %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You cripwalk %0 to %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You strut %0 and end up %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "A double bounce on a trampoline lands you %0."
:subs {0 {:class :location}}}
{:text "You head %0 and arrive at %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "Google Maps leads you to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow %0 to %1."
:subs {0 {:class :actor}
1 {:class :location :config #{:no-prep}}}}
{:text "You are %0."
:subs {0 {:class :location}}}
{:text "You're %0."
:subs {0 {:class :location}}}
{:text "You run screaming into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You tunnel through the soil and pop up %0."
:subs {0 {:class :location}}}
{:text "You emerge %0."
:subs {0 {:class :location}}}
{:text "You arrive %0."
:subs {0 {:class :location}}}
{:text "You are magically teleported to %0!"
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The drugs are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "The spell effects are wearing off. You are %0."
:subs {0 {:class :location}}}
{:text "You are standing %0 of %1."
:subs {0 {:class :direction}
1 {:class :location :config #{:no-prep}}}}
{:text "You stumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You come across %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You follow the treasure map to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You wake up from an odd dream. You are %0."
:subs {0 {:class :location}}}
{:text "You open the secret door only to see %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You find yourself %0."
:subs {0 {:class :location}}}
{:text "Dazed, you climb out of the dryer. You are %0."
:subs {0 {:class :location}}}
{:text "After the shoot-out, you make your escape to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The bridge game turned violent so you went to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You start doing the worm until you find yourself %0."
:subs {0 {:class :location}}}
{:text "You wake up %0."
:subs {0 {:class :location}}}
{:text "You climb down a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "You climb up a tree and find yourself %0."
:subs {0 {:class :location}}}
{:text "The taxi driver randomly drops you off %0."
:subs {0 {:class :location}}}
{:text "The metro bus unceremoniously dumps you %0."
:subs {0 {:class :location}}}
{:text "The fog clears and you find yourself %0."
:subs {0 {:class :location}}}
{:text "Your parachute gently plops you %0."
:subs {0 {:class :location}}}
{:text "You jump out of a moving car, roll down a hill, and find yourself %0."
:subs {0 {:class :location}}}
{:text "After walking for a long time, you find yourself %0."
:subs {0 {:class :location}}}
{:text "You find your way blindly and end up %0."
:subs {0 {:class :location}}}
{:text "No matter how hard you try, you still end up %0."
:subs {0 {:class :location}}}
{:text "You climb out of the treasure chest. You are now %0."
:subs {0 {:class :location}}}
{:text "You come to %0."
:subs {0 {:class :location}}}
{:text "You follow a winding path %0 only to find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You follow a sloping path %0. You find yourself %1."
:subs {0 {:class :direction}
1 {:class :location}}}
{:text "You climb up a flight of stairs. You are now %0."
:subs {0 {:class :location}}}
{:text "You shuffle down a flight of stairs and enter %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You fall down a flight of stairs and into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The elevator doors open to reveal %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "Using a vine to swing across the pit, you land %0."
:subs {0 {:class :location}}}
{:text "The trapdoor drops open beneath you and you land %0."
:subs {0 {:class :location}}}
{:text "You flip the Game Select selector and find yourself %0."
:subs {0 {:class :location}}}
{:text "You blow into the cartridge too hard and are teleported to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "You step through a magic mirror and end up %0."
:subs {0 {:class :location}}}
{:text "You get tangled up in a revolving door. You stumble out into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "After scrambling through some dense underbrush, you find yourself %0."
:subs {0 {:class :location}}}
{:text "After pushing your way through a dense crowd, you arrive %0."
:subs {0 {:class :location}}}
{:text "You squeeze out of the sewage outflow and tumble into %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "A tornado deposits you %0."
:subs {0 {:class :location}}}
{:text "Right on cue, you pop up out of the jack-in-the-box. You're %0."
:subs {0 {:class :location}}}
{:text "After being shot out of a cannon, you land %0."
:subs {0 {:class :location}}}
{:text "You slide down a fireman's pole and land %0."
:subs {0 {:class :location}}}
{:text "Hands on your hips, you survey %0 %1."
:subs {0 {:class :location :config #{:no-prep}}
1 {:class :adverb}}}
{:text "You wake up in front of %0's house. You have no clue how you got there."
:subs {0 {:class :person}}}
{:text "You ride %0 to %1."
:subs {0 {:class :animal}
1 {:class :location :config #{:no-prep}}}}
{:text "You fall through the ceiling and land %0."
:subs {0 {:class :location}}}
{:text "The drugs are starting to take hold. Casually you saunter over to %0."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "The merry-go-round spins faster and faster until you're flung off and land %0."
:subs {0 {:class :location}}}]})
(def action-events
{:action-events
[{:text "You awake from a nightmare. You saw yourself %0. The corpse of %1 was there, holding %2."
:subs {0 {:class :location}
1 {:class :person :config #{:no-groups}}
2 {:class :item}}}
{:text "%0 arrives from the %1, carrying %2."
:subs {0 {:class :actor :config #{:no-groups}}
1 {:class :direction}
2 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You pick up %0 and hold it close to your chest."
:subs {0 {:class :item}}}
{:text "The radio crackles to life."
:follow-ups {:optional? false
:options [{:text "It sounds like someone with a cold is eating PI:NAME:<NAME>END_PI." }
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Ketchup begins seeping through the speaker holes."}
{:text "It continues to crackle to life. It's still crackling. It's on fire."}
{:text "An announcer shouts, 'They found rice on Mars!"}
{:text "A news report is on about %0 %1."
:subs {0 {:class :disaster}
1 {:class :location :config #{:no-prep}}}}
{:text "%0 solemnly '%1'"}]}}
{:text "%0 drops %1, looks at you %2, then leaves."
:subs {0 {:class :actor}
1 {:class :item}
2 {:class :adverb}}}
{:text "You check your messages."
:follow-ups {:optional? false
:options [{:text "%0 %1"
:subs {0 {:class :person :config #{:no-groups}}
1 {:class :dialogue}}}]}}
{:text "You read morning paper."
:follow-ups {:optional? false
:options {:text "%0"
:subs {0 {:class :news}}}}}
{:text "%0 gently places %1 on the ground and then backs away slowly."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 %1 %2."
:subs {0 {:class :actor}
1 {:class :action}
2 {:class :actor}}}
{:text "%0 %1 you."
:subs {0 {:class :actor}
1 {:class :action}}}
{:text "%0 drops %1 here."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 does a little jig. 'Bidibidibidi, wanna dance?'"
:subs {0 {:class :actor}}}
{:text "%0 marches up to you and says, 'Hello please.'"
:subs {0 {:class :person}}}
{:text "%0 starts breakdancing and won't stop no matter how much you scream."
:subs {0 {:class :person}}}
{:text "%0 attacks you and knocks you out. You awake sometime later %1."
:subs {0 {:class :actor}
1 {:class :location}}}
{:text "%0 attacks you but you fight back with %1,"
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "winning the battle."}
{:text "taking only a hit to your pride."}]}}
{:text "%0 attacks you but you fight back with %1."
:subs {0 {:class :actor}
1 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "It isn't enough: you lose."}
{:text "This scares the shit out of %2. %3 runs away."
:subs {2 {:ref 0
:class :gender
:case :objective}
3 {:ref 0
:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You execute %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "You are victorious!"}
{:text "You have been killed."}
{:text "You have been slain!"}
{:text "%0 keels over all dead and stuff."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "%0 attacks with %1. You respond with %2. You are defeated."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}}
{:text "%0 attacks with %1. You strike back with %2. FATALITY. But who?!"
:subs {0 {:class :actor}
1 {:class :attack}}}
{:text "%0 attacks with %1. You with %2."
:subs {0 {:class :actor}
1 {:class :attack}
2 {:class :attack}}
:follow-ups {:optional? false
:options [{:text "Look at you what with the killing and all."}
{:text "%0 is a bloodstain."
:subs {0 {:class :gender
:case :subjective}}}]}}
{:text "Suddenly you're in freeze-frame as the credits roll."}
{:text "%0 appears in a puff of smoke, %1"
:subs {0 {:class :person}
1 {:class :actor-action}}}
{:text "You startle %0 who drops %1 and runs away."
:subs {0 {:class :person}
1 {:class :item}}}
{:text "%0 slams down a half-empty glass of %1."
:subs {0 {:class :person}
1 {:class :drink :config #{:no-prep :no-article}}}
:follow-ups {:optional? false
:options [{:text "'All this nonsense about %0 needs to stop! I can't take it anymore!'"
:subs {0 {:class :item}}}
{:text "'They're making plans for Nigel! They want what's best for him!'"}
{:text "'You can't go up against city hall!'"}
{:text "'I just can't take you seriously anymore!'"}
{:text "'MOM?!'"}]}}
{:text "%0 suddenly shrieks."
:subs {0 {:class :person}}}
{:text "%0 makes a rude noise, points surreptitiously to %1 nearby."
:subs {0 {:class :person}
1 {:class :animal}}}
{:text "You get tired of waiting for";
:follow-ups {:optional? false
:options [{:text "your Uber and decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "your private jet so you decide to walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}
{:text "the all-you-can-eat-buffet to open so you walk to %0 instead."
:subs {0 {:class :location :config #{:no-prep}}}}]}}
{:text "The phone rings."
:follow-ups {:optional? false
:options [{:text "%0 stares at it %1. Eventually the ringing stops."
:subs {0 {:class :person}
1 {:class :adverb}}}
{:text "%0 watches as it starts to melt, the sound of the ring slowing and burbling to a stop."
:subs {0 {:class :person}}}
{:text "%0 picks it up, listens a moment, shrieks, and slams the phone down again."
:subs {0 {:class :person}}}
{:text "%0 picks it up, says, 'It's for you,' but you're longer there."
:subs {0 {:class :person}}}]}}
{:text "You start eating %0 and don't stop until you're done."
:subs {0 {:class :food}}}
{:text "You eat %0."
:subs {0 {:class :food}}
:follow-ups {:optional? true
:options [{:text "%0 looks on %1."
:subs {0 {:class :actor}
1 {:class :adverb}}}]}}
{:text "You think to yourself, '%0'"
:subs {0 {:class :thought}}}
{:text "You pause and think, '%0'"
:subs {0 {:class :thought}}}
{:text "You feel a little famished so you eat %0."
:subs {0 {:class :food}}}
{:text "You take a sip of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "You check your inventory."
:follow-ups {:optional? true
:options [{:text "You are empty-handed."}
{:text "You are carrying %0, %1, and %2."
:subs {0 {:class :item}
1 {:class :item}
2 {:class :item}}}
{:text "You have %0 and %1."
:subs {0 {:class :item}
1 {:class :item}}}]}}
{:text "You open up %0."
:subs {0 {:class :book}}
:follow-ups {:optional? false
:options [{:text "Someone has scribbled all over the margins. You throw it down on the floor in disgust."}
{:text "Someone has left a recipe for beef stew inside."}
{:text "You read a bit before tossing it over your shoulder and then doing the electric slide."}]}}
{:text "%0 suddenly appears out of the shadows and"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "hisses at you, then scrambles away like a spider."}
{:text "says, 'Oh, sorry about that,' then retreats back into the shadows."}
{:text "says, '%0 will see you now,' then slowly retreats back into the shadows."
:subs {0 {:class :actor}}}]}}
{:text "%0 picks up %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "An overhead loudspeaker crackles to life,"
:follow-ups {:optional? false
:options [{:text "'Citizen! Report immediately to the nearest oddly-angled inner tube.'"}
{:text "'Citizen! Report immediately to the nearest self-incrimination booth.'"}
{:text "'Citizen! Report immediately to the nearest Java stacktrace.'"}
{:text "'Citizen! Report immediately to the bean simulator.'"}
{:text "'Citizen! Report immediately to the nearest certified manhole.'"}
{:text "'Citizen! Report immediately to the National Baby Oil Slip-n-Slide.'"}
{:text "'Citizen! Report immediately to the Hall of Uncomfortable Touching.'"}
{:text "'Citizen! Report immediately to the Bakery of Unravelled Cinnamon Buns.'"}
{:text "'Citizen! Stop that.'"}
{:text "'Citizen! Report immediately to the Readers' Digest Condensation Camp.'"}
{:text "'Citizen! Open up your textbook and turn to the chapter concerning your death.'"}
{:text "'Citizen! Report immediately to the Out-of-Control Rototiller Museum.'"}
{:text "'Citizen! Report immediately to the nearest mandatory prison hug.'"}
{:text "'Citizen! Report immediately to the nearest sanctioned dogpile.'"}
{:text "'Citizen! Report immediately to the nearest full-contact Bible study group.'"}
{:text "'Citizen! Report immediately to the mannequin factory.'"}
{:text "'Citizen! Report immediately to The Garbagerie.'"}
{:text "'Citizen! Report immediately to Stall #3.'"}
{:text "'Citizen! Just shut up already.'"}]}}
{:text "An overhead loudspeaker crackles to life. The announcement is completely garbled. The loudspeaker switches off with a squawk."}
{:text "You start spinning around and around."
:follow-ups {:optional? false
:options [{:text "%0 looks unimpressed."
:subs {0 {:class :person}}}
{:text "%0 faints."
:subs {0 {:class :person}}}
{:text "You drill straight into the crust of the earth."}
{:text "You gracefully lift off into a blue sky."}
{:text "You gracefully lift off into a blue sky never to be seen again."}
{:text "You gracefully lift off, go sideways, and crash into a building."}]}}
{:text "You start spinning around and around while"
:follow-ups {:optional? false
:options [{:text "%0 claps and cheers."
:subs {0 {:class :person}}}
{:text "%0 cries and points."
:subs {0 {:class :person}}}
{:text "%0 writes furiously on a clipboard."
:subs {0 {:class :person}}}
{:text "%0 beams with pride."
:subs {0 {:class :person}}}]}}
{:text "%0 is calling from %1 asking for %2."
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}
2 {:class :item}}}
{:text "%0 is calling from %1"
:subs {0 {:class :person}
1 {:class :location :config #{:no-prep}}}
:follow-ups {:optional? false
:options [{:text "asking if %2 can come out and play."
:subs {2 {:class :person}}}]}}
{:text "You peek out the window."
:follow-ups {:optional? true
:options [{:text "%0 is messing around with your mailbox. You crouch in fear."
:subs {0 {:class :person}}}
{:text "%0 is laying facedown in your flowerbed. You sink to your knees with worry."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's on fire."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. It's covered in bees."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand in your yard. The line stretches around the block."
:subs {0 {:class :person}}}
{:text "%0 has set up a lemonade stand across the street. You feel oddly jealous."
:subs {0 {:class :person}}}
{:text "%0 is struggling to start a chainsaw while staring at you. You bite your knuckle."
:subs {0 {:class :person}}}
{:text "%0 is standing in your yard, painting a portrait of you peeking out the window."
:subs {0 {:class :person}}}
{:text "Your entire house has been encased in a giant stone column."}]}}
{:text "In the distance,"
:follow-ups {:optional? false
:options [{:text "you hear %0 let the bass drop."
:subs {0 {:class :person}}}
{:text "you hear %0 drop the mic."
:subs {0 {:class :person}}}
{:text "you hear %0 get wicked."
:subs {0 {:class :person}}}
{:text "you hear %0 shake it off."
:subs {0 {:class :person}}}]}}
{:text "A magician saws you in half... lengthwise."}
{:text "You check your health: you are %0."
:subs {0 {:class :diagnose}}}
{:text "You find yourself being slowly teleported away. Very slowly. People are beginning to stare."}]})
(def secondary-events
{:secondary-events
[{:text "You see %0 here."
:subs {0 {:class :item}}}
{:text "You see %0 here. It looks oddly familiar."
:subs {0 {:class :item}}}
{:text "There is %0 here."
:subs {0 {:class :item}}}
{:text "You pick up %0. It's covered in dust."
:subs {0 {:class :item}}}
{:text "You pick up %0."
:subs {0 {:class :item}}}
{:text "You drop %0 here."
:subs {0 {:class :item}}
:follow-ups {:optional? true
:options [{:text "It bursts into flames."}
{:text "It turns into a wisp of smoke."}
{:text "And then some really bad CGI happens."}
{:text "It pierces the crust of the Earth."}
{:text "It bounces right back into your hand."}]}}
{:text "You find %0 here. You back away %1."
:subs {0 {:class :item}
1 {:class :adjective}}}
{:text "%0 is here."
:subs {0 {:class :actor}}}
{:text "%0 is here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "You find %0 here %1"
:subs {0 {:class :actor}
1 {:class :actor-action}}}
{:text "%0 %1"
:subs {0 {:class :person}
1 {:class :dialogue}}}
{:text "%0 is here searching for %1."
:subs {0 {:class :actor}
1 {:class :item}}}
{:text "%0 is here with %1. They look %2."
:subs {0 {:class :actor}
1 {:class :actor}
2 {:class :adjective}}}
{:text "%0 follows you."
:subs {0 {:class :actor}}}
{:text "%0 slinks up behind you."
:subs {0 {:class :actor}}}
{:text "%0 wanders by,"
:subs {0 {:class :actor}}
:follow-ups {:optional? false
:options [{:text "doing algebra and shit."}
{:text "playing a recorder."}
{:text "jamming on a mouth organ."}
{:text "wearing a cape."}
{:text "casually on fire."}
{:text "followed by a classy balloon."}
{:text "whistling the theme to the Andy Griffith Show."}
{:text "whistling the theme to the Garry Shandling Show."}]}}
{:text "A hollow voice intones, '%0'"
:subs {0 {:class :intonation}}}
{:text "Something smells %0 here."
:subs {0 {:class :scent}}}
{:text "It smells %0."
:subs {0 {:class :scent}}}
{:text "You hear %0 in the distance."
:subs {0 {:class :noise}}}
{:text "You hear the sound of %0 nearby."
:subs {0 {:class :noise}}}
{:text "The wind howls in the distance."}
{:text "It appears abandoned."}
{:text "Someone has been here recently."}
{:text "There are fresh footprints here."}
{:text "It seems that no one has been here for a long time."}
{:text "Someone has attached marionnette wires to your hands, feet, and head."}
{:text "Someone has left a running bulldozer here."}
{:text "The words 'eat dulp' are spray-painted on a wall here."}
{:text "The words 'Knifekitten lives!' are spray-painted on a wall here."}
{:text "The words 'Hammerdog lives!' are spray-painted on a wall here."}
{:text "Spray-painted on the wall here are the words 'Alice?! Alice?! Who the f...'. The rest is illegible."}
{:text "An ice cream truck goes by. It's on fire."}
{:text "A fire truck goes by. It's covered in ice."}
{:text "There has been significant damage from %0."
:subs {0 {:class :disaster}}}
{:text "You see a sign here. On it is written '%0'"
:subs {0 {:class :sign}}}]})
(def tertiary-events
{:tertiary-events
[{:text "You aren't wearing any clothes."}
{:text "Your clothes feel too small."}
{:text "Your clothes feel too loose."}
{:text "You're certain these aren't your clothes."}
{:text "Your shoes are on the wrong feet."}
{:text "Your tie feels uneven."}
{:text "You're wearing two bowties for some reason."}
{:text "You're not wearing any underwear."}
{:text "You're wearing two pairs of underwear."}
{:text "Someone is struggling with warped Tupperware nearby."}
{:text "You do a little jig and then whistle."}
{:text "You clap once."}
{:text "You have socks on your hands."}
{:text "You slowly slide your hands into your pockets. You regret this immediately."}
{:text "You feel serene."}
{:text "You feel nervous."}
{:text "You feel anxious."}
{:text "You feel cold."}
{:text "You feel warm."}
{:text "You aren't alone."}
{:text "You blink really slowly."}
{:text "You find yourself humming the theme to Too Many Cooks."}
{:text "You hear gunfire in the distance."}
{:text "You hear a party in the distance."}
{:text "You hear a toilet flush nearby."}
{:text "Someone is having fun against their will nearby."}
{:text "You yawn."}
{:text "You sneeze."}
{:text "You cough."}
{:text "You chuckle to yourself."}
{:text "You practice frowning for awhile."}
{:text "You begin to smile uncontrollably."}
{:text "You wish you had your grandpappy's harmonica."}
{:text "You are starting to feel sleepy."}
{:text "You glance at your watch; you're running 15 minutes late."}
{:text "You glance at your watch; somehow, you're still on time."}
{:text "You glance at your watch; you're a little ahead of schedule."}
{:text "You spend a few moments thinking fondly about your teeth."}
{:text "You feel as if you're being followed."}
{:text "A warm breeze blows by."}
{:text "A cool breeze blows by."}
{:text "It starts to rain."}
{:text "It starts to snow."}
{:text "Thunder coughs gently in the distance."}
{:text "A basketball bounces by."}
{:text "Something nearby is on fire."}
{:text "You can smell something burning in the distance."}
{:text "You look around nervously."}
{:text "You spot a balloon stuck in a tree."}
{:text "You spot a kitten stuck in a tree."}
{:text "You spot an office desk in a tree."}
{:text "You spot a bonsai tree stuck in a regular tree."}
{:text "You see a pair of sneakers dangling on a utility line overhead."}
{:text "Someone nearby is repeatedly zipping and unzipping a duffel bag."}
{:text "Somehow, you've lost your %0."
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "You hear someone nearby typing away on a manual typewriter."}
{:text "You're catching your second wind."}
{:text "You are starting to feel thirsty."}
{:text "You feel better."}
{:text "You have died."}
{:text "You are starting to feel hungry."}]})
(def actor-actions
{:actor-actions
[{:text "looking %0."
:subs {0 {:class :adjective}}}
{:text "being chased by a swarm of balloon animals."}
{:text "being chased by %0."
:subs {0 {:class :person}}}
{:text "being chased by %0 which is attached to them by a string."
:subs {0 {:class :item}}}
{:text "dancing furiously."}
{:text "dancing extremely slowly."}
{:text "shouting at an imaginary helicopter."}
{:text "doing the Kenosha Kid."}
{:text "thinking %0 about %1."
:subs {0 {:class :adverb}
1 {:class :actor}}}
{:text "being chased around by a bee."}
{:text "defiantly eating Scrabble tiles, one by one."}
{:text "%0 playing the organ."
:subs {0 {:class :adverb}}}
{:text "organizing matches."}
{:text "having a Guru Meditation Error."}
{:text "juggling some balls."}
{:text "dancing in a little circle."}
{:text "stooping up and down like a rapper in concert."}
{:text "drooling uncontrollably."}
{:text "clutching a DVD of Dot & the Kangaroo."}
{:text "clutching a DVD of BMX Bandits."}
{:text "wearing an eyepatch."}
{:text "wearing two eyepatches and stumbling around blindly."}
{:text "hiding under a table."}
{:text "hiding under a sofa."}
{:text "hiding in the bushes."}
{:text "munching on %0."
:subs {0 {:class :food}}}
{:text "pretending to be invisible."}
{:text "having a coughing fit."}
{:text "having a sneezing fit."}
{:text "being menaced by %0."
:subs {0 {:class :animal}}}
{:text "ready to start some shit."}
{:text "examining %0 with great confusion."
:subs {0 {:class :item}}}]})
(def locations
{:locations
[{:text "dead-end"
:type :interior
:article "a"
:preps ["at" "in front of"]
:follow-ups {:optional? true
:options [{:text "You start to moonwalk away."}
{:text "Someone has painted a giant sad face here."}]}}
{:text "ice skating rink"
:type :exterior
:article "an"
:preps ["at" "in front of" "on"]
:follow-ups {:optional? true
:options [{:text "It's currently on fire."}
{:text "Unfortunately, it's made of dry ice."}
{:text "A solid-gold curling stone is nearby."}
{:text "There are three hungry-looking zambonies here."}]}}
{:text "movie set"
:type :exterior
:article "a"
:preps ["on"]
:follow-ups {:optional? true
:options [{:text "The crafts table is covered with another, smaller crafts table."}
{:text "A nude man strolls by."}
{:text "A hundred tiny dogs are here, looking menacing."}]}}
{:text "particle board storage facility"
:type :interior
:article "a"
:preps ["at" "near" "in front of" "behind" "inside"]}
{:text "tire fire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is warm and welcoming."}
{:text "Someone had been roasting marshmallows here."}
{:text "The air here is black with despair and entropy."}
{:text "The sky is darkened by the hellish smoke."}]}}
{:text "dildo bonfire"
:type :exterior
:article "a"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "You look closely but don't recognize any of them."}
{:text "The plastic hisses and creaks in the blaze."}
{:text "The smoke smells of vanilla."}
{:text "The air is dense with the echoes of unreached orgasms."}]}}
{:text "hot tub"
:type :interior
:article "a"
:preps ["in near"]
:follow-ups {:optional? true
:options [{:text "The water roils and steams like water roils and steams."}
{:text "It's frozen solid."}
{:text "A basketball dances on the bubbles."}
{:text "You see a staircase beneath the water."}
{:text "Is it water or is it hydrocarbons?"}
{:text "It smells delicious because someone filled it with chicken soup."} ]}}
{:text "maze of twisty little passages, all alike"
:type :interior
:article "a"
:preps ["in"]}
{:text "Burning Man"
:type :exterior
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "Oddly, no one appears to be here."}
{:text "A tumbleweed made out of human hair stumbles by."}
{:text "A dust storm is approaching."}
{:text "It looks like it might rain soon."}
{:text "Snow is gently falling."}
{:text "%0 is here, looking %1."
:subs {0 {:class :person}
1 {:class :adjective}}}
{:text "Clearly the drugs have begun to take hold."}]}}
{:text "Shrim Healing Center"
:type :exterior
:article "a"
:preps ["in" "at" "in front of" "behind"]
:follow-ups {:optional? true
:options [{:text "There are TVs in the window, all turned off."}
{:text "Someone has spray-painted 'I crave brown baths' here."}
{:text "Inside you hear the sound of repulsed joy."}
{:text "The door has been boarded up."}
{:text "%0 is patiently waiting in line by %1."
:subs {0 {:class :person}
1 {:class :gender
:case :compound}}}
{:text "The building looks like it has been condemned."}]}}
{:text "quicksand"
:type :exterior
:article "some"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Briefly, you see a fin rise up and cruise back and forth."}
{:text "The surface quicksand gently sways, beckoning you..."}
{:text "Oddly, it smells like freshly cooked oatmeal."}]}}
{:text "swimming pool"
:type :exterior
:article "a"
:preps ["in" "at" "near"]
:follow-ups {:optional? true
:options [{:text "The surface of the pool is almost entirely still. You are afraid to disturb it."}
{:text "The water has turned slightly murky; it does not look inviting."}
{:text "The surface of the pool is littered with leaves."}
{:text "The pool is empty."}
{:text "The pool is empty. A broken skateboard is nearby."}
{:text "A dead bird floats by."}
{:text "An abandoned plastic float with a dinosaur's head floats lonely nearby."}]}}
{:text "PI:NAME:<NAME>END_PI"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The wood paneling sweats sweetly in the oppressive heat."}
{:text "Great thunderheads of steam rise up from the rock basin, making it hard to see."}
{:text "The room is cold and dark. No one has been here in years."}
{:text "The floor is covered with cute little mushrooms."}]}}
{:text "New York Public Library"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]}
{:text "PI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It stretches out in front of you, meandering as if drunk."}
{:text "A giant marshmallow avalanche blocks the way ahead."}
{:text "A small trickle of spaghetti sauce runs down the middle."}]}}
{:text "PI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The dusty stench of aged sewage gives you a hug."}
{:text "It is completely blocked here by a giant boulder."}
{:text "A trickle of clear water runs down the middle of it."}]}}
{:text "dump"
:type :exterior
:article "the"
:preps ["at" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "In the distance, you see a hazy castle."}
{:text "The hill of trash shifts dangerously beneath your feet."}]}}
{:text "dump truck"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "It's covered with a patina of black filth."}
{:text "Fresh off the line, it gleams bright red."}
{:text "The engine rumbles roughly to itself. The doors are locked."}]}}
{:text "Starbucks"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is packed tightly with hipsters."}
{:text "There is a surprising lack of hipsters here."}
{:text "It reeks of slightly burnt coffee here."}]}}
{:text "park restroom stall"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The door has been torn off its hinges."}
{:text "The walls are covered with violent scratches."}
{:text "The toilet is made of solid gold."}
{:text "A garden gnome greets you from the bowl."}
{:text "The toilet is missing."}
{:text "There's a basketball in the bowl."}
{:text "Suddenly the lights go out."}
{:text "The lingering scents of lemon and Lysol haunt the air."}
{:text "Someone has scratched your name and number on the wall."}]}}
{:text "all-you-can-eat buffet"
:type :interior
:article "an"
:preps ["at"]
:follow-ups {:optional? true
:options [{:text "It looks abandoned."}
{:text "Bullet time means more eggrolls."}
{:text "Steam crowds the air."}
{:text "It's all gluten-free and vegan. You leave immediately."}
{:text "It smells of freedom and gluttony."}
{:text "All of the food has been replaced with wax replicas."}
{:text "It's in complete disarray and hasn't been tended for some time."}]}}
{:text "gPI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The ceiling is sparkling with reflected light."}
{:text "The water is darkened with greenish-gray algae."}
{:text "The pool of water seems unusually deep. A lean, black fish swims in a circle."}]}}
{:text "bedroom"
:type :interior
:article "your"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It hasn't been cleaned in a long time."}
{:text "There's a pleasantly disgusting smell here."}
{:text "It's small and lightly furnished. The bed is unmade."}
{:text "There is nothing special about it."}
{:text "You notice an unusual stain in the carpet."}
{:text "There's an unusual stain in the carpet next to a usual stain."}
{:text "The ceiling fan is spinning dangerously fast."}
{:text "The walls are covered with %0 posters."
:subs {0 {:class :person}}}
{:text "There's a pile of clothes nearby."}]}}
{:text "PI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "White Castle"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "It's white and vaguely castle-shaped."}
{:text "It smells squarely delicious."}]}}
{:text "PI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "dark area"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is pitch black here. You're likely to be eaten by %0."
:subs {0 {:class :actor}}}
{:text "It's really dark here. Like... REALLY dark."}
{:text "It just got slightly darker somehow."}
{:text "It's so dark you can taste it. Tastes like dark."}
{:text "It's dark here. DARK AS YOUR SOUL."}]}}
{:text "breezy cave"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "There's a constant breeze rising up from the depths."}
{:text "Wide and low, the cave gently slopes %0-%1 here."
:subs {0 {:class :direction}
1 {:class :direction}}}
{:text "It smells of warm packing peanuts."}
{:text "It's really breezy. Gale-force breezy."}
{:text "It's seems over-oxygenated. You get light-headed."}
{:text "The cave seems to be breathing rapidly."}]}}
{:text "forest"
:type :exterior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is a dense, dark, and tangled choke of gnarled trees, thorny underbrush, and spiky thickets."}
{:text "Shot through with shafts of light, the forest before you looks serene."}
{:text "The trees, mostly oak and spruce, sway gently in the occasional breeze."}
{:text "It's currently on fire."}
{:text "The trees are all inflated plastic."}
{:text "The trees ignore your incessant crying."}
{:text "Birds are chirping and rodents scamper through the underbrush."}]}}
{:text "riverbed"
:type :exterior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "It's dry and littered with rocks and branches."}
{:text "The water steadfastedly refuses to flow. It just sits there."}
{:text "Nearby two bears are standing on the water, defiantly."}
{:text "The river immediately parts and just keeps on parting."}
{:text "It's mostly dry, the flow of the water blocked by a beaver dams upstream."}]}}
{:text "AT&T Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "Apple Store"
:type :exterior
:article "an"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "ballpit"
:type :interior
:article "a"
:preps ["in" "near"]
:follow-ups {:optional? true
:options [{:text "Oddly, all of the balls here are the same color: orange."}
{:text "The ballpit seems unusually deep. You can't feel the bottom."}
{:text "It's been filled with Rubik's Cubes."}
{:text "It's empty except for one orange ball at the bottom."}
{:text "It contains only one ball: orange and 12' across."}
{:text "You get the feeling someone is swimming around in there."}]}}
{:text "airplane"
:type :interior
:article "an"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "There's no one else on board."}
{:text "You hear strange noises coming from the restroom."}
{:text "Somehow you have a dozen packets of pretzels."}
{:text "Someone drank your Fresca while you were napping."}
{:text "It's pitch black outside. Can grues fly?"}
{:text "The pilot says, 'We've reached our cruising altitude of 30 feet.'"}
{:text "The plane has been going straight up for hours now."}]}}
{:text "trunk of a car"
:type :interior
:article "the"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "A tire iron is digging into your back a little bit."}
{:text "There's a half-eaten bag of Bugles here."}
{:text "With all the trash in here, there's barely any room for you."}
{:text "It's pitch black. No room for a grue, luckily."}]}}
{:text "coffin"
:type :interior
:article "a"
:preps ["in" "near" "in front of"]
:follow-ups {:optional? true
:options [{:text "It is well upholstered."}
{:text "It smells of cotton candy in here for some reason."}
{:text "It smells of Aquanet in here. Makes sense."}
{:text "It's pitch black. It probably doesn't matter if ther's a grue here."}]}}
{:text "hugbox"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "You feel at home again."}
{:text "It's very warm in here. Perhaps too warm."}
{:text "It smells of stale sweat and lies, lies, lies..."}]}}
{:text "haunted house"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The house shrugs under its own entropy."}
{:text "An orange light wanders from window to window."}
{:text "A sign here reads: 'As seen on TV."}
{:text "Endless amounts of blood pour from the windows."}
{:text "Looks inviting except for the corpses littering the lawn."}]}}
{:text "graveyard"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "There is a freshly laid grave nearby."}
{:text "There is an open grave nearby. It's empty."}
{:text "There is an open grave nearby. There's a phone book in it."}
{:text "There is an open grave nearby. It's full of %0."
:subs {0 {:class :drink :config #{:no-article}}}}
{:text "There are fresh footprints here."}
{:text "A lazy mist drifts amongst the tombstones."}
{:text "The tombstones have been replaced by durable plastic bricks."}
{:text "All the graves are filled with Mr. Bubbles."}
{:text "The Christmas lights sure make it look festive."}
{:text "A disco ball spins lonely from a gnarled tree."}]}}
{:text "playground"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of"]
:follow-ups {:optional? true
:options [{:text "The equipment looks like it's never been used."}
{:text "Most of the equipment is missing or broken."}
{:text "You hear the sound of children laughing but no one else is here."}]}}
{:text "pile of diapers"
:type :exterior
:article "a"
:preps ["in" "near" "behind" "in front of" "underneath"]
:follow-ups {:optional? true
:options [{:text "Some of these look awfully familiar."}]}}
{:text "meeting"
:type :interior
:article "a"
:preps ["in"]
:follow-ups {:optional? true
:options [{:text "The room is crowded by tripods holding colorful charts."}
{:text "The projector is on, showing random photos of cats at play."}
{:text "The table is covered with a chalk outline."}
{:text "The chairs are all occupied by cobweb-encrusted skeletons."}
{:text "The room is almost full of balloons."}]}}
{:text "PI:NAME:<NAME>END_PI"
:type :exterior
:article "a"
:preps ["at" "in" "near" "behind" "in front of"]}
{:text "full-contact Bible study group"
:type :interior
:article "a"
:preps ["near" "behind" "in front of" "in"]
:follow-ups {:optional? true
:options [{:text "No one is here."}
{:text "They stare at you and begin to crowl."}
{:text "They're all covered with cuts and bruises."}
{:text "They're currently scrumming over a Bible."}]}}]})
(def dialogues
{:dialogues
[{:text "asks, 'Have you ever seen an elephant throw up?'"}
{:text "asks, 'Why am I holding this pitchfork?'"}
{:text "asks, 'How long is a man?'"}
{:text "asks, 'Where have you been?'"}
{:text "asks, 'Would you like to see my collection of tiny ceiling fans?'"}
{:text "asks, 'Which one are you?'"}
{:text "asks, 'Can I have a hug?'"}
{:text "asks, 'Are you following me?'"}
{:text "asks, 'Does it smell like %0 in here to you?'"
:subs {0 {:class :food}}}
{:text "asks, 'Have you got a flag?'"}
{:text "asks, 'Have you ever seen a grown man naked?'"}
{:text "asks, 'May I use your FAX machine?'"}
{:text "chants, 'It's time to pay the price.'"}
{:text "mumbles, 'You can't go up against city hall.'"}
{:text "mumbles, 'One day I'm going to burn this place to the ground.'"}
{:text "mumbles, 'SkPI:NAME:<NAME>END_PI ruined it all for everybody.'"}
{:text "mumbles, 'I've never been to Belize.'"}
{:text "says, 'It's true: the boot is the best McNugget shape.'"}
{:text "says, 'Wrong answer, chief.'"}
{:text "says, 'This is giving me the freak-out.'"}
{:text "says, 'How unfortunate.'"}
{:text "says, 'Well that really scrambles my eggs.'"}
{:text "says, 'I've been waiting for you.'"}
{:text "says, 'I can't find my heirloom clown suit.'"}
{:text "says, 'I can't find my %0.'"
:subs {0 {:class :garment :config #{:no-article}}}}
{:text "says, 'No money? No hamburger!'"}
{:text "says, 'It's like drinking a meatloaf!'"}
{:text "says, 'Took you long enough.'"}
{:text "says, 'I'm addicted to Kitty LPI:NAME:<NAME>END_PI III.'"}
{:text "says, 'Looks like I'm not having any mayonnaise.'"}
{:text "says, 'I'm a brown-belt in speed tai chi.'"}
{:text "says, 'I'm stuck in a poo loop.'"}
{:text "says, 'Well, that's a dead give away.'"}
{:text "says, 'If you asked me to have sex with you, I wouldn't say \"no\".'"}
{:text "says, 'I'm not an actor but I play one on television.'"}
{:text "says, 'That dog rode on a bus by itself."}
{:text "says, 'The time has come for me to deal with the fact that I'll never be PI:NAME:<NAME>END_PI, Jr.'"}
{:text "says, 'So I guess PI:NAME:<NAME>END_PI is going to be a thing now.'"}
{:text "says, 'I'm going to button up the top of my polo shirt to demonstrate I don't want to talk to you.'"}
{:text "says, 'I'm in a poo trance.'"}
{:text "says, 'I'm a source of fiber.'"}
{:text "says, 'Surrealism is the scourage of butane.'"}
{:text "says, 'This drink tastes like Sears!'"}
{:text "says, 'This teenager salad tastes like a slowly closing door.'"}
{:text "says, 'It never hurts to have a corpse open the door for you.'"}
{:text "says, 'The Swanson TV Dinner heard 'round the world.'"}
{:text "says, 'The membership card is edible.'"}
{:text "says, 'That bisexual really jazzed up my latte.'"}
{:text "shouts, 'You can't go up against city hall!'"}
{:text "shouts, 'You can't fold a cat!'"}
{:text "shouts, 'It keeps happening!'"}
{:text "shouts, 'They're having a brownout in Lagos!'"}
{:text "shouts, 'Don Quixote! Swingin' from a pipe!'"}
{:text "shrieks, 'What's this shit I keep hearing about erections?!'"}
{:text "shrieks, 'I'm living on the edge!'"}
{:text "shrieks, 'Boiled soil!'"}
{:text "shriefs, 'Baby-oil covered balloon animals for all!"}
{:text "sighs, 'I liked you better before the hip-replacement surgery.'"}
{:text "snarls, 'Siddown before ya fall down!'"}
{:text "whispers, 'Why are you talking in all lowercase?'"}
{:text "whispers, 'It puts the lotion on its skin...'"}
{:text "whispers, 'I've always wanted to be a creepy uncle.'"}
{:text "whispers, 'Fee was a Buddhist prodigy.'"}
{:text "whispers, 'There squats the brown clown.'"}
{:text "whispers, 'Sleep is unproductive and a waste of time.'"}
{:text "whispers, 'You just lost the game.'"}
{:text "yells, 'I warned you about stairs, bro! I told ya, dawg!'"}]})
(def thoughts
{:thoughts
[{:text "Why don't they put mayo in the can with the tuna?"}
{:text "%0 never has a second cup of coffee at home..."
:subs {0 {:class :person}}}
{:text "You can't go up against city hall."}
{:text "I've made a huge mistake."}
{:text "It's time to pay the price."}
{:text "Why don't they have Double Stuf Nutter Butters?"}
{:text "This'll all end in tears."}
{:text "Hey! But I didn't eat the mousse!"}
{:text "%0 still owes me a backrub."
:subs {0 {:class :person}}}
{:text "I wonder if I could forge us a Group 6 Access..."}]})
(def intonations
{:intonations
[{:text "Toast goes in the toaster."}
{:text "These pretzels are making me thirsty."}
{:text "For those who can make the journey, there is a place."}
{:text "Slightly uncomfortable pleasures."}
{:text "It is a winning cake."}
{:text "POKE 1024,0."}
{:text "Coitus?"}
{:text "Pave Canada."}
{:text "Your pilikia is all pau."}
{:text "The owls are not what they seem."}
{:text "Plugh."}
{:text "Zzyzx."}
{:text "Guch."}
{:text "Spigot."}
{:text "You sank my battleship."}
{:text "Sorry, but it couldn't be helped."}
{:text "Clean up in aisle 8A."}
{:text "Rabbit feces."}
{:text "Don't panic."}
{:text "Don't panic. Oh, all right. You can panic a little bit."}
{:text "Consider deeply the baked ham."}
{:text "You can't go up against city hall."}]})
(def signs
{:signs
[{:text "PI:NAME:<NAME>END_PI shave!"}
{:text "It's time to pay the price."}
{:text "You can't go up against city hall."}
{:text "For those who can make the journey, there is a place."}
{:text "Here lies Hammerdog, a dog made of hammers."}
{:text "Here lies Knifekitten, a kitten made of knives."}
{:text "When you're not reading this, it's written in Spanish."}
{:text "Now you know how hard it is to say \"Irish wristwatch\"."}]})
(def books
{:books
[{:text "the Bible"
:preps ["a copy of"]}
{:text "Catcher in the Rye"
:preps ["a copy of"]}
{:text "Infinite Jest"
:preps ["a copy of"]}
{:text "Gravity's Rainbow"
:preps ["a copy of"]}
{:text "A Prayer for Owen Meany"
:preps ["a copy of"]}
{:text "The Hitchhiker's Guide to the Galaxy"
:preps ["a copy of"]}]})
(def attacks
{:attacks
[{:text "%0"
:subs {0 {:class :actor}}}
{:text "%0"
:subs {0 {:class :item}}}
{:text "a judo chop"}
{:text "a Judeo chop"}
{:text "a filthy soap slap"}
{:text "a rough kitty lick"}
{:text "a high clownkick"}
{:text "a sad testicle tug"}
{:text "a sushi pants special"}
{:text "a rub cut"}
{:text "a rusty trombone"}
{:text "an antiparticle dildo"}
{:text "a Cleveland steamer"}
{:text "a wet hug"}
{:text "a prison hug"}
{:text "a reverse hug"}
{:text "Canadian disapproval"}
{:text "a dangling participle"}
{:text "a fancy uppercut"}
{:text "a flurry of tiny kisses"}
{:text "a forlorn sigh"}
{:text "a balloon"}
{:text "a spontaneous coma"}
{:text "a smug kidney punch"}
{:text "a bit of the ol' in-out"}
{:text "a atomic wedge"}
{:text "Vogon poetry"}
{:text "a bad British accent"}
{:text "poor grammar"}
{:text "Conservative politics"}
{:text "Liberal politics"}
{:text "secret.jpg"}
{:text "tubgirl.jpg"}
{:text "cute kittens"}
{:text "tumbly puppies"}
{:text "a weaponized beard"}
{:text "an apathetic hipster"}]})
(def directions
{:directions
[{:text "north"}
{:text "northeast"}
{:text "east"}
{:text "southeast"}
{:text "south"}
{:text "southwest"}
{:text "west"}
{:text "northwest"}]})
(def persons
{:persons
[{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "a police officer"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :female}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "your mom"
:gender :female}
{:text "a bunch of kids"
:gender :group}
{:text "a crowd of Yoga enthusiasts"
:gender :group}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "a gas station attendant"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "@akiva"
:gender :male}
{:text "@jimminy"
:gender :male}
{:text "@veo_"
:gender :male}
{:text "@vmcny"
:gender :male}
{:text "@KamenPrime"
:gender :male}
{:text "@ActuallySparky"
:gender :male}
{:text "@neonbubble"
:gender :male}
{:text "@micahwittman"
:gender :male}
{:text "@itafroma"
:gender :male}
{:text "@clive"
:gender :male}
{:text "@mokargas"
:gender :male}
{:text "@drew"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}
{:text "PI:NAME:<NAME>END_PI"
:gender :male}]})
(def actions
{:actions
[{:text "attacks"}
{:text "sneezes on"}
{:text "ignores"}
{:text "tickles"}
{:text "stands uncomfortably close to"}
{:text "violently points at"}
{:text "imitates"}
{:text "pets"}
{:text "examines"}
{:text "flirts with"}]})
(def adjectives
{:adjectives
[{:text "worried"}
{:text "relieved"}
{:text "aroused"}
{:text "afraid"}
{:text "nonplussed"}
{:text "sleepy"}
{:text "hungry"}
{:text "thirsty"}
{:text "bored"}
{:text "hopeful"}
{:text "sad"}
{:text "happy"}
{:text "forlorn"}
{:text "angry"}]})
(def adverbs
{:adverbs
[{:text "carefully"}
{:text "wistfully"}
{:text "uncertainly"}
{:text "willfully"}
{:text "lustfully"}
{:text "warily"}
{:text "solemnly"}
{:text "mournfully"}
{:text "proudly"}
{:text "bravely"}
{:text "sadly"}
{:text "happily"}
{:text "balefully"}]})
(def scents
{:scents
[{:text "acrid"}
{:text "sweet"}
{:text "sour"}
{:text "rotten"}
{:text "nice"}
{:text "foul"}
{:text "of feet"}
{:text "of your grandfather's hair cream"}
{:text "of warm peanut butter"}
{:text "bitter"}
{:text "smoky"}
{:text "gross"}
{:text "pleasant"}]})
(def diagnoses
{:diagnoses
[{:text "feeling great"}
{:text "feeling gross"}
{:text "absurdly sticky"}
{:text "lightly wounded"}
{:text "moderately wounded"}
{:text "heavily wounded"}
{:text "near death"}
{:text "sleepy"}
{:text "drunk"}
{:text "stoned"}
{:text "confused"}
{:text "hungry"}
{:text "thirsty"}
{:text "temporarily blind"}
{:text "temporarily deaf"}
{:text "covered in bees"}]})
(def foods
{:foods
[{:text "burrito"
:article "a"}
{:text "weaponized cornbread"
:article "some"}
{:text "persecution sandwich"
:article "a"}
{:text "tooth burger"
:article "a"}
{:text "bouquet of corndogs"
:article "a"}
{:text "corndog"
:article "a"}
{:text "pancakes"
:article "some"}
{:text "cake"
:article "a"}
{:text "cake"
:article "a slice of"}
{:text "kumquat"
:article "a"}
{:text "salad"
:article "a"}
{:text "Rice Chex"
:article "a bowl of"}
{:text "Reese's Peanut Butter Cup"
:article "a"}
{:text "apple pocket"
:article "an"}
{:text "block of cheese"
:article "a"}
{:text "wedge of cheese with some mold on it"
:article "a"}
{:text "slice of fried spam"
:article "a"}
{:text "delicious churro"
:article "a"}
{:text "chocolate bobka"
:article "a"}
{:text "sweetroll"
:article "a"}
{:text "Cinnabon"
:article "a"}
{:text "duck confit"
:article "some"}
{:text "pasta"
:article "some"}
{:text "uncooked rice"
:article "some"}
{:text "Fritos"
:article "some"}
{:text "sushi"
:article "some"}
{:text "apple cinnamon Pop Tart"
:article "an"}]})
(def drinks
{:drinks
[{:text "steaming gravy"
:article "a cup of"}
{:text "milk"
:article "a gallon of"}
{:text "orange juice"
:article "a glass of"}
{:text "tea"
:article "some"}
{:text "soda"
:article "some"}
{:text "water"
:article "some"}
{:text "beef broth"
:article "some"}
{:text "scotch"
:article "a"}]})
(def garments
{:garments
[{:text "hat"
:article "a"}
{:text "pants"
:article "some"}
{:text "shirt"
:article "a"}
{:text "gloves"
:article "some"}
{:text "shoes"
:article "some"}
{:text "belt"
:article "a"}
{:text "socks"
:article "some"}
{:text "coat"
:article "a"}
{:text "jacket"
:article "a"}
{:text "underwear"
:article "some"}
{:text "dress"
:article "a"}
{:text "skirt"
:article "a"}
{:text "schizophrenic mood ring"
:article "a"}
{:text "sweater"
:article "a"}
{:text "watch"
:article "a"}]})
(def items
{:items
[{:text "skinny jeans"
:article "a pair of"}
{:text "slick pellets"
:article "a bag of"}
{:text "fat-soluble PI:NAME:<NAME>END_PI"
:article "a bottle of"}
{:text "llama treats"
:article "a bag of"}
{:text "parachute pants"
:article "a pair of"}
{:text "Breakin' 2: Electric Boogaloo"
:article "a Laserdisc copy of"}
{:text "magic scroll"
:article "a"}
{:text "no tea"}
{:text "Snausages"
:article "some"}
{:text "slide rule"
:article "a"}
{:text "pinecone"
:article "a"}
{:text "sweat-incrusted trilby"
:article "a"}
{:text "vitamins"
:plural true
:article "some"}
{:text "bucket of corks"
:article "a"}
{:text "PI:NAME:<NAME>END_PI"
:article "a pair of"}
{:text "non-Euclidian Lego"
:article "a"}
{:text "spray-on bacon"
:article "a can of"}
{:text "spackle"
:article "a can of"}
{:text "unfamiliar briefcase"
:article "an"}
{:text "towel from the Las Vegas Radisson"
:article "a"}
{:text "receipt from a bunny outfit rental"
:article "a"}
{:text "floppy disk"
:article "a"}
{:text "pencil"
:article "a"}
{:text "lantern"
:article "a"}
{:text "elven sword"
:article "an"}
{:text "books"
:article "some"}
{:text "movie ticket"
:article "a"}
{:text "newspaper"
:article "a"}
{:text "kitten"
:article "a"}
{:text "puppy"
:article "a"}
{:text "bag of potatoes"
:article "a"}
{:text "bag of rice"
:article "a"}
{:text "giant styrofoam peanut"
:article "a"}
{:text "phone book"
:article "a"}
{:text "pyramid of tennis balls"
:article "a"}
{:text "deflated soccer ball"
:article "a"}
{:text "fourth grade report card"
:article "your"}
{:text "half-eaten sandwich"
:article "a"}
{:text "signed photograph of PI:NAME:<NAME>END_PI"
:article "a"}
{:text "hipster t-shirt"
:article "a"}
{:text "pile of discarded puppets"
:article "a"}
{:text "wet Lincoln Log"
:article "a"}
{:text "VHS tape covered in blood"
:article "a"}]})
(def animals
{:animals
[{:text "kitten"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "cat"
:article "a"
:sounds ["purrs" "meows" "growls"]
:adjectives ["purring" "meowing" "growling"]}
{:text "puppy"
:article "a"
:sounds ["pants" "barks" "growls" "whimpers"]
:adjectives ["panting" "barking" "growling" "whimpering"]}
{:text "duck"
:article "a"
:sounds ["quacks"]
:adjectives ["quacking"]}
{:text "marPI:NAME:<NAME>END_PI"
:article "a"}
{:text "tiger"
:article "a"
:sounds ["roars"]
:adjectives ["roaring"]}
{:text "hamster"
:article "a"}
{:text "gerbil"
:article "a"}
{:text "hedgehog"
:article "a"}]})
(def noises
{:noises
[{:text "foghorn"
:article "a"}
{:text "laughter"
:article "some"}
{:text "laughing"
:article "somebody"}
{:text "chuckling"
:article "someone"}
{:text "cackling"
:article "someone"}
{:text "crying"
:article "someone"}
{:text "sobbing"
:article "someone"}
{:text "sneeze"
:article "a"}
{:text "wolves howling"}
{:text "ice cream truck"
:article "an"}
{:text "door slam"
:article "a"}
{:text "sinister chuckle"
:article "a"}]})
(def disasters
{:disasters
[{:text "fire"
:article "a"}
{:text "tornado"
:article "a"}
{:text "hurricane"
:article "a"}
{:text "flood"
:article "a"}
{:text "tsunami"
:article "a"}
{:text "landslide"
:article "a"}
{:text "avalanche"
:article "an"}
{:text "radioactive leak"
:article "a"}
{:text "lava flow"
:article "a"}
{:text "sandstorm"
:article "a"}
{:text "lightning strike"
:article "a"}
{:text "plague of locusts"
:article "a"}
{:text "snowstorm"
:article "a"}
{:text "duststorm"
:article "a"}]})
(def obstacles
{:obstacles
[{:text "a black comb on the ground"}
{:text "a stack of dogs going all the way to the moon"}
{:text "PI:NAME:<NAME>END_PI grin"}
{:text "an obstinant balloon expert"}
{:text "a pile of corroded Ewoks"}
{:text "a horrible taste in your mouth"}
{:text "a movie being shown in the wrong aspect ratio"}
{:text "someone who has never listened to Neutral Milk Hotel"}
{:text "the thing your aunt gave you which you don't know what it is"}
{:text "an aquarium full of milk"}
{:text "dubstep"}
{:text "a 404 error"}
{:text "PI:NAME:<NAME>END_PI's career"}
{:text "that awful man"}
{:text "a dude who insists on putting his hand in his girlfriend's back pocket"}
{:text "a maelstrom of hipster beards"}
{:text "a wall of tepid soup"}
{:text "a giant cat tongue"}
{:text "PI:NAME:<NAME>END_PI' neck"}
{:text "Ruby On Rails"}
{:text "someone who takes too many selfies"}
{:text "a cat who has been pet against the grain"}
{:text "substandard prequels"}
{:text "the Scut Farkus Affair"}
{:text "a lack of retweets"}
{:text "a sweaty 486DX4 chip"}
{:text "a convenient reclosing tab"}
{:text "a lengthy German noun"}
{:text "your own unwillingness to improve yourself"}
{:text "%0's sheer force of will"
:subs {0 {:class :person}}}
{:text "%0's birthday party"
:subs {0 {:class :person}}}
{:text "a delicious Nutter Butter"}
{:text "double-double Animal style"}
{:text "someone who doesn’t know how to eat a goddamned Oreo properly"}]})
(def news
{:news
[{:text "Shamer Claims Bullying from Shame Shamers"}]})
(def games
{:games
[{:text "Agricola"
:type :tabletop}
{:text "Advanced Squad Leader"
:type :tabletop}
{:text "Carcassonne"
:type :tabletop}
{:text "World in Flames"
:type :tabletop}
{:text "Monopoly"
:type :tabletop}
{:text "World of Warcraft"
:type :video}
{:text "Civilization V"
:type :video}
{:text "Grand Theft Auto V"
:type :video}]})
(def classes
["events"
"location-events"
"action-events"
"secondary-events"
"tertiary-events"
"actor-actions"
"locations"
"dialogues"
"intonations"
"books"
"directions"
"persons"
"actions"
"adjectives"
"adverbs"
"scents"
"diagnoses"
"foods"
"drinks"
"signs"
"obstacles"
"garments"
"items"
"animals"
"noises"
"attacks"
"games"
"thoughts"
"news"
"disasters"])
|
[
{
"context": "q)\n (cmd/queue-bind ch c q x {\"routing_key\" \"acits.#\"})\n (Thread/sleep 300)\n (lb/publish ch ",
"end": 1188,
"score": 0.8760731220245361,
"start": 1181,
"tag": "KEY",
"value": "acits.#"
}
] | langohr/test/com/novemberain/acits/queue_bind_test.clj | michaelklishin/acits | 1 | (ns com.novemberain.acits.queue-bind-test
(:require [langohr.core :as lc]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.basic :as lb]
[com.novemberain.acits.commands :as cmd]
[clojure.test :refer :all]
[com.novemberain.acits.shared :refer [clients]]))
(defonce conn (lc/connect))
;;
;; Tests
;;
(deftest test-binding-a-durable-queue-to-predefined-fanout-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q1"
x "amq.fanout"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" ""})
(Thread/sleep 300)
(lb/publish ch x q "verify")
(is (lb/get ch q))
(lq/delete ch q))))
(deftest test-binding-a-durable-queue-to-predefined-topic-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q2"
x "amq.topic"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" "acits.#"})
(Thread/sleep 300)
(lb/publish ch x "acits.fanout" "verify")
(is (lb/get ch q))
(lq/delete ch q))))
| 81976 | (ns com.novemberain.acits.queue-bind-test
(:require [langohr.core :as lc]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.basic :as lb]
[com.novemberain.acits.commands :as cmd]
[clojure.test :refer :all]
[com.novemberain.acits.shared :refer [clients]]))
(defonce conn (lc/connect))
;;
;; Tests
;;
(deftest test-binding-a-durable-queue-to-predefined-fanout-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q1"
x "amq.fanout"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" ""})
(Thread/sleep 300)
(lb/publish ch x q "verify")
(is (lb/get ch q))
(lq/delete ch q))))
(deftest test-binding-a-durable-queue-to-predefined-topic-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q2"
x "amq.topic"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" "<KEY>"})
(Thread/sleep 300)
(lb/publish ch x "acits.fanout" "verify")
(is (lb/get ch q))
(lq/delete ch q))))
| true | (ns com.novemberain.acits.queue-bind-test
(:require [langohr.core :as lc]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.exchange :as le]
[langohr.basic :as lb]
[com.novemberain.acits.commands :as cmd]
[clojure.test :refer :all]
[com.novemberain.acits.shared :refer [clients]]))
(defonce conn (lc/connect))
;;
;; Tests
;;
(deftest test-binding-a-durable-queue-to-predefined-fanout-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q1"
x "amq.fanout"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" ""})
(Thread/sleep 300)
(lb/publish ch x q "verify")
(is (lb/get ch q))
(lq/delete ch q))))
(deftest test-binding-a-durable-queue-to-predefined-topic-exchange
(let [ch (lch/open conn)
q "acits.queue.bind.q2"
x "amq.topic"]
(doseq [c clients]
(println (format "Running queue binding test for client %s" c))
(lq/declare ch q)
(cmd/queue-bind ch c q x {"routing_key" "PI:KEY:<KEY>END_PI"})
(Thread/sleep 300)
(lb/publish ch x "acits.fanout" "verify")
(is (lb/get ch q))
(lq/delete ch q))))
|
[
{
"context": ".core))\n\n;; Color conversion function, courtesy of Jack Rusher\n(defn hex-to-rgb [hex]\n (map (comp #(Integer/par",
"end": 90,
"score": 0.9998058080673218,
"start": 79,
"tag": "NAME",
"value": "Jack Rusher"
}
] | src/vdquil/util.clj | Jjunior130/vdquil | 33 | (ns vdquil.util
(:use quil.core))
;; Color conversion function, courtesy of Jack Rusher
(defn hex-to-rgb [hex]
(map (comp #(Integer/parseInt % 16) (partial apply str))
(partition 2 (.replace hex "#" ""))))
(defn hex-to-color [hex]
(apply color (hex-to-rgb hex)))
| 62569 | (ns vdquil.util
(:use quil.core))
;; Color conversion function, courtesy of <NAME>
(defn hex-to-rgb [hex]
(map (comp #(Integer/parseInt % 16) (partial apply str))
(partition 2 (.replace hex "#" ""))))
(defn hex-to-color [hex]
(apply color (hex-to-rgb hex)))
| true | (ns vdquil.util
(:use quil.core))
;; Color conversion function, courtesy of PI:NAME:<NAME>END_PI
(defn hex-to-rgb [hex]
(map (comp #(Integer/parseInt % 16) (partial apply str))
(partition 2 (.replace hex "#" ""))))
(defn hex-to-color [hex]
(apply color (hex-to-rgb hex)))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998128414154053,
"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.9998273849487305,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/test/integration/font_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 integration.font-test
(:require [clojure.test :refer :all]
[clojure.string :as s]
[dynamo.graph :as g]
[integration.test-util :as test-util]
[editor.workspace :as workspace]
[editor.font :as font]
[editor.defold-project :as project]))
(defn- prop [node-id label]
(get-in (g/node-value node-id :_properties) [:properties label :value]))
(defn- prop! [node-id label val]
(g/transact (g/set-property node-id label val)))
(deftest load-material-render-data
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
scene (g/node-value node-id :scene)]
(is (not (nil? scene))))))
(deftest text-measure
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)]
(let [[w h] (font/measure font-map "test")]
(is (> w 0))
(is (> h 0))
(let [[w' h'] (font/measure font-map "test\ntest")]
(is (= w' w))
(is (> h' h))
(let [[w'' h''] (font/measure font-map "test\u200Btest" true w 0 1)]
(is (= w'' w'))
(is (= h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0 1)]
(is (= w'' w'))
(is (> h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0.1 1.1)]
(is (> w'' w'))
(is (> h'' h'))))))))
(deftest preview-text
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)
pre-text (g/node-value node-id :preview-text)
no-break (s/replace pre-text " " "")
[w h] (font/measure font-map pre-text true (:cache-width font-map) 0 1)
[ew eh] (font/measure font-map no-break true (:cache-width font-map) 0 1)]
(is (.contains pre-text " "))
(is (not (.contains no-break " ")))
(is (< w ew))
(is (< eh h)))))
(deftest validation
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")]
(is (nil? (test-util/prop-error node-id :font)))
(is (nil? (test-util/prop-error node-id :material)))
(test-util/with-prop [node-id :font nil]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :font (workspace/resolve-workspace-resource workspace "/not_found.ttf")]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :material nil]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(test-util/with-prop [node-id :material (workspace/resolve-workspace-resource workspace "/not_found.material")]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(doseq [p [:size :alpha :outline-alpha :outline-width :shadow-alpha :shadow-blur :cache-width :cache-height]]
(test-util/with-prop [node-id p -1]
(is (g/error-fatal? (test-util/prop-error node-id p))))))))
(defn pb-property [node-id property]
(get-in (g/node-value node-id :pb-msg) [property]))
(deftest antialias
(test-util/with-loaded-project
(let [score (test-util/resource-node project "/fonts/score.font")
score-not-antialias (test-util/resource-node project "/fonts/score_not_antialias.font")
score-no-antialias (test-util/resource-node project "/fonts/score_no_antialias.font")]
(is (= (g/node-value score :antialiased) true))
(is (= (g/node-value score :antialias) 1))
(is (= (pb-property score :antialias) 1))
(g/set-property! score :antialiased false)
(is (= (g/node-value score :antialias) 0))
(is (= (pb-property score :antialias) 0))
(is (= (g/node-value score-not-antialias :antialiased) false))
(is (= (g/node-value score-not-antialias :antialias) 0))
(is (= (pb-property score-not-antialias :antialias) 0))
(g/set-property! score-not-antialias :antialiased true)
(is (= (g/node-value score-not-antialias :antialias) 1))
(is (= (pb-property score-not-antialias :antialias) 1))
(is (= (g/node-value score-no-antialias :antialiased) true)) ; font_ddf defaults antialias to 1 = true
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialiased false)
(is (= (g/node-value score-no-antialias :antialias) 0))
(is (= (pb-property score-no-antialias :antialias) 0))
(g/set-property! score-no-antialias :antialiased true)
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialias) nil))
(is (= (pb-property score-no-antialias :antialias) nil))
(g/set-property! score-no-antialias :antialias 1)
(is (= (g/node-value score-no-antialias :antialiased) true))
(g/set-property! score-no-antialias :antialias 0)
(is (= (g/node-value score-no-antialias :antialiased) false))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialiased) nil)))))
(deftest font-scene
(test-util/with-loaded-project
(let [node-id (project/get-resource-node project "/fonts/logo.font")]
(test-util/test-uses-assigned-material workspace project node-id
:material
[:renderable :user-data :shader]
[:renderable :user-data :texture]))))
| 116352 | ;; 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 integration.font-test
(:require [clojure.test :refer :all]
[clojure.string :as s]
[dynamo.graph :as g]
[integration.test-util :as test-util]
[editor.workspace :as workspace]
[editor.font :as font]
[editor.defold-project :as project]))
(defn- prop [node-id label]
(get-in (g/node-value node-id :_properties) [:properties label :value]))
(defn- prop! [node-id label val]
(g/transact (g/set-property node-id label val)))
(deftest load-material-render-data
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
scene (g/node-value node-id :scene)]
(is (not (nil? scene))))))
(deftest text-measure
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)]
(let [[w h] (font/measure font-map "test")]
(is (> w 0))
(is (> h 0))
(let [[w' h'] (font/measure font-map "test\ntest")]
(is (= w' w))
(is (> h' h))
(let [[w'' h''] (font/measure font-map "test\u200Btest" true w 0 1)]
(is (= w'' w'))
(is (= h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0 1)]
(is (= w'' w'))
(is (> h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0.1 1.1)]
(is (> w'' w'))
(is (> h'' h'))))))))
(deftest preview-text
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)
pre-text (g/node-value node-id :preview-text)
no-break (s/replace pre-text " " "")
[w h] (font/measure font-map pre-text true (:cache-width font-map) 0 1)
[ew eh] (font/measure font-map no-break true (:cache-width font-map) 0 1)]
(is (.contains pre-text " "))
(is (not (.contains no-break " ")))
(is (< w ew))
(is (< eh h)))))
(deftest validation
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")]
(is (nil? (test-util/prop-error node-id :font)))
(is (nil? (test-util/prop-error node-id :material)))
(test-util/with-prop [node-id :font nil]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :font (workspace/resolve-workspace-resource workspace "/not_found.ttf")]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :material nil]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(test-util/with-prop [node-id :material (workspace/resolve-workspace-resource workspace "/not_found.material")]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(doseq [p [:size :alpha :outline-alpha :outline-width :shadow-alpha :shadow-blur :cache-width :cache-height]]
(test-util/with-prop [node-id p -1]
(is (g/error-fatal? (test-util/prop-error node-id p))))))))
(defn pb-property [node-id property]
(get-in (g/node-value node-id :pb-msg) [property]))
(deftest antialias
(test-util/with-loaded-project
(let [score (test-util/resource-node project "/fonts/score.font")
score-not-antialias (test-util/resource-node project "/fonts/score_not_antialias.font")
score-no-antialias (test-util/resource-node project "/fonts/score_no_antialias.font")]
(is (= (g/node-value score :antialiased) true))
(is (= (g/node-value score :antialias) 1))
(is (= (pb-property score :antialias) 1))
(g/set-property! score :antialiased false)
(is (= (g/node-value score :antialias) 0))
(is (= (pb-property score :antialias) 0))
(is (= (g/node-value score-not-antialias :antialiased) false))
(is (= (g/node-value score-not-antialias :antialias) 0))
(is (= (pb-property score-not-antialias :antialias) 0))
(g/set-property! score-not-antialias :antialiased true)
(is (= (g/node-value score-not-antialias :antialias) 1))
(is (= (pb-property score-not-antialias :antialias) 1))
(is (= (g/node-value score-no-antialias :antialiased) true)) ; font_ddf defaults antialias to 1 = true
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialiased false)
(is (= (g/node-value score-no-antialias :antialias) 0))
(is (= (pb-property score-no-antialias :antialias) 0))
(g/set-property! score-no-antialias :antialiased true)
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialias) nil))
(is (= (pb-property score-no-antialias :antialias) nil))
(g/set-property! score-no-antialias :antialias 1)
(is (= (g/node-value score-no-antialias :antialiased) true))
(g/set-property! score-no-antialias :antialias 0)
(is (= (g/node-value score-no-antialias :antialiased) false))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialiased) nil)))))
(deftest font-scene
(test-util/with-loaded-project
(let [node-id (project/get-resource-node project "/fonts/logo.font")]
(test-util/test-uses-assigned-material workspace project node-id
:material
[:renderable :user-data :shader]
[:renderable :user-data :texture]))))
| 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 integration.font-test
(:require [clojure.test :refer :all]
[clojure.string :as s]
[dynamo.graph :as g]
[integration.test-util :as test-util]
[editor.workspace :as workspace]
[editor.font :as font]
[editor.defold-project :as project]))
(defn- prop [node-id label]
(get-in (g/node-value node-id :_properties) [:properties label :value]))
(defn- prop! [node-id label val]
(g/transact (g/set-property node-id label val)))
(deftest load-material-render-data
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
scene (g/node-value node-id :scene)]
(is (not (nil? scene))))))
(deftest text-measure
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)]
(let [[w h] (font/measure font-map "test")]
(is (> w 0))
(is (> h 0))
(let [[w' h'] (font/measure font-map "test\ntest")]
(is (= w' w))
(is (> h' h))
(let [[w'' h''] (font/measure font-map "test\u200Btest" true w 0 1)]
(is (= w'' w'))
(is (= h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0 1)]
(is (= w'' w'))
(is (> h'' h')))
(let [[w'' h''] (font/measure font-map "test test test" true w 0.1 1.1)]
(is (> w'' w'))
(is (> h'' h'))))))))
(deftest preview-text
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")
font-map (g/node-value node-id :font-map)
pre-text (g/node-value node-id :preview-text)
no-break (s/replace pre-text " " "")
[w h] (font/measure font-map pre-text true (:cache-width font-map) 0 1)
[ew eh] (font/measure font-map no-break true (:cache-width font-map) 0 1)]
(is (.contains pre-text " "))
(is (not (.contains no-break " ")))
(is (< w ew))
(is (< eh h)))))
(deftest validation
(test-util/with-loaded-project
(let [node-id (test-util/resource-node project "/fonts/score.font")]
(is (nil? (test-util/prop-error node-id :font)))
(is (nil? (test-util/prop-error node-id :material)))
(test-util/with-prop [node-id :font nil]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :font (workspace/resolve-workspace-resource workspace "/not_found.ttf")]
(is (g/error-fatal? (test-util/prop-error node-id :font))))
(test-util/with-prop [node-id :material nil]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(test-util/with-prop [node-id :material (workspace/resolve-workspace-resource workspace "/not_found.material")]
(is (g/error-fatal? (test-util/prop-error node-id :material))))
(doseq [p [:size :alpha :outline-alpha :outline-width :shadow-alpha :shadow-blur :cache-width :cache-height]]
(test-util/with-prop [node-id p -1]
(is (g/error-fatal? (test-util/prop-error node-id p))))))))
(defn pb-property [node-id property]
(get-in (g/node-value node-id :pb-msg) [property]))
(deftest antialias
(test-util/with-loaded-project
(let [score (test-util/resource-node project "/fonts/score.font")
score-not-antialias (test-util/resource-node project "/fonts/score_not_antialias.font")
score-no-antialias (test-util/resource-node project "/fonts/score_no_antialias.font")]
(is (= (g/node-value score :antialiased) true))
(is (= (g/node-value score :antialias) 1))
(is (= (pb-property score :antialias) 1))
(g/set-property! score :antialiased false)
(is (= (g/node-value score :antialias) 0))
(is (= (pb-property score :antialias) 0))
(is (= (g/node-value score-not-antialias :antialiased) false))
(is (= (g/node-value score-not-antialias :antialias) 0))
(is (= (pb-property score-not-antialias :antialias) 0))
(g/set-property! score-not-antialias :antialiased true)
(is (= (g/node-value score-not-antialias :antialias) 1))
(is (= (pb-property score-not-antialias :antialias) 1))
(is (= (g/node-value score-no-antialias :antialiased) true)) ; font_ddf defaults antialias to 1 = true
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialiased false)
(is (= (g/node-value score-no-antialias :antialias) 0))
(is (= (pb-property score-no-antialias :antialias) 0))
(g/set-property! score-no-antialias :antialiased true)
(is (= (g/node-value score-no-antialias :antialias) 1))
(is (= (pb-property score-no-antialias :antialias) 1))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialias) nil))
(is (= (pb-property score-no-antialias :antialias) nil))
(g/set-property! score-no-antialias :antialias 1)
(is (= (g/node-value score-no-antialias :antialiased) true))
(g/set-property! score-no-antialias :antialias 0)
(is (= (g/node-value score-no-antialias :antialiased) false))
(g/set-property! score-no-antialias :antialias nil)
(is (= (g/node-value score-no-antialias :antialiased) nil)))))
(deftest font-scene
(test-util/with-loaded-project
(let [node-id (project/get-resource-node project "/fonts/logo.font")]
(test-util/test-uses-assigned-material workspace project node-id
:material
[:renderable :user-data :shader]
[:renderable :user-data :texture]))))
|
[
{
"context": "be ordered by.\n\n Example: [{:label \\\"Name\\\" :accessor :name}\n {:labe",
"end": 3589,
"score": 0.9361647367477417,
"start": 3585,
"tag": "NAME",
"value": "Name"
},
{
"context": "accessor :name}\n {:label \\\"Email\\\" :accessor :email}]\n\n :filter-fn predicate tha",
"end": 3648,
"score": 0.7877808213233948,
"start": 3643,
"tag": "NAME",
"value": "Email"
}
] | src/xtdb_inspector/ui/table.clj | tatut/xtdb-inspector | 18 | (ns xtdb-inspector.ui.table
"A table component with filtering."
(:require [ripley.html :as h]
[ripley.live.source :as source]
[ripley.live.collection :as collection]
[clojure.string :as str]
[ripley.js :as js]))
(defn- default-filter-fn
"A very simple text filter, just checks if printed representation
includes the string (ignoring case)."
[item text]
(str/includes? (str/lower-case (pr-str item))
(str/lower-case text)))
(def comparator
(reify java.util.Comparator
(compare [_ o1 o2]
(if (and (instance? java.lang.Comparable o1)
(= (type o1) (type o2)))
;; Compare comparables of the same type
(.compareTo o1 o2)
;; Fallback to comparing string representations
(let [s1 (pr-str o1)
s2 (pr-str o2)]
(.compareTo s1 s2))))))
(defn- filter-items [ordered-source? filter-fn items text [order-by order-direction]]
(let [items (into []
(filter #(filter-fn % text))
items)]
(if (and order-by (not ordered-source?))
((case order-direction
:asc identity
:desc reverse)
(sort-by order-by comparator items))
items)))
(defn- render-row [{:keys [columns]} row]
(h/html
[:tr
[::h/for [{:keys [accessor render]} columns
:let [data (accessor row)
data (if render data (str data))]]
[::h/if render
[:td (render data)]
[:td data]]]]))
(defn- filter-input [set-filter!]
(let [id (str (gensym "table-filter"))]
(h/html
[:div {:class "my-2 flex sm:flex-row flex-col"}
[:div.block.relative
[:span.h-full.absolute.inset-y-0.left-0.flex.items-center.pl-2
[:svg.h-4.w-4.fill-current.text-gray-500 {:viewBox "0 0 24 24"}
[:path {:d "M10 4a6 6 0 100 12 6 6 0 000-12zm-8 6a8 8 0 1114.32 4.906l5.387 5.387a1 1 0 01-1.414 1.414l-5.387-5.387A8 8 0 012 10z"}]]]
[:input {:id id
:class "appearance-none rounded-r rounded-l sm:rounded-l-none border border-gray-400 border-b block pl-8 pr-6 py-2 w-full bg-white text-sm placeholder-gray-400 text-gray-700 focus:bg-white focus:placeholder-gray-600 focus:text-gray-700 focus:outline-none"
:placeholder "Filter..."
:on-input (js/js-debounced 300 set-filter!
(js/input-value id))}]]])))
(defn- header [{:keys [columns]} set-order! [order-by order-direction]]
(h/html
[:thead
[:tr
[::h/for [{:keys [label accessor order-by?]
:or {order-by? true}} columns]
[:th {:on-click #(when order-by?
(set-order! [accessor (case order-direction
:asc :desc
:desc :asc)]))}
label
(when (and (= order-by accessor))
(h/out! (case order-direction
:asc " \u2303"
:desc " \u2304")))]]]]))
(defn table
"A data table that allows ordering by columns and filtering.
Takes two arguments: an options map and the live source for items.
Options:
:columns collection of columns for the table. Each column is a map
containing at least :label and :accessor.
Column may contain :render which is called to render the value.
Default render just stringifies the value.
If :order-by? is false, then this column can't be ordered by.
Example: [{:label \"Name\" :accessor :name}
{:label \"Email\" :accessor :email}]
:filter-fn predicate that is called with item and current filter text
default implementation just checks the printed representation
of the item for a substring match.
:order the initial order [accessor direction] (eg. [:name :asc])
:set-order! if specified, ordering will be done at the source level
and not by the table. If the source is an XTDB query,
it should handle the ordering in the query.
If not set, the items are ordered by using clojure builtin
`sort-by` function.
"
[{:keys [key filter-fn order set-order!]
:or {filter-fn default-filter-fn
key identity
order [nil :asc]} :as table-def} data-source]
(let [[filter-source set-filter!] (source/use-state "")
[order-source set-table-order!] (source/use-state order)
rows-source (source/computed
(partial filter-items (some? set-order!) filter-fn)
data-source filter-source order-source)]
(h/html
[:div.mx-2
(filter-input set-filter!)
[:table.table-auto
[::h/live order-source (partial header table-def
#(do
(when set-order!
(set-order! %))
(set-table-order! %))) ]
(collection/live-collection
{:render (partial render-row table-def)
:key key
:container-element :tbody
:source rows-source})]])))
| 80927 | (ns xtdb-inspector.ui.table
"A table component with filtering."
(:require [ripley.html :as h]
[ripley.live.source :as source]
[ripley.live.collection :as collection]
[clojure.string :as str]
[ripley.js :as js]))
(defn- default-filter-fn
"A very simple text filter, just checks if printed representation
includes the string (ignoring case)."
[item text]
(str/includes? (str/lower-case (pr-str item))
(str/lower-case text)))
(def comparator
(reify java.util.Comparator
(compare [_ o1 o2]
(if (and (instance? java.lang.Comparable o1)
(= (type o1) (type o2)))
;; Compare comparables of the same type
(.compareTo o1 o2)
;; Fallback to comparing string representations
(let [s1 (pr-str o1)
s2 (pr-str o2)]
(.compareTo s1 s2))))))
(defn- filter-items [ordered-source? filter-fn items text [order-by order-direction]]
(let [items (into []
(filter #(filter-fn % text))
items)]
(if (and order-by (not ordered-source?))
((case order-direction
:asc identity
:desc reverse)
(sort-by order-by comparator items))
items)))
(defn- render-row [{:keys [columns]} row]
(h/html
[:tr
[::h/for [{:keys [accessor render]} columns
:let [data (accessor row)
data (if render data (str data))]]
[::h/if render
[:td (render data)]
[:td data]]]]))
(defn- filter-input [set-filter!]
(let [id (str (gensym "table-filter"))]
(h/html
[:div {:class "my-2 flex sm:flex-row flex-col"}
[:div.block.relative
[:span.h-full.absolute.inset-y-0.left-0.flex.items-center.pl-2
[:svg.h-4.w-4.fill-current.text-gray-500 {:viewBox "0 0 24 24"}
[:path {:d "M10 4a6 6 0 100 12 6 6 0 000-12zm-8 6a8 8 0 1114.32 4.906l5.387 5.387a1 1 0 01-1.414 1.414l-5.387-5.387A8 8 0 012 10z"}]]]
[:input {:id id
:class "appearance-none rounded-r rounded-l sm:rounded-l-none border border-gray-400 border-b block pl-8 pr-6 py-2 w-full bg-white text-sm placeholder-gray-400 text-gray-700 focus:bg-white focus:placeholder-gray-600 focus:text-gray-700 focus:outline-none"
:placeholder "Filter..."
:on-input (js/js-debounced 300 set-filter!
(js/input-value id))}]]])))
(defn- header [{:keys [columns]} set-order! [order-by order-direction]]
(h/html
[:thead
[:tr
[::h/for [{:keys [label accessor order-by?]
:or {order-by? true}} columns]
[:th {:on-click #(when order-by?
(set-order! [accessor (case order-direction
:asc :desc
:desc :asc)]))}
label
(when (and (= order-by accessor))
(h/out! (case order-direction
:asc " \u2303"
:desc " \u2304")))]]]]))
(defn table
"A data table that allows ordering by columns and filtering.
Takes two arguments: an options map and the live source for items.
Options:
:columns collection of columns for the table. Each column is a map
containing at least :label and :accessor.
Column may contain :render which is called to render the value.
Default render just stringifies the value.
If :order-by? is false, then this column can't be ordered by.
Example: [{:label \"<NAME>\" :accessor :name}
{:label \"<NAME>\" :accessor :email}]
:filter-fn predicate that is called with item and current filter text
default implementation just checks the printed representation
of the item for a substring match.
:order the initial order [accessor direction] (eg. [:name :asc])
:set-order! if specified, ordering will be done at the source level
and not by the table. If the source is an XTDB query,
it should handle the ordering in the query.
If not set, the items are ordered by using clojure builtin
`sort-by` function.
"
[{:keys [key filter-fn order set-order!]
:or {filter-fn default-filter-fn
key identity
order [nil :asc]} :as table-def} data-source]
(let [[filter-source set-filter!] (source/use-state "")
[order-source set-table-order!] (source/use-state order)
rows-source (source/computed
(partial filter-items (some? set-order!) filter-fn)
data-source filter-source order-source)]
(h/html
[:div.mx-2
(filter-input set-filter!)
[:table.table-auto
[::h/live order-source (partial header table-def
#(do
(when set-order!
(set-order! %))
(set-table-order! %))) ]
(collection/live-collection
{:render (partial render-row table-def)
:key key
:container-element :tbody
:source rows-source})]])))
| true | (ns xtdb-inspector.ui.table
"A table component with filtering."
(:require [ripley.html :as h]
[ripley.live.source :as source]
[ripley.live.collection :as collection]
[clojure.string :as str]
[ripley.js :as js]))
(defn- default-filter-fn
"A very simple text filter, just checks if printed representation
includes the string (ignoring case)."
[item text]
(str/includes? (str/lower-case (pr-str item))
(str/lower-case text)))
(def comparator
(reify java.util.Comparator
(compare [_ o1 o2]
(if (and (instance? java.lang.Comparable o1)
(= (type o1) (type o2)))
;; Compare comparables of the same type
(.compareTo o1 o2)
;; Fallback to comparing string representations
(let [s1 (pr-str o1)
s2 (pr-str o2)]
(.compareTo s1 s2))))))
(defn- filter-items [ordered-source? filter-fn items text [order-by order-direction]]
(let [items (into []
(filter #(filter-fn % text))
items)]
(if (and order-by (not ordered-source?))
((case order-direction
:asc identity
:desc reverse)
(sort-by order-by comparator items))
items)))
(defn- render-row [{:keys [columns]} row]
(h/html
[:tr
[::h/for [{:keys [accessor render]} columns
:let [data (accessor row)
data (if render data (str data))]]
[::h/if render
[:td (render data)]
[:td data]]]]))
(defn- filter-input [set-filter!]
(let [id (str (gensym "table-filter"))]
(h/html
[:div {:class "my-2 flex sm:flex-row flex-col"}
[:div.block.relative
[:span.h-full.absolute.inset-y-0.left-0.flex.items-center.pl-2
[:svg.h-4.w-4.fill-current.text-gray-500 {:viewBox "0 0 24 24"}
[:path {:d "M10 4a6 6 0 100 12 6 6 0 000-12zm-8 6a8 8 0 1114.32 4.906l5.387 5.387a1 1 0 01-1.414 1.414l-5.387-5.387A8 8 0 012 10z"}]]]
[:input {:id id
:class "appearance-none rounded-r rounded-l sm:rounded-l-none border border-gray-400 border-b block pl-8 pr-6 py-2 w-full bg-white text-sm placeholder-gray-400 text-gray-700 focus:bg-white focus:placeholder-gray-600 focus:text-gray-700 focus:outline-none"
:placeholder "Filter..."
:on-input (js/js-debounced 300 set-filter!
(js/input-value id))}]]])))
(defn- header [{:keys [columns]} set-order! [order-by order-direction]]
(h/html
[:thead
[:tr
[::h/for [{:keys [label accessor order-by?]
:or {order-by? true}} columns]
[:th {:on-click #(when order-by?
(set-order! [accessor (case order-direction
:asc :desc
:desc :asc)]))}
label
(when (and (= order-by accessor))
(h/out! (case order-direction
:asc " \u2303"
:desc " \u2304")))]]]]))
(defn table
"A data table that allows ordering by columns and filtering.
Takes two arguments: an options map and the live source for items.
Options:
:columns collection of columns for the table. Each column is a map
containing at least :label and :accessor.
Column may contain :render which is called to render the value.
Default render just stringifies the value.
If :order-by? is false, then this column can't be ordered by.
Example: [{:label \"PI:NAME:<NAME>END_PI\" :accessor :name}
{:label \"PI:NAME:<NAME>END_PI\" :accessor :email}]
:filter-fn predicate that is called with item and current filter text
default implementation just checks the printed representation
of the item for a substring match.
:order the initial order [accessor direction] (eg. [:name :asc])
:set-order! if specified, ordering will be done at the source level
and not by the table. If the source is an XTDB query,
it should handle the ordering in the query.
If not set, the items are ordered by using clojure builtin
`sort-by` function.
"
[{:keys [key filter-fn order set-order!]
:or {filter-fn default-filter-fn
key identity
order [nil :asc]} :as table-def} data-source]
(let [[filter-source set-filter!] (source/use-state "")
[order-source set-table-order!] (source/use-state order)
rows-source (source/computed
(partial filter-items (some? set-order!) filter-fn)
data-source filter-source order-source)]
(h/html
[:div.mx-2
(filter-input set-filter!)
[:table.table-auto
[::h/live order-source (partial header table-def
#(do
(when set-order!
(set-order! %))
(set-table-order! %))) ]
(collection/live-collection
{:render (partial render-row table-def)
:key key
:container-element :tbody
:source rows-source})]])))
|
[
{
"context": "\n ;; create the admin\n admin-email \"admin@purpleapp.com\"\n admin-password \"foobar\"\n admin-fu",
"end": 899,
"score": 0.9999279379844666,
"start": 880,
"tag": "EMAIL",
"value": "admin@purpleapp.com"
},
{
"context": "ail \"admin@purpleapp.com\"\n admin-password \"foobar\"\n admin-full-name \"Purple Admin\"\n _",
"end": 931,
"score": 0.9995881915092468,
"start": 925,
"tag": "PASSWORD",
"value": "foobar"
},
{
"context": " {:email admin-email\n :password admin-password\n :full-name admin-full-name\n ",
"end": 1087,
"score": 0.9915578365325928,
"start": 1073,
"tag": "PASSWORD",
"value": "admin-password"
},
{
"context": " ;; create the courier\n courier-email \"courier@purpleapp.com\"\n courier-password \"courier\"\n couri",
"end": 1601,
"score": 0.9999302625656128,
"start": 1580,
"tag": "EMAIL",
"value": "courier@purpleapp.com"
},
{
"context": "\"courier@purpleapp.com\"\n courier-password \"courier\"\n courier-full-name \"Purple Courier\"\n ",
"end": 1636,
"score": 0.9993531703948975,
"start": 1629,
"tag": "PASSWORD",
"value": "courier"
},
{
"context": " :password courier-password\n :full-na",
"end": 1874,
"score": 0.8905861973762512,
"start": 1866,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " ;; create the nonmember\n nonmember-email \"regular@foo.com\"\n nonmember-password \"regularfoo\"\n ",
"end": 2086,
"score": 0.9999233484268188,
"start": 2071,
"tag": "EMAIL",
"value": "regular@foo.com"
},
{
"context": "ail \"regular@foo.com\"\n nonmember-password \"regularfoo\"\n nonmember-full-name \"Regular User\"\n ",
"end": 2126,
"score": 0.9993986487388611,
"start": 2116,
"tag": "PASSWORD",
"value": "regularfoo"
},
{
"context": "assword \"regularfoo\"\n nonmember-full-name \"Regular User\"\n _ (data-tools/create-app-user-vehicle-o",
"end": 2169,
"score": 0.9588713645935059,
"start": 2157,
"tag": "NAME",
"value": "Regular User"
},
{
"context": " {:email nonmember-email\n :password nonmember-password\n :full-name nonmember-full-name\n ",
"end": 2302,
"score": 0.9727075099945068,
"start": 2284,
"tag": "PASSWORD",
"value": "nonmember-password"
},
{
"context": " ;; create the member\n member-email \"member@foo.com\"\n member-password \"memberfoo\"\n memb",
"end": 2515,
"score": 0.9999229311943054,
"start": 2501,
"tag": "EMAIL",
"value": "member@foo.com"
},
{
"context": "r-email \"member@foo.com\"\n member-password \"memberfoo\"\n member-full-name \"Member User\"\n _",
"end": 2551,
"score": 0.9994901418685913,
"start": 2542,
"tag": "PASSWORD",
"value": "memberfoo"
},
{
"context": "er-password \"memberfoo\"\n member-full-name \"Member User\"\n _ (data-tools/create-app-user-vehicl",
"end": 2590,
"score": 0.8120381832122803,
"start": 2579,
"tag": "NAME",
"value": "Member User"
},
{
"context": " {:email member-email\n :password member-password\n :full-name member-full-name\n ",
"end": 2726,
"score": 0.9895767569541931,
"start": 2711,
"tag": "PASSWORD",
"value": "member-password"
}
] | test/dashboard/test/orders.clj | Purple-Services/dashboard-service | 3 | (ns dashboard.test.orders
(:require [clojure.test :refer [is deftest testing use-fixtures]]
[clj-time.coerce :as c]
[clj-time.local :as l]
[common.db :as db]
[dashboard.orders :as orders]
[dashboard.test.data-tools :as data-tools]
[dashboard.test.db-tools :as db-tools]
[dashboard.users :as users]))
(use-fixtures :once db-tools/setup-ebdb-test-for-conn-fixture)
(use-fixtures :each db-tools/clear-and-populate-test-database-fixture)
(def reset-db! db-tools/reset-db!)
(def setup-ebdb-test-pool! db-tools/setup-ebdb-test-pool!)
(defn get-order-by-email
[email orders]
(first (filter #(= (:email %) email) orders)))
(deftest first-time-ordered
(let [db-conn (db/conn)
now (quot (c/to-long (l/local-now))
1000)
;; create the admin
admin-email "admin@purpleapp.com"
admin-password "foobar"
admin-full-name "Purple Admin"
_ (data-tools/create-minimal-dash-user!
{:email admin-email
:password admin-password
:full-name admin-full-name
:db-conn db-conn})
admin (first (db/!select db-conn "dashboard_users" ["*"]
{:email admin-email}))
;; update the admins perms
_ (data-tools/give-perms!
{:user admin
:perms (str "view-dash,view-couriers,view-users,"
"view-zones,view-orders,edit-orders")
:db-conn db-conn})
;; create the courier
courier-email "courier@purpleapp.com"
courier-password "courier"
courier-full-name "Purple Courier"
_ (data-tools/register-courier! {:db-conn db-conn
:platform-id courier-email
:password courier-password
:full-name courier-full-name})
courier (first (users/search-users db-conn courier-email))
;; create the nonmember
nonmember-email "regular@foo.com"
nonmember-password "regularfoo"
nonmember-full-name "Regular User"
_ (data-tools/create-app-user-vehicle-order!
{:email nonmember-email
:password nonmember-password
:full-name nonmember-full-name
:db-conn db-conn})
nonmember (first (users/search-users db-conn nonmember-email))
;; create the member
member-email "member@foo.com"
member-password "memberfoo"
member-full-name "Member User"
_ (data-tools/create-app-user-vehicle-order!
{:email member-email
:password member-password
:full-name member-full-name
:db-conn db-conn})
member (first (users/search-users db-conn member-email))
current-orders (orders/orders-since-date db-conn
now
true)
nonmember-order (get-order-by-email nonmember-email current-orders)
member-order (get-order-by-email member-email current-orders)]
(testing "First time orders are indicated"
;; are both orders indicated as being first time?
(is (:first_order? nonmember-order))
(is (:first_order? member-order)))
(testing "Cancel the orders, reorder and check if first_order"
;; cancel both of those orders
(orders/cancel-order db-conn
(:id member)
(:id member-order)
(:id admin)
"Test")
(orders/cancel-order db-conn
(:id nonmember)
(:id nonmember-order)
(:id admin)
"Test")
;; create two new orders
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id member)}))
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id nonmember)}))
(let [current-orders (orders/orders-since-date db-conn
now
true)]
;; should still be first time orders
(is (every? true? (map :first_order? current-orders)))
(let [active-member-order (->> current-orders
(filter #(= (:email %) member-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)
active-nonmember-order (->> current-orders
(filter #(= (:email %)
nonmember-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)]
;; assign orders to a courier and mark them as complete
(orders/assign-to-courier-by-admin
db-conn (:id active-member-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-member-order) %)
["accepted" "enroute" "servicing" "complete"])
(orders/assign-to-courier-by-admin
db-conn (:id active-nonmember-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-nonmember-order) %)
["accepted" "enroute" "servicing" "complete"])
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-nonmember-order))))))
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-member-order)))))))))))
| 80325 | (ns dashboard.test.orders
(:require [clojure.test :refer [is deftest testing use-fixtures]]
[clj-time.coerce :as c]
[clj-time.local :as l]
[common.db :as db]
[dashboard.orders :as orders]
[dashboard.test.data-tools :as data-tools]
[dashboard.test.db-tools :as db-tools]
[dashboard.users :as users]))
(use-fixtures :once db-tools/setup-ebdb-test-for-conn-fixture)
(use-fixtures :each db-tools/clear-and-populate-test-database-fixture)
(def reset-db! db-tools/reset-db!)
(def setup-ebdb-test-pool! db-tools/setup-ebdb-test-pool!)
(defn get-order-by-email
[email orders]
(first (filter #(= (:email %) email) orders)))
(deftest first-time-ordered
(let [db-conn (db/conn)
now (quot (c/to-long (l/local-now))
1000)
;; create the admin
admin-email "<EMAIL>"
admin-password "<PASSWORD>"
admin-full-name "Purple Admin"
_ (data-tools/create-minimal-dash-user!
{:email admin-email
:password <PASSWORD>
:full-name admin-full-name
:db-conn db-conn})
admin (first (db/!select db-conn "dashboard_users" ["*"]
{:email admin-email}))
;; update the admins perms
_ (data-tools/give-perms!
{:user admin
:perms (str "view-dash,view-couriers,view-users,"
"view-zones,view-orders,edit-orders")
:db-conn db-conn})
;; create the courier
courier-email "<EMAIL>"
courier-password "<PASSWORD>"
courier-full-name "Purple Courier"
_ (data-tools/register-courier! {:db-conn db-conn
:platform-id courier-email
:password courier-<PASSWORD>
:full-name courier-full-name})
courier (first (users/search-users db-conn courier-email))
;; create the nonmember
nonmember-email "<EMAIL>"
nonmember-password "<PASSWORD>"
nonmember-full-name "<NAME>"
_ (data-tools/create-app-user-vehicle-order!
{:email nonmember-email
:password <PASSWORD>
:full-name nonmember-full-name
:db-conn db-conn})
nonmember (first (users/search-users db-conn nonmember-email))
;; create the member
member-email "<EMAIL>"
member-password "<PASSWORD>"
member-full-name "<NAME>"
_ (data-tools/create-app-user-vehicle-order!
{:email member-email
:password <PASSWORD>
:full-name member-full-name
:db-conn db-conn})
member (first (users/search-users db-conn member-email))
current-orders (orders/orders-since-date db-conn
now
true)
nonmember-order (get-order-by-email nonmember-email current-orders)
member-order (get-order-by-email member-email current-orders)]
(testing "First time orders are indicated"
;; are both orders indicated as being first time?
(is (:first_order? nonmember-order))
(is (:first_order? member-order)))
(testing "Cancel the orders, reorder and check if first_order"
;; cancel both of those orders
(orders/cancel-order db-conn
(:id member)
(:id member-order)
(:id admin)
"Test")
(orders/cancel-order db-conn
(:id nonmember)
(:id nonmember-order)
(:id admin)
"Test")
;; create two new orders
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id member)}))
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id nonmember)}))
(let [current-orders (orders/orders-since-date db-conn
now
true)]
;; should still be first time orders
(is (every? true? (map :first_order? current-orders)))
(let [active-member-order (->> current-orders
(filter #(= (:email %) member-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)
active-nonmember-order (->> current-orders
(filter #(= (:email %)
nonmember-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)]
;; assign orders to a courier and mark them as complete
(orders/assign-to-courier-by-admin
db-conn (:id active-member-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-member-order) %)
["accepted" "enroute" "servicing" "complete"])
(orders/assign-to-courier-by-admin
db-conn (:id active-nonmember-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-nonmember-order) %)
["accepted" "enroute" "servicing" "complete"])
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-nonmember-order))))))
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-member-order)))))))))))
| true | (ns dashboard.test.orders
(:require [clojure.test :refer [is deftest testing use-fixtures]]
[clj-time.coerce :as c]
[clj-time.local :as l]
[common.db :as db]
[dashboard.orders :as orders]
[dashboard.test.data-tools :as data-tools]
[dashboard.test.db-tools :as db-tools]
[dashboard.users :as users]))
(use-fixtures :once db-tools/setup-ebdb-test-for-conn-fixture)
(use-fixtures :each db-tools/clear-and-populate-test-database-fixture)
(def reset-db! db-tools/reset-db!)
(def setup-ebdb-test-pool! db-tools/setup-ebdb-test-pool!)
(defn get-order-by-email
[email orders]
(first (filter #(= (:email %) email) orders)))
(deftest first-time-ordered
(let [db-conn (db/conn)
now (quot (c/to-long (l/local-now))
1000)
;; create the admin
admin-email "PI:EMAIL:<EMAIL>END_PI"
admin-password "PI:PASSWORD:<PASSWORD>END_PI"
admin-full-name "Purple Admin"
_ (data-tools/create-minimal-dash-user!
{:email admin-email
:password PI:PASSWORD:<PASSWORD>END_PI
:full-name admin-full-name
:db-conn db-conn})
admin (first (db/!select db-conn "dashboard_users" ["*"]
{:email admin-email}))
;; update the admins perms
_ (data-tools/give-perms!
{:user admin
:perms (str "view-dash,view-couriers,view-users,"
"view-zones,view-orders,edit-orders")
:db-conn db-conn})
;; create the courier
courier-email "PI:EMAIL:<EMAIL>END_PI"
courier-password "PI:PASSWORD:<PASSWORD>END_PI"
courier-full-name "Purple Courier"
_ (data-tools/register-courier! {:db-conn db-conn
:platform-id courier-email
:password courier-PI:PASSWORD:<PASSWORD>END_PI
:full-name courier-full-name})
courier (first (users/search-users db-conn courier-email))
;; create the nonmember
nonmember-email "PI:EMAIL:<EMAIL>END_PI"
nonmember-password "PI:PASSWORD:<PASSWORD>END_PI"
nonmember-full-name "PI:NAME:<NAME>END_PI"
_ (data-tools/create-app-user-vehicle-order!
{:email nonmember-email
:password PI:PASSWORD:<PASSWORD>END_PI
:full-name nonmember-full-name
:db-conn db-conn})
nonmember (first (users/search-users db-conn nonmember-email))
;; create the member
member-email "PI:EMAIL:<EMAIL>END_PI"
member-password "PI:PASSWORD:<PASSWORD>END_PI"
member-full-name "PI:NAME:<NAME>END_PI"
_ (data-tools/create-app-user-vehicle-order!
{:email member-email
:password PI:PASSWORD:<PASSWORD>END_PI
:full-name member-full-name
:db-conn db-conn})
member (first (users/search-users db-conn member-email))
current-orders (orders/orders-since-date db-conn
now
true)
nonmember-order (get-order-by-email nonmember-email current-orders)
member-order (get-order-by-email member-email current-orders)]
(testing "First time orders are indicated"
;; are both orders indicated as being first time?
(is (:first_order? nonmember-order))
(is (:first_order? member-order)))
(testing "Cancel the orders, reorder and check if first_order"
;; cancel both of those orders
(orders/cancel-order db-conn
(:id member)
(:id member-order)
(:id admin)
"Test")
(orders/cancel-order db-conn
(:id nonmember)
(:id nonmember-order)
(:id admin)
"Test")
;; create two new orders
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id member)}))
(data-tools/create-order! db-conn
(data-tools/order-map {:user_id
(:id nonmember)}))
(let [current-orders (orders/orders-since-date db-conn
now
true)]
;; should still be first time orders
(is (every? true? (map :first_order? current-orders)))
(let [active-member-order (->> current-orders
(filter #(= (:email %) member-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)
active-nonmember-order (->> current-orders
(filter #(= (:email %)
nonmember-email))
(filter #(contains? #{"unassigned"}
(:status %)))
first)]
;; assign orders to a courier and mark them as complete
(orders/assign-to-courier-by-admin
db-conn (:id active-member-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-member-order) %)
["accepted" "enroute" "servicing" "complete"])
(orders/assign-to-courier-by-admin
db-conn (:id active-nonmember-order) (:id courier))
(mapv #(orders/update-status-by-admin
db-conn
(:id active-nonmember-order) %)
["accepted" "enroute" "servicing" "complete"])
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-nonmember-order))))))
(is (= false (:first_order? (first
(orders/search-orders
db-conn
(:id active-member-order)))))))))))
|
[
{
"context": "l/new-hospital))]\n\n (person-arrives! hospital \"victor\")\n (person-arrives! hospital \"alessandra\")\n ",
"end": 423,
"score": 0.9991849660873413,
"start": 417,
"tag": "NAME",
"value": "victor"
},
{
"context": "hospital \"victor\")\n (person-arrives! hospital \"alessandra\")\n (person-arrives! hospital \"billy\")\n (per",
"end": 467,
"score": 0.9996252655982971,
"start": 457,
"tag": "NAME",
"value": "alessandra"
},
{
"context": "ital \"alessandra\")\n (person-arrives! hospital \"billy\")\n (person-arrives! hospital \"leo\")\n (perso",
"end": 506,
"score": 0.9995362162590027,
"start": 501,
"tag": "NAME",
"value": "billy"
},
{
"context": " hospital \"billy\")\n (person-arrives! hospital \"leo\")\n (person-arrives! hospital \"fred\")\n\n (tra",
"end": 543,
"score": 0.9998617768287659,
"start": 540,
"tag": "NAME",
"value": "leo"
},
{
"context": "s! hospital \"leo\")\n (person-arrives! hospital \"fred\")\n\n (transfer! hospital :waiting :lab1)\n (t",
"end": 581,
"score": 0.9997169375419617,
"start": 577,
"tag": "NAME",
"value": "fred"
}
] | hospital/src/hospital/class5.clj | vgeorgo/courses-alura-clojure | 0 | (ns hospital.class5
(:use [clojure pprint])
(:require [hospital.model :as h.model]
[hospital.logic :as h.logic]))
(defn person-arrives! [hospital, person]
(swap! hospital h.logic/person-arrives :waiting person))
(defn transfer! [hospital from to]
(swap! hospital h.logic/transfer from to))
(defn simulate-day-1 []
(let [hospital (atom (h.model/new-hospital))]
(person-arrives! hospital "victor")
(person-arrives! hospital "alessandra")
(person-arrives! hospital "billy")
(person-arrives! hospital "leo")
(person-arrives! hospital "fred")
(transfer! hospital :waiting :lab1)
(transfer! hospital :waiting :lab2)
(transfer! hospital :waiting :lab2)
(transfer! hospital :lab1 :lab3)
(pprint hospital)))
(simulate-day-1) | 103995 | (ns hospital.class5
(:use [clojure pprint])
(:require [hospital.model :as h.model]
[hospital.logic :as h.logic]))
(defn person-arrives! [hospital, person]
(swap! hospital h.logic/person-arrives :waiting person))
(defn transfer! [hospital from to]
(swap! hospital h.logic/transfer from to))
(defn simulate-day-1 []
(let [hospital (atom (h.model/new-hospital))]
(person-arrives! hospital "<NAME>")
(person-arrives! hospital "<NAME>")
(person-arrives! hospital "<NAME>")
(person-arrives! hospital "<NAME>")
(person-arrives! hospital "<NAME>")
(transfer! hospital :waiting :lab1)
(transfer! hospital :waiting :lab2)
(transfer! hospital :waiting :lab2)
(transfer! hospital :lab1 :lab3)
(pprint hospital)))
(simulate-day-1) | true | (ns hospital.class5
(:use [clojure pprint])
(:require [hospital.model :as h.model]
[hospital.logic :as h.logic]))
(defn person-arrives! [hospital, person]
(swap! hospital h.logic/person-arrives :waiting person))
(defn transfer! [hospital from to]
(swap! hospital h.logic/transfer from to))
(defn simulate-day-1 []
(let [hospital (atom (h.model/new-hospital))]
(person-arrives! hospital "PI:NAME:<NAME>END_PI")
(person-arrives! hospital "PI:NAME:<NAME>END_PI")
(person-arrives! hospital "PI:NAME:<NAME>END_PI")
(person-arrives! hospital "PI:NAME:<NAME>END_PI")
(person-arrives! hospital "PI:NAME:<NAME>END_PI")
(transfer! hospital :waiting :lab1)
(transfer! hospital :waiting :lab2)
(transfer! hospital :waiting :lab2)
(transfer! hospital :lab1 :lab3)
(pprint hospital)))
(simulate-day-1) |
[
{
"context": "fying handlers (better portability).\"\n {:author \"Peter Taoussanis\"}\n\n \n \n ",
"end": 2719,
"score": 0.9998626708984375,
"start": 2703,
"tag": "NAME",
"value": "Peter Taoussanis"
}
] | resources/public/js/out/taoensso/sente.cljs | nathanWedwards/vote-simple | 0 | (ns taoensso.sente
"Channel sockets. Otherwise known as The Shiz.
Protocol | client>server | client>server ?+ ack/reply | server>user push
* WebSockets: ✓ [1] ✓
* Ajax: [2] ✓ [3]
[1] Emulate with cb-uuid wrapping.
[2] Emulate with dummy-cb wrapping.
[3] Emulate with long-polling.
Abbreviations:
* chsk - Channel socket. Sente's own pseudo \"socket\".
* net-ch - Network channel. Underlying web server's channel. Must implement
Sente's async net channel interface.
* uid - User-id. An application-level user identifier used for async push.
May have semantic meaning (e.g. username, email address), or not
(e.g. client/random id) - app's discretion.
* cb - Callback.
* tout - Timeout.
* ws - WebSocket/s.
* pstr - Packed string. Arbitrary Clojure data serialized as a string (e.g.
edn) for client<->server comms.
Special messages:
* Callback wrapping: [<clj> <?cb-uuid>] for [1],[2].
* Callback replies: :chsk/closed, :chsk/timeout, :chsk/error.
* Client-side events:
[:chsk/handshake [<?uid> <?csrf-token> <?handshake-data>]],
[:chsk/state <new-state>],
[:chsk/recv <[buffered-evs]>] ; server>user push
* Server-side events:
[:chsk/ws-ping],
[:chsk/bad-package <packed-str>],
[:chsk/bad-event <chsk-event>],
[:chsk/uidport-open],
[:chsk/uidport-close].
Notable implementation details:
* core.async is used liberally where brute-force core.async allows for
significant implementation simplifications. We lean on core.async's strong
efficiency here.
* For WebSocket fallback we use long-polling rather than HTTP 1.1 streaming
(chunked transfer encoding). Http-kit _does_ support chunked transfer
encoding but a small minority of browsers &/or proxies do not. Instead of
implementing all 3 modes (WebSockets, streaming, long-polling) - it seemed
reasonable to focus on the two extremes (performance + compatibility). In
any case client support for WebSockets is growing rapidly so fallback
modes will become increasingly irrelevant while the extra simplicity will
continue to pay dividends.
General-use notes:
* Single HTTP req+session persists over entire chsk session but cannot
modify sessions! Use standard a/sync HTTP Ring req/resp for logins, etc.
* Easy to wrap standard HTTP Ring resps for transport over chsks. Prefer
this approach to modifying handlers (better portability)."
{:author "Peter Taoussanis"}
(:require
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[taoensso.encore :as enc :refer (format swap-in! reset-in! swapped)
:refer-macros (have? have)]
[taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)]
[taoensso.sente.interfaces :as interfaces])
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)]))
;;;; Encore version check
;;;; Events
;; * Clients & server both send `event`s and receive (i.e. route) `event-msg`s.
(defn- validate-event [x]
(cond
(not (vector? x)) :wrong-type
(not (#{1 2} (count x))) :wrong-length
:else (let [[ev-id _] x]
(cond (not (keyword? ev-id)) :wrong-id-type
(not (namespace ev-id)) :unnamespaced-id
:else nil))))
(defn event? "Valid [ev-id ?ev-data] form?" [x] (nil? (validate-event x)))
(defn as-event [x] (if (event? x) x [:chsk/bad-event x]))
(defn assert-event [x]
(when-let [?err (validate-event x)]
(let [err-fmt
(str
(case ?err
:wrong-type "Malformed event (wrong type)."
:wrong-length "Malformed event (wrong length)."
(:wrong-id-type :unnamespaced-id)
"Malformed event (`ev-id` should be a namespaced keyword)."
:else "Malformed event (unknown error).")
" Event should be of `[ev-id ?ev-data]` form: %s")]
(throw (ex-info (format err-fmt (str x)) {:malformed-event x})))))
(defn event-msg? [x]
(and
(map? x)
(enc/keys= x #{:ch-recv :send-fn :state :event :id :?data})
(let [{:keys [ch-recv send-fn state event]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? state)
(event? event))))
)
(defn cb-success? "Note that cb reply need _not_ be `event` form!"
[cb-reply-clj] (not (#{:chsk/closed :chsk/timeout :chsk/error} cb-reply-clj)))
;;;; Packing
;; * Client<->server payloads are arbitrary Clojure vals (cb replies or events).
;; * Payloads are packed for client<->server transit.
;; * Packing includes ->str encoding, and may incl. wrapping to carry cb info.
(defn- unpack* "pstr->clj" [packer pstr]
(try
(interfaces/unpack packer (have string? pstr))
(catch :default t
(debugf "Bad package: %s (%s)" pstr t)
(throw t) ; Let client rethrow on bad pstr from server
)))
(defn- with-?meta [x ?m] (if (seq ?m) (with-meta x ?m) x))
(defn- pack* "clj->prefixed-pstr"
([packer ?packer-meta clj]
(str "-" ; => Unwrapped (no cb metadata)
(interfaces/pack packer (with-?meta clj ?packer-meta))))
([packer ?packer-meta clj ?cb-uuid]
(let [;;; Keep wrapping as light as possible:
?cb-uuid (if (= ?cb-uuid :ajax-cb) 0 ?cb-uuid)
wrapped-clj (if ?cb-uuid [clj ?cb-uuid] [clj])]
(str "+" ; => Wrapped (cb metadata)
(interfaces/pack packer (with-?meta wrapped-clj ?packer-meta))))))
(defn- pack [& args]
(let [pstr (apply pack* args)]
(tracef "Packing: %s -> %s" args pstr)
pstr))
(defn- unpack "prefixed-pstr->[clj ?cb-uuid]"
[packer prefixed-pstr]
(have? string? prefixed-pstr)
(let [prefix (enc/substr prefixed-pstr 0 1)
pstr (enc/substr prefixed-pstr 1)
clj (unpack* packer pstr) ; May be un/wrapped
wrapped? (case prefix "-" false "+" true)
[clj ?cb-uuid] (if wrapped? clj [clj nil])
?cb-uuid (if (= 0 ?cb-uuid) :ajax-cb ?cb-uuid)]
(tracef "Unpacking: %s -> %s" prefixed-pstr [clj ?cb-uuid])
[clj ?cb-uuid]))
(comment
(do (require '[taoensso.sente.packers.transit :as transit])
(def edn-packer interfaces/edn-packer)
(def flexi-packer (transit/get-flexi-packer)))
(unpack edn-packer (pack edn-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {:json true} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] :ajax-cb)))
;;;; Server API
;;;; Client API
(defprotocol IChSocket
(chsk-init! [chsk] "Implementation detail.")
(chsk-destroy! [chsk] "Kills socket, stops auto-reconnects.")
(chsk-reconnect! [chsk] "Drops connection, allows auto-reconnect. Useful for reauthenticating after login/logout.")
(chsk-send!* [chsk ev opts] "Implementation detail."))
(defn chsk-send!
"Sends `[ev-id ev-?data :as event]`, returns true on apparent success."
([chsk ev] (chsk-send! chsk ev {}))
([chsk ev ?timeout-ms ?cb] (chsk-send! chsk ev {:timeout-ms ?timeout-ms
:cb ?cb}))
([chsk ev opts]
(tracef "Chsk send: (%s) %s" (assoc opts :cb (boolean (:cb opts))) ev)
(chsk-send!* chsk ev opts)))
(defn- assert-send-args [x ?timeout-ms ?cb]
(assert-event x)
(assert (or (and (nil? ?timeout-ms) (nil? ?cb))
(and (enc/nneg-int? ?timeout-ms)))
(format "cb requires a timeout; timeout-ms should be a +ive integer: %s"
?timeout-ms))
(assert (or (nil? ?cb) (ifn? ?cb) (enc/chan? ?cb))
(format "cb should be nil, an ifn, or a channel: %s" (type ?cb))))
(defn- pull-unused-cb-fn! [cbs-waiting_ ?cb-uuid]
(when-let [cb-uuid ?cb-uuid]
(swap-in! cbs-waiting_ [cb-uuid]
(fn [?f] (swapped :swap/dissoc ?f)))))
(defn- merge>chsk-state! [{:keys [chs state_] :as chsk} merge-state]
(let [[old-state new-state]
(swap-in! state_ []
(fn [old-state]
(let [new-state (merge old-state merge-state)
;; Is this a reasonable way of helping client distinguish
;; cause of an auto reconnect? Didn't give it much thought...
new-state (if-not (and (:requested-reconnect-pending? old-state)
(:open? new-state)
(not (:open? old-state)))
new-state
(-> new-state
(dissoc :requested-reconnect-pending?)
(assoc :requested-reconnect? true)))]
(swapped new-state [old-state new-state]))))]
(when (not= old-state new-state)
;; (debugf "Chsk state change: %s" new-state)
(put! (:state chs) new-state)
new-state)))
(defn- cb-chan-as-fn
"Experimental, undocumented. Allows a core.async channel to be provided
instead of a cb-fn. The channel will receive values of form
[<event-id>.cb <reply>]."
[?cb ev]
(if (or (nil? ?cb) (ifn? ?cb)) ?cb
(do (have? enc/chan? ?cb)
(assert-event ev)
(let [[ev-id _] ev
cb-ch ?cb]
(fn [reply]
(put! cb-ch [(keyword (str (enc/fq-name ev-id) ".cb"))
reply]))))))
(defn- receive-buffered-evs! [chs clj]
(tracef "receive-buffered-evs!: %s" clj)
(let [buffered-evs (have vector? clj)]
(doseq [ev buffered-evs]
(assert-event ev)
(put! (:<server chs) ev))))
(defn- handle-when-handshake! [chsk chs clj]
(let [handshake? (and (vector? clj) ; Nb clj may be callback reply
(= (first clj) :chsk/handshake))]
(tracef "handle-when-handshake (%s): %s"
(if handshake? :handshake :non-handshake) clj)
(when handshake?
(let [[_ [?uid ?csrf-token ?handshake-data] :as handshake-ev] clj
;; Another idea? Not fond of how this places restrictions on the
;; form and content of ?handshake-data:
;; handshake-ev [:chsk/handshake
;; (merge
;; (have [:or nil? map?] ?handshake-data)
;; {:?uid ?uid
;; :?csrf-token ?csrf-token})]
]
(when (str/blank? ?csrf-token)
(warnf "SECURITY WARNING: no CSRF token available for use by Sente"))
(merge>chsk-state! chsk
{:open? true
:uid ?uid
:csrf-token ?csrf-token
;; Could also just merge ?handshake-data into chsk state here, but
;; it seems preferable (?) to instead register a unique
;; :chsk/handshake event
})
(assert-event handshake-ev)
(put! (:internal chs) handshake-ev)
:handled))))
(defn set-exp-backoff-timeout! [nullary-f nattempt & [backoff-ms-fn]]
(let [timeout-ms (backoff-ms-fn (or nattempt 0))]
(.setTimeout js/window nullary-f timeout-ms)))
;; Handles reconnects, keep-alives, callbacks:
(defrecord ChWebSocket
[client-id url chs socket_ kalive-ms kalive-timer_ kalive-due?_ nattempt_
cbs-waiting_ ; {<cb-uuid> <fn> ...}
state_ ; {:type _ :open? _ :uid _ :csrf-token _ :destroyed? _}
packer ; IPacker
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(let [?cb-uuid (when ?cb-fn (enc/uuid-str 6))
ppstr (pack packer (meta ev) ev ?cb-uuid)]
(when-let [cb-uuid ?cb-uuid]
(reset-in! cbs-waiting_ [cb-uuid] (have ?cb-fn))
(when-let [timeout-ms ?timeout-ms]
(go (<! (async/timeout timeout-ms))
(when-let [cb-fn* (pull-unused-cb-fn! cbs-waiting_ ?cb-uuid)]
(cb-fn* :chsk/timeout)))))
(try
(.send @socket_ ppstr)
(reset! kalive-due?_ false)
:apparent-success
(catch js/Error e
(errorf e "Chsk send error")
(when-let [cb-uuid ?cb-uuid]
(let [cb-fn* (or (pull-unused-cb-fn! cbs-waiting_ cb-uuid)
(have ?cb-fn))]
(cb-fn* :chsk/error)))
false))))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [s @socket_] (.close s 3000 "SENTE_RECONNECT")))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [s @socket_] (.close s 1000 "CLOSE_NORMAL")))
(chsk-init! [chsk]
(when-let [WebSocket (or (aget js/window "WebSocket")
(aget js/window "MozWebSocket"))]
((fn connect! []
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (swap! nattempt_ inc)]
(.clearInterval js/window @kalive-timer_)
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout! connect! nattempt*
backoff-ms-fn)))]
(if-let [socket
(try
(WebSocket. (enc/merge-url-with-query-string url
{:client-id client-id}))
(catch js/Error e
(errorf e "WebSocket js/Error")
nil))]
(reset! socket_
(doto socket
(aset "onerror" (fn [ws-ev] (errorf "WebSocket error: %s" ws-ev)))
(aset "onmessage" ; Nb receives both push & cb evs!
(fn [ws-ev]
(let [;; Nb may or may NOT satisfy `event?` since we also
;; receive cb replies here! This is actually why
;; we prefix our pstrs to indicate whether they're
;; wrapped or not.
ppstr (aget ws-ev "data")
[clj ?cb-uuid] (unpack packer ppstr)]
;; (assert-event clj) ;; NO!
(or
(and (handle-when-handshake! chsk chs clj)
(reset! nattempt_ 0))
(if-let [cb-uuid ?cb-uuid]
(if-let [cb-fn (pull-unused-cb-fn! cbs-waiting_
cb-uuid)]
(cb-fn clj)
(warnf "Cb reply w/o local cb-fn: %s" clj))
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)))))))
(aset "onopen"
(fn [_ws-ev]
(reset! kalive-timer_
(.setInterval js/window
(fn []
(when @kalive-due?_ ; Don't ping unnecessarily
(chsk-send! chsk [:chsk/ws-ping]))
(reset! kalive-due?_ true))
kalive-ms))
;; NO, better for server to send a handshake!:
;; (merge>chsk-state! chsk {:open? true})
))
;; Fires repeatedly (on each connection attempt) while
;; server is down:
(aset "onclose"
(fn [_ws-ev]
(merge>chsk-state! chsk {:open? false})
(retry!)))))
;; Couldn't even get a socket:
(retry!))))))
chsk)))
(defrecord ChAjaxSocket
[client-id url chs timeout-ms ajax-opts curr-xhr_ state_ packer
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(do
(enc/ajax-lite url
(merge ajax-opts
{:method :post :timeout-ms ?timeout-ms
:resp-type :text ; We'll do our own pstr decoding
:params
(let [ppstr (pack packer (meta ev) ev (when ?cb-fn :ajax-cb))]
{:_ (enc/now-udt) ; Force uncached resp
:csrf-token (:csrf-token @state_)
;; :client-id client-id ; Unnecessary here
:ppstr ppstr})})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(if (= ?error :timeout)
(when ?cb-fn (?cb-fn :chsk/timeout))
(do (merge>chsk-state! chsk {:open? false})
(when ?cb-fn (?cb-fn :chsk/error))))
(let [content ?content
resp-ppstr content
[resp-clj _] (unpack packer resp-ppstr)]
(if ?cb-fn (?cb-fn resp-clj)
(when (not= resp-clj :chsk/dummy-cb-200)
(warnf "Cb reply w/o local cb-fn: %s" resp-clj)))
(merge>chsk-state! chsk {:open? true})))))
:apparent-success))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-init! [chsk]
((fn async-poll-for-update! [nattempt]
(tracef "async-poll-for-update!")
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (inc nattempt)]
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout!
(partial async-poll-for-update! nattempt*)
nattempt*
backoff-ms-fn)))]
(reset! curr-xhr_
(enc/ajax-lite url
(merge ajax-opts
{:method :get :timeout-ms timeout-ms
:resp-type :text ; Prefer to do our own pstr reading
:params
(merge
{:_ (enc/now-udt) ; Force uncached resp
:client-id client-id}
;; A truthy :handshake? param will prompt server to
;; reply immediately with a handshake response,
;; letting us confirm that our client<->server comms
;; are working:
(when-not (:open? @state_) {:handshake? true}))})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(cond
(= ?error :timeout) (async-poll-for-update! 0)
;; (= ?error :abort) ; Abort => intentional, not an error
:else
(do (merge>chsk-state! chsk {:open? false})
(retry!)))
;; The Ajax long-poller is used only for events, never cbs:
(let [content ?content
ppstr content
[clj _] (unpack packer ppstr)]
(or
(handle-when-handshake! chsk chs clj)
;; Actually poll for an application reply:
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)
(merge>chsk-state! chsk {:open? true})))
(async-poll-for-update! 0)))))))))
0)
chsk))
(defn- get-chsk-url [protocol chsk-host chsk-path type]
(let [protocol (case type :ajax protocol
:ws (if (= protocol "https:") "wss:" "ws:"))]
(str protocol "//" (enc/path chsk-host chsk-path))))
(defn make-channel-socket!
"Returns a map with keys:
:ch-recv ; core.async channel to receive `event-msg`s (internal or from clients).
; May `put!` (inject) arbitrary `event`s to this channel.
:send-fn ; (fn [event & [?timeout-ms ?cb-fn]]) for client>server send.
:state ; Watchable, read-only (atom {:type _ :open? _ :uid _ :csrf-token _}).
:chsk ; IChSocket implementer. You can usu. ignore this.
Common options:
:type ; e/o #{:auto :ws :ajax}. You'll usually want the default (:auto)
:host ; Server host (defaults to current page's host)
:ws-kalive-ms ; Ping to keep a WebSocket conn alive if no activity w/in given
; number of milliseconds
:lp-kalive-ms ; Ping to keep a long-polling (Ajax) conn alive ''
:packer ; :edn (default), or an IPacker implementation (experimental)
:ajax-opts ; Base opts map provided to `taoensso.encore/ajax-lite`
:wrap-recv-evs? ; Should events from server be wrapped in [:chsk/recv _]?"
[path &
& [{:keys [type host recv-buf-or-n ws-kalive-ms lp-timeout-ms packer
client-id ajax-opts wrap-recv-evs? backoff-ms-fn]
:as opts
:or {type :auto
recv-buf-or-n (async/sliding-buffer 2048) ; Mostly for buffered-evs
ws-kalive-ms 25000 ; < Heroku 30s conn timeout
lp-timeout-ms 25000 ; ''
packer :edn
client-id (or (:client-uuid opts) ; Backwards compatibility
(enc/uuid-str))
;; TODO Deprecated. Default to false later, then eventually just
;; drop this option altogether? - here now for back compatibility:
wrap-recv-evs? true
backoff-ms-fn enc/exp-backoff}}
_deprecated-more-opts]]
{:pre [(have? [:in #{:ajax :ws :auto}] type)
(have? enc/nblank-str? client-id)]}
(when (not (nil? _deprecated-more-opts))
(warnf "`make-channel-socket!` fn signature CHANGED with Sente v0.10.0."))
(when (contains? opts :lp-timeout)
(warnf ":lp-timeout opt has CHANGED; please use :lp-timout-ms."))
(let [packer (interfaces/coerce-packer packer)
win-location (enc/get-window-location)
win-protocol (:protocol win-location)
host (or host (:host win-location))
path (or path (:pathname win-location))
private-chs {:state (chan (async/sliding-buffer 10))
:internal (chan (async/sliding-buffer 10))
:<server (chan recv-buf-or-n)}
ever-opened?_ (atom false)
state* (fn [state]
(if (or (not (:open? state)) @ever-opened?_) state
(do (reset! ever-opened?_ true)
(assoc state :first-open? true))))
;; TODO map< is deprecated in favour of transducers (but needs Clojure 1.7+)
public-ch-recv
(async/merge
[(:internal private-chs)
(async/map< (fn [state] [:chsk/state (state* state)]) (:state private-chs))
(let [<server-ch (:<server private-chs)]
(if wrap-recv-evs?
(async/map< (fn [ev] [:chsk/recv ev]) <server-ch)
(async/map< (fn [ev]
(let [[id ?data] ev]
;; Server shouldn't send :chsk/ events. As a
;; matter of hygiene, ensure no :chsk/_ evs are
;; received over <server-ch
(have? #(not= % "chsk") (namespace id))
ev))
<server-ch)))]
;; recv-buf-or-n ; Seems to be malfunctioning
)
chsk
(or
(and (not= type :ajax)
(chsk-init!
(map->ChWebSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ws) ; Deprecated
(get-chsk-url win-protocol host path :ws))
:chs private-chs
:packer packer
:socket_ (atom nil)
:kalive-ms ws-kalive-ms
:kalive-timer_ (atom nil)
:kalive-due?_ (atom true)
:nattempt_ (atom 0)
:cbs-waiting_ (atom {})
:state_ (atom {:type :ws :open? false
:destroyed? false})
:backoff-ms-fn backoff-ms-fn})))
(and (not= type :ws)
(chsk-init!
(map->ChAjaxSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ajax) ; Deprecated
(get-chsk-url win-protocol host path :ajax))
:chs private-chs
:packer packer
:timeout-ms lp-timeout-ms
:curr-xhr_ (atom nil)
:state_ (atom {:type :ajax :open? false
:destroyed? false})
:ajax-opts ajax-opts
:backoff-ms-fn backoff-ms-fn}))))
_ (assert chsk "Failed to create channel socket")
send-fn (partial chsk-send! chsk)
public-ch-recv
(async/map<
;; All client-side `event-msg`s go through this (allows client to
;; inject arbitrary synthetic events into router for handling):
(fn ev->ev-msg [ev]
(let [[ev-id ev-?data :as ev] (as-event ev)]
{:ch-recv public-ch-recv
:send-fn send-fn
:state (:state_ chsk)
:event ev
:id ev-id
:?data ev-?data}))
public-ch-recv)]
(when chsk
{:chsk chsk
:ch-recv public-ch-recv ; `ev`s->`ev-msg`s ch
:send-fn send-fn
:state (:state_ chsk)})))
;;;; Router wrapper
(defn start-chsk-router!
"Creates a go-loop to call `(event-msg-handler <event-msg>)` and returns a
`(fn stop! [])`. Catches & logs errors. Advanced users may choose to instead
write their own loop against `ch-recv`."
[ch-recv event-msg-handler & [{:as opts :keys [trace-evs?]}]]
(let [ch-ctrl (chan)]
(go-loop []
(let [[v p] (async/alts! [ch-recv ch-ctrl])
stop? (enc/kw-identical? p ch-ctrl)]
(when-not stop?
(let [{:as event-msg :keys [event]} v
[_ ?error]
(enc/catch-errors
(when trace-evs? (tracef "Pre-handler event: %s" event))
(if-not (event-msg? event-msg)
;; Shouldn't be possible here, but we're being cautious:
(errorf "Bad event: %s" event) ; Log 'n drop
(event-msg-handler event-msg)))]
(when-let [e ?error] (errorf e "Chsk router handling error: %s" event))
(recur)))))
(fn stop! [] (async/close! ch-ctrl))))
;;;; Deprecated
(defn start-chsk-router-loop!
"DEPRECATED: Please use `start-chsk-router!` instead."
[event-handler ch-recv]
(start-chsk-router! ch-recv
;; Old handler form: (fn [ev ch-recv])
(fn [ev-msg] (event-handler (:event ev-msg) (:ch-recv ev-msg)))))
(defn set-logging-level! "DEPRECATED. Please use `timbre/set-level!` instead."
[level] (timbre/set-level! level))
;; (set-logging-level! :trace) ; For debugging
(def ajax-call
"DEPRECATED. Please use `taoensso.encore/ajax-lite` instead."
enc/ajax-lite)
(def default-chsk-url-fn "DEPRECATED."
(fn [path {:as location :keys [adjusted-protocol host pathname]} websocket?]
(str adjusted-protocol "//" host (or path pathname))))
;;;;;;;;;;;; This file autogenerated from src/taoensso/sente.cljx
| 54098 | (ns taoensso.sente
"Channel sockets. Otherwise known as The Shiz.
Protocol | client>server | client>server ?+ ack/reply | server>user push
* WebSockets: ✓ [1] ✓
* Ajax: [2] ✓ [3]
[1] Emulate with cb-uuid wrapping.
[2] Emulate with dummy-cb wrapping.
[3] Emulate with long-polling.
Abbreviations:
* chsk - Channel socket. Sente's own pseudo \"socket\".
* net-ch - Network channel. Underlying web server's channel. Must implement
Sente's async net channel interface.
* uid - User-id. An application-level user identifier used for async push.
May have semantic meaning (e.g. username, email address), or not
(e.g. client/random id) - app's discretion.
* cb - Callback.
* tout - Timeout.
* ws - WebSocket/s.
* pstr - Packed string. Arbitrary Clojure data serialized as a string (e.g.
edn) for client<->server comms.
Special messages:
* Callback wrapping: [<clj> <?cb-uuid>] for [1],[2].
* Callback replies: :chsk/closed, :chsk/timeout, :chsk/error.
* Client-side events:
[:chsk/handshake [<?uid> <?csrf-token> <?handshake-data>]],
[:chsk/state <new-state>],
[:chsk/recv <[buffered-evs]>] ; server>user push
* Server-side events:
[:chsk/ws-ping],
[:chsk/bad-package <packed-str>],
[:chsk/bad-event <chsk-event>],
[:chsk/uidport-open],
[:chsk/uidport-close].
Notable implementation details:
* core.async is used liberally where brute-force core.async allows for
significant implementation simplifications. We lean on core.async's strong
efficiency here.
* For WebSocket fallback we use long-polling rather than HTTP 1.1 streaming
(chunked transfer encoding). Http-kit _does_ support chunked transfer
encoding but a small minority of browsers &/or proxies do not. Instead of
implementing all 3 modes (WebSockets, streaming, long-polling) - it seemed
reasonable to focus on the two extremes (performance + compatibility). In
any case client support for WebSockets is growing rapidly so fallback
modes will become increasingly irrelevant while the extra simplicity will
continue to pay dividends.
General-use notes:
* Single HTTP req+session persists over entire chsk session but cannot
modify sessions! Use standard a/sync HTTP Ring req/resp for logins, etc.
* Easy to wrap standard HTTP Ring resps for transport over chsks. Prefer
this approach to modifying handlers (better portability)."
{:author "<NAME>"}
(:require
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[taoensso.encore :as enc :refer (format swap-in! reset-in! swapped)
:refer-macros (have? have)]
[taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)]
[taoensso.sente.interfaces :as interfaces])
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)]))
;;;; Encore version check
;;;; Events
;; * Clients & server both send `event`s and receive (i.e. route) `event-msg`s.
(defn- validate-event [x]
(cond
(not (vector? x)) :wrong-type
(not (#{1 2} (count x))) :wrong-length
:else (let [[ev-id _] x]
(cond (not (keyword? ev-id)) :wrong-id-type
(not (namespace ev-id)) :unnamespaced-id
:else nil))))
(defn event? "Valid [ev-id ?ev-data] form?" [x] (nil? (validate-event x)))
(defn as-event [x] (if (event? x) x [:chsk/bad-event x]))
(defn assert-event [x]
(when-let [?err (validate-event x)]
(let [err-fmt
(str
(case ?err
:wrong-type "Malformed event (wrong type)."
:wrong-length "Malformed event (wrong length)."
(:wrong-id-type :unnamespaced-id)
"Malformed event (`ev-id` should be a namespaced keyword)."
:else "Malformed event (unknown error).")
" Event should be of `[ev-id ?ev-data]` form: %s")]
(throw (ex-info (format err-fmt (str x)) {:malformed-event x})))))
(defn event-msg? [x]
(and
(map? x)
(enc/keys= x #{:ch-recv :send-fn :state :event :id :?data})
(let [{:keys [ch-recv send-fn state event]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? state)
(event? event))))
)
(defn cb-success? "Note that cb reply need _not_ be `event` form!"
[cb-reply-clj] (not (#{:chsk/closed :chsk/timeout :chsk/error} cb-reply-clj)))
;;;; Packing
;; * Client<->server payloads are arbitrary Clojure vals (cb replies or events).
;; * Payloads are packed for client<->server transit.
;; * Packing includes ->str encoding, and may incl. wrapping to carry cb info.
(defn- unpack* "pstr->clj" [packer pstr]
(try
(interfaces/unpack packer (have string? pstr))
(catch :default t
(debugf "Bad package: %s (%s)" pstr t)
(throw t) ; Let client rethrow on bad pstr from server
)))
(defn- with-?meta [x ?m] (if (seq ?m) (with-meta x ?m) x))
(defn- pack* "clj->prefixed-pstr"
([packer ?packer-meta clj]
(str "-" ; => Unwrapped (no cb metadata)
(interfaces/pack packer (with-?meta clj ?packer-meta))))
([packer ?packer-meta clj ?cb-uuid]
(let [;;; Keep wrapping as light as possible:
?cb-uuid (if (= ?cb-uuid :ajax-cb) 0 ?cb-uuid)
wrapped-clj (if ?cb-uuid [clj ?cb-uuid] [clj])]
(str "+" ; => Wrapped (cb metadata)
(interfaces/pack packer (with-?meta wrapped-clj ?packer-meta))))))
(defn- pack [& args]
(let [pstr (apply pack* args)]
(tracef "Packing: %s -> %s" args pstr)
pstr))
(defn- unpack "prefixed-pstr->[clj ?cb-uuid]"
[packer prefixed-pstr]
(have? string? prefixed-pstr)
(let [prefix (enc/substr prefixed-pstr 0 1)
pstr (enc/substr prefixed-pstr 1)
clj (unpack* packer pstr) ; May be un/wrapped
wrapped? (case prefix "-" false "+" true)
[clj ?cb-uuid] (if wrapped? clj [clj nil])
?cb-uuid (if (= 0 ?cb-uuid) :ajax-cb ?cb-uuid)]
(tracef "Unpacking: %s -> %s" prefixed-pstr [clj ?cb-uuid])
[clj ?cb-uuid]))
(comment
(do (require '[taoensso.sente.packers.transit :as transit])
(def edn-packer interfaces/edn-packer)
(def flexi-packer (transit/get-flexi-packer)))
(unpack edn-packer (pack edn-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {:json true} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] :ajax-cb)))
;;;; Server API
;;;; Client API
(defprotocol IChSocket
(chsk-init! [chsk] "Implementation detail.")
(chsk-destroy! [chsk] "Kills socket, stops auto-reconnects.")
(chsk-reconnect! [chsk] "Drops connection, allows auto-reconnect. Useful for reauthenticating after login/logout.")
(chsk-send!* [chsk ev opts] "Implementation detail."))
(defn chsk-send!
"Sends `[ev-id ev-?data :as event]`, returns true on apparent success."
([chsk ev] (chsk-send! chsk ev {}))
([chsk ev ?timeout-ms ?cb] (chsk-send! chsk ev {:timeout-ms ?timeout-ms
:cb ?cb}))
([chsk ev opts]
(tracef "Chsk send: (%s) %s" (assoc opts :cb (boolean (:cb opts))) ev)
(chsk-send!* chsk ev opts)))
(defn- assert-send-args [x ?timeout-ms ?cb]
(assert-event x)
(assert (or (and (nil? ?timeout-ms) (nil? ?cb))
(and (enc/nneg-int? ?timeout-ms)))
(format "cb requires a timeout; timeout-ms should be a +ive integer: %s"
?timeout-ms))
(assert (or (nil? ?cb) (ifn? ?cb) (enc/chan? ?cb))
(format "cb should be nil, an ifn, or a channel: %s" (type ?cb))))
(defn- pull-unused-cb-fn! [cbs-waiting_ ?cb-uuid]
(when-let [cb-uuid ?cb-uuid]
(swap-in! cbs-waiting_ [cb-uuid]
(fn [?f] (swapped :swap/dissoc ?f)))))
(defn- merge>chsk-state! [{:keys [chs state_] :as chsk} merge-state]
(let [[old-state new-state]
(swap-in! state_ []
(fn [old-state]
(let [new-state (merge old-state merge-state)
;; Is this a reasonable way of helping client distinguish
;; cause of an auto reconnect? Didn't give it much thought...
new-state (if-not (and (:requested-reconnect-pending? old-state)
(:open? new-state)
(not (:open? old-state)))
new-state
(-> new-state
(dissoc :requested-reconnect-pending?)
(assoc :requested-reconnect? true)))]
(swapped new-state [old-state new-state]))))]
(when (not= old-state new-state)
;; (debugf "Chsk state change: %s" new-state)
(put! (:state chs) new-state)
new-state)))
(defn- cb-chan-as-fn
"Experimental, undocumented. Allows a core.async channel to be provided
instead of a cb-fn. The channel will receive values of form
[<event-id>.cb <reply>]."
[?cb ev]
(if (or (nil? ?cb) (ifn? ?cb)) ?cb
(do (have? enc/chan? ?cb)
(assert-event ev)
(let [[ev-id _] ev
cb-ch ?cb]
(fn [reply]
(put! cb-ch [(keyword (str (enc/fq-name ev-id) ".cb"))
reply]))))))
(defn- receive-buffered-evs! [chs clj]
(tracef "receive-buffered-evs!: %s" clj)
(let [buffered-evs (have vector? clj)]
(doseq [ev buffered-evs]
(assert-event ev)
(put! (:<server chs) ev))))
(defn- handle-when-handshake! [chsk chs clj]
(let [handshake? (and (vector? clj) ; Nb clj may be callback reply
(= (first clj) :chsk/handshake))]
(tracef "handle-when-handshake (%s): %s"
(if handshake? :handshake :non-handshake) clj)
(when handshake?
(let [[_ [?uid ?csrf-token ?handshake-data] :as handshake-ev] clj
;; Another idea? Not fond of how this places restrictions on the
;; form and content of ?handshake-data:
;; handshake-ev [:chsk/handshake
;; (merge
;; (have [:or nil? map?] ?handshake-data)
;; {:?uid ?uid
;; :?csrf-token ?csrf-token})]
]
(when (str/blank? ?csrf-token)
(warnf "SECURITY WARNING: no CSRF token available for use by Sente"))
(merge>chsk-state! chsk
{:open? true
:uid ?uid
:csrf-token ?csrf-token
;; Could also just merge ?handshake-data into chsk state here, but
;; it seems preferable (?) to instead register a unique
;; :chsk/handshake event
})
(assert-event handshake-ev)
(put! (:internal chs) handshake-ev)
:handled))))
(defn set-exp-backoff-timeout! [nullary-f nattempt & [backoff-ms-fn]]
(let [timeout-ms (backoff-ms-fn (or nattempt 0))]
(.setTimeout js/window nullary-f timeout-ms)))
;; Handles reconnects, keep-alives, callbacks:
(defrecord ChWebSocket
[client-id url chs socket_ kalive-ms kalive-timer_ kalive-due?_ nattempt_
cbs-waiting_ ; {<cb-uuid> <fn> ...}
state_ ; {:type _ :open? _ :uid _ :csrf-token _ :destroyed? _}
packer ; IPacker
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(let [?cb-uuid (when ?cb-fn (enc/uuid-str 6))
ppstr (pack packer (meta ev) ev ?cb-uuid)]
(when-let [cb-uuid ?cb-uuid]
(reset-in! cbs-waiting_ [cb-uuid] (have ?cb-fn))
(when-let [timeout-ms ?timeout-ms]
(go (<! (async/timeout timeout-ms))
(when-let [cb-fn* (pull-unused-cb-fn! cbs-waiting_ ?cb-uuid)]
(cb-fn* :chsk/timeout)))))
(try
(.send @socket_ ppstr)
(reset! kalive-due?_ false)
:apparent-success
(catch js/Error e
(errorf e "Chsk send error")
(when-let [cb-uuid ?cb-uuid]
(let [cb-fn* (or (pull-unused-cb-fn! cbs-waiting_ cb-uuid)
(have ?cb-fn))]
(cb-fn* :chsk/error)))
false))))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [s @socket_] (.close s 3000 "SENTE_RECONNECT")))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [s @socket_] (.close s 1000 "CLOSE_NORMAL")))
(chsk-init! [chsk]
(when-let [WebSocket (or (aget js/window "WebSocket")
(aget js/window "MozWebSocket"))]
((fn connect! []
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (swap! nattempt_ inc)]
(.clearInterval js/window @kalive-timer_)
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout! connect! nattempt*
backoff-ms-fn)))]
(if-let [socket
(try
(WebSocket. (enc/merge-url-with-query-string url
{:client-id client-id}))
(catch js/Error e
(errorf e "WebSocket js/Error")
nil))]
(reset! socket_
(doto socket
(aset "onerror" (fn [ws-ev] (errorf "WebSocket error: %s" ws-ev)))
(aset "onmessage" ; Nb receives both push & cb evs!
(fn [ws-ev]
(let [;; Nb may or may NOT satisfy `event?` since we also
;; receive cb replies here! This is actually why
;; we prefix our pstrs to indicate whether they're
;; wrapped or not.
ppstr (aget ws-ev "data")
[clj ?cb-uuid] (unpack packer ppstr)]
;; (assert-event clj) ;; NO!
(or
(and (handle-when-handshake! chsk chs clj)
(reset! nattempt_ 0))
(if-let [cb-uuid ?cb-uuid]
(if-let [cb-fn (pull-unused-cb-fn! cbs-waiting_
cb-uuid)]
(cb-fn clj)
(warnf "Cb reply w/o local cb-fn: %s" clj))
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)))))))
(aset "onopen"
(fn [_ws-ev]
(reset! kalive-timer_
(.setInterval js/window
(fn []
(when @kalive-due?_ ; Don't ping unnecessarily
(chsk-send! chsk [:chsk/ws-ping]))
(reset! kalive-due?_ true))
kalive-ms))
;; NO, better for server to send a handshake!:
;; (merge>chsk-state! chsk {:open? true})
))
;; Fires repeatedly (on each connection attempt) while
;; server is down:
(aset "onclose"
(fn [_ws-ev]
(merge>chsk-state! chsk {:open? false})
(retry!)))))
;; Couldn't even get a socket:
(retry!))))))
chsk)))
(defrecord ChAjaxSocket
[client-id url chs timeout-ms ajax-opts curr-xhr_ state_ packer
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(do
(enc/ajax-lite url
(merge ajax-opts
{:method :post :timeout-ms ?timeout-ms
:resp-type :text ; We'll do our own pstr decoding
:params
(let [ppstr (pack packer (meta ev) ev (when ?cb-fn :ajax-cb))]
{:_ (enc/now-udt) ; Force uncached resp
:csrf-token (:csrf-token @state_)
;; :client-id client-id ; Unnecessary here
:ppstr ppstr})})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(if (= ?error :timeout)
(when ?cb-fn (?cb-fn :chsk/timeout))
(do (merge>chsk-state! chsk {:open? false})
(when ?cb-fn (?cb-fn :chsk/error))))
(let [content ?content
resp-ppstr content
[resp-clj _] (unpack packer resp-ppstr)]
(if ?cb-fn (?cb-fn resp-clj)
(when (not= resp-clj :chsk/dummy-cb-200)
(warnf "Cb reply w/o local cb-fn: %s" resp-clj)))
(merge>chsk-state! chsk {:open? true})))))
:apparent-success))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-init! [chsk]
((fn async-poll-for-update! [nattempt]
(tracef "async-poll-for-update!")
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (inc nattempt)]
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout!
(partial async-poll-for-update! nattempt*)
nattempt*
backoff-ms-fn)))]
(reset! curr-xhr_
(enc/ajax-lite url
(merge ajax-opts
{:method :get :timeout-ms timeout-ms
:resp-type :text ; Prefer to do our own pstr reading
:params
(merge
{:_ (enc/now-udt) ; Force uncached resp
:client-id client-id}
;; A truthy :handshake? param will prompt server to
;; reply immediately with a handshake response,
;; letting us confirm that our client<->server comms
;; are working:
(when-not (:open? @state_) {:handshake? true}))})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(cond
(= ?error :timeout) (async-poll-for-update! 0)
;; (= ?error :abort) ; Abort => intentional, not an error
:else
(do (merge>chsk-state! chsk {:open? false})
(retry!)))
;; The Ajax long-poller is used only for events, never cbs:
(let [content ?content
ppstr content
[clj _] (unpack packer ppstr)]
(or
(handle-when-handshake! chsk chs clj)
;; Actually poll for an application reply:
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)
(merge>chsk-state! chsk {:open? true})))
(async-poll-for-update! 0)))))))))
0)
chsk))
(defn- get-chsk-url [protocol chsk-host chsk-path type]
(let [protocol (case type :ajax protocol
:ws (if (= protocol "https:") "wss:" "ws:"))]
(str protocol "//" (enc/path chsk-host chsk-path))))
(defn make-channel-socket!
"Returns a map with keys:
:ch-recv ; core.async channel to receive `event-msg`s (internal or from clients).
; May `put!` (inject) arbitrary `event`s to this channel.
:send-fn ; (fn [event & [?timeout-ms ?cb-fn]]) for client>server send.
:state ; Watchable, read-only (atom {:type _ :open? _ :uid _ :csrf-token _}).
:chsk ; IChSocket implementer. You can usu. ignore this.
Common options:
:type ; e/o #{:auto :ws :ajax}. You'll usually want the default (:auto)
:host ; Server host (defaults to current page's host)
:ws-kalive-ms ; Ping to keep a WebSocket conn alive if no activity w/in given
; number of milliseconds
:lp-kalive-ms ; Ping to keep a long-polling (Ajax) conn alive ''
:packer ; :edn (default), or an IPacker implementation (experimental)
:ajax-opts ; Base opts map provided to `taoensso.encore/ajax-lite`
:wrap-recv-evs? ; Should events from server be wrapped in [:chsk/recv _]?"
[path &
& [{:keys [type host recv-buf-or-n ws-kalive-ms lp-timeout-ms packer
client-id ajax-opts wrap-recv-evs? backoff-ms-fn]
:as opts
:or {type :auto
recv-buf-or-n (async/sliding-buffer 2048) ; Mostly for buffered-evs
ws-kalive-ms 25000 ; < Heroku 30s conn timeout
lp-timeout-ms 25000 ; ''
packer :edn
client-id (or (:client-uuid opts) ; Backwards compatibility
(enc/uuid-str))
;; TODO Deprecated. Default to false later, then eventually just
;; drop this option altogether? - here now for back compatibility:
wrap-recv-evs? true
backoff-ms-fn enc/exp-backoff}}
_deprecated-more-opts]]
{:pre [(have? [:in #{:ajax :ws :auto}] type)
(have? enc/nblank-str? client-id)]}
(when (not (nil? _deprecated-more-opts))
(warnf "`make-channel-socket!` fn signature CHANGED with Sente v0.10.0."))
(when (contains? opts :lp-timeout)
(warnf ":lp-timeout opt has CHANGED; please use :lp-timout-ms."))
(let [packer (interfaces/coerce-packer packer)
win-location (enc/get-window-location)
win-protocol (:protocol win-location)
host (or host (:host win-location))
path (or path (:pathname win-location))
private-chs {:state (chan (async/sliding-buffer 10))
:internal (chan (async/sliding-buffer 10))
:<server (chan recv-buf-or-n)}
ever-opened?_ (atom false)
state* (fn [state]
(if (or (not (:open? state)) @ever-opened?_) state
(do (reset! ever-opened?_ true)
(assoc state :first-open? true))))
;; TODO map< is deprecated in favour of transducers (but needs Clojure 1.7+)
public-ch-recv
(async/merge
[(:internal private-chs)
(async/map< (fn [state] [:chsk/state (state* state)]) (:state private-chs))
(let [<server-ch (:<server private-chs)]
(if wrap-recv-evs?
(async/map< (fn [ev] [:chsk/recv ev]) <server-ch)
(async/map< (fn [ev]
(let [[id ?data] ev]
;; Server shouldn't send :chsk/ events. As a
;; matter of hygiene, ensure no :chsk/_ evs are
;; received over <server-ch
(have? #(not= % "chsk") (namespace id))
ev))
<server-ch)))]
;; recv-buf-or-n ; Seems to be malfunctioning
)
chsk
(or
(and (not= type :ajax)
(chsk-init!
(map->ChWebSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ws) ; Deprecated
(get-chsk-url win-protocol host path :ws))
:chs private-chs
:packer packer
:socket_ (atom nil)
:kalive-ms ws-kalive-ms
:kalive-timer_ (atom nil)
:kalive-due?_ (atom true)
:nattempt_ (atom 0)
:cbs-waiting_ (atom {})
:state_ (atom {:type :ws :open? false
:destroyed? false})
:backoff-ms-fn backoff-ms-fn})))
(and (not= type :ws)
(chsk-init!
(map->ChAjaxSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ajax) ; Deprecated
(get-chsk-url win-protocol host path :ajax))
:chs private-chs
:packer packer
:timeout-ms lp-timeout-ms
:curr-xhr_ (atom nil)
:state_ (atom {:type :ajax :open? false
:destroyed? false})
:ajax-opts ajax-opts
:backoff-ms-fn backoff-ms-fn}))))
_ (assert chsk "Failed to create channel socket")
send-fn (partial chsk-send! chsk)
public-ch-recv
(async/map<
;; All client-side `event-msg`s go through this (allows client to
;; inject arbitrary synthetic events into router for handling):
(fn ev->ev-msg [ev]
(let [[ev-id ev-?data :as ev] (as-event ev)]
{:ch-recv public-ch-recv
:send-fn send-fn
:state (:state_ chsk)
:event ev
:id ev-id
:?data ev-?data}))
public-ch-recv)]
(when chsk
{:chsk chsk
:ch-recv public-ch-recv ; `ev`s->`ev-msg`s ch
:send-fn send-fn
:state (:state_ chsk)})))
;;;; Router wrapper
(defn start-chsk-router!
"Creates a go-loop to call `(event-msg-handler <event-msg>)` and returns a
`(fn stop! [])`. Catches & logs errors. Advanced users may choose to instead
write their own loop against `ch-recv`."
[ch-recv event-msg-handler & [{:as opts :keys [trace-evs?]}]]
(let [ch-ctrl (chan)]
(go-loop []
(let [[v p] (async/alts! [ch-recv ch-ctrl])
stop? (enc/kw-identical? p ch-ctrl)]
(when-not stop?
(let [{:as event-msg :keys [event]} v
[_ ?error]
(enc/catch-errors
(when trace-evs? (tracef "Pre-handler event: %s" event))
(if-not (event-msg? event-msg)
;; Shouldn't be possible here, but we're being cautious:
(errorf "Bad event: %s" event) ; Log 'n drop
(event-msg-handler event-msg)))]
(when-let [e ?error] (errorf e "Chsk router handling error: %s" event))
(recur)))))
(fn stop! [] (async/close! ch-ctrl))))
;;;; Deprecated
(defn start-chsk-router-loop!
"DEPRECATED: Please use `start-chsk-router!` instead."
[event-handler ch-recv]
(start-chsk-router! ch-recv
;; Old handler form: (fn [ev ch-recv])
(fn [ev-msg] (event-handler (:event ev-msg) (:ch-recv ev-msg)))))
(defn set-logging-level! "DEPRECATED. Please use `timbre/set-level!` instead."
[level] (timbre/set-level! level))
;; (set-logging-level! :trace) ; For debugging
(def ajax-call
"DEPRECATED. Please use `taoensso.encore/ajax-lite` instead."
enc/ajax-lite)
(def default-chsk-url-fn "DEPRECATED."
(fn [path {:as location :keys [adjusted-protocol host pathname]} websocket?]
(str adjusted-protocol "//" host (or path pathname))))
;;;;;;;;;;;; This file autogenerated from src/taoensso/sente.cljx
| true | (ns taoensso.sente
"Channel sockets. Otherwise known as The Shiz.
Protocol | client>server | client>server ?+ ack/reply | server>user push
* WebSockets: ✓ [1] ✓
* Ajax: [2] ✓ [3]
[1] Emulate with cb-uuid wrapping.
[2] Emulate with dummy-cb wrapping.
[3] Emulate with long-polling.
Abbreviations:
* chsk - Channel socket. Sente's own pseudo \"socket\".
* net-ch - Network channel. Underlying web server's channel. Must implement
Sente's async net channel interface.
* uid - User-id. An application-level user identifier used for async push.
May have semantic meaning (e.g. username, email address), or not
(e.g. client/random id) - app's discretion.
* cb - Callback.
* tout - Timeout.
* ws - WebSocket/s.
* pstr - Packed string. Arbitrary Clojure data serialized as a string (e.g.
edn) for client<->server comms.
Special messages:
* Callback wrapping: [<clj> <?cb-uuid>] for [1],[2].
* Callback replies: :chsk/closed, :chsk/timeout, :chsk/error.
* Client-side events:
[:chsk/handshake [<?uid> <?csrf-token> <?handshake-data>]],
[:chsk/state <new-state>],
[:chsk/recv <[buffered-evs]>] ; server>user push
* Server-side events:
[:chsk/ws-ping],
[:chsk/bad-package <packed-str>],
[:chsk/bad-event <chsk-event>],
[:chsk/uidport-open],
[:chsk/uidport-close].
Notable implementation details:
* core.async is used liberally where brute-force core.async allows for
significant implementation simplifications. We lean on core.async's strong
efficiency here.
* For WebSocket fallback we use long-polling rather than HTTP 1.1 streaming
(chunked transfer encoding). Http-kit _does_ support chunked transfer
encoding but a small minority of browsers &/or proxies do not. Instead of
implementing all 3 modes (WebSockets, streaming, long-polling) - it seemed
reasonable to focus on the two extremes (performance + compatibility). In
any case client support for WebSockets is growing rapidly so fallback
modes will become increasingly irrelevant while the extra simplicity will
continue to pay dividends.
General-use notes:
* Single HTTP req+session persists over entire chsk session but cannot
modify sessions! Use standard a/sync HTTP Ring req/resp for logins, etc.
* Easy to wrap standard HTTP Ring resps for transport over chsks. Prefer
this approach to modifying handlers (better portability)."
{:author "PI:NAME:<NAME>END_PI"}
(:require
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[taoensso.encore :as enc :refer (format swap-in! reset-in! swapped)
:refer-macros (have? have)]
[taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)]
[taoensso.sente.interfaces :as interfaces])
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)]))
;;;; Encore version check
;;;; Events
;; * Clients & server both send `event`s and receive (i.e. route) `event-msg`s.
(defn- validate-event [x]
(cond
(not (vector? x)) :wrong-type
(not (#{1 2} (count x))) :wrong-length
:else (let [[ev-id _] x]
(cond (not (keyword? ev-id)) :wrong-id-type
(not (namespace ev-id)) :unnamespaced-id
:else nil))))
(defn event? "Valid [ev-id ?ev-data] form?" [x] (nil? (validate-event x)))
(defn as-event [x] (if (event? x) x [:chsk/bad-event x]))
(defn assert-event [x]
(when-let [?err (validate-event x)]
(let [err-fmt
(str
(case ?err
:wrong-type "Malformed event (wrong type)."
:wrong-length "Malformed event (wrong length)."
(:wrong-id-type :unnamespaced-id)
"Malformed event (`ev-id` should be a namespaced keyword)."
:else "Malformed event (unknown error).")
" Event should be of `[ev-id ?ev-data]` form: %s")]
(throw (ex-info (format err-fmt (str x)) {:malformed-event x})))))
(defn event-msg? [x]
(and
(map? x)
(enc/keys= x #{:ch-recv :send-fn :state :event :id :?data})
(let [{:keys [ch-recv send-fn state event]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? state)
(event? event))))
)
(defn cb-success? "Note that cb reply need _not_ be `event` form!"
[cb-reply-clj] (not (#{:chsk/closed :chsk/timeout :chsk/error} cb-reply-clj)))
;;;; Packing
;; * Client<->server payloads are arbitrary Clojure vals (cb replies or events).
;; * Payloads are packed for client<->server transit.
;; * Packing includes ->str encoding, and may incl. wrapping to carry cb info.
(defn- unpack* "pstr->clj" [packer pstr]
(try
(interfaces/unpack packer (have string? pstr))
(catch :default t
(debugf "Bad package: %s (%s)" pstr t)
(throw t) ; Let client rethrow on bad pstr from server
)))
(defn- with-?meta [x ?m] (if (seq ?m) (with-meta x ?m) x))
(defn- pack* "clj->prefixed-pstr"
([packer ?packer-meta clj]
(str "-" ; => Unwrapped (no cb metadata)
(interfaces/pack packer (with-?meta clj ?packer-meta))))
([packer ?packer-meta clj ?cb-uuid]
(let [;;; Keep wrapping as light as possible:
?cb-uuid (if (= ?cb-uuid :ajax-cb) 0 ?cb-uuid)
wrapped-clj (if ?cb-uuid [clj ?cb-uuid] [clj])]
(str "+" ; => Wrapped (cb metadata)
(interfaces/pack packer (with-?meta wrapped-clj ?packer-meta))))))
(defn- pack [& args]
(let [pstr (apply pack* args)]
(tracef "Packing: %s -> %s" args pstr)
pstr))
(defn- unpack "prefixed-pstr->[clj ?cb-uuid]"
[packer prefixed-pstr]
(have? string? prefixed-pstr)
(let [prefix (enc/substr prefixed-pstr 0 1)
pstr (enc/substr prefixed-pstr 1)
clj (unpack* packer pstr) ; May be un/wrapped
wrapped? (case prefix "-" false "+" true)
[clj ?cb-uuid] (if wrapped? clj [clj nil])
?cb-uuid (if (= 0 ?cb-uuid) :ajax-cb ?cb-uuid)]
(tracef "Unpacking: %s -> %s" prefixed-pstr [clj ?cb-uuid])
[clj ?cb-uuid]))
(comment
(do (require '[taoensso.sente.packers.transit :as transit])
(def edn-packer interfaces/edn-packer)
(def flexi-packer (transit/get-flexi-packer)))
(unpack edn-packer (pack edn-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer nil "hello"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {:json true} [:foo/bar {}] "my-cb-uuid"))
(unpack flexi-packer (pack flexi-packer {} [:foo/bar {}] :ajax-cb)))
;;;; Server API
;;;; Client API
(defprotocol IChSocket
(chsk-init! [chsk] "Implementation detail.")
(chsk-destroy! [chsk] "Kills socket, stops auto-reconnects.")
(chsk-reconnect! [chsk] "Drops connection, allows auto-reconnect. Useful for reauthenticating after login/logout.")
(chsk-send!* [chsk ev opts] "Implementation detail."))
(defn chsk-send!
"Sends `[ev-id ev-?data :as event]`, returns true on apparent success."
([chsk ev] (chsk-send! chsk ev {}))
([chsk ev ?timeout-ms ?cb] (chsk-send! chsk ev {:timeout-ms ?timeout-ms
:cb ?cb}))
([chsk ev opts]
(tracef "Chsk send: (%s) %s" (assoc opts :cb (boolean (:cb opts))) ev)
(chsk-send!* chsk ev opts)))
(defn- assert-send-args [x ?timeout-ms ?cb]
(assert-event x)
(assert (or (and (nil? ?timeout-ms) (nil? ?cb))
(and (enc/nneg-int? ?timeout-ms)))
(format "cb requires a timeout; timeout-ms should be a +ive integer: %s"
?timeout-ms))
(assert (or (nil? ?cb) (ifn? ?cb) (enc/chan? ?cb))
(format "cb should be nil, an ifn, or a channel: %s" (type ?cb))))
(defn- pull-unused-cb-fn! [cbs-waiting_ ?cb-uuid]
(when-let [cb-uuid ?cb-uuid]
(swap-in! cbs-waiting_ [cb-uuid]
(fn [?f] (swapped :swap/dissoc ?f)))))
(defn- merge>chsk-state! [{:keys [chs state_] :as chsk} merge-state]
(let [[old-state new-state]
(swap-in! state_ []
(fn [old-state]
(let [new-state (merge old-state merge-state)
;; Is this a reasonable way of helping client distinguish
;; cause of an auto reconnect? Didn't give it much thought...
new-state (if-not (and (:requested-reconnect-pending? old-state)
(:open? new-state)
(not (:open? old-state)))
new-state
(-> new-state
(dissoc :requested-reconnect-pending?)
(assoc :requested-reconnect? true)))]
(swapped new-state [old-state new-state]))))]
(when (not= old-state new-state)
;; (debugf "Chsk state change: %s" new-state)
(put! (:state chs) new-state)
new-state)))
(defn- cb-chan-as-fn
"Experimental, undocumented. Allows a core.async channel to be provided
instead of a cb-fn. The channel will receive values of form
[<event-id>.cb <reply>]."
[?cb ev]
(if (or (nil? ?cb) (ifn? ?cb)) ?cb
(do (have? enc/chan? ?cb)
(assert-event ev)
(let [[ev-id _] ev
cb-ch ?cb]
(fn [reply]
(put! cb-ch [(keyword (str (enc/fq-name ev-id) ".cb"))
reply]))))))
(defn- receive-buffered-evs! [chs clj]
(tracef "receive-buffered-evs!: %s" clj)
(let [buffered-evs (have vector? clj)]
(doseq [ev buffered-evs]
(assert-event ev)
(put! (:<server chs) ev))))
(defn- handle-when-handshake! [chsk chs clj]
(let [handshake? (and (vector? clj) ; Nb clj may be callback reply
(= (first clj) :chsk/handshake))]
(tracef "handle-when-handshake (%s): %s"
(if handshake? :handshake :non-handshake) clj)
(when handshake?
(let [[_ [?uid ?csrf-token ?handshake-data] :as handshake-ev] clj
;; Another idea? Not fond of how this places restrictions on the
;; form and content of ?handshake-data:
;; handshake-ev [:chsk/handshake
;; (merge
;; (have [:or nil? map?] ?handshake-data)
;; {:?uid ?uid
;; :?csrf-token ?csrf-token})]
]
(when (str/blank? ?csrf-token)
(warnf "SECURITY WARNING: no CSRF token available for use by Sente"))
(merge>chsk-state! chsk
{:open? true
:uid ?uid
:csrf-token ?csrf-token
;; Could also just merge ?handshake-data into chsk state here, but
;; it seems preferable (?) to instead register a unique
;; :chsk/handshake event
})
(assert-event handshake-ev)
(put! (:internal chs) handshake-ev)
:handled))))
(defn set-exp-backoff-timeout! [nullary-f nattempt & [backoff-ms-fn]]
(let [timeout-ms (backoff-ms-fn (or nattempt 0))]
(.setTimeout js/window nullary-f timeout-ms)))
;; Handles reconnects, keep-alives, callbacks:
(defrecord ChWebSocket
[client-id url chs socket_ kalive-ms kalive-timer_ kalive-due?_ nattempt_
cbs-waiting_ ; {<cb-uuid> <fn> ...}
state_ ; {:type _ :open? _ :uid _ :csrf-token _ :destroyed? _}
packer ; IPacker
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(let [?cb-uuid (when ?cb-fn (enc/uuid-str 6))
ppstr (pack packer (meta ev) ev ?cb-uuid)]
(when-let [cb-uuid ?cb-uuid]
(reset-in! cbs-waiting_ [cb-uuid] (have ?cb-fn))
(when-let [timeout-ms ?timeout-ms]
(go (<! (async/timeout timeout-ms))
(when-let [cb-fn* (pull-unused-cb-fn! cbs-waiting_ ?cb-uuid)]
(cb-fn* :chsk/timeout)))))
(try
(.send @socket_ ppstr)
(reset! kalive-due?_ false)
:apparent-success
(catch js/Error e
(errorf e "Chsk send error")
(when-let [cb-uuid ?cb-uuid]
(let [cb-fn* (or (pull-unused-cb-fn! cbs-waiting_ cb-uuid)
(have ?cb-fn))]
(cb-fn* :chsk/error)))
false))))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [s @socket_] (.close s 3000 "SENTE_RECONNECT")))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [s @socket_] (.close s 1000 "CLOSE_NORMAL")))
(chsk-init! [chsk]
(when-let [WebSocket (or (aget js/window "WebSocket")
(aget js/window "MozWebSocket"))]
((fn connect! []
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (swap! nattempt_ inc)]
(.clearInterval js/window @kalive-timer_)
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout! connect! nattempt*
backoff-ms-fn)))]
(if-let [socket
(try
(WebSocket. (enc/merge-url-with-query-string url
{:client-id client-id}))
(catch js/Error e
(errorf e "WebSocket js/Error")
nil))]
(reset! socket_
(doto socket
(aset "onerror" (fn [ws-ev] (errorf "WebSocket error: %s" ws-ev)))
(aset "onmessage" ; Nb receives both push & cb evs!
(fn [ws-ev]
(let [;; Nb may or may NOT satisfy `event?` since we also
;; receive cb replies here! This is actually why
;; we prefix our pstrs to indicate whether they're
;; wrapped or not.
ppstr (aget ws-ev "data")
[clj ?cb-uuid] (unpack packer ppstr)]
;; (assert-event clj) ;; NO!
(or
(and (handle-when-handshake! chsk chs clj)
(reset! nattempt_ 0))
(if-let [cb-uuid ?cb-uuid]
(if-let [cb-fn (pull-unused-cb-fn! cbs-waiting_
cb-uuid)]
(cb-fn clj)
(warnf "Cb reply w/o local cb-fn: %s" clj))
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)))))))
(aset "onopen"
(fn [_ws-ev]
(reset! kalive-timer_
(.setInterval js/window
(fn []
(when @kalive-due?_ ; Don't ping unnecessarily
(chsk-send! chsk [:chsk/ws-ping]))
(reset! kalive-due?_ true))
kalive-ms))
;; NO, better for server to send a handshake!:
;; (merge>chsk-state! chsk {:open? true})
))
;; Fires repeatedly (on each connection attempt) while
;; server is down:
(aset "onclose"
(fn [_ws-ev]
(merge>chsk-state! chsk {:open? false})
(retry!)))))
;; Couldn't even get a socket:
(retry!))))))
chsk)))
(defrecord ChAjaxSocket
[client-id url chs timeout-ms ajax-opts curr-xhr_ state_ packer
backoff-ms-fn]
IChSocket
(chsk-send!* [chsk ev {:as opts ?timeout-ms :timeout-ms ?cb :cb :keys [flush?]}]
(assert-send-args ev ?timeout-ms ?cb)
(let [?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(do (warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed)))
;; TODO Buffer before sending (but honor `:flush?`)
(do
(enc/ajax-lite url
(merge ajax-opts
{:method :post :timeout-ms ?timeout-ms
:resp-type :text ; We'll do our own pstr decoding
:params
(let [ppstr (pack packer (meta ev) ev (when ?cb-fn :ajax-cb))]
{:_ (enc/now-udt) ; Force uncached resp
:csrf-token (:csrf-token @state_)
;; :client-id client-id ; Unnecessary here
:ppstr ppstr})})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(if (= ?error :timeout)
(when ?cb-fn (?cb-fn :chsk/timeout))
(do (merge>chsk-state! chsk {:open? false})
(when ?cb-fn (?cb-fn :chsk/error))))
(let [content ?content
resp-ppstr content
[resp-clj _] (unpack packer resp-ppstr)]
(if ?cb-fn (?cb-fn resp-clj)
(when (not= resp-clj :chsk/dummy-cb-200)
(warnf "Cb reply w/o local cb-fn: %s" resp-clj)))
(merge>chsk-state! chsk {:open? true})))))
:apparent-success))))
(chsk-reconnect! [chsk]
(merge>chsk-state! chsk {:open? false :requested-reconnect-pending? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-destroy! [chsk]
(merge>chsk-state! chsk {:open? false :destroyed? true})
(when-let [x @curr-xhr_] (.abort x)))
(chsk-init! [chsk]
((fn async-poll-for-update! [nattempt]
(tracef "async-poll-for-update!")
(when-not (:destroyed? @state_)
(let [retry!
(fn []
(let [nattempt* (inc nattempt)]
(warnf "Chsk is closed: will try reconnect (%s)." nattempt*)
(set-exp-backoff-timeout!
(partial async-poll-for-update! nattempt*)
nattempt*
backoff-ms-fn)))]
(reset! curr-xhr_
(enc/ajax-lite url
(merge ajax-opts
{:method :get :timeout-ms timeout-ms
:resp-type :text ; Prefer to do our own pstr reading
:params
(merge
{:_ (enc/now-udt) ; Force uncached resp
:client-id client-id}
;; A truthy :handshake? param will prompt server to
;; reply immediately with a handshake response,
;; letting us confirm that our client<->server comms
;; are working:
(when-not (:open? @state_) {:handshake? true}))})
(fn ajax-cb [{:keys [?error ?content]}]
(if ?error
(cond
(= ?error :timeout) (async-poll-for-update! 0)
;; (= ?error :abort) ; Abort => intentional, not an error
:else
(do (merge>chsk-state! chsk {:open? false})
(retry!)))
;; The Ajax long-poller is used only for events, never cbs:
(let [content ?content
ppstr content
[clj _] (unpack packer ppstr)]
(or
(handle-when-handshake! chsk chs clj)
;; Actually poll for an application reply:
(let [buffered-evs clj]
(receive-buffered-evs! chs buffered-evs)
(merge>chsk-state! chsk {:open? true})))
(async-poll-for-update! 0)))))))))
0)
chsk))
(defn- get-chsk-url [protocol chsk-host chsk-path type]
(let [protocol (case type :ajax protocol
:ws (if (= protocol "https:") "wss:" "ws:"))]
(str protocol "//" (enc/path chsk-host chsk-path))))
(defn make-channel-socket!
"Returns a map with keys:
:ch-recv ; core.async channel to receive `event-msg`s (internal or from clients).
; May `put!` (inject) arbitrary `event`s to this channel.
:send-fn ; (fn [event & [?timeout-ms ?cb-fn]]) for client>server send.
:state ; Watchable, read-only (atom {:type _ :open? _ :uid _ :csrf-token _}).
:chsk ; IChSocket implementer. You can usu. ignore this.
Common options:
:type ; e/o #{:auto :ws :ajax}. You'll usually want the default (:auto)
:host ; Server host (defaults to current page's host)
:ws-kalive-ms ; Ping to keep a WebSocket conn alive if no activity w/in given
; number of milliseconds
:lp-kalive-ms ; Ping to keep a long-polling (Ajax) conn alive ''
:packer ; :edn (default), or an IPacker implementation (experimental)
:ajax-opts ; Base opts map provided to `taoensso.encore/ajax-lite`
:wrap-recv-evs? ; Should events from server be wrapped in [:chsk/recv _]?"
[path &
& [{:keys [type host recv-buf-or-n ws-kalive-ms lp-timeout-ms packer
client-id ajax-opts wrap-recv-evs? backoff-ms-fn]
:as opts
:or {type :auto
recv-buf-or-n (async/sliding-buffer 2048) ; Mostly for buffered-evs
ws-kalive-ms 25000 ; < Heroku 30s conn timeout
lp-timeout-ms 25000 ; ''
packer :edn
client-id (or (:client-uuid opts) ; Backwards compatibility
(enc/uuid-str))
;; TODO Deprecated. Default to false later, then eventually just
;; drop this option altogether? - here now for back compatibility:
wrap-recv-evs? true
backoff-ms-fn enc/exp-backoff}}
_deprecated-more-opts]]
{:pre [(have? [:in #{:ajax :ws :auto}] type)
(have? enc/nblank-str? client-id)]}
(when (not (nil? _deprecated-more-opts))
(warnf "`make-channel-socket!` fn signature CHANGED with Sente v0.10.0."))
(when (contains? opts :lp-timeout)
(warnf ":lp-timeout opt has CHANGED; please use :lp-timout-ms."))
(let [packer (interfaces/coerce-packer packer)
win-location (enc/get-window-location)
win-protocol (:protocol win-location)
host (or host (:host win-location))
path (or path (:pathname win-location))
private-chs {:state (chan (async/sliding-buffer 10))
:internal (chan (async/sliding-buffer 10))
:<server (chan recv-buf-or-n)}
ever-opened?_ (atom false)
state* (fn [state]
(if (or (not (:open? state)) @ever-opened?_) state
(do (reset! ever-opened?_ true)
(assoc state :first-open? true))))
;; TODO map< is deprecated in favour of transducers (but needs Clojure 1.7+)
public-ch-recv
(async/merge
[(:internal private-chs)
(async/map< (fn [state] [:chsk/state (state* state)]) (:state private-chs))
(let [<server-ch (:<server private-chs)]
(if wrap-recv-evs?
(async/map< (fn [ev] [:chsk/recv ev]) <server-ch)
(async/map< (fn [ev]
(let [[id ?data] ev]
;; Server shouldn't send :chsk/ events. As a
;; matter of hygiene, ensure no :chsk/_ evs are
;; received over <server-ch
(have? #(not= % "chsk") (namespace id))
ev))
<server-ch)))]
;; recv-buf-or-n ; Seems to be malfunctioning
)
chsk
(or
(and (not= type :ajax)
(chsk-init!
(map->ChWebSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ws) ; Deprecated
(get-chsk-url win-protocol host path :ws))
:chs private-chs
:packer packer
:socket_ (atom nil)
:kalive-ms ws-kalive-ms
:kalive-timer_ (atom nil)
:kalive-due?_ (atom true)
:nattempt_ (atom 0)
:cbs-waiting_ (atom {})
:state_ (atom {:type :ws :open? false
:destroyed? false})
:backoff-ms-fn backoff-ms-fn})))
(and (not= type :ws)
(chsk-init!
(map->ChAjaxSocket
{:client-id client-id
:url (if-let [f (:chsk-url-fn opts)]
(f path win-location :ajax) ; Deprecated
(get-chsk-url win-protocol host path :ajax))
:chs private-chs
:packer packer
:timeout-ms lp-timeout-ms
:curr-xhr_ (atom nil)
:state_ (atom {:type :ajax :open? false
:destroyed? false})
:ajax-opts ajax-opts
:backoff-ms-fn backoff-ms-fn}))))
_ (assert chsk "Failed to create channel socket")
send-fn (partial chsk-send! chsk)
public-ch-recv
(async/map<
;; All client-side `event-msg`s go through this (allows client to
;; inject arbitrary synthetic events into router for handling):
(fn ev->ev-msg [ev]
(let [[ev-id ev-?data :as ev] (as-event ev)]
{:ch-recv public-ch-recv
:send-fn send-fn
:state (:state_ chsk)
:event ev
:id ev-id
:?data ev-?data}))
public-ch-recv)]
(when chsk
{:chsk chsk
:ch-recv public-ch-recv ; `ev`s->`ev-msg`s ch
:send-fn send-fn
:state (:state_ chsk)})))
;;;; Router wrapper
(defn start-chsk-router!
"Creates a go-loop to call `(event-msg-handler <event-msg>)` and returns a
`(fn stop! [])`. Catches & logs errors. Advanced users may choose to instead
write their own loop against `ch-recv`."
[ch-recv event-msg-handler & [{:as opts :keys [trace-evs?]}]]
(let [ch-ctrl (chan)]
(go-loop []
(let [[v p] (async/alts! [ch-recv ch-ctrl])
stop? (enc/kw-identical? p ch-ctrl)]
(when-not stop?
(let [{:as event-msg :keys [event]} v
[_ ?error]
(enc/catch-errors
(when trace-evs? (tracef "Pre-handler event: %s" event))
(if-not (event-msg? event-msg)
;; Shouldn't be possible here, but we're being cautious:
(errorf "Bad event: %s" event) ; Log 'n drop
(event-msg-handler event-msg)))]
(when-let [e ?error] (errorf e "Chsk router handling error: %s" event))
(recur)))))
(fn stop! [] (async/close! ch-ctrl))))
;;;; Deprecated
(defn start-chsk-router-loop!
"DEPRECATED: Please use `start-chsk-router!` instead."
[event-handler ch-recv]
(start-chsk-router! ch-recv
;; Old handler form: (fn [ev ch-recv])
(fn [ev-msg] (event-handler (:event ev-msg) (:ch-recv ev-msg)))))
(defn set-logging-level! "DEPRECATED. Please use `timbre/set-level!` instead."
[level] (timbre/set-level! level))
;; (set-logging-level! :trace) ; For debugging
(def ajax-call
"DEPRECATED. Please use `taoensso.encore/ajax-lite` instead."
enc/ajax-lite)
(def default-chsk-url-fn "DEPRECATED."
(fn [path {:as location :keys [adjusted-protocol host pathname]} websocket?]
(str adjusted-protocol "//" host (or path pathname))))
;;;;;;;;;;;; This file autogenerated from src/taoensso/sente.cljx
|
[
{
"context": "pe :email\n :channel/identifier \"john@example.com\"}]\n user {:user/first-name \"John\"\n ",
"end": 806,
"score": 0.9999194145202637,
"start": 790,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "hn@example.com\"}]\n user {:user/first-name \"John\"\n :user/last-name \"Doe\"\n ",
"end": 846,
"score": 0.9998626708984375,
"start": 842,
"tag": "NAME",
"value": "John"
},
{
"context": "/first-name \"John\"\n :user/last-name \"Doe\"\n :user/channels channels\n ",
"end": 882,
"score": 0.9997905492782593,
"start": 879,
"tag": "NAME",
"value": "Doe"
},
{
"context": "r/channels channels\n :user/password \"foo\"}\n {:keys [:db/id]} (user/create-new-user ",
"end": 955,
"score": 0.9987671375274658,
"start": 952,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "und\n (user/find-user-by-identifier res \"john@example.com\")))))\n\n\n;; (def cn (create-empty-in-memory-db))\n\n",
"end": 1141,
"score": 0.9999184608459473,
"start": 1125,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "pe :email\n;; :channel/identifier \"john@example.com\"}])\n;; (def u-entity {:user/first-name \"John\"\n;; ",
"end": 1316,
"score": 0.9999197721481323,
"start": 1300,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "ample.com\"}])\n;; (def u-entity {:user/first-name \"John\"\n;; :user/last-name \"Doe\"\n;; ",
"end": 1361,
"score": 0.999866247177124,
"start": 1357,
"tag": "NAME",
"value": "John"
},
{
"context": "st-name \"John\"\n;; :user/last-name \"Doe\"\n;; :user/channels channels\n;; ",
"end": 1401,
"score": 0.9998229742050171,
"start": 1398,
"tag": "NAME",
"value": "Doe"
},
{
"context": "annels channels\n;; :user/password \"foo\"})\n\n;; (def u (user/create-new-user res u-entity ",
"end": 1482,
"score": 0.9981611371040344,
"start": 1479,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "0555),\n\n;; (user/find-channels-by-identifier res \"john@example.com\")\n\n;;(user/find-user-by-identifier! res \"john@exa",
"end": 1688,
"score": 0.9999249577522278,
"start": 1672,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "mple.com\")\n\n;;(user/find-user-by-identifier! res \"john@example.com\")\n\n;;(user/rm-user res (:db/id u) 1)\n\n\n;; (user/f",
"end": 1746,
"score": 0.9999250173568726,
"start": 1730,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": "u) 1)\n\n\n;; (user/find-channel-by-type res :email \"john@example.com\")\n\n;; (user/find-user-id-by-identifier res \"john",
"end": 1844,
"score": 0.9999256134033203,
"start": 1828,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": ".com\")\n\n;; (user/find-user-id-by-identifier res \"john@example.com\")\n\n;; (def new-c (user/create-channel res {:chann",
"end": 1906,
"score": 0.9999257922172546,
"start": 1890,
"tag": "EMAIL",
"value": "john@example.com"
},
{
"context": " {:channel/identifier \"john@example.com\"}\n;; {:cha",
"end": 2325,
"score": 0.999920666217804,
"start": 2309,
"tag": "EMAIL",
"value": "john@example.com"
}
] | test/jsk/data/user_test.clj | e85th/jsk | 0 | (ns jsk.data.user-test
(:require [clojure.test :refer :all]
;[jsk.core-test :as test]
[taoensso.timbre :as log]
[datomic.api :as d]
[jsk.data.user :as user]
[e85th.commons.datomic :as datomic]
[e85th.commons.util :as u]))
;(use-fixtures :once test/with-system)
(def uri "datomic:mem://scheduler-test")
(defn create-empty-in-memory-db
([]
(create-empty-in-memory-db (load-file "resources/schema.edn")))
([schema]
(d/delete-database uri)
(d/create-database uri)
(let [cn (d/connect uri)]
@(d/transact cn schema)
cn)))
(deftest find-user-test
(let [cn (create-empty-in-memory-db)
res {:db {:cn cn}}
channels [{:channel/type :email
:channel/identifier "john@example.com"}]
user {:user/first-name "John"
:user/last-name "Doe"
:user/channels channels
:user/password "foo"}
{:keys [:db/id]} (user/create-new-user res user 1)
found (user/find-user-by-id res id)]
(is (= found
(user/find-user-by-identifier res "john@example.com")))))
;; (def cn (create-empty-in-memory-db))
;; (def res {:db {:cn cn}})
;; (def channels [{:channel/type :email
;; :channel/identifier "john@example.com"}])
;; (def u-entity {:user/first-name "John"
;; :user/last-name "Doe"
;; :user/channels channels
;; :user/password "foo"})
;; (def u (user/create-new-user res u-entity 1))
;; (user/find-user-auth res (:db/id u))
;; (user/find-channel-by-id res 277076930200555),
;; (user/find-channels-by-identifier res "john@example.com")
;;(user/find-user-by-identifier! res "john@example.com")
;;(user/rm-user res (:db/id u) 1)
;; (user/find-channel-by-type res :email "john@example.com")
;; (user/find-user-id-by-identifier res "john@example.com")
;; (def new-c (user/create-channel res {:channel/type :mobile
;; :channel/identifier "+19277249558"} (:db/id u)))
;; new-c
;; (user/update-channel res (:db/id new-c) {:channel/identifier "+12121234567"} 1)
;; (user/remove-channel res (:db/id new-c) 1)
;; (user/filter-existing-identifiers res [
;; {:channel/identifier "john@example.com"}
;; {:channel/identifier "+19177249558"}
;; {:channel/identifier "+12121234567"}
;; ])
| 36724 | (ns jsk.data.user-test
(:require [clojure.test :refer :all]
;[jsk.core-test :as test]
[taoensso.timbre :as log]
[datomic.api :as d]
[jsk.data.user :as user]
[e85th.commons.datomic :as datomic]
[e85th.commons.util :as u]))
;(use-fixtures :once test/with-system)
(def uri "datomic:mem://scheduler-test")
(defn create-empty-in-memory-db
([]
(create-empty-in-memory-db (load-file "resources/schema.edn")))
([schema]
(d/delete-database uri)
(d/create-database uri)
(let [cn (d/connect uri)]
@(d/transact cn schema)
cn)))
(deftest find-user-test
(let [cn (create-empty-in-memory-db)
res {:db {:cn cn}}
channels [{:channel/type :email
:channel/identifier "<EMAIL>"}]
user {:user/first-name "<NAME>"
:user/last-name "<NAME>"
:user/channels channels
:user/password "<PASSWORD>"}
{:keys [:db/id]} (user/create-new-user res user 1)
found (user/find-user-by-id res id)]
(is (= found
(user/find-user-by-identifier res "<EMAIL>")))))
;; (def cn (create-empty-in-memory-db))
;; (def res {:db {:cn cn}})
;; (def channels [{:channel/type :email
;; :channel/identifier "<EMAIL>"}])
;; (def u-entity {:user/first-name "<NAME>"
;; :user/last-name "<NAME>"
;; :user/channels channels
;; :user/password "<PASSWORD>"})
;; (def u (user/create-new-user res u-entity 1))
;; (user/find-user-auth res (:db/id u))
;; (user/find-channel-by-id res 277076930200555),
;; (user/find-channels-by-identifier res "<EMAIL>")
;;(user/find-user-by-identifier! res "<EMAIL>")
;;(user/rm-user res (:db/id u) 1)
;; (user/find-channel-by-type res :email "<EMAIL>")
;; (user/find-user-id-by-identifier res "<EMAIL>")
;; (def new-c (user/create-channel res {:channel/type :mobile
;; :channel/identifier "+19277249558"} (:db/id u)))
;; new-c
;; (user/update-channel res (:db/id new-c) {:channel/identifier "+12121234567"} 1)
;; (user/remove-channel res (:db/id new-c) 1)
;; (user/filter-existing-identifiers res [
;; {:channel/identifier "<EMAIL>"}
;; {:channel/identifier "+19177249558"}
;; {:channel/identifier "+12121234567"}
;; ])
| true | (ns jsk.data.user-test
(:require [clojure.test :refer :all]
;[jsk.core-test :as test]
[taoensso.timbre :as log]
[datomic.api :as d]
[jsk.data.user :as user]
[e85th.commons.datomic :as datomic]
[e85th.commons.util :as u]))
;(use-fixtures :once test/with-system)
(def uri "datomic:mem://scheduler-test")
(defn create-empty-in-memory-db
([]
(create-empty-in-memory-db (load-file "resources/schema.edn")))
([schema]
(d/delete-database uri)
(d/create-database uri)
(let [cn (d/connect uri)]
@(d/transact cn schema)
cn)))
(deftest find-user-test
(let [cn (create-empty-in-memory-db)
res {:db {:cn cn}}
channels [{:channel/type :email
:channel/identifier "PI:EMAIL:<EMAIL>END_PI"}]
user {:user/first-name "PI:NAME:<NAME>END_PI"
:user/last-name "PI:NAME:<NAME>END_PI"
:user/channels channels
:user/password "PI:PASSWORD:<PASSWORD>END_PI"}
{:keys [:db/id]} (user/create-new-user res user 1)
found (user/find-user-by-id res id)]
(is (= found
(user/find-user-by-identifier res "PI:EMAIL:<EMAIL>END_PI")))))
;; (def cn (create-empty-in-memory-db))
;; (def res {:db {:cn cn}})
;; (def channels [{:channel/type :email
;; :channel/identifier "PI:EMAIL:<EMAIL>END_PI"}])
;; (def u-entity {:user/first-name "PI:NAME:<NAME>END_PI"
;; :user/last-name "PI:NAME:<NAME>END_PI"
;; :user/channels channels
;; :user/password "PI:PASSWORD:<PASSWORD>END_PI"})
;; (def u (user/create-new-user res u-entity 1))
;; (user/find-user-auth res (:db/id u))
;; (user/find-channel-by-id res 277076930200555),
;; (user/find-channels-by-identifier res "PI:EMAIL:<EMAIL>END_PI")
;;(user/find-user-by-identifier! res "PI:EMAIL:<EMAIL>END_PI")
;;(user/rm-user res (:db/id u) 1)
;; (user/find-channel-by-type res :email "PI:EMAIL:<EMAIL>END_PI")
;; (user/find-user-id-by-identifier res "PI:EMAIL:<EMAIL>END_PI")
;; (def new-c (user/create-channel res {:channel/type :mobile
;; :channel/identifier "+19277249558"} (:db/id u)))
;; new-c
;; (user/update-channel res (:db/id new-c) {:channel/identifier "+12121234567"} 1)
;; (user/remove-channel res (:db/id new-c) 1)
;; (user/filter-existing-identifiers res [
;; {:channel/identifier "PI:EMAIL:<EMAIL>END_PI"}
;; {:channel/identifier "+19177249558"}
;; {:channel/identifier "+12121234567"}
;; ])
|
[
{
"context": " ;; Code from Pedestal:\n ;; https://github.com/pedestal/pedestal/blob/master/log/src/io/pedestal/log.clj#",
"end": 1245,
"score": 0.9987177848815918,
"start": 1237,
"tag": "USERNAME",
"value": "pedestal"
},
{
"context": "-jdbc-url db-config))\n (.setUsername db-user)\n (.setPassword db-password)\n ",
"end": 2353,
"score": 0.8681014180183411,
"start": 2346,
"tag": "USERNAME",
"value": "db-user"
},
{
"context": ".setUsername db-user)\n (.setPassword db-password)\n (.setSchema db-schema)\n ",
"end": 2395,
"score": 0.9931963086128235,
"start": 2384,
"tag": "PASSWORD",
"value": "db-password"
}
] | src/main/lrsql/system/database.clj | rajkowski/lrsql | 28 | (ns lrsql.system.database
(:require [clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[lrsql.backend.protocol :as bp]
[lrsql.spec.config :as cs]
[lrsql.system.util :as cu :refer [assert-config make-jdbc-url]])
(:import [com.zaxxer.hikari HikariConfig HikariDataSource]
[com.codahale.metrics MetricRegistry]
[com.codahale.metrics.jmx JmxReporter]))
;; Note: there is a hikari-cp wrapper lib for Clojure. However, we skip using
;; this because 1) it uses HikariCP v4 (which is for Java 8, not Java 11+) and
;; 2) it doesn't set several properties that the latest version supports.
(defn- enable-jmx!
[^HikariConfig config]
(let [metric-registry (MetricRegistry.)]
;; Set HikariCP config properties
;; NOTE: we skip setting the healthCheckRegistry since enough info
;; should be already provided by the metrics, and there doesn't seem
;; to be an easy way to call its properties via JMX.
(.setRegisterMbeans config true)
(.setAllowPoolSuspension config true)
(.setMetricRegistry config metric-registry)
;; Add the metric registry to the JMX reporter
;; Code from Pedestal:
;; https://github.com/pedestal/pedestal/blob/master/log/src/io/pedestal/log.clj#L489
(doto (some-> (JmxReporter/forRegistry metric-registry)
(.inDomain "com.zaxxer.hikari.metrics")
(.build))
(.start))))
(defn- make-conn-pool
[;; Backend
backend
;; Config
{{:keys [db-user
db-password
db-schema
db-catalog]
:as db-config}
:database
:keys [pool-auto-commit
pool-keepalive-time
pool-connection-timeout
pool-idle-timeout
pool-validation-timeout
pool-initialization-fail-timeout
pool-max-lifetime
pool-minimum-idle
pool-maximum-size
pool-isolate-internal-queries
pool-leak-detection-threshold
pool-transaction-isolation
pool-enable-jmx
pool-name]
:as conn-config}]
(assert-config ::cs/connection "connection" conn-config)
(let [conf (doto (HikariConfig.)
;; Database properties
(.setJdbcUrl (make-jdbc-url db-config))
(.setUsername db-user)
(.setPassword db-password)
(.setSchema db-schema)
(.setCatalog db-catalog)
;; Connection pool properties
(.setAutoCommit pool-auto-commit)
(.setKeepaliveTime pool-keepalive-time)
(.setConnectionTimeout pool-connection-timeout)
(.setIdleTimeout pool-idle-timeout)
(.setValidationTimeout pool-validation-timeout)
(.setInitializationFailTimeout pool-initialization-fail-timeout)
(.setMaxLifetime pool-max-lifetime)
(.setMinimumIdle pool-minimum-idle)
(.setMaximumPoolSize pool-maximum-size)
(.setIsolateInternalQueries pool-isolate-internal-queries)
(.setLeakDetectionThreshold pool-leak-detection-threshold))]
;; Why is there no conditional doto?
(when pool-name
(.setPoolName conf pool-name))
(when pool-transaction-isolation
(.setTransactionIsolation conf pool-transaction-isolation))
(when-some [init-sql (bp/-conn-init-sql backend)]
(.setConnectionInitSql conf init-sql))
(when pool-enable-jmx
(enable-jmx! conf))
;; Make connection pool/datasource
(HikariDataSource. conf)))
(defrecord Connection [backend conn-pool config]
component/Lifecycle
(start
[conn]
(let [{?conn-pool :conn-pool
{{db-type :db-type} :database :as config} :config}
conn]
(if-not ?conn-pool
(let [conn-pool (make-conn-pool backend config)]
(log/infof "Starting new connection for %s database..." db-type)
(log/debugf "Config: %s" (cu/redact-config-vars config))
(assoc conn :conn-pool conn-pool))
(do
(log/info "Connection already started; do nothing.")
conn))))
(stop
[conn]
(if-some [conn-pool (:conn-pool conn)]
(do
(log/info "Stopping connection...")
(.close ^HikariDataSource conn-pool)
(assoc conn :conn-pool nil))
(do
(log/info "Connection already stopped; do nothing.")
conn))))
| 4489 | (ns lrsql.system.database
(:require [clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[lrsql.backend.protocol :as bp]
[lrsql.spec.config :as cs]
[lrsql.system.util :as cu :refer [assert-config make-jdbc-url]])
(:import [com.zaxxer.hikari HikariConfig HikariDataSource]
[com.codahale.metrics MetricRegistry]
[com.codahale.metrics.jmx JmxReporter]))
;; Note: there is a hikari-cp wrapper lib for Clojure. However, we skip using
;; this because 1) it uses HikariCP v4 (which is for Java 8, not Java 11+) and
;; 2) it doesn't set several properties that the latest version supports.
(defn- enable-jmx!
[^HikariConfig config]
(let [metric-registry (MetricRegistry.)]
;; Set HikariCP config properties
;; NOTE: we skip setting the healthCheckRegistry since enough info
;; should be already provided by the metrics, and there doesn't seem
;; to be an easy way to call its properties via JMX.
(.setRegisterMbeans config true)
(.setAllowPoolSuspension config true)
(.setMetricRegistry config metric-registry)
;; Add the metric registry to the JMX reporter
;; Code from Pedestal:
;; https://github.com/pedestal/pedestal/blob/master/log/src/io/pedestal/log.clj#L489
(doto (some-> (JmxReporter/forRegistry metric-registry)
(.inDomain "com.zaxxer.hikari.metrics")
(.build))
(.start))))
(defn- make-conn-pool
[;; Backend
backend
;; Config
{{:keys [db-user
db-password
db-schema
db-catalog]
:as db-config}
:database
:keys [pool-auto-commit
pool-keepalive-time
pool-connection-timeout
pool-idle-timeout
pool-validation-timeout
pool-initialization-fail-timeout
pool-max-lifetime
pool-minimum-idle
pool-maximum-size
pool-isolate-internal-queries
pool-leak-detection-threshold
pool-transaction-isolation
pool-enable-jmx
pool-name]
:as conn-config}]
(assert-config ::cs/connection "connection" conn-config)
(let [conf (doto (HikariConfig.)
;; Database properties
(.setJdbcUrl (make-jdbc-url db-config))
(.setUsername db-user)
(.setPassword <PASSWORD>)
(.setSchema db-schema)
(.setCatalog db-catalog)
;; Connection pool properties
(.setAutoCommit pool-auto-commit)
(.setKeepaliveTime pool-keepalive-time)
(.setConnectionTimeout pool-connection-timeout)
(.setIdleTimeout pool-idle-timeout)
(.setValidationTimeout pool-validation-timeout)
(.setInitializationFailTimeout pool-initialization-fail-timeout)
(.setMaxLifetime pool-max-lifetime)
(.setMinimumIdle pool-minimum-idle)
(.setMaximumPoolSize pool-maximum-size)
(.setIsolateInternalQueries pool-isolate-internal-queries)
(.setLeakDetectionThreshold pool-leak-detection-threshold))]
;; Why is there no conditional doto?
(when pool-name
(.setPoolName conf pool-name))
(when pool-transaction-isolation
(.setTransactionIsolation conf pool-transaction-isolation))
(when-some [init-sql (bp/-conn-init-sql backend)]
(.setConnectionInitSql conf init-sql))
(when pool-enable-jmx
(enable-jmx! conf))
;; Make connection pool/datasource
(HikariDataSource. conf)))
(defrecord Connection [backend conn-pool config]
component/Lifecycle
(start
[conn]
(let [{?conn-pool :conn-pool
{{db-type :db-type} :database :as config} :config}
conn]
(if-not ?conn-pool
(let [conn-pool (make-conn-pool backend config)]
(log/infof "Starting new connection for %s database..." db-type)
(log/debugf "Config: %s" (cu/redact-config-vars config))
(assoc conn :conn-pool conn-pool))
(do
(log/info "Connection already started; do nothing.")
conn))))
(stop
[conn]
(if-some [conn-pool (:conn-pool conn)]
(do
(log/info "Stopping connection...")
(.close ^HikariDataSource conn-pool)
(assoc conn :conn-pool nil))
(do
(log/info "Connection already stopped; do nothing.")
conn))))
| true | (ns lrsql.system.database
(:require [clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[lrsql.backend.protocol :as bp]
[lrsql.spec.config :as cs]
[lrsql.system.util :as cu :refer [assert-config make-jdbc-url]])
(:import [com.zaxxer.hikari HikariConfig HikariDataSource]
[com.codahale.metrics MetricRegistry]
[com.codahale.metrics.jmx JmxReporter]))
;; Note: there is a hikari-cp wrapper lib for Clojure. However, we skip using
;; this because 1) it uses HikariCP v4 (which is for Java 8, not Java 11+) and
;; 2) it doesn't set several properties that the latest version supports.
(defn- enable-jmx!
[^HikariConfig config]
(let [metric-registry (MetricRegistry.)]
;; Set HikariCP config properties
;; NOTE: we skip setting the healthCheckRegistry since enough info
;; should be already provided by the metrics, and there doesn't seem
;; to be an easy way to call its properties via JMX.
(.setRegisterMbeans config true)
(.setAllowPoolSuspension config true)
(.setMetricRegistry config metric-registry)
;; Add the metric registry to the JMX reporter
;; Code from Pedestal:
;; https://github.com/pedestal/pedestal/blob/master/log/src/io/pedestal/log.clj#L489
(doto (some-> (JmxReporter/forRegistry metric-registry)
(.inDomain "com.zaxxer.hikari.metrics")
(.build))
(.start))))
(defn- make-conn-pool
[;; Backend
backend
;; Config
{{:keys [db-user
db-password
db-schema
db-catalog]
:as db-config}
:database
:keys [pool-auto-commit
pool-keepalive-time
pool-connection-timeout
pool-idle-timeout
pool-validation-timeout
pool-initialization-fail-timeout
pool-max-lifetime
pool-minimum-idle
pool-maximum-size
pool-isolate-internal-queries
pool-leak-detection-threshold
pool-transaction-isolation
pool-enable-jmx
pool-name]
:as conn-config}]
(assert-config ::cs/connection "connection" conn-config)
(let [conf (doto (HikariConfig.)
;; Database properties
(.setJdbcUrl (make-jdbc-url db-config))
(.setUsername db-user)
(.setPassword PI:PASSWORD:<PASSWORD>END_PI)
(.setSchema db-schema)
(.setCatalog db-catalog)
;; Connection pool properties
(.setAutoCommit pool-auto-commit)
(.setKeepaliveTime pool-keepalive-time)
(.setConnectionTimeout pool-connection-timeout)
(.setIdleTimeout pool-idle-timeout)
(.setValidationTimeout pool-validation-timeout)
(.setInitializationFailTimeout pool-initialization-fail-timeout)
(.setMaxLifetime pool-max-lifetime)
(.setMinimumIdle pool-minimum-idle)
(.setMaximumPoolSize pool-maximum-size)
(.setIsolateInternalQueries pool-isolate-internal-queries)
(.setLeakDetectionThreshold pool-leak-detection-threshold))]
;; Why is there no conditional doto?
(when pool-name
(.setPoolName conf pool-name))
(when pool-transaction-isolation
(.setTransactionIsolation conf pool-transaction-isolation))
(when-some [init-sql (bp/-conn-init-sql backend)]
(.setConnectionInitSql conf init-sql))
(when pool-enable-jmx
(enable-jmx! conf))
;; Make connection pool/datasource
(HikariDataSource. conf)))
(defrecord Connection [backend conn-pool config]
component/Lifecycle
(start
[conn]
(let [{?conn-pool :conn-pool
{{db-type :db-type} :database :as config} :config}
conn]
(if-not ?conn-pool
(let [conn-pool (make-conn-pool backend config)]
(log/infof "Starting new connection for %s database..." db-type)
(log/debugf "Config: %s" (cu/redact-config-vars config))
(assoc conn :conn-pool conn-pool))
(do
(log/info "Connection already started; do nothing.")
conn))))
(stop
[conn]
(if-some [conn-pool (:conn-pool conn)]
(do
(log/info "Stopping connection...")
(.close ^HikariDataSource conn-pool)
(assoc conn :conn-pool nil))
(do
(log/info "Connection already stopped; do nothing.")
conn))))
|
[
{
"context": "\n{\"Language\" \"Clojure\"\n \"Version\" 1.10\n \"Author\" \"Rich Hickey\"}\n\n;; Maps have near constant time lookup by key.",
"end": 1660,
"score": 0.9998763799667358,
"start": 1649,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ct.\n\n{:language \"Clojure\"\n :version 1.5\n :author \"Rich Hickey\"}\n\n;; But keys can be of any type\n{1 :number",
"end": 2111,
"score": 0.9998528361320496,
"start": 2100,
"tag": "NAME",
"value": "Rich Hickey"
}
] | src/instructor/01_datastructures.clj | arnaudbos/ratatouille | 0 | (ns instructor.01-datastructures)
;;; Collections: lists, vectors, maps, and sets
;; Clojure provides a rich set of immutable and persistent data structures,
;; which support efficient creation of “modified” versions, by utilizing structural sharing.
;; Don't know what "structural sharing" is? Please ask!
;; Collections are represented by abstractions, and there may be one or more concrete implementations.
;; In particular, since “modification” operations yield new collections,
;; the new collection might not have the same concrete type as the source collection,
;; but will have the same logical (interface) type.
;;; 1. Lists
;; Lists are forms enclosed in parentheses.
()
;; Lists are evaluated as function calls.
(inc 1)
;; Quote yields unevaluated forms.
(quote (1 2))
'(1 2)
;; List is a classic singly linked list data structure. Lisp code itself is made out of lists.
;; Lists support fast append to the beginning and retrieval of the head (first) element.
'(1 2 3)
(list? '(1 2 3))
(first '(1 2 3))
(conj '(1 2) 3)
;;; 2. Vectors
;; Vectors are enclosed in square braces
[1 2 3 4]
;; Vectors have order 1 (O(n)) lookup by index and count.
;; Vectors are used in preference to lists for cases where either could be used.
;; Vectors do not require quoting and are visually distinct.
;; Actually, you will rarely see or use lists.
(vector? [1 2 3])
(nth [1 2 3] 1)
(conj [1 2] 3)
;; Clojure compares by identity and by value. A vector with elements matching a list is equal to it.
(= [1 2 3] '(1 2 3))
;;; 3. Maps
;; A Map is a collection that maps keys to values.
{"Language" "Clojure"
"Version" 1.10
"Author" "Rich Hickey"}
;; Maps have near constant time lookup by key. (If you're wondering what "near constant time" means, just ask :))
;; Maps are tuned to be fast. Maps are an excellent replacement for object fields.
;; Keywords are shorthand identifiers that do not need to be declared. Keywords begin with a colon.
:language
;; Keywords are often used as keys in hashmaps; similar to fields in an object.
{:language "Clojure"
:version 1.5
:author "Rich Hickey"}
;; But keys can be of any type
{1 :number
"1" :string
:a :keyword
[1] :vector
{:a 1} :map}
;; Keywords can be namespaced.
:instructor.01-datastructures/eggplant
;; Double colon is shorthand for a fully qualified keyword in the current namespace.
::eggplant
;;; 4. Sets
;; Sets are collections of unique values.
#{1 2 3}
;; Sets have near constant time membership lookup, with a high branching factor.
;; Collections can be combined and nested
{[1 2] {:name "diamond" :type :treasure}
[3 4] {:name "dragon" :type :monster}}
;; This is a map that has vector coordinates as keys and maps as values.
;; Clojure has a sequence abstraction. Sequences can be lazy.
;; Their values are only created as they are consumed.
;; Lists and sequences are printed the same way.
(seq '(1 2 3))
;; Data structures are functions!
;; Maps, sets, vectors and keywords are functions. They delegate to get.
;; While it is possible to use get to access collections, calling the collection directly is more common.
(get {:a 1 :b 2} :a)
({:a 1 :b 2} :a)
(:a {:a 1 :b 2})
;; This is useful because you don’t need to create a function to call get.
;; It will prove itself useful when we'll see higher order functions.
;; Sets implement get:
(get #{1 2 3} 2)
(#{1 2 3} 2)
(remove #{nil "bad"} [:a nil :b "bad" "good"])
;; And so do vectors:
(get [1 2 3] 0)
([1 2 3] 0)
| 59277 | (ns instructor.01-datastructures)
;;; Collections: lists, vectors, maps, and sets
;; Clojure provides a rich set of immutable and persistent data structures,
;; which support efficient creation of “modified” versions, by utilizing structural sharing.
;; Don't know what "structural sharing" is? Please ask!
;; Collections are represented by abstractions, and there may be one or more concrete implementations.
;; In particular, since “modification” operations yield new collections,
;; the new collection might not have the same concrete type as the source collection,
;; but will have the same logical (interface) type.
;;; 1. Lists
;; Lists are forms enclosed in parentheses.
()
;; Lists are evaluated as function calls.
(inc 1)
;; Quote yields unevaluated forms.
(quote (1 2))
'(1 2)
;; List is a classic singly linked list data structure. Lisp code itself is made out of lists.
;; Lists support fast append to the beginning and retrieval of the head (first) element.
'(1 2 3)
(list? '(1 2 3))
(first '(1 2 3))
(conj '(1 2) 3)
;;; 2. Vectors
;; Vectors are enclosed in square braces
[1 2 3 4]
;; Vectors have order 1 (O(n)) lookup by index and count.
;; Vectors are used in preference to lists for cases where either could be used.
;; Vectors do not require quoting and are visually distinct.
;; Actually, you will rarely see or use lists.
(vector? [1 2 3])
(nth [1 2 3] 1)
(conj [1 2] 3)
;; Clojure compares by identity and by value. A vector with elements matching a list is equal to it.
(= [1 2 3] '(1 2 3))
;;; 3. Maps
;; A Map is a collection that maps keys to values.
{"Language" "Clojure"
"Version" 1.10
"Author" "<NAME>"}
;; Maps have near constant time lookup by key. (If you're wondering what "near constant time" means, just ask :))
;; Maps are tuned to be fast. Maps are an excellent replacement for object fields.
;; Keywords are shorthand identifiers that do not need to be declared. Keywords begin with a colon.
:language
;; Keywords are often used as keys in hashmaps; similar to fields in an object.
{:language "Clojure"
:version 1.5
:author "<NAME>"}
;; But keys can be of any type
{1 :number
"1" :string
:a :keyword
[1] :vector
{:a 1} :map}
;; Keywords can be namespaced.
:instructor.01-datastructures/eggplant
;; Double colon is shorthand for a fully qualified keyword in the current namespace.
::eggplant
;;; 4. Sets
;; Sets are collections of unique values.
#{1 2 3}
;; Sets have near constant time membership lookup, with a high branching factor.
;; Collections can be combined and nested
{[1 2] {:name "diamond" :type :treasure}
[3 4] {:name "dragon" :type :monster}}
;; This is a map that has vector coordinates as keys and maps as values.
;; Clojure has a sequence abstraction. Sequences can be lazy.
;; Their values are only created as they are consumed.
;; Lists and sequences are printed the same way.
(seq '(1 2 3))
;; Data structures are functions!
;; Maps, sets, vectors and keywords are functions. They delegate to get.
;; While it is possible to use get to access collections, calling the collection directly is more common.
(get {:a 1 :b 2} :a)
({:a 1 :b 2} :a)
(:a {:a 1 :b 2})
;; This is useful because you don’t need to create a function to call get.
;; It will prove itself useful when we'll see higher order functions.
;; Sets implement get:
(get #{1 2 3} 2)
(#{1 2 3} 2)
(remove #{nil "bad"} [:a nil :b "bad" "good"])
;; And so do vectors:
(get [1 2 3] 0)
([1 2 3] 0)
| true | (ns instructor.01-datastructures)
;;; Collections: lists, vectors, maps, and sets
;; Clojure provides a rich set of immutable and persistent data structures,
;; which support efficient creation of “modified” versions, by utilizing structural sharing.
;; Don't know what "structural sharing" is? Please ask!
;; Collections are represented by abstractions, and there may be one or more concrete implementations.
;; In particular, since “modification” operations yield new collections,
;; the new collection might not have the same concrete type as the source collection,
;; but will have the same logical (interface) type.
;;; 1. Lists
;; Lists are forms enclosed in parentheses.
()
;; Lists are evaluated as function calls.
(inc 1)
;; Quote yields unevaluated forms.
(quote (1 2))
'(1 2)
;; List is a classic singly linked list data structure. Lisp code itself is made out of lists.
;; Lists support fast append to the beginning and retrieval of the head (first) element.
'(1 2 3)
(list? '(1 2 3))
(first '(1 2 3))
(conj '(1 2) 3)
;;; 2. Vectors
;; Vectors are enclosed in square braces
[1 2 3 4]
;; Vectors have order 1 (O(n)) lookup by index and count.
;; Vectors are used in preference to lists for cases where either could be used.
;; Vectors do not require quoting and are visually distinct.
;; Actually, you will rarely see or use lists.
(vector? [1 2 3])
(nth [1 2 3] 1)
(conj [1 2] 3)
;; Clojure compares by identity and by value. A vector with elements matching a list is equal to it.
(= [1 2 3] '(1 2 3))
;;; 3. Maps
;; A Map is a collection that maps keys to values.
{"Language" "Clojure"
"Version" 1.10
"Author" "PI:NAME:<NAME>END_PI"}
;; Maps have near constant time lookup by key. (If you're wondering what "near constant time" means, just ask :))
;; Maps are tuned to be fast. Maps are an excellent replacement for object fields.
;; Keywords are shorthand identifiers that do not need to be declared. Keywords begin with a colon.
:language
;; Keywords are often used as keys in hashmaps; similar to fields in an object.
{:language "Clojure"
:version 1.5
:author "PI:NAME:<NAME>END_PI"}
;; But keys can be of any type
{1 :number
"1" :string
:a :keyword
[1] :vector
{:a 1} :map}
;; Keywords can be namespaced.
:instructor.01-datastructures/eggplant
;; Double colon is shorthand for a fully qualified keyword in the current namespace.
::eggplant
;;; 4. Sets
;; Sets are collections of unique values.
#{1 2 3}
;; Sets have near constant time membership lookup, with a high branching factor.
;; Collections can be combined and nested
{[1 2] {:name "diamond" :type :treasure}
[3 4] {:name "dragon" :type :monster}}
;; This is a map that has vector coordinates as keys and maps as values.
;; Clojure has a sequence abstraction. Sequences can be lazy.
;; Their values are only created as they are consumed.
;; Lists and sequences are printed the same way.
(seq '(1 2 3))
;; Data structures are functions!
;; Maps, sets, vectors and keywords are functions. They delegate to get.
;; While it is possible to use get to access collections, calling the collection directly is more common.
(get {:a 1 :b 2} :a)
({:a 1 :b 2} :a)
(:a {:a 1 :b 2})
;; This is useful because you don’t need to create a function to call get.
;; It will prove itself useful when we'll see higher order functions.
;; Sets implement get:
(get #{1 2 3} 2)
(#{1 2 3} 2)
(remove #{nil "bad"} [:a nil :b "bad" "good"])
;; And so do vectors:
(get [1 2 3] 0)
([1 2 3] 0)
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998670816421509,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "tice, or any other, from this software.\n\n; Author: Frantisek Sodomka\n\n\n(ns clojure.test-clojure.test-utils)\n\n (defn e",
"end": 491,
"score": 0.9998843669891357,
"start": 474,
"tag": "NAME",
"value": "Frantisek Sodomka"
}
] | ThirdParty/clojure-1.1.0/test/clojure/test_clojure/test_utils.clj | allertonm/Couverjure | 3 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Author: Frantisek Sodomka
(ns clojure.test-clojure.test-utils)
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
;; (defmacro all-are
;; "Test all-with-all.
;; (all-are (= _1 _2)
;; a b c)
;; =>
;; (do
;; (is (= a b))
;; (is (= a c))
;; (is (= b c)))"
;; [expr & args]
;; (concat
;; (list 'clojure.contrib.template/do-template (list 'clojure.test/is expr))
;; (apply concat (combinations args 2)))))
| 46183 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Author: <NAME>
(ns clojure.test-clojure.test-utils)
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
;; (defmacro all-are
;; "Test all-with-all.
;; (all-are (= _1 _2)
;; a b c)
;; =>
;; (do
;; (is (= a b))
;; (is (= a c))
;; (is (= b c)))"
;; [expr & args]
;; (concat
;; (list 'clojure.contrib.template/do-template (list 'clojure.test/is expr))
;; (apply concat (combinations args 2)))))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Author: PI:NAME:<NAME>END_PI
(ns clojure.test-clojure.test-utils)
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
;; (defmacro all-are
;; "Test all-with-all.
;; (all-are (= _1 _2)
;; a b c)
;; =>
;; (do
;; (is (= a b))
;; (is (= a c))
;; (is (= b c)))"
;; [expr & args]
;; (concat
;; (list 'clojure.contrib.template/do-template (list 'clojure.test/is expr))
;; (apply concat (combinations args 2)))))
|
[
{
"context": "l conn/db {:ID @user-id :EMAIL email :PASSWORD (hashers/derive password) :TEMP_TOKEN @temp-token :STATUS_ID status-id})\n ",
"end": 1568,
"score": 0.9979648590087891,
"start": 1545,
"tag": "PASSWORD",
"value": "hashers/derive password"
},
{
"context": "il.UUID/randomUUID) :PHONENUMBER phone :PASSWORD (hashers/derive password) :TEMP_TOKEN @pin-code :STATUS_ID status-id})\n ",
"end": 3025,
"score": 0.9970144033432007,
"start": 3002,
"tag": "PASSWORD",
"value": "hashers/derive password"
}
] | src/stronghand_3e_api/account/register.clj | saingsab/stronghand-3e-api | 0 | (ns stronghand-3e-api.account.register
(:require [aero.core :refer (read-config)]
[ring.util.http-response :refer :all]
[buddy.hashers :as hashers]
[stronghand-3e-api.utils.validate :as validate]
[stronghand-3e-api.utils.mailling :as mailling]
[stronghand-3e-api.utils.writelog :as writelog]
[stronghand-3e-api.utils.genpin :as genpin]
[stronghand-3e-api.utils.sms :as sms]
[clojure.tools.logging :as log]
[stronghand-3e-api.utils.conn :as conn]
[stronghand-3e-api.db.sp-status :as status]
[stronghand-3e-api.db.sp-users :as users]))
(def env (read-config ".config.edn"))
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def status-id
(str (get (status/get-status-by-name conn/db {:STATUS_NAME "inactive"}) :id)))
(def user-id (atom (uuid)))
(def temp-token (atom (uuid)))
(def pin-code (atom (genpin/getpin)))
(defn phone-not-exist?
[phone]
(nil? (users/get-users-by-phone conn/db {:PHONENUMBER phone})))
(defn get-phone-by-id
[id]
(get (users/get-all-users-by-id conn/db {:ID id}) :phonenumber))
(defn email-not-exist?
[email]
(nil? (users/get-users-by-mail conn/db {:EMAIL email})))
(defn account-by-email
[email password]
(if (= (validate/email? email) true)
; True Save it to data base
(if (= (email-not-exist? email) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-mail conn/db {:ID @user-id :EMAIL email :PASSWORD (hashers/derive password) :TEMP_TOKEN @temp-token :STATUS_ID status-id})
; Send email function here
(mailling/send-mail! email
"Activation Required"
(str "Welcome to STRONGHAND3E! <br/> <br/> To complete verification please click the link below <br/> <br/><a href='https://" (str (get env :baseapi)) ".stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' style='padding:10px 28px;background:#0072BC;color:#fff;text-decoration:none' target='_blank' data-saferedirecturl='https://api.stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' >Verify Email</a> <br/> <br/> Best regards, <br/> STRONGHAND 3E Team <br/> https://stronghand3e.com"))
(reset! user-id (uuid))
(reset! temp-token (uuid))
(ok {:message (str "We've sent a message to " email " with a link to activate your account.")})
(catch Exception ex
(log/error ex)))
(ok {:message "Your email account already exists!"}))
; Fale
(ok {:message "Your email doesn't seem right!"})))
(defn account-by-phone
[phone password]
(if (= (validate/phone? phone) true)
; True
(if (= (phone-not-exist? phone) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-phone conn/db {:ID (java.util.UUID/randomUUID) :PHONENUMBER phone :PASSWORD (hashers/derive password) :TEMP_TOKEN @pin-code :STATUS_ID status-id})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message "Successfully registered!"})
(catch Exception ex
(log/error ex)))
(ok {:message "Your phone number already exists!"}))
; Fale
(ok {:message "Your phone number doesn't seem right!"})))
;; ; Account from OAuth ID token
;; (defn invite-phone-number
;; [token phone]
;; (if (= (auth/authorized? token) true)
;; (try
;; (client/post (str (get env :smsendpoint)) {:form-params {:smscontent (str (get-phone-by-id (get (auth/token? token) :_id)) "invited you to join ZEETOMIC https://wallet.zeetomic.com") :phonenumber phone} :content-type :json})
;; (ok {:message "Successfully invited!"})
;; (catch Exception ex
;; (writelog/op-log! (str "ERROR : FN invite-phone-number " (.getMessage ex)))
;; {:error {:message "Something went wrong on our end"}}))
;; (unauthorized {:error {:message "Unauthorized operation not permitted"}})))
(defn resend-code
[phone]
(try
(users/update-temp conn/db {:TEMP_TOKEN @pin-code :PHONENUMBER phone})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message (str "We've sent you an SMS with the code to " phone)})
(catch Exception ex
(writelog/op-log! (str "ERROR : FN resend-code " (.getMessage ex)))
{:error {:message "Something went wrong on our end"}}))) | 39043 | (ns stronghand-3e-api.account.register
(:require [aero.core :refer (read-config)]
[ring.util.http-response :refer :all]
[buddy.hashers :as hashers]
[stronghand-3e-api.utils.validate :as validate]
[stronghand-3e-api.utils.mailling :as mailling]
[stronghand-3e-api.utils.writelog :as writelog]
[stronghand-3e-api.utils.genpin :as genpin]
[stronghand-3e-api.utils.sms :as sms]
[clojure.tools.logging :as log]
[stronghand-3e-api.utils.conn :as conn]
[stronghand-3e-api.db.sp-status :as status]
[stronghand-3e-api.db.sp-users :as users]))
(def env (read-config ".config.edn"))
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def status-id
(str (get (status/get-status-by-name conn/db {:STATUS_NAME "inactive"}) :id)))
(def user-id (atom (uuid)))
(def temp-token (atom (uuid)))
(def pin-code (atom (genpin/getpin)))
(defn phone-not-exist?
[phone]
(nil? (users/get-users-by-phone conn/db {:PHONENUMBER phone})))
(defn get-phone-by-id
[id]
(get (users/get-all-users-by-id conn/db {:ID id}) :phonenumber))
(defn email-not-exist?
[email]
(nil? (users/get-users-by-mail conn/db {:EMAIL email})))
(defn account-by-email
[email password]
(if (= (validate/email? email) true)
; True Save it to data base
(if (= (email-not-exist? email) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-mail conn/db {:ID @user-id :EMAIL email :PASSWORD (<PASSWORD>) :TEMP_TOKEN @temp-token :STATUS_ID status-id})
; Send email function here
(mailling/send-mail! email
"Activation Required"
(str "Welcome to STRONGHAND3E! <br/> <br/> To complete verification please click the link below <br/> <br/><a href='https://" (str (get env :baseapi)) ".stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' style='padding:10px 28px;background:#0072BC;color:#fff;text-decoration:none' target='_blank' data-saferedirecturl='https://api.stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' >Verify Email</a> <br/> <br/> Best regards, <br/> STRONGHAND 3E Team <br/> https://stronghand3e.com"))
(reset! user-id (uuid))
(reset! temp-token (uuid))
(ok {:message (str "We've sent a message to " email " with a link to activate your account.")})
(catch Exception ex
(log/error ex)))
(ok {:message "Your email account already exists!"}))
; Fale
(ok {:message "Your email doesn't seem right!"})))
(defn account-by-phone
[phone password]
(if (= (validate/phone? phone) true)
; True
(if (= (phone-not-exist? phone) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-phone conn/db {:ID (java.util.UUID/randomUUID) :PHONENUMBER phone :PASSWORD (<PASSWORD>) :TEMP_TOKEN @pin-code :STATUS_ID status-id})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message "Successfully registered!"})
(catch Exception ex
(log/error ex)))
(ok {:message "Your phone number already exists!"}))
; Fale
(ok {:message "Your phone number doesn't seem right!"})))
;; ; Account from OAuth ID token
;; (defn invite-phone-number
;; [token phone]
;; (if (= (auth/authorized? token) true)
;; (try
;; (client/post (str (get env :smsendpoint)) {:form-params {:smscontent (str (get-phone-by-id (get (auth/token? token) :_id)) "invited you to join ZEETOMIC https://wallet.zeetomic.com") :phonenumber phone} :content-type :json})
;; (ok {:message "Successfully invited!"})
;; (catch Exception ex
;; (writelog/op-log! (str "ERROR : FN invite-phone-number " (.getMessage ex)))
;; {:error {:message "Something went wrong on our end"}}))
;; (unauthorized {:error {:message "Unauthorized operation not permitted"}})))
(defn resend-code
[phone]
(try
(users/update-temp conn/db {:TEMP_TOKEN @pin-code :PHONENUMBER phone})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message (str "We've sent you an SMS with the code to " phone)})
(catch Exception ex
(writelog/op-log! (str "ERROR : FN resend-code " (.getMessage ex)))
{:error {:message "Something went wrong on our end"}}))) | true | (ns stronghand-3e-api.account.register
(:require [aero.core :refer (read-config)]
[ring.util.http-response :refer :all]
[buddy.hashers :as hashers]
[stronghand-3e-api.utils.validate :as validate]
[stronghand-3e-api.utils.mailling :as mailling]
[stronghand-3e-api.utils.writelog :as writelog]
[stronghand-3e-api.utils.genpin :as genpin]
[stronghand-3e-api.utils.sms :as sms]
[clojure.tools.logging :as log]
[stronghand-3e-api.utils.conn :as conn]
[stronghand-3e-api.db.sp-status :as status]
[stronghand-3e-api.db.sp-users :as users]))
(def env (read-config ".config.edn"))
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def status-id
(str (get (status/get-status-by-name conn/db {:STATUS_NAME "inactive"}) :id)))
(def user-id (atom (uuid)))
(def temp-token (atom (uuid)))
(def pin-code (atom (genpin/getpin)))
(defn phone-not-exist?
[phone]
(nil? (users/get-users-by-phone conn/db {:PHONENUMBER phone})))
(defn get-phone-by-id
[id]
(get (users/get-all-users-by-id conn/db {:ID id}) :phonenumber))
(defn email-not-exist?
[email]
(nil? (users/get-users-by-mail conn/db {:EMAIL email})))
(defn account-by-email
[email password]
(if (= (validate/email? email) true)
; True Save it to data base
(if (= (email-not-exist? email) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-mail conn/db {:ID @user-id :EMAIL email :PASSWORD (PI:PASSWORD:<PASSWORD>END_PI) :TEMP_TOKEN @temp-token :STATUS_ID status-id})
; Send email function here
(mailling/send-mail! email
"Activation Required"
(str "Welcome to STRONGHAND3E! <br/> <br/> To complete verification please click the link below <br/> <br/><a href='https://" (str (get env :baseapi)) ".stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' style='padding:10px 28px;background:#0072BC;color:#fff;text-decoration:none' target='_blank' data-saferedirecturl='https://api.stronghand3e.com/usr/account-confirmation?userid=" @user-id "&verification-code=" @temp-token "' >Verify Email</a> <br/> <br/> Best regards, <br/> STRONGHAND 3E Team <br/> https://stronghand3e.com"))
(reset! user-id (uuid))
(reset! temp-token (uuid))
(ok {:message (str "We've sent a message to " email " with a link to activate your account.")})
(catch Exception ex
(log/error ex)))
(ok {:message "Your email account already exists!"}))
; Fale
(ok {:message "Your email doesn't seem right!"})))
(defn account-by-phone
[phone password]
(if (= (validate/phone? phone) true)
; True
(if (= (phone-not-exist? phone) true)
(try
; SAVE to Database and send welcome message
(users/register-users-by-phone conn/db {:ID (java.util.UUID/randomUUID) :PHONENUMBER phone :PASSWORD (PI:PASSWORD:<PASSWORD>END_PI) :TEMP_TOKEN @pin-code :STATUS_ID status-id})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message "Successfully registered!"})
(catch Exception ex
(log/error ex)))
(ok {:message "Your phone number already exists!"}))
; Fale
(ok {:message "Your phone number doesn't seem right!"})))
;; ; Account from OAuth ID token
;; (defn invite-phone-number
;; [token phone]
;; (if (= (auth/authorized? token) true)
;; (try
;; (client/post (str (get env :smsendpoint)) {:form-params {:smscontent (str (get-phone-by-id (get (auth/token? token) :_id)) "invited you to join ZEETOMIC https://wallet.zeetomic.com") :phonenumber phone} :content-type :json})
;; (ok {:message "Successfully invited!"})
;; (catch Exception ex
;; (writelog/op-log! (str "ERROR : FN invite-phone-number " (.getMessage ex)))
;; {:error {:message "Something went wrong on our end"}}))
;; (unauthorized {:error {:message "Unauthorized operation not permitted"}})))
(defn resend-code
[phone]
(try
(users/update-temp conn/db {:TEMP_TOKEN @pin-code :PHONENUMBER phone})
(sms/send-sms (str "Your STRONGHAND 3E verification code is:" @pin-code) phone)
(reset! pin-code (genpin/getpin))
(ok {:message (str "We've sent you an SMS with the code to " phone)})
(catch Exception ex
(writelog/op-log! (str "ERROR : FN resend-code " (.getMessage ex)))
{:error {:message "Something went wrong on our end"}}))) |
[
{
"context": "wn-test\" schema :facts\n [[:parent :ancestor \"Shmi Skywalker\" :child \"Anakin Skywalker\"]\n [:pare",
"end": 837,
"score": 0.7299403548240662,
"start": 835,
"tag": "NAME",
"value": "mi"
},
{
"context": " [[:parent :ancestor \"Shmi Skywalker\" :child \"Anakin Skywalker\"]\n [:parent :ancestor \"Ruwee Naberr",
"end": 863,
"score": 0.5147989988327026,
"start": 861,
"tag": "NAME",
"value": "in"
},
{
"context": "hild \"Anakin Skywalker\"]\n [:parent :ancestor \"Ruwee Naberrie\" :child \"Padme Amidala\"]\n [:parent :ancestor ",
"end": 915,
"score": 0.9719850420951843,
"start": 901,
"tag": "NAME",
"value": "Ruwee Naberrie"
},
{
"context": "\n [:parent :ancestor \"Ruwee Naberrie\" :child \"Padme Amidala\"]\n [:parent :ancestor \"Jorbal Naberrie\" :chil",
"end": 938,
"score": 0.8863232731819153,
"start": 925,
"tag": "NAME",
"value": "Padme Amidala"
},
{
"context": " :child \"Padme Amidala\"]\n [:parent :ancestor \"Jorbal Naberrie\" :child \"Padme Amidala\"]\n [:parent :ancestor ",
"end": 981,
"score": 0.8329112529754639,
"start": 966,
"tag": "NAME",
"value": "Jorbal Naberrie"
},
{
"context": " [:parent :ancestor \"Jorbal Naberrie\" :child \"Padme Amidala\"]\n [:parent :ancestor \"Cliegg Lars\" :",
"end": 996,
"score": 0.796823263168335,
"start": 994,
"tag": "NAME",
"value": "me"
},
{
"context": " :child \"Ben Skywalker\"]\n [:parent :ancestor \"Mara Jade\" :child \"Ben Skywalker\"]\n [:parent :ancestor ",
"end": 1287,
"score": 0.7417347431182861,
"start": 1278,
"tag": "NAME",
"value": "Mara Jade"
},
{
"context": ":child \"Luke Skywalker\"]\n [:parent :ancestor \"Padme Amidala\" :child \"Luke Skywalker\"]\n [:parent :ancestor",
"end": 1419,
"score": 0.887761116027832,
"start": 1406,
"tag": "NAME",
"value": "Padme Amidala"
},
{
"context": " [:parent :ancestor \"Anakin Skywalker\" :child \"Princess Leia\"]\n [:parent :ancestor \"Padme Amidala\" :child ",
"end": 1510,
"score": 0.7753773927688599,
"start": 1497,
"tag": "NAME",
"value": "Princess Leia"
},
{
"context": " :child \"Princess Leia\"]\n [:parent :ancestor \"Padme Amidala\" :child \"Princess Leia\"]\n [:parent :ancest",
"end": 1548,
"score": 0.7003202438354492,
"start": 1538,
"tag": "NAME",
"value": "Padme Amid"
},
{
"context": " [:parent :ancestor \"Padme Amidala\" :child \"Princess Leia\"]\n [:parent :ancestor \"Bail Organa\" :child ",
"end": 1572,
"score": 0.5723811388015747,
"start": 1565,
"tag": "NAME",
"value": "cess Le"
},
{
"context": "lo\" :child \"Anakin Solo\"]\n\n [:female :person \"Shmi Skywalker\"]\n [:female :person \"Jorbal Naberrie\"]\n [",
"end": 2093,
"score": 0.9996877908706665,
"start": 2079,
"tag": "NAME",
"value": "Shmi Skywalker"
},
{
"context": " :person \"Shmi Skywalker\"]\n [:female :person \"Jorbal Naberrie\"]\n [:female :person \"Beru Lars\"]\n [:femal",
"end": 2134,
"score": 0.9998837113380432,
"start": 2119,
"tag": "NAME",
"value": "Jorbal Naberrie"
},
{
"context": ":person \"Jorbal Naberrie\"]\n [:female :person \"Beru Lars\"]\n [:female :person \"Mara Jade\"]\n [:femal",
"end": 2169,
"score": 0.9998664259910583,
"start": 2160,
"tag": "NAME",
"value": "Beru Lars"
},
{
"context": "emale :person \"Beru Lars\"]\n [:female :person \"Mara Jade\"]\n [:female :person \"Padme Amidala\"]\n [:f",
"end": 2204,
"score": 0.9998597502708435,
"start": 2195,
"tag": "NAME",
"value": "Mara Jade"
},
{
"context": "emale :person \"Mara Jade\"]\n [:female :person \"Padme Amidala\"]\n [:female :person \"Breha Organa\"]\n [:fe",
"end": 2243,
"score": 0.99986732006073,
"start": 2230,
"tag": "NAME",
"value": "Padme Amidala"
},
{
"context": "e :person \"Padme Amidala\"]\n [:female :person \"Breha Organa\"]\n [:female :person \"Princess Leia\"]\n [:f",
"end": 2281,
"score": 0.9997872114181519,
"start": 2269,
"tag": "NAME",
"value": "Breha Organa"
},
{
"context": "le :person \"Breha Organa\"]\n [:female :person \"Princess Leia\"]\n [:female :person \"Jaina Solo\"]\n\n [:mal",
"end": 2320,
"score": 0.9997844696044922,
"start": 2307,
"tag": "NAME",
"value": "Princess Leia"
},
{
"context": "e :person \"Princess Leia\"]\n [:female :person \"Jaina Solo\"]\n\n [:male :person \"Cliegg Lars\"]\n [:male",
"end": 2356,
"score": 0.9873939752578735,
"start": 2346,
"tag": "NAME",
"value": "Jaina Solo"
},
{
"context": "emale :person \"Jaina Solo\"]\n\n [:male :person \"Cliegg Lars\"]\n [:male :person \"Owen Lars\"]\n [:male :p",
"end": 2392,
"score": 0.9997877478599548,
"start": 2381,
"tag": "NAME",
"value": "Cliegg Lars"
},
{
"context": ":male :person \"Cliegg Lars\"]\n [:male :person \"Owen Lars\"]\n [:male :person \"Ruwee Naberrie\"]\n [:ma",
"end": 2425,
"score": 0.999849796295166,
"start": 2416,
"tag": "NAME",
"value": "Owen Lars"
},
{
"context": " [:male :person \"Owen Lars\"]\n [:male :person \"Ruwee Naberrie\"]\n [:male :person \"Anakin Skywalker\"]\n [:",
"end": 2463,
"score": 0.9998870491981506,
"start": 2449,
"tag": "NAME",
"value": "Ruwee Naberrie"
},
{
"context": "le :person \"Ruwee Naberrie\"]\n [:male :person \"Anakin Skywalker\"]\n [:male :person \"Bail Organa\"]\n [:male ",
"end": 2503,
"score": 0.9997321367263794,
"start": 2487,
"tag": "NAME",
"value": "Anakin Skywalker"
},
{
"context": " :person \"Anakin Skywalker\"]\n [:male :person \"Bail Organa\"]\n [:male :person \"Ben Skywalker\"]\n [:mal",
"end": 2538,
"score": 0.9998701214790344,
"start": 2527,
"tag": "NAME",
"value": "Bail Organa"
},
{
"context": ":male :person \"Bail Organa\"]\n [:male :person \"Ben Skywalker\"]\n [:male :person \"Han Solo\"]\n [:male :pe",
"end": 2575,
"score": 0.9998412132263184,
"start": 2562,
"tag": "NAME",
"value": "Ben Skywalker"
},
{
"context": " :person \"Ben Skywalker\"]\n [:male :person \"Han Solo\"]\n [:male :person \"Jacen Solo\"]\n [:male :",
"end": 2607,
"score": 0.7332131862640381,
"start": 2603,
"tag": "NAME",
"value": "Solo"
},
{
"context": " [:male :person \"Han Solo\"]\n [:male :person \"Jacen Solo\"]\n [:male :person \"Anakin Solo\"]]))\n\n;; The r",
"end": 2641,
"score": 0.9845613241195679,
"start": 2631,
"tag": "NAME",
"value": "Jacen Solo"
},
{
"context": "[:male :person \"Jacen Solo\"]\n [:male :person \"Anakin Solo\"]]))\n\n;; The rest is normal bacwn.\n(def rules\n (",
"end": 2676,
"score": 0.9992600679397583,
"start": 2665,
"tag": "NAME",
"value": "Anakin Solo"
},
{
"context": "dfather :gramps ?x :grandchild '??name)))\n\n;; Find Luke's father\n(println (bacwn/run-work-plan wp-1 @test",
"end": 3351,
"score": 0.9981632232666016,
"start": 3347,
"tag": "NAME",
"value": "Luke"
},
{
"context": "ln (bacwn/run-work-plan wp-1 @test-atom {'??name \"Luke Skywalker\"}))\n\n;; Find Luke's mom (step-mom too)\n(println (",
"end": 3431,
"score": 0.9995725750923157,
"start": 3417,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "1 @test-atom {'??name \"Luke Skywalker\"}))\n\n;; Find Luke's mom (step-mom too)\n(println (bacwn/run-work-pla",
"end": 3449,
"score": 0.9967360496520996,
"start": 3445,
"tag": "NAME",
"value": "Luke"
},
{
"context": "ln (bacwn/run-work-plan wp-2 @test-atom {'??name \"Luke Skywalker\"}))\n\n;; FIXME: but there is an error here because",
"end": 3541,
"score": 0.9992988109588623,
"start": 3527,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "but there is an error here because he has none!\n;; Luke has only one grandpa (not an error)\n(println (bac",
"end": 3612,
"score": 0.9984216094017029,
"start": 3608,
"tag": "NAME",
"value": "Luke"
},
{
"context": "ln (bacwn/run-work-plan wp-3 @test-atom {'??name \"Luke Skywalker\"}))\n\n;; another way to do queries, let's find all",
"end": 3719,
"score": 0.9991827607154846,
"start": 3705,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "alker\"]\n [:male :person \"???\"]\n [:male :person \"Chewbacca\"])\n\n;; So now we have unknown fathers in our data",
"end": 4180,
"score": 0.9952195882797241,
"start": 4171,
"tag": "NAME",
"value": "Chewbacca"
},
{
"context": "alker\"]\n [:male :person \"???\"]\n [:male :person \"Chewbacca\"])\n\n;; Double-check that the datums are gone\n(pri",
"end": 4569,
"score": 0.9883972406387329,
"start": 4560,
"tag": "NAME",
"value": "Chewbacca"
},
{
"context": " \"???\"]\n [:male :person \"???\"]\n [:male :person \"Jar Jar Binks\"])\n\n\n;; Try reloading the page and evaluting test",
"end": 4996,
"score": 0.9994130730628967,
"start": 4983,
"tag": "NAME",
"value": "Jar Jar Binks"
}
] | examples/star-wars/bacwn.cljs | greenyouse/multco | 6 | (ns examples.star-wars.bacwn
(:use-macros [fogus.datalog.bacwn.macros :only [<- ?- make-database]])
(:require [fogus.datalog.bacwn :as bacwn]
[fogus.datalog.bacwn.impl.rules :as r]
[multco.core :as m]))
;; Do a bacwn schema like normal.
(def schema
(make-database
(relation :parent [:ancestor :child])
(index :parent :child)
(relation :male [:person])
(index :male :person)
(relation :female [:person])
(index :female :person)))
;; This serves as a default set of datums. Any subsequent additions
;; or retractions will be saved and override this set of datums.
;; This allows a program to store its info persistently!
;; For reference: http://www.chartgeek.com/star-wars-family-tree/
(def test-atom
(m/bacwn-atom "test" "bacwn-test" schema :facts
[[:parent :ancestor "Shmi Skywalker" :child "Anakin Skywalker"]
[:parent :ancestor "Ruwee Naberrie" :child "Padme Amidala"]
[:parent :ancestor "Jorbal Naberrie" :child "Padme Amidala"]
[:parent :ancestor "Cliegg Lars" :child "Owen Lars"]
[:parent :ancestor "Ownen Lars" :child "Luke Skywalker"]
[:parent :ancestor "Beru Lars" :child "Luke Skywalker"]
[:parent :ancestor "Luke Skywalker" :child "Ben Skywalker"]
[:parent :ancestor "Mara Jade" :child "Ben Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "Luke Skywalker"]
[:parent :ancestor "Padme Amidala" :child "Luke Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "Princess Leia"]
[:parent :ancestor "Padme Amidala" :child "Princess Leia"]
[:parent :ancestor "Bail Organa" :child "Princess Leia"]
[:parent :ancestor "Breha Organa" :child "Princess Leia"]
[:parent :ancestor "Princess Leia" :child "Jaina Solo"]
[:parent :ancestor "Princess Leia" :child "Jacen Solo"]
[:parent :ancestor "Princess Leia" :child "Anakin Solo"]
[:parent :ancestor "Han Solo" :child "Jaina Solo"]
[:parent :ancestor "Han Solo" :child "Jacen Solo"]
[:parent :ancestor "Han Solo" :child "Anakin Solo"]
[:female :person "Shmi Skywalker"]
[:female :person "Jorbal Naberrie"]
[:female :person "Beru Lars"]
[:female :person "Mara Jade"]
[:female :person "Padme Amidala"]
[:female :person "Breha Organa"]
[:female :person "Princess Leia"]
[:female :person "Jaina Solo"]
[:male :person "Cliegg Lars"]
[:male :person "Owen Lars"]
[:male :person "Ruwee Naberrie"]
[:male :person "Anakin Skywalker"]
[:male :person "Bail Organa"]
[:male :person "Ben Skywalker"]
[:male :person "Han Solo"]
[:male :person "Jacen Solo"]
[:male :person "Anakin Solo"]]))
;; The rest is normal bacwn.
(def rules
(r/rules-set
(<- (:father :dad ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:male :person ?x))
(<- (:mother :mom ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:female :person ?x))
(<- (:grandpa :gramps ?x :grandchild ?y)
(:parent :ancestor ?z :child ?y)
(:parent :ancestor ?x :child ?z)
(:male :person ?x))))
(def wp-1 (bacwn/build-work-plan rules (?- :father :dad ?x :child '??name)))
(def wp-2 (bacwn/build-work-plan rules (?- :mother :mom ?x :child '??name)))
(def wp-3 (bacwn/build-work-plan rules (?- :grandfather :gramps ?x :grandchild '??name)))
;; Find Luke's father
(println (bacwn/run-work-plan wp-1 @test-atom {'??name "Luke Skywalker"}))
;; Find Luke's mom (step-mom too)
(println (bacwn/run-work-plan wp-2 @test-atom {'??name "Luke Skywalker"}))
;; FIXME: but there is an error here because he has none!
;; Luke has only one grandpa (not an error)
(println (bacwn/run-work-plan wp-3 @test-atom {'??name "Luke Skywalker"}))
;; another way to do queries, let's find all the father-child relations
(println (bacwn/q (?- :father :dad ?x :child ?y)
@test-atom
rules
{}))
;; Now let's add more datums to our database and see how the changes are
;; reflected in the queries
(m/add-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "Chewbacca"])
;; So now we have unknown fathers in our data
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Let's get rid of that and go back to the default
(m/rm-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "Chewbacca"])
;; Double-check that the datums are gone
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; What if we only care about one relationship and want to delete
;; everything else? Just reset the database:
(m/reset-facts! test-atom
[:parent :ancestor "???" :child "Jar Jar Binks"]
[:female :person "???"]
[:male :person "???"]
[:male :person "Jar Jar Binks"])
;; Try reloading the page and evaluting test-atom and the relations above
;; it. Now check to see if the change we made persisted.
;; Is Jar Jar really the only thing we have?
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Yup, Jar Jar is the only thing in there (oh no) and everything worked!
;; If you want to delete this experiment do:
(m/clear! test-atom)
;; and here's how to delete the entire database:
(m/rm-db test-atom)
| 118245 | (ns examples.star-wars.bacwn
(:use-macros [fogus.datalog.bacwn.macros :only [<- ?- make-database]])
(:require [fogus.datalog.bacwn :as bacwn]
[fogus.datalog.bacwn.impl.rules :as r]
[multco.core :as m]))
;; Do a bacwn schema like normal.
(def schema
(make-database
(relation :parent [:ancestor :child])
(index :parent :child)
(relation :male [:person])
(index :male :person)
(relation :female [:person])
(index :female :person)))
;; This serves as a default set of datums. Any subsequent additions
;; or retractions will be saved and override this set of datums.
;; This allows a program to store its info persistently!
;; For reference: http://www.chartgeek.com/star-wars-family-tree/
(def test-atom
(m/bacwn-atom "test" "bacwn-test" schema :facts
[[:parent :ancestor "Sh<NAME> Skywalker" :child "Anak<NAME> Skywalker"]
[:parent :ancestor "<NAME>" :child "<NAME>"]
[:parent :ancestor "<NAME>" :child "Pad<NAME> Amidala"]
[:parent :ancestor "Cliegg Lars" :child "Owen Lars"]
[:parent :ancestor "Ownen Lars" :child "Luke Skywalker"]
[:parent :ancestor "Beru Lars" :child "Luke Skywalker"]
[:parent :ancestor "Luke Skywalker" :child "Ben Skywalker"]
[:parent :ancestor "<NAME>" :child "Ben Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "Luke Skywalker"]
[:parent :ancestor "<NAME>" :child "Luke Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "<NAME>"]
[:parent :ancestor "<NAME>ala" :child "Prin<NAME>ia"]
[:parent :ancestor "Bail Organa" :child "Princess Leia"]
[:parent :ancestor "Breha Organa" :child "Princess Leia"]
[:parent :ancestor "Princess Leia" :child "Jaina Solo"]
[:parent :ancestor "Princess Leia" :child "Jacen Solo"]
[:parent :ancestor "Princess Leia" :child "Anakin Solo"]
[:parent :ancestor "Han Solo" :child "Jaina Solo"]
[:parent :ancestor "Han Solo" :child "Jacen Solo"]
[:parent :ancestor "Han Solo" :child "Anakin Solo"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:female :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]
[:male :person "Han <NAME>"]
[:male :person "<NAME>"]
[:male :person "<NAME>"]]))
;; The rest is normal bacwn.
(def rules
(r/rules-set
(<- (:father :dad ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:male :person ?x))
(<- (:mother :mom ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:female :person ?x))
(<- (:grandpa :gramps ?x :grandchild ?y)
(:parent :ancestor ?z :child ?y)
(:parent :ancestor ?x :child ?z)
(:male :person ?x))))
(def wp-1 (bacwn/build-work-plan rules (?- :father :dad ?x :child '??name)))
(def wp-2 (bacwn/build-work-plan rules (?- :mother :mom ?x :child '??name)))
(def wp-3 (bacwn/build-work-plan rules (?- :grandfather :gramps ?x :grandchild '??name)))
;; Find <NAME>'s father
(println (bacwn/run-work-plan wp-1 @test-atom {'??name "<NAME>"}))
;; Find <NAME>'s mom (step-mom too)
(println (bacwn/run-work-plan wp-2 @test-atom {'??name "<NAME>"}))
;; FIXME: but there is an error here because he has none!
;; <NAME> has only one grandpa (not an error)
(println (bacwn/run-work-plan wp-3 @test-atom {'??name "<NAME>"}))
;; another way to do queries, let's find all the father-child relations
(println (bacwn/q (?- :father :dad ?x :child ?y)
@test-atom
rules
{}))
;; Now let's add more datums to our database and see how the changes are
;; reflected in the queries
(m/add-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "<NAME>"])
;; So now we have unknown fathers in our data
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Let's get rid of that and go back to the default
(m/rm-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "<NAME>"])
;; Double-check that the datums are gone
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; What if we only care about one relationship and want to delete
;; everything else? Just reset the database:
(m/reset-facts! test-atom
[:parent :ancestor "???" :child "Jar Jar Binks"]
[:female :person "???"]
[:male :person "???"]
[:male :person "<NAME>"])
;; Try reloading the page and evaluting test-atom and the relations above
;; it. Now check to see if the change we made persisted.
;; Is Jar Jar really the only thing we have?
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Yup, Jar Jar is the only thing in there (oh no) and everything worked!
;; If you want to delete this experiment do:
(m/clear! test-atom)
;; and here's how to delete the entire database:
(m/rm-db test-atom)
| true | (ns examples.star-wars.bacwn
(:use-macros [fogus.datalog.bacwn.macros :only [<- ?- make-database]])
(:require [fogus.datalog.bacwn :as bacwn]
[fogus.datalog.bacwn.impl.rules :as r]
[multco.core :as m]))
;; Do a bacwn schema like normal.
(def schema
(make-database
(relation :parent [:ancestor :child])
(index :parent :child)
(relation :male [:person])
(index :male :person)
(relation :female [:person])
(index :female :person)))
;; This serves as a default set of datums. Any subsequent additions
;; or retractions will be saved and override this set of datums.
;; This allows a program to store its info persistently!
;; For reference: http://www.chartgeek.com/star-wars-family-tree/
(def test-atom
(m/bacwn-atom "test" "bacwn-test" schema :facts
[[:parent :ancestor "ShPI:NAME:<NAME>END_PI Skywalker" :child "AnakPI:NAME:<NAME>END_PI Skywalker"]
[:parent :ancestor "PI:NAME:<NAME>END_PI" :child "PI:NAME:<NAME>END_PI"]
[:parent :ancestor "PI:NAME:<NAME>END_PI" :child "PadPI:NAME:<NAME>END_PI Amidala"]
[:parent :ancestor "Cliegg Lars" :child "Owen Lars"]
[:parent :ancestor "Ownen Lars" :child "Luke Skywalker"]
[:parent :ancestor "Beru Lars" :child "Luke Skywalker"]
[:parent :ancestor "Luke Skywalker" :child "Ben Skywalker"]
[:parent :ancestor "PI:NAME:<NAME>END_PI" :child "Ben Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "Luke Skywalker"]
[:parent :ancestor "PI:NAME:<NAME>END_PI" :child "Luke Skywalker"]
[:parent :ancestor "Anakin Skywalker" :child "PI:NAME:<NAME>END_PI"]
[:parent :ancestor "PI:NAME:<NAME>END_PIala" :child "PrinPI:NAME:<NAME>END_PIia"]
[:parent :ancestor "Bail Organa" :child "Princess Leia"]
[:parent :ancestor "Breha Organa" :child "Princess Leia"]
[:parent :ancestor "Princess Leia" :child "Jaina Solo"]
[:parent :ancestor "Princess Leia" :child "Jacen Solo"]
[:parent :ancestor "Princess Leia" :child "Anakin Solo"]
[:parent :ancestor "Han Solo" :child "Jaina Solo"]
[:parent :ancestor "Han Solo" :child "Jacen Solo"]
[:parent :ancestor "Han Solo" :child "Anakin Solo"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:female :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "Han PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]
[:male :person "PI:NAME:<NAME>END_PI"]]))
;; The rest is normal bacwn.
(def rules
(r/rules-set
(<- (:father :dad ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:male :person ?x))
(<- (:mother :mom ?x :child ?y)
(:parent :ancestor ?x :child ?y)
(:female :person ?x))
(<- (:grandpa :gramps ?x :grandchild ?y)
(:parent :ancestor ?z :child ?y)
(:parent :ancestor ?x :child ?z)
(:male :person ?x))))
(def wp-1 (bacwn/build-work-plan rules (?- :father :dad ?x :child '??name)))
(def wp-2 (bacwn/build-work-plan rules (?- :mother :mom ?x :child '??name)))
(def wp-3 (bacwn/build-work-plan rules (?- :grandfather :gramps ?x :grandchild '??name)))
;; Find PI:NAME:<NAME>END_PI's father
(println (bacwn/run-work-plan wp-1 @test-atom {'??name "PI:NAME:<NAME>END_PI"}))
;; Find PI:NAME:<NAME>END_PI's mom (step-mom too)
(println (bacwn/run-work-plan wp-2 @test-atom {'??name "PI:NAME:<NAME>END_PI"}))
;; FIXME: but there is an error here because he has none!
;; PI:NAME:<NAME>END_PI has only one grandpa (not an error)
(println (bacwn/run-work-plan wp-3 @test-atom {'??name "PI:NAME:<NAME>END_PI"}))
;; another way to do queries, let's find all the father-child relations
(println (bacwn/q (?- :father :dad ?x :child ?y)
@test-atom
rules
{}))
;; Now let's add more datums to our database and see how the changes are
;; reflected in the queries
(m/add-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "PI:NAME:<NAME>END_PI"])
;; So now we have unknown fathers in our data
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Let's get rid of that and go back to the default
(m/rm-facts! test-atom
[:parent :ancestor "???" :child "Chewbacca"]
[:parent :ancestor "???" :child "Anakin Skywalker"]
[:male :person "???"]
[:male :person "PI:NAME:<NAME>END_PI"])
;; Double-check that the datums are gone
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; What if we only care about one relationship and want to delete
;; everything else? Just reset the database:
(m/reset-facts! test-atom
[:parent :ancestor "???" :child "Jar Jar Binks"]
[:female :person "???"]
[:male :person "???"]
[:male :person "PI:NAME:<NAME>END_PI"])
;; Try reloading the page and evaluting test-atom and the relations above
;; it. Now check to see if the change we made persisted.
;; Is Jar Jar really the only thing we have?
(println (bacwn/q (?- :father :dad "???" :child ?y)
@test-atom
rules
{}))
;; Yup, Jar Jar is the only thing in there (oh no) and everything worked!
;; If you want to delete this experiment do:
(m/clear! test-atom)
;; and here's how to delete the entire database:
(m/rm-db test-atom)
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9997546672821045,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
}
] | plugin/src/leiningen/nvd.clj | plaguna/lein-nvd | 0 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leiningen.nvd
(:require
[clojure.string :as s]
[clojure.data.json :as json]
[leiningen.core.main :as main]
[leiningen.nvd.deps :refer [get-classpath]]
[nvd.task.update-database]
[nvd.task.purge-database]
[nvd.task.check]))
(def temp-file (java.io.File/createTempFile ".lein-nvd_" ".json"))
(defn nvd "
Scans project dependencies, attempting to detect publicly disclosed
vulnerabilities contained within dependent JAR files. It does this by
determining if there is a Common Platform Enumeration (CPE) identifier
for a given dependency. On completion, a summary table is displayed on
the console (showing the status for each dependency), and detailed report
linking to the associated CVE entries.
This task should be invoked with one of three commands:
check - will optionally download the latest database update files,
and then run the analyze and report stages. Typically, if
the database has been updated recently, then the update
stage will be skipped.
purge - will remove the local database files. Subsequently running
the 'check' command will force downloading the files again,
which could take a long time.
update - will attempt to download the latest database updates, and
incorporate them into the local store. Usually not necessary,
as this is incorporated into the 'check' command.
Any text after the command are treated as arguments and are passed directly
directly to the command for further processing.
"
[project command & args]
(let [path (.getAbsolutePath temp-file)
opts (merge
(select-keys project [:name :group :version :nvd])
{:classpath (get-classpath project) :cmd-args args})]
(spit path (json/write-str opts))
(case command
"check" (nvd.task.check/-main path)
"purge" (nvd.task.purge-database/-main path)
"update" (nvd.task.update-database/-main path)
(main/abort "No such command:" command))))
| 103722 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leiningen.nvd
(:require
[clojure.string :as s]
[clojure.data.json :as json]
[leiningen.core.main :as main]
[leiningen.nvd.deps :refer [get-classpath]]
[nvd.task.update-database]
[nvd.task.purge-database]
[nvd.task.check]))
(def temp-file (java.io.File/createTempFile ".lein-nvd_" ".json"))
(defn nvd "
Scans project dependencies, attempting to detect publicly disclosed
vulnerabilities contained within dependent JAR files. It does this by
determining if there is a Common Platform Enumeration (CPE) identifier
for a given dependency. On completion, a summary table is displayed on
the console (showing the status for each dependency), and detailed report
linking to the associated CVE entries.
This task should be invoked with one of three commands:
check - will optionally download the latest database update files,
and then run the analyze and report stages. Typically, if
the database has been updated recently, then the update
stage will be skipped.
purge - will remove the local database files. Subsequently running
the 'check' command will force downloading the files again,
which could take a long time.
update - will attempt to download the latest database updates, and
incorporate them into the local store. Usually not necessary,
as this is incorporated into the 'check' command.
Any text after the command are treated as arguments and are passed directly
directly to the command for further processing.
"
[project command & args]
(let [path (.getAbsolutePath temp-file)
opts (merge
(select-keys project [:name :group :version :nvd])
{:classpath (get-classpath project) :cmd-args args})]
(spit path (json/write-str opts))
(case command
"check" (nvd.task.check/-main path)
"purge" (nvd.task.purge-database/-main path)
"update" (nvd.task.update-database/-main path)
(main/abort "No such command:" command))))
| true | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leiningen.nvd
(:require
[clojure.string :as s]
[clojure.data.json :as json]
[leiningen.core.main :as main]
[leiningen.nvd.deps :refer [get-classpath]]
[nvd.task.update-database]
[nvd.task.purge-database]
[nvd.task.check]))
(def temp-file (java.io.File/createTempFile ".lein-nvd_" ".json"))
(defn nvd "
Scans project dependencies, attempting to detect publicly disclosed
vulnerabilities contained within dependent JAR files. It does this by
determining if there is a Common Platform Enumeration (CPE) identifier
for a given dependency. On completion, a summary table is displayed on
the console (showing the status for each dependency), and detailed report
linking to the associated CVE entries.
This task should be invoked with one of three commands:
check - will optionally download the latest database update files,
and then run the analyze and report stages. Typically, if
the database has been updated recently, then the update
stage will be skipped.
purge - will remove the local database files. Subsequently running
the 'check' command will force downloading the files again,
which could take a long time.
update - will attempt to download the latest database updates, and
incorporate them into the local store. Usually not necessary,
as this is incorporated into the 'check' command.
Any text after the command are treated as arguments and are passed directly
directly to the command for further processing.
"
[project command & args]
(let [path (.getAbsolutePath temp-file)
opts (merge
(select-keys project [:name :group :version :nvd])
{:classpath (get-classpath project) :cmd-args args})]
(spit path (json/write-str opts))
(case command
"check" (nvd.task.check/-main path)
"purge" (nvd.task.purge-database/-main path)
"update" (nvd.task.update-database/-main path)
(main/abort "No such command:" command))))
|
[
{
"context": "Tab \"/secret/hbase.keytab\"\n :principal \"user@HBASE.EXAMPLE.COM\"\n :context \"Client\"))))\n",
"end": 3283,
"score": 0.9999161958694458,
"start": 3261,
"tag": "EMAIL",
"value": "user@HBASE.EXAMPLE.COM"
}
] | test/hbase_region_inspector/config_test.clj | htross/hbase-region-inspector | 115 | (ns hbase-region-inspector.config-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.io :refer [resource file]]
[hbase-region-inspector.config :refer :all :as c]))
(deftest test-kerberos?
(is (= false (#'c/kerberos? {})))
(is (= false (#'c/kerberos? {"hbase.security.authentication" "simple"})))
(is (= false (#'c/kerberos? {"hadoop.security.authentication" "SIMPLE"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "kerberos"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "kerberos"}))))
(deftest test-require-key
(is (= "bar" (#'c/require-key {"foo" "bar"} "foo")))
(is (thrown? IllegalArgumentException
(#'c/require-key {"foo" "bar"} "foobar"))))
(deftest test-parse-pair
(is (= {:foo "bar" :hello "hello world" :baz true :foobar false}
(#'c/parse-pairs
"foo=bar hello=\"hello world\" baz=true foobar=false"))))
(deftest test-parse-config-file
(testing "Insecure"
(let [file (-> "insecure.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys]} config]
(is (= false krb?))
(is (empty? sys))
(are [key val] (= val (hbase key))
"hbase.zookeeper.quorum" "zookeeper.example.com"
"hbase.zookeeper.property.clientPort" "2181")))
(testing "Ticket cache"
(let [file (-> "ticket-cache.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(are [key val] (= val (config key))
:context "KrbClient"
:useTicketCache true)
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "ticket-cache-jaas.conf"))
;; Path untouched
(is (= "/etc/krb5.conf" (sys "java.security.krb5.conf")))))
(testing "Keytab"
(let [file (-> "keytab.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(is (= #{"foo"
"hello"
"hbase.security.authentication"
"hadoop.security.authentication"} (set (keys hbase))))
(is (= #{"java.security.auth.login.config"
"java.extra.system.property"} (set (keys sys))))
(are [key val] (= val (hbase key))
"foo" "bar"
"hello" "world"
"hbase.security.authentication" "kerberos"
"hadoop.security.authentication" "kerberos")
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "keytab-jaas.conf"))
;; Path untouched
(is (= "keytab-jaas.conf" (sys "java.extra.system.property")))
(are [key val] (= val (config key))
:useTicketCache false
:useKeyTab true
:keyTab "/secret/hbase.keytab"
:principal "user@HBASE.EXAMPLE.COM"
:context "Client"))))
| 75062 | (ns hbase-region-inspector.config-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.io :refer [resource file]]
[hbase-region-inspector.config :refer :all :as c]))
(deftest test-kerberos?
(is (= false (#'c/kerberos? {})))
(is (= false (#'c/kerberos? {"hbase.security.authentication" "simple"})))
(is (= false (#'c/kerberos? {"hadoop.security.authentication" "SIMPLE"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "kerberos"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "kerberos"}))))
(deftest test-require-key
(is (= "bar" (#'c/require-key {"foo" "bar"} "foo")))
(is (thrown? IllegalArgumentException
(#'c/require-key {"foo" "bar"} "foobar"))))
(deftest test-parse-pair
(is (= {:foo "bar" :hello "hello world" :baz true :foobar false}
(#'c/parse-pairs
"foo=bar hello=\"hello world\" baz=true foobar=false"))))
(deftest test-parse-config-file
(testing "Insecure"
(let [file (-> "insecure.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys]} config]
(is (= false krb?))
(is (empty? sys))
(are [key val] (= val (hbase key))
"hbase.zookeeper.quorum" "zookeeper.example.com"
"hbase.zookeeper.property.clientPort" "2181")))
(testing "Ticket cache"
(let [file (-> "ticket-cache.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(are [key val] (= val (config key))
:context "KrbClient"
:useTicketCache true)
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "ticket-cache-jaas.conf"))
;; Path untouched
(is (= "/etc/krb5.conf" (sys "java.security.krb5.conf")))))
(testing "Keytab"
(let [file (-> "keytab.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(is (= #{"foo"
"hello"
"hbase.security.authentication"
"hadoop.security.authentication"} (set (keys hbase))))
(is (= #{"java.security.auth.login.config"
"java.extra.system.property"} (set (keys sys))))
(are [key val] (= val (hbase key))
"foo" "bar"
"hello" "world"
"hbase.security.authentication" "kerberos"
"hadoop.security.authentication" "kerberos")
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "keytab-jaas.conf"))
;; Path untouched
(is (= "keytab-jaas.conf" (sys "java.extra.system.property")))
(are [key val] (= val (config key))
:useTicketCache false
:useKeyTab true
:keyTab "/secret/hbase.keytab"
:principal "<EMAIL>"
:context "Client"))))
| true | (ns hbase-region-inspector.config-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.io :refer [resource file]]
[hbase-region-inspector.config :refer :all :as c]))
(deftest test-kerberos?
(is (= false (#'c/kerberos? {})))
(is (= false (#'c/kerberos? {"hbase.security.authentication" "simple"})))
(is (= false (#'c/kerberos? {"hadoop.security.authentication" "SIMPLE"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hbase.security.authentication" "kerberos"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "KERBEROS"})))
(is (= true (#'c/kerberos? {"hadoop.security.authentication" "kerberos"}))))
(deftest test-require-key
(is (= "bar" (#'c/require-key {"foo" "bar"} "foo")))
(is (thrown? IllegalArgumentException
(#'c/require-key {"foo" "bar"} "foobar"))))
(deftest test-parse-pair
(is (= {:foo "bar" :hello "hello world" :baz true :foobar false}
(#'c/parse-pairs
"foo=bar hello=\"hello world\" baz=true foobar=false"))))
(deftest test-parse-config-file
(testing "Insecure"
(let [file (-> "insecure.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys]} config]
(is (= false krb?))
(is (empty? sys))
(are [key val] (= val (hbase key))
"hbase.zookeeper.quorum" "zookeeper.example.com"
"hbase.zookeeper.property.clientPort" "2181")))
(testing "Ticket cache"
(let [file (-> "ticket-cache.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(are [key val] (= val (config key))
:context "KrbClient"
:useTicketCache true)
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "ticket-cache-jaas.conf"))
;; Path untouched
(is (= "/etc/krb5.conf" (sys "java.security.krb5.conf")))))
(testing "Keytab"
(let [file (-> "keytab.properties" resource file)
config (#'c/parse-config-file file)
{:keys [krb? hbase sys context]} config]
(is krb?)
(is (= #{"foo"
"hello"
"hbase.security.authentication"
"hadoop.security.authentication"} (set (keys hbase))))
(is (= #{"java.security.auth.login.config"
"java.extra.system.property"} (set (keys sys))))
(are [key val] (= val (hbase key))
"foo" "bar"
"hello" "world"
"hbase.security.authentication" "kerberos"
"hadoop.security.authentication" "kerberos")
;; Resolved to absolute path
(is (str/starts-with? (sys "java.security.auth.login.config") "/"))
(is (str/ends-with? (sys "java.security.auth.login.config") "keytab-jaas.conf"))
;; Path untouched
(is (= "keytab-jaas.conf" (sys "java.extra.system.property")))
(are [key val] (= val (config key))
:useTicketCache false
:useKeyTab true
:keyTab "/secret/hbase.keytab"
:principal "PI:EMAIL:<EMAIL>END_PI"
:context "Client"))))
|
[
{
"context": ";; Copyright 2017 7bridges s.r.l.\n;;\n;; Licensed under the Apache License, V",
"end": 26,
"score": 0.7470564842224121,
"start": 18,
"tag": "USERNAME",
"value": "7bridges"
},
{
"context": "embedded record. eg:\n\n {:_class \\\"User\\\" :name \\\"Test\\\"}\"\n [r]\n (when (map? r)\n (or (contains? r :",
"end": 2815,
"score": 0.9591223001480103,
"start": 2811,
"tag": "NAME",
"value": "Test"
},
{
"context": " (record-map->structure {:_class \\\"User\\\" :name \\\"Test\\\"} 0) =>\n ({:key-type 7, :field-name :_class, :t",
"end": 14883,
"score": 0.7023026943206787,
"start": 14879,
"tag": "NAME",
"value": "Test"
},
{
"context": ":key-type 7, :field-name :name, :type 7, :value \\\"Test\\\",\n :position [0 0 0 29], :serialized-value [8",
"end": 15079,
"score": 0.5677312612533569,
"start": 15075,
"tag": "NAME",
"value": "Test"
}
] | src/clj_odbp/binary/serialize/types.clj | 7BridgesEu/clj-odbp | 0 | ;; Copyright 2017 7bridges s.r.l.
;;
;; 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 clj-odbp.binary.serialize.types
(:require [clj-odbp.constants :as const]
[clj-odbp.binary.serialize
[int :as i]
[varint :as v]]
[clj-odbp.utils :as u]))
(def orient-types
"Map custom orient types to their respective byte identifier."
{:boolean-type (byte 0) :integer-type (byte 1) :short-type (byte 2)
:long-type (byte 3) :float-type (byte 4) :double-type (byte 5)
:datetime-type (byte 6) :string-type (byte 7) :keyword-type (byte 7)
:binary-type (byte 8) :embedded-record-type (byte 9)
:embedded-list-type (byte 10) :embedded-set-type (byte 11)
:embedded-map-type (byte 12) :link-type (byte 13) :link-list-type (byte 14)
:link-set-type (byte 15) :link-map-type (byte 16) :byte-type (byte 17)
:custom-type (byte 20) :decimal-type (byte 21) :any-type (byte 23)
:nil-type (byte 0) :ridbag-type (byte 22) :ridtree-type (byte 22)})
(defn- bytes-type
"Serialize an array of bytes. `value` must be an array of bytes. eg:
(bytes-type (.getBytes \"test\" \"UTF-8\"))"
[value]
(let [size (count value)
size-varint (v/varint-unsigned size)]
(into size-varint value)))
(defn obinary?
"Check if `v` is an OrientDB binary type."
[v]
(when (map? v)
(contains? v :_obinary)))
(defn oridbag?
"Check if `v` is an OrientDB RidBag embedded type."
[v]
(when (map? v)
(contains? v :_oridbag)))
(defn oridtree?
"Check if `v` is an OrientDB RidBag tree type."
[v]
(when (map? v)
(contains? v :_oridtree)))
(defn link?
"Check if `v` is a valid OrientDB link. e.g.: \"#21:1\""
[v]
(when (string? v)
(re-matches #"#\d+:\d+" v)))
(defn link-list?
"Check if `l` is a valid OrienDB link list. e.g.: [\"#21:1\" \"#21:2\"]"
[l]
(when (sequential? l)
(every? link? l)))
(defn link-set?
"Check if `s` is a valid OrientDB link set. e.g.: #{\"#21:1\" \"#21:2\"}"
[s]
(when (set? s)
(every? link? s)))
(defn link-map?
"Check if `m` is a valid OrientDB link map. e.g.: {\"test\" \"#21:2\"}"
[m]
(when (map? m)
(let [values (vals m)]
(every? link? values))))
(defn embedded-record?
"Check if `r` is a valid OrientDB embedded record. eg:
{:_class \"User\" :name \"Test\"}"
[r]
(when (map? r)
(or (contains? r :_class)
(contains? r "@type")
(contains? r :_version))))
(defn get-type
"Return a keyword the identifies the type of `v.` e.g.
(get-type true) => :boolean-type"
[v]
(cond
(nil? v) :nil-type
(instance? Boolean v) :boolean-type
(instance? Integer v) :integer-type
(instance? Short v) :integer-type
(instance? Long v) :integer-type
(instance? Float v) :float-type
(instance? Double v) :double-type
(instance? Byte v) :byte-type
(instance? java.math.BigDecimal v) :decimal-type
(instance? java.util.Date v) :datetime-type
(keyword? v) :keyword-type
(obinary? v) :binary-type
(oridbag? v) :ridbag-type
(oridtree? v) :ridtree-type
(link? v) :link-type
(string? v) :string-type
(link-list? v) :link-list-type
(link-set? v) :link-set-type
(link-map? v) :link-map-type
(embedded-record? v) :embedded-record-type
(sequential? v) :embedded-list-type
(set? v) :embedded-set-type
(map? v) :embedded-map-type
:else :custom-type))
(defmulti serialize
"Serialize `value` based on its type.
It optionally accepts an `offset` which will be used to calculate the position
of `value` from the beginning of the record."
(fn [value & offset] (get-type value)))
(defmethod serialize :nil-type
([value]
[])
([value offset]
(serialize value)))
(defmethod serialize :boolean-type
([value]
(if value
[(byte 1)]
[(byte 0)]))
([value offset]
(serialize value)))
(defmethod serialize :integer-type
([value]
(v/varint-unsigned value))
([value offset]
(serialize value)))
(defmethod serialize :float-type
([value]
(-> (java.nio.ByteBuffer/allocate 4)
(.putFloat value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :double-type
([value]
(-> (java.nio.ByteBuffer/allocate 8)
(.putDouble value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :byte-type
([value]
[value])
([value offset]
(serialize value)))
(defmethod serialize :decimal-type
([value]
(let [scale (i/int32 (.scale value))
serialized-value (-> value
.unscaledValue
.toByteArray
vec)
value-size (i/int32 (count serialized-value))]
(vec (concat scale value-size serialized-value))))
([value offset]
(serialize value)))
(defmethod serialize :datetime-type
([value]
(serialize (.getTime value)))
([value offset]
(serialize value)))
(defmethod serialize :string-type
([value]
(let [bytes (.getBytes value "UTF-8")]
(bytes-type bytes)))
([value offset]
(serialize value)))
(defmethod serialize :keyword-type
([value]
(serialize (name value)))
([value offset]
(serialize value)))
(defmethod serialize :binary-type
([value]
(bytes-type (get-in value [:_obinary :value])))
([value offset]
(serialize value)))
(defmethod serialize :link-type
([value]
(let [rid (clojure.string/split (subs value 1) #":")
cluster-id (Integer/parseInt (first rid))
record-position (Integer/parseInt (second rid))
cid-varint (v/varint-unsigned cluster-id)
rpos-varint (v/varint-unsigned record-position)]
(vec (concat cid-varint rpos-varint))))
([value offset]
(serialize value)))
(defmethod serialize :link-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :link-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :ridbag-type
([value]
(let [ridbag (:_oridbag value)
config (serialize (byte 1))
bag (:bag ridbag)]
(vec (concat
config
(i/int32 (count bag))
(reduce
(fn [a rid]
(let [[cluster-id record-position] (u/parse-rid rid)]
(concat a
(i/int16 cluster-id)
(i/int64 record-position))))
[]
bag)))))
([value offset]
(serialize value)))
(defmethod serialize :ridtree-type
([value]
(let [ridtree (:_oridtree value)
config (serialize (byte 0))
{filed-id :filed-id page-index :page-index
page-offset :page-offset changes :changes} ridtree]
(vec (concat config
(i/int64 filed-id) (i/int64 page-index)
(i/int32 page-offset) (i/int32 (count changes))
(reduce
(fn [a change]
(let [{cluster-id :cluster-id record-position :record-position
change-type :change-type change-int :change} change]
(concat a
(i/int16 cluster-id)
(i/int64 record-position)
(serialize (byte change-type))
(i/int32 change-int))))
[]
changes)))))
([value offset]
(serialize value)))
(defn serialize-key-value
"Serialize a key-value according to OrientDB specification.
See: http://orientdb.com/docs/last/Record-Schemaless-Binary-Serialization.html#linkmap"
[k v]
(let [key-type [(get orient-types (get-type k))]
key-value (serialize k)
link (serialize v)]
(vec (concat key-type key-value link))))
(defmethod serialize :link-map-type
([value]
(let [size (v/varint-unsigned (count value))
key-values (mapcat (fn [[k v]] (serialize-key-value k v)) value)]
(vec (concat size key-values))))
([value offset]
(serialize value)))
(defn serialize-list-item
"Serialize `value` in a vector of bytes with the byte representing its type
coming first. e.g.:
(serialize-list-item true) => [0 1]"
[value]
(let [t [(get orient-types (get-type value))]
v (serialize value)]
(into t v)))
(defmethod serialize :embedded-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :embedded-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defn get-structure
"Transform the record `record-map` into a custom structure. eg.:
(get-structure {:_class \"User\" :name \"Test\"}) =>
[{:key-type 7, :field-name :_class, :position 0, :type 7, :value \"User\"}
{:key-type 7, :field-name :name, :position 0, :type 7, :value \"Test\"}]"
[record-map]
(reduce
(fn [acc k]
(let [record-map-value (get record-map k)]
(conj acc {:key-type (get orient-types (get-type k))
:field-name k
:position 0
:type (get orient-types (get-type record-map-value))
:value record-map-value})))
[]
(keys record-map)))
(defn header-size
"Calculate the total `headers` size. `fixed-header-int` is needed to
distinguish the calculation of the header size of a record from that of an
embedded map."
[headers fixed-header-int]
(+ 1 ; closing header
(reduce
(fn [acc k]
(+ acc (count (serialize k)) fixed-header-int))
0
headers)))
(defn serialize-structure-values
"Serialize the values inside `structure` according to their type."
[structure]
(map
(fn [s]
(let [v (:value s)]
(assoc s :serialized-value (serialize v))))
structure))
(defn oemap-positions
"Calculate the position of the values in `structure`, offsetting the first
value with `offset.`"
[structure offset]
(let [hsize (header-size
(map :field-name structure) const/fixed-oemap-header-int)]
(reduce
(fn [acc s]
(if (empty? acc)
(conj acc
(assoc s :position (+ offset hsize)))
(conj acc
(assoc s :position
(+ (count (:serialized-value (last acc)))
(:position (last acc)))))))
[]
structure)))
(defn orient-int32
"Convert `value` in an int32. e.g.: (orient-int32 1) => [0 0 0 1]"
[value]
(i/int32 (int value)))
(defn positions->orient-int32
"Convert the positions in `structure` in int32."
[structure]
(map #(update % :position orient-int32) structure))
(defn oemap->structure
"Trasform the embedded map `data-map` into a structure. e.g.:
(oemap->structure {:test 1} 0) =>
({:key-type 7, :field-name :test, :position [0 0 0 12], :type 1, :value 1,
:serialized-value [2]})"
[data-map offset]
(-> (get-structure data-map)
serialize-structure-values
(oemap-positions offset)
positions->orient-int32))
(defn serialize-elements
"Serialize the elements in `header` returning a vector sorted by `key-order`."
[header key-order]
(reduce
(fn [acc hk]
(if (= hk :position)
(conj acc (get header hk))
(let [position (:position header)]
(when-not (= position 0)
(conj acc (serialize (get header hk)))))))
[]
key-order))
(defn serialize-headers
"Serialize the elements in `structure` returning a sequence sorted by
`key-order`."
[structure key-order]
(mapcat
#(serialize-elements % key-order)
structure))
(defn serialize-data
"Retrieve the :serialized-value inside `structure`."
[structure]
(->> structure
(map :serialized-value)))
(defmethod serialize :embedded-map-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
structure (oemap->structure value offset)
key-order [:key-type :field-name :position :type]
serialized-headers (serialize-headers structure key-order)
serialized-data (serialize-data structure)]
(-> (concat size-varint serialized-headers serialized-data)
flatten
vec))))
(defn first-elem
"Determine the structure of the first element of `record-map`."
[record-map offset]
(let [f (first record-map)
k (first f)
v (second f)
hsize (header-size (keys record-map) const/fixed-header-int)
type-v (get-type v)]
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:serialized-value (serialize v (+ 1 offset hsize))
:position (if (= :nil-type type-v)
0
(+ 1 offset hsize))}))
(defn rest-elem
"Determine the structure of all but the first element of `record-map`."
[record-map first-elem]
(reduce
(fn [acc [k v]]
(let [last-elem (last acc)
serialized-elem (:serialized-value last-elem)
size-le (count serialized-elem)
type-v (get-type v)
pos (if (= :nil-type type-v)
0
(+ size-le (:position last-elem)))]
(conj
acc
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:position pos
:serialized-value (serialize v pos)})))
(conj [] first-elem)
(rest record-map)))
(defn record-map->structure
"Transform the record `record-map` into a structure. e.g.:
(record-map->structure {:_class \"User\" :name \"Test\"} 0) =>
({:key-type 7, :field-name :_class, :type 7, :value \"User\",
:serialized-value [8 85 115 101 114], :position [0 0 0 24]}
{:key-type 7, :field-name :name, :type 7, :value \"Test\",
:position [0 0 0 29], :serialized-value [8 84 101 115 116]})"
[record-map offset]
(->> (first-elem record-map offset)
(rest-elem record-map)
positions->orient-int32))
(defn remove-meta-data
"Remove from `v` the entries whose keyword name starts with \"_\"."
[v]
(->> (keys v)
(filter #(clojure.string/starts-with? (name %) "_"))
(apply dissoc v)))
(defmethod serialize :embedded-record-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
class (get value :_class "")
serialized-class (serialize class)
serialized-class-size (count serialized-class)
first-elem-pos (+ offset serialized-class-size)
plain-record (remove-meta-data value)
structure (record-map->structure plain-record first-elem-pos)
key-order [:field-name :position :type]
serialized-headers (serialize-headers structure key-order)
end-headers [(byte 0)]
serialized-data (serialize-data structure)]
(-> (concat const/serialization-version
serialized-class serialized-headers
end-headers serialized-data)
flatten
vec))))
(defmethod serialize :custom-type
[value]
value)
| 21829 | ;; Copyright 2017 7bridges s.r.l.
;;
;; 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 clj-odbp.binary.serialize.types
(:require [clj-odbp.constants :as const]
[clj-odbp.binary.serialize
[int :as i]
[varint :as v]]
[clj-odbp.utils :as u]))
(def orient-types
"Map custom orient types to their respective byte identifier."
{:boolean-type (byte 0) :integer-type (byte 1) :short-type (byte 2)
:long-type (byte 3) :float-type (byte 4) :double-type (byte 5)
:datetime-type (byte 6) :string-type (byte 7) :keyword-type (byte 7)
:binary-type (byte 8) :embedded-record-type (byte 9)
:embedded-list-type (byte 10) :embedded-set-type (byte 11)
:embedded-map-type (byte 12) :link-type (byte 13) :link-list-type (byte 14)
:link-set-type (byte 15) :link-map-type (byte 16) :byte-type (byte 17)
:custom-type (byte 20) :decimal-type (byte 21) :any-type (byte 23)
:nil-type (byte 0) :ridbag-type (byte 22) :ridtree-type (byte 22)})
(defn- bytes-type
"Serialize an array of bytes. `value` must be an array of bytes. eg:
(bytes-type (.getBytes \"test\" \"UTF-8\"))"
[value]
(let [size (count value)
size-varint (v/varint-unsigned size)]
(into size-varint value)))
(defn obinary?
"Check if `v` is an OrientDB binary type."
[v]
(when (map? v)
(contains? v :_obinary)))
(defn oridbag?
"Check if `v` is an OrientDB RidBag embedded type."
[v]
(when (map? v)
(contains? v :_oridbag)))
(defn oridtree?
"Check if `v` is an OrientDB RidBag tree type."
[v]
(when (map? v)
(contains? v :_oridtree)))
(defn link?
"Check if `v` is a valid OrientDB link. e.g.: \"#21:1\""
[v]
(when (string? v)
(re-matches #"#\d+:\d+" v)))
(defn link-list?
"Check if `l` is a valid OrienDB link list. e.g.: [\"#21:1\" \"#21:2\"]"
[l]
(when (sequential? l)
(every? link? l)))
(defn link-set?
"Check if `s` is a valid OrientDB link set. e.g.: #{\"#21:1\" \"#21:2\"}"
[s]
(when (set? s)
(every? link? s)))
(defn link-map?
"Check if `m` is a valid OrientDB link map. e.g.: {\"test\" \"#21:2\"}"
[m]
(when (map? m)
(let [values (vals m)]
(every? link? values))))
(defn embedded-record?
"Check if `r` is a valid OrientDB embedded record. eg:
{:_class \"User\" :name \"<NAME>\"}"
[r]
(when (map? r)
(or (contains? r :_class)
(contains? r "@type")
(contains? r :_version))))
(defn get-type
"Return a keyword the identifies the type of `v.` e.g.
(get-type true) => :boolean-type"
[v]
(cond
(nil? v) :nil-type
(instance? Boolean v) :boolean-type
(instance? Integer v) :integer-type
(instance? Short v) :integer-type
(instance? Long v) :integer-type
(instance? Float v) :float-type
(instance? Double v) :double-type
(instance? Byte v) :byte-type
(instance? java.math.BigDecimal v) :decimal-type
(instance? java.util.Date v) :datetime-type
(keyword? v) :keyword-type
(obinary? v) :binary-type
(oridbag? v) :ridbag-type
(oridtree? v) :ridtree-type
(link? v) :link-type
(string? v) :string-type
(link-list? v) :link-list-type
(link-set? v) :link-set-type
(link-map? v) :link-map-type
(embedded-record? v) :embedded-record-type
(sequential? v) :embedded-list-type
(set? v) :embedded-set-type
(map? v) :embedded-map-type
:else :custom-type))
(defmulti serialize
"Serialize `value` based on its type.
It optionally accepts an `offset` which will be used to calculate the position
of `value` from the beginning of the record."
(fn [value & offset] (get-type value)))
(defmethod serialize :nil-type
([value]
[])
([value offset]
(serialize value)))
(defmethod serialize :boolean-type
([value]
(if value
[(byte 1)]
[(byte 0)]))
([value offset]
(serialize value)))
(defmethod serialize :integer-type
([value]
(v/varint-unsigned value))
([value offset]
(serialize value)))
(defmethod serialize :float-type
([value]
(-> (java.nio.ByteBuffer/allocate 4)
(.putFloat value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :double-type
([value]
(-> (java.nio.ByteBuffer/allocate 8)
(.putDouble value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :byte-type
([value]
[value])
([value offset]
(serialize value)))
(defmethod serialize :decimal-type
([value]
(let [scale (i/int32 (.scale value))
serialized-value (-> value
.unscaledValue
.toByteArray
vec)
value-size (i/int32 (count serialized-value))]
(vec (concat scale value-size serialized-value))))
([value offset]
(serialize value)))
(defmethod serialize :datetime-type
([value]
(serialize (.getTime value)))
([value offset]
(serialize value)))
(defmethod serialize :string-type
([value]
(let [bytes (.getBytes value "UTF-8")]
(bytes-type bytes)))
([value offset]
(serialize value)))
(defmethod serialize :keyword-type
([value]
(serialize (name value)))
([value offset]
(serialize value)))
(defmethod serialize :binary-type
([value]
(bytes-type (get-in value [:_obinary :value])))
([value offset]
(serialize value)))
(defmethod serialize :link-type
([value]
(let [rid (clojure.string/split (subs value 1) #":")
cluster-id (Integer/parseInt (first rid))
record-position (Integer/parseInt (second rid))
cid-varint (v/varint-unsigned cluster-id)
rpos-varint (v/varint-unsigned record-position)]
(vec (concat cid-varint rpos-varint))))
([value offset]
(serialize value)))
(defmethod serialize :link-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :link-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :ridbag-type
([value]
(let [ridbag (:_oridbag value)
config (serialize (byte 1))
bag (:bag ridbag)]
(vec (concat
config
(i/int32 (count bag))
(reduce
(fn [a rid]
(let [[cluster-id record-position] (u/parse-rid rid)]
(concat a
(i/int16 cluster-id)
(i/int64 record-position))))
[]
bag)))))
([value offset]
(serialize value)))
(defmethod serialize :ridtree-type
([value]
(let [ridtree (:_oridtree value)
config (serialize (byte 0))
{filed-id :filed-id page-index :page-index
page-offset :page-offset changes :changes} ridtree]
(vec (concat config
(i/int64 filed-id) (i/int64 page-index)
(i/int32 page-offset) (i/int32 (count changes))
(reduce
(fn [a change]
(let [{cluster-id :cluster-id record-position :record-position
change-type :change-type change-int :change} change]
(concat a
(i/int16 cluster-id)
(i/int64 record-position)
(serialize (byte change-type))
(i/int32 change-int))))
[]
changes)))))
([value offset]
(serialize value)))
(defn serialize-key-value
"Serialize a key-value according to OrientDB specification.
See: http://orientdb.com/docs/last/Record-Schemaless-Binary-Serialization.html#linkmap"
[k v]
(let [key-type [(get orient-types (get-type k))]
key-value (serialize k)
link (serialize v)]
(vec (concat key-type key-value link))))
(defmethod serialize :link-map-type
([value]
(let [size (v/varint-unsigned (count value))
key-values (mapcat (fn [[k v]] (serialize-key-value k v)) value)]
(vec (concat size key-values))))
([value offset]
(serialize value)))
(defn serialize-list-item
"Serialize `value` in a vector of bytes with the byte representing its type
coming first. e.g.:
(serialize-list-item true) => [0 1]"
[value]
(let [t [(get orient-types (get-type value))]
v (serialize value)]
(into t v)))
(defmethod serialize :embedded-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :embedded-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defn get-structure
"Transform the record `record-map` into a custom structure. eg.:
(get-structure {:_class \"User\" :name \"Test\"}) =>
[{:key-type 7, :field-name :_class, :position 0, :type 7, :value \"User\"}
{:key-type 7, :field-name :name, :position 0, :type 7, :value \"Test\"}]"
[record-map]
(reduce
(fn [acc k]
(let [record-map-value (get record-map k)]
(conj acc {:key-type (get orient-types (get-type k))
:field-name k
:position 0
:type (get orient-types (get-type record-map-value))
:value record-map-value})))
[]
(keys record-map)))
(defn header-size
"Calculate the total `headers` size. `fixed-header-int` is needed to
distinguish the calculation of the header size of a record from that of an
embedded map."
[headers fixed-header-int]
(+ 1 ; closing header
(reduce
(fn [acc k]
(+ acc (count (serialize k)) fixed-header-int))
0
headers)))
(defn serialize-structure-values
"Serialize the values inside `structure` according to their type."
[structure]
(map
(fn [s]
(let [v (:value s)]
(assoc s :serialized-value (serialize v))))
structure))
(defn oemap-positions
"Calculate the position of the values in `structure`, offsetting the first
value with `offset.`"
[structure offset]
(let [hsize (header-size
(map :field-name structure) const/fixed-oemap-header-int)]
(reduce
(fn [acc s]
(if (empty? acc)
(conj acc
(assoc s :position (+ offset hsize)))
(conj acc
(assoc s :position
(+ (count (:serialized-value (last acc)))
(:position (last acc)))))))
[]
structure)))
(defn orient-int32
"Convert `value` in an int32. e.g.: (orient-int32 1) => [0 0 0 1]"
[value]
(i/int32 (int value)))
(defn positions->orient-int32
"Convert the positions in `structure` in int32."
[structure]
(map #(update % :position orient-int32) structure))
(defn oemap->structure
"Trasform the embedded map `data-map` into a structure. e.g.:
(oemap->structure {:test 1} 0) =>
({:key-type 7, :field-name :test, :position [0 0 0 12], :type 1, :value 1,
:serialized-value [2]})"
[data-map offset]
(-> (get-structure data-map)
serialize-structure-values
(oemap-positions offset)
positions->orient-int32))
(defn serialize-elements
"Serialize the elements in `header` returning a vector sorted by `key-order`."
[header key-order]
(reduce
(fn [acc hk]
(if (= hk :position)
(conj acc (get header hk))
(let [position (:position header)]
(when-not (= position 0)
(conj acc (serialize (get header hk)))))))
[]
key-order))
(defn serialize-headers
"Serialize the elements in `structure` returning a sequence sorted by
`key-order`."
[structure key-order]
(mapcat
#(serialize-elements % key-order)
structure))
(defn serialize-data
"Retrieve the :serialized-value inside `structure`."
[structure]
(->> structure
(map :serialized-value)))
(defmethod serialize :embedded-map-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
structure (oemap->structure value offset)
key-order [:key-type :field-name :position :type]
serialized-headers (serialize-headers structure key-order)
serialized-data (serialize-data structure)]
(-> (concat size-varint serialized-headers serialized-data)
flatten
vec))))
(defn first-elem
"Determine the structure of the first element of `record-map`."
[record-map offset]
(let [f (first record-map)
k (first f)
v (second f)
hsize (header-size (keys record-map) const/fixed-header-int)
type-v (get-type v)]
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:serialized-value (serialize v (+ 1 offset hsize))
:position (if (= :nil-type type-v)
0
(+ 1 offset hsize))}))
(defn rest-elem
"Determine the structure of all but the first element of `record-map`."
[record-map first-elem]
(reduce
(fn [acc [k v]]
(let [last-elem (last acc)
serialized-elem (:serialized-value last-elem)
size-le (count serialized-elem)
type-v (get-type v)
pos (if (= :nil-type type-v)
0
(+ size-le (:position last-elem)))]
(conj
acc
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:position pos
:serialized-value (serialize v pos)})))
(conj [] first-elem)
(rest record-map)))
(defn record-map->structure
"Transform the record `record-map` into a structure. e.g.:
(record-map->structure {:_class \"User\" :name \"<NAME>\"} 0) =>
({:key-type 7, :field-name :_class, :type 7, :value \"User\",
:serialized-value [8 85 115 101 114], :position [0 0 0 24]}
{:key-type 7, :field-name :name, :type 7, :value \"<NAME>\",
:position [0 0 0 29], :serialized-value [8 84 101 115 116]})"
[record-map offset]
(->> (first-elem record-map offset)
(rest-elem record-map)
positions->orient-int32))
(defn remove-meta-data
"Remove from `v` the entries whose keyword name starts with \"_\"."
[v]
(->> (keys v)
(filter #(clojure.string/starts-with? (name %) "_"))
(apply dissoc v)))
(defmethod serialize :embedded-record-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
class (get value :_class "")
serialized-class (serialize class)
serialized-class-size (count serialized-class)
first-elem-pos (+ offset serialized-class-size)
plain-record (remove-meta-data value)
structure (record-map->structure plain-record first-elem-pos)
key-order [:field-name :position :type]
serialized-headers (serialize-headers structure key-order)
end-headers [(byte 0)]
serialized-data (serialize-data structure)]
(-> (concat const/serialization-version
serialized-class serialized-headers
end-headers serialized-data)
flatten
vec))))
(defmethod serialize :custom-type
[value]
value)
| true | ;; Copyright 2017 7bridges s.r.l.
;;
;; 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 clj-odbp.binary.serialize.types
(:require [clj-odbp.constants :as const]
[clj-odbp.binary.serialize
[int :as i]
[varint :as v]]
[clj-odbp.utils :as u]))
(def orient-types
"Map custom orient types to their respective byte identifier."
{:boolean-type (byte 0) :integer-type (byte 1) :short-type (byte 2)
:long-type (byte 3) :float-type (byte 4) :double-type (byte 5)
:datetime-type (byte 6) :string-type (byte 7) :keyword-type (byte 7)
:binary-type (byte 8) :embedded-record-type (byte 9)
:embedded-list-type (byte 10) :embedded-set-type (byte 11)
:embedded-map-type (byte 12) :link-type (byte 13) :link-list-type (byte 14)
:link-set-type (byte 15) :link-map-type (byte 16) :byte-type (byte 17)
:custom-type (byte 20) :decimal-type (byte 21) :any-type (byte 23)
:nil-type (byte 0) :ridbag-type (byte 22) :ridtree-type (byte 22)})
(defn- bytes-type
"Serialize an array of bytes. `value` must be an array of bytes. eg:
(bytes-type (.getBytes \"test\" \"UTF-8\"))"
[value]
(let [size (count value)
size-varint (v/varint-unsigned size)]
(into size-varint value)))
(defn obinary?
"Check if `v` is an OrientDB binary type."
[v]
(when (map? v)
(contains? v :_obinary)))
(defn oridbag?
"Check if `v` is an OrientDB RidBag embedded type."
[v]
(when (map? v)
(contains? v :_oridbag)))
(defn oridtree?
"Check if `v` is an OrientDB RidBag tree type."
[v]
(when (map? v)
(contains? v :_oridtree)))
(defn link?
"Check if `v` is a valid OrientDB link. e.g.: \"#21:1\""
[v]
(when (string? v)
(re-matches #"#\d+:\d+" v)))
(defn link-list?
"Check if `l` is a valid OrienDB link list. e.g.: [\"#21:1\" \"#21:2\"]"
[l]
(when (sequential? l)
(every? link? l)))
(defn link-set?
"Check if `s` is a valid OrientDB link set. e.g.: #{\"#21:1\" \"#21:2\"}"
[s]
(when (set? s)
(every? link? s)))
(defn link-map?
"Check if `m` is a valid OrientDB link map. e.g.: {\"test\" \"#21:2\"}"
[m]
(when (map? m)
(let [values (vals m)]
(every? link? values))))
(defn embedded-record?
"Check if `r` is a valid OrientDB embedded record. eg:
{:_class \"User\" :name \"PI:NAME:<NAME>END_PI\"}"
[r]
(when (map? r)
(or (contains? r :_class)
(contains? r "@type")
(contains? r :_version))))
(defn get-type
"Return a keyword the identifies the type of `v.` e.g.
(get-type true) => :boolean-type"
[v]
(cond
(nil? v) :nil-type
(instance? Boolean v) :boolean-type
(instance? Integer v) :integer-type
(instance? Short v) :integer-type
(instance? Long v) :integer-type
(instance? Float v) :float-type
(instance? Double v) :double-type
(instance? Byte v) :byte-type
(instance? java.math.BigDecimal v) :decimal-type
(instance? java.util.Date v) :datetime-type
(keyword? v) :keyword-type
(obinary? v) :binary-type
(oridbag? v) :ridbag-type
(oridtree? v) :ridtree-type
(link? v) :link-type
(string? v) :string-type
(link-list? v) :link-list-type
(link-set? v) :link-set-type
(link-map? v) :link-map-type
(embedded-record? v) :embedded-record-type
(sequential? v) :embedded-list-type
(set? v) :embedded-set-type
(map? v) :embedded-map-type
:else :custom-type))
(defmulti serialize
"Serialize `value` based on its type.
It optionally accepts an `offset` which will be used to calculate the position
of `value` from the beginning of the record."
(fn [value & offset] (get-type value)))
(defmethod serialize :nil-type
([value]
[])
([value offset]
(serialize value)))
(defmethod serialize :boolean-type
([value]
(if value
[(byte 1)]
[(byte 0)]))
([value offset]
(serialize value)))
(defmethod serialize :integer-type
([value]
(v/varint-unsigned value))
([value offset]
(serialize value)))
(defmethod serialize :float-type
([value]
(-> (java.nio.ByteBuffer/allocate 4)
(.putFloat value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :double-type
([value]
(-> (java.nio.ByteBuffer/allocate 8)
(.putDouble value)
.array
vec))
([value offset]
(serialize value)))
(defmethod serialize :byte-type
([value]
[value])
([value offset]
(serialize value)))
(defmethod serialize :decimal-type
([value]
(let [scale (i/int32 (.scale value))
serialized-value (-> value
.unscaledValue
.toByteArray
vec)
value-size (i/int32 (count serialized-value))]
(vec (concat scale value-size serialized-value))))
([value offset]
(serialize value)))
(defmethod serialize :datetime-type
([value]
(serialize (.getTime value)))
([value offset]
(serialize value)))
(defmethod serialize :string-type
([value]
(let [bytes (.getBytes value "UTF-8")]
(bytes-type bytes)))
([value offset]
(serialize value)))
(defmethod serialize :keyword-type
([value]
(serialize (name value)))
([value offset]
(serialize value)))
(defmethod serialize :binary-type
([value]
(bytes-type (get-in value [:_obinary :value])))
([value offset]
(serialize value)))
(defmethod serialize :link-type
([value]
(let [rid (clojure.string/split (subs value 1) #":")
cluster-id (Integer/parseInt (first rid))
record-position (Integer/parseInt (second rid))
cid-varint (v/varint-unsigned cluster-id)
rpos-varint (v/varint-unsigned record-position)]
(vec (concat cid-varint rpos-varint))))
([value offset]
(serialize value)))
(defmethod serialize :link-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :link-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (mapcat serialize value)]
(vec (concat size-varint serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :ridbag-type
([value]
(let [ridbag (:_oridbag value)
config (serialize (byte 1))
bag (:bag ridbag)]
(vec (concat
config
(i/int32 (count bag))
(reduce
(fn [a rid]
(let [[cluster-id record-position] (u/parse-rid rid)]
(concat a
(i/int16 cluster-id)
(i/int64 record-position))))
[]
bag)))))
([value offset]
(serialize value)))
(defmethod serialize :ridtree-type
([value]
(let [ridtree (:_oridtree value)
config (serialize (byte 0))
{filed-id :filed-id page-index :page-index
page-offset :page-offset changes :changes} ridtree]
(vec (concat config
(i/int64 filed-id) (i/int64 page-index)
(i/int32 page-offset) (i/int32 (count changes))
(reduce
(fn [a change]
(let [{cluster-id :cluster-id record-position :record-position
change-type :change-type change-int :change} change]
(concat a
(i/int16 cluster-id)
(i/int64 record-position)
(serialize (byte change-type))
(i/int32 change-int))))
[]
changes)))))
([value offset]
(serialize value)))
(defn serialize-key-value
"Serialize a key-value according to OrientDB specification.
See: http://orientdb.com/docs/last/Record-Schemaless-Binary-Serialization.html#linkmap"
[k v]
(let [key-type [(get orient-types (get-type k))]
key-value (serialize k)
link (serialize v)]
(vec (concat key-type key-value link))))
(defmethod serialize :link-map-type
([value]
(let [size (v/varint-unsigned (count value))
key-values (mapcat (fn [[k v]] (serialize-key-value k v)) value)]
(vec (concat size key-values))))
([value offset]
(serialize value)))
(defn serialize-list-item
"Serialize `value` in a vector of bytes with the byte representing its type
coming first. e.g.:
(serialize-list-item true) => [0 1]"
[value]
(let [t [(get orient-types (get-type value))]
v (serialize value)]
(into t v)))
(defmethod serialize :embedded-list-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defmethod serialize :embedded-set-type
([value]
(let [size (count value)
size-varint (v/varint-unsigned size)
serialized-items (vec (apply concat (map serialize-list-item value)))
any [(byte 23)]]
(vec (concat size-varint any serialized-items))))
([value offset]
(serialize value)))
(defn get-structure
"Transform the record `record-map` into a custom structure. eg.:
(get-structure {:_class \"User\" :name \"Test\"}) =>
[{:key-type 7, :field-name :_class, :position 0, :type 7, :value \"User\"}
{:key-type 7, :field-name :name, :position 0, :type 7, :value \"Test\"}]"
[record-map]
(reduce
(fn [acc k]
(let [record-map-value (get record-map k)]
(conj acc {:key-type (get orient-types (get-type k))
:field-name k
:position 0
:type (get orient-types (get-type record-map-value))
:value record-map-value})))
[]
(keys record-map)))
(defn header-size
"Calculate the total `headers` size. `fixed-header-int` is needed to
distinguish the calculation of the header size of a record from that of an
embedded map."
[headers fixed-header-int]
(+ 1 ; closing header
(reduce
(fn [acc k]
(+ acc (count (serialize k)) fixed-header-int))
0
headers)))
(defn serialize-structure-values
"Serialize the values inside `structure` according to their type."
[structure]
(map
(fn [s]
(let [v (:value s)]
(assoc s :serialized-value (serialize v))))
structure))
(defn oemap-positions
"Calculate the position of the values in `structure`, offsetting the first
value with `offset.`"
[structure offset]
(let [hsize (header-size
(map :field-name structure) const/fixed-oemap-header-int)]
(reduce
(fn [acc s]
(if (empty? acc)
(conj acc
(assoc s :position (+ offset hsize)))
(conj acc
(assoc s :position
(+ (count (:serialized-value (last acc)))
(:position (last acc)))))))
[]
structure)))
(defn orient-int32
"Convert `value` in an int32. e.g.: (orient-int32 1) => [0 0 0 1]"
[value]
(i/int32 (int value)))
(defn positions->orient-int32
"Convert the positions in `structure` in int32."
[structure]
(map #(update % :position orient-int32) structure))
(defn oemap->structure
"Trasform the embedded map `data-map` into a structure. e.g.:
(oemap->structure {:test 1} 0) =>
({:key-type 7, :field-name :test, :position [0 0 0 12], :type 1, :value 1,
:serialized-value [2]})"
[data-map offset]
(-> (get-structure data-map)
serialize-structure-values
(oemap-positions offset)
positions->orient-int32))
(defn serialize-elements
"Serialize the elements in `header` returning a vector sorted by `key-order`."
[header key-order]
(reduce
(fn [acc hk]
(if (= hk :position)
(conj acc (get header hk))
(let [position (:position header)]
(when-not (= position 0)
(conj acc (serialize (get header hk)))))))
[]
key-order))
(defn serialize-headers
"Serialize the elements in `structure` returning a sequence sorted by
`key-order`."
[structure key-order]
(mapcat
#(serialize-elements % key-order)
structure))
(defn serialize-data
"Retrieve the :serialized-value inside `structure`."
[structure]
(->> structure
(map :serialized-value)))
(defmethod serialize :embedded-map-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
structure (oemap->structure value offset)
key-order [:key-type :field-name :position :type]
serialized-headers (serialize-headers structure key-order)
serialized-data (serialize-data structure)]
(-> (concat size-varint serialized-headers serialized-data)
flatten
vec))))
(defn first-elem
"Determine the structure of the first element of `record-map`."
[record-map offset]
(let [f (first record-map)
k (first f)
v (second f)
hsize (header-size (keys record-map) const/fixed-header-int)
type-v (get-type v)]
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:serialized-value (serialize v (+ 1 offset hsize))
:position (if (= :nil-type type-v)
0
(+ 1 offset hsize))}))
(defn rest-elem
"Determine the structure of all but the first element of `record-map`."
[record-map first-elem]
(reduce
(fn [acc [k v]]
(let [last-elem (last acc)
serialized-elem (:serialized-value last-elem)
size-le (count serialized-elem)
type-v (get-type v)
pos (if (= :nil-type type-v)
0
(+ size-le (:position last-elem)))]
(conj
acc
{:key-type (get orient-types (get-type k))
:field-name k
:type (get orient-types type-v)
:value v
:position pos
:serialized-value (serialize v pos)})))
(conj [] first-elem)
(rest record-map)))
(defn record-map->structure
"Transform the record `record-map` into a structure. e.g.:
(record-map->structure {:_class \"User\" :name \"PI:NAME:<NAME>END_PI\"} 0) =>
({:key-type 7, :field-name :_class, :type 7, :value \"User\",
:serialized-value [8 85 115 101 114], :position [0 0 0 24]}
{:key-type 7, :field-name :name, :type 7, :value \"PI:NAME:<NAME>END_PI\",
:position [0 0 0 29], :serialized-value [8 84 101 115 116]})"
[record-map offset]
(->> (first-elem record-map offset)
(rest-elem record-map)
positions->orient-int32))
(defn remove-meta-data
"Remove from `v` the entries whose keyword name starts with \"_\"."
[v]
(->> (keys v)
(filter #(clojure.string/starts-with? (name %) "_"))
(apply dissoc v)))
(defmethod serialize :embedded-record-type
([value]
(serialize value 0))
([value offset]
(let [size (count value)
size-varint (v/varint-unsigned size)
class (get value :_class "")
serialized-class (serialize class)
serialized-class-size (count serialized-class)
first-elem-pos (+ offset serialized-class-size)
plain-record (remove-meta-data value)
structure (record-map->structure plain-record first-elem-pos)
key-order [:field-name :position :type]
serialized-headers (serialize-headers structure key-order)
end-headers [(byte 0)]
serialized-data (serialize-data structure)]
(-> (concat const/serialization-version
serialized-class serialized-headers
end-headers serialized-data)
flatten
vec))))
(defmethod serialize :custom-type
[value]
value)
|
[
{
"context": ";; Copyright (c) Metail and Thomas Athorne\n;;\n;; Licensed under the Apa",
"end": 25,
"score": 0.9984632730484009,
"start": 19,
"tag": "NAME",
"value": "Metail"
},
{
"context": ";; Copyright (c) Metail and Thomas Athorne\n;;\n;; Licensed under the Apache License, Versio",
"end": 44,
"score": 0.9998664259910583,
"start": 30,
"tag": "NAME",
"value": "Thomas Athorne"
}
] | src/clj_stan/read_output.clj | thomasathorne/clj-stan | 14 | ;; Copyright (c) Metail and Thomas Athorne
;;
;; 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 clj-stan.read-output
(:require [clojure.string :as str]
[clojure.data.csv :as csv]))
(defn vec-assoc-in
"A version of the `assoc-in` function that defaults to vectors
rather than maps when adding a new integer key:
```(vec-assoc-in {} [:a 0] \"foo\") => {:a [\"foo\"]}```
This is not safe: `(vec-assoc-in {} [:a 1] 2)` produces an index out
of range exception."
[coll [k & ks :as korks] x]
(cond
(nil? coll) (vec-assoc-in [] korks x)
ks (assoc coll k (vec-assoc-in (get coll k) ks x))
:else (assoc coll k x)))
(defn into-maps
"Translates rows with STAN's output key names (eg. `:mu.1.1`,
`:mu.2.3`) into the natural clojure nested vectors."
[rows]
(let [paths (map (comp (fn [[a & rest]]
(into [(keyword a)] (map (comp dec #(Integer/parseInt %)) rest)))
#(str/split % #"\."))
(first rows))]
(into []
(map (fn [row]
(reduce (fn [accum [path v]]
(vec-assoc-in accum path (Double/parseDouble v)))
{}
(map vector paths row))))
(rest rows))))
(defn read-stan-output
"Read a STAN output csv file, return a vector of clojure maps."
[filename]
(into-maps (csv/read-csv
(str/join "\n" (remove #(re-find #"^#" %) (str/split-lines (slurp filename)))))))
| 56097 | ;; Copyright (c) <NAME> and <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 clj-stan.read-output
(:require [clojure.string :as str]
[clojure.data.csv :as csv]))
(defn vec-assoc-in
"A version of the `assoc-in` function that defaults to vectors
rather than maps when adding a new integer key:
```(vec-assoc-in {} [:a 0] \"foo\") => {:a [\"foo\"]}```
This is not safe: `(vec-assoc-in {} [:a 1] 2)` produces an index out
of range exception."
[coll [k & ks :as korks] x]
(cond
(nil? coll) (vec-assoc-in [] korks x)
ks (assoc coll k (vec-assoc-in (get coll k) ks x))
:else (assoc coll k x)))
(defn into-maps
"Translates rows with STAN's output key names (eg. `:mu.1.1`,
`:mu.2.3`) into the natural clojure nested vectors."
[rows]
(let [paths (map (comp (fn [[a & rest]]
(into [(keyword a)] (map (comp dec #(Integer/parseInt %)) rest)))
#(str/split % #"\."))
(first rows))]
(into []
(map (fn [row]
(reduce (fn [accum [path v]]
(vec-assoc-in accum path (Double/parseDouble v)))
{}
(map vector paths row))))
(rest rows))))
(defn read-stan-output
"Read a STAN output csv file, return a vector of clojure maps."
[filename]
(into-maps (csv/read-csv
(str/join "\n" (remove #(re-find #"^#" %) (str/split-lines (slurp filename)))))))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI and 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 clj-stan.read-output
(:require [clojure.string :as str]
[clojure.data.csv :as csv]))
(defn vec-assoc-in
"A version of the `assoc-in` function that defaults to vectors
rather than maps when adding a new integer key:
```(vec-assoc-in {} [:a 0] \"foo\") => {:a [\"foo\"]}```
This is not safe: `(vec-assoc-in {} [:a 1] 2)` produces an index out
of range exception."
[coll [k & ks :as korks] x]
(cond
(nil? coll) (vec-assoc-in [] korks x)
ks (assoc coll k (vec-assoc-in (get coll k) ks x))
:else (assoc coll k x)))
(defn into-maps
"Translates rows with STAN's output key names (eg. `:mu.1.1`,
`:mu.2.3`) into the natural clojure nested vectors."
[rows]
(let [paths (map (comp (fn [[a & rest]]
(into [(keyword a)] (map (comp dec #(Integer/parseInt %)) rest)))
#(str/split % #"\."))
(first rows))]
(into []
(map (fn [row]
(reduce (fn [accum [path v]]
(vec-assoc-in accum path (Double/parseDouble v)))
{}
(map vector paths row))))
(rest rows))))
(defn read-stan-output
"Read a STAN output csv file, return a vector of clojure maps."
[filename]
(into-maps (csv/read-csv
(str/join "\n" (remove #(re-find #"^#" %) (str/split-lines (slurp filename)))))))
|
[
{
"context": "nstrument and studio abstractions.\"\n :author \"Jeff Rose & Sam Aaron\"}\n overtone.studio.core\n (:use [ove",
"end": 87,
"score": 0.9998766183853149,
"start": 78,
"tag": "NAME",
"value": "Jeff Rose"
},
{
"context": "nd studio abstractions.\"\n :author \"Jeff Rose & Sam Aaron\"}\n overtone.studio.core\n (:use [overtone.sc def",
"end": 99,
"score": 0.9998769164085388,
"start": 90,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/studio/core.clj | ABaldwinHunter/overtone | 3,870 | (ns
^{:doc "Higher level instrument and studio abstractions."
:author "Jeff Rose & Sam Aaron"}
overtone.studio.core
(:use [overtone.sc defaults server])
(:require [overtone.config.log :as log]))
(defonce studio* (atom {:synth-group nil
:instruments {}
:instrument-group nil
:master-volume DEFAULT-MASTER-VOLUME
:input-gain DEFAULT-MASTER-GAIN
:bus-mixers {:in []
:out []}
:recorder nil}))
| 117132 | (ns
^{:doc "Higher level instrument and studio abstractions."
:author "<NAME> & <NAME>"}
overtone.studio.core
(:use [overtone.sc defaults server])
(:require [overtone.config.log :as log]))
(defonce studio* (atom {:synth-group nil
:instruments {}
:instrument-group nil
:master-volume DEFAULT-MASTER-VOLUME
:input-gain DEFAULT-MASTER-GAIN
:bus-mixers {:in []
:out []}
:recorder nil}))
| true | (ns
^{:doc "Higher level instrument and studio abstractions."
:author "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"}
overtone.studio.core
(:use [overtone.sc defaults server])
(:require [overtone.config.log :as log]))
(defonce studio* (atom {:synth-group nil
:instruments {}
:instrument-group nil
:master-volume DEFAULT-MASTER-VOLUME
:input-gain DEFAULT-MASTER-GAIN
:bus-mixers {:in []
:out []}
:recorder nil}))
|
[
{
"context": "te used for testing data products\"\n :author \"Herve Schnegg\"}\n\n test-site.core\n\n (:require [io.pedestal.htt",
"end": 82,
"score": 0.9998677372932434,
"start": 69,
"tag": "NAME",
"value": "Herve Schnegg"
}
] | data/test/clojure/aa21ef044eef173e32643879c8568a42403a1c42core.clj | harshp8l/deep-learning-lang-detection | 84 | (ns ^{:doc "Test site used for testing data products"
:author "Herve Schnegg"}
test-site.core
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[hiccup.page :as page]))
(defn test-page [request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (page/html5
[:body
[:div
[:iframe {:src "http://www.google.com"}]]])})
(def routes
(route/expand-routes
#{["/test-page" :get test-page :route-name :test-page]}))
;; Manage dev server
(defonce server (atom nil))
(def service-map
{::http/routes routes
::http/type :jetty
::http/port 8890})
(defn start-dev []
(reset! server
(http/start (http/create-server
(assoc service-map
::http/join? false)))))
(defn stop-dev []
(http/stop @server))
(defn restart []
(stop-dev)
(start-dev))
| 43962 | (ns ^{:doc "Test site used for testing data products"
:author "<NAME>"}
test-site.core
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[hiccup.page :as page]))
(defn test-page [request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (page/html5
[:body
[:div
[:iframe {:src "http://www.google.com"}]]])})
(def routes
(route/expand-routes
#{["/test-page" :get test-page :route-name :test-page]}))
;; Manage dev server
(defonce server (atom nil))
(def service-map
{::http/routes routes
::http/type :jetty
::http/port 8890})
(defn start-dev []
(reset! server
(http/start (http/create-server
(assoc service-map
::http/join? false)))))
(defn stop-dev []
(http/stop @server))
(defn restart []
(stop-dev)
(start-dev))
| true | (ns ^{:doc "Test site used for testing data products"
:author "PI:NAME:<NAME>END_PI"}
test-site.core
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[hiccup.page :as page]))
(defn test-page [request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (page/html5
[:body
[:div
[:iframe {:src "http://www.google.com"}]]])})
(def routes
(route/expand-routes
#{["/test-page" :get test-page :route-name :test-page]}))
;; Manage dev server
(defonce server (atom nil))
(def service-map
{::http/routes routes
::http/type :jetty
::http/port 8890})
(defn start-dev []
(reset! server
(http/start (http/create-server
(assoc service-map
::http/join? false)))))
(defn stop-dev []
(http/stop @server))
(defn restart []
(stop-dev)
(start-dev))
|
[
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.9998824000358582,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 54,
"score": 0.9999317526817322,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | test/datoteka/tests/test_storages.clj | kiramclean/datoteka | 0 | ;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns datoteka.tests.test-storages
(:require [clojure.test :as t]
[datoteka.storages :as st]
[datoteka.storages.local :as local]
[datoteka.storages.misc :as misc]
[cuerdas.core :as str])
(:import java.io.File
org.apache.commons.io.FileUtils))
;; --- Test Fixtures
(defn- clean-temp-directory
[next]
(next)
(let [directory (File. "/tmp/datoteka/")]
(FileUtils/deleteDirectory directory)))
(t/use-fixtures :each clean-temp-directory)
;; --- Tests: FileSystemStorage
(t/deftest test-localfs-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-get-public-url
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
ruri (st/public-url storage rpath)]
(t/is (= (str ruri) "http://localhost:5050/test.txt"))))
(t/deftest test-localfs-store-and-lookup-with-subdirs
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "somepath/test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/somepath/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
;; --- Tests: ScopedPathStorage
(t/deftest test-localfs-scoped-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/some/prefix/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-scoped-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-scoped-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
| 87842 | ;; Copyright (c) 2015-2016 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns datoteka.tests.test-storages
(:require [clojure.test :as t]
[datoteka.storages :as st]
[datoteka.storages.local :as local]
[datoteka.storages.misc :as misc]
[cuerdas.core :as str])
(:import java.io.File
org.apache.commons.io.FileUtils))
;; --- Test Fixtures
(defn- clean-temp-directory
[next]
(next)
(let [directory (File. "/tmp/datoteka/")]
(FileUtils/deleteDirectory directory)))
(t/use-fixtures :each clean-temp-directory)
;; --- Tests: FileSystemStorage
(t/deftest test-localfs-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-get-public-url
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
ruri (st/public-url storage rpath)]
(t/is (= (str ruri) "http://localhost:5050/test.txt"))))
(t/deftest test-localfs-store-and-lookup-with-subdirs
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "somepath/test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/somepath/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
;; --- Tests: ScopedPathStorage
(t/deftest test-localfs-scoped-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/some/prefix/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-scoped-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-scoped-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
| true | ;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns datoteka.tests.test-storages
(:require [clojure.test :as t]
[datoteka.storages :as st]
[datoteka.storages.local :as local]
[datoteka.storages.misc :as misc]
[cuerdas.core :as str])
(:import java.io.File
org.apache.commons.io.FileUtils))
;; --- Test Fixtures
(defn- clean-temp-directory
[next]
(next)
(let [directory (File. "/tmp/datoteka/")]
(FileUtils/deleteDirectory directory)))
(t/use-fixtures :each clean-temp-directory)
;; --- Tests: FileSystemStorage
(t/deftest test-localfs-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-get-public-url
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")
ruri (st/public-url storage rpath)]
(t/is (= (str ruri) "http://localhost:5050/test.txt"))))
(t/deftest test-localfs-store-and-lookup-with-subdirs
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "somepath/test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/somepath/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
;; --- Tests: ScopedPathStorage
(t/deftest test-localfs-scoped-store-and-lookup
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")
fpath @(st/lookup storage rpath)
fdata (slurp fpath)]
(t/is (= (str fpath) "/tmp/datoteka/test/some/prefix/test.txt"))
(t/is (= "my content" fdata))))
(t/deftest test-localfs-scoped-store-and-delete-and-check
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")
rpath @(st/save storage "test.txt" "my content")]
(t/is @(st/delete storage rpath))
(t/is (not @(st/exists? storage rpath)))))
(t/deftest test-localfs-scoped-access-unauthorized-path
(let [storage (local/localfs {:basedir "/tmp/datoteka/test"
:baseuri "http://localhost:5050/"})
storage (misc/scoped storage "some/prefix")]
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "../test.txt")))
(t/is (thrown? java.util.concurrent.ExecutionException
@(st/lookup storage "/test.txt")))))
|
[
{
"context": ":in {:source \"worker\", :data-key \"test\"}, :email \"apple@pair.com\",\n :test \"gt\", :value 23})\n ))\n\n(defn proc",
"end": 8418,
"score": 0.9998974800109863,
"start": 8404,
"tag": "EMAIL",
"value": "apple@pair.com"
}
] | data/test/clojure/51d6320be316f23bdc1ee39be570a8399d14bdd7hive_controller.clj | harshp8l/deep-learning-lang-detection | 84 | (ns hivewing-web.hive-controller
(:require [hivewing-web.session :as session]
[hivewing-web.controller-core :refer :all]
[hivewing-web.paths :as paths]
[hivewing-core.beekeeper :as bk]
[hivewing-core.hive-manager :as hm]
[hivewing-core.hive-logs :as hive-logs]
[hivewing-core.hive-data :as hive-data]
[hivewing-core.hive-data-stages :as hds]
[hivewing-core.worker :as worker]
[hivewing-core.hive :as hive]
[hivewing-core.apiary :as apiary]
[ring.util.response :as r]
[views.hive :as views]
[views.layout :as layout]
))
(comment
(def bk "2599052e-903d-11e4-854c-0242ac110027")
(def hive-uuid "25c56a10-903d-11e4-a644-0242ac110027")
(hive/hive-can-modify? bk hive-uuid )
(hm/hive-managers-managing bk)
)
(defn sub-menu [req current-page can-manage?]
"Determine the submenu listing for the apiary-controller!"
(let [hu (:hive-uuid (:params req))]
[
{:href (paths/hive-path hu)
:active (= current-page :status)
:text "Status"}
{:href (paths/hive-manage-path hu)
:active (= current-page :manage)
:text "Manage"
:disabled (not can-manage?)}
{:href (paths/hive-data-path hu)
:active (= current-page :data)
:text "Data"
:disabled (not can-manage?)}
{:href (paths/hive-processing-path hu)
:active (= current-page :processing)
:text "Processing"
:disabled (not can-manage?)}
]))
(defn back-link [req]
"Determine the breadcrumbs for the apiary controller"
{:href (paths/apiary-path)
:text "Apiary"}
)
(defn status
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
worker-uuids (worker/worker-list hive-uuid :page 1 :per-page 500)
workers (map #(worker/worker-get (:uuid %)) worker-uuids)
system-worker-logs (hive-logs/hive-logs-read hive-uuid :worker-uuid nil :task nil)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/status req hive workers can-manage? system-worker-logs)
:style :default
:sub-menu (sub-menu req :status can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn show-data-values
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid data-name]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-values (hive-data/hive-data-read hive-uuid nil data-name)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/show-data-values req hive data-name data-values)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn data
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-keys (hive-data/hive-data-get-keys hive-uuid)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/data req hive data-keys)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn update-manage
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [hive (hive/hive-get hive-uuid)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
]
(let [new-name (:hive-manage-name (:params req))
new-branch (:hive-manage-image-branch (:params req))
]
(if new-branch (hive/hive-set-image-branch hive-uuid new-branch))
;; Updating to a new name
(if new-name (hive/hive-set-name hive-uuid new-name))
(->
(r/redirect (paths/hive-manage-path hive-uuid))
(assoc :flash "Updated hive")))))))
(defn manage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
]
(render (layout/render req (views/manage req hive)
:style :default
:sub-menu (sub-menu req :manage can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-choose-stage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stage-specs (remove :hidden (map :spec (vals (hds/hive-data-stages-specs))))
]
(render (layout/render req (views/processing-new-choose-stage req hive hive-stage-specs)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec])
]
(render (layout/render req (views/processing-new-stage req hive hive-stage-spec)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn clean-stage-param
[stage-spec [field-name field-val]]
(let [field-spec (get stage-spec field-name)
[field-type field-desc field-details] field-spec ]
(vector
(keyword field-name)
(case field-type
:data-stream (apply hash-map (vals field-val))
:url field-val
:string field-val
:integer field-val
:email field-val
:enum (keyword field-val)))))
(comment
(do
(def hive-uuid "12345678-1234-1234-1234-1234566789012")
(def stage-name "alert-email")
(def hive-stages (hds/hive-data-stages-specs))
(def hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec]))
(def stage-params
{:in {:source "worker", :data-key "test"}, :email "apple@pair.com",
:test "gt", :value 23})
))
(defn processing-create-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec :params])
]
(let [stage-params (:stage (:params req))
clean-stage-params (concat
(list hive-uuid (keyword stage-name))
(apply concat (map #(clean-stage-param hive-stage-spec %) stage-params)))
stage (apply hds/hive-data-stages-create clean-stage-params)
]
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Created processing stage"))))))
(defn processing-delete-stage
[req & args]
(with-required-parameters req [hive-uuid stage-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive-stage (hds/hive-data-stages-get hive-uuid stage-uuid)
]
(hds/hive-data-stages-delete stage-uuid)
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Deleted processing stage")))))
(defn processing
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-index hive-uuid)
]
(render (layout/render req (views/processing req hive hive-stages)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
| 54856 | (ns hivewing-web.hive-controller
(:require [hivewing-web.session :as session]
[hivewing-web.controller-core :refer :all]
[hivewing-web.paths :as paths]
[hivewing-core.beekeeper :as bk]
[hivewing-core.hive-manager :as hm]
[hivewing-core.hive-logs :as hive-logs]
[hivewing-core.hive-data :as hive-data]
[hivewing-core.hive-data-stages :as hds]
[hivewing-core.worker :as worker]
[hivewing-core.hive :as hive]
[hivewing-core.apiary :as apiary]
[ring.util.response :as r]
[views.hive :as views]
[views.layout :as layout]
))
(comment
(def bk "2599052e-903d-11e4-854c-0242ac110027")
(def hive-uuid "25c56a10-903d-11e4-a644-0242ac110027")
(hive/hive-can-modify? bk hive-uuid )
(hm/hive-managers-managing bk)
)
(defn sub-menu [req current-page can-manage?]
"Determine the submenu listing for the apiary-controller!"
(let [hu (:hive-uuid (:params req))]
[
{:href (paths/hive-path hu)
:active (= current-page :status)
:text "Status"}
{:href (paths/hive-manage-path hu)
:active (= current-page :manage)
:text "Manage"
:disabled (not can-manage?)}
{:href (paths/hive-data-path hu)
:active (= current-page :data)
:text "Data"
:disabled (not can-manage?)}
{:href (paths/hive-processing-path hu)
:active (= current-page :processing)
:text "Processing"
:disabled (not can-manage?)}
]))
(defn back-link [req]
"Determine the breadcrumbs for the apiary controller"
{:href (paths/apiary-path)
:text "Apiary"}
)
(defn status
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
worker-uuids (worker/worker-list hive-uuid :page 1 :per-page 500)
workers (map #(worker/worker-get (:uuid %)) worker-uuids)
system-worker-logs (hive-logs/hive-logs-read hive-uuid :worker-uuid nil :task nil)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/status req hive workers can-manage? system-worker-logs)
:style :default
:sub-menu (sub-menu req :status can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn show-data-values
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid data-name]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-values (hive-data/hive-data-read hive-uuid nil data-name)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/show-data-values req hive data-name data-values)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn data
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-keys (hive-data/hive-data-get-keys hive-uuid)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/data req hive data-keys)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn update-manage
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [hive (hive/hive-get hive-uuid)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
]
(let [new-name (:hive-manage-name (:params req))
new-branch (:hive-manage-image-branch (:params req))
]
(if new-branch (hive/hive-set-image-branch hive-uuid new-branch))
;; Updating to a new name
(if new-name (hive/hive-set-name hive-uuid new-name))
(->
(r/redirect (paths/hive-manage-path hive-uuid))
(assoc :flash "Updated hive")))))))
(defn manage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
]
(render (layout/render req (views/manage req hive)
:style :default
:sub-menu (sub-menu req :manage can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-choose-stage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stage-specs (remove :hidden (map :spec (vals (hds/hive-data-stages-specs))))
]
(render (layout/render req (views/processing-new-choose-stage req hive hive-stage-specs)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec])
]
(render (layout/render req (views/processing-new-stage req hive hive-stage-spec)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn clean-stage-param
[stage-spec [field-name field-val]]
(let [field-spec (get stage-spec field-name)
[field-type field-desc field-details] field-spec ]
(vector
(keyword field-name)
(case field-type
:data-stream (apply hash-map (vals field-val))
:url field-val
:string field-val
:integer field-val
:email field-val
:enum (keyword field-val)))))
(comment
(do
(def hive-uuid "12345678-1234-1234-1234-1234566789012")
(def stage-name "alert-email")
(def hive-stages (hds/hive-data-stages-specs))
(def hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec]))
(def stage-params
{:in {:source "worker", :data-key "test"}, :email "<EMAIL>",
:test "gt", :value 23})
))
(defn processing-create-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec :params])
]
(let [stage-params (:stage (:params req))
clean-stage-params (concat
(list hive-uuid (keyword stage-name))
(apply concat (map #(clean-stage-param hive-stage-spec %) stage-params)))
stage (apply hds/hive-data-stages-create clean-stage-params)
]
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Created processing stage"))))))
(defn processing-delete-stage
[req & args]
(with-required-parameters req [hive-uuid stage-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive-stage (hds/hive-data-stages-get hive-uuid stage-uuid)
]
(hds/hive-data-stages-delete stage-uuid)
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Deleted processing stage")))))
(defn processing
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-index hive-uuid)
]
(render (layout/render req (views/processing req hive hive-stages)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
| true | (ns hivewing-web.hive-controller
(:require [hivewing-web.session :as session]
[hivewing-web.controller-core :refer :all]
[hivewing-web.paths :as paths]
[hivewing-core.beekeeper :as bk]
[hivewing-core.hive-manager :as hm]
[hivewing-core.hive-logs :as hive-logs]
[hivewing-core.hive-data :as hive-data]
[hivewing-core.hive-data-stages :as hds]
[hivewing-core.worker :as worker]
[hivewing-core.hive :as hive]
[hivewing-core.apiary :as apiary]
[ring.util.response :as r]
[views.hive :as views]
[views.layout :as layout]
))
(comment
(def bk "2599052e-903d-11e4-854c-0242ac110027")
(def hive-uuid "25c56a10-903d-11e4-a644-0242ac110027")
(hive/hive-can-modify? bk hive-uuid )
(hm/hive-managers-managing bk)
)
(defn sub-menu [req current-page can-manage?]
"Determine the submenu listing for the apiary-controller!"
(let [hu (:hive-uuid (:params req))]
[
{:href (paths/hive-path hu)
:active (= current-page :status)
:text "Status"}
{:href (paths/hive-manage-path hu)
:active (= current-page :manage)
:text "Manage"
:disabled (not can-manage?)}
{:href (paths/hive-data-path hu)
:active (= current-page :data)
:text "Data"
:disabled (not can-manage?)}
{:href (paths/hive-processing-path hu)
:active (= current-page :processing)
:text "Processing"
:disabled (not can-manage?)}
]))
(defn back-link [req]
"Determine the breadcrumbs for the apiary controller"
{:href (paths/apiary-path)
:text "Apiary"}
)
(defn status
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
worker-uuids (worker/worker-list hive-uuid :page 1 :per-page 500)
workers (map #(worker/worker-get (:uuid %)) worker-uuids)
system-worker-logs (hive-logs/hive-logs-read hive-uuid :worker-uuid nil :task nil)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/status req hive workers can-manage? system-worker-logs)
:style :default
:sub-menu (sub-menu req :status can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn show-data-values
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid data-name]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-values (hive-data/hive-data-read hive-uuid nil data-name)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/show-data-values req hive data-name data-values)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn data
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [
hive (hive/hive-get hive-uuid)
access? (hive/hive-can-read? (:uuid bk) hive-uuid)
data-keys (hive-data/hive-data-get-keys hive-uuid)
]
(let [can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)]
(render (layout/render req (views/data req hive data-keys)
:style :default
:sub-menu (sub-menu req :data can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))))
(defn update-manage
[req & args]
(with-beekeeper req bk
(with-required-parameters req [hive-uuid]
(with-preconditions req [hive (hive/hive-get hive-uuid)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
]
(let [new-name (:hive-manage-name (:params req))
new-branch (:hive-manage-image-branch (:params req))
]
(if new-branch (hive/hive-set-image-branch hive-uuid new-branch))
;; Updating to a new name
(if new-name (hive/hive-set-name hive-uuid new-name))
(->
(r/redirect (paths/hive-manage-path hive-uuid))
(assoc :flash "Updated hive")))))))
(defn manage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
]
(render (layout/render req (views/manage req hive)
:style :default
:sub-menu (sub-menu req :manage can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-choose-stage
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stage-specs (remove :hidden (map :spec (vals (hds/hive-data-stages-specs))))
]
(render (layout/render req (views/processing-new-choose-stage req hive hive-stage-specs)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn processing-new-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec])
]
(render (layout/render req (views/processing-new-stage req hive hive-stage-spec)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
(defn clean-stage-param
[stage-spec [field-name field-val]]
(let [field-spec (get stage-spec field-name)
[field-type field-desc field-details] field-spec ]
(vector
(keyword field-name)
(case field-type
:data-stream (apply hash-map (vals field-val))
:url field-val
:string field-val
:integer field-val
:email field-val
:enum (keyword field-val)))))
(comment
(do
(def hive-uuid "12345678-1234-1234-1234-1234566789012")
(def stage-name "alert-email")
(def hive-stages (hds/hive-data-stages-specs))
(def hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec]))
(def stage-params
{:in {:source "worker", :data-key "test"}, :email "PI:EMAIL:<EMAIL>END_PI",
:test "gt", :value 23})
))
(defn processing-create-stage
[req & args]
(with-required-parameters req [hive-uuid stage-name]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-specs)
hive-stage-spec (get-in hive-stages [(keyword stage-name) :spec :params])
]
(let [stage-params (:stage (:params req))
clean-stage-params (concat
(list hive-uuid (keyword stage-name))
(apply concat (map #(clean-stage-param hive-stage-spec %) stage-params)))
stage (apply hds/hive-data-stages-create clean-stage-params)
]
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Created processing stage"))))))
(defn processing-delete-stage
[req & args]
(with-required-parameters req [hive-uuid stage-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive-stage (hds/hive-data-stages-get hive-uuid stage-uuid)
]
(hds/hive-data-stages-delete stage-uuid)
(->
(r/redirect (paths/hive-processing-path hive-uuid))
(assoc :flash "Deleted processing stage")))))
(defn processing
[req & args]
(with-required-parameters req [hive-uuid]
(with-preconditions req [
bk (session/current-user req)
can-manage? (hive/hive-can-modify? (:uuid bk) hive-uuid)
hive (hive/hive-get hive-uuid)
hive-stages (hds/hive-data-stages-index hive-uuid)
]
(render (layout/render req (views/processing req hive hive-stages)
:style :default
:sub-menu (sub-menu req :processing can-manage?)
:current-name (:name hive)
:back-link (back-link req)
:body-class :hive
)))))
|
[
{
"context": "-c/map->Personnel\n {:last-name \"John Smith\"\n :roles [\"pointOfContact\"]})\n",
"end": 16097,
"score": 0.9997783899307251,
"start": 16087,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "-c/map->Personnel\n {:last-name \"SEDAC AC\"\n :roles [\"distributor\"]})]}))",
"end": 16226,
"score": 0.999819278717041,
"start": 16218,
"tag": "NAME",
"value": "SEDAC AC"
}
] | umm-lib/test/cmr/umm/test/iso_mends/iso_mends_collection_tests.clj | eereiter/Common-Metadata-Repository | 0 | (ns cmr.umm.test.iso-mends.iso-mends-collection-tests
"Tests parsing and generating ISO Collection XML."
(:require
[clojure.java.io :as io]
[clojure.string :as s]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :refer [for-all]]
[cmr.common.date-time-parser :as p]
[cmr.common.joda-time]
[cmr.common.test.test-check-ext :refer [defspec checking]]
;; this is not needed until the ECHO to ISO XSLT is fixed
;; [cmr.common.xml.xslt :as xslt]
[cmr.spatial.derived :as d]
[cmr.spatial.encoding.gmd :as gmd]
[cmr.spatial.relations :as r]
[cmr.umm.echo10.collection.personnel :as echo-pe]
[cmr.umm.echo10.echo10-collection :as echo10-c]
[cmr.umm.echo10.echo10-core :as echo10]
[cmr.umm.iso-mends.iso-mends-collection :as c]
[cmr.umm.iso-mends.iso-mends-core :as iso]
[cmr.umm.test.echo10.echo10-collection-tests :as test-echo10]
[cmr.umm.test.generators.collection :as coll-gen]
[cmr.umm.umm-collection :as umm-c]
[cmr.umm.umm-spatial :as umm-s]))
(defn- fix-mbr
"The mbr creation in the functions below sometimes gets a rounding error when using
calculate-derived. This function fixes that since the rounding error occurs
in :center-point."
[mbr]
(cmr.spatial.mbr/mbr
(:west mbr) (:north mbr) (:east mbr) (:south mbr)))
(defmulti create-bounding-box
(fn [geometry]
(type geometry)))
(defmethod create-bounding-box cmr.spatial.mbr.Mbr
[geometry]
geometry)
(defmethod create-bounding-box cmr.spatial.point.Point
[geometry]
(cmr.spatial.mbr/point->mbr geometry))
(defmethod create-bounding-box cmr.spatial.line_string.LineString
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defmethod create-bounding-box cmr.spatial.polygon.Polygon
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defn- add-redundant-bounding-boxes
"ISO generates redundant bounding boxes. We are no longer removing them. In the
expected conversion we need to generate redundant bounding boxes for each geomtry
type."
[spatial-coverage]
(if-let [geometries (:geometries spatial-coverage)]
(assoc spatial-coverage :geometries
(interleave
(map create-bounding-box geometries)
geometries))
spatial-coverage))
(defn- spatial-coverage->expected-parsed
"Returns the expected parsed ISO MENDS SpatialCoverage from a UMM collection."
[{:keys [geometries spatial-representation granule-spatial-representation]}]
(when (or granule-spatial-representation (seq geometries))
(umm-c/map->SpatialCoverage
{:spatial-representation spatial-representation
:granule-spatial-representation (or granule-spatial-representation :no-spatial)
:geometries (seq (map #(umm-s/set-coordinate-system spatial-representation %) geometries))})))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil) related-urls)))
(defn- sensors->expected-parsed
"Return the expected parsed sensors for the given sensors."
[sensors]
(seq (map #(assoc % :technique nil :characteristics nil) sensors)))
(defn- instrument->expected-parsed
"Return the expected parsed instrument for the given instrument."
[instrument]
(-> instrument
;; ISO does not support instrument technique, characteristics or operation modes
(assoc :technique nil :characteristics nil :operation-modes nil)
(update-in [:sensors] sensors->expected-parsed)))
(defn- instruments->expected-parsed
"Return the expected parsed instruments for the given instruments."
[instruments]
(seq (map instrument->expected-parsed instruments)))
(defn- platform->expected-parsed
"Return the expected parsed platform for the given platform."
[platform]
(let [instruments (:instruments platform)]
(-> platform
(assoc :characteristics nil)
(assoc :instruments (instruments->expected-parsed instruments)))))
(defn- platforms->expected-parsed
"Returns the expected parsed platforms for the given platforms."
[platforms]
(seq (map platform->expected-parsed platforms)))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil :mime-type nil) related-urls)))
(defn- collection->personnel
"Creates personnel from the distribution center contacts."
[coll]
(let [distrib-centers (filter #(= :archive-center (:type %)) (:organizations coll))]
(map (fn [distrib-center]
(umm-c/map->Personnel
{:last-name (:org-name distrib-center)
:roles ["distributor"]}))
distrib-centers)))
(defn umm->expected-parsed-iso
"Modifies the UMM record for testing ISO. ISO contains a subset of the total UMM fields so certain
fields are removed for comparison of the parsed record"
[coll]
(let [{:keys [spatial-coverage]} coll
range-date-times (get-in coll [:temporal :range-date-times])
single-date-times (get-in coll [:temporal :single-date-times])
temporal (if (seq range-date-times)
(umm-c/map->Temporal {:range-date-times range-date-times
:single-date-times []
:periodic-date-times []})
(when (seq single-date-times)
(umm-c/map->Temporal {:range-date-times []
:single-date-times single-date-times
:periodic-date-times []})))
revision-date-time (get-in coll [:data-provider-timestamps :revision-date-time])
personnel (not-empty (collection->personnel coll))
organizations (seq (filter #(not (= :distribution-center (:type %))) (:organizations coll)))]
(-> coll
;; ISO does not have version-description
(assoc-in [:product :version-description] nil)
;; ISO does not have collection-data-type
(assoc-in [:product :collection-data-type] nil)
;; There is no delete-time in ISO
(assoc-in [:data-provider-timestamps :delete-time] nil)
;; Revision date time is same as update-time
(assoc-in [:data-provider-timestamps :update-time] revision-date-time)
;; ISO does not have periodic-date-times
(assoc :temporal temporal)
;; ISO does not support mime-type in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not have distribution centers as Organization
(assoc :organizations organizations)
;; ISO does not support sensor technique or platform characteristics
(update-in [:platforms] platforms->expected-parsed)
;; ISO does not support size in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not fully support two-d-coordinate-systems
(dissoc :two-d-coordinate-systems)
;; It looks like ISO-19115-2 does not have a string we can extract representing quality.
;; ISO-19115-1 will have a string which we can extract.
(dissoc :quality)
(update-in [:spatial-coverage] spatial-coverage->expected-parsed)
(update :spatial-coverage add-redundant-bounding-boxes)
(assoc :personnel personnel)
;; publication-reference will be added later
(dissoc :publication-references)
(dissoc :collection-citations)
(dissoc :collection-progress)
umm-c/map->UmmCollection)))
(defn derive-geometries
"Returns SpatialCoverage with all geometries updated by calling
calculate-derived with the collection coordinate system."
[{cs :spatial-representation :as sc}]
(when sc
(let [derive #(d/calculate-derived (umm-s/set-coordinate-system cs %))]
(update-in sc [:geometries] (partial map derive)))))
(defspec generate-collection-is-valid-xml-test 100
(for-all [collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)]
(and
(> (count xml) 0)
(= 0 (count (c/validate-xml xml)))))))
(deftest generate-and-parse-collection-test
(checking "collection round tripping" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed (c/parse-collection xml)
expected-parsed (umm->expected-parsed-iso collection)]
(is (= expected-parsed parsed)))))
(deftest generate-and-parse-collection-between-formats-test
(checking "parse between formats" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed-iso (c/parse-collection xml)
echo10-xml (echo10/umm->echo10-xml parsed-iso)
parsed-echo10 (echo10-c/parse-collection echo10-xml)
;; fudge the spatial coverage here because ECHO 10 doesn't
;; apply the collection spatial representation to the
;; geometries it contains...
parsed-echo10 (update-in parsed-echo10 [:spatial-coverage] spatial-coverage->expected-parsed)
expected-parsed (test-echo10/umm->expected-parsed-echo10 (umm->expected-parsed-iso collection))]
(is (= parsed-echo10 expected-parsed))
(is (= 0 (count (echo10-c/validate-xml echo10-xml)))))))
(comment
;; This test is currently failing pending an update to the XSLT file
;; to generate closed polygons per the GML spec
(def echo-to-iso-xslt
(xslt/read-template
(io/resource "schema/iso_mends/resources/transforms/ECHOToISO.xsl")))
(defspec umm-to-echo-to-iso-mends-via-xslt-to-umm-test 100
(for-all [collection coll-gen/collections]
(let [echo10-xml (echo10/umm->echo10-xml collection)
iso-xml (xslt/transform echo10-xml echo-to-iso-xslt)
parsed-iso (c/parse-collection iso-xml)]
;; only comparing the parsed :spatial-coverage, since there are
;; funky parts in the rest of the XSLT output
(= (:spatial-coverage (umm->expected-parsed-iso collection))
(:spatial-coverage (umm->expected-parsed-iso parsed-iso)))))))
;; This is a made-up include all fields collection xml sample for the parse collection test
(def all-fields-collection-xml
(slurp (io/file (io/resource "data/iso_mends/all_fields_iso_collection.xml"))))
(def valid-collection-xml
(slurp (io/file (io/resource "data/iso_mends/sample_iso_collection.xml"))))
(def real-data-collection-xml
(slurp (io/file (io/resource "data/iso_mends/C1216109961-NSIDCV0TST.xml"))))
(def expected-temporal
(umm-c/map->Temporal
{:range-date-times
[(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1996-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1997-03-24T22:20:41-05:00")})
(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1998-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1999-03-24T22:20:41-05:00")})]
:single-date-times
[(p/parse-datetime "2010-01-05T05:30:30.550-05:00")]
:periodic-date-times []}))
(def expected-collection
(umm-c/map->UmmCollection
{:entry-title "MINIMAL > A minimal valid collection"
:summary "A minimal valid collection"
:purpose "A grand purpose"
:metadata-language "eng"
:product (umm-c/map->Product
{:short-name "MINIMAL"
:long-name "A minimal valid collection"
:version-id "1"
:processing-level-id "1B"})
:access-value 4.2
:use-constraints "Restriction Comment:"
:data-provider-timestamps (umm-c/map->DataProviderTimestamps
{:insert-time (p/parse-datetime "1999-12-30T19:00:00-05:00")
:update-time (p/parse-datetime "1999-12-31T19:00:00-05:00")
:revision-date-time (p/parse-datetime "1999-12-31T19:00:00-05:00")})
:spatial-keywords ["Word-2" "Word-1" "Word-0"]
:temporal-keywords ["Word-5" "Word-3" "Word-4"]
:temporal expected-temporal
:spatial-coverage (umm-c/map->SpatialCoverage {:granule-spatial-representation :cartesian})
:science-keywords
[(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SNOW/ICE"
:variable-level-1 "ALBEDO"
:variable-level-2 "BETA"
:variable-level-3 "GAMMA"
:detailed-variable "DETAILED"})
(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SEA ICE"
:variable-level-1 "REFLECTANCE"})]
:platforms
[(umm-c/map->Platform
{:short-name "RADARSAT-1"
:long-name "RADARSAT-LONG-1"
:type "Spacecraft"
:instruments [(umm-c/map->Instrument
{:short-name "SAR"
:long-name "SAR long name"
:sensors [(umm-c/map->Sensor {:short-name "SNA"
:long-name "SNA long name"})
(umm-c/map->Sensor {:short-name "SNB"})]})
(umm-c/map->Instrument {:short-name "MAR"})]})
(umm-c/map->Platform
{:short-name "RADARSAT-2"
:long-name "RADARSAT-LONG-2"
:type "Spacecraft-2"
:instruments nil})]
:product-specific-attributes
[(umm-c/map->ProductSpecificAttribute
{:name "SIPSMetGenVersion"
:description "The version of the SIPSMetGen software used to produce the metadata file for this granule"
:data-type :string
:parameter-range-begin "alpha"
:parameter-range-end "bravo"
:value "alpha1"
:parsed-parameter-range-begin "alpha"
:parsed-parameter-range-end "bravo"
:parsed-value "alpha1"})
(umm-c/map->ProductSpecificAttribute
{:name "No description"
:description "Not provided"
:data-type :string
:value "alpha2"
:parsed-value "alpha2"})]
:collection-associations [(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-237"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-238"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-239"
:version-id "1"})]
:projects
[(umm-c/map->Project
{:short-name "ESI"
:long-name "Environmental Sustainability Index"})
(umm-c/map->Project
{:short-name "EVI"
:long-name "Environmental Vulnerability Index"})
(umm-c/map->Project
{:short-name "EPI"
:long-name "Environmental Performance Index"})]
:related-urls
[(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://ghrc.nsstc.nasa.gov/hydro/details.pl?ds=dc8capac"})
(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://camex.nsstc.nasa.gov/camex3/"})
(umm-c/map->RelatedURL
{:type "VIEW RELATED INFORMATION"
:url "http://ghrc.nsstc.nasa.gov/uso/ds_docs/camex3/dc8capac/dc8capac_dataset.html"})
(umm-c/map->RelatedURL
{:type "GET RELATED VISUALIZATION"
:url "ftp://camex.nsstc.nasa.gov/camex3/dc8capac/browse/"
:description "Some description."
:title "Some description."})]
:associated-difs ["DIF-255" "DIF-256" "DIF-257"]
:organizations
[(umm-c/map->Organization
{:type :processing-center
:org-name "SEDAC PC"})
(umm-c/map->Organization
{:type :archive-center
:org-name "SEDAC AC"})]
:personnel [(umm-c/map->Personnel
{:last-name "SEDAC AC"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "John Smith"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "SEDAC AC"
:roles ["distributor"]})]}))
(deftest parse-collection-test
(testing "parse collection"
(is (= expected-collection (c/parse-collection all-fields-collection-xml))))
(testing "parse temporal"
(is (= expected-temporal (c/parse-temporal all-fields-collection-xml))))
(testing "parse access value"
(is (= 4.2 (c/parse-access-value all-fields-collection-xml)))))
(deftest validate-xml
(testing "valid xml"
(is (= 0 (count (c/validate-xml valid-collection-xml)))))
(testing "invalid xml"
(is (= [(str "Line 15 - cvc-complex-type.2.4.a: Invalid content was found "
"starting with element 'gmd:XXXX'. One of "
"'{\"http://www.isotc211.org/2005/gmd\":fileIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":language, "
"\"http://www.isotc211.org/2005/gmd\":characterSet, "
"\"http://www.isotc211.org/2005/gmd\":parentIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevel, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevelName, "
"\"http://www.isotc211.org/2005/gmd\":contact}' is expected.")]
(c/validate-xml (s/replace valid-collection-xml "fileIdentifier" "XXXX"))))))
(deftest parse-collection-defaults-test
"Check that defaults are being added correctly to create valid umm"
(let [umm (c/parse-collection real-data-collection-xml)]
(testing "default granule spatial represetation"
(is (= :no-spatial (get-in umm [:spatial-coverage :granule-spatial-representation]))))
(testing "default ScienceKeywords Term"
(is (= umm-c/not-provided (->> umm :science-keywords first :term))))))
| 1561 | (ns cmr.umm.test.iso-mends.iso-mends-collection-tests
"Tests parsing and generating ISO Collection XML."
(:require
[clojure.java.io :as io]
[clojure.string :as s]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :refer [for-all]]
[cmr.common.date-time-parser :as p]
[cmr.common.joda-time]
[cmr.common.test.test-check-ext :refer [defspec checking]]
;; this is not needed until the ECHO to ISO XSLT is fixed
;; [cmr.common.xml.xslt :as xslt]
[cmr.spatial.derived :as d]
[cmr.spatial.encoding.gmd :as gmd]
[cmr.spatial.relations :as r]
[cmr.umm.echo10.collection.personnel :as echo-pe]
[cmr.umm.echo10.echo10-collection :as echo10-c]
[cmr.umm.echo10.echo10-core :as echo10]
[cmr.umm.iso-mends.iso-mends-collection :as c]
[cmr.umm.iso-mends.iso-mends-core :as iso]
[cmr.umm.test.echo10.echo10-collection-tests :as test-echo10]
[cmr.umm.test.generators.collection :as coll-gen]
[cmr.umm.umm-collection :as umm-c]
[cmr.umm.umm-spatial :as umm-s]))
(defn- fix-mbr
"The mbr creation in the functions below sometimes gets a rounding error when using
calculate-derived. This function fixes that since the rounding error occurs
in :center-point."
[mbr]
(cmr.spatial.mbr/mbr
(:west mbr) (:north mbr) (:east mbr) (:south mbr)))
(defmulti create-bounding-box
(fn [geometry]
(type geometry)))
(defmethod create-bounding-box cmr.spatial.mbr.Mbr
[geometry]
geometry)
(defmethod create-bounding-box cmr.spatial.point.Point
[geometry]
(cmr.spatial.mbr/point->mbr geometry))
(defmethod create-bounding-box cmr.spatial.line_string.LineString
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defmethod create-bounding-box cmr.spatial.polygon.Polygon
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defn- add-redundant-bounding-boxes
"ISO generates redundant bounding boxes. We are no longer removing them. In the
expected conversion we need to generate redundant bounding boxes for each geomtry
type."
[spatial-coverage]
(if-let [geometries (:geometries spatial-coverage)]
(assoc spatial-coverage :geometries
(interleave
(map create-bounding-box geometries)
geometries))
spatial-coverage))
(defn- spatial-coverage->expected-parsed
"Returns the expected parsed ISO MENDS SpatialCoverage from a UMM collection."
[{:keys [geometries spatial-representation granule-spatial-representation]}]
(when (or granule-spatial-representation (seq geometries))
(umm-c/map->SpatialCoverage
{:spatial-representation spatial-representation
:granule-spatial-representation (or granule-spatial-representation :no-spatial)
:geometries (seq (map #(umm-s/set-coordinate-system spatial-representation %) geometries))})))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil) related-urls)))
(defn- sensors->expected-parsed
"Return the expected parsed sensors for the given sensors."
[sensors]
(seq (map #(assoc % :technique nil :characteristics nil) sensors)))
(defn- instrument->expected-parsed
"Return the expected parsed instrument for the given instrument."
[instrument]
(-> instrument
;; ISO does not support instrument technique, characteristics or operation modes
(assoc :technique nil :characteristics nil :operation-modes nil)
(update-in [:sensors] sensors->expected-parsed)))
(defn- instruments->expected-parsed
"Return the expected parsed instruments for the given instruments."
[instruments]
(seq (map instrument->expected-parsed instruments)))
(defn- platform->expected-parsed
"Return the expected parsed platform for the given platform."
[platform]
(let [instruments (:instruments platform)]
(-> platform
(assoc :characteristics nil)
(assoc :instruments (instruments->expected-parsed instruments)))))
(defn- platforms->expected-parsed
"Returns the expected parsed platforms for the given platforms."
[platforms]
(seq (map platform->expected-parsed platforms)))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil :mime-type nil) related-urls)))
(defn- collection->personnel
"Creates personnel from the distribution center contacts."
[coll]
(let [distrib-centers (filter #(= :archive-center (:type %)) (:organizations coll))]
(map (fn [distrib-center]
(umm-c/map->Personnel
{:last-name (:org-name distrib-center)
:roles ["distributor"]}))
distrib-centers)))
(defn umm->expected-parsed-iso
"Modifies the UMM record for testing ISO. ISO contains a subset of the total UMM fields so certain
fields are removed for comparison of the parsed record"
[coll]
(let [{:keys [spatial-coverage]} coll
range-date-times (get-in coll [:temporal :range-date-times])
single-date-times (get-in coll [:temporal :single-date-times])
temporal (if (seq range-date-times)
(umm-c/map->Temporal {:range-date-times range-date-times
:single-date-times []
:periodic-date-times []})
(when (seq single-date-times)
(umm-c/map->Temporal {:range-date-times []
:single-date-times single-date-times
:periodic-date-times []})))
revision-date-time (get-in coll [:data-provider-timestamps :revision-date-time])
personnel (not-empty (collection->personnel coll))
organizations (seq (filter #(not (= :distribution-center (:type %))) (:organizations coll)))]
(-> coll
;; ISO does not have version-description
(assoc-in [:product :version-description] nil)
;; ISO does not have collection-data-type
(assoc-in [:product :collection-data-type] nil)
;; There is no delete-time in ISO
(assoc-in [:data-provider-timestamps :delete-time] nil)
;; Revision date time is same as update-time
(assoc-in [:data-provider-timestamps :update-time] revision-date-time)
;; ISO does not have periodic-date-times
(assoc :temporal temporal)
;; ISO does not support mime-type in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not have distribution centers as Organization
(assoc :organizations organizations)
;; ISO does not support sensor technique or platform characteristics
(update-in [:platforms] platforms->expected-parsed)
;; ISO does not support size in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not fully support two-d-coordinate-systems
(dissoc :two-d-coordinate-systems)
;; It looks like ISO-19115-2 does not have a string we can extract representing quality.
;; ISO-19115-1 will have a string which we can extract.
(dissoc :quality)
(update-in [:spatial-coverage] spatial-coverage->expected-parsed)
(update :spatial-coverage add-redundant-bounding-boxes)
(assoc :personnel personnel)
;; publication-reference will be added later
(dissoc :publication-references)
(dissoc :collection-citations)
(dissoc :collection-progress)
umm-c/map->UmmCollection)))
(defn derive-geometries
"Returns SpatialCoverage with all geometries updated by calling
calculate-derived with the collection coordinate system."
[{cs :spatial-representation :as sc}]
(when sc
(let [derive #(d/calculate-derived (umm-s/set-coordinate-system cs %))]
(update-in sc [:geometries] (partial map derive)))))
(defspec generate-collection-is-valid-xml-test 100
(for-all [collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)]
(and
(> (count xml) 0)
(= 0 (count (c/validate-xml xml)))))))
(deftest generate-and-parse-collection-test
(checking "collection round tripping" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed (c/parse-collection xml)
expected-parsed (umm->expected-parsed-iso collection)]
(is (= expected-parsed parsed)))))
(deftest generate-and-parse-collection-between-formats-test
(checking "parse between formats" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed-iso (c/parse-collection xml)
echo10-xml (echo10/umm->echo10-xml parsed-iso)
parsed-echo10 (echo10-c/parse-collection echo10-xml)
;; fudge the spatial coverage here because ECHO 10 doesn't
;; apply the collection spatial representation to the
;; geometries it contains...
parsed-echo10 (update-in parsed-echo10 [:spatial-coverage] spatial-coverage->expected-parsed)
expected-parsed (test-echo10/umm->expected-parsed-echo10 (umm->expected-parsed-iso collection))]
(is (= parsed-echo10 expected-parsed))
(is (= 0 (count (echo10-c/validate-xml echo10-xml)))))))
(comment
;; This test is currently failing pending an update to the XSLT file
;; to generate closed polygons per the GML spec
(def echo-to-iso-xslt
(xslt/read-template
(io/resource "schema/iso_mends/resources/transforms/ECHOToISO.xsl")))
(defspec umm-to-echo-to-iso-mends-via-xslt-to-umm-test 100
(for-all [collection coll-gen/collections]
(let [echo10-xml (echo10/umm->echo10-xml collection)
iso-xml (xslt/transform echo10-xml echo-to-iso-xslt)
parsed-iso (c/parse-collection iso-xml)]
;; only comparing the parsed :spatial-coverage, since there are
;; funky parts in the rest of the XSLT output
(= (:spatial-coverage (umm->expected-parsed-iso collection))
(:spatial-coverage (umm->expected-parsed-iso parsed-iso)))))))
;; This is a made-up include all fields collection xml sample for the parse collection test
(def all-fields-collection-xml
(slurp (io/file (io/resource "data/iso_mends/all_fields_iso_collection.xml"))))
(def valid-collection-xml
(slurp (io/file (io/resource "data/iso_mends/sample_iso_collection.xml"))))
(def real-data-collection-xml
(slurp (io/file (io/resource "data/iso_mends/C1216109961-NSIDCV0TST.xml"))))
(def expected-temporal
(umm-c/map->Temporal
{:range-date-times
[(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1996-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1997-03-24T22:20:41-05:00")})
(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1998-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1999-03-24T22:20:41-05:00")})]
:single-date-times
[(p/parse-datetime "2010-01-05T05:30:30.550-05:00")]
:periodic-date-times []}))
(def expected-collection
(umm-c/map->UmmCollection
{:entry-title "MINIMAL > A minimal valid collection"
:summary "A minimal valid collection"
:purpose "A grand purpose"
:metadata-language "eng"
:product (umm-c/map->Product
{:short-name "MINIMAL"
:long-name "A minimal valid collection"
:version-id "1"
:processing-level-id "1B"})
:access-value 4.2
:use-constraints "Restriction Comment:"
:data-provider-timestamps (umm-c/map->DataProviderTimestamps
{:insert-time (p/parse-datetime "1999-12-30T19:00:00-05:00")
:update-time (p/parse-datetime "1999-12-31T19:00:00-05:00")
:revision-date-time (p/parse-datetime "1999-12-31T19:00:00-05:00")})
:spatial-keywords ["Word-2" "Word-1" "Word-0"]
:temporal-keywords ["Word-5" "Word-3" "Word-4"]
:temporal expected-temporal
:spatial-coverage (umm-c/map->SpatialCoverage {:granule-spatial-representation :cartesian})
:science-keywords
[(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SNOW/ICE"
:variable-level-1 "ALBEDO"
:variable-level-2 "BETA"
:variable-level-3 "GAMMA"
:detailed-variable "DETAILED"})
(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SEA ICE"
:variable-level-1 "REFLECTANCE"})]
:platforms
[(umm-c/map->Platform
{:short-name "RADARSAT-1"
:long-name "RADARSAT-LONG-1"
:type "Spacecraft"
:instruments [(umm-c/map->Instrument
{:short-name "SAR"
:long-name "SAR long name"
:sensors [(umm-c/map->Sensor {:short-name "SNA"
:long-name "SNA long name"})
(umm-c/map->Sensor {:short-name "SNB"})]})
(umm-c/map->Instrument {:short-name "MAR"})]})
(umm-c/map->Platform
{:short-name "RADARSAT-2"
:long-name "RADARSAT-LONG-2"
:type "Spacecraft-2"
:instruments nil})]
:product-specific-attributes
[(umm-c/map->ProductSpecificAttribute
{:name "SIPSMetGenVersion"
:description "The version of the SIPSMetGen software used to produce the metadata file for this granule"
:data-type :string
:parameter-range-begin "alpha"
:parameter-range-end "bravo"
:value "alpha1"
:parsed-parameter-range-begin "alpha"
:parsed-parameter-range-end "bravo"
:parsed-value "alpha1"})
(umm-c/map->ProductSpecificAttribute
{:name "No description"
:description "Not provided"
:data-type :string
:value "alpha2"
:parsed-value "alpha2"})]
:collection-associations [(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-237"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-238"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-239"
:version-id "1"})]
:projects
[(umm-c/map->Project
{:short-name "ESI"
:long-name "Environmental Sustainability Index"})
(umm-c/map->Project
{:short-name "EVI"
:long-name "Environmental Vulnerability Index"})
(umm-c/map->Project
{:short-name "EPI"
:long-name "Environmental Performance Index"})]
:related-urls
[(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://ghrc.nsstc.nasa.gov/hydro/details.pl?ds=dc8capac"})
(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://camex.nsstc.nasa.gov/camex3/"})
(umm-c/map->RelatedURL
{:type "VIEW RELATED INFORMATION"
:url "http://ghrc.nsstc.nasa.gov/uso/ds_docs/camex3/dc8capac/dc8capac_dataset.html"})
(umm-c/map->RelatedURL
{:type "GET RELATED VISUALIZATION"
:url "ftp://camex.nsstc.nasa.gov/camex3/dc8capac/browse/"
:description "Some description."
:title "Some description."})]
:associated-difs ["DIF-255" "DIF-256" "DIF-257"]
:organizations
[(umm-c/map->Organization
{:type :processing-center
:org-name "SEDAC PC"})
(umm-c/map->Organization
{:type :archive-center
:org-name "SEDAC AC"})]
:personnel [(umm-c/map->Personnel
{:last-name "SEDAC AC"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "<NAME>"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "<NAME>"
:roles ["distributor"]})]}))
(deftest parse-collection-test
(testing "parse collection"
(is (= expected-collection (c/parse-collection all-fields-collection-xml))))
(testing "parse temporal"
(is (= expected-temporal (c/parse-temporal all-fields-collection-xml))))
(testing "parse access value"
(is (= 4.2 (c/parse-access-value all-fields-collection-xml)))))
(deftest validate-xml
(testing "valid xml"
(is (= 0 (count (c/validate-xml valid-collection-xml)))))
(testing "invalid xml"
(is (= [(str "Line 15 - cvc-complex-type.2.4.a: Invalid content was found "
"starting with element 'gmd:XXXX'. One of "
"'{\"http://www.isotc211.org/2005/gmd\":fileIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":language, "
"\"http://www.isotc211.org/2005/gmd\":characterSet, "
"\"http://www.isotc211.org/2005/gmd\":parentIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevel, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevelName, "
"\"http://www.isotc211.org/2005/gmd\":contact}' is expected.")]
(c/validate-xml (s/replace valid-collection-xml "fileIdentifier" "XXXX"))))))
(deftest parse-collection-defaults-test
"Check that defaults are being added correctly to create valid umm"
(let [umm (c/parse-collection real-data-collection-xml)]
(testing "default granule spatial represetation"
(is (= :no-spatial (get-in umm [:spatial-coverage :granule-spatial-representation]))))
(testing "default ScienceKeywords Term"
(is (= umm-c/not-provided (->> umm :science-keywords first :term))))))
| true | (ns cmr.umm.test.iso-mends.iso-mends-collection-tests
"Tests parsing and generating ISO Collection XML."
(:require
[clojure.java.io :as io]
[clojure.string :as s]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :refer [for-all]]
[cmr.common.date-time-parser :as p]
[cmr.common.joda-time]
[cmr.common.test.test-check-ext :refer [defspec checking]]
;; this is not needed until the ECHO to ISO XSLT is fixed
;; [cmr.common.xml.xslt :as xslt]
[cmr.spatial.derived :as d]
[cmr.spatial.encoding.gmd :as gmd]
[cmr.spatial.relations :as r]
[cmr.umm.echo10.collection.personnel :as echo-pe]
[cmr.umm.echo10.echo10-collection :as echo10-c]
[cmr.umm.echo10.echo10-core :as echo10]
[cmr.umm.iso-mends.iso-mends-collection :as c]
[cmr.umm.iso-mends.iso-mends-core :as iso]
[cmr.umm.test.echo10.echo10-collection-tests :as test-echo10]
[cmr.umm.test.generators.collection :as coll-gen]
[cmr.umm.umm-collection :as umm-c]
[cmr.umm.umm-spatial :as umm-s]))
(defn- fix-mbr
"The mbr creation in the functions below sometimes gets a rounding error when using
calculate-derived. This function fixes that since the rounding error occurs
in :center-point."
[mbr]
(cmr.spatial.mbr/mbr
(:west mbr) (:north mbr) (:east mbr) (:south mbr)))
(defmulti create-bounding-box
(fn [geometry]
(type geometry)))
(defmethod create-bounding-box cmr.spatial.mbr.Mbr
[geometry]
geometry)
(defmethod create-bounding-box cmr.spatial.point.Point
[geometry]
(cmr.spatial.mbr/point->mbr geometry))
(defmethod create-bounding-box cmr.spatial.line_string.LineString
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defmethod create-bounding-box cmr.spatial.polygon.Polygon
[geometry]
(fix-mbr (:mbr (d/calculate-derived geometry))))
(defn- add-redundant-bounding-boxes
"ISO generates redundant bounding boxes. We are no longer removing them. In the
expected conversion we need to generate redundant bounding boxes for each geomtry
type."
[spatial-coverage]
(if-let [geometries (:geometries spatial-coverage)]
(assoc spatial-coverage :geometries
(interleave
(map create-bounding-box geometries)
geometries))
spatial-coverage))
(defn- spatial-coverage->expected-parsed
"Returns the expected parsed ISO MENDS SpatialCoverage from a UMM collection."
[{:keys [geometries spatial-representation granule-spatial-representation]}]
(when (or granule-spatial-representation (seq geometries))
(umm-c/map->SpatialCoverage
{:spatial-representation spatial-representation
:granule-spatial-representation (or granule-spatial-representation :no-spatial)
:geometries (seq (map #(umm-s/set-coordinate-system spatial-representation %) geometries))})))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil) related-urls)))
(defn- sensors->expected-parsed
"Return the expected parsed sensors for the given sensors."
[sensors]
(seq (map #(assoc % :technique nil :characteristics nil) sensors)))
(defn- instrument->expected-parsed
"Return the expected parsed instrument for the given instrument."
[instrument]
(-> instrument
;; ISO does not support instrument technique, characteristics or operation modes
(assoc :technique nil :characteristics nil :operation-modes nil)
(update-in [:sensors] sensors->expected-parsed)))
(defn- instruments->expected-parsed
"Return the expected parsed instruments for the given instruments."
[instruments]
(seq (map instrument->expected-parsed instruments)))
(defn- platform->expected-parsed
"Return the expected parsed platform for the given platform."
[platform]
(let [instruments (:instruments platform)]
(-> platform
(assoc :characteristics nil)
(assoc :instruments (instruments->expected-parsed instruments)))))
(defn- platforms->expected-parsed
"Returns the expected parsed platforms for the given platforms."
[platforms]
(seq (map platform->expected-parsed platforms)))
(defn- related-urls->expected-parsed
"Returns the expected parsed related-urls for the given related-urls."
[related-urls]
(seq (map #(assoc % :size nil :mime-type nil) related-urls)))
(defn- collection->personnel
"Creates personnel from the distribution center contacts."
[coll]
(let [distrib-centers (filter #(= :archive-center (:type %)) (:organizations coll))]
(map (fn [distrib-center]
(umm-c/map->Personnel
{:last-name (:org-name distrib-center)
:roles ["distributor"]}))
distrib-centers)))
(defn umm->expected-parsed-iso
"Modifies the UMM record for testing ISO. ISO contains a subset of the total UMM fields so certain
fields are removed for comparison of the parsed record"
[coll]
(let [{:keys [spatial-coverage]} coll
range-date-times (get-in coll [:temporal :range-date-times])
single-date-times (get-in coll [:temporal :single-date-times])
temporal (if (seq range-date-times)
(umm-c/map->Temporal {:range-date-times range-date-times
:single-date-times []
:periodic-date-times []})
(when (seq single-date-times)
(umm-c/map->Temporal {:range-date-times []
:single-date-times single-date-times
:periodic-date-times []})))
revision-date-time (get-in coll [:data-provider-timestamps :revision-date-time])
personnel (not-empty (collection->personnel coll))
organizations (seq (filter #(not (= :distribution-center (:type %))) (:organizations coll)))]
(-> coll
;; ISO does not have version-description
(assoc-in [:product :version-description] nil)
;; ISO does not have collection-data-type
(assoc-in [:product :collection-data-type] nil)
;; There is no delete-time in ISO
(assoc-in [:data-provider-timestamps :delete-time] nil)
;; Revision date time is same as update-time
(assoc-in [:data-provider-timestamps :update-time] revision-date-time)
;; ISO does not have periodic-date-times
(assoc :temporal temporal)
;; ISO does not support mime-type in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not have distribution centers as Organization
(assoc :organizations organizations)
;; ISO does not support sensor technique or platform characteristics
(update-in [:platforms] platforms->expected-parsed)
;; ISO does not support size in RelatedURLs
(update-in [:related-urls] related-urls->expected-parsed)
;; ISO does not fully support two-d-coordinate-systems
(dissoc :two-d-coordinate-systems)
;; It looks like ISO-19115-2 does not have a string we can extract representing quality.
;; ISO-19115-1 will have a string which we can extract.
(dissoc :quality)
(update-in [:spatial-coverage] spatial-coverage->expected-parsed)
(update :spatial-coverage add-redundant-bounding-boxes)
(assoc :personnel personnel)
;; publication-reference will be added later
(dissoc :publication-references)
(dissoc :collection-citations)
(dissoc :collection-progress)
umm-c/map->UmmCollection)))
(defn derive-geometries
"Returns SpatialCoverage with all geometries updated by calling
calculate-derived with the collection coordinate system."
[{cs :spatial-representation :as sc}]
(when sc
(let [derive #(d/calculate-derived (umm-s/set-coordinate-system cs %))]
(update-in sc [:geometries] (partial map derive)))))
(defspec generate-collection-is-valid-xml-test 100
(for-all [collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)]
(and
(> (count xml) 0)
(= 0 (count (c/validate-xml xml)))))))
(deftest generate-and-parse-collection-test
(checking "collection round tripping" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed (c/parse-collection xml)
expected-parsed (umm->expected-parsed-iso collection)]
(is (= expected-parsed parsed)))))
(deftest generate-and-parse-collection-between-formats-test
(checking "parse between formats" 100
[collection coll-gen/collections]
(let [xml (iso/umm->iso-mends-xml collection)
parsed-iso (c/parse-collection xml)
echo10-xml (echo10/umm->echo10-xml parsed-iso)
parsed-echo10 (echo10-c/parse-collection echo10-xml)
;; fudge the spatial coverage here because ECHO 10 doesn't
;; apply the collection spatial representation to the
;; geometries it contains...
parsed-echo10 (update-in parsed-echo10 [:spatial-coverage] spatial-coverage->expected-parsed)
expected-parsed (test-echo10/umm->expected-parsed-echo10 (umm->expected-parsed-iso collection))]
(is (= parsed-echo10 expected-parsed))
(is (= 0 (count (echo10-c/validate-xml echo10-xml)))))))
(comment
;; This test is currently failing pending an update to the XSLT file
;; to generate closed polygons per the GML spec
(def echo-to-iso-xslt
(xslt/read-template
(io/resource "schema/iso_mends/resources/transforms/ECHOToISO.xsl")))
(defspec umm-to-echo-to-iso-mends-via-xslt-to-umm-test 100
(for-all [collection coll-gen/collections]
(let [echo10-xml (echo10/umm->echo10-xml collection)
iso-xml (xslt/transform echo10-xml echo-to-iso-xslt)
parsed-iso (c/parse-collection iso-xml)]
;; only comparing the parsed :spatial-coverage, since there are
;; funky parts in the rest of the XSLT output
(= (:spatial-coverage (umm->expected-parsed-iso collection))
(:spatial-coverage (umm->expected-parsed-iso parsed-iso)))))))
;; This is a made-up include all fields collection xml sample for the parse collection test
(def all-fields-collection-xml
(slurp (io/file (io/resource "data/iso_mends/all_fields_iso_collection.xml"))))
(def valid-collection-xml
(slurp (io/file (io/resource "data/iso_mends/sample_iso_collection.xml"))))
(def real-data-collection-xml
(slurp (io/file (io/resource "data/iso_mends/C1216109961-NSIDCV0TST.xml"))))
(def expected-temporal
(umm-c/map->Temporal
{:range-date-times
[(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1996-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1997-03-24T22:20:41-05:00")})
(umm-c/map->RangeDateTime
{:beginning-date-time (p/parse-datetime "1998-02-24T22:20:41-05:00")
:ending-date-time (p/parse-datetime "1999-03-24T22:20:41-05:00")})]
:single-date-times
[(p/parse-datetime "2010-01-05T05:30:30.550-05:00")]
:periodic-date-times []}))
(def expected-collection
(umm-c/map->UmmCollection
{:entry-title "MINIMAL > A minimal valid collection"
:summary "A minimal valid collection"
:purpose "A grand purpose"
:metadata-language "eng"
:product (umm-c/map->Product
{:short-name "MINIMAL"
:long-name "A minimal valid collection"
:version-id "1"
:processing-level-id "1B"})
:access-value 4.2
:use-constraints "Restriction Comment:"
:data-provider-timestamps (umm-c/map->DataProviderTimestamps
{:insert-time (p/parse-datetime "1999-12-30T19:00:00-05:00")
:update-time (p/parse-datetime "1999-12-31T19:00:00-05:00")
:revision-date-time (p/parse-datetime "1999-12-31T19:00:00-05:00")})
:spatial-keywords ["Word-2" "Word-1" "Word-0"]
:temporal-keywords ["Word-5" "Word-3" "Word-4"]
:temporal expected-temporal
:spatial-coverage (umm-c/map->SpatialCoverage {:granule-spatial-representation :cartesian})
:science-keywords
[(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SNOW/ICE"
:variable-level-1 "ALBEDO"
:variable-level-2 "BETA"
:variable-level-3 "GAMMA"
:detailed-variable "DETAILED"})
(umm-c/map->ScienceKeyword
{:category "EARTH SCIENCE"
:topic "CRYOSPHERE"
:term "SEA ICE"
:variable-level-1 "REFLECTANCE"})]
:platforms
[(umm-c/map->Platform
{:short-name "RADARSAT-1"
:long-name "RADARSAT-LONG-1"
:type "Spacecraft"
:instruments [(umm-c/map->Instrument
{:short-name "SAR"
:long-name "SAR long name"
:sensors [(umm-c/map->Sensor {:short-name "SNA"
:long-name "SNA long name"})
(umm-c/map->Sensor {:short-name "SNB"})]})
(umm-c/map->Instrument {:short-name "MAR"})]})
(umm-c/map->Platform
{:short-name "RADARSAT-2"
:long-name "RADARSAT-LONG-2"
:type "Spacecraft-2"
:instruments nil})]
:product-specific-attributes
[(umm-c/map->ProductSpecificAttribute
{:name "SIPSMetGenVersion"
:description "The version of the SIPSMetGen software used to produce the metadata file for this granule"
:data-type :string
:parameter-range-begin "alpha"
:parameter-range-end "bravo"
:value "alpha1"
:parsed-parameter-range-begin "alpha"
:parsed-parameter-range-end "bravo"
:parsed-value "alpha1"})
(umm-c/map->ProductSpecificAttribute
{:name "No description"
:description "Not provided"
:data-type :string
:value "alpha2"
:parsed-value "alpha2"})]
:collection-associations [(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-237"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-238"
:version-id "1"})
(umm-c/map->CollectionAssociation
{:short-name "COLLOTHER-239"
:version-id "1"})]
:projects
[(umm-c/map->Project
{:short-name "ESI"
:long-name "Environmental Sustainability Index"})
(umm-c/map->Project
{:short-name "EVI"
:long-name "Environmental Vulnerability Index"})
(umm-c/map->Project
{:short-name "EPI"
:long-name "Environmental Performance Index"})]
:related-urls
[(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://ghrc.nsstc.nasa.gov/hydro/details.pl?ds=dc8capac"})
(umm-c/map->RelatedURL
{:type "GET DATA"
:url "http://camex.nsstc.nasa.gov/camex3/"})
(umm-c/map->RelatedURL
{:type "VIEW RELATED INFORMATION"
:url "http://ghrc.nsstc.nasa.gov/uso/ds_docs/camex3/dc8capac/dc8capac_dataset.html"})
(umm-c/map->RelatedURL
{:type "GET RELATED VISUALIZATION"
:url "ftp://camex.nsstc.nasa.gov/camex3/dc8capac/browse/"
:description "Some description."
:title "Some description."})]
:associated-difs ["DIF-255" "DIF-256" "DIF-257"]
:organizations
[(umm-c/map->Organization
{:type :processing-center
:org-name "SEDAC PC"})
(umm-c/map->Organization
{:type :archive-center
:org-name "SEDAC AC"})]
:personnel [(umm-c/map->Personnel
{:last-name "SEDAC AC"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "PI:NAME:<NAME>END_PI"
:roles ["pointOfContact"]})
(umm-c/map->Personnel
{:last-name "PI:NAME:<NAME>END_PI"
:roles ["distributor"]})]}))
(deftest parse-collection-test
(testing "parse collection"
(is (= expected-collection (c/parse-collection all-fields-collection-xml))))
(testing "parse temporal"
(is (= expected-temporal (c/parse-temporal all-fields-collection-xml))))
(testing "parse access value"
(is (= 4.2 (c/parse-access-value all-fields-collection-xml)))))
(deftest validate-xml
(testing "valid xml"
(is (= 0 (count (c/validate-xml valid-collection-xml)))))
(testing "invalid xml"
(is (= [(str "Line 15 - cvc-complex-type.2.4.a: Invalid content was found "
"starting with element 'gmd:XXXX'. One of "
"'{\"http://www.isotc211.org/2005/gmd\":fileIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":language, "
"\"http://www.isotc211.org/2005/gmd\":characterSet, "
"\"http://www.isotc211.org/2005/gmd\":parentIdentifier, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevel, "
"\"http://www.isotc211.org/2005/gmd\":hierarchyLevelName, "
"\"http://www.isotc211.org/2005/gmd\":contact}' is expected.")]
(c/validate-xml (s/replace valid-collection-xml "fileIdentifier" "XXXX"))))))
(deftest parse-collection-defaults-test
"Check that defaults are being added correctly to create valid umm"
(let [umm (c/parse-collection real-data-collection-xml)]
(testing "default granule spatial represetation"
(is (= :no-spatial (get-in umm [:spatial-coverage :granule-spatial-representation]))))
(testing "default ScienceKeywords Term"
(is (= umm-c/not-provided (->> umm :science-keywords first :term))))))
|
[
{
"context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 33,
"score": 0.9332128763198853,
"start": 30,
"tag": "NAME",
"value": "Net"
}
] | pigpen-core/src/test/clojure/pigpen/functional_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-test
(:refer-clojure :exclude [read]))
(defprotocol TestHarness
(data
[this data]
"Create mock input with specified data")
(dump
[this command]
"Execute the command & return the results")
(file
[this]
"Returns a new unique filename for writing results to")
(read
[this file]
"Reads data from a file, returns a sequence of lines")
(write
[this lines]
"Writes data to a file, returns the name of the file"))
(defonce all-tests (atom []))
(defmacro deftest
"Looks like defn, but defines a cross-platform test. Should take a single arg,
which is a TestHarness. This should be used for all data creation and test
execution."
[name docstring params & body]
{:pre [(symbol? name)
(string? docstring)
(vector? params) (nil? (next params))
body]}
`(do
(swap! all-tests conj '~(symbol (str (ns-name *ns*)) (str name)))
(defn ~(symbol (clojure.core/name name))
~docstring
~params
~@body)))
| 24290 | ;;
;;
;; 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-test
(:refer-clojure :exclude [read]))
(defprotocol TestHarness
(data
[this data]
"Create mock input with specified data")
(dump
[this command]
"Execute the command & return the results")
(file
[this]
"Returns a new unique filename for writing results to")
(read
[this file]
"Reads data from a file, returns a sequence of lines")
(write
[this lines]
"Writes data to a file, returns the name of the file"))
(defonce all-tests (atom []))
(defmacro deftest
"Looks like defn, but defines a cross-platform test. Should take a single arg,
which is a TestHarness. This should be used for all data creation and test
execution."
[name docstring params & body]
{:pre [(symbol? name)
(string? docstring)
(vector? params) (nil? (next params))
body]}
`(do
(swap! all-tests conj '~(symbol (str (ns-name *ns*)) (str name)))
(defn ~(symbol (clojure.core/name name))
~docstring
~params
~@body)))
| 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-test
(:refer-clojure :exclude [read]))
(defprotocol TestHarness
(data
[this data]
"Create mock input with specified data")
(dump
[this command]
"Execute the command & return the results")
(file
[this]
"Returns a new unique filename for writing results to")
(read
[this file]
"Reads data from a file, returns a sequence of lines")
(write
[this lines]
"Writes data to a file, returns the name of the file"))
(defonce all-tests (atom []))
(defmacro deftest
"Looks like defn, but defines a cross-platform test. Should take a single arg,
which is a TestHarness. This should be used for all data creation and test
execution."
[name docstring params & body]
{:pre [(symbol? name)
(string? docstring)
(vector? params) (nil? (next params))
body]}
`(do
(swap! all-tests conj '~(symbol (str (ns-name *ns*)) (str name)))
(defn ~(symbol (clojure.core/name name))
~docstring
~params
~@body)))
|
[
{
"context": "annedPdf.dir/DrinkingPhil.pdf\n;;\n;; Copyright 2015 Prajna Inc.\n;;\n;; Licensed under the Apache License, Ver",
"end": 164,
"score": 0.9189598560333252,
"start": 158,
"tag": "NAME",
"value": "Prajna"
}
] | test/diningphils/c_m_async/tests.clj | wizardpb/diningphils | 0 | ;;
;; Dining philosophers solution using Chandy-Misra algorithm
;; https://www.cs.utexas.edu/users/misra/scannedPdf.dir/DrinkingPhil.pdf
;;
;; Copyright 2015 Prajna 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 diningphils.c-m-async.tests
(:use diningphils.c-m-agents.core
diningphils.c-m-async.system
clojure.test))
#_(deftest id-wrap
(doseq [id (range 5)] (is (= id (wrapped-phil-id id))))
(is (= 0 (wrapped-phil-id 5)))
(is (= 4 (wrapped-phil-id -1))))
(deftest channel-init
(let [phils (:phils (init-fn {}))]
(testing "Values"
(doseq [phil phils]
(is (:phil-id phil))
(is (identical? phil (nth phils (:phil-id phil))))))
(testing "Channel connections"
(doseq [phil phils]
(let [phil-id (:phil-id phil)
n (count phils)
neighbors (:neighbors phil)
left (nth phils (mod (dec phil-id) n))
right (nth phils (mod (inc phil-id) n))]
;; Left neighbors chans should be my chans
(is (identical? (:to (last (:neighbors left))) (:from (:chans phil))))
(is (identical? (:from (last (:neighbors left))) (:to (:chans phil))))
(is (identical? (:to (last (:neighbors left))) (:from (first neighbors))))
(is (identical? (:from (last (:neighbors left))) (:to (first neighbors))))
(is (identical? (:to (first (:neighbors right))) (:from (last neighbors))))
(is (identical? (:from (first (:neighbors right))) (:to (last neighbors))))
)))
))
| 8819 | ;;
;; Dining philosophers solution using Chandy-Misra algorithm
;; https://www.cs.utexas.edu/users/misra/scannedPdf.dir/DrinkingPhil.pdf
;;
;; Copyright 2015 <NAME> 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 diningphils.c-m-async.tests
(:use diningphils.c-m-agents.core
diningphils.c-m-async.system
clojure.test))
#_(deftest id-wrap
(doseq [id (range 5)] (is (= id (wrapped-phil-id id))))
(is (= 0 (wrapped-phil-id 5)))
(is (= 4 (wrapped-phil-id -1))))
(deftest channel-init
(let [phils (:phils (init-fn {}))]
(testing "Values"
(doseq [phil phils]
(is (:phil-id phil))
(is (identical? phil (nth phils (:phil-id phil))))))
(testing "Channel connections"
(doseq [phil phils]
(let [phil-id (:phil-id phil)
n (count phils)
neighbors (:neighbors phil)
left (nth phils (mod (dec phil-id) n))
right (nth phils (mod (inc phil-id) n))]
;; Left neighbors chans should be my chans
(is (identical? (:to (last (:neighbors left))) (:from (:chans phil))))
(is (identical? (:from (last (:neighbors left))) (:to (:chans phil))))
(is (identical? (:to (last (:neighbors left))) (:from (first neighbors))))
(is (identical? (:from (last (:neighbors left))) (:to (first neighbors))))
(is (identical? (:to (first (:neighbors right))) (:from (last neighbors))))
(is (identical? (:from (first (:neighbors right))) (:to (last neighbors))))
)))
))
| true | ;;
;; Dining philosophers solution using Chandy-Misra algorithm
;; https://www.cs.utexas.edu/users/misra/scannedPdf.dir/DrinkingPhil.pdf
;;
;; Copyright 2015 PI:NAME:<NAME>END_PI 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 diningphils.c-m-async.tests
(:use diningphils.c-m-agents.core
diningphils.c-m-async.system
clojure.test))
#_(deftest id-wrap
(doseq [id (range 5)] (is (= id (wrapped-phil-id id))))
(is (= 0 (wrapped-phil-id 5)))
(is (= 4 (wrapped-phil-id -1))))
(deftest channel-init
(let [phils (:phils (init-fn {}))]
(testing "Values"
(doseq [phil phils]
(is (:phil-id phil))
(is (identical? phil (nth phils (:phil-id phil))))))
(testing "Channel connections"
(doseq [phil phils]
(let [phil-id (:phil-id phil)
n (count phils)
neighbors (:neighbors phil)
left (nth phils (mod (dec phil-id) n))
right (nth phils (mod (inc phil-id) n))]
;; Left neighbors chans should be my chans
(is (identical? (:to (last (:neighbors left))) (:from (:chans phil))))
(is (identical? (:from (last (:neighbors left))) (:to (:chans phil))))
(is (identical? (:to (last (:neighbors left))) (:from (first neighbors))))
(is (identical? (:from (last (:neighbors left))) (:to (first neighbors))))
(is (identical? (:to (first (:neighbors right))) (:from (last neighbors))))
(is (identical? (:from (first (:neighbors right))) (:to (last neighbors))))
)))
))
|
[
{
"context": " :request-method :post\n :req-key [1 2 3]} [1 2 3]\n {:uri \"rest\"\n :req",
"end": 1763,
"score": 0.5992968678474426,
"start": 1762,
"tag": "KEY",
"value": "2"
}
] | test/restfn/test.clj | MichaelBlume/restfn | 1 | (ns restfn.test
(:import (java.util ArrayList))
(:use (clojure test)
(clojure [string :only [split-lines]])
(restfn core)
(cheshire [core :only [parse-string]])))
(extend-type java.util.regex.Pattern
RestSerializable
(rest-serialize [r] #(re-matches r %)))
(def delay-calls (atom 0))
(def handler
(get-rest-handler
{"list" [1 3 5]
"map" {"foo" "bar"}
"atom" (atom 5)
"doubleatom" (atom (atom 7))
"javalist" (ArrayList. [5 9 7])
"simplefn" inc
"complexfn" (fn [x] {"key" x})
"pattern" #"(.*)and(.*)"
"seq" (for [x (range 3)]
(reify RestSerializable (rest-serialize [_] x)))
"rest-delay" (rest-delay (swap! delay-calls inc))
"rest" {:post (fn [req] (:req-key req))
:delete (fn [] "deleted")}}))
(defn object-from-request [req]
(let [res (handler req)]
(is (= (:status res) 200) res)
(is (= (:headers res) {"Content-Type" "application/json"}) res)
(parse-string (:body res))))
(defn object-from-uri [uri]
(object-from-request {:uri uri :request-method :get}))
(deftest simplegets
(are [uri result]
(= result (object-from-uri uri))
"list" [1 3 5]
"/list/" [1 3 5]
"/list/0" 1
"/list/1" 3
"atom" 5
"doubleatom" 7
"map" {"foo" "bar"}
"map/foo" "bar"
"javalist/" [5 9 7]
"javalist/0" 5
"simplefn/5" 6
"complexfn/3" {"key" 3}
"complexfn/hello/key" "hello"
"pattern/fooandbar" ["fooandbar" "foo" "bar"]
"seq" [0 1 2]))
(deftest test-404
(is (= 404 (:status (handler {:uri "/null" :request-method :get})))))
(deftest testrest
(are [req result]
(= result (object-from-request req))
{:uri "rest"
:request-method :post
:req-key [1 2 3]} [1 2 3]
{:uri "rest"
:request-method :delete} "deleted"))
(deftest testerror
(let [result (handler {:uri "list/5" :request-method :get})]
(is (= (:status result) 500))
(is (= (:headers result) {"Content-Type" "text/plain"}))
(is (re-matches #".*IndexOutOfBoundsException.*"
(-> result :body split-lines first)))))
(deftest test-delay
(let [delay-calls-init @delay-calls]
(doseq [n (range 1 100)]
(is (= (+ n delay-calls-init)
(object-from-uri "rest-delay"))))))
| 20412 | (ns restfn.test
(:import (java.util ArrayList))
(:use (clojure test)
(clojure [string :only [split-lines]])
(restfn core)
(cheshire [core :only [parse-string]])))
(extend-type java.util.regex.Pattern
RestSerializable
(rest-serialize [r] #(re-matches r %)))
(def delay-calls (atom 0))
(def handler
(get-rest-handler
{"list" [1 3 5]
"map" {"foo" "bar"}
"atom" (atom 5)
"doubleatom" (atom (atom 7))
"javalist" (ArrayList. [5 9 7])
"simplefn" inc
"complexfn" (fn [x] {"key" x})
"pattern" #"(.*)and(.*)"
"seq" (for [x (range 3)]
(reify RestSerializable (rest-serialize [_] x)))
"rest-delay" (rest-delay (swap! delay-calls inc))
"rest" {:post (fn [req] (:req-key req))
:delete (fn [] "deleted")}}))
(defn object-from-request [req]
(let [res (handler req)]
(is (= (:status res) 200) res)
(is (= (:headers res) {"Content-Type" "application/json"}) res)
(parse-string (:body res))))
(defn object-from-uri [uri]
(object-from-request {:uri uri :request-method :get}))
(deftest simplegets
(are [uri result]
(= result (object-from-uri uri))
"list" [1 3 5]
"/list/" [1 3 5]
"/list/0" 1
"/list/1" 3
"atom" 5
"doubleatom" 7
"map" {"foo" "bar"}
"map/foo" "bar"
"javalist/" [5 9 7]
"javalist/0" 5
"simplefn/5" 6
"complexfn/3" {"key" 3}
"complexfn/hello/key" "hello"
"pattern/fooandbar" ["fooandbar" "foo" "bar"]
"seq" [0 1 2]))
(deftest test-404
(is (= 404 (:status (handler {:uri "/null" :request-method :get})))))
(deftest testrest
(are [req result]
(= result (object-from-request req))
{:uri "rest"
:request-method :post
:req-key [1 <KEY> 3]} [1 2 3]
{:uri "rest"
:request-method :delete} "deleted"))
(deftest testerror
(let [result (handler {:uri "list/5" :request-method :get})]
(is (= (:status result) 500))
(is (= (:headers result) {"Content-Type" "text/plain"}))
(is (re-matches #".*IndexOutOfBoundsException.*"
(-> result :body split-lines first)))))
(deftest test-delay
(let [delay-calls-init @delay-calls]
(doseq [n (range 1 100)]
(is (= (+ n delay-calls-init)
(object-from-uri "rest-delay"))))))
| true | (ns restfn.test
(:import (java.util ArrayList))
(:use (clojure test)
(clojure [string :only [split-lines]])
(restfn core)
(cheshire [core :only [parse-string]])))
(extend-type java.util.regex.Pattern
RestSerializable
(rest-serialize [r] #(re-matches r %)))
(def delay-calls (atom 0))
(def handler
(get-rest-handler
{"list" [1 3 5]
"map" {"foo" "bar"}
"atom" (atom 5)
"doubleatom" (atom (atom 7))
"javalist" (ArrayList. [5 9 7])
"simplefn" inc
"complexfn" (fn [x] {"key" x})
"pattern" #"(.*)and(.*)"
"seq" (for [x (range 3)]
(reify RestSerializable (rest-serialize [_] x)))
"rest-delay" (rest-delay (swap! delay-calls inc))
"rest" {:post (fn [req] (:req-key req))
:delete (fn [] "deleted")}}))
(defn object-from-request [req]
(let [res (handler req)]
(is (= (:status res) 200) res)
(is (= (:headers res) {"Content-Type" "application/json"}) res)
(parse-string (:body res))))
(defn object-from-uri [uri]
(object-from-request {:uri uri :request-method :get}))
(deftest simplegets
(are [uri result]
(= result (object-from-uri uri))
"list" [1 3 5]
"/list/" [1 3 5]
"/list/0" 1
"/list/1" 3
"atom" 5
"doubleatom" 7
"map" {"foo" "bar"}
"map/foo" "bar"
"javalist/" [5 9 7]
"javalist/0" 5
"simplefn/5" 6
"complexfn/3" {"key" 3}
"complexfn/hello/key" "hello"
"pattern/fooandbar" ["fooandbar" "foo" "bar"]
"seq" [0 1 2]))
(deftest test-404
(is (= 404 (:status (handler {:uri "/null" :request-method :get})))))
(deftest testrest
(are [req result]
(= result (object-from-request req))
{:uri "rest"
:request-method :post
:req-key [1 PI:KEY:<KEY>END_PI 3]} [1 2 3]
{:uri "rest"
:request-method :delete} "deleted"))
(deftest testerror
(let [result (handler {:uri "list/5" :request-method :get})]
(is (= (:status result) 500))
(is (= (:headers result) {"Content-Type" "text/plain"}))
(is (re-matches #".*IndexOutOfBoundsException.*"
(-> result :body split-lines first)))))
(deftest test-delay
(let [delay-calls-init @delay-calls]
(doseq [n (range 1 100)]
(is (= (+ n delay-calls-init)
(object-from-uri "rest-delay"))))))
|
[
{
"context": "stgresql://localhost/postgres?user=orbis&password=orbis\"\r\n ;;optional, will use internal table otherwise",
"end": 104,
"score": 0.9993428587913513,
"start": 99,
"tag": "PASSWORD",
"value": "orbis"
}
] | profiles.clj | Orbisnetworkadmin/orbis-grcmanager | 0 | {:profiles/dev
{:env
{:database-url "jdbc:postgresql://localhost/postgres?user=orbis&password=orbis"
;;optional, will use internal table otherwise
}}} | 58688 | {:profiles/dev
{:env
{:database-url "jdbc:postgresql://localhost/postgres?user=orbis&password=<PASSWORD>"
;;optional, will use internal table otherwise
}}} | true | {:profiles/dev
{:env
{:database-url "jdbc:postgresql://localhost/postgres?user=orbis&password=PI:PASSWORD:<PASSWORD>END_PI"
;;optional, will use internal table otherwise
}}} |
[
{
"context": " :username (System/getenv \"CLOJARS_USER\")\n :password (",
"end": 584,
"score": 0.6606954336166382,
"start": 575,
"tag": "USERNAME",
"value": "JARS_USER"
},
{
"context": " :password (System/getenv \"CLOJARS_PASS\")}]))\n\n(require '[adzerk.boot-cljs :refer [cljs]]",
"end": 661,
"score": 0.9958862066268921,
"start": 649,
"tag": "PASSWORD",
"value": "CLOJARS_PASS"
},
{
"context": "oring for Node.js\"\n :url \"https://github.com/johan-sports/busboy\"\n :license {\"MIT\" \"https://github.com",
"end": 994,
"score": 0.9977256655693054,
"start": 982,
"tag": "USERNAME",
"value": "johan-sports"
},
{
"context": "busboy\"\n :license {\"MIT\" \"https://github.com/johan-sports/busboy/blob/master/LICENSE\"}}\n push {:tag true\n ",
"end": 1057,
"score": 0.9936850666999817,
"start": 1045,
"tag": "USERNAME",
"value": "johan-sports"
}
] | build.boot | johan-sports/busboy | 2 | (set-env!
:source-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.8.0" :scope "test"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/core.async "0.2.385"]
[adzerk/boot-cljs "1.7.228-1" :scope "test"]
[crisptrutski/boot-cljs-test "0.3.1" :scope "test"]
[degree9/boot-npm "1.4.0" :scope "test"]]
:repositories #(conj % ["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "CLOJARS_PASS")}]))
(require '[adzerk.boot-cljs :refer [cljs]]
'[crisptrutski.boot-cljs-test :refer [test-cljs]]
'[degree9.boot-npm :refer [npm]])
(task-options!
pom {:project 'johan-sports/busboy
:version "0.1.0"
:description "Clojurescript USB monitoring for Node.js"
:url "https://github.com/johan-sports/busboy"
:license {"MIT" "https://github.com/johan-sports/busboy/blob/master/LICENSE"}}
push {:tag true
:ensure-branch "master"
:ensure-release true
:ensure-clean true
:repo "clojars"})
(deftask testing []
(merge-env! :source-paths #{"test"})
identity)
(deftask test []
(comp
(testing)
(test-cljs)))
(deftask build
"Install dependencies and compile to a JS file."
[]
(comp
(npm :install {:subdevil "0.1.0"})
(cljs :optimizations :advanced
:compiler-options {:target :nodejs
:infer-externs true})
(target)))
(deftask package
"Package in to a JAR file."
[]
(comp
(build)
(pom)
(jar)))
| 13984 | (set-env!
:source-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.8.0" :scope "test"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/core.async "0.2.385"]
[adzerk/boot-cljs "1.7.228-1" :scope "test"]
[crisptrutski/boot-cljs-test "0.3.1" :scope "test"]
[degree9/boot-npm "1.4.0" :scope "test"]]
:repositories #(conj % ["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "<PASSWORD>")}]))
(require '[adzerk.boot-cljs :refer [cljs]]
'[crisptrutski.boot-cljs-test :refer [test-cljs]]
'[degree9.boot-npm :refer [npm]])
(task-options!
pom {:project 'johan-sports/busboy
:version "0.1.0"
:description "Clojurescript USB monitoring for Node.js"
:url "https://github.com/johan-sports/busboy"
:license {"MIT" "https://github.com/johan-sports/busboy/blob/master/LICENSE"}}
push {:tag true
:ensure-branch "master"
:ensure-release true
:ensure-clean true
:repo "clojars"})
(deftask testing []
(merge-env! :source-paths #{"test"})
identity)
(deftask test []
(comp
(testing)
(test-cljs)))
(deftask build
"Install dependencies and compile to a JS file."
[]
(comp
(npm :install {:subdevil "0.1.0"})
(cljs :optimizations :advanced
:compiler-options {:target :nodejs
:infer-externs true})
(target)))
(deftask package
"Package in to a JAR file."
[]
(comp
(build)
(pom)
(jar)))
| true | (set-env!
:source-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.8.0" :scope "test"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/core.async "0.2.385"]
[adzerk/boot-cljs "1.7.228-1" :scope "test"]
[crisptrutski/boot-cljs-test "0.3.1" :scope "test"]
[degree9/boot-npm "1.4.0" :scope "test"]]
:repositories #(conj % ["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "PI:PASSWORD:<PASSWORD>END_PI")}]))
(require '[adzerk.boot-cljs :refer [cljs]]
'[crisptrutski.boot-cljs-test :refer [test-cljs]]
'[degree9.boot-npm :refer [npm]])
(task-options!
pom {:project 'johan-sports/busboy
:version "0.1.0"
:description "Clojurescript USB monitoring for Node.js"
:url "https://github.com/johan-sports/busboy"
:license {"MIT" "https://github.com/johan-sports/busboy/blob/master/LICENSE"}}
push {:tag true
:ensure-branch "master"
:ensure-release true
:ensure-clean true
:repo "clojars"})
(deftask testing []
(merge-env! :source-paths #{"test"})
identity)
(deftask test []
(comp
(testing)
(test-cljs)))
(deftask build
"Install dependencies and compile to a JS file."
[]
(comp
(npm :install {:subdevil "0.1.0"})
(cljs :optimizations :advanced
:compiler-options {:target :nodejs
:infer-externs true})
(target)))
(deftask package
"Package in to a JAR file."
[]
(comp
(build)
(pom)
(jar)))
|
[
{
"context": "tp://test.test/data\"\n :username \"dude\"\n :password \"sweet\"}]\n (wit",
"end": 666,
"score": 0.9996689558029175,
"start": 662,
"tag": "USERNAME",
"value": "dude"
},
{
"context": " :username \"dude\"\n :password \"sweet\"}]\n (with-fake-routes {(:login-url config)\n ",
"end": 702,
"score": 0.9994247555732727,
"start": 697,
"tag": "PASSWORD",
"value": "sweet"
}
] | test/birthday_bot/parser_test.clj | MarinoPoletine/birthday_slack_bot | 0 | (ns birthday_slack_bot.parser-test
(:require [clojure.test :refer :all]
[birthday_slack_bot.parser :refer :all]
[clj-http.client :as client])
(:use clj-http.fake))
(deftest get-day-test
(testing "get-day returns in proper format"
(is (re-matches (re-pattern (str "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|"
"Sep|Oct|Nov|Dec)-[1-9][0-9]?"))
(get-day)))))
(deftest get-page-test
(testing "get-page makes expected http calls to configured URLs"
(let [config {:login-url "http://test.test/login"
:url "http://test.test/data"
:username "dude"
:password "sweet"}]
(with-fake-routes {(:login-url config)
{:post (fn [request] {:status 200
:headers {}
:body "Logged in"})}
(:url config)
(fn [request] {:status 200
:headers {}
:body "Some data"})}
(is (= (:body (get-page config)) "Some data"))))))
(deftest get-people-test
(let [data {:body (str "<p><strong>JANUARY</strong></p><div>"
"<table class=\"confluenceTable\"><tbody><tr>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Single Person</td><td colspan=\"1\" "
"class=\"confluenceTd\">Jan-4</td></tr><tr>"
"<td class=\"confluenceTd\"><p>Person 1 &"
"</p><p>Person 2 &</p><p>Person 3</p></td>"
"<td class=\"confluenceTd\"><p>Jan-5</p></td></tr>"
"<tr><td colspan=\"1\" class=\"confluenceTd\">"
"Person 1 & <span>Person 2</span></td>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Jan-6</td></tr>"
"</tbody></table></div>")}]
(testing "get-people with a single person's birthday"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-4")}
#(is (= (get-people {}) "Single Person"))))
(testing "get-people with a multiple people's birthdays"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-5")}
#(is (= (get-people {}) (str "Person 1 & Person 2 & Person 3")))))
(testing "get-people with a two people's birthdays on same line"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-6")}
#(is (= (get-people {}) (str "Person 1 & Person 2")))))))
| 119867 | (ns birthday_slack_bot.parser-test
(:require [clojure.test :refer :all]
[birthday_slack_bot.parser :refer :all]
[clj-http.client :as client])
(:use clj-http.fake))
(deftest get-day-test
(testing "get-day returns in proper format"
(is (re-matches (re-pattern (str "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|"
"Sep|Oct|Nov|Dec)-[1-9][0-9]?"))
(get-day)))))
(deftest get-page-test
(testing "get-page makes expected http calls to configured URLs"
(let [config {:login-url "http://test.test/login"
:url "http://test.test/data"
:username "dude"
:password "<PASSWORD>"}]
(with-fake-routes {(:login-url config)
{:post (fn [request] {:status 200
:headers {}
:body "Logged in"})}
(:url config)
(fn [request] {:status 200
:headers {}
:body "Some data"})}
(is (= (:body (get-page config)) "Some data"))))))
(deftest get-people-test
(let [data {:body (str "<p><strong>JANUARY</strong></p><div>"
"<table class=\"confluenceTable\"><tbody><tr>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Single Person</td><td colspan=\"1\" "
"class=\"confluenceTd\">Jan-4</td></tr><tr>"
"<td class=\"confluenceTd\"><p>Person 1 &"
"</p><p>Person 2 &</p><p>Person 3</p></td>"
"<td class=\"confluenceTd\"><p>Jan-5</p></td></tr>"
"<tr><td colspan=\"1\" class=\"confluenceTd\">"
"Person 1 & <span>Person 2</span></td>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Jan-6</td></tr>"
"</tbody></table></div>")}]
(testing "get-people with a single person's birthday"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-4")}
#(is (= (get-people {}) "Single Person"))))
(testing "get-people with a multiple people's birthdays"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-5")}
#(is (= (get-people {}) (str "Person 1 & Person 2 & Person 3")))))
(testing "get-people with a two people's birthdays on same line"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-6")}
#(is (= (get-people {}) (str "Person 1 & Person 2")))))))
| true | (ns birthday_slack_bot.parser-test
(:require [clojure.test :refer :all]
[birthday_slack_bot.parser :refer :all]
[clj-http.client :as client])
(:use clj-http.fake))
(deftest get-day-test
(testing "get-day returns in proper format"
(is (re-matches (re-pattern (str "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|"
"Sep|Oct|Nov|Dec)-[1-9][0-9]?"))
(get-day)))))
(deftest get-page-test
(testing "get-page makes expected http calls to configured URLs"
(let [config {:login-url "http://test.test/login"
:url "http://test.test/data"
:username "dude"
:password "PI:PASSWORD:<PASSWORD>END_PI"}]
(with-fake-routes {(:login-url config)
{:post (fn [request] {:status 200
:headers {}
:body "Logged in"})}
(:url config)
(fn [request] {:status 200
:headers {}
:body "Some data"})}
(is (= (:body (get-page config)) "Some data"))))))
(deftest get-people-test
(let [data {:body (str "<p><strong>JANUARY</strong></p><div>"
"<table class=\"confluenceTable\"><tbody><tr>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Single Person</td><td colspan=\"1\" "
"class=\"confluenceTd\">Jan-4</td></tr><tr>"
"<td class=\"confluenceTd\"><p>Person 1 &"
"</p><p>Person 2 &</p><p>Person 3</p></td>"
"<td class=\"confluenceTd\"><p>Jan-5</p></td></tr>"
"<tr><td colspan=\"1\" class=\"confluenceTd\">"
"Person 1 & <span>Person 2</span></td>"
"<td colspan=\"1\" class=\"confluenceTd\">"
"Jan-6</td></tr>"
"</tbody></table></div>")}]
(testing "get-people with a single person's birthday"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-4")}
#(is (= (get-people {}) "Single Person"))))
(testing "get-people with a multiple people's birthdays"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-5")}
#(is (= (get-people {}) (str "Person 1 & Person 2 & Person 3")))))
(testing "get-people with a two people's birthdays on same line"
(with-redefs-fn {#'birthday_slack_bot.parser/get-page (fn [config] data)
#'birthday_slack_bot.parser/get-day (fn [] "Jan-6")}
#(is (= (get-people {}) (str "Person 1 & Person 2")))))))
|
[
{
"context": " \"passing a vector as a function argument\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 690,
"score": 0.9998307228088379,
"start": 677,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "ctor as a function argument\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 704,
"score": 0.9998369216918945,
"start": 692,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": " (a (def john (merge person-class {:first-name \"John\" :last-name \"Smith\"})))\n (a (= ((:get-full-name ",
"end": 1172,
"score": 0.9997919201850891,
"start": 1168,
"tag": "NAME",
"value": "John"
},
{
"context": "rge person-class {:first-name \"John\" :last-name \"Smith\"})))\n (a (= ((:get-full-name john) john) \"John S",
"end": 1191,
"score": 0.9997427463531494,
"start": 1186,
"tag": "NAME",
"value": "Smith"
},
{
"context": "\"Smith\"})))\n (a (= ((:get-full-name john) john) \"John Smith\"))\n (a \"added bonus - prototype-based inheritanc",
"end": 1245,
"score": 0.9994286298751831,
"start": 1235,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " free!\")\n (a (def mary (merge john {:first-name \"Mary\"})))\n (a (= ((:get-full-name mary) mary) \"Mary S",
"end": 1354,
"score": 0.999626636505127,
"start": 1350,
"tag": "NAME",
"value": "Mary"
},
{
"context": " \"Mary\"})))\n (a (= ((:get-full-name mary) mary) \"Mary Smith\"))\n (m \"https://stackoverflow.com/questions/5024",
"end": 1408,
"score": 0.9997066855430603,
"start": 1398,
"tag": "NAME",
"value": "Mary Smith"
},
{
"context": " arguments\")\n (a (= ((fnth 3 )[1 2 3]) 3))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 2834,
"score": 0.9998586773872375,
"start": 2821,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": " (a (= ((fnth 3 )[1 2 3]) 3))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 2848,
"score": 0.9998647570610046,
"start": 2836,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "ely\")\n (a (= ((partial + 5) 100 200) 305))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 3192,
"score": 0.9998899698257446,
"start": 3179,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "((partial + 5) 100 200) 305))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 3206,
"score": 0.9998001456260681,
"start": 3194,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "ions serially to the return of the former\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 3525,
"score": 0.9998951554298401,
"start": 3512,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "to the return of the former\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 3539,
"score": 0.9997775554656982,
"start": 3527,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "}]) [{:x 1 :y 3} {:x 1 :y 2} {:x 1 :y 1}]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 3955,
"score": 0.9998863339424133,
"start": 3942,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "3} {:x 1 :y 2} {:x 1 :y 1}]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 3969,
"score": 0.9997969269752502,
"start": 3957,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "5) 100 200) (#(apply + 5 %&) 100 200) 305))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 4195,
"score": 0.99989253282547,
"start": 4182,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "(apply + 5 %&) 100 200) 305))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 4209,
"score": 0.9997782707214355,
"start": 4197,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "lue and returns the opposite truthy value\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 5348,
"score": 0.9997639060020447,
"start": 5335,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "s the opposite truthy value\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 5362,
"score": 0.9998249411582947,
"start": 5350,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "((comp not even?) 1) (#(not (even? %)) 1)))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 5596,
"score": 0.9997789859771729,
"start": 5583,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "n?) 1) (#(not (even? %)) 1)))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 5610,
"score": 0.9998331069946289,
"start": 5598,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "oo) \"foo\")))} [] \"foo\"))\n (a (test #'foo))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 5932,
"score": 0.9998905658721924,
"start": 5919,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "[] \"foo\"))\n (a (test #'foo))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 5946,
"score": 0.9998414516448975,
"start": 5934,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "\") {:something true :something-else true}))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 6365,
"score": 0.9998897314071655,
"start": 6352,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": " true :something-else true}))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 6379,
"score": 0.9998257756233215,
"start": 6367,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "3] [:b 2] [:c 1]]) [[:c 1] [:b 2] [:a 3]]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 6803,
"score": 0.9998897314071655,
"start": 6790,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "1]]) [[:c 1] [:b 2] [:a 3]]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 6817,
"score": 0.9998419880867004,
"start": 6805,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": " 1 :z 3}{:x 2 :y 2 :z 1}{:x 2 :y 3 :z 2}]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 7377,
"score": 0.9998912811279297,
"start": 7364,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": ":y 2 :z 1}{:x 2 :y 3 :z 2}]))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 7391,
"score": 0.9998728632926941,
"start": 7379,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "lope :p2 [2 1]) 0.5))\n (a (= (slope) 1.0))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 7751,
"score": 0.9998883008956909,
"start": 7738,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": ") 0.5))\n (a (= (slope) 1.0))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 7765,
"score": 0.999861478805542,
"start": 7753,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "ters?\")\n (a \"the destructuring mechanism\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 7961,
"score": 0.9998906254768372,
"start": 7948,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "the destructuring mechanism\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 7975,
"score": 0.9998717308044434,
"start": 7963,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": ".lang.AssertionError)\n (a (= (foo 2 1) 2))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 8287,
"score": 0.9998940229415894,
"start": 8274,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "nError)\n (a (= (foo 2 1) 2))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 8301,
"score": 0.9998657703399658,
"start": 8289,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "(a \"- but after the namespace declaration\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 8607,
"score": 0.9998920559883118,
"start": 8594,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "r the namespace declaration\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 8621,
"score": 0.9998652935028076,
"start": 8609,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": ".lang.AssertionError)\n (a (= (foo 2 1) 2))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 8947,
"score": 0.9998812079429626,
"start": 8934,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "nError)\n (a (= (foo 2 1) 2))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 8961,
"score": 0.9998471736907959,
"start": 8949,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "alanced-diet put-things {:fruit \"apple\"})))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 9542,
"score": 0.9998950958251953,
"start": 9529,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "ut-things {:fruit \"apple\"})))\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 9556,
"score": 0.9998838305473328,
"start": 9544,
"tag": "NAME",
"value": "Chris Houser"
},
{
"context": "contract its interposition is transparent\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Funct",
"end": 10001,
"score": 0.9998910427093506,
"start": 9988,
"tag": "NAME",
"value": "Michael Fogus"
},
{
"context": "nterposition is transparent\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all th",
"end": 10015,
"score": 0.9998838305473328,
"start": 10003,
"tag": "NAME",
"value": "Chris Houser"
}
] | src/test/clojure/pl/tomaszgigiel/quizzes/packs/joc/joc_07_01_test.clj | tomaszgigiel/quizzes | 1 | (ns pl.tomaszgigiel.quizzes.packs.joc.joc-07-01-test
(:require [clojure.test :as tst])
(:require [uncomplicate.fluokitten.core :as fluokitten])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "Show that complex types are functions of their elements.")
(a (= ([:a :b] 0) :a) "vector is a function, index 0 is an argument")
(a (= (map [:a :b :c :d :e] [0 2 4]) [:a :c :e]) "passing a vector as a function argument")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 136"))
(qam
(q "Create custom dynamic OO system")
(a "define a prototype instance to serve as your class")
(a "use this to define your methods, plus any default values")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a "define an instance by merging member variables into the class")
(a (def john (merge person-class {:first-name "John" :last-name "Smith"})))
(a (= ((:get-full-name john) john) "John Smith"))
(a "added bonus - prototype-based inheritance for free!")
(a (def mary (merge john {:first-name "Mary"})))
(a (= ((:get-full-name mary) mary) "Mary Smith"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Create a closure (function)")
(a (defn messenger-builder [greeting] (fn [who] (str greeting who))) "closes over greeting")
(a (def hello-er (messenger-builder "Hello ")) "greeting provided here, then goes out of scope")
(a (= (hello-er "world!") "Hello world!") "greeting value still available because hello-er is a closure")
(m "https://clojure.org/guides/learn/functions#_locals_and_closures"))
(qam
(q "Create a closure (atom)")
(a (def foo (let [counter (atom 0)] (fn [] (do (swap! counter inc) @counter)))) "closes over counter, counter goes out of scope")
(a (= (foo) 1) "counter value still available because foo is a closure")
(a (= (foo) 2) "foo holds a reference to counter")
(a (= (foo) 3) "counter will not be garbage-collected as long as foo is needed")
(m "https://stackoverflow.com/questions/14874970/clojure-closure"))
(qam
(q "Create function using composition.")
(a (= ((comp first rest rest) [1 2 3]) 3) "built from existing parts using the comp (compose) function")
(a (= (def third (comp first rest rest))))
(a (= (third [1 2 3]) 3))
(a (defn fnth [n] (apply comp (cons first (take (dec n) (repeat rest))))) "the function fnth builds new functions on the fly based on its arguments")
(a (= ((fnth 3 )[1 2 3]) 3))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 137"))
(qam
(q "When are more than one open parenthesis in a row?")
(a (= ((comp first rest rest) [1 2 3]) 3) "it is almost always because a function is creating and returning a function that is called immediately")
(a (= ((partial + 5) 100 200) 305))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "When to use the comp (compose) function?")
(a (= (map (comp keyword #(.toLowerCase %) name) '(a B C)) '(:a :b :c)) "if you need a function that applies a number of functions serially to the return of the former")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Create function using partial function.")
(a (= ((partial + 5) 100 200) 305) "built from the partial application of another function")
(a (def sort-by-some-ratio (partial sort-by #(/ (:x %) (:y %)))))
(a (= (sort-by-some-ratio [{:x 1 :y 1} {:x 1 :y 2} {:x 1 :y 3}]) [{:x 1 :y 3} {:x 1 :y 2} {:x 1 :y 1}]))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Write equivalent to ((partial + 5) 100 200) with apply.")
(a (= ((partial + 5) 100 200) (#(apply + 5 %&) 100 200) 305))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to implement currying in clojure?")
(a (= ((defn add [a b c] (+ a b c)) 1 2 3) 6) "the function")
(a (= ((((defn add-curried [a] (fn [b] (fn [c] (+ a b c)))) 1) 2) 3) 6) "the curried version")
(m "https://stackoverflow.com/questions/36314/what-is-currying")
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure"))
(qam
(q "How to implement automatic currying in clojure?")
(a "use Fluokitten")
(a "e.g. [uncomplicate/fluokitten \"0.9.1\"]")
(a "(:require [uncomplicate.fluokitten.core :as fluokitten])")
(a "(curry f)")
(a "(curry f arity)")
(a (= ((((fluokitten/curry + 3) 1) 2) 3) 6))
(a (= ((fluokitten/curry +) 1 2 3) 6))
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")
(m "https://fluokitten.uncomplicate.org/codox/uncomplicate.fluokitten.core.html#var-curry"))
(qam
(q "Create function using complement.")
(a ((complement even?) 1) "takes a function that returns a truthy value and returns the opposite truthy value")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Write equivalent to (complement even?) 2) with comp.")
(a (= ((complement even?) 1) ((comp not even?) 1) (#(not (even? %)) 1)))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example that a function is data.")
(a "clojure.test stores and validates unit tests in the metadata of a var holding a function")
(a (defn foo {:test (fn [] (assert (= (foo) "foo")))} [] "foo"))
(a (test #'foo))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to assign metadata to a function using the defn macro?")
(a (defn foo {:something true :something-else true} [] "foo"))
(a (defn ^:something ^:something-else foo [] "foo"))
(a (defn ^{:something true, :something-else true} foo [] "foo"))
(a (defn foo ([] "foo") {:something true :something-else true}))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example use of functions as argument")
(a (= (map second [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (reduce #(conj %1 (second %2)) [] [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (filter #(-> % second odd?) [[:a 3] [:b 2] [:c 1]]) [[:a 3] [:c 1]]))
(a (= (sort-by second [[:a 3] [:b 2] [:c 1]]) [[:c 1] [:b 2] [:a 3]]))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 141"))
(qam
(q "Sort rows based on selected columns.")
(a (defn columns [column-names] (fn [row] (vec (map row column-names)))))
(a (= ((columns [:x :z]) {:x 1 :y 2 :z 3}) [1 3]))
(a (= (compare [1 3] [2 3]) -1) "vector is a closure function, so it implements the java.util.Comparator interface")
(a "sort-by uses compare")
(a (= (sort-by (columns [:x :z]) [{:x 2 :y 3 :z 2}{:x 2 :y 2 :z 1}{:x 1 :y 1 :z 3}]) [{:x 1 :y 1 :z 3}{:x 2 :y 2 :z 1}{:x 2 :y 3 :z 2}]))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 143"))
(qam
(q "Example of a function with named arguments.")
(a (defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}] (float (/ (- (p2 1) (p1 1)) (- (p2 0) (p1 0))))))
(a (= (slope :p1 [4 15] :p2 [3 21]) -6.0))
(a (= (slope :p2 [2 1]) 0.5))
(a (= (slope) 1.0))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "Which mechanism forms the basis for named parameters?")
(a "the destructuring mechanism")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to constrain function with pre- or postconditions?")
(a (defn foo [a b] {:pre [(int? a) (int? b) (not= b 0)] :post [(even? %)]} (/ a b)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to turn off :pre and :post checks for a specific file?")
(a "- add the line (set! *assert* false) to a source file")
(a "- somewhere near the top")
(a "- but after the namespace declaration")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "How to use assert instead pre- or postconditions?")
(a (defn foo [a b] (assert (and (int? a) (int? b) (not= b 0))) (let [r (/ a b)] (assert (even? r)) r)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "Example of decoupling assertions from functions.")
(a (defn put-things [m] (into m {:meat "beef" :veggie "broccoli"})))
(a (defn vegan-constraints [f m] {:pre [(:veggie m)] :post [(:veggie %) (nil? (:meat %))]} (f m)))
(at (vegan-constraints put-things {:fruit "apple"}) java.lang.AssertionError)
(a (defn balanced-diet [f m] {:post [(:meat %) (:veggie %)]} (f m)))
(a (= {:fruit "apple" :meat "beef" :veggie "broccoli"} (balanced-diet put-things {:fruit "apple"})))
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "What is main adventage of pulling out the assertions into a wrapper function?")
(a "you detach some domain-specific requirements from a potentially globally useful function and isolate them in aspects")
(a "you can mix in any implementation you please, knowing that as long as it fulfills the contract its interposition is transparent")
(m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 148"))
| 91074 | (ns pl.tomaszgigiel.quizzes.packs.joc.joc-07-01-test
(:require [clojure.test :as tst])
(:require [uncomplicate.fluokitten.core :as fluokitten])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "Show that complex types are functions of their elements.")
(a (= ([:a :b] 0) :a) "vector is a function, index 0 is an argument")
(a (= (map [:a :b :c :d :e] [0 2 4]) [:a :c :e]) "passing a vector as a function argument")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 136"))
(qam
(q "Create custom dynamic OO system")
(a "define a prototype instance to serve as your class")
(a "use this to define your methods, plus any default values")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a "define an instance by merging member variables into the class")
(a (def john (merge person-class {:first-name "<NAME>" :last-name "<NAME>"})))
(a (= ((:get-full-name john) john) "<NAME>"))
(a "added bonus - prototype-based inheritance for free!")
(a (def mary (merge john {:first-name "<NAME>"})))
(a (= ((:get-full-name mary) mary) "<NAME>"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Create a closure (function)")
(a (defn messenger-builder [greeting] (fn [who] (str greeting who))) "closes over greeting")
(a (def hello-er (messenger-builder "Hello ")) "greeting provided here, then goes out of scope")
(a (= (hello-er "world!") "Hello world!") "greeting value still available because hello-er is a closure")
(m "https://clojure.org/guides/learn/functions#_locals_and_closures"))
(qam
(q "Create a closure (atom)")
(a (def foo (let [counter (atom 0)] (fn [] (do (swap! counter inc) @counter)))) "closes over counter, counter goes out of scope")
(a (= (foo) 1) "counter value still available because foo is a closure")
(a (= (foo) 2) "foo holds a reference to counter")
(a (= (foo) 3) "counter will not be garbage-collected as long as foo is needed")
(m "https://stackoverflow.com/questions/14874970/clojure-closure"))
(qam
(q "Create function using composition.")
(a (= ((comp first rest rest) [1 2 3]) 3) "built from existing parts using the comp (compose) function")
(a (= (def third (comp first rest rest))))
(a (= (third [1 2 3]) 3))
(a (defn fnth [n] (apply comp (cons first (take (dec n) (repeat rest))))) "the function fnth builds new functions on the fly based on its arguments")
(a (= ((fnth 3 )[1 2 3]) 3))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 137"))
(qam
(q "When are more than one open parenthesis in a row?")
(a (= ((comp first rest rest) [1 2 3]) 3) "it is almost always because a function is creating and returning a function that is called immediately")
(a (= ((partial + 5) 100 200) 305))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "When to use the comp (compose) function?")
(a (= (map (comp keyword #(.toLowerCase %) name) '(a B C)) '(:a :b :c)) "if you need a function that applies a number of functions serially to the return of the former")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Create function using partial function.")
(a (= ((partial + 5) 100 200) 305) "built from the partial application of another function")
(a (def sort-by-some-ratio (partial sort-by #(/ (:x %) (:y %)))))
(a (= (sort-by-some-ratio [{:x 1 :y 1} {:x 1 :y 2} {:x 1 :y 3}]) [{:x 1 :y 3} {:x 1 :y 2} {:x 1 :y 1}]))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Write equivalent to ((partial + 5) 100 200) with apply.")
(a (= ((partial + 5) 100 200) (#(apply + 5 %&) 100 200) 305))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to implement currying in clojure?")
(a (= ((defn add [a b c] (+ a b c)) 1 2 3) 6) "the function")
(a (= ((((defn add-curried [a] (fn [b] (fn [c] (+ a b c)))) 1) 2) 3) 6) "the curried version")
(m "https://stackoverflow.com/questions/36314/what-is-currying")
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure"))
(qam
(q "How to implement automatic currying in clojure?")
(a "use Fluokitten")
(a "e.g. [uncomplicate/fluokitten \"0.9.1\"]")
(a "(:require [uncomplicate.fluokitten.core :as fluokitten])")
(a "(curry f)")
(a "(curry f arity)")
(a (= ((((fluokitten/curry + 3) 1) 2) 3) 6))
(a (= ((fluokitten/curry +) 1 2 3) 6))
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")
(m "https://fluokitten.uncomplicate.org/codox/uncomplicate.fluokitten.core.html#var-curry"))
(qam
(q "Create function using complement.")
(a ((complement even?) 1) "takes a function that returns a truthy value and returns the opposite truthy value")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Write equivalent to (complement even?) 2) with comp.")
(a (= ((complement even?) 1) ((comp not even?) 1) (#(not (even? %)) 1)))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example that a function is data.")
(a "clojure.test stores and validates unit tests in the metadata of a var holding a function")
(a (defn foo {:test (fn [] (assert (= (foo) "foo")))} [] "foo"))
(a (test #'foo))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to assign metadata to a function using the defn macro?")
(a (defn foo {:something true :something-else true} [] "foo"))
(a (defn ^:something ^:something-else foo [] "foo"))
(a (defn ^{:something true, :something-else true} foo [] "foo"))
(a (defn foo ([] "foo") {:something true :something-else true}))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example use of functions as argument")
(a (= (map second [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (reduce #(conj %1 (second %2)) [] [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (filter #(-> % second odd?) [[:a 3] [:b 2] [:c 1]]) [[:a 3] [:c 1]]))
(a (= (sort-by second [[:a 3] [:b 2] [:c 1]]) [[:c 1] [:b 2] [:a 3]]))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 141"))
(qam
(q "Sort rows based on selected columns.")
(a (defn columns [column-names] (fn [row] (vec (map row column-names)))))
(a (= ((columns [:x :z]) {:x 1 :y 2 :z 3}) [1 3]))
(a (= (compare [1 3] [2 3]) -1) "vector is a closure function, so it implements the java.util.Comparator interface")
(a "sort-by uses compare")
(a (= (sort-by (columns [:x :z]) [{:x 2 :y 3 :z 2}{:x 2 :y 2 :z 1}{:x 1 :y 1 :z 3}]) [{:x 1 :y 1 :z 3}{:x 2 :y 2 :z 1}{:x 2 :y 3 :z 2}]))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 143"))
(qam
(q "Example of a function with named arguments.")
(a (defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}] (float (/ (- (p2 1) (p1 1)) (- (p2 0) (p1 0))))))
(a (= (slope :p1 [4 15] :p2 [3 21]) -6.0))
(a (= (slope :p2 [2 1]) 0.5))
(a (= (slope) 1.0))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "Which mechanism forms the basis for named parameters?")
(a "the destructuring mechanism")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to constrain function with pre- or postconditions?")
(a (defn foo [a b] {:pre [(int? a) (int? b) (not= b 0)] :post [(even? %)]} (/ a b)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to turn off :pre and :post checks for a specific file?")
(a "- add the line (set! *assert* false) to a source file")
(a "- somewhere near the top")
(a "- but after the namespace declaration")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "How to use assert instead pre- or postconditions?")
(a (defn foo [a b] (assert (and (int? a) (int? b) (not= b 0))) (let [r (/ a b)] (assert (even? r)) r)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "Example of decoupling assertions from functions.")
(a (defn put-things [m] (into m {:meat "beef" :veggie "broccoli"})))
(a (defn vegan-constraints [f m] {:pre [(:veggie m)] :post [(:veggie %) (nil? (:meat %))]} (f m)))
(at (vegan-constraints put-things {:fruit "apple"}) java.lang.AssertionError)
(a (defn balanced-diet [f m] {:post [(:meat %) (:veggie %)]} (f m)))
(a (= {:fruit "apple" :meat "beef" :veggie "broccoli"} (balanced-diet put-things {:fruit "apple"})))
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "What is main adventage of pulling out the assertions into a wrapper function?")
(a "you detach some domain-specific requirements from a potentially globally useful function and isolate them in aspects")
(a "you can mix in any implementation you please, knowing that as long as it fulfills the contract its interposition is transparent")
(m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 148"))
| true | (ns pl.tomaszgigiel.quizzes.packs.joc.joc-07-01-test
(:require [clojure.test :as tst])
(:require [uncomplicate.fluokitten.core :as fluokitten])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "Show that complex types are functions of their elements.")
(a (= ([:a :b] 0) :a) "vector is a function, index 0 is an argument")
(a (= (map [:a :b :c :d :e] [0 2 4]) [:a :c :e]) "passing a vector as a function argument")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 136"))
(qam
(q "Create custom dynamic OO system")
(a "define a prototype instance to serve as your class")
(a "use this to define your methods, plus any default values")
(a (def person-class {:get-full-name (fn [this] (str (:first-name this) " " (:last-name this)))}))
(a "define an instance by merging member variables into the class")
(a (def john (merge person-class {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})))
(a (= ((:get-full-name john) john) "PI:NAME:<NAME>END_PI"))
(a "added bonus - prototype-based inheritance for free!")
(a (def mary (merge john {:first-name "PI:NAME:<NAME>END_PI"})))
(a (= ((:get-full-name mary) mary) "PI:NAME:<NAME>END_PI"))
(m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol"))
(qam
(q "Create a closure (function)")
(a (defn messenger-builder [greeting] (fn [who] (str greeting who))) "closes over greeting")
(a (def hello-er (messenger-builder "Hello ")) "greeting provided here, then goes out of scope")
(a (= (hello-er "world!") "Hello world!") "greeting value still available because hello-er is a closure")
(m "https://clojure.org/guides/learn/functions#_locals_and_closures"))
(qam
(q "Create a closure (atom)")
(a (def foo (let [counter (atom 0)] (fn [] (do (swap! counter inc) @counter)))) "closes over counter, counter goes out of scope")
(a (= (foo) 1) "counter value still available because foo is a closure")
(a (= (foo) 2) "foo holds a reference to counter")
(a (= (foo) 3) "counter will not be garbage-collected as long as foo is needed")
(m "https://stackoverflow.com/questions/14874970/clojure-closure"))
(qam
(q "Create function using composition.")
(a (= ((comp first rest rest) [1 2 3]) 3) "built from existing parts using the comp (compose) function")
(a (= (def third (comp first rest rest))))
(a (= (third [1 2 3]) 3))
(a (defn fnth [n] (apply comp (cons first (take (dec n) (repeat rest))))) "the function fnth builds new functions on the fly based on its arguments")
(a (= ((fnth 3 )[1 2 3]) 3))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 137"))
(qam
(q "When are more than one open parenthesis in a row?")
(a (= ((comp first rest rest) [1 2 3]) 3) "it is almost always because a function is creating and returning a function that is called immediately")
(a (= ((partial + 5) 100 200) 305))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "When to use the comp (compose) function?")
(a (= (map (comp keyword #(.toLowerCase %) name) '(a B C)) '(:a :b :c)) "if you need a function that applies a number of functions serially to the return of the former")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Create function using partial function.")
(a (= ((partial + 5) 100 200) 305) "built from the partial application of another function")
(a (def sort-by-some-ratio (partial sort-by #(/ (:x %) (:y %)))))
(a (= (sort-by-some-ratio [{:x 1 :y 1} {:x 1 :y 2} {:x 1 :y 3}]) [{:x 1 :y 3} {:x 1 :y 2} {:x 1 :y 1}]))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 138"))
(qam
(q "Write equivalent to ((partial + 5) 100 200) with apply.")
(a (= ((partial + 5) 100 200) (#(apply + 5 %&) 100 200) 305))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to implement currying in clojure?")
(a (= ((defn add [a b c] (+ a b c)) 1 2 3) 6) "the function")
(a (= ((((defn add-curried [a] (fn [b] (fn [c] (+ a b c)))) 1) 2) 3) 6) "the curried version")
(m "https://stackoverflow.com/questions/36314/what-is-currying")
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure"))
(qam
(q "How to implement automatic currying in clojure?")
(a "use Fluokitten")
(a "e.g. [uncomplicate/fluokitten \"0.9.1\"]")
(a "(:require [uncomplicate.fluokitten.core :as fluokitten])")
(a "(curry f)")
(a "(curry f arity)")
(a (= ((((fluokitten/curry + 3) 1) 2) 3) 6))
(a (= ((fluokitten/curry +) 1 2 3) 6))
(m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")
(m "https://fluokitten.uncomplicate.org/codox/uncomplicate.fluokitten.core.html#var-curry"))
(qam
(q "Create function using complement.")
(a ((complement even?) 1) "takes a function that returns a truthy value and returns the opposite truthy value")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Write equivalent to (complement even?) 2) with comp.")
(a (= ((complement even?) 1) ((comp not even?) 1) (#(not (even? %)) 1)))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example that a function is data.")
(a "clojure.test stores and validates unit tests in the metadata of a var holding a function")
(a (defn foo {:test (fn [] (assert (= (foo) "foo")))} [] "foo"))
(a (test #'foo))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "How to assign metadata to a function using the defn macro?")
(a (defn foo {:something true :something-else true} [] "foo"))
(a (defn ^:something ^:something-else foo [] "foo"))
(a (defn ^{:something true, :something-else true} foo [] "foo"))
(a (defn foo ([] "foo") {:something true :something-else true}))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 139"))
(qam
(q "Example use of functions as argument")
(a (= (map second [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (reduce #(conj %1 (second %2)) [] [[:a 3] [:b 2] [:c 1]]) [3 2 1]))
(a (= (filter #(-> % second odd?) [[:a 3] [:b 2] [:c 1]]) [[:a 3] [:c 1]]))
(a (= (sort-by second [[:a 3] [:b 2] [:c 1]]) [[:c 1] [:b 2] [:a 3]]))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 141"))
(qam
(q "Sort rows based on selected columns.")
(a (defn columns [column-names] (fn [row] (vec (map row column-names)))))
(a (= ((columns [:x :z]) {:x 1 :y 2 :z 3}) [1 3]))
(a (= (compare [1 3] [2 3]) -1) "vector is a closure function, so it implements the java.util.Comparator interface")
(a "sort-by uses compare")
(a (= (sort-by (columns [:x :z]) [{:x 2 :y 3 :z 2}{:x 2 :y 2 :z 1}{:x 1 :y 1 :z 3}]) [{:x 1 :y 1 :z 3}{:x 2 :y 2 :z 1}{:x 2 :y 3 :z 2}]))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 143"))
(qam
(q "Example of a function with named arguments.")
(a (defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}] (float (/ (- (p2 1) (p1 1)) (- (p2 0) (p1 0))))))
(a (= (slope :p1 [4 15] :p2 [3 21]) -6.0))
(a (= (slope :p2 [2 1]) 0.5))
(a (= (slope) 1.0))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "Which mechanism forms the basis for named parameters?")
(a "the destructuring mechanism")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to constrain function with pre- or postconditions?")
(a (defn foo [a b] {:pre [(int? a) (int? b) (not= b 0)] :post [(even? %)]} (/ a b)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 146"))
(qam
(q "How to turn off :pre and :post checks for a specific file?")
(a "- add the line (set! *assert* false) to a source file")
(a "- somewhere near the top")
(a "- but after the namespace declaration")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "How to use assert instead pre- or postconditions?")
(a (defn foo [a b] (assert (and (int? a) (int? b) (not= b 0))) (let [r (/ a b)] (assert (even? r)) r)))
(at (foo 2 0) java.lang.AssertionError)
(a (= (foo 2 1) 2))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "Example of decoupling assertions from functions.")
(a (defn put-things [m] (into m {:meat "beef" :veggie "broccoli"})))
(a (defn vegan-constraints [f m] {:pre [(:veggie m)] :post [(:veggie %) (nil? (:meat %))]} (f m)))
(at (vegan-constraints put-things {:fruit "apple"}) java.lang.AssertionError)
(a (defn balanced-diet [f m] {:post [(:meat %) (:veggie %)]} (f m)))
(a (= {:fruit "apple" :meat "beef" :veggie "broccoli"} (balanced-diet put-things {:fruit "apple"})))
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 147"))
(qam
(q "What is main adventage of pulling out the assertions into a wrapper function?")
(a "you detach some domain-specific requirements from a potentially globally useful function and isolate them in aspects")
(a "you can mix in any implementation you please, knowing that as long as it fulfills the contract its interposition is transparent")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.1 Functions in all their forms, page 148"))
|
[
{
"context": "t\n (deal-among 4 (shuffle deck))\n\n (def names [\"allan\" \"adi\" \"quan\" \"lucy\"])\n (def players (-> names i",
"end": 6265,
"score": 0.9996861219406128,
"start": 6260,
"tag": "NAME",
"value": "allan"
},
{
"context": "l-among 4 (shuffle deck))\n\n (def names [\"allan\" \"adi\" \"quan\" \"lucy\"])\n (def players (-> names init-pl",
"end": 6271,
"score": 0.9968196749687195,
"start": 6268,
"tag": "NAME",
"value": "adi"
},
{
"context": "g 4 (shuffle deck))\n\n (def names [\"allan\" \"adi\" \"quan\" \"lucy\"])\n (def players (-> names init-players (",
"end": 6278,
"score": 0.9993744492530823,
"start": 6274,
"tag": "NAME",
"value": "quan"
},
{
"context": "uffle deck))\n\n (def names [\"allan\" \"adi\" \"quan\" \"lucy\"])\n (def players (-> names init-players (init-ha",
"end": 6285,
"score": 0.9991956949234009,
"start": 6281,
"tag": "NAME",
"value": "lucy"
}
] | src/hearts/core.cljs | jiangts/hearts-clojure | 0 | (ns hearts.core
(:require [cljs.core.match :refer-macros [match]]
[hearts.utils :as utils :refer [spy]]
[cljs.pprint :refer [pprint]]
[goog.string :as gstr])
(:require-macros [hearts.macros :refer [spy2]]))
;; ===== CREATE DATA ===== ;;
(def suits #{"H" "D" "S" "C"})
(def ranks (concat (map str (range 2 10)) ["T" "J" "Q" "K" "A"]))
(def deck (for [suit suits rank ranks]
(str rank suit)))
(def max-score 26)
(def card-scores
(let [hearts (for [rank ranks]
(str rank "H"))]
(-> hearts
(zipmap (repeat 1))
(assoc "QS" 13))))
(def has-some? (comp some? some))
;; ===== DECK OPERATIONS ===== ;;
(defn discard
"removes set of cards from deck"
[cards deck]
(remove cards deck))
(defn deal-among
"returns n hands with the same number of cards"
[n deck]
(let [hand-size (quot (count deck) n)]
(partition hand-size deck)))
;; ===== CARD OPERATIONS ===== ;;
(defn card->suit [[rank suit]]
suit)
(defn card->rank [[rank suit]]
rank)
;; ===== CONSTRUCT GAME STATE ===== ;;
(defn make-player [-name]
{:name -name :hand [] :taken [] :score 0})
(defn init-players [names]
(mapv make-player names))
(defn init-hands [players deck]
(let [n-players (count players)
hands (deal-among n-players (shuffle deck))]
(mapv #(assoc %1 :hand %2) players hands)))
;; {:ntrick 0
;; :turn 0 ;; player index. increment mod 4 or change when someone wins trick
;; :players [{:name "str"
;; :hand []
;; :taken []
;; :score 0}]
;; :trick []
;; }
(defn init-game-state [names]
{:ntrick 0
:turn 0
:players (-> names init-players (init-hands deck))
:trick []})
;; ===== HAND OPERATIONS ===== ;;
(defn trick-broken? [players]
(some (set (keys card-scores)) (mapcat :taken players)))
(defn trick-suit [trick]
(card->suit (first trick)))
(defn valid-move
"Each player must follow suit if possible. If a player is void of the suit led, a
card of any other suit may be discarded. However, if a player has no clubs
when the first trick is led, a heart or the queen of spades cannot be
discarded."
[card hand trick first?]
(let [suit #{(trick-suit trick)}
has-card? (some #{card} hand)
has-suit? (has-some? suit (map #(card->suit %) hand))
follows-suit? (has-some? suit (card->suit card))]
(if has-card?
(match [has-suit? follows-suit? first?]
[true true _] card
[true false _] (js/Error. "Card does not match suit.")
[false _ true] (if (has-some? #{card} (keys card-scores))
(js/Error. "Cannot discard heart or queen of spades on first trick.")
card)
[false _ false] card)
(js/Error. (str "You don't have " card " in your hand.")))))
(defn highest-of-suit [suit cards]
(let [rank-vals (zipmap ranks (range))]
(->> cards
(filter #(contains? #{suit} (card->suit %)))
(apply max-key #(rank-vals (card->rank %))))))
(defn trick-winner
"The highest card of the suit led wins a trick and the winner of
that trick leads next."
[trick leader]
(let [winning-card (highest-of-suit (trick-suit trick) trick)
card-index (.indexOf trick winning-card)]
(-> card-index
(+ leader)
(mod (count trick)))))
(defn starting-player [players]
(let [arr (map #(some #{"2C"} (:hand %)) players)]
(.indexOf arr "2C")))
;; ===== QUERIES ===== ;;
(defn trick-over? [{:keys [ntrick turn players trick] :as state}]
(= (count trick) (count players)))
(defn round-over? [{:keys [ntrick turn players trick] :as state}]
(= ntrick (count deck)))
(defn player-score [player]
(->> player
:taken
(map card-scores)
(apply +)))
(defn game-over? [state]
(>= (apply max (map :score (:players state)))
max-score))
(defn game-winner [state]
(apply min-key (into [:score] (:players state))))
;; ===== GAMEPLAY OPERATIONS ===== ;;
(defn start-game [state]
(assoc state :turn (starting-player (:players state))))
(defn next-turn [state]
(let [n-players (count (:players state))]
(-> state
(update :ntrick inc)
(update :turn #(-> % inc (mod n-players))))))
(defn shoot-moon? [players]
(.indexOf (map player-score players) (apply + (vals card-scores))))
(defn update-scores [players]
(map #(update % :score + (player-score %)) players))
(defn moonshot-update-scores [players shooter]
(as-> players p
(map #(update % :score + 26) p)
(update-in p [shooter :score] - 26)))
(defn clear-cards [player]
(-> player
(assoc :taken [])
(assoc :hand [])))
(defn next-round [state]
(-> state
(update :players #(let [shooter (shoot-moon? %)]
(if (< shooter 0)
(update-scores %)
(moonshot-update-scores % shooter))))
(update :players #(map clear-cards %))
(update :players init-hands deck)
(assoc :ntrick 0)))
(defn play-card [{:keys [ntrick turn players trick] :as state} card]
(let [player (get players turn)
hand (:hand player)
;; that's jank...
_ (when (and (not= card "2C") (= 0 ntrick (count trick)))
(throw (js/Error. "Must lead with 2C.")))
move (utils/throw-err (valid-move card hand trick (zero? ntrick)))
_ (when (and (contains? card-scores card) (not (trick-broken? players))
(zero? (count trick)))
(throw (js/Error. "Cannot lead with H or QS: Hearts not yet broken.")))]
(-> state
(update-in [:players turn :hand] #(discard #{%2} %1) move)
(update-in [:trick] conj move))))
(defn finish-trick [{:keys [ntrick turn players trick] :as state}]
(let [winner (trick-winner trick turn)]
(-> state
(update-in [:players winner :taken] concat trick)
(assoc :trick [])
(assoc :turn winner))))
(defn play-turn [state card]
(let [next-state (-> state
(play-card card)
next-turn)
new-round (comp start-game next-round)]
(cond-> next-state
(trick-over? next-state) finish-trick
(round-over? next-state) new-round)))
(comment
(deal-among 4 (shuffle deck))
(def names ["allan" "adi" "quan" "lucy"])
(def players (-> names init-players (init-hands deck)))
(def state (init-game-state names))
(starting-player (:players state))
(def state-1 (start-turn state))
(next-turn state-1)
(def card "1S")
(def hand '("QH" "QS" "1H" "1S"))
(def trick '("3C" "KC"))
(def first? false)
(valid-move "QH" hand '() first?)
(valid-move card hand trick first?)
(highest-of-suit-2 "C" '("3C" "6C" "JH" "7C"))
(trick-winner '("3C" "6C" "JH" "7C") 2)
(def state (start-game (init-game-state names)))
(pprint state)
(pprint
(-> state
(play-turn "JS")
(play-turn "4S")
(play-turn "KS")
(play-turn "8S")))
)
| 74921 | (ns hearts.core
(:require [cljs.core.match :refer-macros [match]]
[hearts.utils :as utils :refer [spy]]
[cljs.pprint :refer [pprint]]
[goog.string :as gstr])
(:require-macros [hearts.macros :refer [spy2]]))
;; ===== CREATE DATA ===== ;;
(def suits #{"H" "D" "S" "C"})
(def ranks (concat (map str (range 2 10)) ["T" "J" "Q" "K" "A"]))
(def deck (for [suit suits rank ranks]
(str rank suit)))
(def max-score 26)
(def card-scores
(let [hearts (for [rank ranks]
(str rank "H"))]
(-> hearts
(zipmap (repeat 1))
(assoc "QS" 13))))
(def has-some? (comp some? some))
;; ===== DECK OPERATIONS ===== ;;
(defn discard
"removes set of cards from deck"
[cards deck]
(remove cards deck))
(defn deal-among
"returns n hands with the same number of cards"
[n deck]
(let [hand-size (quot (count deck) n)]
(partition hand-size deck)))
;; ===== CARD OPERATIONS ===== ;;
(defn card->suit [[rank suit]]
suit)
(defn card->rank [[rank suit]]
rank)
;; ===== CONSTRUCT GAME STATE ===== ;;
(defn make-player [-name]
{:name -name :hand [] :taken [] :score 0})
(defn init-players [names]
(mapv make-player names))
(defn init-hands [players deck]
(let [n-players (count players)
hands (deal-among n-players (shuffle deck))]
(mapv #(assoc %1 :hand %2) players hands)))
;; {:ntrick 0
;; :turn 0 ;; player index. increment mod 4 or change when someone wins trick
;; :players [{:name "str"
;; :hand []
;; :taken []
;; :score 0}]
;; :trick []
;; }
(defn init-game-state [names]
{:ntrick 0
:turn 0
:players (-> names init-players (init-hands deck))
:trick []})
;; ===== HAND OPERATIONS ===== ;;
(defn trick-broken? [players]
(some (set (keys card-scores)) (mapcat :taken players)))
(defn trick-suit [trick]
(card->suit (first trick)))
(defn valid-move
"Each player must follow suit if possible. If a player is void of the suit led, a
card of any other suit may be discarded. However, if a player has no clubs
when the first trick is led, a heart or the queen of spades cannot be
discarded."
[card hand trick first?]
(let [suit #{(trick-suit trick)}
has-card? (some #{card} hand)
has-suit? (has-some? suit (map #(card->suit %) hand))
follows-suit? (has-some? suit (card->suit card))]
(if has-card?
(match [has-suit? follows-suit? first?]
[true true _] card
[true false _] (js/Error. "Card does not match suit.")
[false _ true] (if (has-some? #{card} (keys card-scores))
(js/Error. "Cannot discard heart or queen of spades on first trick.")
card)
[false _ false] card)
(js/Error. (str "You don't have " card " in your hand.")))))
(defn highest-of-suit [suit cards]
(let [rank-vals (zipmap ranks (range))]
(->> cards
(filter #(contains? #{suit} (card->suit %)))
(apply max-key #(rank-vals (card->rank %))))))
(defn trick-winner
"The highest card of the suit led wins a trick and the winner of
that trick leads next."
[trick leader]
(let [winning-card (highest-of-suit (trick-suit trick) trick)
card-index (.indexOf trick winning-card)]
(-> card-index
(+ leader)
(mod (count trick)))))
(defn starting-player [players]
(let [arr (map #(some #{"2C"} (:hand %)) players)]
(.indexOf arr "2C")))
;; ===== QUERIES ===== ;;
(defn trick-over? [{:keys [ntrick turn players trick] :as state}]
(= (count trick) (count players)))
(defn round-over? [{:keys [ntrick turn players trick] :as state}]
(= ntrick (count deck)))
(defn player-score [player]
(->> player
:taken
(map card-scores)
(apply +)))
(defn game-over? [state]
(>= (apply max (map :score (:players state)))
max-score))
(defn game-winner [state]
(apply min-key (into [:score] (:players state))))
;; ===== GAMEPLAY OPERATIONS ===== ;;
(defn start-game [state]
(assoc state :turn (starting-player (:players state))))
(defn next-turn [state]
(let [n-players (count (:players state))]
(-> state
(update :ntrick inc)
(update :turn #(-> % inc (mod n-players))))))
(defn shoot-moon? [players]
(.indexOf (map player-score players) (apply + (vals card-scores))))
(defn update-scores [players]
(map #(update % :score + (player-score %)) players))
(defn moonshot-update-scores [players shooter]
(as-> players p
(map #(update % :score + 26) p)
(update-in p [shooter :score] - 26)))
(defn clear-cards [player]
(-> player
(assoc :taken [])
(assoc :hand [])))
(defn next-round [state]
(-> state
(update :players #(let [shooter (shoot-moon? %)]
(if (< shooter 0)
(update-scores %)
(moonshot-update-scores % shooter))))
(update :players #(map clear-cards %))
(update :players init-hands deck)
(assoc :ntrick 0)))
(defn play-card [{:keys [ntrick turn players trick] :as state} card]
(let [player (get players turn)
hand (:hand player)
;; that's jank...
_ (when (and (not= card "2C") (= 0 ntrick (count trick)))
(throw (js/Error. "Must lead with 2C.")))
move (utils/throw-err (valid-move card hand trick (zero? ntrick)))
_ (when (and (contains? card-scores card) (not (trick-broken? players))
(zero? (count trick)))
(throw (js/Error. "Cannot lead with H or QS: Hearts not yet broken.")))]
(-> state
(update-in [:players turn :hand] #(discard #{%2} %1) move)
(update-in [:trick] conj move))))
(defn finish-trick [{:keys [ntrick turn players trick] :as state}]
(let [winner (trick-winner trick turn)]
(-> state
(update-in [:players winner :taken] concat trick)
(assoc :trick [])
(assoc :turn winner))))
(defn play-turn [state card]
(let [next-state (-> state
(play-card card)
next-turn)
new-round (comp start-game next-round)]
(cond-> next-state
(trick-over? next-state) finish-trick
(round-over? next-state) new-round)))
(comment
(deal-among 4 (shuffle deck))
(def names ["<NAME>" "<NAME>" "<NAME>" "<NAME>"])
(def players (-> names init-players (init-hands deck)))
(def state (init-game-state names))
(starting-player (:players state))
(def state-1 (start-turn state))
(next-turn state-1)
(def card "1S")
(def hand '("QH" "QS" "1H" "1S"))
(def trick '("3C" "KC"))
(def first? false)
(valid-move "QH" hand '() first?)
(valid-move card hand trick first?)
(highest-of-suit-2 "C" '("3C" "6C" "JH" "7C"))
(trick-winner '("3C" "6C" "JH" "7C") 2)
(def state (start-game (init-game-state names)))
(pprint state)
(pprint
(-> state
(play-turn "JS")
(play-turn "4S")
(play-turn "KS")
(play-turn "8S")))
)
| true | (ns hearts.core
(:require [cljs.core.match :refer-macros [match]]
[hearts.utils :as utils :refer [spy]]
[cljs.pprint :refer [pprint]]
[goog.string :as gstr])
(:require-macros [hearts.macros :refer [spy2]]))
;; ===== CREATE DATA ===== ;;
(def suits #{"H" "D" "S" "C"})
(def ranks (concat (map str (range 2 10)) ["T" "J" "Q" "K" "A"]))
(def deck (for [suit suits rank ranks]
(str rank suit)))
(def max-score 26)
(def card-scores
(let [hearts (for [rank ranks]
(str rank "H"))]
(-> hearts
(zipmap (repeat 1))
(assoc "QS" 13))))
(def has-some? (comp some? some))
;; ===== DECK OPERATIONS ===== ;;
(defn discard
"removes set of cards from deck"
[cards deck]
(remove cards deck))
(defn deal-among
"returns n hands with the same number of cards"
[n deck]
(let [hand-size (quot (count deck) n)]
(partition hand-size deck)))
;; ===== CARD OPERATIONS ===== ;;
(defn card->suit [[rank suit]]
suit)
(defn card->rank [[rank suit]]
rank)
;; ===== CONSTRUCT GAME STATE ===== ;;
(defn make-player [-name]
{:name -name :hand [] :taken [] :score 0})
(defn init-players [names]
(mapv make-player names))
(defn init-hands [players deck]
(let [n-players (count players)
hands (deal-among n-players (shuffle deck))]
(mapv #(assoc %1 :hand %2) players hands)))
;; {:ntrick 0
;; :turn 0 ;; player index. increment mod 4 or change when someone wins trick
;; :players [{:name "str"
;; :hand []
;; :taken []
;; :score 0}]
;; :trick []
;; }
(defn init-game-state [names]
{:ntrick 0
:turn 0
:players (-> names init-players (init-hands deck))
:trick []})
;; ===== HAND OPERATIONS ===== ;;
(defn trick-broken? [players]
(some (set (keys card-scores)) (mapcat :taken players)))
(defn trick-suit [trick]
(card->suit (first trick)))
(defn valid-move
"Each player must follow suit if possible. If a player is void of the suit led, a
card of any other suit may be discarded. However, if a player has no clubs
when the first trick is led, a heart or the queen of spades cannot be
discarded."
[card hand trick first?]
(let [suit #{(trick-suit trick)}
has-card? (some #{card} hand)
has-suit? (has-some? suit (map #(card->suit %) hand))
follows-suit? (has-some? suit (card->suit card))]
(if has-card?
(match [has-suit? follows-suit? first?]
[true true _] card
[true false _] (js/Error. "Card does not match suit.")
[false _ true] (if (has-some? #{card} (keys card-scores))
(js/Error. "Cannot discard heart or queen of spades on first trick.")
card)
[false _ false] card)
(js/Error. (str "You don't have " card " in your hand.")))))
(defn highest-of-suit [suit cards]
(let [rank-vals (zipmap ranks (range))]
(->> cards
(filter #(contains? #{suit} (card->suit %)))
(apply max-key #(rank-vals (card->rank %))))))
(defn trick-winner
"The highest card of the suit led wins a trick and the winner of
that trick leads next."
[trick leader]
(let [winning-card (highest-of-suit (trick-suit trick) trick)
card-index (.indexOf trick winning-card)]
(-> card-index
(+ leader)
(mod (count trick)))))
(defn starting-player [players]
(let [arr (map #(some #{"2C"} (:hand %)) players)]
(.indexOf arr "2C")))
;; ===== QUERIES ===== ;;
(defn trick-over? [{:keys [ntrick turn players trick] :as state}]
(= (count trick) (count players)))
(defn round-over? [{:keys [ntrick turn players trick] :as state}]
(= ntrick (count deck)))
(defn player-score [player]
(->> player
:taken
(map card-scores)
(apply +)))
(defn game-over? [state]
(>= (apply max (map :score (:players state)))
max-score))
(defn game-winner [state]
(apply min-key (into [:score] (:players state))))
;; ===== GAMEPLAY OPERATIONS ===== ;;
(defn start-game [state]
(assoc state :turn (starting-player (:players state))))
(defn next-turn [state]
(let [n-players (count (:players state))]
(-> state
(update :ntrick inc)
(update :turn #(-> % inc (mod n-players))))))
(defn shoot-moon? [players]
(.indexOf (map player-score players) (apply + (vals card-scores))))
(defn update-scores [players]
(map #(update % :score + (player-score %)) players))
(defn moonshot-update-scores [players shooter]
(as-> players p
(map #(update % :score + 26) p)
(update-in p [shooter :score] - 26)))
(defn clear-cards [player]
(-> player
(assoc :taken [])
(assoc :hand [])))
(defn next-round [state]
(-> state
(update :players #(let [shooter (shoot-moon? %)]
(if (< shooter 0)
(update-scores %)
(moonshot-update-scores % shooter))))
(update :players #(map clear-cards %))
(update :players init-hands deck)
(assoc :ntrick 0)))
(defn play-card [{:keys [ntrick turn players trick] :as state} card]
(let [player (get players turn)
hand (:hand player)
;; that's jank...
_ (when (and (not= card "2C") (= 0 ntrick (count trick)))
(throw (js/Error. "Must lead with 2C.")))
move (utils/throw-err (valid-move card hand trick (zero? ntrick)))
_ (when (and (contains? card-scores card) (not (trick-broken? players))
(zero? (count trick)))
(throw (js/Error. "Cannot lead with H or QS: Hearts not yet broken.")))]
(-> state
(update-in [:players turn :hand] #(discard #{%2} %1) move)
(update-in [:trick] conj move))))
(defn finish-trick [{:keys [ntrick turn players trick] :as state}]
(let [winner (trick-winner trick turn)]
(-> state
(update-in [:players winner :taken] concat trick)
(assoc :trick [])
(assoc :turn winner))))
(defn play-turn [state card]
(let [next-state (-> state
(play-card card)
next-turn)
new-round (comp start-game next-round)]
(cond-> next-state
(trick-over? next-state) finish-trick
(round-over? next-state) new-round)))
(comment
(deal-among 4 (shuffle deck))
(def names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])
(def players (-> names init-players (init-hands deck)))
(def state (init-game-state names))
(starting-player (:players state))
(def state-1 (start-turn state))
(next-turn state-1)
(def card "1S")
(def hand '("QH" "QS" "1H" "1S"))
(def trick '("3C" "KC"))
(def first? false)
(valid-move "QH" hand '() first?)
(valid-move card hand trick first?)
(highest-of-suit-2 "C" '("3C" "6C" "JH" "7C"))
(trick-winner '("3C" "6C" "JH" "7C") 2)
(def state (start-game (init-game-state names)))
(pprint state)
(pprint
(-> state
(play-turn "JS")
(play-turn "4S")
(play-turn "KS")
(play-turn "8S")))
)
|
[
{
"context": "very-grace-period]} opts]\n {:name \"Apache Flink\"\n :os debian/os\n ",
"end": 2127,
"score": 0.5602487921714783,
"start": 2121,
"tag": "NAME",
"value": "Apache"
},
{
"context": "ce-period]} opts]\n {:name \"Apache Flink\"\n :os debian/os\n :db",
"end": 2133,
"score": 0.48520514369010925,
"start": 2129,
"tag": "NAME",
"value": "link"
}
] | flink-jepsen/src/jepsen/flink/flink.clj | Noctune/flink | 2 | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns jepsen.flink.flink
(:require [clojure.tools.logging :refer :all]
[jepsen
[cli :as cli]
[generator :as gen]
[tests :as tests]]
[jepsen.os.debian :as debian]
[jepsen.flink.client :refer :all]
[jepsen.flink.checker :as flink-checker]
[jepsen.flink.db :as fdb]
[jepsen.flink.nemesis :as fn])
(:import (jepsen.flink.client Client)))
(def flink-test-config
{:yarn-session {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-session!}
:yarn-job {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-job!}
:mesos-session {:db (fdb/flink-mesos-db)
:deployment-strategy fdb/start-mesos-session!}})
(defn client-gen
[]
(->
(cons {:type :invoke, :f :submit, :value nil}
(cycle [{:type :invoke, :f :job-running?, :value nil}
(gen/sleep 5)]))
(gen/seq)
(gen/singlethreaded)))
(defn flink-test
[opts]
(merge tests/noop-test
(let [{:keys [db deployment-strategy]} (-> opts :deployment-mode flink-test-config)
{:keys [job-running-healthy-threshold job-recovery-grace-period]} opts]
{:name "Apache Flink"
:os debian/os
:db db
:nemesis (fn/nemesis)
:model (flink-checker/job-running-within-grace-period
job-running-healthy-threshold
job-recovery-grace-period)
:generator (let [stop (atom nil)]
(->> (fn/stoppable-generator stop (client-gen))
(gen/nemesis
(fn/stop-generator stop
((fn/nemesis-generator-factories (:nemesis-gen opts)) opts)
job-running-healthy-threshold
job-recovery-grace-period))))
:client (Client. deployment-strategy nil nil nil nil)
:checker (flink-checker/job-running-checker)})
(assoc opts :concurrency 1)))
(defn keys-as-allowed-values-help-text
"Takes a map and returns a string explaining which values are allowed.
This is a CLI helper function."
[m]
(->> (keys m)
(map name)
(clojure.string/join ", ")
(str "Must be one of: ")))
(defn -main
[& args]
(cli/run!
(merge
(cli/single-test-cmd
{:test-fn flink-test
:tarball fdb/default-flink-dist-url
:opt-spec [[nil "--ha-storage-dir DIR" "high-availability.storageDir"]
[nil "--job-jar JAR" "Path to the job jar"]
[nil "--job-args ARGS" "CLI arguments for the flink job"]
[nil "--main-class CLASS" "Job main class"]
[nil "--nemesis-gen GEN" (str "Which nemesis should be used?"
(keys-as-allowed-values-help-text fn/nemesis-generator-factories))
:parse-fn keyword
:default :kill-task-managers
:validate [#(fn/nemesis-generator-factories (keyword %))
(keys-as-allowed-values-help-text fn/nemesis-generator-factories)]]
[nil "--deployment-mode MODE" (keys-as-allowed-values-help-text flink-test-config)
:parse-fn keyword
:default :yarn-session
:validate [#(flink-test-config (keyword %))
(keys-as-allowed-values-help-text flink-test-config)]]
[nil "--job-running-healthy-threshold TIMES" "Number of consecutive times the job must be running to be considered healthy."
:default 5
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive"]]
[nil "--job-recovery-grace-period SECONDS" "Time period in which the job must become healthy."
:default 180
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive" (fn [v] (<= 60 v)) "Should be greater than 60"]]]})
(cli/serve-cmd))
args))
| 76446 | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns jepsen.flink.flink
(:require [clojure.tools.logging :refer :all]
[jepsen
[cli :as cli]
[generator :as gen]
[tests :as tests]]
[jepsen.os.debian :as debian]
[jepsen.flink.client :refer :all]
[jepsen.flink.checker :as flink-checker]
[jepsen.flink.db :as fdb]
[jepsen.flink.nemesis :as fn])
(:import (jepsen.flink.client Client)))
(def flink-test-config
{:yarn-session {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-session!}
:yarn-job {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-job!}
:mesos-session {:db (fdb/flink-mesos-db)
:deployment-strategy fdb/start-mesos-session!}})
(defn client-gen
[]
(->
(cons {:type :invoke, :f :submit, :value nil}
(cycle [{:type :invoke, :f :job-running?, :value nil}
(gen/sleep 5)]))
(gen/seq)
(gen/singlethreaded)))
(defn flink-test
[opts]
(merge tests/noop-test
(let [{:keys [db deployment-strategy]} (-> opts :deployment-mode flink-test-config)
{:keys [job-running-healthy-threshold job-recovery-grace-period]} opts]
{:name "<NAME> F<NAME>"
:os debian/os
:db db
:nemesis (fn/nemesis)
:model (flink-checker/job-running-within-grace-period
job-running-healthy-threshold
job-recovery-grace-period)
:generator (let [stop (atom nil)]
(->> (fn/stoppable-generator stop (client-gen))
(gen/nemesis
(fn/stop-generator stop
((fn/nemesis-generator-factories (:nemesis-gen opts)) opts)
job-running-healthy-threshold
job-recovery-grace-period))))
:client (Client. deployment-strategy nil nil nil nil)
:checker (flink-checker/job-running-checker)})
(assoc opts :concurrency 1)))
(defn keys-as-allowed-values-help-text
"Takes a map and returns a string explaining which values are allowed.
This is a CLI helper function."
[m]
(->> (keys m)
(map name)
(clojure.string/join ", ")
(str "Must be one of: ")))
(defn -main
[& args]
(cli/run!
(merge
(cli/single-test-cmd
{:test-fn flink-test
:tarball fdb/default-flink-dist-url
:opt-spec [[nil "--ha-storage-dir DIR" "high-availability.storageDir"]
[nil "--job-jar JAR" "Path to the job jar"]
[nil "--job-args ARGS" "CLI arguments for the flink job"]
[nil "--main-class CLASS" "Job main class"]
[nil "--nemesis-gen GEN" (str "Which nemesis should be used?"
(keys-as-allowed-values-help-text fn/nemesis-generator-factories))
:parse-fn keyword
:default :kill-task-managers
:validate [#(fn/nemesis-generator-factories (keyword %))
(keys-as-allowed-values-help-text fn/nemesis-generator-factories)]]
[nil "--deployment-mode MODE" (keys-as-allowed-values-help-text flink-test-config)
:parse-fn keyword
:default :yarn-session
:validate [#(flink-test-config (keyword %))
(keys-as-allowed-values-help-text flink-test-config)]]
[nil "--job-running-healthy-threshold TIMES" "Number of consecutive times the job must be running to be considered healthy."
:default 5
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive"]]
[nil "--job-recovery-grace-period SECONDS" "Time period in which the job must become healthy."
:default 180
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive" (fn [v] (<= 60 v)) "Should be greater than 60"]]]})
(cli/serve-cmd))
args))
| true | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns jepsen.flink.flink
(:require [clojure.tools.logging :refer :all]
[jepsen
[cli :as cli]
[generator :as gen]
[tests :as tests]]
[jepsen.os.debian :as debian]
[jepsen.flink.client :refer :all]
[jepsen.flink.checker :as flink-checker]
[jepsen.flink.db :as fdb]
[jepsen.flink.nemesis :as fn])
(:import (jepsen.flink.client Client)))
(def flink-test-config
{:yarn-session {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-session!}
:yarn-job {:db (fdb/flink-yarn-db)
:deployment-strategy fdb/start-yarn-job!}
:mesos-session {:db (fdb/flink-mesos-db)
:deployment-strategy fdb/start-mesos-session!}})
(defn client-gen
[]
(->
(cons {:type :invoke, :f :submit, :value nil}
(cycle [{:type :invoke, :f :job-running?, :value nil}
(gen/sleep 5)]))
(gen/seq)
(gen/singlethreaded)))
(defn flink-test
[opts]
(merge tests/noop-test
(let [{:keys [db deployment-strategy]} (-> opts :deployment-mode flink-test-config)
{:keys [job-running-healthy-threshold job-recovery-grace-period]} opts]
{:name "PI:NAME:<NAME>END_PI FPI:NAME:<NAME>END_PI"
:os debian/os
:db db
:nemesis (fn/nemesis)
:model (flink-checker/job-running-within-grace-period
job-running-healthy-threshold
job-recovery-grace-period)
:generator (let [stop (atom nil)]
(->> (fn/stoppable-generator stop (client-gen))
(gen/nemesis
(fn/stop-generator stop
((fn/nemesis-generator-factories (:nemesis-gen opts)) opts)
job-running-healthy-threshold
job-recovery-grace-period))))
:client (Client. deployment-strategy nil nil nil nil)
:checker (flink-checker/job-running-checker)})
(assoc opts :concurrency 1)))
(defn keys-as-allowed-values-help-text
"Takes a map and returns a string explaining which values are allowed.
This is a CLI helper function."
[m]
(->> (keys m)
(map name)
(clojure.string/join ", ")
(str "Must be one of: ")))
(defn -main
[& args]
(cli/run!
(merge
(cli/single-test-cmd
{:test-fn flink-test
:tarball fdb/default-flink-dist-url
:opt-spec [[nil "--ha-storage-dir DIR" "high-availability.storageDir"]
[nil "--job-jar JAR" "Path to the job jar"]
[nil "--job-args ARGS" "CLI arguments for the flink job"]
[nil "--main-class CLASS" "Job main class"]
[nil "--nemesis-gen GEN" (str "Which nemesis should be used?"
(keys-as-allowed-values-help-text fn/nemesis-generator-factories))
:parse-fn keyword
:default :kill-task-managers
:validate [#(fn/nemesis-generator-factories (keyword %))
(keys-as-allowed-values-help-text fn/nemesis-generator-factories)]]
[nil "--deployment-mode MODE" (keys-as-allowed-values-help-text flink-test-config)
:parse-fn keyword
:default :yarn-session
:validate [#(flink-test-config (keyword %))
(keys-as-allowed-values-help-text flink-test-config)]]
[nil "--job-running-healthy-threshold TIMES" "Number of consecutive times the job must be running to be considered healthy."
:default 5
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive"]]
[nil "--job-recovery-grace-period SECONDS" "Time period in which the job must become healthy."
:default 180
:parse-fn #(Long/parseLong %)
:validate [pos? "Must be positive" (fn [v] (<= 60 v)) "Should be greater than 60"]]]})
(cli/serve-cmd))
args))
|
[
{
"context": " :typ [\"M\" \"L\" \"S\"]\n :p-token 0.05})\n\n(defonce traders [{:i 0 :v \"geojit\" :n \"Geojit",
"end": 877,
"score": 0.9965846538543701,
"start": 873,
"tag": "PASSWORD",
"value": "0.05"
}
] | src/bulk_trader/cljs/globals.cljs | spradnyesh/bulk-trader | 0 | (ns ^:figwheel-always bulk-trader.cljs.globals)
(enable-console-print!)
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:trader nil
:logged-in? false
:data []}))
(defonce overlay-state (atom {:data nil
:state false}))
(defonce error-state (atom {:data nil
:state false}))
(defonce login-state (atom {:state false
:trader nil
;; Geojit
:usercode nil
:pass nil
:sessionkey nil}))
(defonce validateur {:exch {:nse {:segments ["EQ"]}
:bse {:segments ["EQ"]}}
:bs ["B" "S"]
:typ ["M" "L" "S"]
:p-token 0.05})
(defonce traders [{:i 0 :v "geojit" :n "Geojit BNP Paribas"
:login-fn "bulk_trader/cljs/geojit/login"
:login-url "/login"
:vr validateur}
{:i 1 :v "icici" :n "ICICI Direct"
:login-fl "bulk_trader/cljs/icici/login"}])
(def login-domain "http://localhost:3000") ; be-stox.gryff.in
(defonce login-url "/login")
| 98837 | (ns ^:figwheel-always bulk-trader.cljs.globals)
(enable-console-print!)
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:trader nil
:logged-in? false
:data []}))
(defonce overlay-state (atom {:data nil
:state false}))
(defonce error-state (atom {:data nil
:state false}))
(defonce login-state (atom {:state false
:trader nil
;; Geojit
:usercode nil
:pass nil
:sessionkey nil}))
(defonce validateur {:exch {:nse {:segments ["EQ"]}
:bse {:segments ["EQ"]}}
:bs ["B" "S"]
:typ ["M" "L" "S"]
:p-token <PASSWORD>})
(defonce traders [{:i 0 :v "geojit" :n "Geojit BNP Paribas"
:login-fn "bulk_trader/cljs/geojit/login"
:login-url "/login"
:vr validateur}
{:i 1 :v "icici" :n "ICICI Direct"
:login-fl "bulk_trader/cljs/icici/login"}])
(def login-domain "http://localhost:3000") ; be-stox.gryff.in
(defonce login-url "/login")
| true | (ns ^:figwheel-always bulk-trader.cljs.globals)
(enable-console-print!)
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:trader nil
:logged-in? false
:data []}))
(defonce overlay-state (atom {:data nil
:state false}))
(defonce error-state (atom {:data nil
:state false}))
(defonce login-state (atom {:state false
:trader nil
;; Geojit
:usercode nil
:pass nil
:sessionkey nil}))
(defonce validateur {:exch {:nse {:segments ["EQ"]}
:bse {:segments ["EQ"]}}
:bs ["B" "S"]
:typ ["M" "L" "S"]
:p-token PI:PASSWORD:<PASSWORD>END_PI})
(defonce traders [{:i 0 :v "geojit" :n "Geojit BNP Paribas"
:login-fn "bulk_trader/cljs/geojit/login"
:login-url "/login"
:vr validateur}
{:i 1 :v "icici" :n "ICICI Direct"
:login-fl "bulk_trader/cljs/icici/login"}])
(def login-domain "http://localhost:3000") ; be-stox.gryff.in
(defonce login-url "/login")
|
[
{
"context": " once dependencies have been met.\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.libs.deps\n (:require [c",
"end": 147,
"score": 0.9998752474784851,
"start": 138,
"tag": "NAME",
"value": "Sam Aaron"
},
{
"context": "dencies have been met.\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.libs.deps\n (:require [clojure.set :",
"end": 159,
"score": 0.9998701214790344,
"start": 150,
"tag": "NAME",
"value": "Jeff Rose"
}
] | src/overtone/libs/deps.clj | samaaron/overtone | 2 | (ns
^{:doc "A basic dependency system for specifying the execution of
fns once dependencies have been met."
:author "Sam Aaron & Jeff Rose"}
overtone.libs.deps
(:require [clojure.set :as set]))
(defonce dep-state* (agent {:satisfied #{}
:todo []
:done []}))
(defn- process-handler
"Returns a new deps map containing either processed handler or it placed in
the todo list"
[dep-state key deps task]
(apply assoc dep-state
(if (set/superset? (:satisfied dep-state) deps)
(do
(task)
[:done (conj (:done dep-state)
[key deps task])])
[:todo (conj (:todo dep-state)
[key deps task])])))
(defn- replace-handler
"Replace all occurances of handers with the given key with the new handler
and deps set"
[dep-state key deps task]
(let [replacer-fn #(if (= key (first %))
[key deps task]
%)]
{:satisfied (dep-state :satisfied)
:todo (map replacer-fn (dep-state :todo))
:done (map replacer-fn (dep-state :done))}))
(defn- key-known?
"Returns true or false depending on whether this key is associated with a
handler in either the completed or todo lists."
[dep-state key]
(some #(= key (first %)) (concat (:done dep-state) (:todo dep-state))))
(defn- on-deps*
"If a handler with this key has already been registered, just replace the
handler - either in todo or completed. If the key is unknown, then either
execute the handler if the deps are satisfied or add it to the todo list"
[dep-state key deps task]
(if (key-known? dep-state key)
(replace-handler dep-state key deps task)
(process-handler dep-state key deps task)))
(defn- satisfy*
[{:keys [satisfied todo done]} new-deps]
(let [satisfied (set/union satisfied new-deps)
execute-tasks (fn [[final-done final-todo] [key deps task]]
(if (set/superset? satisfied deps)
(do
(task)
[(conj final-done [key deps task]) final-todo])
[final-done (conj final-todo [key deps task])]))
[t-done t-todo] (reduce execute-tasks [done []] todo)]
{:satisfied satisfied
:done t-done
:todo t-todo}))
(defn on-deps
"Specify that a function should be called once one or more dependencies
have been satisfied. The function is run immediately if the deps have
already been satisfied, otherwise it will run as soon as they are.
If a dep handler has already been registered with the same key, a second
registration with just replace the first."
[deps key handler]
(let [deps (if (coll? deps)
(set deps)
(set [deps]))]
(send-off dep-state* on-deps* key deps handler)))
(defn satisfy-deps
"Specifies that a given dependency has been satisfied."
[& deps]
(send-off dep-state* satisfy* (set deps)))
(defn reset-deps
"Reset the dependency system."
[]
(send dep-state* (fn [& args]
{:satisfied #{}
:todo []
:done []})))
(defn unsatisfy-all-dependencies
"Unsatisfy all deps and reset completed tasks as todo tasks"
[]
(send dep-state* (fn [deps]
{:satisfied #{}
:todo (deps :done)
:done []})))
| 18571 | (ns
^{:doc "A basic dependency system for specifying the execution of
fns once dependencies have been met."
:author "<NAME> & <NAME>"}
overtone.libs.deps
(:require [clojure.set :as set]))
(defonce dep-state* (agent {:satisfied #{}
:todo []
:done []}))
(defn- process-handler
"Returns a new deps map containing either processed handler or it placed in
the todo list"
[dep-state key deps task]
(apply assoc dep-state
(if (set/superset? (:satisfied dep-state) deps)
(do
(task)
[:done (conj (:done dep-state)
[key deps task])])
[:todo (conj (:todo dep-state)
[key deps task])])))
(defn- replace-handler
"Replace all occurances of handers with the given key with the new handler
and deps set"
[dep-state key deps task]
(let [replacer-fn #(if (= key (first %))
[key deps task]
%)]
{:satisfied (dep-state :satisfied)
:todo (map replacer-fn (dep-state :todo))
:done (map replacer-fn (dep-state :done))}))
(defn- key-known?
"Returns true or false depending on whether this key is associated with a
handler in either the completed or todo lists."
[dep-state key]
(some #(= key (first %)) (concat (:done dep-state) (:todo dep-state))))
(defn- on-deps*
"If a handler with this key has already been registered, just replace the
handler - either in todo or completed. If the key is unknown, then either
execute the handler if the deps are satisfied or add it to the todo list"
[dep-state key deps task]
(if (key-known? dep-state key)
(replace-handler dep-state key deps task)
(process-handler dep-state key deps task)))
(defn- satisfy*
[{:keys [satisfied todo done]} new-deps]
(let [satisfied (set/union satisfied new-deps)
execute-tasks (fn [[final-done final-todo] [key deps task]]
(if (set/superset? satisfied deps)
(do
(task)
[(conj final-done [key deps task]) final-todo])
[final-done (conj final-todo [key deps task])]))
[t-done t-todo] (reduce execute-tasks [done []] todo)]
{:satisfied satisfied
:done t-done
:todo t-todo}))
(defn on-deps
"Specify that a function should be called once one or more dependencies
have been satisfied. The function is run immediately if the deps have
already been satisfied, otherwise it will run as soon as they are.
If a dep handler has already been registered with the same key, a second
registration with just replace the first."
[deps key handler]
(let [deps (if (coll? deps)
(set deps)
(set [deps]))]
(send-off dep-state* on-deps* key deps handler)))
(defn satisfy-deps
"Specifies that a given dependency has been satisfied."
[& deps]
(send-off dep-state* satisfy* (set deps)))
(defn reset-deps
"Reset the dependency system."
[]
(send dep-state* (fn [& args]
{:satisfied #{}
:todo []
:done []})))
(defn unsatisfy-all-dependencies
"Unsatisfy all deps and reset completed tasks as todo tasks"
[]
(send dep-state* (fn [deps]
{:satisfied #{}
:todo (deps :done)
:done []})))
| true | (ns
^{:doc "A basic dependency system for specifying the execution of
fns once dependencies have been met."
:author "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"}
overtone.libs.deps
(:require [clojure.set :as set]))
(defonce dep-state* (agent {:satisfied #{}
:todo []
:done []}))
(defn- process-handler
"Returns a new deps map containing either processed handler or it placed in
the todo list"
[dep-state key deps task]
(apply assoc dep-state
(if (set/superset? (:satisfied dep-state) deps)
(do
(task)
[:done (conj (:done dep-state)
[key deps task])])
[:todo (conj (:todo dep-state)
[key deps task])])))
(defn- replace-handler
"Replace all occurances of handers with the given key with the new handler
and deps set"
[dep-state key deps task]
(let [replacer-fn #(if (= key (first %))
[key deps task]
%)]
{:satisfied (dep-state :satisfied)
:todo (map replacer-fn (dep-state :todo))
:done (map replacer-fn (dep-state :done))}))
(defn- key-known?
"Returns true or false depending on whether this key is associated with a
handler in either the completed or todo lists."
[dep-state key]
(some #(= key (first %)) (concat (:done dep-state) (:todo dep-state))))
(defn- on-deps*
"If a handler with this key has already been registered, just replace the
handler - either in todo or completed. If the key is unknown, then either
execute the handler if the deps are satisfied or add it to the todo list"
[dep-state key deps task]
(if (key-known? dep-state key)
(replace-handler dep-state key deps task)
(process-handler dep-state key deps task)))
(defn- satisfy*
[{:keys [satisfied todo done]} new-deps]
(let [satisfied (set/union satisfied new-deps)
execute-tasks (fn [[final-done final-todo] [key deps task]]
(if (set/superset? satisfied deps)
(do
(task)
[(conj final-done [key deps task]) final-todo])
[final-done (conj final-todo [key deps task])]))
[t-done t-todo] (reduce execute-tasks [done []] todo)]
{:satisfied satisfied
:done t-done
:todo t-todo}))
(defn on-deps
"Specify that a function should be called once one or more dependencies
have been satisfied. The function is run immediately if the deps have
already been satisfied, otherwise it will run as soon as they are.
If a dep handler has already been registered with the same key, a second
registration with just replace the first."
[deps key handler]
(let [deps (if (coll? deps)
(set deps)
(set [deps]))]
(send-off dep-state* on-deps* key deps handler)))
(defn satisfy-deps
"Specifies that a given dependency has been satisfied."
[& deps]
(send-off dep-state* satisfy* (set deps)))
(defn reset-deps
"Reset the dependency system."
[]
(send dep-state* (fn [& args]
{:satisfied #{}
:todo []
:done []})))
(defn unsatisfy-all-dependencies
"Unsatisfy all deps and reset completed tasks as todo tasks"
[]
(send dep-state* (fn [deps]
{:satisfied #{}
:todo (deps :done)
:done []})))
|
[
{
"context": ";\n; Copyright 2020 AppsFlyer\n;\n; Licensed under the Apache License, Versi",
"end": 23,
"score": 0.5943925380706787,
"start": 19,
"tag": "NAME",
"value": "Apps"
},
{
"context": ";\n; Copyright 2020 AppsFlyer\n;\n; Licensed under the Apache License, Version 2.",
"end": 28,
"score": 0.6855350732803345,
"start": 23,
"tag": "USERNAME",
"value": "Flyer"
}
] | src/test/clojure/com/appsflyer/donkey/test_helper.clj | svanburen/donkey | 1 | ;
; 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.test-helper
(:require [clojure.test :refer [is]]
[com.appsflyer.donkey.core :as donkey]
[com.appsflyer.donkey.server :as server]
[com.appsflyer.donkey.request :as request]
[com.appsflyer.donkey.client :as client])
(:import (io.vertx.ext.web.client WebClient WebClientOptions HttpResponse)
(io.vertx.core Vertx Future Handler)
(com.appsflyer.donkey.server DonkeyServer)
(com.appsflyer.donkey.core Donkey)
(com.appsflyer.donkey.client DonkeyClient)
(com.appsflyer.donkey FutureResult)))
(def ^:dynamic ^Donkey donkey-core)
(def ^:dynamic ^DonkeyServer donkey-server)
(def ^:dynamic ^DonkeyClient donkey-client)
(def ^:dynamic ^WebClient vertx-client)
(def ^:const DEFAULT-HOST "localhost")
(def ^:const DEFAULT-PORT 16969)
(def ^:const
default-server-options {:port DEFAULT-PORT})
(def ^:const
default-client-options {:default-host DEFAULT-HOST :default-port DEFAULT-PORT})
(def ^:const
default-donkey-options {:instances 4 :event-loops 1 :worker-threads 4})
(defn- ^WebClient launch-vertx-client [^Vertx vertx]
(WebClient/create
vertx
(-> (WebClientOptions.)
(.setDefaultHost DEFAULT-HOST)
(.setDefaultPort (int (:port default-server-options))))))
(defn init-web-client [test-fn]
(binding [vertx-client (launch-vertx-client (-> donkey-core .-config :vertx))]
(test-fn)
(.close vertx-client)))
(defn init-donkey-client [test-fn]
(binding [donkey-client (donkey/create-client donkey-core default-client-options)]
(test-fn)
(client/stop donkey-client)))
(defn- launch-donkey-server [^Donkey donkey-instance opts]
(let [instance (donkey/create-server donkey-instance (merge default-server-options opts))]
(server/start-sync instance)
instance))
(defn init-donkey-server
([test-fn routes] (init-donkey-server test-fn routes []))
([test-fn routes middleware]
(binding [donkey-server (launch-donkey-server donkey-core {:routes routes :middleware middleware})]
(test-fn)
(is (nil? (server/stop-sync donkey-server))))))
(defn init-donkey [test-fn]
(binding [donkey-core (donkey/create-donkey default-donkey-options)]
(test-fn)))
(defn run-with-server-and-client
"Run `test-fn` under the context of a new DonkeyServer and Vertx WebClient.
Creates a server instance according to the given `routes` and optional `middleware`,
and a default client. Both will be closed after the `test-fn` returns.
The server and client are available inside the test as
`donkey-server` and `vertx-client` respectively."
([test-fn routes] (run-with-server-and-client test-fn routes []))
([test-fn routes middleware]
(let [^Donkey donkey-instance (donkey/create-donkey default-donkey-options)]
(binding [donkey-server (launch-donkey-server donkey-instance {:routes routes :middleware middleware})
vertx-client (launch-vertx-client (-> donkey-instance .-config :vertx))]
(test-fn)
(.close vertx-client)
(is (nil? (server/stop-sync donkey-server)))))))
;; ---------- Helper Functions ---------- ;;
(defn ^HttpResponse wait-for-response
"Waits (blocks) until the `response-promise` is resolved.
Returns the result on success, or throws the exception if failed."
[response-promise]
(let [^Future future-result @response-promise]
(when (.failed future-result)
(throw (.cause future-result)))
(.result future-result)))
(defn parse-response-body [^HttpResponse res]
(-> res .bodyAsString read-string))
(defn parse-response-body-when-resolved [response-promise]
(-> response-promise wait-for-response parse-response-body))
(defn ^Handler create-client-handler
"Create a handler that resolves `response-promise` when the client receives a response"
[response-promise]
(reify Handler
(handle [_this res]
(deliver response-promise ^Future res))))
(defn make-pre-processing-middleware [fun]
(fn [handler]
(fn
([req]
(handler (fun req)))
([req respond raise]
(fun req (fn [res] (respond (handler res respond raise))) raise)))))
(defn make-post-processing-middleware [fun]
(fn [handler]
(fn
([req]
(fun (handler req)))
([req respond raise]
(handler req (fn [res] (respond (fun res respond raise))) raise)))))
(defn ^FutureResult make-request
([opts]
(->
(client/request donkey-client opts)
request/submit))
([opts body]
(->
(client/request donkey-client opts)
(request/submit body))))
(defn ^FutureResult submit-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-form body)))
(defn ^FutureResult submit-multi-part-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-multipart-form body)))
| 54562 | ;
; 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.test-helper
(:require [clojure.test :refer [is]]
[com.appsflyer.donkey.core :as donkey]
[com.appsflyer.donkey.server :as server]
[com.appsflyer.donkey.request :as request]
[com.appsflyer.donkey.client :as client])
(:import (io.vertx.ext.web.client WebClient WebClientOptions HttpResponse)
(io.vertx.core Vertx Future Handler)
(com.appsflyer.donkey.server DonkeyServer)
(com.appsflyer.donkey.core Donkey)
(com.appsflyer.donkey.client DonkeyClient)
(com.appsflyer.donkey FutureResult)))
(def ^:dynamic ^Donkey donkey-core)
(def ^:dynamic ^DonkeyServer donkey-server)
(def ^:dynamic ^DonkeyClient donkey-client)
(def ^:dynamic ^WebClient vertx-client)
(def ^:const DEFAULT-HOST "localhost")
(def ^:const DEFAULT-PORT 16969)
(def ^:const
default-server-options {:port DEFAULT-PORT})
(def ^:const
default-client-options {:default-host DEFAULT-HOST :default-port DEFAULT-PORT})
(def ^:const
default-donkey-options {:instances 4 :event-loops 1 :worker-threads 4})
(defn- ^WebClient launch-vertx-client [^Vertx vertx]
(WebClient/create
vertx
(-> (WebClientOptions.)
(.setDefaultHost DEFAULT-HOST)
(.setDefaultPort (int (:port default-server-options))))))
(defn init-web-client [test-fn]
(binding [vertx-client (launch-vertx-client (-> donkey-core .-config :vertx))]
(test-fn)
(.close vertx-client)))
(defn init-donkey-client [test-fn]
(binding [donkey-client (donkey/create-client donkey-core default-client-options)]
(test-fn)
(client/stop donkey-client)))
(defn- launch-donkey-server [^Donkey donkey-instance opts]
(let [instance (donkey/create-server donkey-instance (merge default-server-options opts))]
(server/start-sync instance)
instance))
(defn init-donkey-server
([test-fn routes] (init-donkey-server test-fn routes []))
([test-fn routes middleware]
(binding [donkey-server (launch-donkey-server donkey-core {:routes routes :middleware middleware})]
(test-fn)
(is (nil? (server/stop-sync donkey-server))))))
(defn init-donkey [test-fn]
(binding [donkey-core (donkey/create-donkey default-donkey-options)]
(test-fn)))
(defn run-with-server-and-client
"Run `test-fn` under the context of a new DonkeyServer and Vertx WebClient.
Creates a server instance according to the given `routes` and optional `middleware`,
and a default client. Both will be closed after the `test-fn` returns.
The server and client are available inside the test as
`donkey-server` and `vertx-client` respectively."
([test-fn routes] (run-with-server-and-client test-fn routes []))
([test-fn routes middleware]
(let [^Donkey donkey-instance (donkey/create-donkey default-donkey-options)]
(binding [donkey-server (launch-donkey-server donkey-instance {:routes routes :middleware middleware})
vertx-client (launch-vertx-client (-> donkey-instance .-config :vertx))]
(test-fn)
(.close vertx-client)
(is (nil? (server/stop-sync donkey-server)))))))
;; ---------- Helper Functions ---------- ;;
(defn ^HttpResponse wait-for-response
"Waits (blocks) until the `response-promise` is resolved.
Returns the result on success, or throws the exception if failed."
[response-promise]
(let [^Future future-result @response-promise]
(when (.failed future-result)
(throw (.cause future-result)))
(.result future-result)))
(defn parse-response-body [^HttpResponse res]
(-> res .bodyAsString read-string))
(defn parse-response-body-when-resolved [response-promise]
(-> response-promise wait-for-response parse-response-body))
(defn ^Handler create-client-handler
"Create a handler that resolves `response-promise` when the client receives a response"
[response-promise]
(reify Handler
(handle [_this res]
(deliver response-promise ^Future res))))
(defn make-pre-processing-middleware [fun]
(fn [handler]
(fn
([req]
(handler (fun req)))
([req respond raise]
(fun req (fn [res] (respond (handler res respond raise))) raise)))))
(defn make-post-processing-middleware [fun]
(fn [handler]
(fn
([req]
(fun (handler req)))
([req respond raise]
(handler req (fn [res] (respond (fun res respond raise))) raise)))))
(defn ^FutureResult make-request
([opts]
(->
(client/request donkey-client opts)
request/submit))
([opts body]
(->
(client/request donkey-client opts)
(request/submit body))))
(defn ^FutureResult submit-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-form body)))
(defn ^FutureResult submit-multi-part-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-multipart-form body)))
| 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.test-helper
(:require [clojure.test :refer [is]]
[com.appsflyer.donkey.core :as donkey]
[com.appsflyer.donkey.server :as server]
[com.appsflyer.donkey.request :as request]
[com.appsflyer.donkey.client :as client])
(:import (io.vertx.ext.web.client WebClient WebClientOptions HttpResponse)
(io.vertx.core Vertx Future Handler)
(com.appsflyer.donkey.server DonkeyServer)
(com.appsflyer.donkey.core Donkey)
(com.appsflyer.donkey.client DonkeyClient)
(com.appsflyer.donkey FutureResult)))
(def ^:dynamic ^Donkey donkey-core)
(def ^:dynamic ^DonkeyServer donkey-server)
(def ^:dynamic ^DonkeyClient donkey-client)
(def ^:dynamic ^WebClient vertx-client)
(def ^:const DEFAULT-HOST "localhost")
(def ^:const DEFAULT-PORT 16969)
(def ^:const
default-server-options {:port DEFAULT-PORT})
(def ^:const
default-client-options {:default-host DEFAULT-HOST :default-port DEFAULT-PORT})
(def ^:const
default-donkey-options {:instances 4 :event-loops 1 :worker-threads 4})
(defn- ^WebClient launch-vertx-client [^Vertx vertx]
(WebClient/create
vertx
(-> (WebClientOptions.)
(.setDefaultHost DEFAULT-HOST)
(.setDefaultPort (int (:port default-server-options))))))
(defn init-web-client [test-fn]
(binding [vertx-client (launch-vertx-client (-> donkey-core .-config :vertx))]
(test-fn)
(.close vertx-client)))
(defn init-donkey-client [test-fn]
(binding [donkey-client (donkey/create-client donkey-core default-client-options)]
(test-fn)
(client/stop donkey-client)))
(defn- launch-donkey-server [^Donkey donkey-instance opts]
(let [instance (donkey/create-server donkey-instance (merge default-server-options opts))]
(server/start-sync instance)
instance))
(defn init-donkey-server
([test-fn routes] (init-donkey-server test-fn routes []))
([test-fn routes middleware]
(binding [donkey-server (launch-donkey-server donkey-core {:routes routes :middleware middleware})]
(test-fn)
(is (nil? (server/stop-sync donkey-server))))))
(defn init-donkey [test-fn]
(binding [donkey-core (donkey/create-donkey default-donkey-options)]
(test-fn)))
(defn run-with-server-and-client
"Run `test-fn` under the context of a new DonkeyServer and Vertx WebClient.
Creates a server instance according to the given `routes` and optional `middleware`,
and a default client. Both will be closed after the `test-fn` returns.
The server and client are available inside the test as
`donkey-server` and `vertx-client` respectively."
([test-fn routes] (run-with-server-and-client test-fn routes []))
([test-fn routes middleware]
(let [^Donkey donkey-instance (donkey/create-donkey default-donkey-options)]
(binding [donkey-server (launch-donkey-server donkey-instance {:routes routes :middleware middleware})
vertx-client (launch-vertx-client (-> donkey-instance .-config :vertx))]
(test-fn)
(.close vertx-client)
(is (nil? (server/stop-sync donkey-server)))))))
;; ---------- Helper Functions ---------- ;;
(defn ^HttpResponse wait-for-response
"Waits (blocks) until the `response-promise` is resolved.
Returns the result on success, or throws the exception if failed."
[response-promise]
(let [^Future future-result @response-promise]
(when (.failed future-result)
(throw (.cause future-result)))
(.result future-result)))
(defn parse-response-body [^HttpResponse res]
(-> res .bodyAsString read-string))
(defn parse-response-body-when-resolved [response-promise]
(-> response-promise wait-for-response parse-response-body))
(defn ^Handler create-client-handler
"Create a handler that resolves `response-promise` when the client receives a response"
[response-promise]
(reify Handler
(handle [_this res]
(deliver response-promise ^Future res))))
(defn make-pre-processing-middleware [fun]
(fn [handler]
(fn
([req]
(handler (fun req)))
([req respond raise]
(fun req (fn [res] (respond (handler res respond raise))) raise)))))
(defn make-post-processing-middleware [fun]
(fn [handler]
(fn
([req]
(fun (handler req)))
([req respond raise]
(handler req (fn [res] (respond (fun res respond raise))) raise)))))
(defn ^FutureResult make-request
([opts]
(->
(client/request donkey-client opts)
request/submit))
([opts body]
(->
(client/request donkey-client opts)
(request/submit body))))
(defn ^FutureResult submit-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-form body)))
(defn ^FutureResult submit-multi-part-form [opts body]
(->
(client/request donkey-client opts)
(request/submit-multipart-form body)))
|
[
{
"context": " :node/display-name (or display-name \"HTN\")\n ;; NOTE: for this \"synthetic\"",
"end": 34268,
"score": 0.5766932964324951,
"start": 34265,
"tag": "NAME",
"value": "HTN"
}
] | src/plan_schema/core.clj | dollabs/plan-schema | 2 | ;; Copyright © 2016 Dynamic Object Language Labs Inc.
;;
;; This software is licensed under the terms of the
;; Apache License, Version 2.0 which can be found in
;; the file LICENSE at the root of this distribution.
(ns plan-schema.core
"Temporal Planning Network schema utilities"
(:require [clojure.string :as string]
[clojure.set :as set]
[plan-schema.coerce :as records]
[plan-schema.utils :refer [synopsis strict? fs-basename
error? stdout-option?
read-json-str write-json-str
log-trace log-debug log-info
log-warn log-error]]
[plan-schema.sorting :refer [sort-map]]
[clojure.pprint :refer [pprint]]
[avenir.utils :as au
:refer [keywordize assoc-if concatv]]
[schema.core :as s]
[schema.coerce :as coerce]
[schema.utils :as su]
[schema.spec.core :as spec]
[me.raynes.fs :as fs]))
;; TPN-------------------------------------------------------------------
(defn network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema network-id
"network-id"
s/Keyword)
(def check-network-id (s/checker network-id))
(defn network? [x]
(and (map? x)
(#{:network
"network"
"NETWORK"} (get x :tpn-type))))
(s/defschema eq-network?
"eq-network?"
(s/conditional
keyword? (s/eq :network)
#(and (string? %)
(= "network" (string/lower-case %))) s/Keyword
'eq-network?))
(s/defschema network
"An network"
{:tpn-type eq-network?
:uid s/Keyword
:begin-node s/Keyword
(s/optional-key :end-node) s/Keyword})
(def check-network (s/checker network))
(s/defschema non-primitive
"A non-primitive is false or a network"
(s/conditional
false? (s/eq false)
keyword? s/Keyword
string? s/Keyword
'non-primitive?))
(def check-non-primitive (s/checker non-primitive))
(s/defschema upper-bound
"upper-bound"
(s/conditional
#(= :infinity %) (s/eq :infinity)
number? s/Num
'upper-bound?))
(def check-upper-bound (s/checker upper-bound))
(s/defschema bounds
"Temporal bounds"
[(s/one s/Num "lower-bound")
(s/one upper-bound "upper-bound")])
(def check-bounds (s/checker bounds))
(defn lvar? [x]
(and (map? x)
(#{:lvar
"lvar"
"LVAR"} (get x :type))))
(s/defschema eq-lvar?
"eq-lvar?"
(s/conditional
keyword? (s/eq :lvar)
#(and (string? %)
(= "lvar" (string/lower-case %))) s/Keyword
'eq-lvar?))
(s/defschema lvar
"A temporal constraint"
{:type eq-lvar?
:name s/Str
(s/optional-key :default) bounds})
(def check-lvar (s/checker lvar))
(s/defschema bounds-or-lvar
"bounds-or-lvar"
(s/conditional
vector? bounds
map? lvar
'bounds-or-lvar?))
(def check-bounds-or-lvar (s/checker bounds-or-lvar))
(s/defschema args
"plant function args (positional)"
[s/Any])
(def check-args (s/checker args))
(s/defschema argsmap
"plant function args (by parameter name)"
{s/Keyword s/Any})
(def check-argsmap (s/checker argsmap))
(s/defschema between
"between constraint [from to]"
[(s/one s/Keyword "between-from-label")
(s/one s/Keyword "between-to-label")])
(def check-between (s/checker between))
(defn temporal-constraint? [x]
(and (map? x)
(#{:temporal-constraint
"temporal-constraint"
"TEMPORAL-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-temporal-constraint?
"eq-temporal-constraint?"
(s/conditional
keyword? (s/eq :temporal-constraint)
#(and (string? %)
(= "temporal-constraint" (string/lower-case %))) s/Keyword
'eq-temporal-constraint?))
(s/defschema temporal-constraint
"A temporal constraint"
{:tpn-type eq-temporal-constraint?
:uid s/Keyword
:value bounds-or-lvar
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-temporal-constraint (s/checker temporal-constraint))
(defn cost<=-constraint? [x]
(and (map? x)
(#{:cost<=-constraint
"cost<=-constraint"
"COST<=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-cost<=-constraint?
"eq-cost<=-constraint?"
(s/conditional
keyword? (s/eq :cost<=-constraint)
#(and (string? %)
(= "cost<=-constraint" (string/lower-case %))) s/Keyword
'eq-cost<=-constraint?))
(s/defschema cost<=-constraint
"A cost<= constraint"
{:tpn-type eq-cost<=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-cost<=-constraint (s/checker cost<=-constraint))
(defn reward>=-constraint? [x]
(and (map? x)
(#{:reward>=-constraint
"reward>=-constraint"
"REWARD>=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-reward>=-constraint?
"eq-reward>=-constraint?"
(s/conditional
keyword? (s/eq :reward>=-constraint)
#(and (string? %)
(= "reward>=-constraint" (string/lower-case %))) s/Keyword
'eq-reward>=-constraint?))
(s/defschema reward>=-constraint
"A reward>= constraint"
{:tpn-type eq-reward>=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-reward>=-constraint (s/checker reward>=-constraint))
(s/defschema element-number
"Element number"
[s/Num])
(def check-element-number (s/checker element-number))
(defn activity? [x]
(and (map? x)
(#{:activity
"activity"
"ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-activity?
"eq-activity?"
(s/conditional
keyword? (s/eq :activity)
#(and (string? %)
(= "activity" (string/lower-case %))) s/Keyword
'eq-activity?))
(s/defschema activity
"An activity"
{:tpn-type eq-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :plant) s/Str
(s/optional-key :plantid) s/Str
(s/optional-key :command) s/Str
(s/optional-key :args) args
(s/optional-key :argsmap) argsmap
(s/optional-key :non-primitive) non-primitive
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
s/Keyword s/Any
})
(def check-activity (s/checker activity))
(defn delay-activity? [x]
(and (map? x)
(#{:delay-activity
"delay-activity"
"DELAY-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-delay-activity?
"eq-delay-activity?"
(s/conditional
keyword? (s/eq :delay-activity)
#(and (string? %)
(= "delay-activity" (string/lower-case %))) s/Keyword
'eq-delay-activity?))
(s/defschema delay-activity
"An delay-activity"
{:tpn-type eq-delay-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :order) s/Num ;; order of delay-activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-delay-activity (s/checker delay-activity))
(defn null-activity? [x]
(and (map? x)
(#{:null-activity
"null-activity"
"NULL-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-null-activity?
"eq-null-activity?"
(s/conditional
keyword? (s/eq :null-activity)
#(and (string? %)
(= "null-activity" (string/lower-case %))) s/Keyword
'eq-null-activity?))
(s/defschema null-activity
"An null-activity"
{:tpn-type eq-null-activity?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :probability) s/Num
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :guard) s/Str
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-null-activity (s/checker null-activity))
(defn state? [x]
(and (map? x)
(#{:state
"state"
"STATE"} (get x :tpn-type))))
(s/defschema eq-state?
"eq-state?"
(s/conditional
keyword? (s/eq :state)
#(and (string? %)
(= "state" (string/lower-case %))) s/Keyword
'eq-state?))
(s/defschema state
"An state"
{:tpn-type eq-state?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword ;; added by the merge operation
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
(s/optional-key :end-node) s/Keyword
})
(def check-state (s/checker state))
(defn c-begin? [x]
(and (map? x)
(#{:c-begin
"c-begin"
"C-BEGIN"} (get x :tpn-type))))
(s/defschema eq-c-begin?
"eq-c-begin?"
(s/conditional
keyword? (s/eq :c-begin)
#(and (string? %)
(= "c-begin" (string/lower-case %))) s/Keyword
'eq-c-begin?))
(s/defschema c-begin
"An c-begin"
{:tpn-type eq-c-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :probability) s/Num
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-begin (s/checker c-begin))
(defn c-end? [x]
(and (map? x)
(#{:c-end
"c-end"
"C-END"} (get x :tpn-type))))
(s/defschema eq-c-end?
"eq-c-end?"
(s/conditional
keyword? (s/eq :c-end)
#(and (string? %)
(= "c-end" (string/lower-case %))) s/Keyword
'eq-c-end?))
(s/defschema c-end
"An c-end"
{:tpn-type eq-c-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :probability) s/Num
(s/optional-key :begin) s/Keyword ;; new, points to c-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-end (s/checker c-end))
(defn p-begin? [x]
(and (map? x)
(#{:p-begin
"p-begin"
"P-BEGIN"} (get x :tpn-type))))
(s/defschema eq-p-begin?
"eq-p-begin?"
(s/conditional
keyword? (s/eq :p-begin)
#(and (string? %)
(= "p-begin" (string/lower-case %))) s/Keyword
'eq-p-begin?))
(s/defschema p-begin
"An p-begin"
{:tpn-type eq-p-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-begin (s/checker p-begin))
(defn p-end? [x]
(and (map? x)
(#{:p-end
"p-end"
"P-END"} (get x :tpn-type))))
(s/defschema eq-p-end?
"eq-p-end?"
(s/conditional
keyword? (s/eq :p-end)
#(and (string? %)
(= "p-end" (string/lower-case %))) s/Keyword
'eq-p-end?))
(s/defschema p-end
"An p-end"
{:tpn-type eq-p-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :begin) s/Keyword ;; new, points to p-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-end (s/checker p-end))
;; unknown object is an escape hatch to facilitate future
;; schema evolution
(defn unknown-object? [x]
(if (strict?)
false ;; do NOT accept unknown objects
(if (map? x)
(do
(log-warn "ACCEPT" (synopsis x) "UNKNOWN object")
true)
false)))
(def known-keywords #{:tpn-type :uid :begin-node :end-node :activities
:constraints :incidence-set :label :display-name :args
:sequence-label :sequence-end :htn-node})
;; NOTE: this does not work as desired
;; (s/defschema unknown-keyword?
;; "An unknown keyword"
;; (s/conditional
;; #(not (known-keywords (keyword %))) s/Keyword
;; 'unknown-keyword?))
;; NOTE: coerce the possible keys we care about to keywords
(s/defschema unknown-object
"An unknown object"
{:tpn-type s/Keyword
:uid s/Keyword
;; (s/optional-key :begin-node) s/Keyword
;; (s/optional-key :end-node) s/Keyword
;; (s/optional-key :activities) #{s/Keyword}
;; (s/optional-key :constraints) #{s/Keyword}
;; (s/optional-key :incidence-set) #{s/Keyword}
;; (s/optional-key :label) s/Keyword ;; label for between
;; (s/optional-key :sequence-label) s/Keyword ;; label for between
;; (s/optional-key :sequence-end) s/Keyword ;; label for between
;; (s/optional-key :htn-node) s/Keyword
;; unknown-keyword? s/Any
s/Keyword s/Any
})
(def check-unknown-object (s/checker unknown-object))
(s/defschema tpn-object
"One of the valid TPN object types"
(s/conditional
network-id? network-id
network? network
temporal-constraint? temporal-constraint
cost<=-constraint? cost<=-constraint
reward>=-constraint? reward>=-constraint
activity? activity
null-activity? null-activity
delay-activity? delay-activity
state? state
c-begin? c-begin
c-end? c-end
p-begin? p-begin
p-end? p-end
unknown-object? unknown-object
'tpn-object?))
(def check-tpn-object (s/checker tpn-object))
(s/defschema tpn
"A TPN"
{s/Keyword tpn-object})
(def check-tpn (s/checker tpn))
;; HTN -------------------------------------------------------------------
(defn htn-network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema htn-network-id
"network"
s/Keyword)
(def check-htn-network-id (s/checker htn-network-id))
(defn edge? [x]
(and (map? x)
(#{:edge "edge" "EDGE"} (get x :type))))
(s/defschema eq-edge?
"eq-edge?"
(s/conditional
keyword? (s/eq :edge)
#(and (string? %) (= "edge" (string/lower-case %)))
s/Keyword
'eq-edge?))
(s/defschema edge
"An edge"
{:type eq-edge?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :edge-type) s/Keyword
(s/optional-key :label) s/Str
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :order) s/Num}) ;; order of hedge
(def check-edge (s/checker edge))
(defn htn-network? [x]
(and (map? x)
(#{:htn-network
"htn-network"
"HTN-NETWORK"} (get x :type))))
(s/defschema eq-htn-network?
"eq-htn-network?"
(s/conditional
keyword? (s/eq :htn-network)
#(and (string? %) (= "htn-network" (string/lower-case %)))
s/Keyword
'eq-htn-network?))
(s/defschema htn-network
"An htn-network"
{:type eq-htn-network?
:uid s/Keyword
:label s/Str
:display-name s/Str
:rootnodes #{s/Keyword} ;; probably wants to be a vector, not a set
(s/optional-key :parentid) s/Keyword})
;; NOTE the parentid points to the parent htn-expanded-method
(def check-htn-network (s/checker htn-network))
(defn htn-primitive-task? [x]
(and (map? x)
(#{:htn-primitive-task
"htn-primitive-task"
"HTN-PRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-primitive-task?
"eq-htn-primitive-task?"
(s/conditional
keyword? (s/eq :htn-primitive-task)
#(and (string? %) (= "htn-primitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-primitive-task?))
(s/defschema htn-primitive-task
"An htn-primitive-task"
{:type eq-htn-primitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-primitive-task (s/checker htn-primitive-task))
(defn htn-expanded-method? [x]
(and (map? x)
(#{:htn-expanded-method
"htn-expanded-method"
"HTN-EXPANDED-METHOD"} (get x :type))))
(s/defschema eq-htn-expanded-method?
"eq-htn-expanded-method?"
(s/conditional
keyword? (s/eq :htn-expanded-method)
#(and (string? %) (= "htn-expanded-method" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-method?))
(s/defschema htn-expanded-method
"An htn-expanded-method"
{:type eq-htn-expanded-method?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
:network s/Keyword
(s/optional-key :edges) [s/Keyword]
;; WAS (s/optional-key :tpn-node) s/Keyword ;; new
(s/optional-key :tpn-selection) s/Any ;; new
})
(def check-htn-expanded-method (s/checker htn-expanded-method))
(defn htn-expanded-nonprimitive-task? [x]
(and (map? x)
(#{:htn-expanded-nonprimitive-task
"htn-expanded-nonprimitive-task"
"HTN-EXPANDED-NONPRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-expanded-nonprimitive-task?
"eq-htn-expanded-nonprimitive-task?"
(s/conditional
keyword? (s/eq :htn-expanded-nonprimitive-task)
#(and (string? %) (= "htn-expanded-nonprimitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-nonprimitive-task?))
(s/defschema htn-expanded-nonprimitive-task
"An htn-expanded-nonprimitive-task"
{:type eq-htn-expanded-nonprimitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-expanded-nonprimitive-task (s/checker htn-expanded-nonprimitive-task))
(s/defschema htn-object
"One of the valid HTN object types"
(s/conditional
htn-network-id? htn-network-id
htn-network? htn-network
edge? edge
htn-primitive-task? htn-primitive-task
htn-expanded-method? htn-expanded-method
htn-expanded-nonprimitive-task? htn-expanded-nonprimitive-task
'htn-object?))
(def check-htn-object (s/checker htn-object))
(s/defschema htn
"A HTN"
{s/Keyword htn-object})
(def check-htn (s/checker htn))
;; -------------------------------------------------------------------
(defn coercion [schema]
(spec/run-checker
(fn [s params]
(let [walk (spec/checker (s/spec s) params)]
(fn [x]
(let [result
(cond
(and (string? x)
(or (= s s/Keyword) (= s upper-bound)))
(walk (keyword (string/lower-case x)))
(and (= s #{s/Keyword}) (vector? x))
(walk (set x))
:else
(walk x))]
(if (su/error? result)
(if (strict?)
result
(let [xstr (synopsis x)
explanation (synopsis (s/explain s))
errstr (synopsis
(with-out-str (print (su/error-val result))))]
(log-warn "ACCEPT\n" xstr "\nEXPECTED\n" explanation "ERROR" errstr)
x)) ;; return it ANYWAY
result)))))
true
schema))
(def coerce-tpn (coercion tpn))
(def coerce-htn (coercion htn))
;; takes pathname as a string
;; plantypes as a set of valid plantypes (strings)
;; formats as a set of valid formats (strings)
;; returns true if filename matches
(defn kind-filename? [pathname plantypes formats]
(let [basename (fs-basename pathname)
[format plantype] (reverse (string/split basename #"\."))]
(boolean (and (plantypes plantype) (formats format)))))
(defn tpn-filename? [filename]
(kind-filename? filename #{"tpn"} #{"json" "edn"}))
(defn htn-filename? [filename]
(kind-filename? filename #{"htn"} #{"json" "edn"}))
(defn json-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"json"}))
(defn edn-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"edn"}))
(defn validate-input [input cwd]
(if (fs/exists? input)
input
(let [cwd-input (str cwd "/" input)]
(if (fs/exists? cwd-input)
cwd-input
{:error (str "input does not exist: " input)}))))
(defn validate-output [output cwd]
(if (stdout-option? output)
output
(if (string/starts-with? output "/")
output
(str cwd "/" output))))
(defn cleanup-relaxed-tpn
"coerces values of known-keywords to keywords"
{:added "0.2.0"}
([tpn]
(reduce-kv cleanup-relaxed-tpn {} tpn))
([m k v]
(assoc m k
(if (map? v)
(let [kw-as (seq v)]
(loop [new-v {} kw-a (first kw-as) more (rest kw-as)]
(if-not kw-a
new-v
(let [[kw a] kw-a
a (if (#{:activities :constraints :incidence-set} kw)
(set (map keyword a))
(if (known-keywords kw)
(keyword a)
a))
new-v (assoc new-v kw a)]
(recur new-v (first more) (rest more))))))
v))))
;; returns a network map -or- {:error "error message"}
(defn parse-network
"Parse TPN"
{:added "0.1.0"}
[network-type options]
(let [{:keys [verbose file-format input output cwd]} options
;; _ (println "Reading input from:" input)
verbose? (and (not (nil? verbose)) (pos? verbose))
input (validate-input (if (vector? input) (first input) input) cwd)
data (if (:error input) input (slurp input))
data (if (:error data)
data
(if (json-filename? input)
(read-json-str data)
(read-string data)))
;;_ (println "DEBUG DATA\n" (with-out-str (pprint data)))
result (if (:error data)
data
(if (= network-type :htn)
#_(coerce-htn data)
(records/coerce data)
#_(coerce-tpn data)
(records/coerce data))
)
;;_ (println "DEBUG RESULT\n" (with-out-str (pprint result)))
out (if (:error result)
result
(if (su/error? result)
{:error (with-out-str (println (:error result)))}
(sort-map result)))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when (:error out)
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
;; returns a map with :tpn on success or :error on failure
(defn parse-tpn
"Parse TPN"
{:added "0.1.0"}
[options]
(parse-network :tpn options))
(defn parse-htn
"Parse HTN"
{:added "0.1.0"}
[options]
(parse-network :htn options))
;; -------------------------------------------------------------
(defn name->id [name]
(if (keyword? name)
name
(keyword (string/replace (string/lower-case name) #"\s+" "_"))))
(defn composite-key [k1 k2]
(keyword (subs (str k1 k2) 1)))
(defn composite-key? [k]
(= 2 (count (string/split (name k) #":"))))
(defn composite-key-fn [k1 k2]
(fn [props]
(keyword (subs (str (get props k1) (get props k2)) 1))))
(def node-key-fn (composite-key-fn :plan/plid :node/id))
(def edge-key-fn (composite-key-fn :plan/plid :edge/id))
(def activity-types #{:activity :null-activity :delay-activity})
(defn activity-type? [edge-or-type]
(activity-types (if (map? edge-or-type)
(:edge/type edge-or-type)
edge-or-type)))
;; HTN ---------------------
(defn get-node [plan node-id]
(get-in @plan [:node/node-by-plid-id node-id]))
(defn update-node [plan node]
;; (log-debug "UPDATE-NODE" node)
(let [plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plan update-in ref merge node)))
(defn get-edge [plan edge-id]
(get-in @plan [:edge/edge-by-plid-id edge-id]))
(defn update-edge [plan edge]
(let [plid-id (edge-key-fn edge)
ref [:edge/edge-by-plid-id plid-id]]
(swap! plan update-in ref merge edge)))
(declare add-htn-node)
(defn add-htn-edge [plans plan-id network-plid-id edge-id from-plid-id net]
(let [plid-id (composite-key plan-id edge-id)
htn-edge (get net edge-id)
{:keys [end-node label display-name args]} htn-edge
type :sequence-edge
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-htn-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-htn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
htn-node (get net node-id)
{:keys [type label display-name args edges]} htn-node
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type
:node/parent network-plid-id}
:node/label label
:node/display-name display-name
:node/args args)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? edges)
(doseq [edge edges]
;; workaround schema coercion problem
(let [edge-id (if (keyword? edge) edge (keyword edge))]
(add-htn-edge plans plan-id network-plid-id edge-id plid-id net))))
nil))
;; nil on success
(defn add-htn-network [plans plan-id network-id net]
(let [htn-network (get net network-id)
{:keys [type label display-name rootnodes parentid]} htn-network
plid-id (composite-key plan-id network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
network (assoc-if {:plan/plid plan-id
:network/id network-id
:network/type type
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes
:network/parent (composite-key plan-id parentid))]
(swap! plans update-in [:network/network-by-plid-id]
assoc plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj plid-id)
(when-not (empty? rootnodes)
(doseq [rootnode rootnodes]
(add-htn-node plans plan-id plid-id rootnode net)))
nil))
(declare add-hem-node)
(defn add-hem-edge [plans plan-id network-plid-id edge-id from-plid-id
default-order net]
(let [plid-id (composite-key plan-id edge-id)
hem-edge (get net edge-id)
{:keys [end-node edge-type label display-name args order]} hem-edge
type (if (= edge-type :choice) :choice-edge :parallel-edge)
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-hem-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-hem-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
hem-node (get net node-id)
{:keys [type label display-name args network edges]} hem-node
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec edges)
plid-network (if network (composite-key plan-id network))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type}
:node/label label
:node/display-name display-name
:node/args args
:node/htn-network plid-network)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when network
(add-htn-network plans plan-id network net))
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id network-plid-id
edge plid-id order net)))))
nil))
(defn unique-id [net prefix]
(let [id (keyword (gensym prefix))]
(if (get net id)
(recur net prefix)
id)))
(defn add-hem-network [plans plan-id network-id net]
(when (= network-id :top-hem-network-id)
(let [hem-network-id (unique-id net "net-") ;; for the hem network
hem-plid-id (composite-key plan-id hem-network-id)
begin-id (unique-id net "hid-") ;; for the top hem
begin-plid-id (composite-key plan-id begin-id)
htn-network-id (:network net)
htn-network (get net htn-network-id)
{:keys [label display-name rootnodes]} htn-network
htn-plid-id (composite-key plan-id htn-network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
htn-network (assoc-if {:plan/plid plan-id
:network/id htn-network-id
:network/type :htn-network
:network/parent hem-plid-id
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes)
begin (assoc-if {:plan/plid plan-id
:node/id begin-id
:node/type :htn-expanded-method
:node/htn-network htn-network-id}
:node/label label
:node/display-name (or display-name "HTN")
;; NOTE: for this "synthetic" top level HEM we don't
;; have any args for the root-task --> they will be
;; in the child HEM of this one.
;; :node/args args
)
hem-network {:plan/plid plan-id
:network/id hem-network-id
:network/type :hem-network
:network/begin (composite-key plan-id begin-id)
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc hem-plid-id hem-network htn-plid-id htn-network)
(swap! plans update-in [:plan/by-plid plan-id]
(fn [p]
(assoc p
:plan/networks (conj (:plan/networks p) hem-plid-id htn-plid-id)
:plan/begin hem-plid-id)))
;; add begin hem node
(update-node plans begin)
(swap! plans update-in
[:network/network-by-plid-id hem-plid-id :network/nodes]
conj begin-plid-id)
(loop [edges [] root (first rootnodes) more (rest rootnodes)]
(if-not root
;; add hem edges from begin
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id hem-plid-id
edge begin-plid-id order net)))))
;; add this htn-node
(let [htn-node (get net root)
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec (:edges htn-node))
;; edges (set/union edges (:edges htn-node))
n-plid-id (composite-key plan-id root)
node (assoc-if {:plan/plid plan-id
:node/id root
:node/type (:type htn-node)
:node/parent htn-plid-id}
:node/label (:label htn-node)
:node/display-name (:display-name htn-node)
:node/args (:args htn-node))]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id htn-plid-id :network/nodes]
conj n-plid-id)
(recur edges (first more) (rest more)))))
nil)))
;; TPN ---------------------
(declare add-tpn-node)
;; nil on success
(defn add-tpn-edge [plans plan-id network-plid-id edge-id from-plid-id to-id
net & [default-order]]
(let [plid-id (composite-key plan-id edge-id)
net-edge (get net edge-id)
;; :temporal-constraint :activity :null-activity
{:keys [tpn-type end-node constraints
value ;; value is bounds in :temporal-constraint
between between-ends between-starts ;; :temporal-constraint
name label display-name args
sequence-label sequence-end ;; :activity
plant plantid command args argsmap non-primitive ;; :activity
cost reward controllable;; :activity :null-activity
probability guard ;; :null-activity
network-flows htn-node order]} net-edge
to-id (or end-node to-id)
to-plid-id (composite-key plan-id to-id)
edge (assoc-if
(if (nil? controllable) {} {:edge/controllable controllable})
:plan/plid plan-id
:edge/id edge-id
:edge/type tpn-type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)
:edge/value value ;; bounds for temporal constraint
:edge/between between
:edge/between-ends between-ends
:edge/between-starts between-starts
:edge/name name
:edge/label label
:edge/display-name display-name
:edge/args args
:edge/sequence-label sequence-label
:edge/sequence-end sequence-end
:edge/plant plant
:edge/plantid plantid
:edge/command command
:edge/args args
:edge/argsmap argsmap
:edge/cost cost
:edge/reward reward
:edge/probability probability
:edge/guard guard
:edge/network-flows network-flows
:edge/non-primitive non-primitive
:edge/htn-node htn-node)]
;; (log-debug "ADDING EDGE" plid-id "TO-ID" to-id "END-NODE" end-node)
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
from-plid-id to-id net)))
;; (if (not (keyword? to-id))
;; (log-debug "NOT KEYWORD TO-ID" to-id))
(add-tpn-node plans plan-id network-plid-id to-id net)
;; FIXME handle network-flows non-primitive
nil))
;; nil on success
(defn add-tpn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
node (get-in @plans [:node/node-by-plid-id plid-id])]
;; (log-debug "ADDING NODE?" node-id "NODE" node)
(when-not node
;; :state :c-begin :p-begin :c-end :p-end
(let [net-node (get net node-id)
{:keys [tpn-type activities ;; mandatory
constraints end-node
label display-name args sequence-label sequence-end
probability htn-node]} net-node
;; HERE we assume at some point in the future activities
;; will become a vector (because order is important)
activities (vec activities)
end-node (if end-node (composite-key plan-id end-node))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type tpn-type}
:node/end end-node
:node/label label
:node/display-name display-name
:node/args args
:node/sequence-label sequence-label
:node/sequence-end sequence-end
:node/probability probability
:node/htn-node htn-node)]
;; (log-debug "ADDING NODE" plid-id "ACTIVITIES" activities
;; "END-NODE" end-node)
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? activities)
(doall
(for [order (range (count activities))
:let [activity (get activities order)]]
(add-tpn-edge plans plan-id network-plid-id activity
plid-id end-node net order))))
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
plid-id end-node net)))
nil))))
(declare find-end)
(defn inc-number-last [number]
(let [subgraph (vec (or (butlast number) []))
n (inc (or (last number) -1))]
(conj subgraph n)))
;; returns context
(defn set-number [plans plan-id prev-context numbers node? x]
(if node?
(let [{:keys [node/id node/type node/begin node/context node/number]} x
begin? (#{:p-begin :c-begin} type)
end? (#{:p-end :c-end} type)
no-context? (nil? context) ;; first pass
context (if no-context? prev-context context)
number (if no-context?
(get (swap! numbers update-in [context] inc-number-last) context)
number)
node-id (composite-key plan-id id)
edge-context (if begin?
node-id
(if end?
(:node/context (get-node plans begin))
context))]
(if (and begin? no-context?)
(swap! numbers assoc edge-context (conj number -1)))
(when no-context?
(update-node plans (assoc x :node/context context :node/number number)))
edge-context)
(let [number
(get (swap! numbers update-in [prev-context] inc-number-last)
prev-context)]
(update-edge plans (assoc x :edge/number number))
prev-context)))
(declare visit-nodes)
(declare map-outgoing)
;; add experimental node/edge numbers
;; nil on success
(defn number-nodes-edges [plans plan-id begin-id end-id nodes]
(let [context ::top
numbers (atom {context [-1]})]
(visit-nodes plans begin-id #{end-id}
(fn [node]
(let [edge-context (set-number plans plan-id context numbers true node)]
(remove nil?
(map-outgoing plans node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(when follow?
(set-number plans plan-id edge-context numbers false edge)
(set-number plans plan-id edge-context numbers true
(get-node plans to))
to))))))))
;; remove :node/context
(doseq [node nodes]
(let [node (get-node plans node)
plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plans assoc-in ref (dissoc node :node/context))))
nil))
;; nil on success
(defn add-tpn-network [plans plan-id network-id net]
(let [net-network (get net network-id)
{:keys [begin-node end-node]} net-network
begin-id (composite-key plan-id begin-node)
end-node (or end-node
;; NOTE: the following will likely MISS the true end
;; if the plan is a top level sequence, beginning with
;; p-begin or c-begin
;; (:end-node (get net begin-node))
::walk)
end-id (if (= end-node ::walk) end-node (composite-key plan-id end-node))
network-plid-id (composite-key plan-id network-id)
network {:plan/plid plan-id
:network/id network-id
:network/type :tpn-network
:network/begin begin-id
:network/end end-id
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc network-plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj network-plid-id)
;; (if (not (keyword? begin-node))
;; (log-debug "NOT KEYWORD BEGIN-NODE" begin-node))
(add-tpn-node plans plan-id network-plid-id begin-node net)
;; create *-end pointer
(let [nodes (:network/nodes
(get-in @plans [:network/network-by-plid-id network-plid-id]))
find-end? (= end-node ::walk)] ;; walk the graph to find the end node
;; (log-debug "DEBUG NODES =========")
;; (log-debug "\n" (with-out-str (pprint nodes)))
(doseq [node nodes]
(let [node (get-node plans node)
{:keys [node/type node/id node/end]} node
node-id (composite-key plan-id id)
end-node (if (and (#{:p-begin :c-begin} type) end)
(get-node plans end))]
;; (log-debug "NODE-ID" node-id "END" end "NODE" node)
(if-not (empty? end-node)
(update-node plans (assoc end-node :node/begin node-id))
;; (if end
;; (log-debug "END NODE" end "NOT FOUND?"))
)))
(when find-end?
(swap! plans assoc-in [:network/network-by-plid-id
network-plid-id :network/end]
(if find-end?
(find-end plans plan-id begin-id)
end-id)))
(number-nodes-edges plans plan-id begin-id end-id nodes))))
;; nil on success
(defn add-plan [plans network-type plan-id plan-name net & [corresponding-id]]
(let [begin (if (= network-type :htn-network)
:top-hem-network-id
(:network-id net))
plan (assoc-if {:plan/plid plan-id
:plan/name plan-name
:plan/type network-type
:plan/begin (composite-key plan-id begin)
:plan/networks []}
:plan/corresponding corresponding-id)]
(swap! plans
(fn [st]
(let [{:keys [plans/plans plan/by-plid
network/network-by-plid-id
node/node-by-plid-id edge/edge-by-plid-id
]} st
st-plans (or plans [])
st-by-plid (or by-plid {})
st-network-by-plid-id (or network-by-plid-id {})
st-node-by-plid-id (or node-by-plid-id {})
st-edge-by-plid-id (or edge-by-plid-id {})
by-plid {plan-id plan}]
(assoc st
:plans/plans (vec (set (conj st-plans plan-id)))
:plan/by-plid (merge st-by-plid by-plid)
:network/network-by-plid-id st-network-by-plid-id
:edge/edge-by-plid-id st-edge-by-plid-id
:node/node-by-plid-id st-node-by-plid-id
)
)))
((if (= network-type :htn-network) add-hem-network add-tpn-network)
plans plan-id begin net)
nil))
;; look in the TPN
;; pick the begin network
;; look at the edges that are activities AND p-begin c-begin nodes
;; (NOTE: include state nodes if superfluous NA's have not been removed)
;; if one has htn-node then the from is the tpn-node
;; link that htn-node to that tpn activity or tpn node
(defn link-htn-nodes-to-tpn-nodes [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @tpn-plan
tpn-by-plid by-plid
tpn-network-by-plid-id network-by-plid-id
tpn-edge-by-plid-id edge-by-plid-id
tpn-node-by-plid-id node-by-plid-id
tpn-plan-id (first (keys tpn-by-plid))
tpn-plan0 (get tpn-by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get tpn-network-by-plid-id begin)
{:keys [network/nodes network/edges]} tpn-network
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plan-id (first (keys by-plid))]
(doseq [edge edges]
(let [edge (get-edge tpn-plan edge)
{:keys [edge/type edge/id edge/from edge/htn-node]} edge
from-node (get-node tpn-plan from)
from-htn-node-id (if-let [h (:node/htn-node from-node)]
(composite-key htn-plan-id h))
;; from-htn-node-id (composite-key tpn-plan from)
from-htn-node (if from-htn-node-id
(get-node htn-plan from-htn-node-id))
from-htn-node-tpn-selection (or (:node/tpn-selection from-htn-node) [])
edge-id (composite-key tpn-plan-id id)
htn-node-id (if htn-node (composite-key htn-plan-id htn-node))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
(when (and (or (= type :activity) (= type :delay-activity)) htn-node-id)
(if (not hnode)
(log-error "edge" edge-id "specifies htn-node" htn-node "but"
htn-node-id "is not found")
(do
(update-edge tpn-plan ;; fully qualify the htn-node
(assoc edge :edge/htn-node htn-node-id))
(when (and from-htn-node-id
(or (not= from-htn-node-id htn-node-id)
(not (some #(= (second %) edge-id)
from-htn-node-tpn-selection))))
;; (log-warn "FROM-NODE" from
;; "htn-node will change from" from-htn-node-id
;; "to" htn-node-id) ;; DEBUG
;; add this to the htn-node selection before it's lost
(update-node htn-plan
(assoc from-htn-node
:node/tpn-selection (conj from-htn-node-tpn-selection
[:edge edge-id]))))
(update-node tpn-plan ;; give the from the htn-node also!
(assoc from-node
:node/htn-node htn-node-id))
(update-node htn-plan ;; backpointer link the htn-node --> edge
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:edge edge-id]))
(assoc hnode
:node/tpn-edge edge-id))))))))
(doseq [node nodes]
(let [node (get-node tpn-plan node)
{:keys [node/type node/id node/htn-node node/end]} node
node-id (composite-key tpn-plan-id id)
from-node? (and htn-node (composite-key? htn-node))
htn-node-id (if htn-node
(if from-node?
htn-node
(composite-key htn-plan-id htn-node)))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
;; :state for extra nodes when superfluous not removed
(when (and (not from-node?) ;; b/c activity will have the link
(#{:p-begin :c-begin :state} type)
htn-node-id)
(if (not hnode)
(log-error "node" node-id "specficies htn-node" htn-node
"but" htn-node-id "is not found")
(do
(update-node tpn-plan ;; fully qualify the htn-node
(assoc node :node/htn-node htn-node-id))
(update-node htn-plan
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:node node-id]))
(assoc hnode
:node/tpn-node node-id))))))))))
(defn visit-nodes [tpn-plan node-id prev-visited node-fn]
(if (prev-visited node-id)
prev-visited
(let [node (get-node tpn-plan node-id)
visited (atom (conj prev-visited node-id))
tovisit (remove nil? (node-fn node))] ;; visit any nodes returned
(loop [visit (first tovisit) more (rest tovisit)]
(when visit
(swap! visited set/union (visit-nodes tpn-plan visit @visited node-fn))
(recur (first more) (rest more))))
@visited)))
;; since we have not precomputed outgoing we'll figure
;; it out the hard way
(defn map-outgoing [tpn-plan node edge-fn]
(let [node-id (node-key-fn node)
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id]} @tpn-plan
tpn-plan-id (first (keys by-plid))
tpn-plan0 (get by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get network-by-plid-id begin)
{:keys [network/edges]} tpn-network
from-node (fn [e]
(let [edge (get edge-by-plid-id e)]
(if (= (:edge/from edge) node-id) edge)))
outgoing (remove nil? (map from-node edges))]
(doall (map edge-fn outgoing))))
;; returns end-id
(defn find-end [plan plan-id begin-id]
(let [the-end (atom :end-not-found)]
(visit-nodes plan begin-id #{}
(fn [node]
(when (= @the-end :end-not-found)
(reset! the-end (composite-key plan-id (:node/id node)))
(remove nil?
(map-outgoing plan node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(if to ;; that was not the end
(reset! the-end :end-not-found))
(if follow?
to))))))))
@the-end))
;; new generation using :node/number and :edge/number
;; is sel within node-id?
(defn is-within-node? [tpn-plan sel node-id]
(let [node (get-node tpn-plan node-id)
{:keys [node/number]} node
[element id] sel
sel-number (if (= :node element)
(:node/number (get-node tpn-plan id))
(:edge/number (get-edge tpn-plan id)))
number-n (count number)
sel-number-n (count sel-number)]
(and (> sel-number-n number-n)
(= number
(vec (take number-n sel-number))))))
;; return the parts of sub in selection
(defn selection-subset [tpn-plan sub selection]
(loop [a-subs [] a (first sub) a-more (rest sub)]
(if-not a
a-subs
(let [within? (loop [b (first selection) b-more (rest selection)]
(if-not b
false
(if (or (= a b) (and (= (first b) :node)
(is-within-node?
tpn-plan a (second b))))
true
(recur (first b-more) (rest b-more)))))
a-subs (if within? (conj a-subs a) a-subs)]
(recur a-subs (first a-more) (rest a-more))))))
(defn remove-subset [selection remove]
(loop [selection selection r (first remove) more (rest remove)]
(if-not r
selection
(do
(recur (vec (filter #(not= % r) selection)) (first more) (rest more))))))
;; return the minimal representation of sel
;; first find any leader nodes among the nodes
;; then add in any non comprised edges
(defn minimal-selection [tpn-plan sel]
(let [mnodes (vec (remove nil? (filter #(= :node (first %)) sel)))
medges (remove nil? (filter #(= :edge (first %)) sel))
msel (loop [msel [] n (first mnodes) more (rest mnodes)]
(if-not n
msel
(let [node-subset (selection-subset tpn-plan [n] msel)
subset-node (selection-subset tpn-plan msel [n])
msel (cond
(not (empty? node-subset))
msel ;; n is already in msel
(not (empty? subset-node))
;; remove the subset-node in msel already, add n
(conj (remove-subset msel subset-node) n)
:else
(conj msel n))]
(recur msel (first more) (rest more)))))
msel (loop [msel msel e (first medges) more (rest medges)]
(if-not e
msel
(let [edge-subset (selection-subset tpn-plan [e] msel)
msel (cond
(not (empty? edge-subset))
msel ;; e is already in msel
:else
(conj msel e))]
(recur msel (first more) (rest more)))))]
msel))
;; collect selection comprising
;; -- all tpn-node/tpn-edge from the htn network
;; -- for all child hem's
;; if they have a tpn-selection, use it
;; else recurse
(defn update-tpn-selection [htn-plan tpn-plan network-by-plid-id hem-network
hem tpn-selection]
(let [hem-id (node-key-fn hem)
{:keys [node/htn-network]} hem
htn-net (get network-by-plid-id htn-network)
{:keys [network/nodes]} htn-net
{:keys [network/edges]} hem-network
selection (if tpn-selection (set tpn-selection) #{})
selection (loop [selection selection n (first nodes) more (rest nodes)]
(if-not n
selection
(let [{:keys [node/tpn-edge node/tpn-node]}
(get-node htn-plan n)
sel (if tpn-edge [:edge tpn-edge]
(if tpn-node [:node tpn-node]))]
(recur (if sel (conj selection sel) selection)
(first more) (rest more)))))
selection (loop [selection selection e (first edges) more (rest edges)]
(if-not e
selection
(let [{:keys [edge/from edge/to]} (get-edge htn-plan e)
hnode (get-node htn-plan to)
{:keys [node/tpn-selection
node/tpn-selection-complete?]} hnode
tpn-selection (if (= from hem-id)
(if tpn-selection-complete?
tpn-selection
(update-tpn-selection
htn-plan tpn-plan
network-by-plid-id
hem-network hnode
tpn-selection)))]
(recur (if tpn-selection
(set/union selection (set tpn-selection))
selection)
(first more) (rest more)))))
;; _ (log-warn "BEFORE MINIMAL" selection) ;; DEBUG
selection (minimal-selection tpn-plan (vec selection))]
(update-node htn-plan
(assoc hem
:node/tpn-selection selection
:node/tpn-selection-complete? true))
;; (log-warn "DEBUG update-tpn-selection" hem-id "=" selection) ;; DEBUG
selection))
(defn complete-tpn-selections [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plid (first (keys by-plid))
htn-plan0 (get by-plid htn-plid)
{:keys [plan/begin]} htn-plan0
hem-network (get network-by-plid-id begin)
{:keys [network/nodes]} hem-network]
(doseq [node nodes]
(let [node (get-node htn-plan node)
{:keys [node/tpn-selection node/tpn-selection-complete?]} node]
(when-not tpn-selection-complete?
;; collect all from htn-network and edges from this hem
(update-tpn-selection
htn-plan tpn-plan network-by-plid-id hem-network
node tpn-selection))))))
;; returns {:error} map or plans
(defn merge-htn-tpn
"Merge HTN+TPN"
{:added "0.1.0"}
[htn htn-name tpn tpn-name]
(let [htn-plan (atom {})
tpn-plan (atom {})
htn-id (name->id htn-name)
tpn-id (name->id tpn-name)]
(or
(add-plan htn-plan :htn-network htn-id htn-name htn tpn-id)
(add-plan tpn-plan :tpn-network tpn-id tpn-name tpn htn-id)
;; cross link here
(link-htn-nodes-to-tpn-nodes htn-plan tpn-plan)
(complete-tpn-selections htn-plan tpn-plan)
[(sort-map @htn-plan)
(sort-map @tpn-plan)])))
;; returns a plan map on success or :error on failure
(defn tpn-plan
"Parse TPN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one TPN file"})
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
[error tpn] (if error
[error nil]
(if (empty? tpn-filename)
[{:error
(str "Expected a TPN file, but tpn is not in the filename: " input)}
nil]
(let [rv (parse-tpn {:input tpn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
tpn-plan (atom {})
tpn-name (if-not error (first (fs/split-ext tpn-filename)))
_ (if-not error
(add-plan tpn-plan :tpn-network (name->id tpn-name) tpn-name tpn))
out (or error
(sort-map @tpn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn htn-plan
"Parse HTN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one HTN file"})
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
[error htn] (if error
[error nil]
(if (empty? htn-filename)
[{:error (str "Expected a HTN file, but htn is not in the filename: " input)} nil]
(let [rv (parse-htn {:input htn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
htn-plan (atom {})
htn-name (if-not error (first (fs/split-ext htn-filename)))
_ (if-not error
(add-plan htn-plan :htn-network (name->id htn-name) htn-name htn))
out (or error
(sort-map @htn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn merge-networks
"Merge HTN+TPN inputs"
{:added "0.1.0"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 2 (count input)))
"input must include exactly one HTN and one TPN file")
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
error (or error
(if (empty? htn-filename)
(str "HTN file not one of: " input)
(if (empty? tpn-filename)
(str "TPN file not one of: " input))))
htn-filename (if-not error (validate-input htn-filename cwd))
error (or error (:error htn-filename))
tpn-filename (if-not error (validate-input tpn-filename cwd))
error (or error (:error tpn-filename))
htn (if (not error) (parse-htn {:input htn-filename :output "-"
:cwd cwd}))
error (or error (:error htn))
tpn (if (not error) (parse-tpn {:input tpn-filename :output "-"
:cwd cwd}))
;; _ (log-debug "== TPN begin ==")
;; _ (log-debug "\n" (with-out-str (pprint tpn)))
;; _ (log-debug "== TPN end ==")
error (or error (:error tpn))
out (if error
{:error error}
(merge-htn-tpn
htn (first (fs/split-ext htn-filename))
tpn (first (fs/split-ext tpn-filename))))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when error
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
| 96058 | ;; Copyright © 2016 Dynamic Object Language Labs Inc.
;;
;; This software is licensed under the terms of the
;; Apache License, Version 2.0 which can be found in
;; the file LICENSE at the root of this distribution.
(ns plan-schema.core
"Temporal Planning Network schema utilities"
(:require [clojure.string :as string]
[clojure.set :as set]
[plan-schema.coerce :as records]
[plan-schema.utils :refer [synopsis strict? fs-basename
error? stdout-option?
read-json-str write-json-str
log-trace log-debug log-info
log-warn log-error]]
[plan-schema.sorting :refer [sort-map]]
[clojure.pprint :refer [pprint]]
[avenir.utils :as au
:refer [keywordize assoc-if concatv]]
[schema.core :as s]
[schema.coerce :as coerce]
[schema.utils :as su]
[schema.spec.core :as spec]
[me.raynes.fs :as fs]))
;; TPN-------------------------------------------------------------------
(defn network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema network-id
"network-id"
s/Keyword)
(def check-network-id (s/checker network-id))
(defn network? [x]
(and (map? x)
(#{:network
"network"
"NETWORK"} (get x :tpn-type))))
(s/defschema eq-network?
"eq-network?"
(s/conditional
keyword? (s/eq :network)
#(and (string? %)
(= "network" (string/lower-case %))) s/Keyword
'eq-network?))
(s/defschema network
"An network"
{:tpn-type eq-network?
:uid s/Keyword
:begin-node s/Keyword
(s/optional-key :end-node) s/Keyword})
(def check-network (s/checker network))
(s/defschema non-primitive
"A non-primitive is false or a network"
(s/conditional
false? (s/eq false)
keyword? s/Keyword
string? s/Keyword
'non-primitive?))
(def check-non-primitive (s/checker non-primitive))
(s/defschema upper-bound
"upper-bound"
(s/conditional
#(= :infinity %) (s/eq :infinity)
number? s/Num
'upper-bound?))
(def check-upper-bound (s/checker upper-bound))
(s/defschema bounds
"Temporal bounds"
[(s/one s/Num "lower-bound")
(s/one upper-bound "upper-bound")])
(def check-bounds (s/checker bounds))
(defn lvar? [x]
(and (map? x)
(#{:lvar
"lvar"
"LVAR"} (get x :type))))
(s/defschema eq-lvar?
"eq-lvar?"
(s/conditional
keyword? (s/eq :lvar)
#(and (string? %)
(= "lvar" (string/lower-case %))) s/Keyword
'eq-lvar?))
(s/defschema lvar
"A temporal constraint"
{:type eq-lvar?
:name s/Str
(s/optional-key :default) bounds})
(def check-lvar (s/checker lvar))
(s/defschema bounds-or-lvar
"bounds-or-lvar"
(s/conditional
vector? bounds
map? lvar
'bounds-or-lvar?))
(def check-bounds-or-lvar (s/checker bounds-or-lvar))
(s/defschema args
"plant function args (positional)"
[s/Any])
(def check-args (s/checker args))
(s/defschema argsmap
"plant function args (by parameter name)"
{s/Keyword s/Any})
(def check-argsmap (s/checker argsmap))
(s/defschema between
"between constraint [from to]"
[(s/one s/Keyword "between-from-label")
(s/one s/Keyword "between-to-label")])
(def check-between (s/checker between))
(defn temporal-constraint? [x]
(and (map? x)
(#{:temporal-constraint
"temporal-constraint"
"TEMPORAL-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-temporal-constraint?
"eq-temporal-constraint?"
(s/conditional
keyword? (s/eq :temporal-constraint)
#(and (string? %)
(= "temporal-constraint" (string/lower-case %))) s/Keyword
'eq-temporal-constraint?))
(s/defschema temporal-constraint
"A temporal constraint"
{:tpn-type eq-temporal-constraint?
:uid s/Keyword
:value bounds-or-lvar
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-temporal-constraint (s/checker temporal-constraint))
(defn cost<=-constraint? [x]
(and (map? x)
(#{:cost<=-constraint
"cost<=-constraint"
"COST<=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-cost<=-constraint?
"eq-cost<=-constraint?"
(s/conditional
keyword? (s/eq :cost<=-constraint)
#(and (string? %)
(= "cost<=-constraint" (string/lower-case %))) s/Keyword
'eq-cost<=-constraint?))
(s/defschema cost<=-constraint
"A cost<= constraint"
{:tpn-type eq-cost<=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-cost<=-constraint (s/checker cost<=-constraint))
(defn reward>=-constraint? [x]
(and (map? x)
(#{:reward>=-constraint
"reward>=-constraint"
"REWARD>=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-reward>=-constraint?
"eq-reward>=-constraint?"
(s/conditional
keyword? (s/eq :reward>=-constraint)
#(and (string? %)
(= "reward>=-constraint" (string/lower-case %))) s/Keyword
'eq-reward>=-constraint?))
(s/defschema reward>=-constraint
"A reward>= constraint"
{:tpn-type eq-reward>=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-reward>=-constraint (s/checker reward>=-constraint))
(s/defschema element-number
"Element number"
[s/Num])
(def check-element-number (s/checker element-number))
(defn activity? [x]
(and (map? x)
(#{:activity
"activity"
"ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-activity?
"eq-activity?"
(s/conditional
keyword? (s/eq :activity)
#(and (string? %)
(= "activity" (string/lower-case %))) s/Keyword
'eq-activity?))
(s/defschema activity
"An activity"
{:tpn-type eq-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :plant) s/Str
(s/optional-key :plantid) s/Str
(s/optional-key :command) s/Str
(s/optional-key :args) args
(s/optional-key :argsmap) argsmap
(s/optional-key :non-primitive) non-primitive
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
s/Keyword s/Any
})
(def check-activity (s/checker activity))
(defn delay-activity? [x]
(and (map? x)
(#{:delay-activity
"delay-activity"
"DELAY-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-delay-activity?
"eq-delay-activity?"
(s/conditional
keyword? (s/eq :delay-activity)
#(and (string? %)
(= "delay-activity" (string/lower-case %))) s/Keyword
'eq-delay-activity?))
(s/defschema delay-activity
"An delay-activity"
{:tpn-type eq-delay-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :order) s/Num ;; order of delay-activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-delay-activity (s/checker delay-activity))
(defn null-activity? [x]
(and (map? x)
(#{:null-activity
"null-activity"
"NULL-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-null-activity?
"eq-null-activity?"
(s/conditional
keyword? (s/eq :null-activity)
#(and (string? %)
(= "null-activity" (string/lower-case %))) s/Keyword
'eq-null-activity?))
(s/defschema null-activity
"An null-activity"
{:tpn-type eq-null-activity?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :probability) s/Num
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :guard) s/Str
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-null-activity (s/checker null-activity))
(defn state? [x]
(and (map? x)
(#{:state
"state"
"STATE"} (get x :tpn-type))))
(s/defschema eq-state?
"eq-state?"
(s/conditional
keyword? (s/eq :state)
#(and (string? %)
(= "state" (string/lower-case %))) s/Keyword
'eq-state?))
(s/defschema state
"An state"
{:tpn-type eq-state?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword ;; added by the merge operation
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
(s/optional-key :end-node) s/Keyword
})
(def check-state (s/checker state))
(defn c-begin? [x]
(and (map? x)
(#{:c-begin
"c-begin"
"C-BEGIN"} (get x :tpn-type))))
(s/defschema eq-c-begin?
"eq-c-begin?"
(s/conditional
keyword? (s/eq :c-begin)
#(and (string? %)
(= "c-begin" (string/lower-case %))) s/Keyword
'eq-c-begin?))
(s/defschema c-begin
"An c-begin"
{:tpn-type eq-c-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :probability) s/Num
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-begin (s/checker c-begin))
(defn c-end? [x]
(and (map? x)
(#{:c-end
"c-end"
"C-END"} (get x :tpn-type))))
(s/defschema eq-c-end?
"eq-c-end?"
(s/conditional
keyword? (s/eq :c-end)
#(and (string? %)
(= "c-end" (string/lower-case %))) s/Keyword
'eq-c-end?))
(s/defschema c-end
"An c-end"
{:tpn-type eq-c-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :probability) s/Num
(s/optional-key :begin) s/Keyword ;; new, points to c-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-end (s/checker c-end))
(defn p-begin? [x]
(and (map? x)
(#{:p-begin
"p-begin"
"P-BEGIN"} (get x :tpn-type))))
(s/defschema eq-p-begin?
"eq-p-begin?"
(s/conditional
keyword? (s/eq :p-begin)
#(and (string? %)
(= "p-begin" (string/lower-case %))) s/Keyword
'eq-p-begin?))
(s/defschema p-begin
"An p-begin"
{:tpn-type eq-p-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-begin (s/checker p-begin))
(defn p-end? [x]
(and (map? x)
(#{:p-end
"p-end"
"P-END"} (get x :tpn-type))))
(s/defschema eq-p-end?
"eq-p-end?"
(s/conditional
keyword? (s/eq :p-end)
#(and (string? %)
(= "p-end" (string/lower-case %))) s/Keyword
'eq-p-end?))
(s/defschema p-end
"An p-end"
{:tpn-type eq-p-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :begin) s/Keyword ;; new, points to p-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-end (s/checker p-end))
;; unknown object is an escape hatch to facilitate future
;; schema evolution
(defn unknown-object? [x]
(if (strict?)
false ;; do NOT accept unknown objects
(if (map? x)
(do
(log-warn "ACCEPT" (synopsis x) "UNKNOWN object")
true)
false)))
(def known-keywords #{:tpn-type :uid :begin-node :end-node :activities
:constraints :incidence-set :label :display-name :args
:sequence-label :sequence-end :htn-node})
;; NOTE: this does not work as desired
;; (s/defschema unknown-keyword?
;; "An unknown keyword"
;; (s/conditional
;; #(not (known-keywords (keyword %))) s/Keyword
;; 'unknown-keyword?))
;; NOTE: coerce the possible keys we care about to keywords
(s/defschema unknown-object
"An unknown object"
{:tpn-type s/Keyword
:uid s/Keyword
;; (s/optional-key :begin-node) s/Keyword
;; (s/optional-key :end-node) s/Keyword
;; (s/optional-key :activities) #{s/Keyword}
;; (s/optional-key :constraints) #{s/Keyword}
;; (s/optional-key :incidence-set) #{s/Keyword}
;; (s/optional-key :label) s/Keyword ;; label for between
;; (s/optional-key :sequence-label) s/Keyword ;; label for between
;; (s/optional-key :sequence-end) s/Keyword ;; label for between
;; (s/optional-key :htn-node) s/Keyword
;; unknown-keyword? s/Any
s/Keyword s/Any
})
(def check-unknown-object (s/checker unknown-object))
(s/defschema tpn-object
"One of the valid TPN object types"
(s/conditional
network-id? network-id
network? network
temporal-constraint? temporal-constraint
cost<=-constraint? cost<=-constraint
reward>=-constraint? reward>=-constraint
activity? activity
null-activity? null-activity
delay-activity? delay-activity
state? state
c-begin? c-begin
c-end? c-end
p-begin? p-begin
p-end? p-end
unknown-object? unknown-object
'tpn-object?))
(def check-tpn-object (s/checker tpn-object))
(s/defschema tpn
"A TPN"
{s/Keyword tpn-object})
(def check-tpn (s/checker tpn))
;; HTN -------------------------------------------------------------------
(defn htn-network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema htn-network-id
"network"
s/Keyword)
(def check-htn-network-id (s/checker htn-network-id))
(defn edge? [x]
(and (map? x)
(#{:edge "edge" "EDGE"} (get x :type))))
(s/defschema eq-edge?
"eq-edge?"
(s/conditional
keyword? (s/eq :edge)
#(and (string? %) (= "edge" (string/lower-case %)))
s/Keyword
'eq-edge?))
(s/defschema edge
"An edge"
{:type eq-edge?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :edge-type) s/Keyword
(s/optional-key :label) s/Str
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :order) s/Num}) ;; order of hedge
(def check-edge (s/checker edge))
(defn htn-network? [x]
(and (map? x)
(#{:htn-network
"htn-network"
"HTN-NETWORK"} (get x :type))))
(s/defschema eq-htn-network?
"eq-htn-network?"
(s/conditional
keyword? (s/eq :htn-network)
#(and (string? %) (= "htn-network" (string/lower-case %)))
s/Keyword
'eq-htn-network?))
(s/defschema htn-network
"An htn-network"
{:type eq-htn-network?
:uid s/Keyword
:label s/Str
:display-name s/Str
:rootnodes #{s/Keyword} ;; probably wants to be a vector, not a set
(s/optional-key :parentid) s/Keyword})
;; NOTE the parentid points to the parent htn-expanded-method
(def check-htn-network (s/checker htn-network))
(defn htn-primitive-task? [x]
(and (map? x)
(#{:htn-primitive-task
"htn-primitive-task"
"HTN-PRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-primitive-task?
"eq-htn-primitive-task?"
(s/conditional
keyword? (s/eq :htn-primitive-task)
#(and (string? %) (= "htn-primitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-primitive-task?))
(s/defschema htn-primitive-task
"An htn-primitive-task"
{:type eq-htn-primitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-primitive-task (s/checker htn-primitive-task))
(defn htn-expanded-method? [x]
(and (map? x)
(#{:htn-expanded-method
"htn-expanded-method"
"HTN-EXPANDED-METHOD"} (get x :type))))
(s/defschema eq-htn-expanded-method?
"eq-htn-expanded-method?"
(s/conditional
keyword? (s/eq :htn-expanded-method)
#(and (string? %) (= "htn-expanded-method" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-method?))
(s/defschema htn-expanded-method
"An htn-expanded-method"
{:type eq-htn-expanded-method?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
:network s/Keyword
(s/optional-key :edges) [s/Keyword]
;; WAS (s/optional-key :tpn-node) s/Keyword ;; new
(s/optional-key :tpn-selection) s/Any ;; new
})
(def check-htn-expanded-method (s/checker htn-expanded-method))
(defn htn-expanded-nonprimitive-task? [x]
(and (map? x)
(#{:htn-expanded-nonprimitive-task
"htn-expanded-nonprimitive-task"
"HTN-EXPANDED-NONPRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-expanded-nonprimitive-task?
"eq-htn-expanded-nonprimitive-task?"
(s/conditional
keyword? (s/eq :htn-expanded-nonprimitive-task)
#(and (string? %) (= "htn-expanded-nonprimitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-nonprimitive-task?))
(s/defschema htn-expanded-nonprimitive-task
"An htn-expanded-nonprimitive-task"
{:type eq-htn-expanded-nonprimitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-expanded-nonprimitive-task (s/checker htn-expanded-nonprimitive-task))
(s/defschema htn-object
"One of the valid HTN object types"
(s/conditional
htn-network-id? htn-network-id
htn-network? htn-network
edge? edge
htn-primitive-task? htn-primitive-task
htn-expanded-method? htn-expanded-method
htn-expanded-nonprimitive-task? htn-expanded-nonprimitive-task
'htn-object?))
(def check-htn-object (s/checker htn-object))
(s/defschema htn
"A HTN"
{s/Keyword htn-object})
(def check-htn (s/checker htn))
;; -------------------------------------------------------------------
(defn coercion [schema]
(spec/run-checker
(fn [s params]
(let [walk (spec/checker (s/spec s) params)]
(fn [x]
(let [result
(cond
(and (string? x)
(or (= s s/Keyword) (= s upper-bound)))
(walk (keyword (string/lower-case x)))
(and (= s #{s/Keyword}) (vector? x))
(walk (set x))
:else
(walk x))]
(if (su/error? result)
(if (strict?)
result
(let [xstr (synopsis x)
explanation (synopsis (s/explain s))
errstr (synopsis
(with-out-str (print (su/error-val result))))]
(log-warn "ACCEPT\n" xstr "\nEXPECTED\n" explanation "ERROR" errstr)
x)) ;; return it ANYWAY
result)))))
true
schema))
(def coerce-tpn (coercion tpn))
(def coerce-htn (coercion htn))
;; takes pathname as a string
;; plantypes as a set of valid plantypes (strings)
;; formats as a set of valid formats (strings)
;; returns true if filename matches
(defn kind-filename? [pathname plantypes formats]
(let [basename (fs-basename pathname)
[format plantype] (reverse (string/split basename #"\."))]
(boolean (and (plantypes plantype) (formats format)))))
(defn tpn-filename? [filename]
(kind-filename? filename #{"tpn"} #{"json" "edn"}))
(defn htn-filename? [filename]
(kind-filename? filename #{"htn"} #{"json" "edn"}))
(defn json-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"json"}))
(defn edn-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"edn"}))
(defn validate-input [input cwd]
(if (fs/exists? input)
input
(let [cwd-input (str cwd "/" input)]
(if (fs/exists? cwd-input)
cwd-input
{:error (str "input does not exist: " input)}))))
(defn validate-output [output cwd]
(if (stdout-option? output)
output
(if (string/starts-with? output "/")
output
(str cwd "/" output))))
(defn cleanup-relaxed-tpn
"coerces values of known-keywords to keywords"
{:added "0.2.0"}
([tpn]
(reduce-kv cleanup-relaxed-tpn {} tpn))
([m k v]
(assoc m k
(if (map? v)
(let [kw-as (seq v)]
(loop [new-v {} kw-a (first kw-as) more (rest kw-as)]
(if-not kw-a
new-v
(let [[kw a] kw-a
a (if (#{:activities :constraints :incidence-set} kw)
(set (map keyword a))
(if (known-keywords kw)
(keyword a)
a))
new-v (assoc new-v kw a)]
(recur new-v (first more) (rest more))))))
v))))
;; returns a network map -or- {:error "error message"}
(defn parse-network
"Parse TPN"
{:added "0.1.0"}
[network-type options]
(let [{:keys [verbose file-format input output cwd]} options
;; _ (println "Reading input from:" input)
verbose? (and (not (nil? verbose)) (pos? verbose))
input (validate-input (if (vector? input) (first input) input) cwd)
data (if (:error input) input (slurp input))
data (if (:error data)
data
(if (json-filename? input)
(read-json-str data)
(read-string data)))
;;_ (println "DEBUG DATA\n" (with-out-str (pprint data)))
result (if (:error data)
data
(if (= network-type :htn)
#_(coerce-htn data)
(records/coerce data)
#_(coerce-tpn data)
(records/coerce data))
)
;;_ (println "DEBUG RESULT\n" (with-out-str (pprint result)))
out (if (:error result)
result
(if (su/error? result)
{:error (with-out-str (println (:error result)))}
(sort-map result)))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when (:error out)
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
;; returns a map with :tpn on success or :error on failure
(defn parse-tpn
"Parse TPN"
{:added "0.1.0"}
[options]
(parse-network :tpn options))
(defn parse-htn
"Parse HTN"
{:added "0.1.0"}
[options]
(parse-network :htn options))
;; -------------------------------------------------------------
(defn name->id [name]
(if (keyword? name)
name
(keyword (string/replace (string/lower-case name) #"\s+" "_"))))
(defn composite-key [k1 k2]
(keyword (subs (str k1 k2) 1)))
(defn composite-key? [k]
(= 2 (count (string/split (name k) #":"))))
(defn composite-key-fn [k1 k2]
(fn [props]
(keyword (subs (str (get props k1) (get props k2)) 1))))
(def node-key-fn (composite-key-fn :plan/plid :node/id))
(def edge-key-fn (composite-key-fn :plan/plid :edge/id))
(def activity-types #{:activity :null-activity :delay-activity})
(defn activity-type? [edge-or-type]
(activity-types (if (map? edge-or-type)
(:edge/type edge-or-type)
edge-or-type)))
;; HTN ---------------------
(defn get-node [plan node-id]
(get-in @plan [:node/node-by-plid-id node-id]))
(defn update-node [plan node]
;; (log-debug "UPDATE-NODE" node)
(let [plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plan update-in ref merge node)))
(defn get-edge [plan edge-id]
(get-in @plan [:edge/edge-by-plid-id edge-id]))
(defn update-edge [plan edge]
(let [plid-id (edge-key-fn edge)
ref [:edge/edge-by-plid-id plid-id]]
(swap! plan update-in ref merge edge)))
(declare add-htn-node)
(defn add-htn-edge [plans plan-id network-plid-id edge-id from-plid-id net]
(let [plid-id (composite-key plan-id edge-id)
htn-edge (get net edge-id)
{:keys [end-node label display-name args]} htn-edge
type :sequence-edge
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-htn-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-htn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
htn-node (get net node-id)
{:keys [type label display-name args edges]} htn-node
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type
:node/parent network-plid-id}
:node/label label
:node/display-name display-name
:node/args args)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? edges)
(doseq [edge edges]
;; workaround schema coercion problem
(let [edge-id (if (keyword? edge) edge (keyword edge))]
(add-htn-edge plans plan-id network-plid-id edge-id plid-id net))))
nil))
;; nil on success
(defn add-htn-network [plans plan-id network-id net]
(let [htn-network (get net network-id)
{:keys [type label display-name rootnodes parentid]} htn-network
plid-id (composite-key plan-id network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
network (assoc-if {:plan/plid plan-id
:network/id network-id
:network/type type
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes
:network/parent (composite-key plan-id parentid))]
(swap! plans update-in [:network/network-by-plid-id]
assoc plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj plid-id)
(when-not (empty? rootnodes)
(doseq [rootnode rootnodes]
(add-htn-node plans plan-id plid-id rootnode net)))
nil))
(declare add-hem-node)
(defn add-hem-edge [plans plan-id network-plid-id edge-id from-plid-id
default-order net]
(let [plid-id (composite-key plan-id edge-id)
hem-edge (get net edge-id)
{:keys [end-node edge-type label display-name args order]} hem-edge
type (if (= edge-type :choice) :choice-edge :parallel-edge)
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-hem-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-hem-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
hem-node (get net node-id)
{:keys [type label display-name args network edges]} hem-node
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec edges)
plid-network (if network (composite-key plan-id network))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type}
:node/label label
:node/display-name display-name
:node/args args
:node/htn-network plid-network)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when network
(add-htn-network plans plan-id network net))
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id network-plid-id
edge plid-id order net)))))
nil))
(defn unique-id [net prefix]
(let [id (keyword (gensym prefix))]
(if (get net id)
(recur net prefix)
id)))
(defn add-hem-network [plans plan-id network-id net]
(when (= network-id :top-hem-network-id)
(let [hem-network-id (unique-id net "net-") ;; for the hem network
hem-plid-id (composite-key plan-id hem-network-id)
begin-id (unique-id net "hid-") ;; for the top hem
begin-plid-id (composite-key plan-id begin-id)
htn-network-id (:network net)
htn-network (get net htn-network-id)
{:keys [label display-name rootnodes]} htn-network
htn-plid-id (composite-key plan-id htn-network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
htn-network (assoc-if {:plan/plid plan-id
:network/id htn-network-id
:network/type :htn-network
:network/parent hem-plid-id
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes)
begin (assoc-if {:plan/plid plan-id
:node/id begin-id
:node/type :htn-expanded-method
:node/htn-network htn-network-id}
:node/label label
:node/display-name (or display-name "<NAME>")
;; NOTE: for this "synthetic" top level HEM we don't
;; have any args for the root-task --> they will be
;; in the child HEM of this one.
;; :node/args args
)
hem-network {:plan/plid plan-id
:network/id hem-network-id
:network/type :hem-network
:network/begin (composite-key plan-id begin-id)
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc hem-plid-id hem-network htn-plid-id htn-network)
(swap! plans update-in [:plan/by-plid plan-id]
(fn [p]
(assoc p
:plan/networks (conj (:plan/networks p) hem-plid-id htn-plid-id)
:plan/begin hem-plid-id)))
;; add begin hem node
(update-node plans begin)
(swap! plans update-in
[:network/network-by-plid-id hem-plid-id :network/nodes]
conj begin-plid-id)
(loop [edges [] root (first rootnodes) more (rest rootnodes)]
(if-not root
;; add hem edges from begin
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id hem-plid-id
edge begin-plid-id order net)))))
;; add this htn-node
(let [htn-node (get net root)
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec (:edges htn-node))
;; edges (set/union edges (:edges htn-node))
n-plid-id (composite-key plan-id root)
node (assoc-if {:plan/plid plan-id
:node/id root
:node/type (:type htn-node)
:node/parent htn-plid-id}
:node/label (:label htn-node)
:node/display-name (:display-name htn-node)
:node/args (:args htn-node))]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id htn-plid-id :network/nodes]
conj n-plid-id)
(recur edges (first more) (rest more)))))
nil)))
;; TPN ---------------------
(declare add-tpn-node)
;; nil on success
(defn add-tpn-edge [plans plan-id network-plid-id edge-id from-plid-id to-id
net & [default-order]]
(let [plid-id (composite-key plan-id edge-id)
net-edge (get net edge-id)
;; :temporal-constraint :activity :null-activity
{:keys [tpn-type end-node constraints
value ;; value is bounds in :temporal-constraint
between between-ends between-starts ;; :temporal-constraint
name label display-name args
sequence-label sequence-end ;; :activity
plant plantid command args argsmap non-primitive ;; :activity
cost reward controllable;; :activity :null-activity
probability guard ;; :null-activity
network-flows htn-node order]} net-edge
to-id (or end-node to-id)
to-plid-id (composite-key plan-id to-id)
edge (assoc-if
(if (nil? controllable) {} {:edge/controllable controllable})
:plan/plid plan-id
:edge/id edge-id
:edge/type tpn-type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)
:edge/value value ;; bounds for temporal constraint
:edge/between between
:edge/between-ends between-ends
:edge/between-starts between-starts
:edge/name name
:edge/label label
:edge/display-name display-name
:edge/args args
:edge/sequence-label sequence-label
:edge/sequence-end sequence-end
:edge/plant plant
:edge/plantid plantid
:edge/command command
:edge/args args
:edge/argsmap argsmap
:edge/cost cost
:edge/reward reward
:edge/probability probability
:edge/guard guard
:edge/network-flows network-flows
:edge/non-primitive non-primitive
:edge/htn-node htn-node)]
;; (log-debug "ADDING EDGE" plid-id "TO-ID" to-id "END-NODE" end-node)
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
from-plid-id to-id net)))
;; (if (not (keyword? to-id))
;; (log-debug "NOT KEYWORD TO-ID" to-id))
(add-tpn-node plans plan-id network-plid-id to-id net)
;; FIXME handle network-flows non-primitive
nil))
;; nil on success
(defn add-tpn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
node (get-in @plans [:node/node-by-plid-id plid-id])]
;; (log-debug "ADDING NODE?" node-id "NODE" node)
(when-not node
;; :state :c-begin :p-begin :c-end :p-end
(let [net-node (get net node-id)
{:keys [tpn-type activities ;; mandatory
constraints end-node
label display-name args sequence-label sequence-end
probability htn-node]} net-node
;; HERE we assume at some point in the future activities
;; will become a vector (because order is important)
activities (vec activities)
end-node (if end-node (composite-key plan-id end-node))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type tpn-type}
:node/end end-node
:node/label label
:node/display-name display-name
:node/args args
:node/sequence-label sequence-label
:node/sequence-end sequence-end
:node/probability probability
:node/htn-node htn-node)]
;; (log-debug "ADDING NODE" plid-id "ACTIVITIES" activities
;; "END-NODE" end-node)
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? activities)
(doall
(for [order (range (count activities))
:let [activity (get activities order)]]
(add-tpn-edge plans plan-id network-plid-id activity
plid-id end-node net order))))
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
plid-id end-node net)))
nil))))
(declare find-end)
(defn inc-number-last [number]
(let [subgraph (vec (or (butlast number) []))
n (inc (or (last number) -1))]
(conj subgraph n)))
;; returns context
(defn set-number [plans plan-id prev-context numbers node? x]
(if node?
(let [{:keys [node/id node/type node/begin node/context node/number]} x
begin? (#{:p-begin :c-begin} type)
end? (#{:p-end :c-end} type)
no-context? (nil? context) ;; first pass
context (if no-context? prev-context context)
number (if no-context?
(get (swap! numbers update-in [context] inc-number-last) context)
number)
node-id (composite-key plan-id id)
edge-context (if begin?
node-id
(if end?
(:node/context (get-node plans begin))
context))]
(if (and begin? no-context?)
(swap! numbers assoc edge-context (conj number -1)))
(when no-context?
(update-node plans (assoc x :node/context context :node/number number)))
edge-context)
(let [number
(get (swap! numbers update-in [prev-context] inc-number-last)
prev-context)]
(update-edge plans (assoc x :edge/number number))
prev-context)))
(declare visit-nodes)
(declare map-outgoing)
;; add experimental node/edge numbers
;; nil on success
(defn number-nodes-edges [plans plan-id begin-id end-id nodes]
(let [context ::top
numbers (atom {context [-1]})]
(visit-nodes plans begin-id #{end-id}
(fn [node]
(let [edge-context (set-number plans plan-id context numbers true node)]
(remove nil?
(map-outgoing plans node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(when follow?
(set-number plans plan-id edge-context numbers false edge)
(set-number plans plan-id edge-context numbers true
(get-node plans to))
to))))))))
;; remove :node/context
(doseq [node nodes]
(let [node (get-node plans node)
plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plans assoc-in ref (dissoc node :node/context))))
nil))
;; nil on success
(defn add-tpn-network [plans plan-id network-id net]
(let [net-network (get net network-id)
{:keys [begin-node end-node]} net-network
begin-id (composite-key plan-id begin-node)
end-node (or end-node
;; NOTE: the following will likely MISS the true end
;; if the plan is a top level sequence, beginning with
;; p-begin or c-begin
;; (:end-node (get net begin-node))
::walk)
end-id (if (= end-node ::walk) end-node (composite-key plan-id end-node))
network-plid-id (composite-key plan-id network-id)
network {:plan/plid plan-id
:network/id network-id
:network/type :tpn-network
:network/begin begin-id
:network/end end-id
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc network-plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj network-plid-id)
;; (if (not (keyword? begin-node))
;; (log-debug "NOT KEYWORD BEGIN-NODE" begin-node))
(add-tpn-node plans plan-id network-plid-id begin-node net)
;; create *-end pointer
(let [nodes (:network/nodes
(get-in @plans [:network/network-by-plid-id network-plid-id]))
find-end? (= end-node ::walk)] ;; walk the graph to find the end node
;; (log-debug "DEBUG NODES =========")
;; (log-debug "\n" (with-out-str (pprint nodes)))
(doseq [node nodes]
(let [node (get-node plans node)
{:keys [node/type node/id node/end]} node
node-id (composite-key plan-id id)
end-node (if (and (#{:p-begin :c-begin} type) end)
(get-node plans end))]
;; (log-debug "NODE-ID" node-id "END" end "NODE" node)
(if-not (empty? end-node)
(update-node plans (assoc end-node :node/begin node-id))
;; (if end
;; (log-debug "END NODE" end "NOT FOUND?"))
)))
(when find-end?
(swap! plans assoc-in [:network/network-by-plid-id
network-plid-id :network/end]
(if find-end?
(find-end plans plan-id begin-id)
end-id)))
(number-nodes-edges plans plan-id begin-id end-id nodes))))
;; nil on success
(defn add-plan [plans network-type plan-id plan-name net & [corresponding-id]]
(let [begin (if (= network-type :htn-network)
:top-hem-network-id
(:network-id net))
plan (assoc-if {:plan/plid plan-id
:plan/name plan-name
:plan/type network-type
:plan/begin (composite-key plan-id begin)
:plan/networks []}
:plan/corresponding corresponding-id)]
(swap! plans
(fn [st]
(let [{:keys [plans/plans plan/by-plid
network/network-by-plid-id
node/node-by-plid-id edge/edge-by-plid-id
]} st
st-plans (or plans [])
st-by-plid (or by-plid {})
st-network-by-plid-id (or network-by-plid-id {})
st-node-by-plid-id (or node-by-plid-id {})
st-edge-by-plid-id (or edge-by-plid-id {})
by-plid {plan-id plan}]
(assoc st
:plans/plans (vec (set (conj st-plans plan-id)))
:plan/by-plid (merge st-by-plid by-plid)
:network/network-by-plid-id st-network-by-plid-id
:edge/edge-by-plid-id st-edge-by-plid-id
:node/node-by-plid-id st-node-by-plid-id
)
)))
((if (= network-type :htn-network) add-hem-network add-tpn-network)
plans plan-id begin net)
nil))
;; look in the TPN
;; pick the begin network
;; look at the edges that are activities AND p-begin c-begin nodes
;; (NOTE: include state nodes if superfluous NA's have not been removed)
;; if one has htn-node then the from is the tpn-node
;; link that htn-node to that tpn activity or tpn node
(defn link-htn-nodes-to-tpn-nodes [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @tpn-plan
tpn-by-plid by-plid
tpn-network-by-plid-id network-by-plid-id
tpn-edge-by-plid-id edge-by-plid-id
tpn-node-by-plid-id node-by-plid-id
tpn-plan-id (first (keys tpn-by-plid))
tpn-plan0 (get tpn-by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get tpn-network-by-plid-id begin)
{:keys [network/nodes network/edges]} tpn-network
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plan-id (first (keys by-plid))]
(doseq [edge edges]
(let [edge (get-edge tpn-plan edge)
{:keys [edge/type edge/id edge/from edge/htn-node]} edge
from-node (get-node tpn-plan from)
from-htn-node-id (if-let [h (:node/htn-node from-node)]
(composite-key htn-plan-id h))
;; from-htn-node-id (composite-key tpn-plan from)
from-htn-node (if from-htn-node-id
(get-node htn-plan from-htn-node-id))
from-htn-node-tpn-selection (or (:node/tpn-selection from-htn-node) [])
edge-id (composite-key tpn-plan-id id)
htn-node-id (if htn-node (composite-key htn-plan-id htn-node))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
(when (and (or (= type :activity) (= type :delay-activity)) htn-node-id)
(if (not hnode)
(log-error "edge" edge-id "specifies htn-node" htn-node "but"
htn-node-id "is not found")
(do
(update-edge tpn-plan ;; fully qualify the htn-node
(assoc edge :edge/htn-node htn-node-id))
(when (and from-htn-node-id
(or (not= from-htn-node-id htn-node-id)
(not (some #(= (second %) edge-id)
from-htn-node-tpn-selection))))
;; (log-warn "FROM-NODE" from
;; "htn-node will change from" from-htn-node-id
;; "to" htn-node-id) ;; DEBUG
;; add this to the htn-node selection before it's lost
(update-node htn-plan
(assoc from-htn-node
:node/tpn-selection (conj from-htn-node-tpn-selection
[:edge edge-id]))))
(update-node tpn-plan ;; give the from the htn-node also!
(assoc from-node
:node/htn-node htn-node-id))
(update-node htn-plan ;; backpointer link the htn-node --> edge
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:edge edge-id]))
(assoc hnode
:node/tpn-edge edge-id))))))))
(doseq [node nodes]
(let [node (get-node tpn-plan node)
{:keys [node/type node/id node/htn-node node/end]} node
node-id (composite-key tpn-plan-id id)
from-node? (and htn-node (composite-key? htn-node))
htn-node-id (if htn-node
(if from-node?
htn-node
(composite-key htn-plan-id htn-node)))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
;; :state for extra nodes when superfluous not removed
(when (and (not from-node?) ;; b/c activity will have the link
(#{:p-begin :c-begin :state} type)
htn-node-id)
(if (not hnode)
(log-error "node" node-id "specficies htn-node" htn-node
"but" htn-node-id "is not found")
(do
(update-node tpn-plan ;; fully qualify the htn-node
(assoc node :node/htn-node htn-node-id))
(update-node htn-plan
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:node node-id]))
(assoc hnode
:node/tpn-node node-id))))))))))
(defn visit-nodes [tpn-plan node-id prev-visited node-fn]
(if (prev-visited node-id)
prev-visited
(let [node (get-node tpn-plan node-id)
visited (atom (conj prev-visited node-id))
tovisit (remove nil? (node-fn node))] ;; visit any nodes returned
(loop [visit (first tovisit) more (rest tovisit)]
(when visit
(swap! visited set/union (visit-nodes tpn-plan visit @visited node-fn))
(recur (first more) (rest more))))
@visited)))
;; since we have not precomputed outgoing we'll figure
;; it out the hard way
(defn map-outgoing [tpn-plan node edge-fn]
(let [node-id (node-key-fn node)
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id]} @tpn-plan
tpn-plan-id (first (keys by-plid))
tpn-plan0 (get by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get network-by-plid-id begin)
{:keys [network/edges]} tpn-network
from-node (fn [e]
(let [edge (get edge-by-plid-id e)]
(if (= (:edge/from edge) node-id) edge)))
outgoing (remove nil? (map from-node edges))]
(doall (map edge-fn outgoing))))
;; returns end-id
(defn find-end [plan plan-id begin-id]
(let [the-end (atom :end-not-found)]
(visit-nodes plan begin-id #{}
(fn [node]
(when (= @the-end :end-not-found)
(reset! the-end (composite-key plan-id (:node/id node)))
(remove nil?
(map-outgoing plan node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(if to ;; that was not the end
(reset! the-end :end-not-found))
(if follow?
to))))))))
@the-end))
;; new generation using :node/number and :edge/number
;; is sel within node-id?
(defn is-within-node? [tpn-plan sel node-id]
(let [node (get-node tpn-plan node-id)
{:keys [node/number]} node
[element id] sel
sel-number (if (= :node element)
(:node/number (get-node tpn-plan id))
(:edge/number (get-edge tpn-plan id)))
number-n (count number)
sel-number-n (count sel-number)]
(and (> sel-number-n number-n)
(= number
(vec (take number-n sel-number))))))
;; return the parts of sub in selection
(defn selection-subset [tpn-plan sub selection]
(loop [a-subs [] a (first sub) a-more (rest sub)]
(if-not a
a-subs
(let [within? (loop [b (first selection) b-more (rest selection)]
(if-not b
false
(if (or (= a b) (and (= (first b) :node)
(is-within-node?
tpn-plan a (second b))))
true
(recur (first b-more) (rest b-more)))))
a-subs (if within? (conj a-subs a) a-subs)]
(recur a-subs (first a-more) (rest a-more))))))
(defn remove-subset [selection remove]
(loop [selection selection r (first remove) more (rest remove)]
(if-not r
selection
(do
(recur (vec (filter #(not= % r) selection)) (first more) (rest more))))))
;; return the minimal representation of sel
;; first find any leader nodes among the nodes
;; then add in any non comprised edges
(defn minimal-selection [tpn-plan sel]
(let [mnodes (vec (remove nil? (filter #(= :node (first %)) sel)))
medges (remove nil? (filter #(= :edge (first %)) sel))
msel (loop [msel [] n (first mnodes) more (rest mnodes)]
(if-not n
msel
(let [node-subset (selection-subset tpn-plan [n] msel)
subset-node (selection-subset tpn-plan msel [n])
msel (cond
(not (empty? node-subset))
msel ;; n is already in msel
(not (empty? subset-node))
;; remove the subset-node in msel already, add n
(conj (remove-subset msel subset-node) n)
:else
(conj msel n))]
(recur msel (first more) (rest more)))))
msel (loop [msel msel e (first medges) more (rest medges)]
(if-not e
msel
(let [edge-subset (selection-subset tpn-plan [e] msel)
msel (cond
(not (empty? edge-subset))
msel ;; e is already in msel
:else
(conj msel e))]
(recur msel (first more) (rest more)))))]
msel))
;; collect selection comprising
;; -- all tpn-node/tpn-edge from the htn network
;; -- for all child hem's
;; if they have a tpn-selection, use it
;; else recurse
(defn update-tpn-selection [htn-plan tpn-plan network-by-plid-id hem-network
hem tpn-selection]
(let [hem-id (node-key-fn hem)
{:keys [node/htn-network]} hem
htn-net (get network-by-plid-id htn-network)
{:keys [network/nodes]} htn-net
{:keys [network/edges]} hem-network
selection (if tpn-selection (set tpn-selection) #{})
selection (loop [selection selection n (first nodes) more (rest nodes)]
(if-not n
selection
(let [{:keys [node/tpn-edge node/tpn-node]}
(get-node htn-plan n)
sel (if tpn-edge [:edge tpn-edge]
(if tpn-node [:node tpn-node]))]
(recur (if sel (conj selection sel) selection)
(first more) (rest more)))))
selection (loop [selection selection e (first edges) more (rest edges)]
(if-not e
selection
(let [{:keys [edge/from edge/to]} (get-edge htn-plan e)
hnode (get-node htn-plan to)
{:keys [node/tpn-selection
node/tpn-selection-complete?]} hnode
tpn-selection (if (= from hem-id)
(if tpn-selection-complete?
tpn-selection
(update-tpn-selection
htn-plan tpn-plan
network-by-plid-id
hem-network hnode
tpn-selection)))]
(recur (if tpn-selection
(set/union selection (set tpn-selection))
selection)
(first more) (rest more)))))
;; _ (log-warn "BEFORE MINIMAL" selection) ;; DEBUG
selection (minimal-selection tpn-plan (vec selection))]
(update-node htn-plan
(assoc hem
:node/tpn-selection selection
:node/tpn-selection-complete? true))
;; (log-warn "DEBUG update-tpn-selection" hem-id "=" selection) ;; DEBUG
selection))
(defn complete-tpn-selections [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plid (first (keys by-plid))
htn-plan0 (get by-plid htn-plid)
{:keys [plan/begin]} htn-plan0
hem-network (get network-by-plid-id begin)
{:keys [network/nodes]} hem-network]
(doseq [node nodes]
(let [node (get-node htn-plan node)
{:keys [node/tpn-selection node/tpn-selection-complete?]} node]
(when-not tpn-selection-complete?
;; collect all from htn-network and edges from this hem
(update-tpn-selection
htn-plan tpn-plan network-by-plid-id hem-network
node tpn-selection))))))
;; returns {:error} map or plans
(defn merge-htn-tpn
"Merge HTN+TPN"
{:added "0.1.0"}
[htn htn-name tpn tpn-name]
(let [htn-plan (atom {})
tpn-plan (atom {})
htn-id (name->id htn-name)
tpn-id (name->id tpn-name)]
(or
(add-plan htn-plan :htn-network htn-id htn-name htn tpn-id)
(add-plan tpn-plan :tpn-network tpn-id tpn-name tpn htn-id)
;; cross link here
(link-htn-nodes-to-tpn-nodes htn-plan tpn-plan)
(complete-tpn-selections htn-plan tpn-plan)
[(sort-map @htn-plan)
(sort-map @tpn-plan)])))
;; returns a plan map on success or :error on failure
(defn tpn-plan
"Parse TPN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one TPN file"})
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
[error tpn] (if error
[error nil]
(if (empty? tpn-filename)
[{:error
(str "Expected a TPN file, but tpn is not in the filename: " input)}
nil]
(let [rv (parse-tpn {:input tpn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
tpn-plan (atom {})
tpn-name (if-not error (first (fs/split-ext tpn-filename)))
_ (if-not error
(add-plan tpn-plan :tpn-network (name->id tpn-name) tpn-name tpn))
out (or error
(sort-map @tpn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn htn-plan
"Parse HTN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one HTN file"})
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
[error htn] (if error
[error nil]
(if (empty? htn-filename)
[{:error (str "Expected a HTN file, but htn is not in the filename: " input)} nil]
(let [rv (parse-htn {:input htn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
htn-plan (atom {})
htn-name (if-not error (first (fs/split-ext htn-filename)))
_ (if-not error
(add-plan htn-plan :htn-network (name->id htn-name) htn-name htn))
out (or error
(sort-map @htn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn merge-networks
"Merge HTN+TPN inputs"
{:added "0.1.0"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 2 (count input)))
"input must include exactly one HTN and one TPN file")
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
error (or error
(if (empty? htn-filename)
(str "HTN file not one of: " input)
(if (empty? tpn-filename)
(str "TPN file not one of: " input))))
htn-filename (if-not error (validate-input htn-filename cwd))
error (or error (:error htn-filename))
tpn-filename (if-not error (validate-input tpn-filename cwd))
error (or error (:error tpn-filename))
htn (if (not error) (parse-htn {:input htn-filename :output "-"
:cwd cwd}))
error (or error (:error htn))
tpn (if (not error) (parse-tpn {:input tpn-filename :output "-"
:cwd cwd}))
;; _ (log-debug "== TPN begin ==")
;; _ (log-debug "\n" (with-out-str (pprint tpn)))
;; _ (log-debug "== TPN end ==")
error (or error (:error tpn))
out (if error
{:error error}
(merge-htn-tpn
htn (first (fs/split-ext htn-filename))
tpn (first (fs/split-ext tpn-filename))))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when error
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
| true | ;; Copyright © 2016 Dynamic Object Language Labs Inc.
;;
;; This software is licensed under the terms of the
;; Apache License, Version 2.0 which can be found in
;; the file LICENSE at the root of this distribution.
(ns plan-schema.core
"Temporal Planning Network schema utilities"
(:require [clojure.string :as string]
[clojure.set :as set]
[plan-schema.coerce :as records]
[plan-schema.utils :refer [synopsis strict? fs-basename
error? stdout-option?
read-json-str write-json-str
log-trace log-debug log-info
log-warn log-error]]
[plan-schema.sorting :refer [sort-map]]
[clojure.pprint :refer [pprint]]
[avenir.utils :as au
:refer [keywordize assoc-if concatv]]
[schema.core :as s]
[schema.coerce :as coerce]
[schema.utils :as su]
[schema.spec.core :as spec]
[me.raynes.fs :as fs]))
;; TPN-------------------------------------------------------------------
(defn network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema network-id
"network-id"
s/Keyword)
(def check-network-id (s/checker network-id))
(defn network? [x]
(and (map? x)
(#{:network
"network"
"NETWORK"} (get x :tpn-type))))
(s/defschema eq-network?
"eq-network?"
(s/conditional
keyword? (s/eq :network)
#(and (string? %)
(= "network" (string/lower-case %))) s/Keyword
'eq-network?))
(s/defschema network
"An network"
{:tpn-type eq-network?
:uid s/Keyword
:begin-node s/Keyword
(s/optional-key :end-node) s/Keyword})
(def check-network (s/checker network))
(s/defschema non-primitive
"A non-primitive is false or a network"
(s/conditional
false? (s/eq false)
keyword? s/Keyword
string? s/Keyword
'non-primitive?))
(def check-non-primitive (s/checker non-primitive))
(s/defschema upper-bound
"upper-bound"
(s/conditional
#(= :infinity %) (s/eq :infinity)
number? s/Num
'upper-bound?))
(def check-upper-bound (s/checker upper-bound))
(s/defschema bounds
"Temporal bounds"
[(s/one s/Num "lower-bound")
(s/one upper-bound "upper-bound")])
(def check-bounds (s/checker bounds))
(defn lvar? [x]
(and (map? x)
(#{:lvar
"lvar"
"LVAR"} (get x :type))))
(s/defschema eq-lvar?
"eq-lvar?"
(s/conditional
keyword? (s/eq :lvar)
#(and (string? %)
(= "lvar" (string/lower-case %))) s/Keyword
'eq-lvar?))
(s/defschema lvar
"A temporal constraint"
{:type eq-lvar?
:name s/Str
(s/optional-key :default) bounds})
(def check-lvar (s/checker lvar))
(s/defschema bounds-or-lvar
"bounds-or-lvar"
(s/conditional
vector? bounds
map? lvar
'bounds-or-lvar?))
(def check-bounds-or-lvar (s/checker bounds-or-lvar))
(s/defschema args
"plant function args (positional)"
[s/Any])
(def check-args (s/checker args))
(s/defschema argsmap
"plant function args (by parameter name)"
{s/Keyword s/Any})
(def check-argsmap (s/checker argsmap))
(s/defschema between
"between constraint [from to]"
[(s/one s/Keyword "between-from-label")
(s/one s/Keyword "between-to-label")])
(def check-between (s/checker between))
(defn temporal-constraint? [x]
(and (map? x)
(#{:temporal-constraint
"temporal-constraint"
"TEMPORAL-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-temporal-constraint?
"eq-temporal-constraint?"
(s/conditional
keyword? (s/eq :temporal-constraint)
#(and (string? %)
(= "temporal-constraint" (string/lower-case %))) s/Keyword
'eq-temporal-constraint?))
(s/defschema temporal-constraint
"A temporal constraint"
{:tpn-type eq-temporal-constraint?
:uid s/Keyword
:value bounds-or-lvar
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-temporal-constraint (s/checker temporal-constraint))
(defn cost<=-constraint? [x]
(and (map? x)
(#{:cost<=-constraint
"cost<=-constraint"
"COST<=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-cost<=-constraint?
"eq-cost<=-constraint?"
(s/conditional
keyword? (s/eq :cost<=-constraint)
#(and (string? %)
(= "cost<=-constraint" (string/lower-case %))) s/Keyword
'eq-cost<=-constraint?))
(s/defschema cost<=-constraint
"A cost<= constraint"
{:tpn-type eq-cost<=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-cost<=-constraint (s/checker cost<=-constraint))
(defn reward>=-constraint? [x]
(and (map? x)
(#{:reward>=-constraint
"reward>=-constraint"
"REWARD>=-CONSTRAINT"} (get x :tpn-type))))
(s/defschema eq-reward>=-constraint?
"eq-reward>=-constraint?"
(s/conditional
keyword? (s/eq :reward>=-constraint)
#(and (string? %)
(= "reward>=-constraint" (string/lower-case %))) s/Keyword
'eq-reward>=-constraint?))
(s/defschema reward>=-constraint
"A reward>= constraint"
{:tpn-type eq-reward>=-constraint?
:uid s/Keyword
:value s/Num
:end-node s/Keyword
(s/optional-key :between) between
(s/optional-key :between-ends) between
(s/optional-key :between-starts) between})
(def check-reward>=-constraint (s/checker reward>=-constraint))
(s/defschema element-number
"Element number"
[s/Num])
(def check-element-number (s/checker element-number))
(defn activity? [x]
(and (map? x)
(#{:activity
"activity"
"ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-activity?
"eq-activity?"
(s/conditional
keyword? (s/eq :activity)
#(and (string? %)
(= "activity" (string/lower-case %))) s/Keyword
'eq-activity?))
(s/defschema activity
"An activity"
{:tpn-type eq-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :plant) s/Str
(s/optional-key :plantid) s/Str
(s/optional-key :command) s/Str
(s/optional-key :args) args
(s/optional-key :argsmap) argsmap
(s/optional-key :non-primitive) non-primitive
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
s/Keyword s/Any
})
(def check-activity (s/checker activity))
(defn delay-activity? [x]
(and (map? x)
(#{:delay-activity
"delay-activity"
"DELAY-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-delay-activity?
"eq-delay-activity?"
(s/conditional
keyword? (s/eq :delay-activity)
#(and (string? %)
(= "delay-activity" (string/lower-case %))) s/Keyword
'eq-delay-activity?))
(s/defschema delay-activity
"An delay-activity"
{:tpn-type eq-delay-activity?
:uid s/Keyword
:constraints #{s/Keyword}
:end-node s/Keyword
(s/optional-key :name) s/Str
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :controllable) s/Bool
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :order) s/Num ;; order of delay-activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-delay-activity (s/checker delay-activity))
(defn null-activity? [x]
(and (map? x)
(#{:null-activity
"null-activity"
"NULL-ACTIVITY"} (get x :tpn-type))))
(s/defschema eq-null-activity?
"eq-null-activity?"
(s/conditional
keyword? (s/eq :null-activity)
#(and (string? %)
(= "null-activity" (string/lower-case %))) s/Keyword
'eq-null-activity?))
(s/defschema null-activity
"An null-activity"
{:tpn-type eq-null-activity?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :probability) s/Num
(s/optional-key :cost) s/Num
(s/optional-key :reward) s/Num
(s/optional-key :guard) s/Str
(s/optional-key :order) s/Num ;; order of activity
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-null-activity (s/checker null-activity))
(defn state? [x]
(and (map? x)
(#{:state
"state"
"STATE"} (get x :tpn-type))))
(s/defschema eq-state?
"eq-state?"
(s/conditional
keyword? (s/eq :state)
#(and (string? %)
(= "state" (string/lower-case %))) s/Keyword
'eq-state?))
(s/defschema state
"An state"
{:tpn-type eq-state?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword ;; added by the merge operation
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
(s/optional-key :end-node) s/Keyword
})
(def check-state (s/checker state))
(defn c-begin? [x]
(and (map? x)
(#{:c-begin
"c-begin"
"C-BEGIN"} (get x :tpn-type))))
(s/defschema eq-c-begin?
"eq-c-begin?"
(s/conditional
keyword? (s/eq :c-begin)
#(and (string? %)
(= "c-begin" (string/lower-case %))) s/Keyword
'eq-c-begin?))
(s/defschema c-begin
"An c-begin"
{:tpn-type eq-c-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :probability) s/Num
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-begin (s/checker c-begin))
(defn c-end? [x]
(and (map? x)
(#{:c-end
"c-end"
"C-END"} (get x :tpn-type))))
(s/defschema eq-c-end?
"eq-c-end?"
(s/conditional
keyword? (s/eq :c-end)
#(and (string? %)
(= "c-end" (string/lower-case %))) s/Keyword
'eq-c-end?))
(s/defschema c-end
"An c-end"
{:tpn-type eq-c-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :probability) s/Num
(s/optional-key :begin) s/Keyword ;; new, points to c-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-c-end (s/checker c-end))
(defn p-begin? [x]
(and (map? x)
(#{:p-begin
"p-begin"
"P-BEGIN"} (get x :tpn-type))))
(s/defschema eq-p-begin?
"eq-p-begin?"
(s/conditional
keyword? (s/eq :p-begin)
#(and (string? %)
(= "p-begin" (string/lower-case %))) s/Keyword
'eq-p-begin?))
(s/defschema p-begin
"An p-begin"
{:tpn-type eq-p-begin?
:uid s/Keyword
:constraints #{s/Keyword}
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
:end-node s/Keyword
(s/optional-key :label) s/Keyword ;; label for between
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :cost<=) s/Num
(s/optional-key :reward>=) s/Num
(s/optional-key :sequence-label) s/Keyword ;; label for between
(s/optional-key :sequence-end) s/Keyword ;; label for between
(s/optional-key :htn-node) s/Keyword
;; htn-node points to htn-primitive-task or htn-expanded-nonprimitive-task
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-begin (s/checker p-begin))
(defn p-end? [x]
(and (map? x)
(#{:p-end
"p-end"
"P-END"} (get x :tpn-type))))
(s/defschema eq-p-end?
"eq-p-end?"
(s/conditional
keyword? (s/eq :p-end)
#(and (string? %)
(= "p-end" (string/lower-case %))) s/Keyword
'eq-p-end?))
(s/defschema p-end
"An p-end"
{:tpn-type eq-p-end?
:uid s/Keyword
:activities #{s/Keyword} ;; probably wants to be a vector, not a set
:incidence-set #{s/Keyword}
(s/optional-key :constraints) #{s/Keyword}
(s/optional-key :begin) s/Keyword ;; new, points to p-begin
(s/optional-key :number) element-number ;; experimental node/edge number
})
(def check-p-end (s/checker p-end))
;; unknown object is an escape hatch to facilitate future
;; schema evolution
(defn unknown-object? [x]
(if (strict?)
false ;; do NOT accept unknown objects
(if (map? x)
(do
(log-warn "ACCEPT" (synopsis x) "UNKNOWN object")
true)
false)))
(def known-keywords #{:tpn-type :uid :begin-node :end-node :activities
:constraints :incidence-set :label :display-name :args
:sequence-label :sequence-end :htn-node})
;; NOTE: this does not work as desired
;; (s/defschema unknown-keyword?
;; "An unknown keyword"
;; (s/conditional
;; #(not (known-keywords (keyword %))) s/Keyword
;; 'unknown-keyword?))
;; NOTE: coerce the possible keys we care about to keywords
(s/defschema unknown-object
"An unknown object"
{:tpn-type s/Keyword
:uid s/Keyword
;; (s/optional-key :begin-node) s/Keyword
;; (s/optional-key :end-node) s/Keyword
;; (s/optional-key :activities) #{s/Keyword}
;; (s/optional-key :constraints) #{s/Keyword}
;; (s/optional-key :incidence-set) #{s/Keyword}
;; (s/optional-key :label) s/Keyword ;; label for between
;; (s/optional-key :sequence-label) s/Keyword ;; label for between
;; (s/optional-key :sequence-end) s/Keyword ;; label for between
;; (s/optional-key :htn-node) s/Keyword
;; unknown-keyword? s/Any
s/Keyword s/Any
})
(def check-unknown-object (s/checker unknown-object))
(s/defschema tpn-object
"One of the valid TPN object types"
(s/conditional
network-id? network-id
network? network
temporal-constraint? temporal-constraint
cost<=-constraint? cost<=-constraint
reward>=-constraint? reward>=-constraint
activity? activity
null-activity? null-activity
delay-activity? delay-activity
state? state
c-begin? c-begin
c-end? c-end
p-begin? p-begin
p-end? p-end
unknown-object? unknown-object
'tpn-object?))
(def check-tpn-object (s/checker tpn-object))
(s/defschema tpn
"A TPN"
{s/Keyword tpn-object})
(def check-tpn (s/checker tpn))
;; HTN -------------------------------------------------------------------
(defn htn-network-id? [x]
(or (keyword? x) (string? x)))
(s/defschema htn-network-id
"network"
s/Keyword)
(def check-htn-network-id (s/checker htn-network-id))
(defn edge? [x]
(and (map? x)
(#{:edge "edge" "EDGE"} (get x :type))))
(s/defschema eq-edge?
"eq-edge?"
(s/conditional
keyword? (s/eq :edge)
#(and (string? %) (= "edge" (string/lower-case %)))
s/Keyword
'eq-edge?))
(s/defschema edge
"An edge"
{:type eq-edge?
:uid s/Keyword
:end-node s/Keyword
(s/optional-key :edge-type) s/Keyword
(s/optional-key :label) s/Str
(s/optional-key :display-name) s/Str
(s/optional-key :args) args
(s/optional-key :order) s/Num}) ;; order of hedge
(def check-edge (s/checker edge))
(defn htn-network? [x]
(and (map? x)
(#{:htn-network
"htn-network"
"HTN-NETWORK"} (get x :type))))
(s/defschema eq-htn-network?
"eq-htn-network?"
(s/conditional
keyword? (s/eq :htn-network)
#(and (string? %) (= "htn-network" (string/lower-case %)))
s/Keyword
'eq-htn-network?))
(s/defschema htn-network
"An htn-network"
{:type eq-htn-network?
:uid s/Keyword
:label s/Str
:display-name s/Str
:rootnodes #{s/Keyword} ;; probably wants to be a vector, not a set
(s/optional-key :parentid) s/Keyword})
;; NOTE the parentid points to the parent htn-expanded-method
(def check-htn-network (s/checker htn-network))
(defn htn-primitive-task? [x]
(and (map? x)
(#{:htn-primitive-task
"htn-primitive-task"
"HTN-PRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-primitive-task?
"eq-htn-primitive-task?"
(s/conditional
keyword? (s/eq :htn-primitive-task)
#(and (string? %) (= "htn-primitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-primitive-task?))
(s/defschema htn-primitive-task
"An htn-primitive-task"
{:type eq-htn-primitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-primitive-task (s/checker htn-primitive-task))
(defn htn-expanded-method? [x]
(and (map? x)
(#{:htn-expanded-method
"htn-expanded-method"
"HTN-EXPANDED-METHOD"} (get x :type))))
(s/defschema eq-htn-expanded-method?
"eq-htn-expanded-method?"
(s/conditional
keyword? (s/eq :htn-expanded-method)
#(and (string? %) (= "htn-expanded-method" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-method?))
(s/defschema htn-expanded-method
"An htn-expanded-method"
{:type eq-htn-expanded-method?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
:network s/Keyword
(s/optional-key :edges) [s/Keyword]
;; WAS (s/optional-key :tpn-node) s/Keyword ;; new
(s/optional-key :tpn-selection) s/Any ;; new
})
(def check-htn-expanded-method (s/checker htn-expanded-method))
(defn htn-expanded-nonprimitive-task? [x]
(and (map? x)
(#{:htn-expanded-nonprimitive-task
"htn-expanded-nonprimitive-task"
"HTN-EXPANDED-NONPRIMITIVE-TASK"} (get x :type))))
(s/defschema eq-htn-expanded-nonprimitive-task?
"eq-htn-expanded-nonprimitive-task?"
(s/conditional
keyword? (s/eq :htn-expanded-nonprimitive-task)
#(and (string? %) (= "htn-expanded-nonprimitive-task" (string/lower-case %)))
s/Keyword
'eq-htn-expanded-nonprimitive-task?))
(s/defschema htn-expanded-nonprimitive-task
"An htn-expanded-nonprimitive-task"
{:type eq-htn-expanded-nonprimitive-task?
:uid s/Keyword
:label s/Str
:incidence-set #{s/Keyword}
(s/optional-key :edges) [s/Keyword] ;; NOTE: must consistently be a vector
;(s/optional-key :parent) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; NOTE the parent points to the parent htn-network
;(s/optional-key :tpn-node) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;(s/optional-key :tpn-edge) s/Keyword ;; new; 1/27/2017 -- PM -- Not found in data and hence removed from checks.
;; tpn-node points to state, c-begin, or p-begin
s/Keyword s/Any
})
(def check-htn-expanded-nonprimitive-task (s/checker htn-expanded-nonprimitive-task))
(s/defschema htn-object
"One of the valid HTN object types"
(s/conditional
htn-network-id? htn-network-id
htn-network? htn-network
edge? edge
htn-primitive-task? htn-primitive-task
htn-expanded-method? htn-expanded-method
htn-expanded-nonprimitive-task? htn-expanded-nonprimitive-task
'htn-object?))
(def check-htn-object (s/checker htn-object))
(s/defschema htn
"A HTN"
{s/Keyword htn-object})
(def check-htn (s/checker htn))
;; -------------------------------------------------------------------
(defn coercion [schema]
(spec/run-checker
(fn [s params]
(let [walk (spec/checker (s/spec s) params)]
(fn [x]
(let [result
(cond
(and (string? x)
(or (= s s/Keyword) (= s upper-bound)))
(walk (keyword (string/lower-case x)))
(and (= s #{s/Keyword}) (vector? x))
(walk (set x))
:else
(walk x))]
(if (su/error? result)
(if (strict?)
result
(let [xstr (synopsis x)
explanation (synopsis (s/explain s))
errstr (synopsis
(with-out-str (print (su/error-val result))))]
(log-warn "ACCEPT\n" xstr "\nEXPECTED\n" explanation "ERROR" errstr)
x)) ;; return it ANYWAY
result)))))
true
schema))
(def coerce-tpn (coercion tpn))
(def coerce-htn (coercion htn))
;; takes pathname as a string
;; plantypes as a set of valid plantypes (strings)
;; formats as a set of valid formats (strings)
;; returns true if filename matches
(defn kind-filename? [pathname plantypes formats]
(let [basename (fs-basename pathname)
[format plantype] (reverse (string/split basename #"\."))]
(boolean (and (plantypes plantype) (formats format)))))
(defn tpn-filename? [filename]
(kind-filename? filename #{"tpn"} #{"json" "edn"}))
(defn htn-filename? [filename]
(kind-filename? filename #{"htn"} #{"json" "edn"}))
(defn json-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"json"}))
(defn edn-filename? [filename]
(kind-filename? filename #{"tpn" "htn"} #{"edn"}))
(defn validate-input [input cwd]
(if (fs/exists? input)
input
(let [cwd-input (str cwd "/" input)]
(if (fs/exists? cwd-input)
cwd-input
{:error (str "input does not exist: " input)}))))
(defn validate-output [output cwd]
(if (stdout-option? output)
output
(if (string/starts-with? output "/")
output
(str cwd "/" output))))
(defn cleanup-relaxed-tpn
"coerces values of known-keywords to keywords"
{:added "0.2.0"}
([tpn]
(reduce-kv cleanup-relaxed-tpn {} tpn))
([m k v]
(assoc m k
(if (map? v)
(let [kw-as (seq v)]
(loop [new-v {} kw-a (first kw-as) more (rest kw-as)]
(if-not kw-a
new-v
(let [[kw a] kw-a
a (if (#{:activities :constraints :incidence-set} kw)
(set (map keyword a))
(if (known-keywords kw)
(keyword a)
a))
new-v (assoc new-v kw a)]
(recur new-v (first more) (rest more))))))
v))))
;; returns a network map -or- {:error "error message"}
(defn parse-network
"Parse TPN"
{:added "0.1.0"}
[network-type options]
(let [{:keys [verbose file-format input output cwd]} options
;; _ (println "Reading input from:" input)
verbose? (and (not (nil? verbose)) (pos? verbose))
input (validate-input (if (vector? input) (first input) input) cwd)
data (if (:error input) input (slurp input))
data (if (:error data)
data
(if (json-filename? input)
(read-json-str data)
(read-string data)))
;;_ (println "DEBUG DATA\n" (with-out-str (pprint data)))
result (if (:error data)
data
(if (= network-type :htn)
#_(coerce-htn data)
(records/coerce data)
#_(coerce-tpn data)
(records/coerce data))
)
;;_ (println "DEBUG RESULT\n" (with-out-str (pprint result)))
out (if (:error result)
result
(if (su/error? result)
{:error (with-out-str (println (:error result)))}
(sort-map result)))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when (:error out)
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
;; returns a map with :tpn on success or :error on failure
(defn parse-tpn
"Parse TPN"
{:added "0.1.0"}
[options]
(parse-network :tpn options))
(defn parse-htn
"Parse HTN"
{:added "0.1.0"}
[options]
(parse-network :htn options))
;; -------------------------------------------------------------
(defn name->id [name]
(if (keyword? name)
name
(keyword (string/replace (string/lower-case name) #"\s+" "_"))))
(defn composite-key [k1 k2]
(keyword (subs (str k1 k2) 1)))
(defn composite-key? [k]
(= 2 (count (string/split (name k) #":"))))
(defn composite-key-fn [k1 k2]
(fn [props]
(keyword (subs (str (get props k1) (get props k2)) 1))))
(def node-key-fn (composite-key-fn :plan/plid :node/id))
(def edge-key-fn (composite-key-fn :plan/plid :edge/id))
(def activity-types #{:activity :null-activity :delay-activity})
(defn activity-type? [edge-or-type]
(activity-types (if (map? edge-or-type)
(:edge/type edge-or-type)
edge-or-type)))
;; HTN ---------------------
(defn get-node [plan node-id]
(get-in @plan [:node/node-by-plid-id node-id]))
(defn update-node [plan node]
;; (log-debug "UPDATE-NODE" node)
(let [plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plan update-in ref merge node)))
(defn get-edge [plan edge-id]
(get-in @plan [:edge/edge-by-plid-id edge-id]))
(defn update-edge [plan edge]
(let [plid-id (edge-key-fn edge)
ref [:edge/edge-by-plid-id plid-id]]
(swap! plan update-in ref merge edge)))
(declare add-htn-node)
(defn add-htn-edge [plans plan-id network-plid-id edge-id from-plid-id net]
(let [plid-id (composite-key plan-id edge-id)
htn-edge (get net edge-id)
{:keys [end-node label display-name args]} htn-edge
type :sequence-edge
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-htn-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-htn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
htn-node (get net node-id)
{:keys [type label display-name args edges]} htn-node
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type
:node/parent network-plid-id}
:node/label label
:node/display-name display-name
:node/args args)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? edges)
(doseq [edge edges]
;; workaround schema coercion problem
(let [edge-id (if (keyword? edge) edge (keyword edge))]
(add-htn-edge plans plan-id network-plid-id edge-id plid-id net))))
nil))
;; nil on success
(defn add-htn-network [plans plan-id network-id net]
(let [htn-network (get net network-id)
{:keys [type label display-name rootnodes parentid]} htn-network
plid-id (composite-key plan-id network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
network (assoc-if {:plan/plid plan-id
:network/id network-id
:network/type type
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes
:network/parent (composite-key plan-id parentid))]
(swap! plans update-in [:network/network-by-plid-id]
assoc plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj plid-id)
(when-not (empty? rootnodes)
(doseq [rootnode rootnodes]
(add-htn-node plans plan-id plid-id rootnode net)))
nil))
(declare add-hem-node)
(defn add-hem-edge [plans plan-id network-plid-id edge-id from-plid-id
default-order net]
(let [plid-id (composite-key plan-id edge-id)
hem-edge (get net edge-id)
{:keys [end-node edge-type label display-name args order]} hem-edge
type (if (= edge-type :choice) :choice-edge :parallel-edge)
to-plid-id (composite-key plan-id end-node)
edge (assoc-if {:plan/plid plan-id
:edge/id edge-id
:edge/type type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)}
:edge/label label
:edge/display-name display-name
:edge/args args)]
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(add-hem-node plans plan-id network-plid-id end-node net)
nil))
;; nil on success
(defn add-hem-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
hem-node (get net node-id)
{:keys [type label display-name args network edges]} hem-node
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec edges)
plid-network (if network (composite-key plan-id network))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type type}
:node/label label
:node/display-name display-name
:node/args args
:node/htn-network plid-network)]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when network
(add-htn-network plans plan-id network net))
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id network-plid-id
edge plid-id order net)))))
nil))
(defn unique-id [net prefix]
(let [id (keyword (gensym prefix))]
(if (get net id)
(recur net prefix)
id)))
(defn add-hem-network [plans plan-id network-id net]
(when (= network-id :top-hem-network-id)
(let [hem-network-id (unique-id net "net-") ;; for the hem network
hem-plid-id (composite-key plan-id hem-network-id)
begin-id (unique-id net "hid-") ;; for the top hem
begin-plid-id (composite-key plan-id begin-id)
htn-network-id (:network net)
htn-network (get net htn-network-id)
{:keys [label display-name rootnodes]} htn-network
htn-plid-id (composite-key plan-id htn-network-id)
plid-rootnodes (if rootnodes
(set (doall
(map (partial composite-key plan-id)
rootnodes))))
htn-network (assoc-if {:plan/plid plan-id
:network/id htn-network-id
:network/type :htn-network
:network/parent hem-plid-id
:network/nodes []
:network/edges []}
:network/label label
:network/display-name display-name
:network/rootnodes plid-rootnodes)
begin (assoc-if {:plan/plid plan-id
:node/id begin-id
:node/type :htn-expanded-method
:node/htn-network htn-network-id}
:node/label label
:node/display-name (or display-name "PI:NAME:<NAME>END_PI")
;; NOTE: for this "synthetic" top level HEM we don't
;; have any args for the root-task --> they will be
;; in the child HEM of this one.
;; :node/args args
)
hem-network {:plan/plid plan-id
:network/id hem-network-id
:network/type :hem-network
:network/begin (composite-key plan-id begin-id)
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc hem-plid-id hem-network htn-plid-id htn-network)
(swap! plans update-in [:plan/by-plid plan-id]
(fn [p]
(assoc p
:plan/networks (conj (:plan/networks p) hem-plid-id htn-plid-id)
:plan/begin hem-plid-id)))
;; add begin hem node
(update-node plans begin)
(swap! plans update-in
[:network/network-by-plid-id hem-plid-id :network/nodes]
conj begin-plid-id)
(loop [edges [] root (first rootnodes) more (rest rootnodes)]
(if-not root
;; add hem edges from begin
(when-not (empty? edges)
(doall
(for [order (range (count edges))
:let [edge (get edges order)]]
(do
(add-hem-edge plans plan-id hem-plid-id
edge begin-plid-id order net)))))
;; add this htn-node
(let [htn-node (get net root)
;; HERE we assume at some point in the future edges
;; will become a vector (because order is important)
edges (vec (:edges htn-node))
;; edges (set/union edges (:edges htn-node))
n-plid-id (composite-key plan-id root)
node (assoc-if {:plan/plid plan-id
:node/id root
:node/type (:type htn-node)
:node/parent htn-plid-id}
:node/label (:label htn-node)
:node/display-name (:display-name htn-node)
:node/args (:args htn-node))]
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id htn-plid-id :network/nodes]
conj n-plid-id)
(recur edges (first more) (rest more)))))
nil)))
;; TPN ---------------------
(declare add-tpn-node)
;; nil on success
(defn add-tpn-edge [plans plan-id network-plid-id edge-id from-plid-id to-id
net & [default-order]]
(let [plid-id (composite-key plan-id edge-id)
net-edge (get net edge-id)
;; :temporal-constraint :activity :null-activity
{:keys [tpn-type end-node constraints
value ;; value is bounds in :temporal-constraint
between between-ends between-starts ;; :temporal-constraint
name label display-name args
sequence-label sequence-end ;; :activity
plant plantid command args argsmap non-primitive ;; :activity
cost reward controllable;; :activity :null-activity
probability guard ;; :null-activity
network-flows htn-node order]} net-edge
to-id (or end-node to-id)
to-plid-id (composite-key plan-id to-id)
edge (assoc-if
(if (nil? controllable) {} {:edge/controllable controllable})
:plan/plid plan-id
:edge/id edge-id
:edge/type tpn-type
:edge/from from-plid-id
:edge/to to-plid-id
:edge/order (or order default-order)
:edge/value value ;; bounds for temporal constraint
:edge/between between
:edge/between-ends between-ends
:edge/between-starts between-starts
:edge/name name
:edge/label label
:edge/display-name display-name
:edge/args args
:edge/sequence-label sequence-label
:edge/sequence-end sequence-end
:edge/plant plant
:edge/plantid plantid
:edge/command command
:edge/args args
:edge/argsmap argsmap
:edge/cost cost
:edge/reward reward
:edge/probability probability
:edge/guard guard
:edge/network-flows network-flows
:edge/non-primitive non-primitive
:edge/htn-node htn-node)]
;; (log-debug "ADDING EDGE" plid-id "TO-ID" to-id "END-NODE" end-node)
(update-edge plans edge)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/edges]
conj plid-id)
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
from-plid-id to-id net)))
;; (if (not (keyword? to-id))
;; (log-debug "NOT KEYWORD TO-ID" to-id))
(add-tpn-node plans plan-id network-plid-id to-id net)
;; FIXME handle network-flows non-primitive
nil))
;; nil on success
(defn add-tpn-node [plans plan-id network-plid-id node-id net]
(let [plid-id (composite-key plan-id node-id)
node (get-in @plans [:node/node-by-plid-id plid-id])]
;; (log-debug "ADDING NODE?" node-id "NODE" node)
(when-not node
;; :state :c-begin :p-begin :c-end :p-end
(let [net-node (get net node-id)
{:keys [tpn-type activities ;; mandatory
constraints end-node
label display-name args sequence-label sequence-end
probability htn-node]} net-node
;; HERE we assume at some point in the future activities
;; will become a vector (because order is important)
activities (vec activities)
end-node (if end-node (composite-key plan-id end-node))
node (assoc-if {:plan/plid plan-id
:node/id node-id
:node/type tpn-type}
:node/end end-node
:node/label label
:node/display-name display-name
:node/args args
:node/sequence-label sequence-label
:node/sequence-end sequence-end
:node/probability probability
:node/htn-node htn-node)]
;; (log-debug "ADDING NODE" plid-id "ACTIVITIES" activities
;; "END-NODE" end-node)
(update-node plans node)
(swap! plans update-in
[:network/network-by-plid-id network-plid-id :network/nodes]
conj plid-id)
(when-not (empty? activities)
(doall
(for [order (range (count activities))
:let [activity (get activities order)]]
(add-tpn-edge plans plan-id network-plid-id activity
plid-id end-node net order))))
(when-not (empty? constraints)
(doseq [constraint constraints]
(add-tpn-edge plans plan-id network-plid-id constraint
plid-id end-node net)))
nil))))
(declare find-end)
(defn inc-number-last [number]
(let [subgraph (vec (or (butlast number) []))
n (inc (or (last number) -1))]
(conj subgraph n)))
;; returns context
(defn set-number [plans plan-id prev-context numbers node? x]
(if node?
(let [{:keys [node/id node/type node/begin node/context node/number]} x
begin? (#{:p-begin :c-begin} type)
end? (#{:p-end :c-end} type)
no-context? (nil? context) ;; first pass
context (if no-context? prev-context context)
number (if no-context?
(get (swap! numbers update-in [context] inc-number-last) context)
number)
node-id (composite-key plan-id id)
edge-context (if begin?
node-id
(if end?
(:node/context (get-node plans begin))
context))]
(if (and begin? no-context?)
(swap! numbers assoc edge-context (conj number -1)))
(when no-context?
(update-node plans (assoc x :node/context context :node/number number)))
edge-context)
(let [number
(get (swap! numbers update-in [prev-context] inc-number-last)
prev-context)]
(update-edge plans (assoc x :edge/number number))
prev-context)))
(declare visit-nodes)
(declare map-outgoing)
;; add experimental node/edge numbers
;; nil on success
(defn number-nodes-edges [plans plan-id begin-id end-id nodes]
(let [context ::top
numbers (atom {context [-1]})]
(visit-nodes plans begin-id #{end-id}
(fn [node]
(let [edge-context (set-number plans plan-id context numbers true node)]
(remove nil?
(map-outgoing plans node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(when follow?
(set-number plans plan-id edge-context numbers false edge)
(set-number plans plan-id edge-context numbers true
(get-node plans to))
to))))))))
;; remove :node/context
(doseq [node nodes]
(let [node (get-node plans node)
plid-id (node-key-fn node)
ref [:node/node-by-plid-id plid-id]]
(swap! plans assoc-in ref (dissoc node :node/context))))
nil))
;; nil on success
(defn add-tpn-network [plans plan-id network-id net]
(let [net-network (get net network-id)
{:keys [begin-node end-node]} net-network
begin-id (composite-key plan-id begin-node)
end-node (or end-node
;; NOTE: the following will likely MISS the true end
;; if the plan is a top level sequence, beginning with
;; p-begin or c-begin
;; (:end-node (get net begin-node))
::walk)
end-id (if (= end-node ::walk) end-node (composite-key plan-id end-node))
network-plid-id (composite-key plan-id network-id)
network {:plan/plid plan-id
:network/id network-id
:network/type :tpn-network
:network/begin begin-id
:network/end end-id
:network/nodes []
:network/edges []}]
(swap! plans update-in [:network/network-by-plid-id]
assoc network-plid-id network)
(swap! plans update-in [:plan/by-plid plan-id :plan/networks]
conj network-plid-id)
;; (if (not (keyword? begin-node))
;; (log-debug "NOT KEYWORD BEGIN-NODE" begin-node))
(add-tpn-node plans plan-id network-plid-id begin-node net)
;; create *-end pointer
(let [nodes (:network/nodes
(get-in @plans [:network/network-by-plid-id network-plid-id]))
find-end? (= end-node ::walk)] ;; walk the graph to find the end node
;; (log-debug "DEBUG NODES =========")
;; (log-debug "\n" (with-out-str (pprint nodes)))
(doseq [node nodes]
(let [node (get-node plans node)
{:keys [node/type node/id node/end]} node
node-id (composite-key plan-id id)
end-node (if (and (#{:p-begin :c-begin} type) end)
(get-node plans end))]
;; (log-debug "NODE-ID" node-id "END" end "NODE" node)
(if-not (empty? end-node)
(update-node plans (assoc end-node :node/begin node-id))
;; (if end
;; (log-debug "END NODE" end "NOT FOUND?"))
)))
(when find-end?
(swap! plans assoc-in [:network/network-by-plid-id
network-plid-id :network/end]
(if find-end?
(find-end plans plan-id begin-id)
end-id)))
(number-nodes-edges plans plan-id begin-id end-id nodes))))
;; nil on success
(defn add-plan [plans network-type plan-id plan-name net & [corresponding-id]]
(let [begin (if (= network-type :htn-network)
:top-hem-network-id
(:network-id net))
plan (assoc-if {:plan/plid plan-id
:plan/name plan-name
:plan/type network-type
:plan/begin (composite-key plan-id begin)
:plan/networks []}
:plan/corresponding corresponding-id)]
(swap! plans
(fn [st]
(let [{:keys [plans/plans plan/by-plid
network/network-by-plid-id
node/node-by-plid-id edge/edge-by-plid-id
]} st
st-plans (or plans [])
st-by-plid (or by-plid {})
st-network-by-plid-id (or network-by-plid-id {})
st-node-by-plid-id (or node-by-plid-id {})
st-edge-by-plid-id (or edge-by-plid-id {})
by-plid {plan-id plan}]
(assoc st
:plans/plans (vec (set (conj st-plans plan-id)))
:plan/by-plid (merge st-by-plid by-plid)
:network/network-by-plid-id st-network-by-plid-id
:edge/edge-by-plid-id st-edge-by-plid-id
:node/node-by-plid-id st-node-by-plid-id
)
)))
((if (= network-type :htn-network) add-hem-network add-tpn-network)
plans plan-id begin net)
nil))
;; look in the TPN
;; pick the begin network
;; look at the edges that are activities AND p-begin c-begin nodes
;; (NOTE: include state nodes if superfluous NA's have not been removed)
;; if one has htn-node then the from is the tpn-node
;; link that htn-node to that tpn activity or tpn node
(defn link-htn-nodes-to-tpn-nodes [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @tpn-plan
tpn-by-plid by-plid
tpn-network-by-plid-id network-by-plid-id
tpn-edge-by-plid-id edge-by-plid-id
tpn-node-by-plid-id node-by-plid-id
tpn-plan-id (first (keys tpn-by-plid))
tpn-plan0 (get tpn-by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get tpn-network-by-plid-id begin)
{:keys [network/nodes network/edges]} tpn-network
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plan-id (first (keys by-plid))]
(doseq [edge edges]
(let [edge (get-edge tpn-plan edge)
{:keys [edge/type edge/id edge/from edge/htn-node]} edge
from-node (get-node tpn-plan from)
from-htn-node-id (if-let [h (:node/htn-node from-node)]
(composite-key htn-plan-id h))
;; from-htn-node-id (composite-key tpn-plan from)
from-htn-node (if from-htn-node-id
(get-node htn-plan from-htn-node-id))
from-htn-node-tpn-selection (or (:node/tpn-selection from-htn-node) [])
edge-id (composite-key tpn-plan-id id)
htn-node-id (if htn-node (composite-key htn-plan-id htn-node))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
(when (and (or (= type :activity) (= type :delay-activity)) htn-node-id)
(if (not hnode)
(log-error "edge" edge-id "specifies htn-node" htn-node "but"
htn-node-id "is not found")
(do
(update-edge tpn-plan ;; fully qualify the htn-node
(assoc edge :edge/htn-node htn-node-id))
(when (and from-htn-node-id
(or (not= from-htn-node-id htn-node-id)
(not (some #(= (second %) edge-id)
from-htn-node-tpn-selection))))
;; (log-warn "FROM-NODE" from
;; "htn-node will change from" from-htn-node-id
;; "to" htn-node-id) ;; DEBUG
;; add this to the htn-node selection before it's lost
(update-node htn-plan
(assoc from-htn-node
:node/tpn-selection (conj from-htn-node-tpn-selection
[:edge edge-id]))))
(update-node tpn-plan ;; give the from the htn-node also!
(assoc from-node
:node/htn-node htn-node-id))
(update-node htn-plan ;; backpointer link the htn-node --> edge
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:edge edge-id]))
(assoc hnode
:node/tpn-edge edge-id))))))))
(doseq [node nodes]
(let [node (get-node tpn-plan node)
{:keys [node/type node/id node/htn-node node/end]} node
node-id (composite-key tpn-plan-id id)
from-node? (and htn-node (composite-key? htn-node))
htn-node-id (if htn-node
(if from-node?
htn-node
(composite-key htn-plan-id htn-node)))
hnode (if htn-node-id (get-node htn-plan htn-node-id))
tpn-selection (or (:node/tpn-selection hnode) [])]
;; :state for extra nodes when superfluous not removed
(when (and (not from-node?) ;; b/c activity will have the link
(#{:p-begin :c-begin :state} type)
htn-node-id)
(if (not hnode)
(log-error "node" node-id "specficies htn-node" htn-node
"but" htn-node-id "is not found")
(do
(update-node tpn-plan ;; fully qualify the htn-node
(assoc node :node/htn-node htn-node-id))
(update-node htn-plan
(if (= (:node/type hnode) :htn-expanded-method)
(assoc hnode
:node/tpn-selection (conj tpn-selection [:node node-id]))
(assoc hnode
:node/tpn-node node-id))))))))))
(defn visit-nodes [tpn-plan node-id prev-visited node-fn]
(if (prev-visited node-id)
prev-visited
(let [node (get-node tpn-plan node-id)
visited (atom (conj prev-visited node-id))
tovisit (remove nil? (node-fn node))] ;; visit any nodes returned
(loop [visit (first tovisit) more (rest tovisit)]
(when visit
(swap! visited set/union (visit-nodes tpn-plan visit @visited node-fn))
(recur (first more) (rest more))))
@visited)))
;; since we have not precomputed outgoing we'll figure
;; it out the hard way
(defn map-outgoing [tpn-plan node edge-fn]
(let [node-id (node-key-fn node)
{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id]} @tpn-plan
tpn-plan-id (first (keys by-plid))
tpn-plan0 (get by-plid tpn-plan-id)
{:keys [plan/begin]} tpn-plan0
tpn-network (get network-by-plid-id begin)
{:keys [network/edges]} tpn-network
from-node (fn [e]
(let [edge (get edge-by-plid-id e)]
(if (= (:edge/from edge) node-id) edge)))
outgoing (remove nil? (map from-node edges))]
(doall (map edge-fn outgoing))))
;; returns end-id
(defn find-end [plan plan-id begin-id]
(let [the-end (atom :end-not-found)]
(visit-nodes plan begin-id #{}
(fn [node]
(when (= @the-end :end-not-found)
(reset! the-end (composite-key plan-id (:node/id node)))
(remove nil?
(map-outgoing plan node
(fn [edge]
(let [{:keys [edge/type edge/to]} edge
follow? (activity-type? type)]
(if to ;; that was not the end
(reset! the-end :end-not-found))
(if follow?
to))))))))
@the-end))
;; new generation using :node/number and :edge/number
;; is sel within node-id?
(defn is-within-node? [tpn-plan sel node-id]
(let [node (get-node tpn-plan node-id)
{:keys [node/number]} node
[element id] sel
sel-number (if (= :node element)
(:node/number (get-node tpn-plan id))
(:edge/number (get-edge tpn-plan id)))
number-n (count number)
sel-number-n (count sel-number)]
(and (> sel-number-n number-n)
(= number
(vec (take number-n sel-number))))))
;; return the parts of sub in selection
(defn selection-subset [tpn-plan sub selection]
(loop [a-subs [] a (first sub) a-more (rest sub)]
(if-not a
a-subs
(let [within? (loop [b (first selection) b-more (rest selection)]
(if-not b
false
(if (or (= a b) (and (= (first b) :node)
(is-within-node?
tpn-plan a (second b))))
true
(recur (first b-more) (rest b-more)))))
a-subs (if within? (conj a-subs a) a-subs)]
(recur a-subs (first a-more) (rest a-more))))))
(defn remove-subset [selection remove]
(loop [selection selection r (first remove) more (rest remove)]
(if-not r
selection
(do
(recur (vec (filter #(not= % r) selection)) (first more) (rest more))))))
;; return the minimal representation of sel
;; first find any leader nodes among the nodes
;; then add in any non comprised edges
(defn minimal-selection [tpn-plan sel]
(let [mnodes (vec (remove nil? (filter #(= :node (first %)) sel)))
medges (remove nil? (filter #(= :edge (first %)) sel))
msel (loop [msel [] n (first mnodes) more (rest mnodes)]
(if-not n
msel
(let [node-subset (selection-subset tpn-plan [n] msel)
subset-node (selection-subset tpn-plan msel [n])
msel (cond
(not (empty? node-subset))
msel ;; n is already in msel
(not (empty? subset-node))
;; remove the subset-node in msel already, add n
(conj (remove-subset msel subset-node) n)
:else
(conj msel n))]
(recur msel (first more) (rest more)))))
msel (loop [msel msel e (first medges) more (rest medges)]
(if-not e
msel
(let [edge-subset (selection-subset tpn-plan [e] msel)
msel (cond
(not (empty? edge-subset))
msel ;; e is already in msel
:else
(conj msel e))]
(recur msel (first more) (rest more)))))]
msel))
;; collect selection comprising
;; -- all tpn-node/tpn-edge from the htn network
;; -- for all child hem's
;; if they have a tpn-selection, use it
;; else recurse
(defn update-tpn-selection [htn-plan tpn-plan network-by-plid-id hem-network
hem tpn-selection]
(let [hem-id (node-key-fn hem)
{:keys [node/htn-network]} hem
htn-net (get network-by-plid-id htn-network)
{:keys [network/nodes]} htn-net
{:keys [network/edges]} hem-network
selection (if tpn-selection (set tpn-selection) #{})
selection (loop [selection selection n (first nodes) more (rest nodes)]
(if-not n
selection
(let [{:keys [node/tpn-edge node/tpn-node]}
(get-node htn-plan n)
sel (if tpn-edge [:edge tpn-edge]
(if tpn-node [:node tpn-node]))]
(recur (if sel (conj selection sel) selection)
(first more) (rest more)))))
selection (loop [selection selection e (first edges) more (rest edges)]
(if-not e
selection
(let [{:keys [edge/from edge/to]} (get-edge htn-plan e)
hnode (get-node htn-plan to)
{:keys [node/tpn-selection
node/tpn-selection-complete?]} hnode
tpn-selection (if (= from hem-id)
(if tpn-selection-complete?
tpn-selection
(update-tpn-selection
htn-plan tpn-plan
network-by-plid-id
hem-network hnode
tpn-selection)))]
(recur (if tpn-selection
(set/union selection (set tpn-selection))
selection)
(first more) (rest more)))))
;; _ (log-warn "BEFORE MINIMAL" selection) ;; DEBUG
selection (minimal-selection tpn-plan (vec selection))]
(update-node htn-plan
(assoc hem
:node/tpn-selection selection
:node/tpn-selection-complete? true))
;; (log-warn "DEBUG update-tpn-selection" hem-id "=" selection) ;; DEBUG
selection))
(defn complete-tpn-selections [htn-plan tpn-plan]
(let [{:keys [plan/by-plid network/network-by-plid-id
edge/edge-by-plid-id node/node-by-plid-id]} @htn-plan
htn-plid (first (keys by-plid))
htn-plan0 (get by-plid htn-plid)
{:keys [plan/begin]} htn-plan0
hem-network (get network-by-plid-id begin)
{:keys [network/nodes]} hem-network]
(doseq [node nodes]
(let [node (get-node htn-plan node)
{:keys [node/tpn-selection node/tpn-selection-complete?]} node]
(when-not tpn-selection-complete?
;; collect all from htn-network and edges from this hem
(update-tpn-selection
htn-plan tpn-plan network-by-plid-id hem-network
node tpn-selection))))))
;; returns {:error} map or plans
(defn merge-htn-tpn
"Merge HTN+TPN"
{:added "0.1.0"}
[htn htn-name tpn tpn-name]
(let [htn-plan (atom {})
tpn-plan (atom {})
htn-id (name->id htn-name)
tpn-id (name->id tpn-name)]
(or
(add-plan htn-plan :htn-network htn-id htn-name htn tpn-id)
(add-plan tpn-plan :tpn-network tpn-id tpn-name tpn htn-id)
;; cross link here
(link-htn-nodes-to-tpn-nodes htn-plan tpn-plan)
(complete-tpn-selections htn-plan tpn-plan)
[(sort-map @htn-plan)
(sort-map @tpn-plan)])))
;; returns a plan map on success or :error on failure
(defn tpn-plan
"Parse TPN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one TPN file"})
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
[error tpn] (if error
[error nil]
(if (empty? tpn-filename)
[{:error
(str "Expected a TPN file, but tpn is not in the filename: " input)}
nil]
(let [rv (parse-tpn {:input tpn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
tpn-plan (atom {})
tpn-name (if-not error (first (fs/split-ext tpn-filename)))
_ (if-not error
(add-plan tpn-plan :tpn-network (name->id tpn-name) tpn-name tpn))
out (or error
(sort-map @tpn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn htn-plan
"Parse HTN"
{:added "0.1.6"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 1 (count input)))
{:error "input must include exactly one HTN file"})
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
[error htn] (if error
[error nil]
(if (empty? htn-filename)
[{:error (str "Expected a HTN file, but htn is not in the filename: " input)} nil]
(let [rv (parse-htn {:input htn-filename :output "-"
:cwd cwd})]
(if (:error rv)
[rv nil]
[nil rv]))))
htn-plan (atom {})
htn-name (if-not error (first (fs/split-ext htn-filename)))
_ (if-not error
(add-plan htn-plan :htn-network (name->id htn-name) htn-name htn))
out (or error
(sort-map @htn-plan))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
(defn merge-networks
"Merge HTN+TPN inputs"
{:added "0.1.0"}
[options]
(let [{:keys [verbose file-format input output cwd]} options
error (if (or (not (vector? input)) (not= 2 (count input)))
"input must include exactly one HTN and one TPN file")
htn-filename (if (and (not error)
(= 1 (count (filter htn-filename? input))))
(first (filter htn-filename? input)))
tpn-filename (if (and (not error)
(= 1 (count (filter tpn-filename? input))))
(first (filter tpn-filename? input)))
error (or error
(if (empty? htn-filename)
(str "HTN file not one of: " input)
(if (empty? tpn-filename)
(str "TPN file not one of: " input))))
htn-filename (if-not error (validate-input htn-filename cwd))
error (or error (:error htn-filename))
tpn-filename (if-not error (validate-input tpn-filename cwd))
error (or error (:error tpn-filename))
htn (if (not error) (parse-htn {:input htn-filename :output "-"
:cwd cwd}))
error (or error (:error htn))
tpn (if (not error) (parse-tpn {:input tpn-filename :output "-"
:cwd cwd}))
;; _ (log-debug "== TPN begin ==")
;; _ (log-debug "\n" (with-out-str (pprint tpn)))
;; _ (log-debug "== TPN end ==")
error (or error (:error tpn))
out (if error
{:error error}
(merge-htn-tpn
htn (first (fs/split-ext htn-filename))
tpn (first (fs/split-ext tpn-filename))))
out-json-str (if (= file-format :json)
(write-json-str out))
output (validate-output output cwd)]
(when error
(log-error
(str "Invalid plan: " input ", see error "
(if (stdout-option? output) "below " "in ")
(if-not (stdout-option? output) output))))
(when-not (stdout-option? output)
(spit output (or out-json-str ;; JSON here
(with-out-str (pprint out))))) ;; EDN here
(or out-json-str out))) ;; JSON or EDN
|
[
{
"context": "))\n\n(deftest test-possible-moves\n (let [my-name \"AI\" opponent \"opponent-name\"\n state (-> game/",
"end": 241,
"score": 0.6261703968048096,
"start": 239,
"tag": "USERNAME",
"value": "AI"
},
{
"context": "g \"static evaluation of state\"\n (let [my-name \"AI\" opponent \"other\"\n base (-> game/empty-s",
"end": 4550,
"score": 0.8346447944641113,
"start": 4548,
"tag": "USERNAME",
"value": "AI"
},
{
"context": "tatic-score my-name (-> state (game/play my-name \"JC\")\n (gam",
"end": 5220,
"score": 0.6644729971885681,
"start": 5218,
"tag": "NAME",
"value": "JC"
},
{
"context": " best moves without recursing\"\n (let [my-name \"AI\" opponent \"other\"\n base (-> game/empty-s",
"end": 6105,
"score": 0.5502528548240662,
"start": 6103,
"tag": "NAME",
"value": "AI"
},
{
"context": "nd see how the AI responds.\n (let [opponent \"opponent-name\"\n state (-> game/empty-state\n ",
"end": 10438,
"score": 0.9500421285629272,
"start": 10425,
"tag": "USERNAME",
"value": "opponent-name"
},
{
"context": "\"AI response to game restarts\"\n (let [my-name \"AI\"\n opponent \"opponent\"\n points (",
"end": 11554,
"score": 0.7778259515762329,
"start": 11552,
"tag": "USERNAME",
"value": "AI"
},
{
"context": "ts\"\n (let [my-name \"AI\"\n opponent \"opponent\"\n points (assoc {} my-name (dec game/MAX",
"end": 11584,
"score": 0.5124610662460327,
"start": 11579,
"tag": "USERNAME",
"value": "onent"
},
{
"context": " (let [cards-played (-> state (game/play my-name \"JC\") (game/play opponent \"6D\"))]\n ;; Game sho",
"end": 12578,
"score": 0.704696774482727,
"start": 12576,
"tag": "NAME",
"value": "JC"
}
] | test/bidpitch/test/ai.clj | tlicata/bidpitch | 1 | (ns bidpitch.test.ai
(:use clojure.test bidpitch.ai)
(:require [clojure.core.async :refer [<!! >!! chan]]
[clojure.set :refer [subset?]]
[bidpitch.game :as game]))
(deftest test-possible-moves
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
(testing "possible bids"
(is (= (possible-moves state) [{:action "bid" :value 0}
{:action "bid" :value 2}]))
(is (= (possible-moves (-> state (game/bid opponent 0)))
[{:action "bid" :value 2}])))
(testing "possible cards"
(is (= (possible-moves (-> state (game/bid opponent 0)
(game/bid my-name 2)))
[{:action "play" :value "AC"}
{:action "play" :value "KC"}
{:action "play" :value "JC"}]))
(is (= (possible-moves (-> state (game/bid opponent 2)
(game/bid my-name 0)))
[{:action "play" :value "2D"}
{:action "play" :value "4D"}
{:action "play" :value "6D"}])))))
(deftest test-possible-next-states
(testing "possible next states"
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid opponent 2) (game/bid my-name 0)
(game/play opponent "6D") (game/play my-name "JC")
(game/play opponent "4D") (game/play my-name "KC"))
one-step (-> state (game/play opponent "2D"))]
(is (= (possible-state state (first (possible-moves state))) one-step))
(binding [game/*reconcile-end-game* false]
(is (= (possible-state one-step (first (possible-moves one-step)))
(-> one-step (game/play my-name "AC"))))))))
(deftest test-ai-helpers
(testing "who has what cards"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
(let [high (-> state
(game/play my-name "AC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= -1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play my-name "JC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name low)))
(is (= 1 (won-or-lost-low my-name low)))
(is (= 1 (won-or-lost-jack my-name low)))
(is (= -1 (won-or-lost-high opponent low)))
(is (= -1 (won-or-lost-low opponent low)))
(is (= -1 (won-or-lost-jack opponent low)))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
(let [high (-> state
(game/play opponent "4D") (game/play my-name "KC"))]
(is (= -1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= 1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play opponent "2D") (game/play my-name "JC"))]
(is (= -1 (won-or-lost-high my-name low)))
(is (= -1 (won-or-lost-low my-name low)))
(is (= 0 (won-or-lost-jack my-name low)))
(is (= 1 (won-or-lost-high opponent low)))
(is (= 1 (won-or-lost-low opponent low)))
(is (= 0 (won-or-lost-jack opponent low))))))))
(deftest test-static-score
(testing "static evaluation of state"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; 1 point for high card.
(is (= 1 (static-score my-name (-> state (game/play my-name "AC")
(game/play opponent "2D")))))
;; 3 points for high, low, and jack.
(is (= 3 (static-score my-name (-> state (game/play my-name "JC")
(game/play opponent "2D"))))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
;; -2 since opponent has high (in hand) and low (played).
(is (= -2 (static-score my-name (-> state (game/play opponent "2D")
(game/play my-name "KC")))))
;; -1 since opponent has high (played).
(is (= -1 (static-score my-name (-> state (game/play opponent "6D")
(game/play my-name "JC")))))
;; -1 since opponent has high (in hand).
(is (= -1 (static-score my-name (-> state (game/play opponent "4D")
(game/play my-name "JC")))))))))
(deftest test-prune
(testing "likely best moves without recursing"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state))]
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; All moves are equivalent when statically considered.
(is (subset?
(set (prune my-name state (possible-moves state)))
(set [{:action "play" :value "4D"}
{:action "play" :value "TD"}
{:action "play" :value "AC"}])))
(let [lead (-> state (game/play my-name "AC"))
moves (possible-moves lead)]
;; Opponent needs to follow suit.
(is (= moves [{:action "play" :value "2C"}
{:action "play" :value "3C"}]))
;; But it should not throw the low.
(is (= (prune opponent lead moves)
[{:action "play" :value "3C"}]))
(let [final (-> lead
(game/play opponent "3C")
(game/play my-name "TD"))]
;; Opponent should use the low to take the ten!
(is (= (prune opponent final (possible-moves final))
[{:action "play" :value "2C"}]))))))))
(deftest test-expected-score
(testing "expected score of a state for a player"
(let [my-name "AI" opponent "opponent"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state)
(game/bid opponent 0) (game/bid my-name 2)
(game/play my-name "AC"))]
(binding [game/*reconcile-end-game* false]
(let [state (-> base (game/play opponent "3C")
(game/play my-name "TD") (game/play opponent "2C")
(game/play opponent "6D"))
done (-> state (game/play my-name "4D"))]
;; AI loses 2 (doesn't make bid) and opponent gets 2 (low + pts).
(is (= (expected-score my-name done) -4))
(is (= (expected-score opponent done) 4))
;; Can the computer figure out that out with one move left?
(is (= (expected-score my-name state) -4))
;; But from the beginning the AI can play smarter.
(is (= (expected-score my-name base) 1)))))))
;; Helper function for serializing state to be sent to AI.
(defn state-to-ai [state username]
(prn-str (game/shield state username true)))
;; This function performs the initial handshake that the AI client
;; (indeed, all clients, including the browser) go through when
;; connecting to the server. It is used in the tests below.
(defn setup-game [my-name from-ai to-ai]
;; Expect to receive "name" message from AI. Every client
;; tries to register with a name and is accepted if the name
;; is available and rejected otherwise.
(is (= {:message my-name} (<!! from-ai)))
;; We'll accept the name "AI". In this case the server usually
;; sends back a signed JWT, giving this client the privilege to
;; that name in case of future collisions. Really, we can send
;; back anything other than "taken".
(>!! to-ai "your-name-was-accepted")
;; After accepting the client, we send them the current state of
;; the game (shielded so they can't see other players' cards).
(>!! to-ai (state-to-ai game/empty-state my-name))
;; Expect to receive the "join" message from the client saying
;; the AI wants to join the game.
(is (= {:message "join"} (<!! from-ai)))
;; The client will now sit in a loop, waiting for updates from
;; the server. The browser will show this new game state to the
;; player and respond with player action. The AI will examine
;; the state and try to come up with its own response (if it is
;; its turn to play).
)
(deftest test-ai
(testing "AI bidding behavior"
(let [my-name "AI"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))]
(setup-game my-name from-ai to-ai)
;; Let's make up some states and see how the AI responds.
(let [opponent "opponent-name"
state (-> game/empty-state
;; Add the AI and another player
(game/add-player my-name opponent)
;; Give them each some cards.
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
;; Set dealer and order players accordingly.
(game/dealt-state))]
(is (= (game/get-dealer state) my-name))
(is (= (game/get-onus state) opponent))
;; If opponent passes, then AI will bid 2.
(>!! to-ai (-> state
(game/bid opponent 0)
(state-to-ai my-name)))
(is (= {:message "bid:2"} (<!! from-ai))))
;; Try to clean up the running AI process.
(future-cancel brain)))
;; There once existed a bug who only showed its face when:
;; 1) a game had ended and a new one started, and
;; 2) the AI was the second player to bid.
;; Let's try to recreate that scenario here.
(testing "AI response to game restarts"
(let [my-name "AI"
opponent "opponent"
points (assoc {} my-name (dec game/MAX_POINTS) opponent 0)
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
(assoc :points points) ;; about to win
(game/add-player opponent my-name)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid my-name 2) (game/bid opponent 0)
(game/play my-name "AC") (game/play opponent "2D")
(game/play my-name "KC") (game/play opponent "4D"))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
;; Send state to AI and it will/should play the only card it has
;; left (JC).
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "play:JC"} (<!! from-ai)))
(let [cards-played (-> state (game/play my-name "JC") (game/play opponent "6D"))]
;; Game should be over, since AI has > MAX_POINTS.
(is (game/game-over? cards-played))
(is (= my-name (game/get-winner cards-played)))
;; Start a new game and have the opponent pass the bid.
(let [new-state (-> cards-played game/restart (game/bid opponent 0))]
(>!! to-ai (state-to-ai new-state my-name))
(is (= {:message "bid:2"} (<!! from-ai)))))
(future-cancel brain))))
(deftest test-ai-start
;; There once existed a bug who only showed its face when:
;; 1) a player had requested an AI opponent, but
;; 2) the player left without starting the game.
;; Now the AI "owned" the game and would be responsible for starting it (if
;; the same player rejoined or another joined) and it had no logic to do so.
(testing "AI can start a game"
(let [my-name "AI" opponent "opponent"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
;; AI is first player
(game/add-player my-name opponent))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "start:"} (<!! from-ai)))
(future-cancel brain))))
| 96254 | (ns bidpitch.test.ai
(:use clojure.test bidpitch.ai)
(:require [clojure.core.async :refer [<!! >!! chan]]
[clojure.set :refer [subset?]]
[bidpitch.game :as game]))
(deftest test-possible-moves
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
(testing "possible bids"
(is (= (possible-moves state) [{:action "bid" :value 0}
{:action "bid" :value 2}]))
(is (= (possible-moves (-> state (game/bid opponent 0)))
[{:action "bid" :value 2}])))
(testing "possible cards"
(is (= (possible-moves (-> state (game/bid opponent 0)
(game/bid my-name 2)))
[{:action "play" :value "AC"}
{:action "play" :value "KC"}
{:action "play" :value "JC"}]))
(is (= (possible-moves (-> state (game/bid opponent 2)
(game/bid my-name 0)))
[{:action "play" :value "2D"}
{:action "play" :value "4D"}
{:action "play" :value "6D"}])))))
(deftest test-possible-next-states
(testing "possible next states"
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid opponent 2) (game/bid my-name 0)
(game/play opponent "6D") (game/play my-name "JC")
(game/play opponent "4D") (game/play my-name "KC"))
one-step (-> state (game/play opponent "2D"))]
(is (= (possible-state state (first (possible-moves state))) one-step))
(binding [game/*reconcile-end-game* false]
(is (= (possible-state one-step (first (possible-moves one-step)))
(-> one-step (game/play my-name "AC"))))))))
(deftest test-ai-helpers
(testing "who has what cards"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
(let [high (-> state
(game/play my-name "AC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= -1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play my-name "JC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name low)))
(is (= 1 (won-or-lost-low my-name low)))
(is (= 1 (won-or-lost-jack my-name low)))
(is (= -1 (won-or-lost-high opponent low)))
(is (= -1 (won-or-lost-low opponent low)))
(is (= -1 (won-or-lost-jack opponent low)))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
(let [high (-> state
(game/play opponent "4D") (game/play my-name "KC"))]
(is (= -1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= 1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play opponent "2D") (game/play my-name "JC"))]
(is (= -1 (won-or-lost-high my-name low)))
(is (= -1 (won-or-lost-low my-name low)))
(is (= 0 (won-or-lost-jack my-name low)))
(is (= 1 (won-or-lost-high opponent low)))
(is (= 1 (won-or-lost-low opponent low)))
(is (= 0 (won-or-lost-jack opponent low))))))))
(deftest test-static-score
(testing "static evaluation of state"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; 1 point for high card.
(is (= 1 (static-score my-name (-> state (game/play my-name "AC")
(game/play opponent "2D")))))
;; 3 points for high, low, and jack.
(is (= 3 (static-score my-name (-> state (game/play my-name "<NAME>")
(game/play opponent "2D"))))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
;; -2 since opponent has high (in hand) and low (played).
(is (= -2 (static-score my-name (-> state (game/play opponent "2D")
(game/play my-name "KC")))))
;; -1 since opponent has high (played).
(is (= -1 (static-score my-name (-> state (game/play opponent "6D")
(game/play my-name "JC")))))
;; -1 since opponent has high (in hand).
(is (= -1 (static-score my-name (-> state (game/play opponent "4D")
(game/play my-name "JC")))))))))
(deftest test-prune
(testing "likely best moves without recursing"
(let [my-name "<NAME>" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state))]
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; All moves are equivalent when statically considered.
(is (subset?
(set (prune my-name state (possible-moves state)))
(set [{:action "play" :value "4D"}
{:action "play" :value "TD"}
{:action "play" :value "AC"}])))
(let [lead (-> state (game/play my-name "AC"))
moves (possible-moves lead)]
;; Opponent needs to follow suit.
(is (= moves [{:action "play" :value "2C"}
{:action "play" :value "3C"}]))
;; But it should not throw the low.
(is (= (prune opponent lead moves)
[{:action "play" :value "3C"}]))
(let [final (-> lead
(game/play opponent "3C")
(game/play my-name "TD"))]
;; Opponent should use the low to take the ten!
(is (= (prune opponent final (possible-moves final))
[{:action "play" :value "2C"}]))))))))
(deftest test-expected-score
(testing "expected score of a state for a player"
(let [my-name "AI" opponent "opponent"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state)
(game/bid opponent 0) (game/bid my-name 2)
(game/play my-name "AC"))]
(binding [game/*reconcile-end-game* false]
(let [state (-> base (game/play opponent "3C")
(game/play my-name "TD") (game/play opponent "2C")
(game/play opponent "6D"))
done (-> state (game/play my-name "4D"))]
;; AI loses 2 (doesn't make bid) and opponent gets 2 (low + pts).
(is (= (expected-score my-name done) -4))
(is (= (expected-score opponent done) 4))
;; Can the computer figure out that out with one move left?
(is (= (expected-score my-name state) -4))
;; But from the beginning the AI can play smarter.
(is (= (expected-score my-name base) 1)))))))
;; Helper function for serializing state to be sent to AI.
(defn state-to-ai [state username]
(prn-str (game/shield state username true)))
;; This function performs the initial handshake that the AI client
;; (indeed, all clients, including the browser) go through when
;; connecting to the server. It is used in the tests below.
(defn setup-game [my-name from-ai to-ai]
;; Expect to receive "name" message from AI. Every client
;; tries to register with a name and is accepted if the name
;; is available and rejected otherwise.
(is (= {:message my-name} (<!! from-ai)))
;; We'll accept the name "AI". In this case the server usually
;; sends back a signed JWT, giving this client the privilege to
;; that name in case of future collisions. Really, we can send
;; back anything other than "taken".
(>!! to-ai "your-name-was-accepted")
;; After accepting the client, we send them the current state of
;; the game (shielded so they can't see other players' cards).
(>!! to-ai (state-to-ai game/empty-state my-name))
;; Expect to receive the "join" message from the client saying
;; the AI wants to join the game.
(is (= {:message "join"} (<!! from-ai)))
;; The client will now sit in a loop, waiting for updates from
;; the server. The browser will show this new game state to the
;; player and respond with player action. The AI will examine
;; the state and try to come up with its own response (if it is
;; its turn to play).
)
(deftest test-ai
(testing "AI bidding behavior"
(let [my-name "AI"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))]
(setup-game my-name from-ai to-ai)
;; Let's make up some states and see how the AI responds.
(let [opponent "opponent-name"
state (-> game/empty-state
;; Add the AI and another player
(game/add-player my-name opponent)
;; Give them each some cards.
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
;; Set dealer and order players accordingly.
(game/dealt-state))]
(is (= (game/get-dealer state) my-name))
(is (= (game/get-onus state) opponent))
;; If opponent passes, then AI will bid 2.
(>!! to-ai (-> state
(game/bid opponent 0)
(state-to-ai my-name)))
(is (= {:message "bid:2"} (<!! from-ai))))
;; Try to clean up the running AI process.
(future-cancel brain)))
;; There once existed a bug who only showed its face when:
;; 1) a game had ended and a new one started, and
;; 2) the AI was the second player to bid.
;; Let's try to recreate that scenario here.
(testing "AI response to game restarts"
(let [my-name "AI"
opponent "opponent"
points (assoc {} my-name (dec game/MAX_POINTS) opponent 0)
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
(assoc :points points) ;; about to win
(game/add-player opponent my-name)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid my-name 2) (game/bid opponent 0)
(game/play my-name "AC") (game/play opponent "2D")
(game/play my-name "KC") (game/play opponent "4D"))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
;; Send state to AI and it will/should play the only card it has
;; left (JC).
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "play:JC"} (<!! from-ai)))
(let [cards-played (-> state (game/play my-name "<NAME>") (game/play opponent "6D"))]
;; Game should be over, since AI has > MAX_POINTS.
(is (game/game-over? cards-played))
(is (= my-name (game/get-winner cards-played)))
;; Start a new game and have the opponent pass the bid.
(let [new-state (-> cards-played game/restart (game/bid opponent 0))]
(>!! to-ai (state-to-ai new-state my-name))
(is (= {:message "bid:2"} (<!! from-ai)))))
(future-cancel brain))))
(deftest test-ai-start
;; There once existed a bug who only showed its face when:
;; 1) a player had requested an AI opponent, but
;; 2) the player left without starting the game.
;; Now the AI "owned" the game and would be responsible for starting it (if
;; the same player rejoined or another joined) and it had no logic to do so.
(testing "AI can start a game"
(let [my-name "AI" opponent "opponent"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
;; AI is first player
(game/add-player my-name opponent))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "start:"} (<!! from-ai)))
(future-cancel brain))))
| true | (ns bidpitch.test.ai
(:use clojure.test bidpitch.ai)
(:require [clojure.core.async :refer [<!! >!! chan]]
[clojure.set :refer [subset?]]
[bidpitch.game :as game]))
(deftest test-possible-moves
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
(testing "possible bids"
(is (= (possible-moves state) [{:action "bid" :value 0}
{:action "bid" :value 2}]))
(is (= (possible-moves (-> state (game/bid opponent 0)))
[{:action "bid" :value 2}])))
(testing "possible cards"
(is (= (possible-moves (-> state (game/bid opponent 0)
(game/bid my-name 2)))
[{:action "play" :value "AC"}
{:action "play" :value "KC"}
{:action "play" :value "JC"}]))
(is (= (possible-moves (-> state (game/bid opponent 2)
(game/bid my-name 0)))
[{:action "play" :value "2D"}
{:action "play" :value "4D"}
{:action "play" :value "6D"}])))))
(deftest test-possible-next-states
(testing "possible next states"
(let [my-name "AI" opponent "opponent-name"
state (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid opponent 2) (game/bid my-name 0)
(game/play opponent "6D") (game/play my-name "JC")
(game/play opponent "4D") (game/play my-name "KC"))
one-step (-> state (game/play opponent "2D"))]
(is (= (possible-state state (first (possible-moves state))) one-step))
(binding [game/*reconcile-end-game* false]
(is (= (possible-state one-step (first (possible-moves one-step)))
(-> one-step (game/play my-name "AC"))))))))
(deftest test-ai-helpers
(testing "who has what cards"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
(let [high (-> state
(game/play my-name "AC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= -1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play my-name "JC") (game/play opponent "2D"))]
(is (= 1 (won-or-lost-high my-name low)))
(is (= 1 (won-or-lost-low my-name low)))
(is (= 1 (won-or-lost-jack my-name low)))
(is (= -1 (won-or-lost-high opponent low)))
(is (= -1 (won-or-lost-low opponent low)))
(is (= -1 (won-or-lost-jack opponent low)))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
(let [high (-> state
(game/play opponent "4D") (game/play my-name "KC"))]
(is (= -1 (won-or-lost-high my-name high)))
(is (= 0 (won-or-lost-low my-name high)))
(is (= 0 (won-or-lost-jack my-name high)))
(is (= 1 (won-or-lost-high opponent high)))
(is (= 0 (won-or-lost-low opponent high)))
(is (= 0 (won-or-lost-jack opponent high))))
(let [low (-> state
(game/play opponent "2D") (game/play my-name "JC"))]
(is (= -1 (won-or-lost-high my-name low)))
(is (= -1 (won-or-lost-low my-name low)))
(is (= 0 (won-or-lost-jack my-name low)))
(is (= 1 (won-or-lost-high opponent low)))
(is (= 1 (won-or-lost-low opponent low)))
(is (= 0 (won-or-lost-jack opponent low))))))))
(deftest test-static-score
(testing "static evaluation of state"
(let [my-name "AI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state))]
;; AI picks trump.
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; 1 point for high card.
(is (= 1 (static-score my-name (-> state (game/play my-name "AC")
(game/play opponent "2D")))))
;; 3 points for high, low, and jack.
(is (= 3 (static-score my-name (-> state (game/play my-name "PI:NAME:<NAME>END_PI")
(game/play opponent "2D"))))))
;; Opponent picks trump.
(let [state (-> base (game/bid opponent 2) (game/bid my-name 0))]
;; -2 since opponent has high (in hand) and low (played).
(is (= -2 (static-score my-name (-> state (game/play opponent "2D")
(game/play my-name "KC")))))
;; -1 since opponent has high (played).
(is (= -1 (static-score my-name (-> state (game/play opponent "6D")
(game/play my-name "JC")))))
;; -1 since opponent has high (in hand).
(is (= -1 (static-score my-name (-> state (game/play opponent "4D")
(game/play my-name "JC")))))))))
(deftest test-prune
(testing "likely best moves without recursing"
(let [my-name "PI:NAME:<NAME>END_PI" opponent "other"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state))]
(let [state (-> base (game/bid opponent 0) (game/bid my-name 2))]
;; All moves are equivalent when statically considered.
(is (subset?
(set (prune my-name state (possible-moves state)))
(set [{:action "play" :value "4D"}
{:action "play" :value "TD"}
{:action "play" :value "AC"}])))
(let [lead (-> state (game/play my-name "AC"))
moves (possible-moves lead)]
;; Opponent needs to follow suit.
(is (= moves [{:action "play" :value "2C"}
{:action "play" :value "3C"}]))
;; But it should not throw the low.
(is (= (prune opponent lead moves)
[{:action "play" :value "3C"}]))
(let [final (-> lead
(game/play opponent "3C")
(game/play my-name "TD"))]
;; Opponent should use the low to take the ten!
(is (= (prune opponent final (possible-moves final))
[{:action "play" :value "2C"}]))))))))
(deftest test-expected-score
(testing "expected score of a state for a player"
(let [my-name "AI" opponent "opponent"
base (-> game/empty-state
(game/add-player my-name opponent)
(game/add-cards my-name ["AC" "TD" "4D"])
(game/add-cards opponent ["2C" "3C" "6D"])
(game/dealt-state)
(game/bid opponent 0) (game/bid my-name 2)
(game/play my-name "AC"))]
(binding [game/*reconcile-end-game* false]
(let [state (-> base (game/play opponent "3C")
(game/play my-name "TD") (game/play opponent "2C")
(game/play opponent "6D"))
done (-> state (game/play my-name "4D"))]
;; AI loses 2 (doesn't make bid) and opponent gets 2 (low + pts).
(is (= (expected-score my-name done) -4))
(is (= (expected-score opponent done) 4))
;; Can the computer figure out that out with one move left?
(is (= (expected-score my-name state) -4))
;; But from the beginning the AI can play smarter.
(is (= (expected-score my-name base) 1)))))))
;; Helper function for serializing state to be sent to AI.
(defn state-to-ai [state username]
(prn-str (game/shield state username true)))
;; This function performs the initial handshake that the AI client
;; (indeed, all clients, including the browser) go through when
;; connecting to the server. It is used in the tests below.
(defn setup-game [my-name from-ai to-ai]
;; Expect to receive "name" message from AI. Every client
;; tries to register with a name and is accepted if the name
;; is available and rejected otherwise.
(is (= {:message my-name} (<!! from-ai)))
;; We'll accept the name "AI". In this case the server usually
;; sends back a signed JWT, giving this client the privilege to
;; that name in case of future collisions. Really, we can send
;; back anything other than "taken".
(>!! to-ai "your-name-was-accepted")
;; After accepting the client, we send them the current state of
;; the game (shielded so they can't see other players' cards).
(>!! to-ai (state-to-ai game/empty-state my-name))
;; Expect to receive the "join" message from the client saying
;; the AI wants to join the game.
(is (= {:message "join"} (<!! from-ai)))
;; The client will now sit in a loop, waiting for updates from
;; the server. The browser will show this new game state to the
;; player and respond with player action. The AI will examine
;; the state and try to come up with its own response (if it is
;; its turn to play).
)
(deftest test-ai
(testing "AI bidding behavior"
(let [my-name "AI"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))]
(setup-game my-name from-ai to-ai)
;; Let's make up some states and see how the AI responds.
(let [opponent "opponent-name"
state (-> game/empty-state
;; Add the AI and another player
(game/add-player my-name opponent)
;; Give them each some cards.
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
;; Set dealer and order players accordingly.
(game/dealt-state))]
(is (= (game/get-dealer state) my-name))
(is (= (game/get-onus state) opponent))
;; If opponent passes, then AI will bid 2.
(>!! to-ai (-> state
(game/bid opponent 0)
(state-to-ai my-name)))
(is (= {:message "bid:2"} (<!! from-ai))))
;; Try to clean up the running AI process.
(future-cancel brain)))
;; There once existed a bug who only showed its face when:
;; 1) a game had ended and a new one started, and
;; 2) the AI was the second player to bid.
;; Let's try to recreate that scenario here.
(testing "AI response to game restarts"
(let [my-name "AI"
opponent "opponent"
points (assoc {} my-name (dec game/MAX_POINTS) opponent 0)
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
(assoc :points points) ;; about to win
(game/add-player opponent my-name)
(game/add-cards my-name ["AC" "KC" "JC"])
(game/add-cards opponent ["2D" "4D" "6D"])
(game/dealt-state)
(game/bid my-name 2) (game/bid opponent 0)
(game/play my-name "AC") (game/play opponent "2D")
(game/play my-name "KC") (game/play opponent "4D"))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
;; Send state to AI and it will/should play the only card it has
;; left (JC).
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "play:JC"} (<!! from-ai)))
(let [cards-played (-> state (game/play my-name "PI:NAME:<NAME>END_PI") (game/play opponent "6D"))]
;; Game should be over, since AI has > MAX_POINTS.
(is (game/game-over? cards-played))
(is (= my-name (game/get-winner cards-played)))
;; Start a new game and have the opponent pass the bid.
(let [new-state (-> cards-played game/restart (game/bid opponent 0))]
(>!! to-ai (state-to-ai new-state my-name))
(is (= {:message "bid:2"} (<!! from-ai)))))
(future-cancel brain))))
(deftest test-ai-start
;; There once existed a bug who only showed its face when:
;; 1) a player had requested an AI opponent, but
;; 2) the player left without starting the game.
;; Now the AI "owned" the game and would be responsible for starting it (if
;; the same player rejoined or another joined) and it had no logic to do so.
(testing "AI can start a game"
(let [my-name "AI" opponent "opponent"
from-ai (chan) to-ai (chan)
brain (future (play from-ai to-ai))
state (-> game/empty-state
;; AI is first player
(game/add-player my-name opponent))]
;; Setup initial state.
(setup-game my-name from-ai to-ai)
(>!! to-ai (state-to-ai state my-name))
(is (= {:message "start:"} (<!! from-ai)))
(future-cancel brain))))
|
[
{
"context": "le\",\n \"error_key\" \"TUTORIAL_ERROR\"},\n \"extra_data\" {\"error_key\"",
"end": 346,
"score": 0.935981035232544,
"start": 332,
"tag": "KEY",
"value": "TUTORIAL_ERROR"
},
{
"context": ",\n \"extra_data\" {\"error_key\" \"TUTORIAL_ERROR\",\n \"type\" \"rule",
"end": 412,
"score": 0.9643800258636475,
"start": 398,
"tag": "KEY",
"value": "TUTORIAL_ERROR"
},
{
"context": "ndpointDegraded: failed to GET well-known https://10.237.112.145:6443/.well-known/oauth-authorization-server: Tunn",
"end": 1406,
"score": 0.999704897403717,
"start": 1392,
"tag": "IP_ADDRESS",
"value": "10.237.112.145"
},
{
"context": "le\",\n \"error_key\" \"AUTH_OPERATOR_PROXY_ERROR\"},\n \"extra_data\" {\"error_key\"",
"end": 2659,
"score": 0.9984602332115173,
"start": 2634,
"tag": "KEY",
"value": "AUTH_OPERATOR_PROXY_ERROR"
},
{
"context": ",\n \"extra_data\" {\"error_key\" \"AUTH_OPERATOR_PROXY_ERROR\",\n \"kcs\" \"https",
"end": 2736,
"score": 0.9987841844558716,
"start": 2711,
"tag": "KEY",
"value": "AUTH_OPERATOR_PROXY_ERROR"
},
{
"context": "le\",\n \"error_key\" \"BUGZILLA_BUG_1766907\"},\n \"extra_data\" {\"error_key\"",
"end": 5342,
"score": 0.9993762969970703,
"start": 5322,
"tag": "KEY",
"value": "BUGZILLA_BUG_1766907"
},
{
"context": ",\n \"extra_data\" {\"error_key\" \"BUGZILLA_BUG_1766907\",\n \"type\" \"rule",
"end": 5414,
"score": 0.9994850158691406,
"start": 5394,
"tag": "KEY",
"value": "BUGZILLA_BUG_1766907"
},
{
"context": " \"details\" {\"nodes\" [{\"name\" \"foo1\",\n \"role",
"end": 6505,
"score": 0.9585925936698914,
"start": 6504,
"tag": "USERNAME",
"value": "1"
},
{
"context": ",\n \"details\" {\"info\" {\"name\" \"openshift-samples\",\n \"condit",
"end": 9353,
"score": 0.9334085583686829,
"start": 9336,
"tag": "USERNAME",
"value": "openshift-samples"
},
{
"context": "le\",\n \"error_key\" \"SAMPLES_FAILED_IMAGE_IMPORT_ERR\"},\n \"extra_data\" {\"error_key\"",
"end": 9922,
"score": 0.9679960608482361,
"start": 9891,
"tag": "KEY",
"value": "SAMPLES_FAILED_IMAGE_IMPORT_ERR"
},
{
"context": ",\n \"extra_data\" {\"error_key\" \"SAMPLES_FAILED_IMAGE_IMPORT_ERR\",\n \"info\" {\"con",
"end": 10005,
"score": 0.9905264973640442,
"start": 9974,
"tag": "KEY",
"value": "SAMPLES_FAILED_IMAGE_IMPORT_ERR"
},
{
"context": " \"name\" \"openshift-samples\",\n \"rea",
"end": 10361,
"score": 0.8969685435295105,
"start": 10344,
"tag": "USERNAME",
"value": "openshift-samples"
}
] | data-edn/report_34c3ecc5-624a-49a5-bab8-4fdc5e51a26b.clj | RedHatInsights/insights-results-aggregator-moc | 2 | {"reports" {"meta" {"count" 7,
"last_checked_at" "2020-05-27T14:15:35Z"},
"data" [{"tags" [],
"total_risk" 1,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "TUTORIAL_ERROR"},
"extra_data" {"error_key" "TUTORIAL_ERROR",
"type" "rule"},
"reason" "",
"created_at" "2020-04-08T00:42:00Z",
"disabled" false,
"description" "Introducing Insights for Red Hat OpenShift Container Platform",
"rule_id" "ccx_rules_ocm.tutorial_rule",
"resolution" ""}
{"tags" ["security" "service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"op" {"available" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"degraded" {"message" "WellKnownEndpointDegraded: failed to GET well-known https://10.237.112.145:6443/.well-known/oauth-authorization-server: Tunnel or SSL Forbidden",
"reason" "WellKnownEndpointDegradedError",
"status" true,
"last_trans_time" "2020-03-31T08:42:33Z"},
"name" "authentication",
"progressing" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"upgradeable" {"message" nil,
"reason" "AsExpected",
"status" true,
"last_trans_time" "2020-03-31T08:39:51Z"},
"version" nil},
"kcs" "https://access.redhat.com/solutions/4569191",
"type" "rule",
"error_key" "AUTH_OPERATOR_PROXY_ERROR"},
"extra_data" {"error_key" "AUTH_OPERATOR_PROXY_ERROR",
"kcs" "https://access.redhat.com/solutions/4569191",
"op" {"available" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"degraded" {"last_trans_time" "2020-04-21T12:46:29Z",
"message" "WellKnownEndpointDegraded: failed to GET well-known",
"reason" "AsExpected",
"status" true},
"name" "authentication",
"progressing" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"upgradeable" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "AsExpected",
"status" true},
"version" nil},
"type" "rule"},
"reason" "Requests to routes and/or the public API endpoint are not being proxied to the cluster.\n",
"created_at" "2020-02-03T08:25:00Z",
"disabled" false,
"description" "The authentication operator is degraded when cluster is configured to use a cluster-wide proxy",
"rule_id" "ccx_rules_ocp.external.rules.cluster_wide_proxy_auth_check",
"resolution" "Red Hat recommends that you to follow steps in the KCS article.\n * [Authentication operator Degraded with Reason `WellKnownEndpointDegradedError`](https://access.redhat.com/solutions/4569191)\n"}
{"tags" ["openshift"
"networking"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "BUGZILLA_BUG_1766907"},
"extra_data" {"error_key" "BUGZILLA_BUG_1766907",
"type" "rule"},
"reason" "On this OCP 4 cluster, a cluster wide proxy is set. Due to a bug, the CVO is not using the proxy. This will lead to a upgrade failure.",
"created_at" "2020-01-17T11:10:00Z",
"disabled" false,
"description" "The OpenShift cluster will experience upgrade failure when the cluster wide proxy is configured due to a bug",
"rule_id" "ccx_rules_ocp.external.bug_rules.bug_1766907",
"resolution" "Red Hat recommends that you to use this workaround:\n1. Set the proxy manually\n~~~\n# oc -n openshift-cluster-version set env deploy cluster-version-operator HTTP_PROXY=xxx HTTPS_PROXY=xxx NO_PROXY=xxx\n~~~\n"}
{"tags" ["openshift"
"configuration"
"performance"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"nodes" [{"name" "foo1",
"role" "master",
"memory" 8.16,
"memory_req" 16}],
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"type" "rule",
"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET"},
"extra_data" {"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET",
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"nodes" [{"cpu" 1,
"cpu_req" 2,
"name" "ip-10-0-144-53.us-east-2.compute.internal",
"role" "worker"}],
"type" "rule"},
"reason" "Node{{?pydata.nodes.length>1}}s{{?}} not meeting the minimum requirements:\n{{~ pydata.nodes :node }}\n1. {{=node[\"name\"]}}\n * Role: {{=node[\"role\"]}}{{?node.memory}}\n * Minimum memory requirement is {{=node[\"memory_req\"]}}, but the node is configured with {{=node[\"memory\"]}}.{{?}}{{?node.cpu}}\n * Minimum cpu requirement is {{=node[\"cpu_req\"]}}, but the node is configured with {{=node[\"cpu\"]}}.{{?}}{{~}}",
"created_at" "2019-10-29T15:00:00Z",
"disabled" false,
"description" "OCP node could behave unexpectedly when it doesn't meet the minimum resource requirements",
"rule_id" "ccx_rules_ocp.external.rules.nodes_requirements_check",
"resolution" "Red Hat recommends that you configure your nodes to meet the minimum resource requirements.\n\nMake sure that:\n\n{{~ pydata.nodes :node }}\n1. Node {{=node[\"name\"]}} ({{=node[\"role\"]}}){{?node[\"memory\"]}}\n * Has enough memory, minimum requirement is {{=node[\"memory_req\"]}}. Currently its only configured with {{=node[\"memory\"]}}GB.{{?}}{{?node.cpu}}\n * Has enough allocatable cpu, minimum requirement is {{=node[\"cpu_req\"]}}. Currently its only configured with {{=node[\"cpu\"]}}.{{?}}{{~}}\n"}
{"tags" ["openshift"
"incident"
"networking"
"registry"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"info" {"name" "openshift-samples",
"condition" "Degraded",
"reason" "FailedImageImports",
"message" "Samples installed at 4.2.0, with image import failures for these imagestreams: php ",
"lastTransitionTime" "2020-03-19T08:32:53Z"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule",
"error_key" "SAMPLES_FAILED_IMAGE_IMPORT_ERR"},
"extra_data" {"error_key" "SAMPLES_FAILED_IMAGE_IMPORT_ERR",
"info" {"condition" "Degraded",
"lastTransitionTime" "2019-12-06T15:58:09Z",
"message" "Samples installed at , with image import failures for these imagestreams:",
"name" "openshift-samples",
"reason" "FailedImageImports"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule"},
"reason" "Due to a temporary hiccup talking to the Red Hat registry the openshift-samples failed to import some of the imagestreams.\n\n\nSource of the issue:\n\n**Cluster-operator:** **{{=pydata.info[\"name\"]}}**\n- *Condition:* {{=pydata.info[\"condition\"]}}\n- *Reason:* {{=pydata.info[\"reason\"]}}\n- *Message:* {{=pydata.info[\"message\"]}}\n- *Last* Transition: {{=pydata.info[\"lastTransitionTime\"]}}\n",
"created_at" "2020-02-07T14:19:00Z",
"disabled" false,
"description" "Pods could fail to start if openshift-samples is degraded due to FailedImageImport which is caused by a hiccup while talking to the Red Hat registry",
"rule_id" "ccx_rules_ocp.external.rules.samples_op_failed_image_import_check",
"resolution" "Red Hat recommends that you to follow these steps:\n\n1. Fix 1, Try running:\n~~~\n# oc import-image <for the ImageStream(s) in question>\n~~~\n\n1. Fix 2, Try running:\n~~~\n# oc delete configs.samples cluster\n~~~"}]},
"status" "ok"}
| 28224 | {"reports" {"meta" {"count" 7,
"last_checked_at" "2020-05-27T14:15:35Z"},
"data" [{"tags" [],
"total_risk" 1,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "<KEY>"},
"extra_data" {"error_key" "<KEY>",
"type" "rule"},
"reason" "",
"created_at" "2020-04-08T00:42:00Z",
"disabled" false,
"description" "Introducing Insights for Red Hat OpenShift Container Platform",
"rule_id" "ccx_rules_ocm.tutorial_rule",
"resolution" ""}
{"tags" ["security" "service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"op" {"available" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"degraded" {"message" "WellKnownEndpointDegraded: failed to GET well-known https://10.237.112.145:6443/.well-known/oauth-authorization-server: Tunnel or SSL Forbidden",
"reason" "WellKnownEndpointDegradedError",
"status" true,
"last_trans_time" "2020-03-31T08:42:33Z"},
"name" "authentication",
"progressing" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"upgradeable" {"message" nil,
"reason" "AsExpected",
"status" true,
"last_trans_time" "2020-03-31T08:39:51Z"},
"version" nil},
"kcs" "https://access.redhat.com/solutions/4569191",
"type" "rule",
"error_key" "<KEY>"},
"extra_data" {"error_key" "<KEY>",
"kcs" "https://access.redhat.com/solutions/4569191",
"op" {"available" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"degraded" {"last_trans_time" "2020-04-21T12:46:29Z",
"message" "WellKnownEndpointDegraded: failed to GET well-known",
"reason" "AsExpected",
"status" true},
"name" "authentication",
"progressing" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"upgradeable" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "AsExpected",
"status" true},
"version" nil},
"type" "rule"},
"reason" "Requests to routes and/or the public API endpoint are not being proxied to the cluster.\n",
"created_at" "2020-02-03T08:25:00Z",
"disabled" false,
"description" "The authentication operator is degraded when cluster is configured to use a cluster-wide proxy",
"rule_id" "ccx_rules_ocp.external.rules.cluster_wide_proxy_auth_check",
"resolution" "Red Hat recommends that you to follow steps in the KCS article.\n * [Authentication operator Degraded with Reason `WellKnownEndpointDegradedError`](https://access.redhat.com/solutions/4569191)\n"}
{"tags" ["openshift"
"networking"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "<KEY>"},
"extra_data" {"error_key" "<KEY>",
"type" "rule"},
"reason" "On this OCP 4 cluster, a cluster wide proxy is set. Due to a bug, the CVO is not using the proxy. This will lead to a upgrade failure.",
"created_at" "2020-01-17T11:10:00Z",
"disabled" false,
"description" "The OpenShift cluster will experience upgrade failure when the cluster wide proxy is configured due to a bug",
"rule_id" "ccx_rules_ocp.external.bug_rules.bug_1766907",
"resolution" "Red Hat recommends that you to use this workaround:\n1. Set the proxy manually\n~~~\n# oc -n openshift-cluster-version set env deploy cluster-version-operator HTTP_PROXY=xxx HTTPS_PROXY=xxx NO_PROXY=xxx\n~~~\n"}
{"tags" ["openshift"
"configuration"
"performance"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"nodes" [{"name" "foo1",
"role" "master",
"memory" 8.16,
"memory_req" 16}],
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"type" "rule",
"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET"},
"extra_data" {"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET",
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"nodes" [{"cpu" 1,
"cpu_req" 2,
"name" "ip-10-0-144-53.us-east-2.compute.internal",
"role" "worker"}],
"type" "rule"},
"reason" "Node{{?pydata.nodes.length>1}}s{{?}} not meeting the minimum requirements:\n{{~ pydata.nodes :node }}\n1. {{=node[\"name\"]}}\n * Role: {{=node[\"role\"]}}{{?node.memory}}\n * Minimum memory requirement is {{=node[\"memory_req\"]}}, but the node is configured with {{=node[\"memory\"]}}.{{?}}{{?node.cpu}}\n * Minimum cpu requirement is {{=node[\"cpu_req\"]}}, but the node is configured with {{=node[\"cpu\"]}}.{{?}}{{~}}",
"created_at" "2019-10-29T15:00:00Z",
"disabled" false,
"description" "OCP node could behave unexpectedly when it doesn't meet the minimum resource requirements",
"rule_id" "ccx_rules_ocp.external.rules.nodes_requirements_check",
"resolution" "Red Hat recommends that you configure your nodes to meet the minimum resource requirements.\n\nMake sure that:\n\n{{~ pydata.nodes :node }}\n1. Node {{=node[\"name\"]}} ({{=node[\"role\"]}}){{?node[\"memory\"]}}\n * Has enough memory, minimum requirement is {{=node[\"memory_req\"]}}. Currently its only configured with {{=node[\"memory\"]}}GB.{{?}}{{?node.cpu}}\n * Has enough allocatable cpu, minimum requirement is {{=node[\"cpu_req\"]}}. Currently its only configured with {{=node[\"cpu\"]}}.{{?}}{{~}}\n"}
{"tags" ["openshift"
"incident"
"networking"
"registry"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"info" {"name" "openshift-samples",
"condition" "Degraded",
"reason" "FailedImageImports",
"message" "Samples installed at 4.2.0, with image import failures for these imagestreams: php ",
"lastTransitionTime" "2020-03-19T08:32:53Z"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule",
"error_key" "<KEY>"},
"extra_data" {"error_key" "<KEY>",
"info" {"condition" "Degraded",
"lastTransitionTime" "2019-12-06T15:58:09Z",
"message" "Samples installed at , with image import failures for these imagestreams:",
"name" "openshift-samples",
"reason" "FailedImageImports"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule"},
"reason" "Due to a temporary hiccup talking to the Red Hat registry the openshift-samples failed to import some of the imagestreams.\n\n\nSource of the issue:\n\n**Cluster-operator:** **{{=pydata.info[\"name\"]}}**\n- *Condition:* {{=pydata.info[\"condition\"]}}\n- *Reason:* {{=pydata.info[\"reason\"]}}\n- *Message:* {{=pydata.info[\"message\"]}}\n- *Last* Transition: {{=pydata.info[\"lastTransitionTime\"]}}\n",
"created_at" "2020-02-07T14:19:00Z",
"disabled" false,
"description" "Pods could fail to start if openshift-samples is degraded due to FailedImageImport which is caused by a hiccup while talking to the Red Hat registry",
"rule_id" "ccx_rules_ocp.external.rules.samples_op_failed_image_import_check",
"resolution" "Red Hat recommends that you to follow these steps:\n\n1. Fix 1, Try running:\n~~~\n# oc import-image <for the ImageStream(s) in question>\n~~~\n\n1. Fix 2, Try running:\n~~~\n# oc delete configs.samples cluster\n~~~"}]},
"status" "ok"}
| true | {"reports" {"meta" {"count" 7,
"last_checked_at" "2020-05-27T14:15:35Z"},
"data" [{"tags" [],
"total_risk" 1,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "PI:KEY:<KEY>END_PI"},
"extra_data" {"error_key" "PI:KEY:<KEY>END_PI",
"type" "rule"},
"reason" "",
"created_at" "2020-04-08T00:42:00Z",
"disabled" false,
"description" "Introducing Insights for Red Hat OpenShift Container Platform",
"rule_id" "ccx_rules_ocm.tutorial_rule",
"resolution" ""}
{"tags" ["security" "service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"op" {"available" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"degraded" {"message" "WellKnownEndpointDegraded: failed to GET well-known https://10.237.112.145:6443/.well-known/oauth-authorization-server: Tunnel or SSL Forbidden",
"reason" "WellKnownEndpointDegradedError",
"status" true,
"last_trans_time" "2020-03-31T08:42:33Z"},
"name" "authentication",
"progressing" {"message" nil,
"reason" "NoData",
"status" nil,
"last_trans_time" "2020-03-31T08:39:51Z"},
"upgradeable" {"message" nil,
"reason" "AsExpected",
"status" true,
"last_trans_time" "2020-03-31T08:39:51Z"},
"version" nil},
"kcs" "https://access.redhat.com/solutions/4569191",
"type" "rule",
"error_key" "PI:KEY:<KEY>END_PI"},
"extra_data" {"error_key" "PI:KEY:<KEY>END_PI",
"kcs" "https://access.redhat.com/solutions/4569191",
"op" {"available" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"degraded" {"last_trans_time" "2020-04-21T12:46:29Z",
"message" "WellKnownEndpointDegraded: failed to GET well-known",
"reason" "AsExpected",
"status" true},
"name" "authentication",
"progressing" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "NoData",
"status" nil},
"upgradeable" {"last_trans_time" "2020-04-21T12:46:28Z",
"message" nil,
"reason" "AsExpected",
"status" true},
"version" nil},
"type" "rule"},
"reason" "Requests to routes and/or the public API endpoint are not being proxied to the cluster.\n",
"created_at" "2020-02-03T08:25:00Z",
"disabled" false,
"description" "The authentication operator is degraded when cluster is configured to use a cluster-wide proxy",
"rule_id" "ccx_rules_ocp.external.rules.cluster_wide_proxy_auth_check",
"resolution" "Red Hat recommends that you to follow steps in the KCS article.\n * [Authentication operator Degraded with Reason `WellKnownEndpointDegradedError`](https://access.redhat.com/solutions/4569191)\n"}
{"tags" ["openshift"
"networking"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"type" "rule",
"error_key" "PI:KEY:<KEY>END_PI"},
"extra_data" {"error_key" "PI:KEY:<KEY>END_PI",
"type" "rule"},
"reason" "On this OCP 4 cluster, a cluster wide proxy is set. Due to a bug, the CVO is not using the proxy. This will lead to a upgrade failure.",
"created_at" "2020-01-17T11:10:00Z",
"disabled" false,
"description" "The OpenShift cluster will experience upgrade failure when the cluster wide proxy is configured due to a bug",
"rule_id" "ccx_rules_ocp.external.bug_rules.bug_1766907",
"resolution" "Red Hat recommends that you to use this workaround:\n1. Set the proxy manually\n~~~\n# oc -n openshift-cluster-version set env deploy cluster-version-operator HTTP_PROXY=xxx HTTPS_PROXY=xxx NO_PROXY=xxx\n~~~\n"}
{"tags" ["openshift"
"configuration"
"performance"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"nodes" [{"name" "foo1",
"role" "master",
"memory" 8.16,
"memory_req" 16}],
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"type" "rule",
"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET"},
"extra_data" {"error_key" "NODES_MINIMUM_REQUIREMENTS_NOT_MET",
"link" "https://docs.openshift.com/container-platform/4.1/installing/installing_bare_metal/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal",
"nodes" [{"cpu" 1,
"cpu_req" 2,
"name" "ip-10-0-144-53.us-east-2.compute.internal",
"role" "worker"}],
"type" "rule"},
"reason" "Node{{?pydata.nodes.length>1}}s{{?}} not meeting the minimum requirements:\n{{~ pydata.nodes :node }}\n1. {{=node[\"name\"]}}\n * Role: {{=node[\"role\"]}}{{?node.memory}}\n * Minimum memory requirement is {{=node[\"memory_req\"]}}, but the node is configured with {{=node[\"memory\"]}}.{{?}}{{?node.cpu}}\n * Minimum cpu requirement is {{=node[\"cpu_req\"]}}, but the node is configured with {{=node[\"cpu\"]}}.{{?}}{{~}}",
"created_at" "2019-10-29T15:00:00Z",
"disabled" false,
"description" "OCP node could behave unexpectedly when it doesn't meet the minimum resource requirements",
"rule_id" "ccx_rules_ocp.external.rules.nodes_requirements_check",
"resolution" "Red Hat recommends that you configure your nodes to meet the minimum resource requirements.\n\nMake sure that:\n\n{{~ pydata.nodes :node }}\n1. Node {{=node[\"name\"]}} ({{=node[\"role\"]}}){{?node[\"memory\"]}}\n * Has enough memory, minimum requirement is {{=node[\"memory_req\"]}}. Currently its only configured with {{=node[\"memory\"]}}GB.{{?}}{{?node.cpu}}\n * Has enough allocatable cpu, minimum requirement is {{=node[\"cpu_req\"]}}. Currently its only configured with {{=node[\"cpu\"]}}.{{?}}{{~}}\n"}
{"tags" ["openshift"
"incident"
"networking"
"registry"
"service_availability"],
"total_risk" 2,
"risk_of_change" 0,
"user_vote" 0,
"details" {"info" {"name" "openshift-samples",
"condition" "Degraded",
"reason" "FailedImageImports",
"message" "Samples installed at 4.2.0, with image import failures for these imagestreams: php ",
"lastTransitionTime" "2020-03-19T08:32:53Z"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule",
"error_key" "PI:KEY:<KEY>END_PI"},
"extra_data" {"error_key" "PI:KEY:<KEY>END_PI",
"info" {"condition" "Degraded",
"lastTransitionTime" "2019-12-06T15:58:09Z",
"message" "Samples installed at , with image import failures for these imagestreams:",
"name" "openshift-samples",
"reason" "FailedImageImports"},
"kcs" "https://access.redhat.com/solutions/4563171",
"type" "rule"},
"reason" "Due to a temporary hiccup talking to the Red Hat registry the openshift-samples failed to import some of the imagestreams.\n\n\nSource of the issue:\n\n**Cluster-operator:** **{{=pydata.info[\"name\"]}}**\n- *Condition:* {{=pydata.info[\"condition\"]}}\n- *Reason:* {{=pydata.info[\"reason\"]}}\n- *Message:* {{=pydata.info[\"message\"]}}\n- *Last* Transition: {{=pydata.info[\"lastTransitionTime\"]}}\n",
"created_at" "2020-02-07T14:19:00Z",
"disabled" false,
"description" "Pods could fail to start if openshift-samples is degraded due to FailedImageImport which is caused by a hiccup while talking to the Red Hat registry",
"rule_id" "ccx_rules_ocp.external.rules.samples_op_failed_image_import_check",
"resolution" "Red Hat recommends that you to follow these steps:\n\n1. Fix 1, Try running:\n~~~\n# oc import-image <for the ImageStream(s) in question>\n~~~\n\n1. Fix 2, Try running:\n~~~\n# oc delete configs.samples cluster\n~~~"}]},
"status" "ok"}
|
[
{
"context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis",
"end": 33,
"score": 0.9998555779457092,
"start": 19,
"tag": "NAME",
"value": "Nicola Mometto"
},
{
"context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter",
"end": 46,
"score": 0.9998403787612915,
"start": 35,
"tag": "NAME",
"value": "Rich Hickey"
}
] | server/target/clojure/tools/analyzer/passes/jvm/annotate_branch.clj | OctavioBR/healthcheck | 0 | ;; Copyright (c) Nicola Mometto, Rich Hickey & contributors.
;; 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 clojure.tools.analyzer.passes.jvm.annotate-branch)
(defmulti annotate-branch
"Adds :branch? to branch AST nodes (if/case), :test? to the test children
node of the branching op and :path? to the branching paths.
Example: {:op if :branch? true :test {:test? true ..} :then {:path? true ..} ..}"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod annotate-branch :if
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:then :path?] true)
(assoc-in [:else :path?] true)))
(defmethod annotate-branch :fn-method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :case
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:default :path?] true)))
(defmethod annotate-branch :case-then
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :default [ast] ast)
| 81683 | ;; Copyright (c) <NAME>, <NAME> & contributors.
;; 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 clojure.tools.analyzer.passes.jvm.annotate-branch)
(defmulti annotate-branch
"Adds :branch? to branch AST nodes (if/case), :test? to the test children
node of the branching op and :path? to the branching paths.
Example: {:op if :branch? true :test {:test? true ..} :then {:path? true ..} ..}"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod annotate-branch :if
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:then :path?] true)
(assoc-in [:else :path?] true)))
(defmethod annotate-branch :fn-method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :case
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:default :path?] true)))
(defmethod annotate-branch :case-then
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :default [ast] ast)
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors.
;; 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 clojure.tools.analyzer.passes.jvm.annotate-branch)
(defmulti annotate-branch
"Adds :branch? to branch AST nodes (if/case), :test? to the test children
node of the branching op and :path? to the branching paths.
Example: {:op if :branch? true :test {:test? true ..} :then {:path? true ..} ..}"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod annotate-branch :if
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:then :path?] true)
(assoc-in [:else :path?] true)))
(defmethod annotate-branch :fn-method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :method
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :case
[ast]
(-> ast
(assoc :branch? true)
(assoc-in [:test :test?] true)
(assoc-in [:default :path?] true)))
(defmethod annotate-branch :case-then
[ast]
(assoc ast :path? true))
(defmethod annotate-branch :default [ast] ast)
|
[
{
"context": "\"localhost\"\n :port \"5439\"\n :user \"postgres\"\n :password \"postgres\"})\n\n (defn eval-mut-in",
"end": 3128,
"score": 0.697109580039978,
"start": 3120,
"tag": "USERNAME",
"value": "postgres"
},
{
"context": " \"5439\"\n :user \"postgres\"\n :password \"postgres\"})\n\n (defn eval-mut-in-pg [transformations data]",
"end": 3154,
"score": 0.9995723366737366,
"start": 3146,
"tag": "PASSWORD",
"value": "postgres"
}
] | src/bxb/core.clj | KGOH/bxb | 1 | (ns bxb.core
(:require [bxb.misc :as misc]
[bxb.mutate.hmap :as hmap]
[bxb.mutate.sql :as sql]
[bxb.mutate.debug :as debug]
[honeysql.core :as hsql]
[bxb.honey]))
(defn- walk-path [const-fn search-fn path]
(loop [[first-p & rest-p :as path] path
cur-path []
walked-paths-vals '()]
(cond
(every? misc/key? path)
{:walked-path (into cur-path (map const-fn path))
:const-paths-vals walked-paths-vals}
(misc/key? first-p)
(recur rest-p
(conj cur-path (const-fn first-p))
walked-paths-vals)
(map? first-p)
(recur rest-p
cur-path
(concat (map (fn [[k v]] [(conj cur-path (const-fn k)) (const-fn v)])
first-p)
walked-paths-vals))
(and (sequential? first-p)
(misc/single-elem? first-p))
(let [[ffp] first-p]
(cond
(map? ffp)
(recur (into first-p rest-p)
(conj cur-path (search-fn cur-path ffp))
walked-paths-vals)
(misc/key? ffp)
{:const-paths-vals walked-paths-vals
:map {:path rest-p
:walked-path (conj cur-path (const-fn ffp))}})))))
(defn- dissoc? [a b]
(some false? (map = a b)))
(defn- interpret-mapping [{:keys [const-fn search-fn map-fn get-fn assoc-fn dissoc-fn] :as fns} src dest]
(let [{get-value-path :walked-path, dissoc-const-paths-vals :const-paths-vals, {map-src :path, dissoc-map-path :walked-path} :map}
(walk-path const-fn search-fn src)
{put-value-path :walked-path, assoc-const-paths-vals :const-paths-vals, {map-dest :path, assoc-map-path :walked-path} :map}
(walk-path const-fn search-fn dest)]
(cond
(and get-value-path put-value-path)
(concat (map (partial apply assoc-fn) assoc-const-paths-vals)
[(assoc-fn put-value-path (get-fn get-value-path))]
(when (dissoc? src dest)
[(dissoc-fn get-value-path (get-fn get-value-path))])
(map (partial apply dissoc-fn) dissoc-const-paths-vals))
(and map-src map-dest)
[(map-fn dissoc-map-path
assoc-map-path
(interpret-mapping fns map-src map-dest))])))
(defn create-transformations
"Creates mutations to transmapm data. Bidirectional"
[fns [from to] mapping]
(misc/keepcat (fn [{src from, dest to}]
(when (and src dest) (interpret-mapping fns src dest)))
mapping))
(def debug-transformations (partial create-transformations debug/fns))
(def hmap-transformations (partial create-transformations hmap/fns))
(def sql-transformations (partial create-transformations sql/fns))
(def mutate misc/mutate)
(comment
(require '[cheshire.core :as json])
(require '[clojure.java.jdbc :as db])
(def db
{:dbtype "postgresql"
:dbname "test_testbox"
:host "localhost"
:port "5439"
:user "postgres"
:password "postgres"})
(defn eval-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs
(db/query db)
first
:r))
(defn test-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs))
(let [mapping
[{:v1 [:e]
:v2 [:a :e]}
{:v1 [:a :c [{:f 3}] :v]
:v2 [:ff]}
{:v1 [:a :d]
:v2 [:d]}]
data-source
{:a {:c [{:f 2, :v 1}
{:f 3, :v 5}
{:f 4, :v 6}]
:d 1}
:e -1}]
(clojure.pprint/pprint (debug-transformations [:v1 :v2] mapping))
(-> (test-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (eval-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (mutate (hmap-transformations [:v1 :v2] mapping)
data-source)
println))
nil)
| 77807 | (ns bxb.core
(:require [bxb.misc :as misc]
[bxb.mutate.hmap :as hmap]
[bxb.mutate.sql :as sql]
[bxb.mutate.debug :as debug]
[honeysql.core :as hsql]
[bxb.honey]))
(defn- walk-path [const-fn search-fn path]
(loop [[first-p & rest-p :as path] path
cur-path []
walked-paths-vals '()]
(cond
(every? misc/key? path)
{:walked-path (into cur-path (map const-fn path))
:const-paths-vals walked-paths-vals}
(misc/key? first-p)
(recur rest-p
(conj cur-path (const-fn first-p))
walked-paths-vals)
(map? first-p)
(recur rest-p
cur-path
(concat (map (fn [[k v]] [(conj cur-path (const-fn k)) (const-fn v)])
first-p)
walked-paths-vals))
(and (sequential? first-p)
(misc/single-elem? first-p))
(let [[ffp] first-p]
(cond
(map? ffp)
(recur (into first-p rest-p)
(conj cur-path (search-fn cur-path ffp))
walked-paths-vals)
(misc/key? ffp)
{:const-paths-vals walked-paths-vals
:map {:path rest-p
:walked-path (conj cur-path (const-fn ffp))}})))))
(defn- dissoc? [a b]
(some false? (map = a b)))
(defn- interpret-mapping [{:keys [const-fn search-fn map-fn get-fn assoc-fn dissoc-fn] :as fns} src dest]
(let [{get-value-path :walked-path, dissoc-const-paths-vals :const-paths-vals, {map-src :path, dissoc-map-path :walked-path} :map}
(walk-path const-fn search-fn src)
{put-value-path :walked-path, assoc-const-paths-vals :const-paths-vals, {map-dest :path, assoc-map-path :walked-path} :map}
(walk-path const-fn search-fn dest)]
(cond
(and get-value-path put-value-path)
(concat (map (partial apply assoc-fn) assoc-const-paths-vals)
[(assoc-fn put-value-path (get-fn get-value-path))]
(when (dissoc? src dest)
[(dissoc-fn get-value-path (get-fn get-value-path))])
(map (partial apply dissoc-fn) dissoc-const-paths-vals))
(and map-src map-dest)
[(map-fn dissoc-map-path
assoc-map-path
(interpret-mapping fns map-src map-dest))])))
(defn create-transformations
"Creates mutations to transmapm data. Bidirectional"
[fns [from to] mapping]
(misc/keepcat (fn [{src from, dest to}]
(when (and src dest) (interpret-mapping fns src dest)))
mapping))
(def debug-transformations (partial create-transformations debug/fns))
(def hmap-transformations (partial create-transformations hmap/fns))
(def sql-transformations (partial create-transformations sql/fns))
(def mutate misc/mutate)
(comment
(require '[cheshire.core :as json])
(require '[clojure.java.jdbc :as db])
(def db
{:dbtype "postgresql"
:dbname "test_testbox"
:host "localhost"
:port "5439"
:user "postgres"
:password "<PASSWORD>"})
(defn eval-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs
(db/query db)
first
:r))
(defn test-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs))
(let [mapping
[{:v1 [:e]
:v2 [:a :e]}
{:v1 [:a :c [{:f 3}] :v]
:v2 [:ff]}
{:v1 [:a :d]
:v2 [:d]}]
data-source
{:a {:c [{:f 2, :v 1}
{:f 3, :v 5}
{:f 4, :v 6}]
:d 1}
:e -1}]
(clojure.pprint/pprint (debug-transformations [:v1 :v2] mapping))
(-> (test-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (eval-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (mutate (hmap-transformations [:v1 :v2] mapping)
data-source)
println))
nil)
| true | (ns bxb.core
(:require [bxb.misc :as misc]
[bxb.mutate.hmap :as hmap]
[bxb.mutate.sql :as sql]
[bxb.mutate.debug :as debug]
[honeysql.core :as hsql]
[bxb.honey]))
(defn- walk-path [const-fn search-fn path]
(loop [[first-p & rest-p :as path] path
cur-path []
walked-paths-vals '()]
(cond
(every? misc/key? path)
{:walked-path (into cur-path (map const-fn path))
:const-paths-vals walked-paths-vals}
(misc/key? first-p)
(recur rest-p
(conj cur-path (const-fn first-p))
walked-paths-vals)
(map? first-p)
(recur rest-p
cur-path
(concat (map (fn [[k v]] [(conj cur-path (const-fn k)) (const-fn v)])
first-p)
walked-paths-vals))
(and (sequential? first-p)
(misc/single-elem? first-p))
(let [[ffp] first-p]
(cond
(map? ffp)
(recur (into first-p rest-p)
(conj cur-path (search-fn cur-path ffp))
walked-paths-vals)
(misc/key? ffp)
{:const-paths-vals walked-paths-vals
:map {:path rest-p
:walked-path (conj cur-path (const-fn ffp))}})))))
(defn- dissoc? [a b]
(some false? (map = a b)))
(defn- interpret-mapping [{:keys [const-fn search-fn map-fn get-fn assoc-fn dissoc-fn] :as fns} src dest]
(let [{get-value-path :walked-path, dissoc-const-paths-vals :const-paths-vals, {map-src :path, dissoc-map-path :walked-path} :map}
(walk-path const-fn search-fn src)
{put-value-path :walked-path, assoc-const-paths-vals :const-paths-vals, {map-dest :path, assoc-map-path :walked-path} :map}
(walk-path const-fn search-fn dest)]
(cond
(and get-value-path put-value-path)
(concat (map (partial apply assoc-fn) assoc-const-paths-vals)
[(assoc-fn put-value-path (get-fn get-value-path))]
(when (dissoc? src dest)
[(dissoc-fn get-value-path (get-fn get-value-path))])
(map (partial apply dissoc-fn) dissoc-const-paths-vals))
(and map-src map-dest)
[(map-fn dissoc-map-path
assoc-map-path
(interpret-mapping fns map-src map-dest))])))
(defn create-transformations
"Creates mutations to transmapm data. Bidirectional"
[fns [from to] mapping]
(misc/keepcat (fn [{src from, dest to}]
(when (and src dest) (interpret-mapping fns src dest)))
mapping))
(def debug-transformations (partial create-transformations debug/fns))
(def hmap-transformations (partial create-transformations hmap/fns))
(def sql-transformations (partial create-transformations sql/fns))
(def mutate misc/mutate)
(comment
(require '[cheshire.core :as json])
(require '[clojure.java.jdbc :as db])
(def db
{:dbtype "postgresql"
:dbname "test_testbox"
:host "localhost"
:port "5439"
:user "postgres"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(defn eval-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs
(db/query db)
first
:r))
(defn test-mut-in-pg [transformations data]
(->> {:select [[(mutate transformations
(hsql/call :cast (json/generate-string data) :jsonb)) :r]]}
hsql/format
misc/hsql-subs))
(let [mapping
[{:v1 [:e]
:v2 [:a :e]}
{:v1 [:a :c [{:f 3}] :v]
:v2 [:ff]}
{:v1 [:a :d]
:v2 [:d]}]
data-source
{:a {:c [{:f 2, :v 1}
{:f 3, :v 5}
{:f 4, :v 6}]
:d 1}
:e -1}]
(clojure.pprint/pprint (debug-transformations [:v1 :v2] mapping))
(-> (test-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (eval-mut-in-pg (sql-transformations [:v1 :v2] mapping) data-source)
println)
(-> (mutate (hmap-transformations [:v1 :v2] mapping)
data-source)
println))
nil)
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2017-10-21\"\n :doc \"Text input.\" }\n ",
"end": 105,
"score": 0.999867856502533,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/main/clojure/zana/data/textin.clj | wahpenayo/zana | 2 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2017-10-21"
:doc "Text input." }
zana.data.textin
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.commons.core :as cc]
[zana.io.gz :as gz]
[zana.collections.generic :as g]
[zana.data.reflect :as r]))
;;------------------------------------------------------------------------------
;; Text Input
;;------------------------------------------------------------------------------
;; TODO: output format isn't the same as input format...
;; TODO: put public functions in data.api
;;------------------------------------------------------------------------------
(defn- child-header-key [^clojure.lang.Symbol field]
(let [c (r/type field)]
(when (r/datum-class? c)
[(keyword
(clojure.string/replace
(clojure.string/lower-case (str field)) "_" "-"))
(r/qualified-symbol c "default-header-key")])))
;;------------------------------------------------------------------------------
;; Return a definition for a function that converts a sequence of header String
;; tokens into a sequence of keys. The key for a non-Datum (non-recursive) field
;; is a Keyword. The key for a Datum field is a sequence of Keywords
;; corresponding to the field names of the nested fields.
(defn emit-default-header-key [fields]
(let [token (gensym "token")
arg (with-meta token {:tag 'String})
standardize (gensym "standardize")
child-keys (into {} (keep identity (map child-header-key fields)))
prefix (gensym "prefix")
suffix (gensym "suffix")
k (gensym "k")
child-key (gensym "child-key")]
`(let []
(require '[clojure.string])
~(if-not (empty? child-keys)
`(let
[;; Assuming field names are lower case and have "-" not "_".
~standardize (fn ~'standardize ~(with-meta [arg] {:tag 'String})
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-"))
]
(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(let [~token (~standardize ~token)
[~prefix ~suffix] (clojure.string/split ~token #"\-" 2)
~k (keyword ~prefix)
~child-key (~child-keys ~k)]
(if ~child-key
(flatten (cons ~k [(~child-key ~suffix)]))
~k))))
`(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(keyword
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-")))))))
;;------------------------------------------------------------------------------
;; return a function that takes a sequence of token strings and returns a tuple
;; tree. A tuple is a hashmap where the keys are keyword versions of the datum's
;; field names. Most values are Strings, When the field type is a descendent of
;; Datum, the value is a tuple tree for that field's Datum.
;; Note: this is equivalent to zipmap in the simple case.
(defn tuple-tree [^Iterable header ^Iterable tokens]
#_(assert (== (count header)(count tokens))
(with-out-str
(println (count header) (count tokens))
(pp/pprint header)
(println)
(pp/pprint tokens)))
(let [ih (.iterator header)
it (.iterator tokens)]
(loop [m {}]
;; hackkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
;; some files we need to process have an extra \tab at the end of some lines,
;; creating an empty extra token.
;; This ignores any mismatch between header and data token count, using the
;; shorter of the 2 (like zipmap).
(if-not (and (.hasNext ih) (.hasNext it))
m
(let [k (.next ih)
v (.next it)
m ((if (keyword? k) assoc assoc-in) m k v)]
(recur m))))))
;;------------------------------------------------------------------------------
;; TODO: eliminate the dependency on zana.data.textin
;; at least move to zana.api
(defn- default-parser [field]
(let [hint (:tag (meta field))
c (r/type field)
k (keyword field)
value (gensym "value")
tuple (gensym "tuple")
arg (with-meta tuple {:tag 'java.util.Map})
archetype (gensym "archetype")]
(if (r/datum-class? c)
`(fn ~'parse-datum ~(with-meta `[~arg ~archetype] {:tag c})
(let [^String ~value (~k ~tuple)]
(when ~value
(~(r/qualified-symbol c "parse-tuple")
~value ~archetype))))
(case hint
;; map empty Strings, "nil", etc, to nil == missing
;; TODO: support general codes for missing
String `(fn ~'parse-string ~(with-meta `[~arg ~archetype] {:tag 'String})
(let [~(with-meta value {:tag 'String}) (~k ~tuple)]
(when ~value
(case (.toLowerCase ~value)
("" "nil" "null") nil
(~archetype ~value)))))
;; missing not possible for boolean, char, byte, short, int, and long
boolean `(fn ~'parse-boolean ~(with-meta `[~arg ~archetype] {:tag 'Boolean})
(let [^String ~value (~k ~tuple)]
(if ~value (Boolean/parseBoolean ~value) false)))
char `(fn ~'parse-char ~(with-meta `[~arg ~archetype] {:tag 'Character})
(let [^String ~value (~k ~tuple)]
(when ~value
(assert (== 1 (count ~value)) (pr-str ~value))
(first ~value))))
byte `(fn ~'parse-byte ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Byte/parseByte ~value))))
short `(fn ~'parse-short ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Short/parseShort ~value))))
int `(fn ~'parse-int ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Integer/parseInt ~value))))
long `(fn ~'parse-long ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(Long/parseLong ~value)))
;; missing == NaN, map "NaN" and empty strings to NaN
float `(fn ~'parse-float ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(double (if-not (empty? ~value)
(Float/parseFloat ~value)
Float/NaN))))
double `(fn ~'parse-double ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(if-not (empty? ~value)
(Double/parseDouble ~value)
Double/NaN)))
java.time.LocalDate `(fn ~'parse-local-date
~(with-meta `[~arg ~archetype] {:tag java.time.LocalDate})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
(~archetype
(java.time.LocalDate/parse ~value)))))
java.time.LocalDateTime `(fn ~'parse-local-date-time
~(with-meta `[~arg ~archetype]
{:tag java.time.LocalDateTime})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
;; don't archetype since too many values
(java.time.LocalDateTime/parse ~value))))
;; else
nil))))
;;------------------------------------------------------------------------------
(defn- parser [field-spec]
(if (sequential? field-spec)
(do
(assert (= 2 (count field-spec)))
field-spec)
[field-spec (default-parser field-spec)]))
;;------------------------------------------------------------------------------
(defn- field-to-parser [field-specs] (into {} (map parser field-specs)))
;;------------------------------------------------------------------------------
;; assume the tuple is a map from (keyword field) to String
;; TODO: column header to field mapping
(defn tuple-parser [classname field-specs]
(let [fields (mapv r/extract-field field-specs)
field-parser (field-to-parser field-specs)
throwable (gensym "throwable")
tuple (gensym "tuple")
archetype (gensym "archetype")]
`(defn ~'parse-tuple
~(print-str
"Constructs an instance of"
classname
"from a tuple-tree, a nested map whose keys are keyword versions"
"of the fields, where the nesting following the nesting of"
"of datum-valued fields,")
~(with-meta `[~(with-meta tuple
{:tag 'java.util.Map})
~archetype]
{:tag (r/munge classname)})
(try
(assert ~tuple "no tuple to parse.")
(assert ~archetype "no de-duping function.")
(~(r/constructor classname)
~@(mapv (fn generate-field-parser [field]
(let [prsr (field-parser field)]
(if prsr
`(~prsr ~tuple ~archetype)
`(~archetype (~(keyword field) ~tuple)))))
fields))
(catch Throwable ~throwable
(binding [*out* *err*]
(println ~tuple)
(throw ~throwable)))))))
;;------------------------------------------------------------------------------
;; only thing here specific to the particular data is the reference to
;; parse-tuple
;; Should this be a global function rather than a datum specific one emitted
;; by macro expansion?
(defn tsv-file-reader [classname field-specs]
(let [;; TODO: generalize File arg
f (gensym "f")
sep (gensym "sep")
n (gensym "n")
hk (gensym "hk")
r (gensym "r")
lines (gensym "lines")
splitter (with-meta (gensym "splitter")
{:tag 'com.google.common.base.Splitter})
header (gensym "header")
parse (gensym "parse")
line (gensym "line")
tokens (gensym "tokens")
parse-tuple (gensym "parse-tuple")
tuple (gensym "tuple")
archetype (gensym "archetype")
fields (mapv r/extract-field field-specs)]
`((require '[clojure.string] '[zana.api])
~(emit-default-header-key fields)
~(tuple-parser classname field-specs)
(defn ~(with-meta 'read-tsv-file {:deprecated "2016-09-06"})
~(str "Read instances of <code>" classname
"</code> from the file <code>" f
"</code>, assuming the field values separated by <code>" sep
"</code> (which defaults to <code>\"\\t\"</code>.<br>"
"This implements a complicated and restrictive strategy for "
"dealing with nested datum classes, and should be replaced by "
"something simpler and more flexible.")
(~(with-meta `[~f ;; File, URL, etc.
~(with-meta sep {:tag 'java.util.regex.Pattern})
~(with-meta hk {:tag 'clojure.lang.IFn})
~(with-meta n {:tag Long/TYPE})]
{:tag java.util.Collection})
(with-open [~r (zana.api/reader ~f)]
(let [~archetype (zana.api/archetyper)
~lines (line-seq ~r)
; ~header (mapv ~hk (clojure.string/split (first ~lines) ~sep -1))
; ~parse (fn ~'parse-line [~line]
; (let [~tokens (clojure.string/split ~line ~sep -1)
; ~tuple (tuple-tree ~header ~tokens)]
; (try
; (~'parse-tuple ~tuple ~archetype)
; (catch Throwable t#
; (println "failed to parse:")
; (pp/pprint ~tuple)
; (.printStackTrace t#)
; (throw t#)))))
~splitter (com.google.common.base.Splitter/on ~sep)
~header (mapv ~hk (.split ~splitter (first ~lines)))
~parse (fn ~'parse-line [~line]
(let [~tokens (.split ~splitter ~line)
~tuple (tuple-tree ~header ~tokens)]
(try
(~'parse-tuple ~tuple ~archetype)
(catch Throwable t#
(println "failed to parse:")
(pp/pprint ~tuple)
(.printStackTrace t#)
(throw t#)))))]
;; TODO: a chunked concurrent version of this
(zana.api/map ~parse (take ~n (rest ~lines))))))
(~(with-meta `[~f ~sep ~hk] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~hk Long/MAX_VALUE))
(~(with-meta `[~f ~sep] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~'default-header-key))
(~(with-meta `[~f] {:tag 'java.util.Collection})
(~'read-tsv-file ~f #"\t"))))))
;;------------------------------------------------------------------------------
| 4644 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2017-10-21"
:doc "Text input." }
zana.data.textin
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.commons.core :as cc]
[zana.io.gz :as gz]
[zana.collections.generic :as g]
[zana.data.reflect :as r]))
;;------------------------------------------------------------------------------
;; Text Input
;;------------------------------------------------------------------------------
;; TODO: output format isn't the same as input format...
;; TODO: put public functions in data.api
;;------------------------------------------------------------------------------
(defn- child-header-key [^clojure.lang.Symbol field]
(let [c (r/type field)]
(when (r/datum-class? c)
[(keyword
(clojure.string/replace
(clojure.string/lower-case (str field)) "_" "-"))
(r/qualified-symbol c "default-header-key")])))
;;------------------------------------------------------------------------------
;; Return a definition for a function that converts a sequence of header String
;; tokens into a sequence of keys. The key for a non-Datum (non-recursive) field
;; is a Keyword. The key for a Datum field is a sequence of Keywords
;; corresponding to the field names of the nested fields.
(defn emit-default-header-key [fields]
(let [token (gensym "token")
arg (with-meta token {:tag 'String})
standardize (gensym "standardize")
child-keys (into {} (keep identity (map child-header-key fields)))
prefix (gensym "prefix")
suffix (gensym "suffix")
k (gensym "k")
child-key (gensym "child-key")]
`(let []
(require '[clojure.string])
~(if-not (empty? child-keys)
`(let
[;; Assuming field names are lower case and have "-" not "_".
~standardize (fn ~'standardize ~(with-meta [arg] {:tag 'String})
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-"))
]
(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(let [~token (~standardize ~token)
[~prefix ~suffix] (clojure.string/split ~token #"\-" 2)
~k (keyword ~prefix)
~child-key (~child-keys ~k)]
(if ~child-key
(flatten (cons ~k [(~child-key ~suffix)]))
~k))))
`(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(keyword
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-")))))))
;;------------------------------------------------------------------------------
;; return a function that takes a sequence of token strings and returns a tuple
;; tree. A tuple is a hashmap where the keys are keyword versions of the datum's
;; field names. Most values are Strings, When the field type is a descendent of
;; Datum, the value is a tuple tree for that field's Datum.
;; Note: this is equivalent to zipmap in the simple case.
(defn tuple-tree [^Iterable header ^Iterable tokens]
#_(assert (== (count header)(count tokens))
(with-out-str
(println (count header) (count tokens))
(pp/pprint header)
(println)
(pp/pprint tokens)))
(let [ih (.iterator header)
it (.iterator tokens)]
(loop [m {}]
;; hackkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
;; some files we need to process have an extra \tab at the end of some lines,
;; creating an empty extra token.
;; This ignores any mismatch between header and data token count, using the
;; shorter of the 2 (like zipmap).
(if-not (and (.hasNext ih) (.hasNext it))
m
(let [k (.next ih)
v (.next it)
m ((if (keyword? k) assoc assoc-in) m k v)]
(recur m))))))
;;------------------------------------------------------------------------------
;; TODO: eliminate the dependency on zana.data.textin
;; at least move to zana.api
(defn- default-parser [field]
(let [hint (:tag (meta field))
c (r/type field)
k (keyword field)
value (gensym "value")
tuple (gensym "tuple")
arg (with-meta tuple {:tag 'java.util.Map})
archetype (gensym "archetype")]
(if (r/datum-class? c)
`(fn ~'parse-datum ~(with-meta `[~arg ~archetype] {:tag c})
(let [^String ~value (~k ~tuple)]
(when ~value
(~(r/qualified-symbol c "parse-tuple")
~value ~archetype))))
(case hint
;; map empty Strings, "nil", etc, to nil == missing
;; TODO: support general codes for missing
String `(fn ~'parse-string ~(with-meta `[~arg ~archetype] {:tag 'String})
(let [~(with-meta value {:tag 'String}) (~k ~tuple)]
(when ~value
(case (.toLowerCase ~value)
("" "nil" "null") nil
(~archetype ~value)))))
;; missing not possible for boolean, char, byte, short, int, and long
boolean `(fn ~'parse-boolean ~(with-meta `[~arg ~archetype] {:tag 'Boolean})
(let [^String ~value (~k ~tuple)]
(if ~value (Boolean/parseBoolean ~value) false)))
char `(fn ~'parse-char ~(with-meta `[~arg ~archetype] {:tag 'Character})
(let [^String ~value (~k ~tuple)]
(when ~value
(assert (== 1 (count ~value)) (pr-str ~value))
(first ~value))))
byte `(fn ~'parse-byte ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Byte/parseByte ~value))))
short `(fn ~'parse-short ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Short/parseShort ~value))))
int `(fn ~'parse-int ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Integer/parseInt ~value))))
long `(fn ~'parse-long ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(Long/parseLong ~value)))
;; missing == NaN, map "NaN" and empty strings to NaN
float `(fn ~'parse-float ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(double (if-not (empty? ~value)
(Float/parseFloat ~value)
Float/NaN))))
double `(fn ~'parse-double ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(if-not (empty? ~value)
(Double/parseDouble ~value)
Double/NaN)))
java.time.LocalDate `(fn ~'parse-local-date
~(with-meta `[~arg ~archetype] {:tag java.time.LocalDate})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
(~archetype
(java.time.LocalDate/parse ~value)))))
java.time.LocalDateTime `(fn ~'parse-local-date-time
~(with-meta `[~arg ~archetype]
{:tag java.time.LocalDateTime})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
;; don't archetype since too many values
(java.time.LocalDateTime/parse ~value))))
;; else
nil))))
;;------------------------------------------------------------------------------
(defn- parser [field-spec]
(if (sequential? field-spec)
(do
(assert (= 2 (count field-spec)))
field-spec)
[field-spec (default-parser field-spec)]))
;;------------------------------------------------------------------------------
(defn- field-to-parser [field-specs] (into {} (map parser field-specs)))
;;------------------------------------------------------------------------------
;; assume the tuple is a map from (keyword field) to String
;; TODO: column header to field mapping
(defn tuple-parser [classname field-specs]
(let [fields (mapv r/extract-field field-specs)
field-parser (field-to-parser field-specs)
throwable (gensym "throwable")
tuple (gensym "tuple")
archetype (gensym "archetype")]
`(defn ~'parse-tuple
~(print-str
"Constructs an instance of"
classname
"from a tuple-tree, a nested map whose keys are keyword versions"
"of the fields, where the nesting following the nesting of"
"of datum-valued fields,")
~(with-meta `[~(with-meta tuple
{:tag 'java.util.Map})
~archetype]
{:tag (r/munge classname)})
(try
(assert ~tuple "no tuple to parse.")
(assert ~archetype "no de-duping function.")
(~(r/constructor classname)
~@(mapv (fn generate-field-parser [field]
(let [prsr (field-parser field)]
(if prsr
`(~prsr ~tuple ~archetype)
`(~archetype (~(keyword field) ~tuple)))))
fields))
(catch Throwable ~throwable
(binding [*out* *err*]
(println ~tuple)
(throw ~throwable)))))))
;;------------------------------------------------------------------------------
;; only thing here specific to the particular data is the reference to
;; parse-tuple
;; Should this be a global function rather than a datum specific one emitted
;; by macro expansion?
(defn tsv-file-reader [classname field-specs]
(let [;; TODO: generalize File arg
f (gensym "f")
sep (gensym "sep")
n (gensym "n")
hk (gensym "hk")
r (gensym "r")
lines (gensym "lines")
splitter (with-meta (gensym "splitter")
{:tag 'com.google.common.base.Splitter})
header (gensym "header")
parse (gensym "parse")
line (gensym "line")
tokens (gensym "tokens")
parse-tuple (gensym "parse-tuple")
tuple (gensym "tuple")
archetype (gensym "archetype")
fields (mapv r/extract-field field-specs)]
`((require '[clojure.string] '[zana.api])
~(emit-default-header-key fields)
~(tuple-parser classname field-specs)
(defn ~(with-meta 'read-tsv-file {:deprecated "2016-09-06"})
~(str "Read instances of <code>" classname
"</code> from the file <code>" f
"</code>, assuming the field values separated by <code>" sep
"</code> (which defaults to <code>\"\\t\"</code>.<br>"
"This implements a complicated and restrictive strategy for "
"dealing with nested datum classes, and should be replaced by "
"something simpler and more flexible.")
(~(with-meta `[~f ;; File, URL, etc.
~(with-meta sep {:tag 'java.util.regex.Pattern})
~(with-meta hk {:tag 'clojure.lang.IFn})
~(with-meta n {:tag Long/TYPE})]
{:tag java.util.Collection})
(with-open [~r (zana.api/reader ~f)]
(let [~archetype (zana.api/archetyper)
~lines (line-seq ~r)
; ~header (mapv ~hk (clojure.string/split (first ~lines) ~sep -1))
; ~parse (fn ~'parse-line [~line]
; (let [~tokens (clojure.string/split ~line ~sep -1)
; ~tuple (tuple-tree ~header ~tokens)]
; (try
; (~'parse-tuple ~tuple ~archetype)
; (catch Throwable t#
; (println "failed to parse:")
; (pp/pprint ~tuple)
; (.printStackTrace t#)
; (throw t#)))))
~splitter (com.google.common.base.Splitter/on ~sep)
~header (mapv ~hk (.split ~splitter (first ~lines)))
~parse (fn ~'parse-line [~line]
(let [~tokens (.split ~splitter ~line)
~tuple (tuple-tree ~header ~tokens)]
(try
(~'parse-tuple ~tuple ~archetype)
(catch Throwable t#
(println "failed to parse:")
(pp/pprint ~tuple)
(.printStackTrace t#)
(throw t#)))))]
;; TODO: a chunked concurrent version of this
(zana.api/map ~parse (take ~n (rest ~lines))))))
(~(with-meta `[~f ~sep ~hk] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~hk Long/MAX_VALUE))
(~(with-meta `[~f ~sep] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~'default-header-key))
(~(with-meta `[~f] {:tag 'java.util.Collection})
(~'read-tsv-file ~f #"\t"))))))
;;------------------------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2017-10-21"
:doc "Text input." }
zana.data.textin
(:require [clojure.string :as s]
[clojure.pprint :as pp]
[zana.commons.core :as cc]
[zana.io.gz :as gz]
[zana.collections.generic :as g]
[zana.data.reflect :as r]))
;;------------------------------------------------------------------------------
;; Text Input
;;------------------------------------------------------------------------------
;; TODO: output format isn't the same as input format...
;; TODO: put public functions in data.api
;;------------------------------------------------------------------------------
(defn- child-header-key [^clojure.lang.Symbol field]
(let [c (r/type field)]
(when (r/datum-class? c)
[(keyword
(clojure.string/replace
(clojure.string/lower-case (str field)) "_" "-"))
(r/qualified-symbol c "default-header-key")])))
;;------------------------------------------------------------------------------
;; Return a definition for a function that converts a sequence of header String
;; tokens into a sequence of keys. The key for a non-Datum (non-recursive) field
;; is a Keyword. The key for a Datum field is a sequence of Keywords
;; corresponding to the field names of the nested fields.
(defn emit-default-header-key [fields]
(let [token (gensym "token")
arg (with-meta token {:tag 'String})
standardize (gensym "standardize")
child-keys (into {} (keep identity (map child-header-key fields)))
prefix (gensym "prefix")
suffix (gensym "suffix")
k (gensym "k")
child-key (gensym "child-key")]
`(let []
(require '[clojure.string])
~(if-not (empty? child-keys)
`(let
[;; Assuming field names are lower case and have "-" not "_".
~standardize (fn ~'standardize ~(with-meta [arg] {:tag 'String})
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-"))
]
(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(let [~token (~standardize ~token)
[~prefix ~suffix] (clojure.string/split ~token #"\-" 2)
~k (keyword ~prefix)
~child-key (~child-keys ~k)]
(if ~child-key
(flatten (cons ~k [(~child-key ~suffix)]))
~k))))
`(defn ~(with-meta 'default-header-key {:no-doc true})
[~arg]
(keyword
(.replaceAll
(.replaceAll
^String (clojure.string/lower-case ~token)
"[^\\-\\w]+" "")
"[\\s_]+" "-")))))))
;;------------------------------------------------------------------------------
;; return a function that takes a sequence of token strings and returns a tuple
;; tree. A tuple is a hashmap where the keys are keyword versions of the datum's
;; field names. Most values are Strings, When the field type is a descendent of
;; Datum, the value is a tuple tree for that field's Datum.
;; Note: this is equivalent to zipmap in the simple case.
(defn tuple-tree [^Iterable header ^Iterable tokens]
#_(assert (== (count header)(count tokens))
(with-out-str
(println (count header) (count tokens))
(pp/pprint header)
(println)
(pp/pprint tokens)))
(let [ih (.iterator header)
it (.iterator tokens)]
(loop [m {}]
;; hackkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
;; some files we need to process have an extra \tab at the end of some lines,
;; creating an empty extra token.
;; This ignores any mismatch between header and data token count, using the
;; shorter of the 2 (like zipmap).
(if-not (and (.hasNext ih) (.hasNext it))
m
(let [k (.next ih)
v (.next it)
m ((if (keyword? k) assoc assoc-in) m k v)]
(recur m))))))
;;------------------------------------------------------------------------------
;; TODO: eliminate the dependency on zana.data.textin
;; at least move to zana.api
(defn- default-parser [field]
(let [hint (:tag (meta field))
c (r/type field)
k (keyword field)
value (gensym "value")
tuple (gensym "tuple")
arg (with-meta tuple {:tag 'java.util.Map})
archetype (gensym "archetype")]
(if (r/datum-class? c)
`(fn ~'parse-datum ~(with-meta `[~arg ~archetype] {:tag c})
(let [^String ~value (~k ~tuple)]
(when ~value
(~(r/qualified-symbol c "parse-tuple")
~value ~archetype))))
(case hint
;; map empty Strings, "nil", etc, to nil == missing
;; TODO: support general codes for missing
String `(fn ~'parse-string ~(with-meta `[~arg ~archetype] {:tag 'String})
(let [~(with-meta value {:tag 'String}) (~k ~tuple)]
(when ~value
(case (.toLowerCase ~value)
("" "nil" "null") nil
(~archetype ~value)))))
;; missing not possible for boolean, char, byte, short, int, and long
boolean `(fn ~'parse-boolean ~(with-meta `[~arg ~archetype] {:tag 'Boolean})
(let [^String ~value (~k ~tuple)]
(if ~value (Boolean/parseBoolean ~value) false)))
char `(fn ~'parse-char ~(with-meta `[~arg ~archetype] {:tag 'Character})
(let [^String ~value (~k ~tuple)]
(when ~value
(assert (== 1 (count ~value)) (pr-str ~value))
(first ~value))))
byte `(fn ~'parse-byte ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Byte/parseByte ~value))))
short `(fn ~'parse-short ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Short/parseShort ~value))))
int `(fn ~'parse-int ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(long (Integer/parseInt ~value))))
long `(fn ~'parse-long ~(with-meta `[~arg ~archetype] {:tag long})
(let [^String ~value (~k ~tuple)]
(Long/parseLong ~value)))
;; missing == NaN, map "NaN" and empty strings to NaN
float `(fn ~'parse-float ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(double (if-not (empty? ~value)
(Float/parseFloat ~value)
Float/NaN))))
double `(fn ~'parse-double ~(with-meta `[~arg ~archetype] {:tag double})
(let [^String ~value (~k ~tuple)]
(if-not (empty? ~value)
(Double/parseDouble ~value)
Double/NaN)))
java.time.LocalDate `(fn ~'parse-local-date
~(with-meta `[~arg ~archetype] {:tag java.time.LocalDate})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
(~archetype
(java.time.LocalDate/parse ~value)))))
java.time.LocalDateTime `(fn ~'parse-local-date-time
~(with-meta `[~arg ~archetype]
{:tag java.time.LocalDateTime})
(let [^String ~value (~k ~tuple)]
(when-not (empty? ~value)
;; don't archetype since too many values
(java.time.LocalDateTime/parse ~value))))
;; else
nil))))
;;------------------------------------------------------------------------------
(defn- parser [field-spec]
(if (sequential? field-spec)
(do
(assert (= 2 (count field-spec)))
field-spec)
[field-spec (default-parser field-spec)]))
;;------------------------------------------------------------------------------
(defn- field-to-parser [field-specs] (into {} (map parser field-specs)))
;;------------------------------------------------------------------------------
;; assume the tuple is a map from (keyword field) to String
;; TODO: column header to field mapping
(defn tuple-parser [classname field-specs]
(let [fields (mapv r/extract-field field-specs)
field-parser (field-to-parser field-specs)
throwable (gensym "throwable")
tuple (gensym "tuple")
archetype (gensym "archetype")]
`(defn ~'parse-tuple
~(print-str
"Constructs an instance of"
classname
"from a tuple-tree, a nested map whose keys are keyword versions"
"of the fields, where the nesting following the nesting of"
"of datum-valued fields,")
~(with-meta `[~(with-meta tuple
{:tag 'java.util.Map})
~archetype]
{:tag (r/munge classname)})
(try
(assert ~tuple "no tuple to parse.")
(assert ~archetype "no de-duping function.")
(~(r/constructor classname)
~@(mapv (fn generate-field-parser [field]
(let [prsr (field-parser field)]
(if prsr
`(~prsr ~tuple ~archetype)
`(~archetype (~(keyword field) ~tuple)))))
fields))
(catch Throwable ~throwable
(binding [*out* *err*]
(println ~tuple)
(throw ~throwable)))))))
;;------------------------------------------------------------------------------
;; only thing here specific to the particular data is the reference to
;; parse-tuple
;; Should this be a global function rather than a datum specific one emitted
;; by macro expansion?
(defn tsv-file-reader [classname field-specs]
(let [;; TODO: generalize File arg
f (gensym "f")
sep (gensym "sep")
n (gensym "n")
hk (gensym "hk")
r (gensym "r")
lines (gensym "lines")
splitter (with-meta (gensym "splitter")
{:tag 'com.google.common.base.Splitter})
header (gensym "header")
parse (gensym "parse")
line (gensym "line")
tokens (gensym "tokens")
parse-tuple (gensym "parse-tuple")
tuple (gensym "tuple")
archetype (gensym "archetype")
fields (mapv r/extract-field field-specs)]
`((require '[clojure.string] '[zana.api])
~(emit-default-header-key fields)
~(tuple-parser classname field-specs)
(defn ~(with-meta 'read-tsv-file {:deprecated "2016-09-06"})
~(str "Read instances of <code>" classname
"</code> from the file <code>" f
"</code>, assuming the field values separated by <code>" sep
"</code> (which defaults to <code>\"\\t\"</code>.<br>"
"This implements a complicated and restrictive strategy for "
"dealing with nested datum classes, and should be replaced by "
"something simpler and more flexible.")
(~(with-meta `[~f ;; File, URL, etc.
~(with-meta sep {:tag 'java.util.regex.Pattern})
~(with-meta hk {:tag 'clojure.lang.IFn})
~(with-meta n {:tag Long/TYPE})]
{:tag java.util.Collection})
(with-open [~r (zana.api/reader ~f)]
(let [~archetype (zana.api/archetyper)
~lines (line-seq ~r)
; ~header (mapv ~hk (clojure.string/split (first ~lines) ~sep -1))
; ~parse (fn ~'parse-line [~line]
; (let [~tokens (clojure.string/split ~line ~sep -1)
; ~tuple (tuple-tree ~header ~tokens)]
; (try
; (~'parse-tuple ~tuple ~archetype)
; (catch Throwable t#
; (println "failed to parse:")
; (pp/pprint ~tuple)
; (.printStackTrace t#)
; (throw t#)))))
~splitter (com.google.common.base.Splitter/on ~sep)
~header (mapv ~hk (.split ~splitter (first ~lines)))
~parse (fn ~'parse-line [~line]
(let [~tokens (.split ~splitter ~line)
~tuple (tuple-tree ~header ~tokens)]
(try
(~'parse-tuple ~tuple ~archetype)
(catch Throwable t#
(println "failed to parse:")
(pp/pprint ~tuple)
(.printStackTrace t#)
(throw t#)))))]
;; TODO: a chunked concurrent version of this
(zana.api/map ~parse (take ~n (rest ~lines))))))
(~(with-meta `[~f ~sep ~hk] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~hk Long/MAX_VALUE))
(~(with-meta `[~f ~sep] {:tag 'java.util.Collection})
(~'read-tsv-file ~f ~sep ~'default-header-key))
(~(with-meta `[~f] {:tag 'java.util.Collection})
(~'read-tsv-file ~f #"\t"))))))
;;------------------------------------------------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.