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": "from here](http://mpqa.cs.pitt.edu/)\"\n {:author \"Mark Woodhall\"}\n (:require [clojure.java.io :as io]\n ",
"end": 141,
"score": 0.9998505115509033,
"start": 128,
"tag": "NAME",
"value": "Mark Woodhall"
}
] | src/clj_subjectivity/core.clj | markwoodhall/clj-subjectivity | 1 | (ns clj-subjectivity.core
"A Clojure wrapper around a subjectivity lexicon [from here](http://mpqa.cs.pitt.edu/)"
{:author "Mark Woodhall"}
(:require [clojure.java.io :as io]
[clojure.string :refer [split lower-case]]))
(def subjectivity-clues
(memoize #(read-string
(slurp (io/resource "subjectivityclues.edn")))))
(def negations
(memoize #(read-string
(slurp (io/resource "negations.edn")))))
(defn- word-sentiment
([word]
(word-sentiment word false))
([word negate?]
(let [{:keys [priorpolarity type]} (first (filter #(= (:word1 %) word) (subjectivity-clues)))
score (if-not (nil? priorpolarity)
(if (= type :strongsubj)
1
0.5)
0)]
{:sentiment (if (and (= priorpolarity :positive)
negate?)
:negative
priorpolarity)
:score score
:word word})))
(def ^:private word-sentiment-memo
(memoize word-sentiment))
(defn- words-sentiment
[words]
(let [last-sentiment (atom {:word ""})]
(for [word words]
(let [negate? (some #{(lower-case (:word @last-sentiment))} (negations))
sentiment (word-sentiment-memo word negate?)
sentiment (if (= (:sentiment @last-sentiment) (:sentiment sentiment))
(update-in sentiment [:score] + 0.5)
sentiment)]
(reset! last-sentiment sentiment)
sentiment))))
(defn sentiment
"Given a collection of words or a function returning a collection of words will
return a map representing the overall sentiment for the words."
[words-or-func]
(let [words (if (fn? words-or-func)
(words-or-func)
words-or-func)
words (if (sequential? words)
words
(split words #"\ "))
sentiments (words-sentiment words)
pos-sents (filter #(= (:sentiment %) :positive) sentiments)
neg-sents (filter #(= (:sentiment %) :negative) sentiments)
neu-sents (filter #(= (:sentiment %) :neutral) sentiments)
pos (reduce + (map #(:score %) pos-sents))
neg (reduce + (map #(:score %) neg-sents))
neu (reduce + (map #(:score %) neu-sents))
pos-words (map #(:word %) pos-sents)
neu-words (map #(:word %) neu-sents)
neg-words (map #(:word %) neg-sents)
p-frequent (map key (take 10 (reverse (sort-by val (frequencies pos-words)))))
p-rare (map key (take 10 (sort-by val (frequencies pos-words))))
n-frequent (map key (take 10 (reverse (sort-by val (frequencies neg-words)))))
n-rare (map key (take 10 (sort-by val (frequencies neg-words))))
neu-frequent (map key (take 10 (reverse (sort-by val (frequencies neu-words)))))
neu-rare (map key (take 10 (sort-by val (frequencies neu-words))))]
{:positive pos
:negative neg
:neutral neu
:top-positive (distinct p-frequent)
:top-negative (distinct n-frequent)
:top-neutral (distinct neu-frequent)
:bottom-positive (distinct p-rare)
:bottom-negative (distinct n-rare)
:bottom-neutral (distinct neu-rare)
:difference (- pos neg)}))
| 108846 | (ns clj-subjectivity.core
"A Clojure wrapper around a subjectivity lexicon [from here](http://mpqa.cs.pitt.edu/)"
{:author "<NAME>"}
(:require [clojure.java.io :as io]
[clojure.string :refer [split lower-case]]))
(def subjectivity-clues
(memoize #(read-string
(slurp (io/resource "subjectivityclues.edn")))))
(def negations
(memoize #(read-string
(slurp (io/resource "negations.edn")))))
(defn- word-sentiment
([word]
(word-sentiment word false))
([word negate?]
(let [{:keys [priorpolarity type]} (first (filter #(= (:word1 %) word) (subjectivity-clues)))
score (if-not (nil? priorpolarity)
(if (= type :strongsubj)
1
0.5)
0)]
{:sentiment (if (and (= priorpolarity :positive)
negate?)
:negative
priorpolarity)
:score score
:word word})))
(def ^:private word-sentiment-memo
(memoize word-sentiment))
(defn- words-sentiment
[words]
(let [last-sentiment (atom {:word ""})]
(for [word words]
(let [negate? (some #{(lower-case (:word @last-sentiment))} (negations))
sentiment (word-sentiment-memo word negate?)
sentiment (if (= (:sentiment @last-sentiment) (:sentiment sentiment))
(update-in sentiment [:score] + 0.5)
sentiment)]
(reset! last-sentiment sentiment)
sentiment))))
(defn sentiment
"Given a collection of words or a function returning a collection of words will
return a map representing the overall sentiment for the words."
[words-or-func]
(let [words (if (fn? words-or-func)
(words-or-func)
words-or-func)
words (if (sequential? words)
words
(split words #"\ "))
sentiments (words-sentiment words)
pos-sents (filter #(= (:sentiment %) :positive) sentiments)
neg-sents (filter #(= (:sentiment %) :negative) sentiments)
neu-sents (filter #(= (:sentiment %) :neutral) sentiments)
pos (reduce + (map #(:score %) pos-sents))
neg (reduce + (map #(:score %) neg-sents))
neu (reduce + (map #(:score %) neu-sents))
pos-words (map #(:word %) pos-sents)
neu-words (map #(:word %) neu-sents)
neg-words (map #(:word %) neg-sents)
p-frequent (map key (take 10 (reverse (sort-by val (frequencies pos-words)))))
p-rare (map key (take 10 (sort-by val (frequencies pos-words))))
n-frequent (map key (take 10 (reverse (sort-by val (frequencies neg-words)))))
n-rare (map key (take 10 (sort-by val (frequencies neg-words))))
neu-frequent (map key (take 10 (reverse (sort-by val (frequencies neu-words)))))
neu-rare (map key (take 10 (sort-by val (frequencies neu-words))))]
{:positive pos
:negative neg
:neutral neu
:top-positive (distinct p-frequent)
:top-negative (distinct n-frequent)
:top-neutral (distinct neu-frequent)
:bottom-positive (distinct p-rare)
:bottom-negative (distinct n-rare)
:bottom-neutral (distinct neu-rare)
:difference (- pos neg)}))
| true | (ns clj-subjectivity.core
"A Clojure wrapper around a subjectivity lexicon [from here](http://mpqa.cs.pitt.edu/)"
{:author "PI:NAME:<NAME>END_PI"}
(:require [clojure.java.io :as io]
[clojure.string :refer [split lower-case]]))
(def subjectivity-clues
(memoize #(read-string
(slurp (io/resource "subjectivityclues.edn")))))
(def negations
(memoize #(read-string
(slurp (io/resource "negations.edn")))))
(defn- word-sentiment
([word]
(word-sentiment word false))
([word negate?]
(let [{:keys [priorpolarity type]} (first (filter #(= (:word1 %) word) (subjectivity-clues)))
score (if-not (nil? priorpolarity)
(if (= type :strongsubj)
1
0.5)
0)]
{:sentiment (if (and (= priorpolarity :positive)
negate?)
:negative
priorpolarity)
:score score
:word word})))
(def ^:private word-sentiment-memo
(memoize word-sentiment))
(defn- words-sentiment
[words]
(let [last-sentiment (atom {:word ""})]
(for [word words]
(let [negate? (some #{(lower-case (:word @last-sentiment))} (negations))
sentiment (word-sentiment-memo word negate?)
sentiment (if (= (:sentiment @last-sentiment) (:sentiment sentiment))
(update-in sentiment [:score] + 0.5)
sentiment)]
(reset! last-sentiment sentiment)
sentiment))))
(defn sentiment
"Given a collection of words or a function returning a collection of words will
return a map representing the overall sentiment for the words."
[words-or-func]
(let [words (if (fn? words-or-func)
(words-or-func)
words-or-func)
words (if (sequential? words)
words
(split words #"\ "))
sentiments (words-sentiment words)
pos-sents (filter #(= (:sentiment %) :positive) sentiments)
neg-sents (filter #(= (:sentiment %) :negative) sentiments)
neu-sents (filter #(= (:sentiment %) :neutral) sentiments)
pos (reduce + (map #(:score %) pos-sents))
neg (reduce + (map #(:score %) neg-sents))
neu (reduce + (map #(:score %) neu-sents))
pos-words (map #(:word %) pos-sents)
neu-words (map #(:word %) neu-sents)
neg-words (map #(:word %) neg-sents)
p-frequent (map key (take 10 (reverse (sort-by val (frequencies pos-words)))))
p-rare (map key (take 10 (sort-by val (frequencies pos-words))))
n-frequent (map key (take 10 (reverse (sort-by val (frequencies neg-words)))))
n-rare (map key (take 10 (sort-by val (frequencies neg-words))))
neu-frequent (map key (take 10 (reverse (sort-by val (frequencies neu-words)))))
neu-rare (map key (take 10 (sort-by val (frequencies neu-words))))]
{:positive pos
:negative neg
:neutral neu
:top-positive (distinct p-frequent)
:top-negative (distinct n-frequent)
:top-neutral (distinct neu-frequent)
:bottom-positive (distinct p-rare)
:bottom-negative (distinct n-rare)
:bottom-neutral (distinct neu-rare)
:difference (- pos neg)}))
|
[
{
"context": "ating dates\n and times.\"\n :author \"James Cunningham\"}\n simulator.time\n (:use [simulator.utils :only",
"end": 120,
"score": 0.9998659491539001,
"start": 104,
"tag": "NAME",
"value": "James Cunningham"
}
] | src/patient-simulator/src/simulator/time.clj | connectedhealthcities/anytown | 0 | (ns ^{:doc "Library for defining, querying and manipulating dates
and times."
:author "James Cunningham"}
simulator.time
(:use [simulator.utils :only (rand-normal)])
(import [java.util Date Calendar]
[java.text SimpleDateFormat]))
;;; --- conversion functions ---
(defn date-in-ms
"Get the time in milliseconds between epoch and given date.
If no date is given default is now."
([] (.getTime (.getTime (Calendar/getInstance))))
([date] (.getTimeInMillis (doto (Calendar/getInstance) (.setTime date)))))
(defn years-to-ms
"Naive conversion of years to milliseconds"
[years] (* years 365 24 60 60 1000))
(defn months-to-ms
"Naive conversion of months to milliseconds"
[months] (* months 30 24 60 60 1000))
(defn weeks-to-ms
"Naive conversion of weeks to milliseconds"
[weeks] (* weeks 7 24 60 60 1000))
(defn days-to-ms
"Naive conversion of days to milliseconds"
[days] (* days 24 60 60 1000))
(defn hours-to-ms
"Naive conversion of hours to milliseconds"
[hours] (* hours 60 60 1000))
(defn year-in-ms
"Converts a calendar year to milliseconds since epoch."
[year] (.getTimeInMillis (doto (Calendar/getInstance)
(.setTimeInMillis 0)
(.set Calendar/YEAR year))))
;;; --- utility functions ---
(defn get-year
"Returns a string representing the year of the given date in yyyy format."
[date]
(.format (SimpleDateFormat. "yyyy") date))
(defn after-now?
"Returns true if the given date is in the future."
[date]
(.after date (Date.)))
(defn add-time-to-date
"Adds a time specified in milliseconds to the given java.util.Date object."
[date time]
(Date. (+ time (date-in-ms date))))
;;; --- random range functions ---
(defn hours
"Gives a random number of milliseconds representing an absolute
value of between from and to hours."
[from to]
(+
(hours-to-ms from)
(rand-int (hours-to-ms (- to from)))))
(defn days
"Gives a random number of milliseconds representing an absolute
value of between from and to days."
[from to]
(+
(days-to-ms from)
(rand-int (days-to-ms (- to from)))))
(defn weeks
"Gives a random number of milliseconds representing an absolute
value of between from and to weeks."
[from to]
(+
(weeks-to-ms from)
(long (* (rand) (weeks-to-ms (- to from))))))
(defn months
"Gives a random number of milliseconds representing an absolute
value of between from and to months."
[from to]
(+
(months-to-ms from)
(long (* (rand) (months-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
(defn years
"Gives a random number of milliseconds representing an absolute
value of between from and to years."
[from to]
(+
(years-to-ms from)
(long (* (rand) (years-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
;;; --- random date functions ---
;; maybe consider moving (not time)
(defn random-date
"Picks a random date (uniformly) between two years.
(from/to 0hrs on 1/1 of year)"
[from-year to-year]
(new Date (+ (year-in-ms from-year)
(long (rand (- (year-in-ms to-year)
(year-in-ms from-year)))))))
(defn random-date-normal
[mean-year sd]
(new Date
(long (rand-normal (year-in-ms mean-year) (years-to-ms sd)))))
| 51708 | (ns ^{:doc "Library for defining, querying and manipulating dates
and times."
:author "<NAME>"}
simulator.time
(:use [simulator.utils :only (rand-normal)])
(import [java.util Date Calendar]
[java.text SimpleDateFormat]))
;;; --- conversion functions ---
(defn date-in-ms
"Get the time in milliseconds between epoch and given date.
If no date is given default is now."
([] (.getTime (.getTime (Calendar/getInstance))))
([date] (.getTimeInMillis (doto (Calendar/getInstance) (.setTime date)))))
(defn years-to-ms
"Naive conversion of years to milliseconds"
[years] (* years 365 24 60 60 1000))
(defn months-to-ms
"Naive conversion of months to milliseconds"
[months] (* months 30 24 60 60 1000))
(defn weeks-to-ms
"Naive conversion of weeks to milliseconds"
[weeks] (* weeks 7 24 60 60 1000))
(defn days-to-ms
"Naive conversion of days to milliseconds"
[days] (* days 24 60 60 1000))
(defn hours-to-ms
"Naive conversion of hours to milliseconds"
[hours] (* hours 60 60 1000))
(defn year-in-ms
"Converts a calendar year to milliseconds since epoch."
[year] (.getTimeInMillis (doto (Calendar/getInstance)
(.setTimeInMillis 0)
(.set Calendar/YEAR year))))
;;; --- utility functions ---
(defn get-year
"Returns a string representing the year of the given date in yyyy format."
[date]
(.format (SimpleDateFormat. "yyyy") date))
(defn after-now?
"Returns true if the given date is in the future."
[date]
(.after date (Date.)))
(defn add-time-to-date
"Adds a time specified in milliseconds to the given java.util.Date object."
[date time]
(Date. (+ time (date-in-ms date))))
;;; --- random range functions ---
(defn hours
"Gives a random number of milliseconds representing an absolute
value of between from and to hours."
[from to]
(+
(hours-to-ms from)
(rand-int (hours-to-ms (- to from)))))
(defn days
"Gives a random number of milliseconds representing an absolute
value of between from and to days."
[from to]
(+
(days-to-ms from)
(rand-int (days-to-ms (- to from)))))
(defn weeks
"Gives a random number of milliseconds representing an absolute
value of between from and to weeks."
[from to]
(+
(weeks-to-ms from)
(long (* (rand) (weeks-to-ms (- to from))))))
(defn months
"Gives a random number of milliseconds representing an absolute
value of between from and to months."
[from to]
(+
(months-to-ms from)
(long (* (rand) (months-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
(defn years
"Gives a random number of milliseconds representing an absolute
value of between from and to years."
[from to]
(+
(years-to-ms from)
(long (* (rand) (years-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
;;; --- random date functions ---
;; maybe consider moving (not time)
(defn random-date
"Picks a random date (uniformly) between two years.
(from/to 0hrs on 1/1 of year)"
[from-year to-year]
(new Date (+ (year-in-ms from-year)
(long (rand (- (year-in-ms to-year)
(year-in-ms from-year)))))))
(defn random-date-normal
[mean-year sd]
(new Date
(long (rand-normal (year-in-ms mean-year) (years-to-ms sd)))))
| true | (ns ^{:doc "Library for defining, querying and manipulating dates
and times."
:author "PI:NAME:<NAME>END_PI"}
simulator.time
(:use [simulator.utils :only (rand-normal)])
(import [java.util Date Calendar]
[java.text SimpleDateFormat]))
;;; --- conversion functions ---
(defn date-in-ms
"Get the time in milliseconds between epoch and given date.
If no date is given default is now."
([] (.getTime (.getTime (Calendar/getInstance))))
([date] (.getTimeInMillis (doto (Calendar/getInstance) (.setTime date)))))
(defn years-to-ms
"Naive conversion of years to milliseconds"
[years] (* years 365 24 60 60 1000))
(defn months-to-ms
"Naive conversion of months to milliseconds"
[months] (* months 30 24 60 60 1000))
(defn weeks-to-ms
"Naive conversion of weeks to milliseconds"
[weeks] (* weeks 7 24 60 60 1000))
(defn days-to-ms
"Naive conversion of days to milliseconds"
[days] (* days 24 60 60 1000))
(defn hours-to-ms
"Naive conversion of hours to milliseconds"
[hours] (* hours 60 60 1000))
(defn year-in-ms
"Converts a calendar year to milliseconds since epoch."
[year] (.getTimeInMillis (doto (Calendar/getInstance)
(.setTimeInMillis 0)
(.set Calendar/YEAR year))))
;;; --- utility functions ---
(defn get-year
"Returns a string representing the year of the given date in yyyy format."
[date]
(.format (SimpleDateFormat. "yyyy") date))
(defn after-now?
"Returns true if the given date is in the future."
[date]
(.after date (Date.)))
(defn add-time-to-date
"Adds a time specified in milliseconds to the given java.util.Date object."
[date time]
(Date. (+ time (date-in-ms date))))
;;; --- random range functions ---
(defn hours
"Gives a random number of milliseconds representing an absolute
value of between from and to hours."
[from to]
(+
(hours-to-ms from)
(rand-int (hours-to-ms (- to from)))))
(defn days
"Gives a random number of milliseconds representing an absolute
value of between from and to days."
[from to]
(+
(days-to-ms from)
(rand-int (days-to-ms (- to from)))))
(defn weeks
"Gives a random number of milliseconds representing an absolute
value of between from and to weeks."
[from to]
(+
(weeks-to-ms from)
(long (* (rand) (weeks-to-ms (- to from))))))
(defn months
"Gives a random number of milliseconds representing an absolute
value of between from and to months."
[from to]
(+
(months-to-ms from)
(long (* (rand) (months-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
(defn years
"Gives a random number of milliseconds representing an absolute
value of between from and to years."
[from to]
(+
(years-to-ms from)
(long (* (rand) (years-to-ms (- to from))))))
(defn years-normal
"Gives a random number of milliseconds representing an absolute
value of between from and to years drawn from a normal distribution
with given mean and sd number of years."
[mean sd]
(long (rand-normal (years-to-ms mean) (years-to-ms sd))))
;;; --- random date functions ---
;; maybe consider moving (not time)
(defn random-date
"Picks a random date (uniformly) between two years.
(from/to 0hrs on 1/1 of year)"
[from-year to-year]
(new Date (+ (year-in-ms from-year)
(long (rand (- (year-in-ms to-year)
(year-in-ms from-year)))))))
(defn random-date-normal
[mean-year sd]
(new Date
(long (rand-normal (year-in-ms mean-year) (years-to-ms sd)))))
|
[
{
"context": ", welche pro Feld vorgenommen wird.\r\n;;\r\n;; Autor: Christian Meichsner\r\n\r\n(ns org.lambdaroyal.util.io\r\n (:require [cloj",
"end": 298,
"score": 0.9998782873153687,
"start": 279,
"tag": "NAME",
"value": "Christian Meichsner"
}
] | src/main/clojure/org/lambdaroyal/util/io.clj | gixxi/clojure-util | 1 | ;; Aspekt I/O
;; Generelle Funktionen zum Lesen von Datensätzen aus einer Datei und zum Eintragen dieser
;; Datensätze in eine Zieldatenbank. Das Eintragen der Daten geschieht nicht direkt, sondern
;; nach einer Datenmutation, welche pro Feld vorgenommen wird.
;;
;; Autor: Christian Meichsner
(ns org.lambdaroyal.util.io
(:require [clojure.java.jdbc :as sql])
(:import [org.apache.tomcat.jdbc.pool DataSource]
[org.lambdaroyal.util ConsoleProgress])
(:gen-class))
(defn checkDatei [abstract file help]
"Prüft ob eine Datei, deren Inhalt durch <abstract> beschrieben ist, tatsächliche
vorhanden ist. Im Fehlerfall wird das Programm beendet und <help> ausgegeben"
(cond
(not file)
(do (println (str "Parameter " abstract " muss angegeben werden." \newline help)) (java.lang.System/exit 1))
(not (.exists file))
(do (println (str "Parameter " abstract " " (.getName file) " ist nicht vorhanden.")) (java.lang.System/exit 1))
(not (.isFile file))
(do (println (str "Parameter " abstract " " (.getName file) " ist keine Datei.")) (java.lang.System/exit 1))))
(defn count-zeile [file]
(with-open
[rdr (clojure.java.io/reader file)]
(reduce (fn [acc _](inc acc)) 0 (line-seq rdr))))
(defn loadDatei
([args k key-fun]
"Laden einer Datei gegeben durch (get args k).
Die Datei muss semikolonsepariert sein.
Die Datei wird in eine transiente Datenstruktur geladen."
(with-open
[csvrdr (clojure.java.io/reader (get args k))]
(let [field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(clojure.string/split % #";"))
(line-seq csvrdr))]
(persistent!
(reduce #(conj! % %2) (transient []) _1)))))
([args k key-fun split-fun & opts]
"Laden einer Datei gegeben durch (get args k).
Eine Zeile wird mitfilge der Funktion (split-fun line) in ihre Spalten geparst.
Die Datei wird in eine transiente Datenstruktur geladen. Die Typumwandlung wird in dieser
Variante in dieser Funktion vorgenommen."
(with-open
[csvrdr (apply clojure.java.io/reader (get args k) opts)]
(let [opts (cond (empty? opts) {} :else (apply hash-map opts))
field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(split-fun %))
(if (= true (get opts :ignore-first))
(next
(line-seq csvrdr))
;else
(line-seq csvrdr)))]
(persistent!
(reduce #(conj! % %2) (transient []) _1))))))
(defn lade-datei-und-convert [args k key-fun split-fun & opts]
"Laden einer Datei mittels .loadDatei und anwenden der Convertierungsfunktion"
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
split-fun (cond (nil? split-fun) #(clojure.string/split % #";") :else split-fun)
typed #(reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} %1)]
(map typed
(apply loadDatei args k key-fun split-fun opts))))
(defn insertRecord [tab rec key-fun & fargs]
"Einfügen eines records in die Datenbanktabelle <tab> unter Berücksichtigung der Typen im Ziel ERD.
<fargs> wird destructed zu f & args und gibt eine Funktion samt parametern an, welche
vor Einfügung des tupels in die Datenbank auf dem tupel angewendet wird (f tupel args)."
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
typed (reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} rec)
[f & a] fargs
record (cond f (apply f typed a) :else typed)]
(sql/insert-records tab record)))
(defn importDatei [phase datasource args k abstract help tab key-fun & fargs]
"Laden der Daten mit Inhaltsbeschreibung <abstract> aus
einer Datei (<args> <k>)und speichern in die interne
Datenbank mit Verbindung
<datasource> für Phase <phase>. Bei einem Fehler wird <help> ausgegeben. Gdw.
args :maxlines enthält, werden nur <:maxlines> Zeilen aus der Datei verarbeitet."
(do
;;Prüfe auf notwendige Parameter und deren Korrektheit
(checkDatei abstract (get args k) help)
(let [s (if
(:encoding args) (loadDatei args k key-fun #(clojure.string/split % #";") :encoding (:encoding args))
(loadDatei args k key-fun #(clojure.string/split % #";")))
sc (count s)
progress (new ConsoleProgress)]
(do
(sql/with-connection {:datasource datasource}
(reduce
(fn [acc i]
(do
(.showProgress progress (str "Phase " phase " - Import (total " sc ")") (* acc (/ 100 sc)))
(apply insertRecord tab i key-fun fargs)
(inc acc))) 1
(cond (contains? (:maxlines args))
(take (:maxlines args) s)
:else
s)))))))
(defn deleteTabelle [phase datasource tab]
"Löschen aller bereits vorhandenen records aus einer datenbanktabelle. "
(let
[progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands (str "delete from " tab)))
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 100))))
(defn performUpdate [datasource phase abstract sqlString]
"Führt ein beliebiges SQL Statement aus und wartet auf das Ergebnis."
(let [progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - " abstract) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands sqlString))
(.showProgress progress (str "Phase " phase " - " abstract) 100))))
(defn query-and-map [datasource query maxcount fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus"
(sql/with-connection {:datasource datasource}
(sql/with-query-results res [query]
(dorun maxcount
(map #(apply fun %1 param) res)))))
(defn query2file [datasource query maxcount filename fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus. Jeder Datensatz wird in die Datei <filename> gespeichert."
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(query-and-map datasource query maxcount write-fun param))))
(defn relation2file [content filename fun & param]
"Speichert die angegebene Relation <content> (sequenz von assoziativen listen aka maps) semicolonsepariert in eine Datei <filename>. Pro Datensatz wird vor der Speicherung in die Datei die Funktion <fun> mit den Parametern <& param> ausgeführt. Als Encoding kommt UTF-8 zur Anwendung"
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(dorun
(map #(apply write-fun %1 param) content)))))
| 10384 | ;; Aspekt I/O
;; Generelle Funktionen zum Lesen von Datensätzen aus einer Datei und zum Eintragen dieser
;; Datensätze in eine Zieldatenbank. Das Eintragen der Daten geschieht nicht direkt, sondern
;; nach einer Datenmutation, welche pro Feld vorgenommen wird.
;;
;; Autor: <NAME>
(ns org.lambdaroyal.util.io
(:require [clojure.java.jdbc :as sql])
(:import [org.apache.tomcat.jdbc.pool DataSource]
[org.lambdaroyal.util ConsoleProgress])
(:gen-class))
(defn checkDatei [abstract file help]
"Prüft ob eine Datei, deren Inhalt durch <abstract> beschrieben ist, tatsächliche
vorhanden ist. Im Fehlerfall wird das Programm beendet und <help> ausgegeben"
(cond
(not file)
(do (println (str "Parameter " abstract " muss angegeben werden." \newline help)) (java.lang.System/exit 1))
(not (.exists file))
(do (println (str "Parameter " abstract " " (.getName file) " ist nicht vorhanden.")) (java.lang.System/exit 1))
(not (.isFile file))
(do (println (str "Parameter " abstract " " (.getName file) " ist keine Datei.")) (java.lang.System/exit 1))))
(defn count-zeile [file]
(with-open
[rdr (clojure.java.io/reader file)]
(reduce (fn [acc _](inc acc)) 0 (line-seq rdr))))
(defn loadDatei
([args k key-fun]
"Laden einer Datei gegeben durch (get args k).
Die Datei muss semikolonsepariert sein.
Die Datei wird in eine transiente Datenstruktur geladen."
(with-open
[csvrdr (clojure.java.io/reader (get args k))]
(let [field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(clojure.string/split % #";"))
(line-seq csvrdr))]
(persistent!
(reduce #(conj! % %2) (transient []) _1)))))
([args k key-fun split-fun & opts]
"Laden einer Datei gegeben durch (get args k).
Eine Zeile wird mitfilge der Funktion (split-fun line) in ihre Spalten geparst.
Die Datei wird in eine transiente Datenstruktur geladen. Die Typumwandlung wird in dieser
Variante in dieser Funktion vorgenommen."
(with-open
[csvrdr (apply clojure.java.io/reader (get args k) opts)]
(let [opts (cond (empty? opts) {} :else (apply hash-map opts))
field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(split-fun %))
(if (= true (get opts :ignore-first))
(next
(line-seq csvrdr))
;else
(line-seq csvrdr)))]
(persistent!
(reduce #(conj! % %2) (transient []) _1))))))
(defn lade-datei-und-convert [args k key-fun split-fun & opts]
"Laden einer Datei mittels .loadDatei und anwenden der Convertierungsfunktion"
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
split-fun (cond (nil? split-fun) #(clojure.string/split % #";") :else split-fun)
typed #(reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} %1)]
(map typed
(apply loadDatei args k key-fun split-fun opts))))
(defn insertRecord [tab rec key-fun & fargs]
"Einfügen eines records in die Datenbanktabelle <tab> unter Berücksichtigung der Typen im Ziel ERD.
<fargs> wird destructed zu f & args und gibt eine Funktion samt parametern an, welche
vor Einfügung des tupels in die Datenbank auf dem tupel angewendet wird (f tupel args)."
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
typed (reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} rec)
[f & a] fargs
record (cond f (apply f typed a) :else typed)]
(sql/insert-records tab record)))
(defn importDatei [phase datasource args k abstract help tab key-fun & fargs]
"Laden der Daten mit Inhaltsbeschreibung <abstract> aus
einer Datei (<args> <k>)und speichern in die interne
Datenbank mit Verbindung
<datasource> für Phase <phase>. Bei einem Fehler wird <help> ausgegeben. Gdw.
args :maxlines enthält, werden nur <:maxlines> Zeilen aus der Datei verarbeitet."
(do
;;Prüfe auf notwendige Parameter und deren Korrektheit
(checkDatei abstract (get args k) help)
(let [s (if
(:encoding args) (loadDatei args k key-fun #(clojure.string/split % #";") :encoding (:encoding args))
(loadDatei args k key-fun #(clojure.string/split % #";")))
sc (count s)
progress (new ConsoleProgress)]
(do
(sql/with-connection {:datasource datasource}
(reduce
(fn [acc i]
(do
(.showProgress progress (str "Phase " phase " - Import (total " sc ")") (* acc (/ 100 sc)))
(apply insertRecord tab i key-fun fargs)
(inc acc))) 1
(cond (contains? (:maxlines args))
(take (:maxlines args) s)
:else
s)))))))
(defn deleteTabelle [phase datasource tab]
"Löschen aller bereits vorhandenen records aus einer datenbanktabelle. "
(let
[progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands (str "delete from " tab)))
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 100))))
(defn performUpdate [datasource phase abstract sqlString]
"Führt ein beliebiges SQL Statement aus und wartet auf das Ergebnis."
(let [progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - " abstract) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands sqlString))
(.showProgress progress (str "Phase " phase " - " abstract) 100))))
(defn query-and-map [datasource query maxcount fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus"
(sql/with-connection {:datasource datasource}
(sql/with-query-results res [query]
(dorun maxcount
(map #(apply fun %1 param) res)))))
(defn query2file [datasource query maxcount filename fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus. Jeder Datensatz wird in die Datei <filename> gespeichert."
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(query-and-map datasource query maxcount write-fun param))))
(defn relation2file [content filename fun & param]
"Speichert die angegebene Relation <content> (sequenz von assoziativen listen aka maps) semicolonsepariert in eine Datei <filename>. Pro Datensatz wird vor der Speicherung in die Datei die Funktion <fun> mit den Parametern <& param> ausgeführt. Als Encoding kommt UTF-8 zur Anwendung"
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(dorun
(map #(apply write-fun %1 param) content)))))
| true | ;; Aspekt I/O
;; Generelle Funktionen zum Lesen von Datensätzen aus einer Datei und zum Eintragen dieser
;; Datensätze in eine Zieldatenbank. Das Eintragen der Daten geschieht nicht direkt, sondern
;; nach einer Datenmutation, welche pro Feld vorgenommen wird.
;;
;; Autor: PI:NAME:<NAME>END_PI
(ns org.lambdaroyal.util.io
(:require [clojure.java.jdbc :as sql])
(:import [org.apache.tomcat.jdbc.pool DataSource]
[org.lambdaroyal.util ConsoleProgress])
(:gen-class))
(defn checkDatei [abstract file help]
"Prüft ob eine Datei, deren Inhalt durch <abstract> beschrieben ist, tatsächliche
vorhanden ist. Im Fehlerfall wird das Programm beendet und <help> ausgegeben"
(cond
(not file)
(do (println (str "Parameter " abstract " muss angegeben werden." \newline help)) (java.lang.System/exit 1))
(not (.exists file))
(do (println (str "Parameter " abstract " " (.getName file) " ist nicht vorhanden.")) (java.lang.System/exit 1))
(not (.isFile file))
(do (println (str "Parameter " abstract " " (.getName file) " ist keine Datei.")) (java.lang.System/exit 1))))
(defn count-zeile [file]
(with-open
[rdr (clojure.java.io/reader file)]
(reduce (fn [acc _](inc acc)) 0 (line-seq rdr))))
(defn loadDatei
([args k key-fun]
"Laden einer Datei gegeben durch (get args k).
Die Datei muss semikolonsepariert sein.
Die Datei wird in eine transiente Datenstruktur geladen."
(with-open
[csvrdr (clojure.java.io/reader (get args k))]
(let [field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(clojure.string/split % #";"))
(line-seq csvrdr))]
(persistent!
(reduce #(conj! % %2) (transient []) _1)))))
([args k key-fun split-fun & opts]
"Laden einer Datei gegeben durch (get args k).
Eine Zeile wird mitfilge der Funktion (split-fun line) in ihre Spalten geparst.
Die Datei wird in eine transiente Datenstruktur geladen. Die Typumwandlung wird in dieser
Variante in dieser Funktion vorgenommen."
(with-open
[csvrdr (apply clojure.java.io/reader (get args k) opts)]
(let [opts (cond (empty? opts) {} :else (apply hash-map opts))
field (take-nth 2 key-fun)
_1 (map
#(zipmap field
(split-fun %))
(if (= true (get opts :ignore-first))
(next
(line-seq csvrdr))
;else
(line-seq csvrdr)))]
(persistent!
(reduce #(conj! % %2) (transient []) _1))))))
(defn lade-datei-und-convert [args k key-fun split-fun & opts]
"Laden einer Datei mittels .loadDatei und anwenden der Convertierungsfunktion"
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
split-fun (cond (nil? split-fun) #(clojure.string/split % #";") :else split-fun)
typed #(reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} %1)]
(map typed
(apply loadDatei args k key-fun split-fun opts))))
(defn insertRecord [tab rec key-fun & fargs]
"Einfügen eines records in die Datenbanktabelle <tab> unter Berücksichtigung der Typen im Ziel ERD.
<fargs> wird destructed zu f & args und gibt eine Funktion samt parametern an, welche
vor Einfügung des tupels in die Datenbank auf dem tupel angewendet wird (f tupel args)."
(let [fun (take-nth 2 (rest key-fun))
field (take-nth 2 key-fun)
fun-by-field (zipmap field fun)
typed (reduce (fn [acc [k v]](conj acc [k ((k fun-by-field) v)])) {} rec)
[f & a] fargs
record (cond f (apply f typed a) :else typed)]
(sql/insert-records tab record)))
(defn importDatei [phase datasource args k abstract help tab key-fun & fargs]
"Laden der Daten mit Inhaltsbeschreibung <abstract> aus
einer Datei (<args> <k>)und speichern in die interne
Datenbank mit Verbindung
<datasource> für Phase <phase>. Bei einem Fehler wird <help> ausgegeben. Gdw.
args :maxlines enthält, werden nur <:maxlines> Zeilen aus der Datei verarbeitet."
(do
;;Prüfe auf notwendige Parameter und deren Korrektheit
(checkDatei abstract (get args k) help)
(let [s (if
(:encoding args) (loadDatei args k key-fun #(clojure.string/split % #";") :encoding (:encoding args))
(loadDatei args k key-fun #(clojure.string/split % #";")))
sc (count s)
progress (new ConsoleProgress)]
(do
(sql/with-connection {:datasource datasource}
(reduce
(fn [acc i]
(do
(.showProgress progress (str "Phase " phase " - Import (total " sc ")") (* acc (/ 100 sc)))
(apply insertRecord tab i key-fun fargs)
(inc acc))) 1
(cond (contains? (:maxlines args))
(take (:maxlines args) s)
:else
s)))))))
(defn deleteTabelle [phase datasource tab]
"Löschen aller bereits vorhandenen records aus einer datenbanktabelle. "
(let
[progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands (str "delete from " tab)))
(.showProgress progress (str "Phase " phase " - Löschen der Tabelle " tab) 100))))
(defn performUpdate [datasource phase abstract sqlString]
"Führt ein beliebiges SQL Statement aus und wartet auf das Ergebnis."
(let [progress (new ConsoleProgress)]
(do
(.showProgress progress (str "Phase " phase " - " abstract) 0)
(sql/with-connection
{:datasource datasource}
(sql/do-commands sqlString))
(.showProgress progress (str "Phase " phase " - " abstract) 100))))
(defn query-and-map [datasource query maxcount fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus"
(sql/with-connection {:datasource datasource}
(sql/with-query-results res [query]
(dorun maxcount
(map #(apply fun %1 param) res)))))
(defn query2file [datasource query maxcount filename fun & param]
"Führt das angegebene query <query> auf der Datenbankverbindung <datasource> aus und führt auf maximal <maxcount> datensätzen
die Funktion <fun> mit den Parametern <& param> aus. Jeder Datensatz wird in die Datei <filename> gespeichert."
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(query-and-map datasource query maxcount write-fun param))))
(defn relation2file [content filename fun & param]
"Speichert die angegebene Relation <content> (sequenz von assoziativen listen aka maps) semicolonsepariert in eine Datei <filename>. Pro Datensatz wird vor der Speicherung in die Datei die Funktion <fun> mit den Parametern <& param> ausgeführt. Als Encoding kommt UTF-8 zur Anwendung"
(with-open [wr (clojure.java.io/writer filename :encoding "ISO-8859-1")]
(let [write-fun
(fn [i & param2]
(do
(let [res (apply str
(interpose ";"
(let [fin
(cond (empty? param2)
(fun i)
:else
(apply fun i param))]
(cond
(map? fin)
(vals fin)
:else
fin))))]
(.write wr res))
(.write wr "\r\n")))]
(dorun
(map #(apply write-fun %1 param) content)))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998644590377808,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "tice, or any other, from this software.\n\n; Author: Stuart Halloway\n\n(ns clojure.test-clojure.rt\n (:require clojure.",
"end": 489,
"score": 0.9998911619186401,
"start": 474,
"tag": "NAME",
"value": "Stuart Halloway"
}
] | Chapter 07 Code/niko/clojure/test/clojure/test_clojure/rt.clj | PacktPublishing/Clojure-Programming-Cookbook | 14 | ; 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: Stuart Halloway
(ns clojure.test-clojure.rt
(:require clojure.set)
(:use clojure.test clojure.test-helper))
(defn bare-rt-print
"Return string RT would print prior to print-initialize"
[x]
(with-out-str
(try
(push-thread-bindings {#'clojure.core/print-initialized false})
(clojure.lang.RT/print x *out*)
(finally
(pop-thread-bindings)))))
(deftest rt-print-prior-to-print-initialize
(testing "pattern literals"
(is (= "#\"foo\"" (bare-rt-print #"foo")))))
(deftest error-messages
(testing "binding a core var that already refers to something"
(should-print-err-message
#"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n"
(defn prefers [] (throw (RuntimeException. "rebound!")))))
(testing "reflection cannot resolve field"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah can't be resolved\.\r?\n"
(defn foo [x] (.blah x))))
(testing "reflection cannot resolve field on known class"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah on java\.lang\.String can't be resolved\.\r?\n"
(defn foo [^String x] (.blah x))))
(testing "reflection cannot resolve instance method because it is missing"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap on java\.lang\.String can't be resolved \(no such method\)\.\r?\n"
(defn foo [^String x] (.zap x 1))))
(testing "reflection cannot resolve instance method because it has incompatible argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [^String x] (.getBytes x #"boom"))))
(testing "reflection cannot resolve instance method because it has unknown argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: unknown\)\.\r?\n"
(defn foo [^String x y] (.getBytes x y))))
(testing "reflection error prints correctly for nil arguments"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method divide on java\.math\.BigDecimal can't be resolved \(argument types: unknown, unknown\)\.\r?\n"
(defn foo [a] (.divide 1M a nil))))
(testing "reflection cannot resolve instance method because target class is unknown"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n"
(defn foo [x] (.zap x 1))))
(testing "reflection cannot resolve static method"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to static method valueOf on java\.lang\.Integer can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [] (Integer/valueOf #"boom"))))
(testing "reflection cannot resolve constructor"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to java\.lang\.String ctor can't be resolved\.\r?\n"
(defn foo [] (String. 1 2 3)))))
(def example-var)
(deftest binding-root-clears-macro-metadata
(alter-meta! #'example-var assoc :macro true)
(is (contains? (meta #'example-var) :macro))
(.bindRoot #'example-var 0)
(is (not (contains? (meta #'example-var) :macro))))
(deftest last-var-wins-for-core
(testing "you can replace a core name, with warning"
(let [ns (temp-ns)
replacement (gensym)]
(with-err-string-writer (intern ns 'prefers replacement))
(is (= replacement @('prefers (ns-publics ns))))))
(testing "you can replace a name you defined before"
(let [ns (temp-ns)
s (gensym)
v1 (intern ns 'foo s)
v2 (intern ns 'bar s)]
(with-err-string-writer (.refer ns 'flatten v1))
(.refer ns 'flatten v2)
(is (= v2 (ns-resolve ns 'flatten)))))
(testing "you cannot intern over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(intern ns 'subset? replacement)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns))))))
(testing "you cannot refer over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(.refer ns 'subset? #'clojure.set/intersection)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
| 45805 | ; 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.rt
(:require clojure.set)
(:use clojure.test clojure.test-helper))
(defn bare-rt-print
"Return string RT would print prior to print-initialize"
[x]
(with-out-str
(try
(push-thread-bindings {#'clojure.core/print-initialized false})
(clojure.lang.RT/print x *out*)
(finally
(pop-thread-bindings)))))
(deftest rt-print-prior-to-print-initialize
(testing "pattern literals"
(is (= "#\"foo\"" (bare-rt-print #"foo")))))
(deftest error-messages
(testing "binding a core var that already refers to something"
(should-print-err-message
#"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n"
(defn prefers [] (throw (RuntimeException. "rebound!")))))
(testing "reflection cannot resolve field"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah can't be resolved\.\r?\n"
(defn foo [x] (.blah x))))
(testing "reflection cannot resolve field on known class"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah on java\.lang\.String can't be resolved\.\r?\n"
(defn foo [^String x] (.blah x))))
(testing "reflection cannot resolve instance method because it is missing"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap on java\.lang\.String can't be resolved \(no such method\)\.\r?\n"
(defn foo [^String x] (.zap x 1))))
(testing "reflection cannot resolve instance method because it has incompatible argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [^String x] (.getBytes x #"boom"))))
(testing "reflection cannot resolve instance method because it has unknown argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: unknown\)\.\r?\n"
(defn foo [^String x y] (.getBytes x y))))
(testing "reflection error prints correctly for nil arguments"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method divide on java\.math\.BigDecimal can't be resolved \(argument types: unknown, unknown\)\.\r?\n"
(defn foo [a] (.divide 1M a nil))))
(testing "reflection cannot resolve instance method because target class is unknown"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n"
(defn foo [x] (.zap x 1))))
(testing "reflection cannot resolve static method"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to static method valueOf on java\.lang\.Integer can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [] (Integer/valueOf #"boom"))))
(testing "reflection cannot resolve constructor"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to java\.lang\.String ctor can't be resolved\.\r?\n"
(defn foo [] (String. 1 2 3)))))
(def example-var)
(deftest binding-root-clears-macro-metadata
(alter-meta! #'example-var assoc :macro true)
(is (contains? (meta #'example-var) :macro))
(.bindRoot #'example-var 0)
(is (not (contains? (meta #'example-var) :macro))))
(deftest last-var-wins-for-core
(testing "you can replace a core name, with warning"
(let [ns (temp-ns)
replacement (gensym)]
(with-err-string-writer (intern ns 'prefers replacement))
(is (= replacement @('prefers (ns-publics ns))))))
(testing "you can replace a name you defined before"
(let [ns (temp-ns)
s (gensym)
v1 (intern ns 'foo s)
v2 (intern ns 'bar s)]
(with-err-string-writer (.refer ns 'flatten v1))
(.refer ns 'flatten v2)
(is (= v2 (ns-resolve ns 'flatten)))))
(testing "you cannot intern over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(intern ns 'subset? replacement)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns))))))
(testing "you cannot refer over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(.refer ns 'subset? #'clojure.set/intersection)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
| 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.rt
(:require clojure.set)
(:use clojure.test clojure.test-helper))
(defn bare-rt-print
"Return string RT would print prior to print-initialize"
[x]
(with-out-str
(try
(push-thread-bindings {#'clojure.core/print-initialized false})
(clojure.lang.RT/print x *out*)
(finally
(pop-thread-bindings)))))
(deftest rt-print-prior-to-print-initialize
(testing "pattern literals"
(is (= "#\"foo\"" (bare-rt-print #"foo")))))
(deftest error-messages
(testing "binding a core var that already refers to something"
(should-print-err-message
#"WARNING: prefers already refers to: #'clojure.core/prefers in namespace: .*\r?\n"
(defn prefers [] (throw (RuntimeException. "rebound!")))))
(testing "reflection cannot resolve field"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah can't be resolved\.\r?\n"
(defn foo [x] (.blah x))))
(testing "reflection cannot resolve field on known class"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - reference to field blah on java\.lang\.String can't be resolved\.\r?\n"
(defn foo [^String x] (.blah x))))
(testing "reflection cannot resolve instance method because it is missing"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap on java\.lang\.String can't be resolved \(no such method\)\.\r?\n"
(defn foo [^String x] (.zap x 1))))
(testing "reflection cannot resolve instance method because it has incompatible argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [^String x] (.getBytes x #"boom"))))
(testing "reflection cannot resolve instance method because it has unknown argument types"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method getBytes on java\.lang\.String can't be resolved \(argument types: unknown\)\.\r?\n"
(defn foo [^String x y] (.getBytes x y))))
(testing "reflection error prints correctly for nil arguments"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method divide on java\.math\.BigDecimal can't be resolved \(argument types: unknown, unknown\)\.\r?\n"
(defn foo [a] (.divide 1M a nil))))
(testing "reflection cannot resolve instance method because target class is unknown"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to method zap can't be resolved \(target class is unknown\)\.\r?\n"
(defn foo [x] (.zap x 1))))
(testing "reflection cannot resolve static method"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to static method valueOf on java\.lang\.Integer can't be resolved \(argument types: java\.util\.regex\.Pattern\)\.\r?\n"
(defn foo [] (Integer/valueOf #"boom"))))
(testing "reflection cannot resolve constructor"
(should-print-err-message
#"Reflection warning, .*:\d+:\d+ - call to java\.lang\.String ctor can't be resolved\.\r?\n"
(defn foo [] (String. 1 2 3)))))
(def example-var)
(deftest binding-root-clears-macro-metadata
(alter-meta! #'example-var assoc :macro true)
(is (contains? (meta #'example-var) :macro))
(.bindRoot #'example-var 0)
(is (not (contains? (meta #'example-var) :macro))))
(deftest last-var-wins-for-core
(testing "you can replace a core name, with warning"
(let [ns (temp-ns)
replacement (gensym)]
(with-err-string-writer (intern ns 'prefers replacement))
(is (= replacement @('prefers (ns-publics ns))))))
(testing "you can replace a name you defined before"
(let [ns (temp-ns)
s (gensym)
v1 (intern ns 'foo s)
v2 (intern ns 'bar s)]
(with-err-string-writer (.refer ns 'flatten v1))
(.refer ns 'flatten v2)
(is (= v2 (ns-resolve ns 'flatten)))))
(testing "you cannot intern over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(intern ns 'subset? replacement)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns))))))
(testing "you cannot refer over an existing non-core name"
(let [ns (temp-ns 'clojure.set)
replacement (gensym)]
(is (thrown? IllegalStateException
(.refer ns 'subset? #'clojure.set/intersection)))
(is (nil? ('subset? (ns-publics ns))))
(is (= #'clojure.set/subset? ('subset? (ns-refers ns)))))))
|
[
{
"context": "ive vs boxing vs adding meta data...\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-09-16\"\n :version \"2017-09-20\"}",
"end": 296,
"score": 0.9846602082252502,
"start": 260,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/main/clojure/palisades/lakes/funx/spaces/linear/l2.clj | palisades-lakes/function-experiments | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.funx.spaces.linear.l2
{:doc "benchmark primitive vs boxing vs adding meta data..."
:author "palisades dot lakes at gmail dot com"
:since "2017-09-16"
:version "2017-09-20"}
(:require [palisades.lakes.dynafun.core :as d])
(:import [clojure.lang IFn$DD]))
;;----------------------------------------------------------------
(defn square ^double [^double x] (* x x))
(def clj-meta-square
(with-meta square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(def funx-meta-square
(d/with square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(set! *unchecked-math* false)
(defn boxed-square [x] (* x x))
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(defn squared ^IFn$DD [^IFn$DD f]
(with-meta
(fn squared0 ^double [^double x]
(let [fx (.invokePrim f x)]
(* fx fx)))
{:domain Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
;;----------------------------------------------------------------
| 70022 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.funx.spaces.linear.l2
{:doc "benchmark primitive vs boxing vs adding meta data..."
:author "<EMAIL>"
:since "2017-09-16"
:version "2017-09-20"}
(:require [palisades.lakes.dynafun.core :as d])
(:import [clojure.lang IFn$DD]))
;;----------------------------------------------------------------
(defn square ^double [^double x] (* x x))
(def clj-meta-square
(with-meta square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(def funx-meta-square
(d/with square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(set! *unchecked-math* false)
(defn boxed-square [x] (* x x))
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(defn squared ^IFn$DD [^IFn$DD f]
(with-meta
(fn squared0 ^double [^double x]
(let [fx (.invokePrim f x)]
(* fx fx)))
{:domain Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.funx.spaces.linear.l2
{:doc "benchmark primitive vs boxing vs adding meta data..."
:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-09-16"
:version "2017-09-20"}
(:require [palisades.lakes.dynafun.core :as d])
(:import [clojure.lang IFn$DD]))
;;----------------------------------------------------------------
(defn square ^double [^double x] (* x x))
(def clj-meta-square
(with-meta square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(def funx-meta-square
(d/with square
{:domain Double/TYPE
:codomain Double/TYPE
:support Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
(set! *unchecked-math* false)
(defn boxed-square [x] (* x x))
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(defn squared ^IFn$DD [^IFn$DD f]
(with-meta
(fn squared0 ^double [^double x]
(let [fx (.invokePrim f x)]
(* fx fx)))
{:domain Double/TYPE
:range [0.0 Double/POSITIVE_INFINITY Double/NaN]}))
;;----------------------------------------------------------------
|
[
{
"context": ";;; Copyright 2014 Mitchell Kember. Subject to the MIT License.\n\n(ns conceal.connect",
"end": 34,
"score": 0.999886691570282,
"start": 19,
"tag": "NAME",
"value": "Mitchell Kember"
}
] | src/cljs/conceal/connect.cljs | mk12/conceal | 0 | ;;; Copyright 2014 Mitchell Kember. Subject to the MIT License.
(ns conceal.connect
(:require [clojure.browser.repl :as repl]))
(repl/connect "http://localhost:9000/repl")
| 108534 | ;;; Copyright 2014 <NAME>. Subject to the MIT License.
(ns conceal.connect
(:require [clojure.browser.repl :as repl]))
(repl/connect "http://localhost:9000/repl")
| true | ;;; Copyright 2014 PI:NAME:<NAME>END_PI. Subject to the MIT License.
(ns conceal.connect
(:require [clojure.browser.repl :as repl]))
(repl/connect "http://localhost:9000/repl")
|
[
{
"context": "subname \"//localhost:5432/test\"\n :user \"user\"\n :password \"pass\"}))\n\n(comment)\n (def",
"end": 342,
"score": 0.7920394539833069,
"start": 338,
"tag": "USERNAME",
"value": "user"
},
{
"context": "st\"\n :user \"user\"\n :password \"pass\"}))\n\n(comment)\n (def db {:classname \"com.mysql.j",
"end": 370,
"score": 0.9996071457862854,
"start": 366,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "ocalhost;instanceName=TEST;databaseName=test;user=username;password=password;\"\n\t :create true}))\n\n(comment\n ",
"end": 719,
"score": 0.7863953709602356,
"start": 711,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ame=TEST;databaseName=test;user=username;password=password;\"\n\t :create true}))\n\n(comment\n (def db {:classna",
"end": 737,
"score": 0.9996545314788818,
"start": 729,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ":subprotocol \"db2\"\n\t :user \"db2\"\n\t :password \"db2\"\n\t :subname \"//localhost:50000/clojure:currentS",
"end": 875,
"score": 0.999455988407135,
"start": 872,
"tag": "PASSWORD",
"value": "db2"
}
] | test/clj_record/test_model/config.clj | duelinmarkers/clj-record | 8 | (ns clj-record.test-model.config)
(comment
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clj-record.test.db"
:create true}))
(comment
(def db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost:5432/test"
:user "user"
:password "pass"}))
(comment)
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:user "root"
:password ""
:subname "//localhost/clj_record_test"})
(comment
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname "//localhost;instanceName=TEST;databaseName=test;user=username;password=password;"
:create true}))
(comment
(def db {:classname "com.ibm.db2.jcc.DB2Driver"
:subprotocol "db2"
:user "db2"
:password "db2"
:subname "//localhost:50000/clojure:currentSchema=CLJRECORD;"}))
| 24250 | (ns clj-record.test-model.config)
(comment
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clj-record.test.db"
:create true}))
(comment
(def db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost:5432/test"
:user "user"
:password "<PASSWORD>"}))
(comment)
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:user "root"
:password ""
:subname "//localhost/clj_record_test"})
(comment
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname "//localhost;instanceName=TEST;databaseName=test;user=username;password=<PASSWORD>;"
:create true}))
(comment
(def db {:classname "com.ibm.db2.jcc.DB2Driver"
:subprotocol "db2"
:user "db2"
:password "<PASSWORD>"
:subname "//localhost:50000/clojure:currentSchema=CLJRECORD;"}))
| true | (ns clj-record.test-model.config)
(comment
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clj-record.test.db"
:create true}))
(comment
(def db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost:5432/test"
:user "user"
:password "PI:PASSWORD:<PASSWORD>END_PI"}))
(comment)
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:user "root"
:password ""
:subname "//localhost/clj_record_test"})
(comment
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname "//localhost;instanceName=TEST;databaseName=test;user=username;password=PI:PASSWORD:<PASSWORD>END_PI;"
:create true}))
(comment
(def db {:classname "com.ibm.db2.jcc.DB2Driver"
:subprotocol "db2"
:user "db2"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:subname "//localhost:50000/clojure:currentSchema=CLJRECORD;"}))
|
[
{
"context": ";; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2015 Alejand",
"end": 40,
"score": 0.999893069267273,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2015 Alejandro Gómez <alej",
"end": 54,
"score": 0.9999296069145203,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
},
{
"context": "y Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2015 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved\n;;",
"end": 98,
"score": 0.9998893737792969,
"start": 83,
"tag": "NAME",
"value": "Alejandro Gómez"
},
{
"context": "i.nz>\n;; Copyright (c) 2014-2015 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved\n;;\n;; Redistribution and ",
"end": 121,
"score": 0.9999338984489441,
"start": 100,
"tag": "EMAIL",
"value": "alejandro@dialelo.com"
}
] | src/cats/builtin.cljc | klausharbo/cats | 896 | ;; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.nz>
;; Copyright (c) 2014-2015 Alejandro Gómez <alejandro@dialelo.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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 cats.builtin
"Clojure(Script) built-in types extensions."
(:require [clojure.set :as s]
[cats.monad.maybe :as maybe]
[cats.protocols :as p]
[cats.context :as ctx]
[cats.core :as m]
[cats.util :as util]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Nil as Nothing of Maybe monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-type nil
p/Contextual
(-get-context [_] maybe/context)
p/Extract
(-extract [_] nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sequence Monad i.e. PersistentList
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv' (reverse sv)))
p/Monoid
(-mempty [_] ())
p/Functor
(-fmap [_ f v]
(loop [[h & t :as c] v
result ()]
(if (empty? c)
(reverse result)
(recur t (cons (f h) result)))))
p/Applicative
(-pure [_ v] (list v))
(-fapply [_ self av]
;; Each function (outer loop) applied to each value (inner loop).
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t
(cons (loop [[h' & t' :as c'] av
result' ()]
(if (empty? c')
result'
(recur t' (cons (h h') result'))))
result))))
;; Note that both `result` & `result'` above are
;; in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/Monad
(-mreturn [_ v]
(list v))
(-mbind [_ self f]
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t (cons (f h) result))))
;; Note that `result` above is in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/MonadZero
(-mzero [_] ())
p/MonadPlus
(-mplus [_ mv mv']
(into mv' (reverse mv)))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure ())
as)))
p/Printable
(-repr [_]
"#<List>")))
(util/make-printable (type sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList
:cljs cljs.core.List)
p/Contextual
(-get-context [_] sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList$EmptyList
:cljs cljs.core.EmptyList)
p/Contextual
(-get-context [_] sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Lazy Sequence Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lazy-sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(concat sv sv'))
p/Monoid
(-mempty [_]
(lazy-seq []))
p/Functor
(-fmap [_ f v]
(map f v))
p/Applicative
(-pure [_ v]
(lazy-seq [v]))
(-fapply [_ self av]
(for [f self
v av]
(f v)))
p/Monad
(-mreturn [_ v]
(lazy-seq [v]))
(-mbind [_ self f]
(apply concat (map f self)))
p/MonadZero
(-mzero [_]
(lazy-seq []))
p/MonadPlus
(-mplus [_ mv mv']
(concat mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure (lazy-seq []))
as)))
p/Printable
(-repr [_]
"#<LazySequence>")))
(util/make-printable (type lazy-sequence-context))
(extend-type #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq)
p/Contextual
(-get-context [_] lazy-sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Range
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def range-context
(reify
p/Context
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Range>")))
(util/make-printable (type range-context))
(extend-type #?(:clj clojure.lang.LongRange
:cljs cljs.core.Range)
p/Contextual
(-get-context [_] range-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vector Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def vector-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv sv'))
p/Monoid
(-mempty [_]
[])
p/Functor
(-fmap [_ f v]
(vec (map f v)))
p/Applicative
(-pure [_ v]
[v])
(-fapply [_ self av]
(vec (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
[v])
(-mbind [_ self f]
(vec (mapcat f self)))
p/MonadZero
(-mzero [_]
[])
p/MonadPlus
(-mplus [_ mv mv']
(into mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z (reverse xs))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldl ctx
(fn [acc a]
(m/alet [x a
xs acc]
(conj xs x)))
(m/pure [])
as)))
p/Printable
(-repr [_]
"#<Vector>")))
(util/make-printable (type vector-context))
(extend-type #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
p/Contextual
(-get-context [_] vector-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Map Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def map-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(merge sv sv'))
p/Monoid
(-mempty [_]
{})
p/Functor
(-fmap [_ f v]
(into {} (map (fn [[key value]] [key (f value)]) v)))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z xs)))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Map>")))
(util/make-printable (type map-context))
(extend-type #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentHashMap
:cljs cljs.core.PersistentHashMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentTreeMap
:cljs cljs.core.PersistentTreeMap)
p/Contextual
(-get-context [_] map-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def set-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(s/union sv (set sv')))
p/Monoid
(-mempty [_]
#{})
p/Functor
(-fmap [_ f self]
(set (map f self)))
p/Applicative
(-pure [_ v]
#{v})
(-fapply [_ self av]
(set (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
#{v})
(-mbind [_ self f]
(apply s/union (map f self)))
p/MonadZero
(-mzero [_]
#{})
p/MonadPlus
(-mplus [_ mv mv']
(s/union mv mv'))
p/Printable
(-repr [_]
"#<Set>")))
(util/make-printable (type set-context))
(extend-type #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet)
p/Contextual
(-get-context [_] set-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def function-context
(reify
p/Context
p/Semigroup
(-mappend [ctx f g] (comp f g))
p/Monoid
(-mempty [_] identity)
p/Functor
(-fmap [_ f self]
(comp f self))
p/Applicative
(-pure [_ v]
(constantly v))
(-fapply [_ self av]
(fn [x] ((self x) (av x))))
p/Monad
(-mreturn [_ v]
(constantly v))
(-mbind [_ self f]
(fn [r] ((f (self r)) r)))
p/Printable
(-repr [_]
"#<Function>")))
(util/make-printable (type function-context))
(extend-type #?(:clj clojure.lang.IFn
:cljs cljs.core.IFn)
p/Contextual
(-get-context [_] function-context))
#?(:cljs
(extend-type function
p/Contextual
(-get-context [_] function-context)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monoids
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def any-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(or sv sv'))
p/Monoid
(-mempty [_]
false)
p/Printable
(-repr [_]
"#<Any>")))
(util/make-printable (type any-monoid))
(def all-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(and sv sv'))
p/Monoid
(-mempty [_]
true)
p/Printable
(-repr [_]
"#<All>")))
(util/make-printable (type all-monoid))
(def sum-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(+ sv sv'))
p/Monoid
(-mempty [_]
0)
p/Printable
(-repr [_]
"#<Sum>")))
(util/make-printable (type sum-monoid))
(def prod-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(* sv sv'))
p/Monoid
(-mempty [_]
1)
p/Printable
(-repr [_]
"#<Product>")))
(util/make-printable (type prod-monoid))
(def string-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(str sv sv'))
p/Monoid
(-mempty [_]
"")
p/Printable
(-repr [_]
"#<String>")))
(util/make-printable (type string-monoid))
(extend-type #?(:clj java.lang.String
:cljs string)
p/Contextual
(-get-context [_] string-monoid))
| 113852 | ;; Copyright (c) 2014-2015 <NAME> <<EMAIL>>
;; Copyright (c) 2014-2015 <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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 cats.builtin
"Clojure(Script) built-in types extensions."
(:require [clojure.set :as s]
[cats.monad.maybe :as maybe]
[cats.protocols :as p]
[cats.context :as ctx]
[cats.core :as m]
[cats.util :as util]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Nil as Nothing of Maybe monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-type nil
p/Contextual
(-get-context [_] maybe/context)
p/Extract
(-extract [_] nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sequence Monad i.e. PersistentList
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv' (reverse sv)))
p/Monoid
(-mempty [_] ())
p/Functor
(-fmap [_ f v]
(loop [[h & t :as c] v
result ()]
(if (empty? c)
(reverse result)
(recur t (cons (f h) result)))))
p/Applicative
(-pure [_ v] (list v))
(-fapply [_ self av]
;; Each function (outer loop) applied to each value (inner loop).
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t
(cons (loop [[h' & t' :as c'] av
result' ()]
(if (empty? c')
result'
(recur t' (cons (h h') result'))))
result))))
;; Note that both `result` & `result'` above are
;; in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/Monad
(-mreturn [_ v]
(list v))
(-mbind [_ self f]
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t (cons (f h) result))))
;; Note that `result` above is in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/MonadZero
(-mzero [_] ())
p/MonadPlus
(-mplus [_ mv mv']
(into mv' (reverse mv)))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure ())
as)))
p/Printable
(-repr [_]
"#<List>")))
(util/make-printable (type sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList
:cljs cljs.core.List)
p/Contextual
(-get-context [_] sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList$EmptyList
:cljs cljs.core.EmptyList)
p/Contextual
(-get-context [_] sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Lazy Sequence Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lazy-sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(concat sv sv'))
p/Monoid
(-mempty [_]
(lazy-seq []))
p/Functor
(-fmap [_ f v]
(map f v))
p/Applicative
(-pure [_ v]
(lazy-seq [v]))
(-fapply [_ self av]
(for [f self
v av]
(f v)))
p/Monad
(-mreturn [_ v]
(lazy-seq [v]))
(-mbind [_ self f]
(apply concat (map f self)))
p/MonadZero
(-mzero [_]
(lazy-seq []))
p/MonadPlus
(-mplus [_ mv mv']
(concat mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure (lazy-seq []))
as)))
p/Printable
(-repr [_]
"#<LazySequence>")))
(util/make-printable (type lazy-sequence-context))
(extend-type #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq)
p/Contextual
(-get-context [_] lazy-sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Range
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def range-context
(reify
p/Context
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Range>")))
(util/make-printable (type range-context))
(extend-type #?(:clj clojure.lang.LongRange
:cljs cljs.core.Range)
p/Contextual
(-get-context [_] range-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vector Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def vector-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv sv'))
p/Monoid
(-mempty [_]
[])
p/Functor
(-fmap [_ f v]
(vec (map f v)))
p/Applicative
(-pure [_ v]
[v])
(-fapply [_ self av]
(vec (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
[v])
(-mbind [_ self f]
(vec (mapcat f self)))
p/MonadZero
(-mzero [_]
[])
p/MonadPlus
(-mplus [_ mv mv']
(into mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z (reverse xs))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldl ctx
(fn [acc a]
(m/alet [x a
xs acc]
(conj xs x)))
(m/pure [])
as)))
p/Printable
(-repr [_]
"#<Vector>")))
(util/make-printable (type vector-context))
(extend-type #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
p/Contextual
(-get-context [_] vector-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Map Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def map-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(merge sv sv'))
p/Monoid
(-mempty [_]
{})
p/Functor
(-fmap [_ f v]
(into {} (map (fn [[key value]] [key (f value)]) v)))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z xs)))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Map>")))
(util/make-printable (type map-context))
(extend-type #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentHashMap
:cljs cljs.core.PersistentHashMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentTreeMap
:cljs cljs.core.PersistentTreeMap)
p/Contextual
(-get-context [_] map-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def set-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(s/union sv (set sv')))
p/Monoid
(-mempty [_]
#{})
p/Functor
(-fmap [_ f self]
(set (map f self)))
p/Applicative
(-pure [_ v]
#{v})
(-fapply [_ self av]
(set (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
#{v})
(-mbind [_ self f]
(apply s/union (map f self)))
p/MonadZero
(-mzero [_]
#{})
p/MonadPlus
(-mplus [_ mv mv']
(s/union mv mv'))
p/Printable
(-repr [_]
"#<Set>")))
(util/make-printable (type set-context))
(extend-type #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet)
p/Contextual
(-get-context [_] set-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def function-context
(reify
p/Context
p/Semigroup
(-mappend [ctx f g] (comp f g))
p/Monoid
(-mempty [_] identity)
p/Functor
(-fmap [_ f self]
(comp f self))
p/Applicative
(-pure [_ v]
(constantly v))
(-fapply [_ self av]
(fn [x] ((self x) (av x))))
p/Monad
(-mreturn [_ v]
(constantly v))
(-mbind [_ self f]
(fn [r] ((f (self r)) r)))
p/Printable
(-repr [_]
"#<Function>")))
(util/make-printable (type function-context))
(extend-type #?(:clj clojure.lang.IFn
:cljs cljs.core.IFn)
p/Contextual
(-get-context [_] function-context))
#?(:cljs
(extend-type function
p/Contextual
(-get-context [_] function-context)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monoids
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def any-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(or sv sv'))
p/Monoid
(-mempty [_]
false)
p/Printable
(-repr [_]
"#<Any>")))
(util/make-printable (type any-monoid))
(def all-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(and sv sv'))
p/Monoid
(-mempty [_]
true)
p/Printable
(-repr [_]
"#<All>")))
(util/make-printable (type all-monoid))
(def sum-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(+ sv sv'))
p/Monoid
(-mempty [_]
0)
p/Printable
(-repr [_]
"#<Sum>")))
(util/make-printable (type sum-monoid))
(def prod-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(* sv sv'))
p/Monoid
(-mempty [_]
1)
p/Printable
(-repr [_]
"#<Product>")))
(util/make-printable (type prod-monoid))
(def string-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(str sv sv'))
p/Monoid
(-mempty [_]
"")
p/Printable
(-repr [_]
"#<String>")))
(util/make-printable (type string-monoid))
(extend-type #?(:clj java.lang.String
:cljs string)
p/Contextual
(-get-context [_] string-monoid))
| true | ;; Copyright (c) 2014-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Copyright (c) 2014-2015 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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 cats.builtin
"Clojure(Script) built-in types extensions."
(:require [clojure.set :as s]
[cats.monad.maybe :as maybe]
[cats.protocols :as p]
[cats.context :as ctx]
[cats.core :as m]
[cats.util :as util]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Nil as Nothing of Maybe monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-type nil
p/Contextual
(-get-context [_] maybe/context)
p/Extract
(-extract [_] nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sequence Monad i.e. PersistentList
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv' (reverse sv)))
p/Monoid
(-mempty [_] ())
p/Functor
(-fmap [_ f v]
(loop [[h & t :as c] v
result ()]
(if (empty? c)
(reverse result)
(recur t (cons (f h) result)))))
p/Applicative
(-pure [_ v] (list v))
(-fapply [_ self av]
;; Each function (outer loop) applied to each value (inner loop).
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t
(cons (loop [[h' & t' :as c'] av
result' ()]
(if (empty? c')
result'
(recur t' (cons (h h') result'))))
result))))
;; Note that both `result` & `result'` above are
;; in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/Monad
(-mreturn [_ v]
(list v))
(-mbind [_ self f]
(->> (loop [[h & t :as c] self
result ()]
(if (empty? c)
result
(recur t (cons (f h) result))))
;; Note that `result` above is in reverse order.
;; Conjing elements of %2 into %1 below is done in
;; in reverse order, so final result is correctly
;; ordered.
(reduce #(into %1 %2) ())))
p/MonadZero
(-mzero [_] ())
p/MonadPlus
(-mplus [_ mv mv']
(into mv' (reverse mv)))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure ())
as)))
p/Printable
(-repr [_]
"#<List>")))
(util/make-printable (type sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList
:cljs cljs.core.List)
p/Contextual
(-get-context [_] sequence-context))
(extend-type #?(:clj clojure.lang.PersistentList$EmptyList
:cljs cljs.core.EmptyList)
p/Contextual
(-get-context [_] sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Lazy Sequence Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def lazy-sequence-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(concat sv sv'))
p/Monoid
(-mempty [_]
(lazy-seq []))
p/Functor
(-fmap [_ f v]
(map f v))
p/Applicative
(-pure [_ v]
(lazy-seq [v]))
(-fapply [_ self av]
(for [f self
v av]
(f v)))
p/Monad
(-mreturn [_ v]
(lazy-seq [v]))
(-mbind [_ self f]
(apply concat (map f self)))
p/MonadZero
(-mzero [_]
(lazy-seq []))
p/MonadPlus
(-mplus [_ mv mv']
(concat mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldr ctx
(fn [a acc]
(m/alet [x a
xs acc]
(cons x xs)))
(m/pure (lazy-seq []))
as)))
p/Printable
(-repr [_]
"#<LazySequence>")))
(util/make-printable (type lazy-sequence-context))
(extend-type #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq)
p/Contextual
(-get-context [_] lazy-sequence-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Range
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def range-context
(reify
p/Context
p/Foldable
(-foldr [ctx f z xs]
(let [x (first xs)]
(if (nil? x)
z
(let [xs (rest xs)]
(f x (p/-foldr ctx f z xs))))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Range>")))
(util/make-printable (type range-context))
(extend-type #?(:clj clojure.lang.LongRange
:cljs cljs.core.Range)
p/Contextual
(-get-context [_] range-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Vector Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def vector-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(into sv sv'))
p/Monoid
(-mempty [_]
[])
p/Functor
(-fmap [_ f v]
(vec (map f v)))
p/Applicative
(-pure [_ v]
[v])
(-fapply [_ self av]
(vec (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
[v])
(-mbind [_ self f]
(vec (mapcat f self)))
p/MonadZero
(-mzero [_]
[])
p/MonadPlus
(-mplus [_ mv mv']
(into mv mv'))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z (reverse xs))))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Traversable
(-traverse [ctx f tv]
(let [as (p/-fmap ctx f tv)]
(p/-foldl ctx
(fn [acc a]
(m/alet [x a
xs acc]
(conj xs x)))
(m/pure [])
as)))
p/Printable
(-repr [_]
"#<Vector>")))
(util/make-printable (type vector-context))
(extend-type #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
p/Contextual
(-get-context [_] vector-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Map Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def map-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(merge sv sv'))
p/Monoid
(-mempty [_]
{})
p/Functor
(-fmap [_ f v]
(into {} (map (fn [[key value]] [key (f value)]) v)))
p/Foldable
(-foldr [ctx f z xs]
(letfn [(rf [acc v] (f v acc))]
(reduce rf z xs)))
(-foldl [ctx f z xs]
(reduce f z xs))
p/Printable
(-repr [_]
"#<Map>")))
(util/make-printable (type map-context))
(extend-type #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentHashMap
:cljs cljs.core.PersistentHashMap)
p/Contextual
(-get-context [_] map-context))
(extend-type #?(:clj clojure.lang.PersistentTreeMap
:cljs cljs.core.PersistentTreeMap)
p/Contextual
(-get-context [_] map-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def set-context
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(s/union sv (set sv')))
p/Monoid
(-mempty [_]
#{})
p/Functor
(-fmap [_ f self]
(set (map f self)))
p/Applicative
(-pure [_ v]
#{v})
(-fapply [_ self av]
(set (for [f self
v av]
(f v))))
p/Monad
(-mreturn [_ v]
#{v})
(-mbind [_ self f]
(apply s/union (map f self)))
p/MonadZero
(-mzero [_]
#{})
p/MonadPlus
(-mplus [_ mv mv']
(s/union mv mv'))
p/Printable
(-repr [_]
"#<Set>")))
(util/make-printable (type set-context))
(extend-type #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet)
p/Contextual
(-get-context [_] set-context))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function Monad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def function-context
(reify
p/Context
p/Semigroup
(-mappend [ctx f g] (comp f g))
p/Monoid
(-mempty [_] identity)
p/Functor
(-fmap [_ f self]
(comp f self))
p/Applicative
(-pure [_ v]
(constantly v))
(-fapply [_ self av]
(fn [x] ((self x) (av x))))
p/Monad
(-mreturn [_ v]
(constantly v))
(-mbind [_ self f]
(fn [r] ((f (self r)) r)))
p/Printable
(-repr [_]
"#<Function>")))
(util/make-printable (type function-context))
(extend-type #?(:clj clojure.lang.IFn
:cljs cljs.core.IFn)
p/Contextual
(-get-context [_] function-context))
#?(:cljs
(extend-type function
p/Contextual
(-get-context [_] function-context)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Monoids
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def any-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(or sv sv'))
p/Monoid
(-mempty [_]
false)
p/Printable
(-repr [_]
"#<Any>")))
(util/make-printable (type any-monoid))
(def all-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(and sv sv'))
p/Monoid
(-mempty [_]
true)
p/Printable
(-repr [_]
"#<All>")))
(util/make-printable (type all-monoid))
(def sum-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(+ sv sv'))
p/Monoid
(-mempty [_]
0)
p/Printable
(-repr [_]
"#<Sum>")))
(util/make-printable (type sum-monoid))
(def prod-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(* sv sv'))
p/Monoid
(-mempty [_]
1)
p/Printable
(-repr [_]
"#<Product>")))
(util/make-printable (type prod-monoid))
(def string-monoid
(reify
p/Context
p/Semigroup
(-mappend [_ sv sv']
(str sv sv'))
p/Monoid
(-mempty [_]
"")
p/Printable
(-repr [_]
"#<String>")))
(util/make-printable (type string-monoid))
(extend-type #?(:clj java.lang.String
:cljs string)
p/Contextual
(-get-context [_] string-monoid))
|
[
{
"context": "ually exclusive from --mid)\"]\n [\"-p\" \"--password PASSWORD\" \"The password of the user\"]\n [nil \"--mid MID\"",
"end": 1686,
"score": 0.9958152174949646,
"start": 1678,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": " from --mid)\"]\n [\"-p\" \"--password PASSWORD\" \"The password of the user\"]\n [nil \"--mid MID\" \"The Manetu ID of the call",
"end": 1713,
"score": 0.951754093170166,
"start": 1693,
"tag": "PASSWORD",
"value": "password of the user"
}
] | src/manetu/data_loader/main.clj | ghaskins/data-loader | 0 | ;; Copyright © 2020-2022 Manetu, Inc. All rights reserved
(ns manetu.data-loader.main
(:require [clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[manetu.data-loader.core :as core]
[manetu.data-loader.commands.core :as commands]
[taoensso.timbre :as log]
[clojure.core.match :refer [match]])
(:gen-class))
(defn set-logging
[level]
(log/set-config!
{:level level
:ns-whitelist ["manetu.*"]
:appenders
{:custom
{:enabled? true
:async false
:fn (fn [{:keys [timestamp_ msg_ level] :as data}]
(println (force timestamp_) (string/upper-case (name level)) (force msg_)))}}}))
(def log-levels #{:trace :debug :info :error})
(defn print-loglevels []
(str "[" (string/join ", " (map name log-levels)) "]"))
(def loglevel-description
(str "Select the logging verbosity level from: " (print-loglevels)))
(def modes (into #{} (keys commands/command-map)))
(defn print-modes []
(str "[" (string/join ", " (map name modes)) "]"))
(def mode-description
(str "Select the mode from: " (print-modes)))
(def options
[["-h" "--help"]
["-v" "--version" "Print the version and exit"]
["-u" "--url URL" "The connection URL"
:default "https://portal.manetu.io:443"]
["-t" "--[no-]tls" "Enable/disable TLS (default: enabled)"
:default true]
[nil "--[no-]progress" "Enable/disable progress output (default: enabled)"
:default true]
[nil "--provider SID" "The service-provider"
:default "manetu.com"]
["-e" "--email EMAIL" "The email address of the user to login with (mutually exclusive from --mid)"]
["-p" "--password PASSWORD" "The password of the user"]
[nil "--mid MID" "The Manetu ID of the caller (mutually exclusive from --email/--password)"]
["-l" "--log-level LEVEL" loglevel-description
:default :info
:parse-fn keyword
:validate [log-levels (str "Must be one of " (print-loglevels))]]
[nil "--fatal-errors" "Any sub-operation failure is considered to be an application level failure"
:default false]
[nil "--type TYPE" "The type of data source this CLI represents"
:default "data-loader"]
[nil "--id ID" "The id of the data-source this CLI represents"
:default "535CC6FC-EAF7-4CF3-BA97-24B2406674A7"]
[nil "--class CLASS" "The schemaClass of the data-source this CLI represents"
:default "global"]
["-c" "--concurrency NUM" "The number of parallel requests to issue"
:default 16
:parse-fn #(Integer/parseInt %)
:validate [pos? "Must be a positive integer"]]
["-m" "--mode MODE" mode-description
:default :load-attributes
:parse-fn keyword
:validate [modes (str "Must be one of " (print-modes))]]])
(defn exit [status msg & args]
(do
(apply println msg args)
status))
(defn version [] (str "manetu-data-loader version: v" (System/getProperty "data-loader.version")))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage [(version)
""
"Usage: manetu-data-loader [options] <file.json>"
""
"Options:"
options-summary]))
(defn xor?
"returns 'true' for the logical exclusive-or condition"
[a b]
(match [a b]
[true false] true
[false true] true
[_ _] false))
(defn mutually-exclusive-auth?
[{:keys [email mid]}]
(xor? (some? email) (some? mid)))
(defn has-auth?
[{:keys [email mid]}]
(or (some? email) (some? mid)))
(defn -app
[& args]
(let [{{:keys [help log-level] :as options} :options :keys [arguments errors summary]} (parse-opts args options)]
(cond
help
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(:version options)
(exit 0 (version))
(not (has-auth? options))
(exit -1 "Must specify --email or --mid")
(not (mutually-exclusive-auth? options))
(exit -1 "--email and --mid are mutually exclusive")
(zero? (count arguments))
(exit -1 (usage summary))
:else
(do
(set-logging log-level)
(core/exec options (first arguments))))))
(defn -main
[& args]
(System/exit (apply -app args)))
| 8411 | ;; Copyright © 2020-2022 Manetu, Inc. All rights reserved
(ns manetu.data-loader.main
(:require [clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[manetu.data-loader.core :as core]
[manetu.data-loader.commands.core :as commands]
[taoensso.timbre :as log]
[clojure.core.match :refer [match]])
(:gen-class))
(defn set-logging
[level]
(log/set-config!
{:level level
:ns-whitelist ["manetu.*"]
:appenders
{:custom
{:enabled? true
:async false
:fn (fn [{:keys [timestamp_ msg_ level] :as data}]
(println (force timestamp_) (string/upper-case (name level)) (force msg_)))}}}))
(def log-levels #{:trace :debug :info :error})
(defn print-loglevels []
(str "[" (string/join ", " (map name log-levels)) "]"))
(def loglevel-description
(str "Select the logging verbosity level from: " (print-loglevels)))
(def modes (into #{} (keys commands/command-map)))
(defn print-modes []
(str "[" (string/join ", " (map name modes)) "]"))
(def mode-description
(str "Select the mode from: " (print-modes)))
(def options
[["-h" "--help"]
["-v" "--version" "Print the version and exit"]
["-u" "--url URL" "The connection URL"
:default "https://portal.manetu.io:443"]
["-t" "--[no-]tls" "Enable/disable TLS (default: enabled)"
:default true]
[nil "--[no-]progress" "Enable/disable progress output (default: enabled)"
:default true]
[nil "--provider SID" "The service-provider"
:default "manetu.com"]
["-e" "--email EMAIL" "The email address of the user to login with (mutually exclusive from --mid)"]
["-p" "--password <PASSWORD>" "The <PASSWORD>"]
[nil "--mid MID" "The Manetu ID of the caller (mutually exclusive from --email/--password)"]
["-l" "--log-level LEVEL" loglevel-description
:default :info
:parse-fn keyword
:validate [log-levels (str "Must be one of " (print-loglevels))]]
[nil "--fatal-errors" "Any sub-operation failure is considered to be an application level failure"
:default false]
[nil "--type TYPE" "The type of data source this CLI represents"
:default "data-loader"]
[nil "--id ID" "The id of the data-source this CLI represents"
:default "535CC6FC-EAF7-4CF3-BA97-24B2406674A7"]
[nil "--class CLASS" "The schemaClass of the data-source this CLI represents"
:default "global"]
["-c" "--concurrency NUM" "The number of parallel requests to issue"
:default 16
:parse-fn #(Integer/parseInt %)
:validate [pos? "Must be a positive integer"]]
["-m" "--mode MODE" mode-description
:default :load-attributes
:parse-fn keyword
:validate [modes (str "Must be one of " (print-modes))]]])
(defn exit [status msg & args]
(do
(apply println msg args)
status))
(defn version [] (str "manetu-data-loader version: v" (System/getProperty "data-loader.version")))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage [(version)
""
"Usage: manetu-data-loader [options] <file.json>"
""
"Options:"
options-summary]))
(defn xor?
"returns 'true' for the logical exclusive-or condition"
[a b]
(match [a b]
[true false] true
[false true] true
[_ _] false))
(defn mutually-exclusive-auth?
[{:keys [email mid]}]
(xor? (some? email) (some? mid)))
(defn has-auth?
[{:keys [email mid]}]
(or (some? email) (some? mid)))
(defn -app
[& args]
(let [{{:keys [help log-level] :as options} :options :keys [arguments errors summary]} (parse-opts args options)]
(cond
help
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(:version options)
(exit 0 (version))
(not (has-auth? options))
(exit -1 "Must specify --email or --mid")
(not (mutually-exclusive-auth? options))
(exit -1 "--email and --mid are mutually exclusive")
(zero? (count arguments))
(exit -1 (usage summary))
:else
(do
(set-logging log-level)
(core/exec options (first arguments))))))
(defn -main
[& args]
(System/exit (apply -app args)))
| true | ;; Copyright © 2020-2022 Manetu, Inc. All rights reserved
(ns manetu.data-loader.main
(:require [clojure.tools.cli :refer [parse-opts]]
[clojure.string :as string]
[manetu.data-loader.core :as core]
[manetu.data-loader.commands.core :as commands]
[taoensso.timbre :as log]
[clojure.core.match :refer [match]])
(:gen-class))
(defn set-logging
[level]
(log/set-config!
{:level level
:ns-whitelist ["manetu.*"]
:appenders
{:custom
{:enabled? true
:async false
:fn (fn [{:keys [timestamp_ msg_ level] :as data}]
(println (force timestamp_) (string/upper-case (name level)) (force msg_)))}}}))
(def log-levels #{:trace :debug :info :error})
(defn print-loglevels []
(str "[" (string/join ", " (map name log-levels)) "]"))
(def loglevel-description
(str "Select the logging verbosity level from: " (print-loglevels)))
(def modes (into #{} (keys commands/command-map)))
(defn print-modes []
(str "[" (string/join ", " (map name modes)) "]"))
(def mode-description
(str "Select the mode from: " (print-modes)))
(def options
[["-h" "--help"]
["-v" "--version" "Print the version and exit"]
["-u" "--url URL" "The connection URL"
:default "https://portal.manetu.io:443"]
["-t" "--[no-]tls" "Enable/disable TLS (default: enabled)"
:default true]
[nil "--[no-]progress" "Enable/disable progress output (default: enabled)"
:default true]
[nil "--provider SID" "The service-provider"
:default "manetu.com"]
["-e" "--email EMAIL" "The email address of the user to login with (mutually exclusive from --mid)"]
["-p" "--password PI:PASSWORD:<PASSWORD>END_PI" "The PI:PASSWORD:<PASSWORD>END_PI"]
[nil "--mid MID" "The Manetu ID of the caller (mutually exclusive from --email/--password)"]
["-l" "--log-level LEVEL" loglevel-description
:default :info
:parse-fn keyword
:validate [log-levels (str "Must be one of " (print-loglevels))]]
[nil "--fatal-errors" "Any sub-operation failure is considered to be an application level failure"
:default false]
[nil "--type TYPE" "The type of data source this CLI represents"
:default "data-loader"]
[nil "--id ID" "The id of the data-source this CLI represents"
:default "535CC6FC-EAF7-4CF3-BA97-24B2406674A7"]
[nil "--class CLASS" "The schemaClass of the data-source this CLI represents"
:default "global"]
["-c" "--concurrency NUM" "The number of parallel requests to issue"
:default 16
:parse-fn #(Integer/parseInt %)
:validate [pos? "Must be a positive integer"]]
["-m" "--mode MODE" mode-description
:default :load-attributes
:parse-fn keyword
:validate [modes (str "Must be one of " (print-modes))]]])
(defn exit [status msg & args]
(do
(apply println msg args)
status))
(defn version [] (str "manetu-data-loader version: v" (System/getProperty "data-loader.version")))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage [(version)
""
"Usage: manetu-data-loader [options] <file.json>"
""
"Options:"
options-summary]))
(defn xor?
"returns 'true' for the logical exclusive-or condition"
[a b]
(match [a b]
[true false] true
[false true] true
[_ _] false))
(defn mutually-exclusive-auth?
[{:keys [email mid]}]
(xor? (some? email) (some? mid)))
(defn has-auth?
[{:keys [email mid]}]
(or (some? email) (some? mid)))
(defn -app
[& args]
(let [{{:keys [help log-level] :as options} :options :keys [arguments errors summary]} (parse-opts args options)]
(cond
help
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(:version options)
(exit 0 (version))
(not (has-auth? options))
(exit -1 "Must specify --email or --mid")
(not (mutually-exclusive-auth? options))
(exit -1 "--email and --mid are mutually exclusive")
(zero? (count arguments))
(exit -1 (usage summary))
:else
(do
(set-logging log-level)
(core/exec options (first arguments))))))
(defn -main
[& args]
(System/exit (apply -app args)))
|
[
{
"context": "neric functions implementation\n;;;; Author: mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins",
"end": 256,
"score": 0.9998828172683716,
"start": 245,
"tag": "NAME",
"value": "mikel evins"
},
{
"context": " mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved\n;;;; License: Licensed",
"end": 306,
"score": 0.9998481273651123,
"start": 295,
"tag": "NAME",
"value": "mikel evins"
}
] | 0.2.1/clj/build/classes/xg/categories/functions.clj | mikelevins/categories | 5 | ;;;; ***********************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: functions.clj
;;;; Project: Categories
;;;; Purpose: generic functions implementation
;;;; Author: mikel evins
;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved
;;;; License: Licensed under the Apache License, version 2.0
;;;; See the accompanying file "License" for more information
;;;;
;;;; ***********************************************************************
(ns xg.categories.functions
(:refer-clojure :exclude [type])
(:require xg.categories.utils
xg.categories.structures
xg.categories.types
xg.categories.domains))
(refer 'xg.categories.utils)
(refer 'xg.categories.structures)
(refer 'xg.categories.types)
(refer 'xg.categories.domains)
;;; ======================================================================
;;; Functions
;;; ======================================================================
(def $function-type-tag ::<function>)
(def <method>
(construct-structure-basis
(into {} (map parse-keyspec '(:signature :method-function)))))
(defn method-signature [m] (:signature m))
(defn method-function [m] (:method-function m))
(defn make-method [sig mfun] (make-structure-instance <method> {:signature sig :method-function mfun}))
;;; ======================================================================
;;; Method tables
;;; ======================================================================
(def <method-table>
(construct-structure-basis
(into {} (map parse-keyspec '(:entries)))))
(defn get-method-entries [m] (deref (:entries m)))
(defn make-method-table [] (make-structure-instance <method-table> {:entries (ref {})}))
;;; ======================================================================
;;; Function objects
;;; ======================================================================
(defn function-object [closure]
(:function-object (meta closure)))
(def <function>
(construct-structure-basis
(into {} (map parse-keyspec '(:domain :method-table)))))
(defn get-domain [f] (:domain f))
(defn get-method-table [f] (:method-table f))
(defn add-method! [f m]
(let [fobj (function-object f)]
(if fobj
(let [adder (get-method-adder (get-domain fobj))]
(adder fobj m))
(error "Can't get reflection data for function: %s" f))))
(defn remove-method! [f sig]
(let [fobj (function-object f)]
(if fobj
(let [remover (get-method-remover (get-domain fobj))]
(remover fobj sig))
(error "Can't get reflection data for function: %s" f))))
(defn compute-applicable-methods [fobj args]
(let [selector (get-method-selector (get-domain fobj))]
(selector fobj args)))
(def next-method)
(def other-applicable-methods)
(defn apply-function [fobj args]
(let [methods-obj (compute-applicable-methods fobj args)]
(if methods-obj
(let [effectivem (:effective-method methods-obj)
nextm (:next-method methods-obj)
otherms (:ordered-other-applicable-methods methods-obj)
default-next (fn [& args] (error "No next method"))]
(binding [next-method (if nextm
(method-function nextm)
default-next)
other-applicable-methods (if otherms
(if (empty? otherms)
(list default-next)
(map method-function otherms))
(list default-next))]
(apply (method-function effectivem) args)))
(error "No applicable method: " args))))
(defn make-function [dom]
(let [fobj (make-structure-instance <function>
{:domain dom
:method-table (make-method-table)})
metadata {:type $function-type-tag :function-object fobj}]
(proxy [clojure.lang.IMeta clojure.lang.IFn] []
(invoke [& args] (apply-function fobj args))
(meta [] metadata))))
(defmethod clojure.core/print-method $function-type-tag [o, #^java.io.Writer w]
(.write w (format "#<generic function %s>" (.hashCode o))))
| 13390 | ;;;; ***********************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: functions.clj
;;;; Project: Categories
;;;; Purpose: generic functions implementation
;;;; Author: <NAME>
;;;; Copyright: Copyright 2009 by <NAME>, all rights reserved
;;;; License: Licensed under the Apache License, version 2.0
;;;; See the accompanying file "License" for more information
;;;;
;;;; ***********************************************************************
(ns xg.categories.functions
(:refer-clojure :exclude [type])
(:require xg.categories.utils
xg.categories.structures
xg.categories.types
xg.categories.domains))
(refer 'xg.categories.utils)
(refer 'xg.categories.structures)
(refer 'xg.categories.types)
(refer 'xg.categories.domains)
;;; ======================================================================
;;; Functions
;;; ======================================================================
(def $function-type-tag ::<function>)
(def <method>
(construct-structure-basis
(into {} (map parse-keyspec '(:signature :method-function)))))
(defn method-signature [m] (:signature m))
(defn method-function [m] (:method-function m))
(defn make-method [sig mfun] (make-structure-instance <method> {:signature sig :method-function mfun}))
;;; ======================================================================
;;; Method tables
;;; ======================================================================
(def <method-table>
(construct-structure-basis
(into {} (map parse-keyspec '(:entries)))))
(defn get-method-entries [m] (deref (:entries m)))
(defn make-method-table [] (make-structure-instance <method-table> {:entries (ref {})}))
;;; ======================================================================
;;; Function objects
;;; ======================================================================
(defn function-object [closure]
(:function-object (meta closure)))
(def <function>
(construct-structure-basis
(into {} (map parse-keyspec '(:domain :method-table)))))
(defn get-domain [f] (:domain f))
(defn get-method-table [f] (:method-table f))
(defn add-method! [f m]
(let [fobj (function-object f)]
(if fobj
(let [adder (get-method-adder (get-domain fobj))]
(adder fobj m))
(error "Can't get reflection data for function: %s" f))))
(defn remove-method! [f sig]
(let [fobj (function-object f)]
(if fobj
(let [remover (get-method-remover (get-domain fobj))]
(remover fobj sig))
(error "Can't get reflection data for function: %s" f))))
(defn compute-applicable-methods [fobj args]
(let [selector (get-method-selector (get-domain fobj))]
(selector fobj args)))
(def next-method)
(def other-applicable-methods)
(defn apply-function [fobj args]
(let [methods-obj (compute-applicable-methods fobj args)]
(if methods-obj
(let [effectivem (:effective-method methods-obj)
nextm (:next-method methods-obj)
otherms (:ordered-other-applicable-methods methods-obj)
default-next (fn [& args] (error "No next method"))]
(binding [next-method (if nextm
(method-function nextm)
default-next)
other-applicable-methods (if otherms
(if (empty? otherms)
(list default-next)
(map method-function otherms))
(list default-next))]
(apply (method-function effectivem) args)))
(error "No applicable method: " args))))
(defn make-function [dom]
(let [fobj (make-structure-instance <function>
{:domain dom
:method-table (make-method-table)})
metadata {:type $function-type-tag :function-object fobj}]
(proxy [clojure.lang.IMeta clojure.lang.IFn] []
(invoke [& args] (apply-function fobj args))
(meta [] metadata))))
(defmethod clojure.core/print-method $function-type-tag [o, #^java.io.Writer w]
(.write w (format "#<generic function %s>" (.hashCode o))))
| true | ;;;; ***********************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: functions.clj
;;;; Project: Categories
;;;; Purpose: generic functions implementation
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Copyright: Copyright 2009 by PI:NAME:<NAME>END_PI, all rights reserved
;;;; License: Licensed under the Apache License, version 2.0
;;;; See the accompanying file "License" for more information
;;;;
;;;; ***********************************************************************
(ns xg.categories.functions
(:refer-clojure :exclude [type])
(:require xg.categories.utils
xg.categories.structures
xg.categories.types
xg.categories.domains))
(refer 'xg.categories.utils)
(refer 'xg.categories.structures)
(refer 'xg.categories.types)
(refer 'xg.categories.domains)
;;; ======================================================================
;;; Functions
;;; ======================================================================
(def $function-type-tag ::<function>)
(def <method>
(construct-structure-basis
(into {} (map parse-keyspec '(:signature :method-function)))))
(defn method-signature [m] (:signature m))
(defn method-function [m] (:method-function m))
(defn make-method [sig mfun] (make-structure-instance <method> {:signature sig :method-function mfun}))
;;; ======================================================================
;;; Method tables
;;; ======================================================================
(def <method-table>
(construct-structure-basis
(into {} (map parse-keyspec '(:entries)))))
(defn get-method-entries [m] (deref (:entries m)))
(defn make-method-table [] (make-structure-instance <method-table> {:entries (ref {})}))
;;; ======================================================================
;;; Function objects
;;; ======================================================================
(defn function-object [closure]
(:function-object (meta closure)))
(def <function>
(construct-structure-basis
(into {} (map parse-keyspec '(:domain :method-table)))))
(defn get-domain [f] (:domain f))
(defn get-method-table [f] (:method-table f))
(defn add-method! [f m]
(let [fobj (function-object f)]
(if fobj
(let [adder (get-method-adder (get-domain fobj))]
(adder fobj m))
(error "Can't get reflection data for function: %s" f))))
(defn remove-method! [f sig]
(let [fobj (function-object f)]
(if fobj
(let [remover (get-method-remover (get-domain fobj))]
(remover fobj sig))
(error "Can't get reflection data for function: %s" f))))
(defn compute-applicable-methods [fobj args]
(let [selector (get-method-selector (get-domain fobj))]
(selector fobj args)))
(def next-method)
(def other-applicable-methods)
(defn apply-function [fobj args]
(let [methods-obj (compute-applicable-methods fobj args)]
(if methods-obj
(let [effectivem (:effective-method methods-obj)
nextm (:next-method methods-obj)
otherms (:ordered-other-applicable-methods methods-obj)
default-next (fn [& args] (error "No next method"))]
(binding [next-method (if nextm
(method-function nextm)
default-next)
other-applicable-methods (if otherms
(if (empty? otherms)
(list default-next)
(map method-function otherms))
(list default-next))]
(apply (method-function effectivem) args)))
(error "No applicable method: " args))))
(defn make-function [dom]
(let [fobj (make-structure-instance <function>
{:domain dom
:method-table (make-method-table)})
metadata {:type $function-type-tag :function-object fobj}]
(proxy [clojure.lang.IMeta clojure.lang.IFn] []
(invoke [& args] (apply-function fobj args))
(meta [] metadata))))
(defmethod clojure.core/print-method $function-type-tag [o, #^java.io.Writer w]
(.write w (format "#<generic function %s>" (.hashCode o))))
|
[
{
"context": "/serialize x \"json\" {}) \"json\" {}) x)\n 42\n \"fred\"\n \"ethel\"\n 42.5\n nil\n {\"foo\" [1 2 \"ba",
"end": 341,
"score": 0.9956677556037903,
"start": 337,
"tag": "NAME",
"value": "fred"
},
{
"context": "x \"json\" {}) \"json\" {}) x)\n 42\n \"fred\"\n \"ethel\"\n 42.5\n nil\n {\"foo\" [1 2 \"bar\" nil]}\n ",
"end": 353,
"score": 0.9021716117858887,
"start": 348,
"tag": "NAME",
"value": "ethel"
},
{
"context": "ze x \"json.zip\" {}) \"json.zip\" {}) x)\n 42\n \"fred\"\n \"ethel\"\n 42.5\n nil\n {\"foo\" [1 2 \"ba",
"end": 583,
"score": 0.995651364326477,
"start": 579,
"tag": "NAME",
"value": "fred"
},
{
"context": "zip\" {}) \"json.zip\" {}) x)\n 42\n \"fred\"\n \"ethel\"\n 42.5\n nil\n {\"foo\" [1 2 \"bar\" nil]}\n ",
"end": 595,
"score": 0.9135669469833374,
"start": 590,
"tag": "NAME",
"value": "ethel"
}
] | test/riverford/durable_ref/format/json/cheshire_test.clj | riverford/durable-ref | 72 | (ns riverford.durable-ref.format.json.cheshire-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.format.json.cheshire]
[riverford.durable-ref.core :as dref]))
(deftest test-json-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json" {}) "json" {}) x)
42
"fred"
"ethel"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99)))
(deftest test-fress-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json.zip" {}) "json.zip" {}) x)
42
"fred"
"ethel"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99))) | 87991 | (ns riverford.durable-ref.format.json.cheshire-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.format.json.cheshire]
[riverford.durable-ref.core :as dref]))
(deftest test-json-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json" {}) "json" {}) x)
42
"<NAME>"
"<NAME>"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99)))
(deftest test-fress-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json.zip" {}) "json.zip" {}) x)
42
"<NAME>"
"<NAME>"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99))) | true | (ns riverford.durable-ref.format.json.cheshire-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.format.json.cheshire]
[riverford.durable-ref.core :as dref]))
(deftest test-json-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json" {}) "json" {}) x)
42
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99)))
(deftest test-fress-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "json.zip" {}) "json.zip" {}) x)
42
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
42.5
nil
{"foo" [1 2 "bar" nil]}
[1 2 3]
(range 99))) |
[
{
"context": " (fn [_] {:host \"smtp@example.com\"\n :",
"end": 1958,
"score": 0.9994317889213562,
"start": 1942,
"tag": "EMAIL",
"value": "smtp@example.com"
},
{
"context": " :user \"admin\"\n :",
"end": 2134,
"score": 0.9086141586303711,
"start": 2129,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " :pass \"password\"})\n\n ;; WARNING: This is a fragi",
"end": 2198,
"score": 0.9994774460792542,
"start": 2190,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "(ltu/strip-unwanted-attrs (assoc template :email \"alice@example.org\"))}\n href-create {:description d",
"end": 3305,
"score": 0.9999202489852905,
"start": 3288,
"tag": "EMAIL",
"value": "alice@example.org"
},
{
"context": " :email \"jane@example.org\"\n :re",
"end": 3565,
"score": 0.999901294708252,
"start": 3549,
"tag": "EMAIL",
"value": "jane@example.org"
},
{
"context": " :body (rc/form-encode {:filter \"name!='super'\"}))\n (ltu/body->edn)\n ",
"end": 4219,
"score": 0.9584240317344666,
"start": 4214,
"tag": "USERNAME",
"value": "super"
},
{
"context": " (with-redefs [auth-password/invited-by (fn [_] \"tarzan\")]\n (let [resp (-> sessi",
"end": 5841,
"score": 0.7544123530387878,
"start": 5835,
"tag": "PASSWORD",
"value": "tarzan"
},
{
"context": "fault to username if no :name)\n (is (= \"jane@example.org\" (:name user)))\n\n\n ; 1 identifier is vi",
"end": 7061,
"score": 0.9999154210090637,
"start": 7045,
"tag": "EMAIL",
"value": "jane@example.org"
},
{
"context": " :body (json/write-str {:new-password \"VeryDifficult-1\"}))\n (ltu/body->edn)\n ",
"end": 8007,
"score": 0.9993729591369629,
"start": 7992,
"tag": "PASSWORD",
"value": "VeryDifficult-1"
}
] | code/test/sixsq/nuvla/server/resources/user_email_invitation_lifecycle_test.clj | 0xbase12/api-server | 6 | (ns sixsq.nuvla.server.resources.user-email-invitation-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[ring.util.codec :as codec]
[ring.util.codec :as rc]
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-identifier :as user-identifier]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-invitation :as email-invitation]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context user/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-invitation/resource-url)))
(deftest lifecycle
(let [invitation-link (atom nil)
template-url (str p/service-context user-tpl/resource-type "/" email-invitation/registration-method)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "smtp@example.com"
:port 465
:ssl true
:user "admin"
:pass "password"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*link:\n\n\s+(.*?)\n.*")
second)]
(reset! invitation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [template (-> session-admin
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
href (str user-tpl/resource-type "/" email-invitation/registration-method)
description-attr "description"
tags-attr ["one", "two"]
no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :email "alice@example.org"))}
href-create {:description description-attr
:tags tags-attr
:template {:href href
:email "jane@example.org"
:redirect-url "http://redirect.example.org"}}
invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template")
bad-params-create (assoc-in href-create [:template :invalid] "BAD")]
;; user collection query should succeed but be empty for all users
(doseq [session [session-anon session-user session-admin]]
(-> session
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; create a new user; fails without reference
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with invalid template fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
;; create with bad parameters fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with user anon fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 400))
;; create user
(with-redefs [auth-password/invited-by (fn [_] "tarzan")]
(let [resp (-> session-user
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201))
user-id (ltu/body-resource-id resp)
session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon"))
{email-id :email :as user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))
callback-url (->> @invitation-link
codec/url-decode
(re-matches #".*callback=(.*?)&.*")
second)]
;; verify name attribute (should default to username if no :name)
(is (= "jane@example.org" (:name user)))
; 1 identifier is visible for the created user one for email
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; one email is visible for the user
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 200))
;; check validation of resource
(is (not (nil? @invitation-link)))
(-> session-admin
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-anon
(request callback-url
:request-method :post
:body (json/write-str {:new-password "VeryDifficult-1"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/message-matches
(re-pattern (format "set password for %s successfully executed" user-id))))
(let [{:keys [state]} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))]
(is (= "ACTIVE" state)))
(let [{:keys [validated]} (-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/body))]
(is validated))
;; user can delete his account
(-> session-created-user
(request (str p/service-context user-id)
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 404))))))))
| 89061 | (ns sixsq.nuvla.server.resources.user-email-invitation-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[ring.util.codec :as codec]
[ring.util.codec :as rc]
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-identifier :as user-identifier]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-invitation :as email-invitation]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context user/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-invitation/resource-url)))
(deftest lifecycle
(let [invitation-link (atom nil)
template-url (str p/service-context user-tpl/resource-type "/" email-invitation/registration-method)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "<EMAIL>"
:port 465
:ssl true
:user "admin"
:pass "<PASSWORD>"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*link:\n\n\s+(.*?)\n.*")
second)]
(reset! invitation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [template (-> session-admin
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
href (str user-tpl/resource-type "/" email-invitation/registration-method)
description-attr "description"
tags-attr ["one", "two"]
no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :email "<EMAIL>"))}
href-create {:description description-attr
:tags tags-attr
:template {:href href
:email "<EMAIL>"
:redirect-url "http://redirect.example.org"}}
invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template")
bad-params-create (assoc-in href-create [:template :invalid] "BAD")]
;; user collection query should succeed but be empty for all users
(doseq [session [session-anon session-user session-admin]]
(-> session
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; create a new user; fails without reference
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with invalid template fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
;; create with bad parameters fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with user anon fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 400))
;; create user
(with-redefs [auth-password/invited-by (fn [_] "<PASSWORD>")]
(let [resp (-> session-user
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201))
user-id (ltu/body-resource-id resp)
session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon"))
{email-id :email :as user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))
callback-url (->> @invitation-link
codec/url-decode
(re-matches #".*callback=(.*?)&.*")
second)]
;; verify name attribute (should default to username if no :name)
(is (= "<EMAIL>" (:name user)))
; 1 identifier is visible for the created user one for email
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; one email is visible for the user
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 200))
;; check validation of resource
(is (not (nil? @invitation-link)))
(-> session-admin
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-anon
(request callback-url
:request-method :post
:body (json/write-str {:new-password "<PASSWORD>"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/message-matches
(re-pattern (format "set password for %s successfully executed" user-id))))
(let [{:keys [state]} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))]
(is (= "ACTIVE" state)))
(let [{:keys [validated]} (-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/body))]
(is validated))
;; user can delete his account
(-> session-created-user
(request (str p/service-context user-id)
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 404))))))))
| true | (ns sixsq.nuvla.server.resources.user-email-invitation-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[ring.util.codec :as codec]
[ring.util.codec :as rc]
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-identifier :as user-identifier]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-invitation :as email-invitation]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context user/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists (str user-tpl/resource-type "-" email-invitation/resource-url)))
(deftest lifecycle
(let [invitation-link (atom nil)
template-url (str p/service-context user-tpl/resource-type "/" email-invitation/registration-method)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "PI:EMAIL:<EMAIL>END_PI"
:port 465
:ssl true
:user "admin"
:pass "PI:PASSWORD:<PASSWORD>END_PI"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*link:\n\n\s+(.*?)\n.*")
second)]
(reset! invitation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [template (-> session-admin
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
href (str user-tpl/resource-type "/" email-invitation/registration-method)
description-attr "description"
tags-attr ["one", "two"]
no-href-create {:template (ltu/strip-unwanted-attrs (assoc template :email "PI:EMAIL:<EMAIL>END_PI"))}
href-create {:description description-attr
:tags tags-attr
:template {:href href
:email "PI:EMAIL:<EMAIL>END_PI"
:redirect-url "http://redirect.example.org"}}
invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template")
bad-params-create (assoc-in href-create [:template :invalid] "BAD")]
;; user collection query should succeed but be empty for all users
(doseq [session [session-anon session-user session-admin]]
(-> session
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; create a new user; fails without reference
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with invalid template fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
;; create with bad parameters fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with user anon fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 400))
;; create user
(with-redefs [auth-password/invited-by (fn [_] "PI:PASSWORD:<PASSWORD>END_PI")]
(let [resp (-> session-user
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201))
user-id (ltu/body-resource-id resp)
session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon"))
{email-id :email :as user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))
callback-url (->> @invitation-link
codec/url-decode
(re-matches #".*callback=(.*?)&.*")
second)]
;; verify name attribute (should default to username if no :name)
(is (= "PI:EMAIL:<EMAIL>END_PI" (:name user)))
; 1 identifier is visible for the created user one for email
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; one email is visible for the user
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 200))
;; check validation of resource
(is (not (nil? @invitation-link)))
(-> session-admin
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-anon
(request callback-url
:request-method :post
:body (json/write-str {:new-password "PI:PASSWORD:<PASSWORD>END_PI"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/message-matches
(re-pattern (format "set password for %s successfully executed" user-id))))
(let [{:keys [state]} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))]
(is (= "ACTIVE" state)))
(let [{:keys [validated]} (-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/body))]
(is validated))
;; user can delete his account
(-> session-created-user
(request (str p/service-context user-id)
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-created-user
(request (str p/service-context user-identifier/resource-type))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 404))))))))
|
[
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.9998797178268433,
"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.999931812286377,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | src/promesa/async_cljs.cljc | k13gomez/promesa | 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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 promesa.async-cljs
"core.async like facilities for dealing with asynchronous
callback hell with promises (experimental).
This is a clojurescript version of the macros."
#?(:cljs
(:require-macros [cljs.core.async.impl.ioc-macros :as ioc]))
(:require [promesa.core :as p]
[promesa.protocols :as pt]
#?(:clj [cljs.core.async.impl.ioc-macros :as ioc])
#?@(:cljs [[cljs.core.async.impl.dispatch :as dispatch]
[cljs.core.async.impl.ioc-helpers :as ioc-helpers]])))
#?(:cljs
(defn run-state-machine-wrapped
[state]
(try
(ioc-helpers/run-state-machine state)
(catch :default ex
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject ex)
)))))
#?(:cljs
(defn do-take
[state blk p]
(-> p
(pt/-map (fn [v]
(ioc/aset-all! state ioc-helpers/VALUE-IDX v ioc-helpers/STATE-IDX blk)
(run-state-machine-wrapped state)
v))
(pt/-catch (fn [e]
(if-let [excframes (seq (ioc-helpers/aget-object state ioc-helpers/EXCEPTION-FRAMES))]
(do
(ioc/aset-all! state ioc-helpers/CURRENT-EXCEPTION e)
(ioc-helpers/process-exception state)
(run-state-machine-wrapped state))
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject e))))))
nil))
#?(:cljs
(defn do-return
[state value]
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(resolve value))))
#?(:clj
(def async-terminators
{'promesa.core/await 'promesa.async-cljs/do-take
'await 'promesa.async-cljs/do-take
:Return 'promesa.async-cljs/do-return}))
#?(:clj
(defmacro async
"Asynchronously executes the body, returning immediately to the
calling thread. Additionally, any visible calls to `await` on
promise operations within the body will block (if necessary) by
'parking' the calling thread rather than tying up an OS thread (or
the only JS thread when in ClojureScript). Upon completion of the
operation, the body will be resumed.
Returns a promise which will be resolved with the result of the
body when completed."
[& body]
`(promesa.core/promise
(fn [resolve# reject#]
(cljs.core.async.impl.dispatch/run
(fn []
(let [f# ~(ioc/state-machine body 1 &env async-terminators)
state# (-> (f#)
(ioc/aset-all! cljs.core.async.impl.ioc-helpers/USER-START-IDX [resolve# reject#]))]
(promesa.async-cljs/run-state-machine-wrapped state#))))))))
| 39402 | ;; 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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 promesa.async-cljs
"core.async like facilities for dealing with asynchronous
callback hell with promises (experimental).
This is a clojurescript version of the macros."
#?(:cljs
(:require-macros [cljs.core.async.impl.ioc-macros :as ioc]))
(:require [promesa.core :as p]
[promesa.protocols :as pt]
#?(:clj [cljs.core.async.impl.ioc-macros :as ioc])
#?@(:cljs [[cljs.core.async.impl.dispatch :as dispatch]
[cljs.core.async.impl.ioc-helpers :as ioc-helpers]])))
#?(:cljs
(defn run-state-machine-wrapped
[state]
(try
(ioc-helpers/run-state-machine state)
(catch :default ex
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject ex)
)))))
#?(:cljs
(defn do-take
[state blk p]
(-> p
(pt/-map (fn [v]
(ioc/aset-all! state ioc-helpers/VALUE-IDX v ioc-helpers/STATE-IDX blk)
(run-state-machine-wrapped state)
v))
(pt/-catch (fn [e]
(if-let [excframes (seq (ioc-helpers/aget-object state ioc-helpers/EXCEPTION-FRAMES))]
(do
(ioc/aset-all! state ioc-helpers/CURRENT-EXCEPTION e)
(ioc-helpers/process-exception state)
(run-state-machine-wrapped state))
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject e))))))
nil))
#?(:cljs
(defn do-return
[state value]
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(resolve value))))
#?(:clj
(def async-terminators
{'promesa.core/await 'promesa.async-cljs/do-take
'await 'promesa.async-cljs/do-take
:Return 'promesa.async-cljs/do-return}))
#?(:clj
(defmacro async
"Asynchronously executes the body, returning immediately to the
calling thread. Additionally, any visible calls to `await` on
promise operations within the body will block (if necessary) by
'parking' the calling thread rather than tying up an OS thread (or
the only JS thread when in ClojureScript). Upon completion of the
operation, the body will be resumed.
Returns a promise which will be resolved with the result of the
body when completed."
[& body]
`(promesa.core/promise
(fn [resolve# reject#]
(cljs.core.async.impl.dispatch/run
(fn []
(let [f# ~(ioc/state-machine body 1 &env async-terminators)
state# (-> (f#)
(ioc/aset-all! cljs.core.async.impl.ioc-helpers/USER-START-IDX [resolve# reject#]))]
(promesa.async-cljs/run-state-machine-wrapped state#))))))))
| 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:
;;
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 promesa.async-cljs
"core.async like facilities for dealing with asynchronous
callback hell with promises (experimental).
This is a clojurescript version of the macros."
#?(:cljs
(:require-macros [cljs.core.async.impl.ioc-macros :as ioc]))
(:require [promesa.core :as p]
[promesa.protocols :as pt]
#?(:clj [cljs.core.async.impl.ioc-macros :as ioc])
#?@(:cljs [[cljs.core.async.impl.dispatch :as dispatch]
[cljs.core.async.impl.ioc-helpers :as ioc-helpers]])))
#?(:cljs
(defn run-state-machine-wrapped
[state]
(try
(ioc-helpers/run-state-machine state)
(catch :default ex
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject ex)
)))))
#?(:cljs
(defn do-take
[state blk p]
(-> p
(pt/-map (fn [v]
(ioc/aset-all! state ioc-helpers/VALUE-IDX v ioc-helpers/STATE-IDX blk)
(run-state-machine-wrapped state)
v))
(pt/-catch (fn [e]
(if-let [excframes (seq (ioc-helpers/aget-object state ioc-helpers/EXCEPTION-FRAMES))]
(do
(ioc/aset-all! state ioc-helpers/CURRENT-EXCEPTION e)
(ioc-helpers/process-exception state)
(run-state-machine-wrapped state))
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(reject e))))))
nil))
#?(:cljs
(defn do-return
[state value]
(let [[resolve reject] (ioc-helpers/aget-object state ioc-helpers/USER-START-IDX)]
(resolve value))))
#?(:clj
(def async-terminators
{'promesa.core/await 'promesa.async-cljs/do-take
'await 'promesa.async-cljs/do-take
:Return 'promesa.async-cljs/do-return}))
#?(:clj
(defmacro async
"Asynchronously executes the body, returning immediately to the
calling thread. Additionally, any visible calls to `await` on
promise operations within the body will block (if necessary) by
'parking' the calling thread rather than tying up an OS thread (or
the only JS thread when in ClojureScript). Upon completion of the
operation, the body will be resumed.
Returns a promise which will be resolved with the result of the
body when completed."
[& body]
`(promesa.core/promise
(fn [resolve# reject#]
(cljs.core.async.impl.dispatch/run
(fn []
(let [f# ~(ioc/state-machine body 1 &env async-terminators)
state# (-> (f#)
(ioc/aset-all! cljs.core.async.impl.ioc-helpers/USER-START-IDX [resolve# reject#]))]
(promesa.async-cljs/run-state-machine-wrapped state#))))))))
|
[
{
"context": "query-input/where-expr where-expr ;; \"[?e :name \\\"IVan\\\"]\"\n ;; TODO: us",
"end": 2330,
"score": 0.9934012293815613,
"start": 2326,
"tag": "NAME",
"value": "IVan"
},
{
"context": "dded true}]\n ;; [{:id 1, :attribute :name, :value Ivanov, :transac-id 536870961, :added true}]]\n ;;(print",
"end": 3560,
"score": 0.9991641640663147,
"start": 3554,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "\n(comment\n (def entity [{:db/id 2 :age 25 :name \"Ivan\"}])\n (def entities #{[{:db/id 2 :age 25 :name \"I",
"end": 5382,
"score": 0.99899822473526,
"start": 5378,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "n\"}])\n (def entities #{[{:db/id 2 :age 25 :name \"Ivan\"}] [{:db/id 1 :age 44 :name \"Petr\"}] [{:db/id 3 :",
"end": 5435,
"score": 0.9992494583129883,
"start": 5431,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :age 25 :name \"Ivan\"}] [{:db/id 1 :age 44 :name \"Petr\"}] [{:db/id 3 :player/age 44 :player/event \"Petr\"",
"end": 5469,
"score": 0.99930739402771,
"start": 5465,
"tag": "NAME",
"value": "Petr"
},
{
"context": "{:db/id 7} {:db/id 8} {:db/id 11}], :player/name \"Paul\", :player/team [{:db/id 11} {:db/id 12}]})\n\n\n (h",
"end": 5692,
"score": 0.9995139837265015,
"start": 5688,
"tag": "NAME",
"value": "Paul"
}
] | src/main/app/dashboard/ui/queries/datoms.cljs | replikativ/datahike-frontend | 33 | (ns app.dashboard.ui.queries.datoms
(:require
[taoensso.timbre :as log]
[app.dashboard.mutations.datoms :as dm]
[app.dashboard.helper :as h]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 button b table thead tr th td tbody label textarea]]
[com.fulcrologic.fulcro.mutations :as m]
["material-table" :default MaterialTable]))
(declare Datoms)
;; TODO: Add tests
;; TODO: format code
;; TODO; use Clj-kondo
(defsc QueryInput [this {:query-input/keys [id pull-expr where-expr] :as props}]
{:query [:query-input/id :query-input/pull-expr :query-input/where-expr]
:initial-state (fn [_] {:query-input/id :query-input-init-state
:query-input/where-expr "[?e :name 'IVan']"
:query-input/pull-expr "[(pull ?e [*])]"})
:ident (fn [] [:query-input/id :the-query-input])}
(div :.ui.form
(div :.field
(label "Pull expression:"
;; TODO: try to use this same string preset in the resolver
(let [set-string! (fn [event]
(println "---->" (type event))
(m/set-string! this :query-input/pull-expr :event event))]
(textarea {:value (or pull-expr "[(pull ?e [*])]")
:onChange set-string!
:onPaste set-string!
:rows 1}))))
(div :.field
(label "Where:"
(let [set-string! #(m/set-string! this :query-input/where-expr :event %)]
(textarea {:value (or where-expr "[?e _ _]")
:onPaste set-string!
:onChange set-string!
:rows 2}))))
#_(div
(println "Pull: " pull-expr "type: " (type pull-expr))
(println "Where: " where-expr))
(button :.ui.button
{:onClick
(fn []
(println "after submit: pull-expr " (type pull-expr))
(println "after submit: Where-Expr: " where-expr)
(comp/transact! this [(dm/submit-query-input
{:query-input/target-comp :app.dashboard.ui.queries.datoms/Datoms
:query-input/where-expr where-expr ;; "[?e :name \"IVan\"]"
;; TODO: use the var pull-expr here once we use this same string set in the resolver
:query-input/pull-expr pull-expr})
(comp/get-query Datoms)]))}
"Query!")))
(def ui-query-input (comp/factory QueryInput))
(def mtable (interop/react-factory MaterialTable))
(def title {:eavt "Datoms" :entities "Entities"})
;; TODO: look of QueryInput
(defsc Datoms [this {:datoms/keys [id elements query-input view-type] :as props}]
{:query [:datoms/id :datoms/elements :datoms/view-type
{:datoms/query-input (comp/get-query QueryInput)}]
:initial-state (fn [_] {:datoms/id ":datoms-init-state"
:datoms/elements {}
:datoms/query-input (comp/get-initial-state QueryInput)
:datoms/view-type :eavt})
:ident (fn [] [:datoms/id :the-datoms])
:route-segment ["datoms"]}
;; TODO: Change so that each collection element below is not inside an array. Use spec to enforce this.
;;
;; Expects: [[{:id 1, :attribute :age, :value 31, :transac-id 536870961, :added true}]
;; [{:id 1, :attribute :name, :value Ivanov, :transac-id 536870961, :added true}]]
;;(println "%%%%%%%%% elements: " elements)
(let [stringified-elems (mapv h/clj-to-str (mapv first elements))
columns (reduce into (map #(into #{} (keys %)) stringified-elems))
update-datoms (fn [newData]
(comp/transact! this
[(dm/update-datoms {:datoms/datom (cond
(= view-type :entities)
(js->clj newData)
(= view-type :eavt)
(vec (vals (js->clj newData))))
:datoms/target-comp :app.dashboard.ui.queries.datoms/Datoms
:datoms/view-type view-type})])
(js/Promise.resolve newData))]
(log/info (str "%%%%%%%%% elements-: " stringified-elems))
(log/info (str "***** Columns: " columns))
[(div :.ui.two.column.grid
(div :.row
(ui-query-input query-input)))
(div :.row
(mtable
{:title (view-type title)
:columns (mapv (fn [c] {:title c :field c}) columns)
:data (if (empty? (first stringified-elems))
[]
stringified-elems)
:editable {:onRowAdd (fn [newData]
(update-datoms newData))
:onRowUpdate (fn [newData, oldData]
(update-datoms newData))
;; TODO: on delete
:onRowDelete id}}))]))
(def ui-datoms (comp/factory Datoms))
(comment
(def entity [{:db/id 2 :age 25 :name "Ivan"}])
(def entities #{[{:db/id 2 :age 25 :name "Ivan"}] [{:db/id 1 :age 44 :name "Petr"}] [{:db/id 3 :player/age 44 :player/event "Petr"}]})
(def columns (reduce into (map #(into #{} (keys (first %))) entities)))
(def res {:db/id 10, :player/event [{:db/id 7} {:db/id 8} {:db/id 11}], :player/name "Paul", :player/team [{:db/id 11} {:db/id 12}]})
(h/clj-to-str {:db/id :hlle})
(h/str-to-clj {":db/id" " :hlle" 1 2})
)
| 78737 | (ns app.dashboard.ui.queries.datoms
(:require
[taoensso.timbre :as log]
[app.dashboard.mutations.datoms :as dm]
[app.dashboard.helper :as h]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 button b table thead tr th td tbody label textarea]]
[com.fulcrologic.fulcro.mutations :as m]
["material-table" :default MaterialTable]))
(declare Datoms)
;; TODO: Add tests
;; TODO: format code
;; TODO; use Clj-kondo
(defsc QueryInput [this {:query-input/keys [id pull-expr where-expr] :as props}]
{:query [:query-input/id :query-input/pull-expr :query-input/where-expr]
:initial-state (fn [_] {:query-input/id :query-input-init-state
:query-input/where-expr "[?e :name 'IVan']"
:query-input/pull-expr "[(pull ?e [*])]"})
:ident (fn [] [:query-input/id :the-query-input])}
(div :.ui.form
(div :.field
(label "Pull expression:"
;; TODO: try to use this same string preset in the resolver
(let [set-string! (fn [event]
(println "---->" (type event))
(m/set-string! this :query-input/pull-expr :event event))]
(textarea {:value (or pull-expr "[(pull ?e [*])]")
:onChange set-string!
:onPaste set-string!
:rows 1}))))
(div :.field
(label "Where:"
(let [set-string! #(m/set-string! this :query-input/where-expr :event %)]
(textarea {:value (or where-expr "[?e _ _]")
:onPaste set-string!
:onChange set-string!
:rows 2}))))
#_(div
(println "Pull: " pull-expr "type: " (type pull-expr))
(println "Where: " where-expr))
(button :.ui.button
{:onClick
(fn []
(println "after submit: pull-expr " (type pull-expr))
(println "after submit: Where-Expr: " where-expr)
(comp/transact! this [(dm/submit-query-input
{:query-input/target-comp :app.dashboard.ui.queries.datoms/Datoms
:query-input/where-expr where-expr ;; "[?e :name \"<NAME>\"]"
;; TODO: use the var pull-expr here once we use this same string set in the resolver
:query-input/pull-expr pull-expr})
(comp/get-query Datoms)]))}
"Query!")))
(def ui-query-input (comp/factory QueryInput))
(def mtable (interop/react-factory MaterialTable))
(def title {:eavt "Datoms" :entities "Entities"})
;; TODO: look of QueryInput
(defsc Datoms [this {:datoms/keys [id elements query-input view-type] :as props}]
{:query [:datoms/id :datoms/elements :datoms/view-type
{:datoms/query-input (comp/get-query QueryInput)}]
:initial-state (fn [_] {:datoms/id ":datoms-init-state"
:datoms/elements {}
:datoms/query-input (comp/get-initial-state QueryInput)
:datoms/view-type :eavt})
:ident (fn [] [:datoms/id :the-datoms])
:route-segment ["datoms"]}
;; TODO: Change so that each collection element below is not inside an array. Use spec to enforce this.
;;
;; Expects: [[{:id 1, :attribute :age, :value 31, :transac-id 536870961, :added true}]
;; [{:id 1, :attribute :name, :value <NAME>, :transac-id 536870961, :added true}]]
;;(println "%%%%%%%%% elements: " elements)
(let [stringified-elems (mapv h/clj-to-str (mapv first elements))
columns (reduce into (map #(into #{} (keys %)) stringified-elems))
update-datoms (fn [newData]
(comp/transact! this
[(dm/update-datoms {:datoms/datom (cond
(= view-type :entities)
(js->clj newData)
(= view-type :eavt)
(vec (vals (js->clj newData))))
:datoms/target-comp :app.dashboard.ui.queries.datoms/Datoms
:datoms/view-type view-type})])
(js/Promise.resolve newData))]
(log/info (str "%%%%%%%%% elements-: " stringified-elems))
(log/info (str "***** Columns: " columns))
[(div :.ui.two.column.grid
(div :.row
(ui-query-input query-input)))
(div :.row
(mtable
{:title (view-type title)
:columns (mapv (fn [c] {:title c :field c}) columns)
:data (if (empty? (first stringified-elems))
[]
stringified-elems)
:editable {:onRowAdd (fn [newData]
(update-datoms newData))
:onRowUpdate (fn [newData, oldData]
(update-datoms newData))
;; TODO: on delete
:onRowDelete id}}))]))
(def ui-datoms (comp/factory Datoms))
(comment
(def entity [{:db/id 2 :age 25 :name "<NAME>"}])
(def entities #{[{:db/id 2 :age 25 :name "<NAME>"}] [{:db/id 1 :age 44 :name "<NAME>"}] [{:db/id 3 :player/age 44 :player/event "Petr"}]})
(def columns (reduce into (map #(into #{} (keys (first %))) entities)))
(def res {:db/id 10, :player/event [{:db/id 7} {:db/id 8} {:db/id 11}], :player/name "<NAME>", :player/team [{:db/id 11} {:db/id 12}]})
(h/clj-to-str {:db/id :hlle})
(h/str-to-clj {":db/id" " :hlle" 1 2})
)
| true | (ns app.dashboard.ui.queries.datoms
(:require
[taoensso.timbre :as log]
[app.dashboard.mutations.datoms :as dm]
[app.dashboard.helper :as h]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h3 button b table thead tr th td tbody label textarea]]
[com.fulcrologic.fulcro.mutations :as m]
["material-table" :default MaterialTable]))
(declare Datoms)
;; TODO: Add tests
;; TODO: format code
;; TODO; use Clj-kondo
(defsc QueryInput [this {:query-input/keys [id pull-expr where-expr] :as props}]
{:query [:query-input/id :query-input/pull-expr :query-input/where-expr]
:initial-state (fn [_] {:query-input/id :query-input-init-state
:query-input/where-expr "[?e :name 'IVan']"
:query-input/pull-expr "[(pull ?e [*])]"})
:ident (fn [] [:query-input/id :the-query-input])}
(div :.ui.form
(div :.field
(label "Pull expression:"
;; TODO: try to use this same string preset in the resolver
(let [set-string! (fn [event]
(println "---->" (type event))
(m/set-string! this :query-input/pull-expr :event event))]
(textarea {:value (or pull-expr "[(pull ?e [*])]")
:onChange set-string!
:onPaste set-string!
:rows 1}))))
(div :.field
(label "Where:"
(let [set-string! #(m/set-string! this :query-input/where-expr :event %)]
(textarea {:value (or where-expr "[?e _ _]")
:onPaste set-string!
:onChange set-string!
:rows 2}))))
#_(div
(println "Pull: " pull-expr "type: " (type pull-expr))
(println "Where: " where-expr))
(button :.ui.button
{:onClick
(fn []
(println "after submit: pull-expr " (type pull-expr))
(println "after submit: Where-Expr: " where-expr)
(comp/transact! this [(dm/submit-query-input
{:query-input/target-comp :app.dashboard.ui.queries.datoms/Datoms
:query-input/where-expr where-expr ;; "[?e :name \"PI:NAME:<NAME>END_PI\"]"
;; TODO: use the var pull-expr here once we use this same string set in the resolver
:query-input/pull-expr pull-expr})
(comp/get-query Datoms)]))}
"Query!")))
(def ui-query-input (comp/factory QueryInput))
(def mtable (interop/react-factory MaterialTable))
(def title {:eavt "Datoms" :entities "Entities"})
;; TODO: look of QueryInput
(defsc Datoms [this {:datoms/keys [id elements query-input view-type] :as props}]
{:query [:datoms/id :datoms/elements :datoms/view-type
{:datoms/query-input (comp/get-query QueryInput)}]
:initial-state (fn [_] {:datoms/id ":datoms-init-state"
:datoms/elements {}
:datoms/query-input (comp/get-initial-state QueryInput)
:datoms/view-type :eavt})
:ident (fn [] [:datoms/id :the-datoms])
:route-segment ["datoms"]}
;; TODO: Change so that each collection element below is not inside an array. Use spec to enforce this.
;;
;; Expects: [[{:id 1, :attribute :age, :value 31, :transac-id 536870961, :added true}]
;; [{:id 1, :attribute :name, :value PI:NAME:<NAME>END_PI, :transac-id 536870961, :added true}]]
;;(println "%%%%%%%%% elements: " elements)
(let [stringified-elems (mapv h/clj-to-str (mapv first elements))
columns (reduce into (map #(into #{} (keys %)) stringified-elems))
update-datoms (fn [newData]
(comp/transact! this
[(dm/update-datoms {:datoms/datom (cond
(= view-type :entities)
(js->clj newData)
(= view-type :eavt)
(vec (vals (js->clj newData))))
:datoms/target-comp :app.dashboard.ui.queries.datoms/Datoms
:datoms/view-type view-type})])
(js/Promise.resolve newData))]
(log/info (str "%%%%%%%%% elements-: " stringified-elems))
(log/info (str "***** Columns: " columns))
[(div :.ui.two.column.grid
(div :.row
(ui-query-input query-input)))
(div :.row
(mtable
{:title (view-type title)
:columns (mapv (fn [c] {:title c :field c}) columns)
:data (if (empty? (first stringified-elems))
[]
stringified-elems)
:editable {:onRowAdd (fn [newData]
(update-datoms newData))
:onRowUpdate (fn [newData, oldData]
(update-datoms newData))
;; TODO: on delete
:onRowDelete id}}))]))
(def ui-datoms (comp/factory Datoms))
(comment
(def entity [{:db/id 2 :age 25 :name "PI:NAME:<NAME>END_PI"}])
(def entities #{[{:db/id 2 :age 25 :name "PI:NAME:<NAME>END_PI"}] [{:db/id 1 :age 44 :name "PI:NAME:<NAME>END_PI"}] [{:db/id 3 :player/age 44 :player/event "Petr"}]})
(def columns (reduce into (map #(into #{} (keys (first %))) entities)))
(def res {:db/id 10, :player/event [{:db/id 7} {:db/id 8} {:db/id 11}], :player/name "PI:NAME:<NAME>END_PI", :player/team [{:db/id 11} {:db/id 12}]})
(h/clj-to-str {:db/id :hlle})
(h/str-to-clj {":db/id" " :hlle" 1 2})
)
|
[
{
"context": "; Copyright (c) Christophe Grand. All rights reserved.\n; The use and distributio",
"end": 34,
"score": 0.9998648762702942,
"start": 18,
"tag": "NAME",
"value": "Christophe Grand"
}
] | server/target/net/cgrand/parsley/demo.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.
;; THIS FILE IS OUT OF DATE
(ns net.cgrand.parsley.demo
(:use net.cgrand.parsley :reload-all)
(:require [net.cgrand.parsley.internal :as core]))
;; TRY AT YOUR OWN RISK :-)
(def simple-lisp
(grammar {:space [" "+]
:main [:expr* eof]}
:eot- (with #{(one-of "()") eof})
:expr #{:symbol ["(" :expr* ")"] :nil}
:nil (token "nil" :eot)
:symbol (token (but :nil) {\a \z \A \Z \- \-} {\a \z \A \Z \0 \9 \- \-}*)))
(-> simple-lisp (step "a") count)
(defmulti str-op first)
(defn str-ops [ops] (apply str (interpose " " (map str-op ops))))
(defmethod str-op :default [[op]] (str"?" (class op) "?"))
(defmethod str-op core/op-cat [[_ & xs]] (str "[" (str-ops xs) "]"))
(defmethod str-op core/op-alt [[_ & xs]] (str "#{" (apply str (interpose ", " (map str-op xs))) "}"))
(defmethod str-op core/op-string [[_ s]] (pr-str s))
(defmethod str-op core/op-repeat [[_ op]] (str (str-op op) "*"))
(defmethod str-op core/op-lookahead [[_ & ops]] (str "(with " (str-ops ops) ")"))
(defmethod str-op core/op-negative-lookahead [[_ & ops]] (str "(but " (str-ops ops) ")"))
;(doseq [[_ _ x] (reduce step clojure-parser (take 10 selfs))] (println (str-ops x)))
(defn copy [x] (-> (java.awt.Toolkit/getDefaultToolkit) .getSystemClipboard (.setContents (java.awt.datatransfer.StringSelection. (str x)) nil)))
(defn str-cont [[_ _ cont]] (str-ops cont))
(defn str-conts [x] (map str-cont x))
(defn prn-conts [xs]
(doseq [x xs] (println (str-cont x))))
(require '[net.cgrand.parsley.glr :as core])
(use 'net.cgrand.parsley :reload-all)
(def sexp
(grammar {:space :whitespace?
:main [:expr*]}
:expr- #{:atom :list :vector :set :map}
:atom (token {\a \z \A \Z \- \- \0 \9 \. \.}+ (?! {\a \z \A \Z \- \- \0 \9 \. \.}))
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:set ["#{" :expr* "}"]
:map ["{" :expr* "}"]
:whitespace (token #{\space \tab \newline}+ (?! #{\space \tab \newline}))))
(def table (apply core/lr-table sexp))
(def sop [[(list 0) () nil]])
(defn bench[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) count))))
(defn bench2[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) first second (core/read-events s)))))
(-> sop (core/step table "hello"))
(def g
(grammar {:space [#{:white-space #_:comment :discard}*]
:main [:expr*]}
:terminating-macro- (one-of "\";']^`~()[]{}\\%")
:macro- #{:terminating-macro (one-of "@#")}
:space- (one-of " \t\n\r,")
:token- (token {\a \z}+ (?= #{:terminating-macro :space $}))
:white-space (token :space+ (?! :space))
;:comment (token #{";" "#!"} (not-one-of "\n")*)
:discard ["#_" :expr]
:expr #{:list :vector :map :set :fn
:meta :with-meta :quote :syntax-quote :unquote :unquote-splice
:regex :string :number :keyword :symbol #_:nil #_:boolean :char}
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:map ["{" [:expr :expr]* "}"]
:set ["#{" :expr* "}"]
:fn ["#(" :expr* ")"]
:meta ["^" :expr]
:with-meta ["#^" :expr :expr]
:quote ["'" :expr]
:syntax-quote ["`" :expr]
:unquote ["~" :expr]
:unquote-splice ["~@" :expr]
:deref ["@" :expr]
:var ["#'" :expr]
; :nil (token "nil" (?! :token-char))
; :boolean (token #{"true" "false"} (?! :token-char))
;; todo: refine these terminals
:char (token \\ any-char)
#_(
:namespace- (token (not-one-of "/" {\0 \9}) :token-char*? "/")
:name- (token (not-one-of "/" {\0 \9}) [(?! "/") :token-char]*)
:symbol (token
#{["%" :token-char*]
["%&"]
["/" (?! :token-char)]
["clojure.core//" (?! :token-char)]
[(?! :macro :nil :boolean ":") :namespace? :name]})
:keyword (token (?= ":") :namespace? :name)
)
:keyword (token \: :token)
:symbol (token :token)
:number (token {\0 \9}+)
#_(
:string (token \" #{[(?! \" \\) any-char] [\\ any-char]}* \")
:regex (token "#\"" #{[(?! \" \\) any-char] [\\ any-char]}* \")
)
:string (token \" {\a \z}* \")
:regex (token "#\"" {\a \z}* \")))
(def table (apply core/lr-table g))
(def ttable (first table))
(def sop [[[(second table)] [] nil]])
(def red (memoize (fn [n] (if (neg? n) clojure-parser (-> (red (dec n)) (step (nth selfs n)))))))
(def test-comment
(grammar {:main :expr* :space [(one-of " \t\n\r,")+]}
:expr [:line :comment]
:line [[(but ";") {\a \z}]*]
:comment (token ";" [(but "\n") any-char]*)))
(-> test-comment (step "a ;b\nc;d") (step nil) results (->> (map #(apply str (e/emit* %)))))
(defn find-error [s g]
(loop [seen [] s s p g]
(if (empty? p)
(apply str seen)
(when-let [[c & s] (seq s)]
(recur (conj seen c) s (step p (str c)))))))
if (and (seq s) (-> f (step s) count zero?))
(let [i (quot (count s) 2)
s1 (subs s 0 i)
s2 (subs s i)
]
(if (-> f (step s1) count zero?)
;; helper functions to display results in a more readable way
(defn terse-result [items]
(map (fn self [item]
(if (map? item)
(cons (:tag item) (map self (:content item)))
item)) items))
(defn prn-terse [results]
(doseq [result results]
(prn (terse-result result))))
;; let's parse this snippet
(-> simple-lisp (step "()(hello)") (step nil) results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; let's parse this snippet in two steps
(-> simple-lisp (step "()(hel") (step "lo)") eof results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; and now, the incremental parsing!
(let [c1 (-> simple-lisp reset (step "()(hel"))
c2 (-> c1 reset (step "lo)" nil))
_ (-> (stitch c1 c2) eof results prn-terse) ; business as usual
c1b (-> simple-lisp reset (step "(bonjour)(hel")) ; an updated 1st chunk
_ (-> (stitch c1b c2) eof results prn-terse)
c1t (-> simple-lisp reset (step "(bonjour hel")) ; an updated 1st chunk
_ (-> (stitch c1t c2) eof results prn-terse)]
nil)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) ")") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) (:w " ") (:expr (:symbol "hello")) ")")))
| 122568 | ; 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.
;; THIS FILE IS OUT OF DATE
(ns net.cgrand.parsley.demo
(:use net.cgrand.parsley :reload-all)
(:require [net.cgrand.parsley.internal :as core]))
;; TRY AT YOUR OWN RISK :-)
(def simple-lisp
(grammar {:space [" "+]
:main [:expr* eof]}
:eot- (with #{(one-of "()") eof})
:expr #{:symbol ["(" :expr* ")"] :nil}
:nil (token "nil" :eot)
:symbol (token (but :nil) {\a \z \A \Z \- \-} {\a \z \A \Z \0 \9 \- \-}*)))
(-> simple-lisp (step "a") count)
(defmulti str-op first)
(defn str-ops [ops] (apply str (interpose " " (map str-op ops))))
(defmethod str-op :default [[op]] (str"?" (class op) "?"))
(defmethod str-op core/op-cat [[_ & xs]] (str "[" (str-ops xs) "]"))
(defmethod str-op core/op-alt [[_ & xs]] (str "#{" (apply str (interpose ", " (map str-op xs))) "}"))
(defmethod str-op core/op-string [[_ s]] (pr-str s))
(defmethod str-op core/op-repeat [[_ op]] (str (str-op op) "*"))
(defmethod str-op core/op-lookahead [[_ & ops]] (str "(with " (str-ops ops) ")"))
(defmethod str-op core/op-negative-lookahead [[_ & ops]] (str "(but " (str-ops ops) ")"))
;(doseq [[_ _ x] (reduce step clojure-parser (take 10 selfs))] (println (str-ops x)))
(defn copy [x] (-> (java.awt.Toolkit/getDefaultToolkit) .getSystemClipboard (.setContents (java.awt.datatransfer.StringSelection. (str x)) nil)))
(defn str-cont [[_ _ cont]] (str-ops cont))
(defn str-conts [x] (map str-cont x))
(defn prn-conts [xs]
(doseq [x xs] (println (str-cont x))))
(require '[net.cgrand.parsley.glr :as core])
(use 'net.cgrand.parsley :reload-all)
(def sexp
(grammar {:space :whitespace?
:main [:expr*]}
:expr- #{:atom :list :vector :set :map}
:atom (token {\a \z \A \Z \- \- \0 \9 \. \.}+ (?! {\a \z \A \Z \- \- \0 \9 \. \.}))
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:set ["#{" :expr* "}"]
:map ["{" :expr* "}"]
:whitespace (token #{\space \tab \newline}+ (?! #{\space \tab \newline}))))
(def table (apply core/lr-table sexp))
(def sop [[(list 0) () nil]])
(defn bench[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) count))))
(defn bench2[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) first second (core/read-events s)))))
(-> sop (core/step table "hello"))
(def g
(grammar {:space [#{:white-space #_:comment :discard}*]
:main [:expr*]}
:terminating-macro- (one-of "\";']^`~()[]{}\\%")
:macro- #{:terminating-macro (one-of "@#")}
:space- (one-of " \t\n\r,")
:token- (token {\a \z}+ (?= #{:terminating-macro :space $}))
:white-space (token :space+ (?! :space))
;:comment (token #{";" "#!"} (not-one-of "\n")*)
:discard ["#_" :expr]
:expr #{:list :vector :map :set :fn
:meta :with-meta :quote :syntax-quote :unquote :unquote-splice
:regex :string :number :keyword :symbol #_:nil #_:boolean :char}
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:map ["{" [:expr :expr]* "}"]
:set ["#{" :expr* "}"]
:fn ["#(" :expr* ")"]
:meta ["^" :expr]
:with-meta ["#^" :expr :expr]
:quote ["'" :expr]
:syntax-quote ["`" :expr]
:unquote ["~" :expr]
:unquote-splice ["~@" :expr]
:deref ["@" :expr]
:var ["#'" :expr]
; :nil (token "nil" (?! :token-char))
; :boolean (token #{"true" "false"} (?! :token-char))
;; todo: refine these terminals
:char (token \\ any-char)
#_(
:namespace- (token (not-one-of "/" {\0 \9}) :token-char*? "/")
:name- (token (not-one-of "/" {\0 \9}) [(?! "/") :token-char]*)
:symbol (token
#{["%" :token-char*]
["%&"]
["/" (?! :token-char)]
["clojure.core//" (?! :token-char)]
[(?! :macro :nil :boolean ":") :namespace? :name]})
:keyword (token (?= ":") :namespace? :name)
)
:keyword (token \: :token)
:symbol (token :token)
:number (token {\0 \9}+)
#_(
:string (token \" #{[(?! \" \\) any-char] [\\ any-char]}* \")
:regex (token "#\"" #{[(?! \" \\) any-char] [\\ any-char]}* \")
)
:string (token \" {\a \z}* \")
:regex (token "#\"" {\a \z}* \")))
(def table (apply core/lr-table g))
(def ttable (first table))
(def sop [[[(second table)] [] nil]])
(def red (memoize (fn [n] (if (neg? n) clojure-parser (-> (red (dec n)) (step (nth selfs n)))))))
(def test-comment
(grammar {:main :expr* :space [(one-of " \t\n\r,")+]}
:expr [:line :comment]
:line [[(but ";") {\a \z}]*]
:comment (token ";" [(but "\n") any-char]*)))
(-> test-comment (step "a ;b\nc;d") (step nil) results (->> (map #(apply str (e/emit* %)))))
(defn find-error [s g]
(loop [seen [] s s p g]
(if (empty? p)
(apply str seen)
(when-let [[c & s] (seq s)]
(recur (conj seen c) s (step p (str c)))))))
if (and (seq s) (-> f (step s) count zero?))
(let [i (quot (count s) 2)
s1 (subs s 0 i)
s2 (subs s i)
]
(if (-> f (step s1) count zero?)
;; helper functions to display results in a more readable way
(defn terse-result [items]
(map (fn self [item]
(if (map? item)
(cons (:tag item) (map self (:content item)))
item)) items))
(defn prn-terse [results]
(doseq [result results]
(prn (terse-result result))))
;; let's parse this snippet
(-> simple-lisp (step "()(hello)") (step nil) results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; let's parse this snippet in two steps
(-> simple-lisp (step "()(hel") (step "lo)") eof results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; and now, the incremental parsing!
(let [c1 (-> simple-lisp reset (step "()(hel"))
c2 (-> c1 reset (step "lo)" nil))
_ (-> (stitch c1 c2) eof results prn-terse) ; business as usual
c1b (-> simple-lisp reset (step "(bonjour)(hel")) ; an updated 1st chunk
_ (-> (stitch c1b c2) eof results prn-terse)
c1t (-> simple-lisp reset (step "(bonjour hel")) ; an updated 1st chunk
_ (-> (stitch c1t c2) eof results prn-terse)]
nil)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) ")") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) (:w " ") (:expr (:symbol "hello")) ")")))
| 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.
;; THIS FILE IS OUT OF DATE
(ns net.cgrand.parsley.demo
(:use net.cgrand.parsley :reload-all)
(:require [net.cgrand.parsley.internal :as core]))
;; TRY AT YOUR OWN RISK :-)
(def simple-lisp
(grammar {:space [" "+]
:main [:expr* eof]}
:eot- (with #{(one-of "()") eof})
:expr #{:symbol ["(" :expr* ")"] :nil}
:nil (token "nil" :eot)
:symbol (token (but :nil) {\a \z \A \Z \- \-} {\a \z \A \Z \0 \9 \- \-}*)))
(-> simple-lisp (step "a") count)
(defmulti str-op first)
(defn str-ops [ops] (apply str (interpose " " (map str-op ops))))
(defmethod str-op :default [[op]] (str"?" (class op) "?"))
(defmethod str-op core/op-cat [[_ & xs]] (str "[" (str-ops xs) "]"))
(defmethod str-op core/op-alt [[_ & xs]] (str "#{" (apply str (interpose ", " (map str-op xs))) "}"))
(defmethod str-op core/op-string [[_ s]] (pr-str s))
(defmethod str-op core/op-repeat [[_ op]] (str (str-op op) "*"))
(defmethod str-op core/op-lookahead [[_ & ops]] (str "(with " (str-ops ops) ")"))
(defmethod str-op core/op-negative-lookahead [[_ & ops]] (str "(but " (str-ops ops) ")"))
;(doseq [[_ _ x] (reduce step clojure-parser (take 10 selfs))] (println (str-ops x)))
(defn copy [x] (-> (java.awt.Toolkit/getDefaultToolkit) .getSystemClipboard (.setContents (java.awt.datatransfer.StringSelection. (str x)) nil)))
(defn str-cont [[_ _ cont]] (str-ops cont))
(defn str-conts [x] (map str-cont x))
(defn prn-conts [xs]
(doseq [x xs] (println (str-cont x))))
(require '[net.cgrand.parsley.glr :as core])
(use 'net.cgrand.parsley :reload-all)
(def sexp
(grammar {:space :whitespace?
:main [:expr*]}
:expr- #{:atom :list :vector :set :map}
:atom (token {\a \z \A \Z \- \- \0 \9 \. \.}+ (?! {\a \z \A \Z \- \- \0 \9 \. \.}))
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:set ["#{" :expr* "}"]
:map ["{" :expr* "}"]
:whitespace (token #{\space \tab \newline}+ (?! #{\space \tab \newline}))))
(def table (apply core/lr-table sexp))
(def sop [[(list 0) () nil]])
(defn bench[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) count))))
(defn bench2[n]
(let [s "(defn fast-tables [table]
(let [fast-rows (map fast-row table)]
[(to-array (map first fast-rows))
(to-array (map second fast-rows))]))"
s (apply str (repeat n s))]
(println "parsing" (count s) "chars")
(time (-> sop (core/step table s) first second (core/read-events s)))))
(-> sop (core/step table "hello"))
(def g
(grammar {:space [#{:white-space #_:comment :discard}*]
:main [:expr*]}
:terminating-macro- (one-of "\";']^`~()[]{}\\%")
:macro- #{:terminating-macro (one-of "@#")}
:space- (one-of " \t\n\r,")
:token- (token {\a \z}+ (?= #{:terminating-macro :space $}))
:white-space (token :space+ (?! :space))
;:comment (token #{";" "#!"} (not-one-of "\n")*)
:discard ["#_" :expr]
:expr #{:list :vector :map :set :fn
:meta :with-meta :quote :syntax-quote :unquote :unquote-splice
:regex :string :number :keyword :symbol #_:nil #_:boolean :char}
:list ["(" :expr* ")"]
:vector ["[" :expr* "]"]
:map ["{" [:expr :expr]* "}"]
:set ["#{" :expr* "}"]
:fn ["#(" :expr* ")"]
:meta ["^" :expr]
:with-meta ["#^" :expr :expr]
:quote ["'" :expr]
:syntax-quote ["`" :expr]
:unquote ["~" :expr]
:unquote-splice ["~@" :expr]
:deref ["@" :expr]
:var ["#'" :expr]
; :nil (token "nil" (?! :token-char))
; :boolean (token #{"true" "false"} (?! :token-char))
;; todo: refine these terminals
:char (token \\ any-char)
#_(
:namespace- (token (not-one-of "/" {\0 \9}) :token-char*? "/")
:name- (token (not-one-of "/" {\0 \9}) [(?! "/") :token-char]*)
:symbol (token
#{["%" :token-char*]
["%&"]
["/" (?! :token-char)]
["clojure.core//" (?! :token-char)]
[(?! :macro :nil :boolean ":") :namespace? :name]})
:keyword (token (?= ":") :namespace? :name)
)
:keyword (token \: :token)
:symbol (token :token)
:number (token {\0 \9}+)
#_(
:string (token \" #{[(?! \" \\) any-char] [\\ any-char]}* \")
:regex (token "#\"" #{[(?! \" \\) any-char] [\\ any-char]}* \")
)
:string (token \" {\a \z}* \")
:regex (token "#\"" {\a \z}* \")))
(def table (apply core/lr-table g))
(def ttable (first table))
(def sop [[[(second table)] [] nil]])
(def red (memoize (fn [n] (if (neg? n) clojure-parser (-> (red (dec n)) (step (nth selfs n)))))))
(def test-comment
(grammar {:main :expr* :space [(one-of " \t\n\r,")+]}
:expr [:line :comment]
:line [[(but ";") {\a \z}]*]
:comment (token ";" [(but "\n") any-char]*)))
(-> test-comment (step "a ;b\nc;d") (step nil) results (->> (map #(apply str (e/emit* %)))))
(defn find-error [s g]
(loop [seen [] s s p g]
(if (empty? p)
(apply str seen)
(when-let [[c & s] (seq s)]
(recur (conj seen c) s (step p (str c)))))))
if (and (seq s) (-> f (step s) count zero?))
(let [i (quot (count s) 2)
s1 (subs s 0 i)
s2 (subs s i)
]
(if (-> f (step s1) count zero?)
;; helper functions to display results in a more readable way
(defn terse-result [items]
(map (fn self [item]
(if (map? item)
(cons (:tag item) (map self (:content item)))
item)) items))
(defn prn-terse [results]
(doseq [result results]
(prn (terse-result result))))
;; let's parse this snippet
(-> simple-lisp (step "()(hello)") (step nil) results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; let's parse this snippet in two steps
(-> simple-lisp (step "()(hel") (step "lo)") eof results prn-terse)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;; and now, the incremental parsing!
(let [c1 (-> simple-lisp reset (step "()(hel"))
c2 (-> c1 reset (step "lo)" nil))
_ (-> (stitch c1 c2) eof results prn-terse) ; business as usual
c1b (-> simple-lisp reset (step "(bonjour)(hel")) ; an updated 1st chunk
_ (-> (stitch c1b c2) eof results prn-terse)
c1t (-> simple-lisp reset (step "(bonjour hel")) ; an updated 1st chunk
_ (-> (stitch c1t c2) eof results prn-terse)]
nil)
;;> ((:main (:expr "()") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) ")") (:expr "(" (:expr (:symbol "hello")) ")")))
;;> ((:main (:expr "(" (:expr (:symbol "bonjour")) (:w " ") (:expr (:symbol "hello")) ")")))
|
[
{
"context": "urians Slack\"]\n [:a {:href \"mailto:crux@juxt.pro\" :target \"_blank\"} \"Email Support\"]]]]]\n ",
"end": 3327,
"score": 0.9999264478683472,
"start": 3314,
"tag": "EMAIL",
"value": "crux@juxt.pro"
}
] | crux-http-server/src/crux/http_server/util.clj | tolitius/crux | 0 | (ns crux.http-server.util
(:require [crux.io :as cio]
[crux.api :as api]
[cognitect.transit :as transit]
[hiccup2.core :as hiccup2])
(:import [crux.api ICruxAPI ICruxDatasource]
java.time.format.DateTimeFormatter
java.net.URLEncoder
java.util.Date))
(def ^DateTimeFormatter default-date-formatter
(DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS"))
(defn db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}]
(cond
(and valid-time transact-time)
(.db crux-node valid-time transact-time)
valid-time
(.db crux-node valid-time)
;; TODO: This could also be an error, depending how you see it,
;; not supported via the Java API itself.
transact-time
(.db crux-node (cio/next-monotonic-date) transact-time)
:else
(.db crux-node)))
(defn raw-html [{:keys [body title options results]}]
(let [latest-completed-tx (api/latest-completed-tx (:crux-node options))]
(str (hiccup2/html
[:html
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}]
[:meta
{:name "viewport"
:content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}]
[:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}]
(when options [:meta {:title "options" :content (pr-str {:node-options (:node-options options)
:latest-completed-tx latest-completed-tx})}])
(when results [:meta {:title "results" :content (str results)}])
[:link {:rel "stylesheet" :href "/css/all.css"}]
[:link {:rel "stylesheet" :href "/latofonts.css"}]
[:link {:rel "stylesheet" :href "/css/table.css"}]
[:link {:rel "stylesheet" :href "/css/react-datetime.css"}]
[:link {:rel "stylesheet" :href "/css/codemirror.css"}]
[:link {:rel "stylesheet"
:href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}]
[:title "Crux Console"]]
[:body
[:nav.header
[:div.crux-logo
[:a {:href "/_crux/index"}
[:img.crux-logo__img {:src "/crux-horizontal-bw.svg.png" }]]]
[:span.mobile-hidden
[:b (when-let [label (get-in options [:node-options :crux.http-server/label])]
(format "\"%s\"" label))]]
[:div.header__links
[:a.header__link {:href "/_crux/query"} "Query"]
[:a.header__link {:href "/_crux/status"} "Status"]
[:div.header-dropdown
[:button.header-dropdown__button
"Help"
[:i.fa.fa-caret-down]]
[:div.header-dropdown__links
[:a {:href "https://opencrux.com/reference" :target "_blank"} "Documentation"]
[:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux" :target "_blank"} "Zulip Chat"]
;; [:a {:href "https://clojurians.slack.com/messages/crux" :target "_blank"} "Clojurians Slack"]
[:a {:href "mailto:crux@juxt.pro" :target "_blank"} "Email Support"]]]]]
[:div.console
[:div#app
[:div.container.page-pane body]]]
[:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
(defn entity-link [eid {:keys [valid-time transaction-time]}]
(let [encoded-eid (URLEncoder/encode (pr-str eid) "UTF-8")
query-params (format "?eid=%s&valid-time=%s&transaction-time=%s"
encoded-eid
(.toInstant ^Date valid-time)
(.toInstant ^Date transaction-time))]
(str "/_crux/entity" query-params)))
| 58257 | (ns crux.http-server.util
(:require [crux.io :as cio]
[crux.api :as api]
[cognitect.transit :as transit]
[hiccup2.core :as hiccup2])
(:import [crux.api ICruxAPI ICruxDatasource]
java.time.format.DateTimeFormatter
java.net.URLEncoder
java.util.Date))
(def ^DateTimeFormatter default-date-formatter
(DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS"))
(defn db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}]
(cond
(and valid-time transact-time)
(.db crux-node valid-time transact-time)
valid-time
(.db crux-node valid-time)
;; TODO: This could also be an error, depending how you see it,
;; not supported via the Java API itself.
transact-time
(.db crux-node (cio/next-monotonic-date) transact-time)
:else
(.db crux-node)))
(defn raw-html [{:keys [body title options results]}]
(let [latest-completed-tx (api/latest-completed-tx (:crux-node options))]
(str (hiccup2/html
[:html
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}]
[:meta
{:name "viewport"
:content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}]
[:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}]
(when options [:meta {:title "options" :content (pr-str {:node-options (:node-options options)
:latest-completed-tx latest-completed-tx})}])
(when results [:meta {:title "results" :content (str results)}])
[:link {:rel "stylesheet" :href "/css/all.css"}]
[:link {:rel "stylesheet" :href "/latofonts.css"}]
[:link {:rel "stylesheet" :href "/css/table.css"}]
[:link {:rel "stylesheet" :href "/css/react-datetime.css"}]
[:link {:rel "stylesheet" :href "/css/codemirror.css"}]
[:link {:rel "stylesheet"
:href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}]
[:title "Crux Console"]]
[:body
[:nav.header
[:div.crux-logo
[:a {:href "/_crux/index"}
[:img.crux-logo__img {:src "/crux-horizontal-bw.svg.png" }]]]
[:span.mobile-hidden
[:b (when-let [label (get-in options [:node-options :crux.http-server/label])]
(format "\"%s\"" label))]]
[:div.header__links
[:a.header__link {:href "/_crux/query"} "Query"]
[:a.header__link {:href "/_crux/status"} "Status"]
[:div.header-dropdown
[:button.header-dropdown__button
"Help"
[:i.fa.fa-caret-down]]
[:div.header-dropdown__links
[:a {:href "https://opencrux.com/reference" :target "_blank"} "Documentation"]
[:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux" :target "_blank"} "Zulip Chat"]
;; [:a {:href "https://clojurians.slack.com/messages/crux" :target "_blank"} "Clojurians Slack"]
[:a {:href "mailto:<EMAIL>" :target "_blank"} "Email Support"]]]]]
[:div.console
[:div#app
[:div.container.page-pane body]]]
[:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
(defn entity-link [eid {:keys [valid-time transaction-time]}]
(let [encoded-eid (URLEncoder/encode (pr-str eid) "UTF-8")
query-params (format "?eid=%s&valid-time=%s&transaction-time=%s"
encoded-eid
(.toInstant ^Date valid-time)
(.toInstant ^Date transaction-time))]
(str "/_crux/entity" query-params)))
| true | (ns crux.http-server.util
(:require [crux.io :as cio]
[crux.api :as api]
[cognitect.transit :as transit]
[hiccup2.core :as hiccup2])
(:import [crux.api ICruxAPI ICruxDatasource]
java.time.format.DateTimeFormatter
java.net.URLEncoder
java.util.Date))
(def ^DateTimeFormatter default-date-formatter
(DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS"))
(defn db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}]
(cond
(and valid-time transact-time)
(.db crux-node valid-time transact-time)
valid-time
(.db crux-node valid-time)
;; TODO: This could also be an error, depending how you see it,
;; not supported via the Java API itself.
transact-time
(.db crux-node (cio/next-monotonic-date) transact-time)
:else
(.db crux-node)))
(defn raw-html [{:keys [body title options results]}]
(let [latest-completed-tx (api/latest-completed-tx (:crux-node options))]
(str (hiccup2/html
[:html
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}]
[:meta
{:name "viewport"
:content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}]
[:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}]
(when options [:meta {:title "options" :content (pr-str {:node-options (:node-options options)
:latest-completed-tx latest-completed-tx})}])
(when results [:meta {:title "results" :content (str results)}])
[:link {:rel "stylesheet" :href "/css/all.css"}]
[:link {:rel "stylesheet" :href "/latofonts.css"}]
[:link {:rel "stylesheet" :href "/css/table.css"}]
[:link {:rel "stylesheet" :href "/css/react-datetime.css"}]
[:link {:rel "stylesheet" :href "/css/codemirror.css"}]
[:link {:rel "stylesheet"
:href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}]
[:title "Crux Console"]]
[:body
[:nav.header
[:div.crux-logo
[:a {:href "/_crux/index"}
[:img.crux-logo__img {:src "/crux-horizontal-bw.svg.png" }]]]
[:span.mobile-hidden
[:b (when-let [label (get-in options [:node-options :crux.http-server/label])]
(format "\"%s\"" label))]]
[:div.header__links
[:a.header__link {:href "/_crux/query"} "Query"]
[:a.header__link {:href "/_crux/status"} "Status"]
[:div.header-dropdown
[:button.header-dropdown__button
"Help"
[:i.fa.fa-caret-down]]
[:div.header-dropdown__links
[:a {:href "https://opencrux.com/reference" :target "_blank"} "Documentation"]
[:a {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-crux" :target "_blank"} "Zulip Chat"]
;; [:a {:href "https://clojurians.slack.com/messages/crux" :target "_blank"} "Clojurians Slack"]
[:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI" :target "_blank"} "Email Support"]]]]]
[:div.console
[:div#app
[:div.container.page-pane body]]]
[:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
(defn entity-link [eid {:keys [valid-time transaction-time]}]
(let [encoded-eid (URLEncoder/encode (pr-str eid) "UTF-8")
query-params (format "?eid=%s&valid-time=%s&transaction-time=%s"
encoded-eid
(.toInstant ^Date valid-time)
(.toInstant ^Date transaction-time))]
(str "/_crux/entity" query-params)))
|
[
{
"context": ";; /*\n;; Non-linear Dynamic Sound Generators\n;; Lance Putnam 2004\n;; lance@uwalumni.com\n;;\n;; This is a set of",
"end": 156,
"score": 0.9998054504394531,
"start": 144,
"tag": "NAME",
"value": "Lance Putnam"
},
{
"context": "ynamic Sound Generators\n;; Lance Putnam 2004\n;; lance@uwalumni.com\n;;\n;; This is a set of iterative functions and di",
"end": 183,
"score": 0.9999306797981262,
"start": 165,
"tag": "EMAIL",
"value": "lance@uwalumni.com"
},
{
"context": "equation: xn+1 = a - b*sqrt(|xn|)\"}\n\n\n {:name \"GbmanN\",\n :args [{:name \"freq\", :default 22050.0 :do",
"end": 2183,
"score": 0.9993405938148499,
"start": 2177,
"tag": "USERNAME",
"value": "GbmanN"
},
{
"context": "+1 = xn\"}\n\n ;; GbmanL : GbmanN {}\n\n {:name \"GbmanL\" :extends \"GbmanN\"\n :doc \"A linear-interpola",
"end": 2584,
"score": 0.9769563674926758,
"start": 2579,
"tag": "USERNAME",
"value": "Gbman"
},
{
"context": "s:\nxn+1 = 1 - yn + |xn|\nyn+1 = xn\"}\n\n\n {:name \"HenonN\",\n :args [{:name \"freq\", :default 22050.0 :do",
"end": 2772,
"score": 0.9990603923797607,
"start": 2766,
"tag": "USERNAME",
"value": "HenonN"
},
{
"context": " This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular cl",
"end": 3306,
"score": 0.9992287158966064,
"start": 3294,
"tag": "NAME",
"value": "Michel Hénon"
},
{
"context": "ts of stars in globular clusters.\"}\n\n\n {:name \"HenonL\" :extends \"HenonN\"\n :doc \"a linear-interpolat",
"end": 3386,
"score": 0.9860020279884338,
"start": 3380,
"tag": "USERNAME",
"value": "HenonL"
},
{
"context": " This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular cl",
"end": 3607,
"score": 0.9993410110473633,
"start": 3595,
"tag": "NAME",
"value": "Michel Hénon"
},
{
"context": "ts of stars in globular clusters.\"}\n\n\n {:name \"HenonC\" :extends \"HenonN\"\n :doc \"a cubic-interpolati",
"end": 3687,
"score": 0.9902129173278809,
"start": 3681,
"tag": "USERNAME",
"value": "HenonC"
},
{
"context": " This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular cl",
"end": 3907,
"score": 0.9994375705718994,
"start": 3895,
"tag": "NAME",
"value": "Michel Hénon"
},
{
"context": "its of stars in globular clusters.\"}\n\n {:name \"LatoocarfianN\",\n :args [{:name \"freq\", :default 22050.0 :do",
"end": 3993,
"score": 0.9975922107696533,
"start": 3980,
"tag": "USERNAME",
"value": "LatoocarfianN"
},
{
"context": " or oscillate in a cycle (tone).\"}\n\n\n {:name \"LatoocarfianL\" :extends \"LatoocarfianN\"\n :doc \"a linear-int",
"end": 4827,
"score": 0.9950732588768005,
"start": 4814,
"tag": "USERNAME",
"value": "LatoocarfianL"
},
{
"context": " or oscillate in a cycle (tone).\"}\n\n\n {:name \"LinCongN\",\n :args [{:name \"freq\", :default 22050.0 :do",
"end": 5631,
"score": 0.9107084274291992,
"start": 5623,
"tag": "USERNAME",
"value": "LinCongN"
},
{
"context": "p of a cylinder discovered by the plasma physicist Boris Chirikov.\"}\n\n\n {:name \"StandardL\" :extends \"StandardN\"\n",
"end": 6948,
"score": 0.9940958023071289,
"start": 6934,
"tag": "NAME",
"value": "Boris Chirikov"
},
{
"context": "p of a cylinder discovered by the plasma physicist Boris Chirikov.\"}\n\n\n {:name \"FBSineN\",\n :args [{:name \"fr",
"end": 7168,
"score": 0.9672856330871582,
"start": 7154,
"tag": "NAME",
"value": "Boris Chirikov"
},
{
"context": "d a = 1 a normal sinewave results.\"}\n\n {:name \"LorenzL\",\n :args [{:name \"freq\", :default 22050.0 :do",
"end": 8490,
"score": 0.9976012706756592,
"start": 8483,
"tag": "USERNAME",
"value": "LorenzL"
},
{
"context": "aotic generator. A strange attractor discovered by Edward N. Lorenz while studying mathematical models of the atmosph",
"end": 9104,
"score": 0.9998785257339478,
"start": 9088,
"tag": "NAME",
"value": "Edward N. Lorenz"
}
] | src/overtone/sc/machinery/ugen/metadata/chaos.clj | samaaron/overtone | 2 | (ns overtone.sc.machinery.ugen.metadata.chaos
(:use [overtone.sc.machinery.ugen common]))
;; /*
;; Non-linear Dynamic Sound Generators
;; Lance Putnam 2004
;; lance@uwalumni.com
;;
;; This is a set of iterative functions and differential equations that
;; are known to exhibit chaotic behavior. Internal calculations are
;; done with 64-bit words to ensure greater accuracy.
;;
;; The name of the function is followed by one of N, L, or C. These
;; represent the interpolation method used between function iterations.
;; N -> None
;; L -> Linear
;; C -> Cubic
;; */
;; ChaosGen : UGen {}
(def specs
(map
#(assoc %
:rates #{:ar})
[
{:name "QuadN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default -1.0 :doc "2nd coefficient"}
{:name "c", :default -0.75 :doc "3rd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c "}
;; QuadL : QuadN {}
{:name "QuadL" :extends "QuadN"
:doc "a linear-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
;; QuadC : QuadN {}
{:name "QuadC", :extends "QuadN"
:doc "a cubic-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
{:name "CuspN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "first coefficient"}
{:name "b", :default 1.9 :doc "2nd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
;; CuspL : CuspN {}
{:name "CuspL" :extends "CuspN"
:doc "a linear-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
{:name "GbmanN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hz"}
{:name "xi", :default 1.2 :doc "initial value of x"}
{:name "yi", :default 2.1 :doc "initial value of y"}]
:doc "A non-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
;; GbmanL : GbmanN {}
{:name "GbmanL" :extends "GbmanN"
:doc "A linear-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
{:name "HenonN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.4 :doc "1st coefficient"}
{:name "b", :default 0.3 :doc "2nd coefficient"}
{:name "x0", :default 0.0 :doc "initial value of x"}
{:name "x1", :default 0.0 :doc "second value of x"}]
:doc "a non-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular clusters."}
{:name "HenonL" :extends "HenonN"
:doc "a linear-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular clusters."}
{:name "HenonC" :extends "HenonN"
:doc "a cubic-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer Michel Hénon while studying the orbits of stars in globular clusters."}
{:name "LatoocarfianN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default 3.0 :doc "2nd coefficient"}
{:name "c", :default 0.5 :doc "3rd coefficient"}
{:name "d", :default 0.5 :doc "4th coefficient"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.5 :doc "initial value of y"}]
:doc "a non-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianL" :extends "LatoocarfianN"
:doc "a linear-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianC" :extends "LatoocarfianN"
:doc "a cubic-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LinCongN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz."}
{:name "a", :default 1.1 :doc "multiplier amount"}
{:name "c", :default 0.13 :doc "increment amount"}
{:name "m", :default 1.0 :doc "modulus amount"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongL" :extends "LinCongN"
:doc "a linear-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongC" :extends "LinCongN"
:doc "a cubic-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "StandardN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "k", :default 1.0 :doc "perturbation amount"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}]
:doc "standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist Boris Chirikov."}
{:name "StandardL" :extends "StandardN"
:doc "linear-interpolating standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist Boris Chirikov."}
{:name "FBSineN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "im", :default 1.0 :doc "index multiplier amount"}
{:name "fb", :default 0.1 :doc "feedback amount"}
{:name "a", :default 1.1 :doc "phase multiplier amount"}
{:name "c", :default 0.5 :doc "phase increment amount"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.1 :doc "initial value of y"}]
:doc "a non-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineL" :extends "FBSineN"
:doc "a linear-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineC" :extends "FBSineN"
:doc "a cubic-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "LorenzL",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "s", :default 10.0 :doc "1st variable"}
{:name "r", :default 28.0 :doc "2nd variable"}
{:name "b", :default 2.667 :doc "3rd variable"}
{:name "h", :default 0.05 :doc "integration time stamp"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}
{:name "zi", :default 0.0 :doc "initial value of z"}]
:doc "lorenz chaotic generator. A strange attractor discovered by Edward N. Lorenz while studying mathematical models of the atmosphere. The time step amount h determines the rate at which the ODE is evaluated. Higher values will increase the rate, but cause more instability. A safe choice is the default amount of 0.05."}]))
| 59371 | (ns overtone.sc.machinery.ugen.metadata.chaos
(:use [overtone.sc.machinery.ugen common]))
;; /*
;; Non-linear Dynamic Sound Generators
;; <NAME> 2004
;; <EMAIL>
;;
;; This is a set of iterative functions and differential equations that
;; are known to exhibit chaotic behavior. Internal calculations are
;; done with 64-bit words to ensure greater accuracy.
;;
;; The name of the function is followed by one of N, L, or C. These
;; represent the interpolation method used between function iterations.
;; N -> None
;; L -> Linear
;; C -> Cubic
;; */
;; ChaosGen : UGen {}
(def specs
(map
#(assoc %
:rates #{:ar})
[
{:name "QuadN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default -1.0 :doc "2nd coefficient"}
{:name "c", :default -0.75 :doc "3rd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c "}
;; QuadL : QuadN {}
{:name "QuadL" :extends "QuadN"
:doc "a linear-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
;; QuadC : QuadN {}
{:name "QuadC", :extends "QuadN"
:doc "a cubic-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
{:name "CuspN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "first coefficient"}
{:name "b", :default 1.9 :doc "2nd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
;; CuspL : CuspN {}
{:name "CuspL" :extends "CuspN"
:doc "a linear-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
{:name "GbmanN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hz"}
{:name "xi", :default 1.2 :doc "initial value of x"}
{:name "yi", :default 2.1 :doc "initial value of y"}]
:doc "A non-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
;; GbmanL : GbmanN {}
{:name "GbmanL" :extends "GbmanN"
:doc "A linear-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
{:name "HenonN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.4 :doc "1st coefficient"}
{:name "b", :default 0.3 :doc "2nd coefficient"}
{:name "x0", :default 0.0 :doc "initial value of x"}
{:name "x1", :default 0.0 :doc "second value of x"}]
:doc "a non-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer <NAME> while studying the orbits of stars in globular clusters."}
{:name "HenonL" :extends "HenonN"
:doc "a linear-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer <NAME> while studying the orbits of stars in globular clusters."}
{:name "HenonC" :extends "HenonN"
:doc "a cubic-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer <NAME> while studying the orbits of stars in globular clusters."}
{:name "LatoocarfianN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default 3.0 :doc "2nd coefficient"}
{:name "c", :default 0.5 :doc "3rd coefficient"}
{:name "d", :default 0.5 :doc "4th coefficient"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.5 :doc "initial value of y"}]
:doc "a non-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianL" :extends "LatoocarfianN"
:doc "a linear-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianC" :extends "LatoocarfianN"
:doc "a cubic-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LinCongN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz."}
{:name "a", :default 1.1 :doc "multiplier amount"}
{:name "c", :default 0.13 :doc "increment amount"}
{:name "m", :default 1.0 :doc "modulus amount"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongL" :extends "LinCongN"
:doc "a linear-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongC" :extends "LinCongN"
:doc "a cubic-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "StandardN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "k", :default 1.0 :doc "perturbation amount"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}]
:doc "standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist <NAME>."}
{:name "StandardL" :extends "StandardN"
:doc "linear-interpolating standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist <NAME>."}
{:name "FBSineN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "im", :default 1.0 :doc "index multiplier amount"}
{:name "fb", :default 0.1 :doc "feedback amount"}
{:name "a", :default 1.1 :doc "phase multiplier amount"}
{:name "c", :default 0.5 :doc "phase increment amount"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.1 :doc "initial value of y"}]
:doc "a non-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineL" :extends "FBSineN"
:doc "a linear-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineC" :extends "FBSineN"
:doc "a cubic-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "LorenzL",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "s", :default 10.0 :doc "1st variable"}
{:name "r", :default 28.0 :doc "2nd variable"}
{:name "b", :default 2.667 :doc "3rd variable"}
{:name "h", :default 0.05 :doc "integration time stamp"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}
{:name "zi", :default 0.0 :doc "initial value of z"}]
:doc "lorenz chaotic generator. A strange attractor discovered by <NAME> while studying mathematical models of the atmosphere. The time step amount h determines the rate at which the ODE is evaluated. Higher values will increase the rate, but cause more instability. A safe choice is the default amount of 0.05."}]))
| true | (ns overtone.sc.machinery.ugen.metadata.chaos
(:use [overtone.sc.machinery.ugen common]))
;; /*
;; Non-linear Dynamic Sound Generators
;; PI:NAME:<NAME>END_PI 2004
;; PI:EMAIL:<EMAIL>END_PI
;;
;; This is a set of iterative functions and differential equations that
;; are known to exhibit chaotic behavior. Internal calculations are
;; done with 64-bit words to ensure greater accuracy.
;;
;; The name of the function is followed by one of N, L, or C. These
;; represent the interpolation method used between function iterations.
;; N -> None
;; L -> Linear
;; C -> Cubic
;; */
;; ChaosGen : UGen {}
(def specs
(map
#(assoc %
:rates #{:ar})
[
{:name "QuadN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default -1.0 :doc "2nd coefficient"}
{:name "c", :default -0.75 :doc "3rd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c "}
;; QuadL : QuadN {}
{:name "QuadL" :extends "QuadN"
:doc "a linear-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
;; QuadC : QuadN {}
{:name "QuadC", :extends "QuadN"
:doc "a cubic-interpolating (general quadratic map chaotic) sound generator based on the difference equation: xn+1 = axn2 + bxn + c"}
{:name "CuspN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "first coefficient"}
{:name "b", :default 1.9 :doc "2nd coefficient"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
;; CuspL : CuspN {}
{:name "CuspL" :extends "CuspN"
:doc "a linear-interpolating (cusp map chaotic) sound generator based on the difference equation: xn+1 = a - b*sqrt(|xn|)"}
{:name "GbmanN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hz"}
{:name "xi", :default 1.2 :doc "initial value of x"}
{:name "yi", :default 2.1 :doc "initial value of y"}]
:doc "A non-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
;; GbmanL : GbmanN {}
{:name "GbmanL" :extends "GbmanN"
:doc "A linear-interpolating (gingerbreadman map chaotic) sound generator based on the difference equations:
xn+1 = 1 - yn + |xn|
yn+1 = xn"}
{:name "HenonN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.4 :doc "1st coefficient"}
{:name "b", :default 0.3 :doc "2nd coefficient"}
{:name "x0", :default 0.0 :doc "initial value of x"}
{:name "x1", :default 0.0 :doc "second value of x"}]
:doc "a non-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer PI:NAME:<NAME>END_PI while studying the orbits of stars in globular clusters."}
{:name "HenonL" :extends "HenonN"
:doc "a linear-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer PI:NAME:<NAME>END_PI while studying the orbits of stars in globular clusters."}
{:name "HenonC" :extends "HenonN"
:doc "a cubic-interpolating (henon map chaotic) sound generator based on the difference equation:
x[n+2] = 1 - a*(x[n+1]^)2 + bx[n]. This equation was discovered by French astronomer PI:NAME:<NAME>END_PI while studying the orbits of stars in globular clusters."}
{:name "LatoocarfianN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "a", :default 1.0 :doc "1st coefficient"}
{:name "b", :default 3.0 :doc "2nd coefficient"}
{:name "c", :default 0.5 :doc "3rd coefficient"}
{:name "d", :default 0.5 :doc "4th coefficient"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.5 :doc "initial value of y"}]
:doc "a non-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianL" :extends "LatoocarfianN"
:doc "a linear-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LatoocarfianC" :extends "LatoocarfianN"
:doc "a cubic-interpolating (latoocarfian chaotic) sound generator. Parameters a and b should be in the range from -3 to +3, and parameters c and d should be in the range from 0.5 to 1.5. The function can, depending on the parameters given, give continuous chaotic output, converge to a single value (silence) or oscillate in a cycle (tone)."}
{:name "LinCongN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz."}
{:name "a", :default 1.1 :doc "multiplier amount"}
{:name "c", :default 0.13 :doc "increment amount"}
{:name "m", :default 1.0 :doc "modulus amount"}
{:name "xi", :default 0.0 :doc "initial value of x"}]
:doc "a non-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongL" :extends "LinCongN"
:doc "a linear-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "LinCongC" :extends "LinCongN"
:doc "a cubic-interpolating (linear congruential chaotic) sound generator. The output signal is automatically scaled to a range of [-1, 1]."}
{:name "StandardN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "k", :default 1.0 :doc "perturbation amount"}
{:name "xi", :default 0.5 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}]
:doc "standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist PI:NAME:<NAME>END_PI."}
{:name "StandardL" :extends "StandardN"
:doc "linear-interpolating standard map chaotic generator. The standard map is an area preserving map of a cylinder discovered by the plasma physicist PI:NAME:<NAME>END_PI."}
{:name "FBSineN",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "im", :default 1.0 :doc "index multiplier amount"}
{:name "fb", :default 0.1 :doc "feedback amount"}
{:name "a", :default 1.1 :doc "phase multiplier amount"}
{:name "c", :default 0.5 :doc "phase increment amount"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.1 :doc "initial value of y"}]
:doc "a non-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineL" :extends "FBSineN"
:doc "a linear-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "FBSineC" :extends "FBSineN"
:doc "a cubic-interpolating feedback sine with chaotic phase indexing sound generator. This uses a linear congruential function to drive the phase indexing of a sine wave. For im = 1, fb = 0, and a = 1 a normal sinewave results."}
{:name "LorenzL",
:args [{:name "freq", :default 22050.0 :doc "iteration frequency in Hertz"}
{:name "s", :default 10.0 :doc "1st variable"}
{:name "r", :default 28.0 :doc "2nd variable"}
{:name "b", :default 2.667 :doc "3rd variable"}
{:name "h", :default 0.05 :doc "integration time stamp"}
{:name "xi", :default 0.1 :doc "initial value of x"}
{:name "yi", :default 0.0 :doc "initial value of y"}
{:name "zi", :default 0.0 :doc "initial value of z"}]
:doc "lorenz chaotic generator. A strange attractor discovered by PI:NAME:<NAME>END_PI while studying mathematical models of the atmosphere. The time step amount h determines the rate at which the ODE is evaluated. Higher values will increase the rate, but cause more instability. A safe choice is the default amount of 0.05."}]))
|
[
{
"context": "comment\n (quote-parser {:a \"\"\n :b \"@@123@@456\"\n :c \"hello@@world\"\n ",
"end": 498,
"score": 0.9037801027297974,
"start": 487,
"tag": "PASSWORD",
"value": "\"@@123@@456"
}
] | src/nr_data/quotes.clj | plural/netrunner-data | 7 | (ns nr-data.quotes
(:require
[clojure.string :as string]
[medley.core :refer [filter-vals map-vals]]
[semantic-csv.core :as sc]
[zprint.core :as zp]))
(defn quote-parser
[quotes]
(->> quotes
(filter-vals seq)
(map-vals (fn [text]
(as-> text text
(string/split text #"@@")
(filter seq text)
(mapv string/trim text))))))
(comment
(quote-parser {:a ""
:b "@@123@@456"
:c "hello@@world"
:d "asdf "}))
(defn id-merger
[path]
(into {}
(for [c (sc/slurp-csv path :keyify false)
:let [k (get c "")
v (dissoc c "")]]
[k (quote-parser v)])))
(comment (get (id-merger "quotes/quotes-corp.csv") "Asa Group: Security Through Vigilance"))
(comment (get (id-merger "quotes/quotes-runner.csv") "Sunny Lebeau: Security Specialist"))
(defn build-quotes [& _]
(let [
corp (id-merger "quotes/quotes-corp.csv")
runner (id-merger "quotes/quotes-runner.csv")
]
(spit "quotes/quotes-corp.edn" (str (zp/zprint-str corp) "\n"))
(spit "quotes/quotes-runner.edn" (str (zp/zprint-str runner) "\n"))))
(comment
(build-quotes))
| 6537 | (ns nr-data.quotes
(:require
[clojure.string :as string]
[medley.core :refer [filter-vals map-vals]]
[semantic-csv.core :as sc]
[zprint.core :as zp]))
(defn quote-parser
[quotes]
(->> quotes
(filter-vals seq)
(map-vals (fn [text]
(as-> text text
(string/split text #"@@")
(filter seq text)
(mapv string/trim text))))))
(comment
(quote-parser {:a ""
:b <PASSWORD>"
:c "hello@@world"
:d "asdf "}))
(defn id-merger
[path]
(into {}
(for [c (sc/slurp-csv path :keyify false)
:let [k (get c "")
v (dissoc c "")]]
[k (quote-parser v)])))
(comment (get (id-merger "quotes/quotes-corp.csv") "Asa Group: Security Through Vigilance"))
(comment (get (id-merger "quotes/quotes-runner.csv") "Sunny Lebeau: Security Specialist"))
(defn build-quotes [& _]
(let [
corp (id-merger "quotes/quotes-corp.csv")
runner (id-merger "quotes/quotes-runner.csv")
]
(spit "quotes/quotes-corp.edn" (str (zp/zprint-str corp) "\n"))
(spit "quotes/quotes-runner.edn" (str (zp/zprint-str runner) "\n"))))
(comment
(build-quotes))
| true | (ns nr-data.quotes
(:require
[clojure.string :as string]
[medley.core :refer [filter-vals map-vals]]
[semantic-csv.core :as sc]
[zprint.core :as zp]))
(defn quote-parser
[quotes]
(->> quotes
(filter-vals seq)
(map-vals (fn [text]
(as-> text text
(string/split text #"@@")
(filter seq text)
(mapv string/trim text))))))
(comment
(quote-parser {:a ""
:b PI:PASSWORD:<PASSWORD>END_PI"
:c "hello@@world"
:d "asdf "}))
(defn id-merger
[path]
(into {}
(for [c (sc/slurp-csv path :keyify false)
:let [k (get c "")
v (dissoc c "")]]
[k (quote-parser v)])))
(comment (get (id-merger "quotes/quotes-corp.csv") "Asa Group: Security Through Vigilance"))
(comment (get (id-merger "quotes/quotes-runner.csv") "Sunny Lebeau: Security Specialist"))
(defn build-quotes [& _]
(let [
corp (id-merger "quotes/quotes-corp.csv")
runner (id-merger "quotes/quotes-runner.csv")
]
(spit "quotes/quotes-corp.edn" (str (zp/zprint-str corp) "\n"))
(spit "quotes/quotes-runner.edn" (str (zp/zprint-str runner) "\n"))))
(comment
(build-quotes))
|
[
{
"context": "ame\"\n (t/is (clojure.string/includes? usage \"Ash Ra\")))\n (t/testing \"(usage) mentions the ART",
"end": 1924,
"score": 0.7520370483398438,
"start": 1923,
"tag": "NAME",
"value": "A"
}
] | clj-art/test/vivid/art/clj_tool_test.clj | vivid-inc/ash-ra-template | 14 | ; Copyright 2021 Vivid 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
;
; https://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 vivid.art.clj-tool-test
(:require
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.string]
[clojure.test :as t]
[vivid.art.clj-tool :as clj-tool])
(:import
(java.io File)))
(defn delete-file-tree
[path & [silently]]
((fn del [^File file]
(when (.isDirectory file)
(doseq [child (.listFiles file)]
(del child)))
(io/delete-file file silently))
(io/file path)))
(defn all-invocation-patterns
[path & art-options]
(let [expected-dir (str path "/expected")
target-dir (str path "/target")
templates-dir (str path "/templates")]
(delete-file-tree target-dir :silently)
(let [art-args (concat [templates-dir "--output-dir" target-dir] art-options)
art-res (apply vivid.art.clj-tool/-main art-args)
diff-res (clojure.java.shell/sh "/usr/bin/diff" "--recursive"
target-dir
expected-dir)]
(t/is (nil? art-res))
(t/is (= 0 (diff-res :exit))))))
(t/deftest usage
(let [usage (clj-tool/usage)]
(t/testing "(usage) indicates how to run this tool at the CLI"
(t/is (clojure.string/includes? usage "clj -m vivid.art.clj-tool")))
(t/testing "(usage) mentions the overall project name"
(t/is (clojure.string/includes? usage "Ash Ra")))
(t/testing "(usage) mentions the ART file extension"
(t/is (clojure.string/includes? usage vivid.art/art-filename-suffix)))))
(t/deftest clj-tool-all-options-exercise
(all-invocation-patterns "../examples/all-options"
"--bindings" "{updated \"2021-01-01\"}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"
"--dependencies" "{hiccup {:mvn/version \"1.0.5\"}}"
"--to-phase" "evaluate"))
(t/deftest clj-tool-readme-examples
(all-invocation-patterns "../examples/readme-examples"
"--bindings" "{mysterious-primes [7 191]}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"))
(t/deftest clj-tool-simple
(all-invocation-patterns "../examples/simple"))
(t/deftest clj-tool-utf-8
(all-invocation-patterns "../examples/utf-8"
"--bindings" "../examples/utf-8/greek.edn"
"--delimiters" "jinja"))
;; TODO: examples/custom-options is currently failing until a newer version of org.clojure/tools.cli is released.
(t/deftest clj-tool-example-multi-batch
(let [res (clojure.java.shell/sh "./test.sh" "clj-art"
:dir "../examples/multi-batch")]
(t/is (= 0 (res :exit)))))
(t/deftest clj-tool-example-override-clojure-version
(all-invocation-patterns "../examples/override-clojure-version"
"--dependencies" "{org.clojure/clojure {:mvn/version \"1.10.1\"}}"))
| 79735 | ; Copyright 2021 Vivid 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
;
; https://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 vivid.art.clj-tool-test
(:require
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.string]
[clojure.test :as t]
[vivid.art.clj-tool :as clj-tool])
(:import
(java.io File)))
(defn delete-file-tree
[path & [silently]]
((fn del [^File file]
(when (.isDirectory file)
(doseq [child (.listFiles file)]
(del child)))
(io/delete-file file silently))
(io/file path)))
(defn all-invocation-patterns
[path & art-options]
(let [expected-dir (str path "/expected")
target-dir (str path "/target")
templates-dir (str path "/templates")]
(delete-file-tree target-dir :silently)
(let [art-args (concat [templates-dir "--output-dir" target-dir] art-options)
art-res (apply vivid.art.clj-tool/-main art-args)
diff-res (clojure.java.shell/sh "/usr/bin/diff" "--recursive"
target-dir
expected-dir)]
(t/is (nil? art-res))
(t/is (= 0 (diff-res :exit))))))
(t/deftest usage
(let [usage (clj-tool/usage)]
(t/testing "(usage) indicates how to run this tool at the CLI"
(t/is (clojure.string/includes? usage "clj -m vivid.art.clj-tool")))
(t/testing "(usage) mentions the overall project name"
(t/is (clojure.string/includes? usage "<NAME>sh Ra")))
(t/testing "(usage) mentions the ART file extension"
(t/is (clojure.string/includes? usage vivid.art/art-filename-suffix)))))
(t/deftest clj-tool-all-options-exercise
(all-invocation-patterns "../examples/all-options"
"--bindings" "{updated \"2021-01-01\"}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"
"--dependencies" "{hiccup {:mvn/version \"1.0.5\"}}"
"--to-phase" "evaluate"))
(t/deftest clj-tool-readme-examples
(all-invocation-patterns "../examples/readme-examples"
"--bindings" "{mysterious-primes [7 191]}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"))
(t/deftest clj-tool-simple
(all-invocation-patterns "../examples/simple"))
(t/deftest clj-tool-utf-8
(all-invocation-patterns "../examples/utf-8"
"--bindings" "../examples/utf-8/greek.edn"
"--delimiters" "jinja"))
;; TODO: examples/custom-options is currently failing until a newer version of org.clojure/tools.cli is released.
(t/deftest clj-tool-example-multi-batch
(let [res (clojure.java.shell/sh "./test.sh" "clj-art"
:dir "../examples/multi-batch")]
(t/is (= 0 (res :exit)))))
(t/deftest clj-tool-example-override-clojure-version
(all-invocation-patterns "../examples/override-clojure-version"
"--dependencies" "{org.clojure/clojure {:mvn/version \"1.10.1\"}}"))
| true | ; Copyright 2021 Vivid 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
;
; https://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 vivid.art.clj-tool-test
(:require
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.string]
[clojure.test :as t]
[vivid.art.clj-tool :as clj-tool])
(:import
(java.io File)))
(defn delete-file-tree
[path & [silently]]
((fn del [^File file]
(when (.isDirectory file)
(doseq [child (.listFiles file)]
(del child)))
(io/delete-file file silently))
(io/file path)))
(defn all-invocation-patterns
[path & art-options]
(let [expected-dir (str path "/expected")
target-dir (str path "/target")
templates-dir (str path "/templates")]
(delete-file-tree target-dir :silently)
(let [art-args (concat [templates-dir "--output-dir" target-dir] art-options)
art-res (apply vivid.art.clj-tool/-main art-args)
diff-res (clojure.java.shell/sh "/usr/bin/diff" "--recursive"
target-dir
expected-dir)]
(t/is (nil? art-res))
(t/is (= 0 (diff-res :exit))))))
(t/deftest usage
(let [usage (clj-tool/usage)]
(t/testing "(usage) indicates how to run this tool at the CLI"
(t/is (clojure.string/includes? usage "clj -m vivid.art.clj-tool")))
(t/testing "(usage) mentions the overall project name"
(t/is (clojure.string/includes? usage "PI:NAME:<NAME>END_PIsh Ra")))
(t/testing "(usage) mentions the ART file extension"
(t/is (clojure.string/includes? usage vivid.art/art-filename-suffix)))))
(t/deftest clj-tool-all-options-exercise
(all-invocation-patterns "../examples/all-options"
"--bindings" "{updated \"2021-01-01\"}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"
"--dependencies" "{hiccup {:mvn/version \"1.0.5\"}}"
"--to-phase" "evaluate"))
(t/deftest clj-tool-readme-examples
(all-invocation-patterns "../examples/readme-examples"
"--bindings" "{mysterious-primes [7 191]}"
"--delimiters" "{:begin-forms \"{%\" :end-forms \"%}\" :begin-eval \"{%=\" :end-eval \"%}\"}"))
(t/deftest clj-tool-simple
(all-invocation-patterns "../examples/simple"))
(t/deftest clj-tool-utf-8
(all-invocation-patterns "../examples/utf-8"
"--bindings" "../examples/utf-8/greek.edn"
"--delimiters" "jinja"))
;; TODO: examples/custom-options is currently failing until a newer version of org.clojure/tools.cli is released.
(t/deftest clj-tool-example-multi-batch
(let [res (clojure.java.shell/sh "./test.sh" "clj-art"
:dir "../examples/multi-batch")]
(t/is (= 0 (res :exit)))))
(t/deftest clj-tool-example-override-clojure-version
(all-invocation-patterns "../examples/override-clojure-version"
"--dependencies" "{org.clojure/clojure {:mvn/version \"1.10.1\"}}"))
|
[
{
"context": "ame \"USERS\"\n :display_name \"Users\"\n :entity_type \"entity/UserTable\"\n",
"end": 6009,
"score": 0.9693475961685181,
"start": 6004,
"tag": "NAME",
"value": "Users"
},
{
"context": " :name \"ID\"\n :display_na",
"end": 6333,
"score": 0.9155964851379395,
"start": 6331,
"tag": "NAME",
"value": "ID"
},
{
"context": " :display_name \"ID\"\n :database_t",
"end": 6393,
"score": 0.92094886302948,
"start": 6391,
"tag": "NAME",
"value": "ID"
},
{
"context": " :name \"NAME\"\n :display_na",
"end": 7036,
"score": 0.9832621812820435,
"start": 7032,
"tag": "NAME",
"value": "NAME"
},
{
"context": " :display_name \"Name\"\n :database_t",
"end": 7106,
"score": 0.9817028641700745,
"start": 7102,
"tag": "NAME",
"value": "Name"
},
{
"context": " :name \"LAST_LOGIN\"\n :display_na",
"end": 7977,
"score": 0.9970149397850037,
"start": 7967,
"tag": "NAME",
"value": "LAST_LOGIN"
},
{
"context": " :display_name \"Last Login\"\n :database_t",
"end": 8053,
"score": 0.9971970915794373,
"start": 8043,
"tag": "NAME",
"value": "Last Login"
},
{
"context": " :name \"LAST_LOGIN\"\n :display_na",
"end": 11931,
"score": 0.9981799721717834,
"start": 11921,
"tag": "NAME",
"value": "LAST_LOGIN"
},
{
"context": " :display_name \"Last Login\"\n :database_t",
"end": 12007,
"score": 0.9991581439971924,
"start": 11997,
"tag": "NAME",
"value": "Last Login"
},
{
"context": "))\n {:display_name \"Userz\"\n :visibility_type \"h",
"end": 14758,
"score": 0.7293996214866638,
"start": 14753,
"tag": "NAME",
"value": "Userz"
},
{
"context": "ty_type \"hidden\"\n :display_name \"Userz\"\n :pk_field (table/pk-field-",
"end": 15332,
"score": 0.7011654376983643,
"start": 15327,
"tag": "NAME",
"value": "Userz"
},
{
"context": " {:display_name \"Userz\"\n ",
"end": 16837,
"score": 0.9750773310661316,
"start": 16832,
"tag": "NAME",
"value": "Userz"
},
{
"context": " :display_name \"User ID\"\n :",
"end": 19353,
"score": 0.5683233141899109,
"start": 19349,
"tag": "NAME",
"value": "User"
},
{
"context": " :name \"NAME\"\n :display_name ",
"end": 23395,
"score": 0.9894853234291077,
"start": 23391,
"tag": "NAME",
"value": "NAME"
},
{
"context": " :display_name \"Name\"\n :database_type ",
"end": 23458,
"score": 0.9962361454963684,
"start": 23454,
"tag": "NAME",
"value": "Name"
},
{
"context": "-id card))]\n {:display_name \"Go Dubs!\"\n :schema \"Everything ",
"end": 25819,
"score": 0.960131049156189,
"start": 25812,
"tag": "NAME",
"value": "Go Dubs"
},
{
"context": " [{:name \"NAME\"\n :dis",
"end": 26387,
"score": 0.9103111028671265,
"start": 26383,
"tag": "NAME",
"value": "NAME"
},
{
"context": " :display_name \"NAME\"\n :bas",
"end": 26452,
"score": 0.9652439951896667,
"start": 26448,
"tag": "NAME",
"value": "NAME"
},
{
"context": "\"\n (mt/with-temp Card [card {:name \"Users\"\n :database_id (",
"end": 28894,
"score": 0.7451244592666626,
"start": 28889,
"tag": "NAME",
"value": "Users"
},
{
"context": "d card))]\n (is (= {:display_name \"Users\"\n :schema \"Everythi",
"end": 29662,
"score": 0.6976818442344666,
"start": 29657,
"tag": "NAME",
"value": "Users"
},
{
"context": " :fields [{:name \"NAME\"\n :displa",
"end": 30066,
"score": 0.9819692373275757,
"start": 30062,
"tag": "NAME",
"value": "NAME"
},
{
"context": " :display_name \"NAME\"\n :base_t",
"end": 30140,
"score": 0.9813023805618286,
"start": 30136,
"tag": "NAME",
"value": "NAME"
},
{
"context": " {:name \"LAST_LOGIN\"\n :displa",
"end": 30923,
"score": 0.8198332190513611,
"start": 30913,
"tag": "NAME",
"value": "LAST_LOGIN"
},
{
"context": " :display_name \"LAST_LOGIN\"\n :base_t",
"end": 31003,
"score": 0.9009559750556946,
"start": 30993,
"tag": "NAME",
"value": "LAST_LOGIN"
}
] | c#-metabase/test/metabase/api/table_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.api.table-test
"Tests for /api/table endpoints."
(:require [cheshire.core :as json]
[clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.api.table :as table-api]
[metabase.driver.util :as driver.u]
[metabase.http-client :as http]
[metabase.mbql.util :as mbql.u]
[metabase.models :refer [Card Database Field FieldValues Table]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.table :as table]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :as mutil]
[metabase.test.util :as tu]
[metabase.timeseries-query-processor-test.util :as tqpt]
[metabase.util :as u]
[toucan.db :as db]))
;; ## /api/org/* AUTHENTICATION Tests
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest unauthenticated-test
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "table")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 (format "table/%d" (mt/id :users))))))
(defn- db-details []
(merge
(select-keys (mt/db) [:id :created_at :updated_at :timezone])
{:engine "h2"
:name "test-data"
:is_sample false
:is_full_sync true
:is_on_demand false
:description nil
:caveats nil
:points_of_interest nil
:features (mapv u/qualified-name (driver.u/features :h2 (mt/db)))
:cache_field_values_schedule "0 50 0 * * ? *"
:metadata_sync_schedule "0 50 * * * ? *"
:options nil
:refingerprint nil
:auto_run_queries true}))
(defn- table-defaults []
(merge
(mt/object-defaults Table)
{:db (db-details)
:entity_type "entity/GenericTable"
:field_order "database"
:metrics []
:segments []}))
(defn- field-defaults []
(merge
(mt/object-defaults Field)
{:default_dimension_option nil
:dimension_options []
:dimensions []
:position 0
:target nil
:visibility_type "normal"}))
(defn- field-details [field]
(merge
(field-defaults)
(select-keys
field
[:created_at :fingerprint :fingerprint_version :fk_target_field_id :id :last_analyzed :updated_at])))
(defn- fk-field-details [field]
(-> (field-details field)
(dissoc :dimension_options :default_dimension_option)))
(deftest list-table-test
(testing "GET /api/table"
(testing "These should come back in alphabetical order and include relevant metadata"
(is (= #{{:name (mt/format-name "categories")
:display_name "Categories"
:id (mt/id :categories)
:entity_type "entity/GenericTable"}
{:name (mt/format-name "checkins")
:display_name "Checkins"
:id (mt/id :checkins)
:entity_type "entity/EventTable"}
{:name (mt/format-name "users")
:display_name "Users"
:id (mt/id :users)
:entity_type "entity/UserTable"}
{:name (mt/format-name "venues")
:display_name "Venues"
:id (mt/id :venues)
:entity_type "entity/GenericTable"}}
(->> (mt/user-http-request :rasta :get 200 "table")
(filter #(= (:db_id %) (mt/id))) ; prevent stray tables from affecting unit test results
(map #(select-keys % [:name :display_name :id :entity_type]))
set))))))
(deftest get-table-test
(testing "GET /api/table/:id"
(is (= (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :created_at :updated_at] :id (mt/id :venues))
{:schema "PUBLIC"
:name "VENUES"
:display_name "Venues"
:pk_field (table/pk-field-id (Table (mt/id :venues)))
:id (mt/id :venues)
:db_id (mt/id)})
(mt/user-http-request :rasta :get 200 (format "table/%d" (mt/id :venues)))))
(testing " should return a 403 for a user that doesn't have read permissions for the table"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]]
(perms/revoke-permissions! (perms-group/all-users) database-id)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "table/" table-id))))))))
(defn- default-dimension-options []
(as-> @#'table-api/dimension-options-for-response options
(m/map-vals #(update % :name str) options)
(walk/keywordize-keys options)
;; since we're comparing API responses, need to de-keywordize the `:field` clauses
(mbql.u/replace options :field (mt/obj->json->obj &match))))
(defn- query-metadata-defaults []
(-> (table-defaults)
(assoc :dimension_options (default-dimension-options))))
(deftest sensitive-fields-included-test
(testing "GET api/table/:id/query_metadata?include_sensitive_fields"
(testing "Sensitive fields are included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:semantic_type "type/PK"
:table_id (mt/id :users)
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:visibility_type "normal"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:semantic_type "type/Name"
:table_id (mt/id :users)
:name "NAME"
:display_name "Name"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "normal"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "LAST_LOGIN"
:display_name "Last Login"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:visibility_type "normal"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)
(assoc (field-details (Field :table_id (mt/id :users), :name "PASSWORD"))
:semantic_type "type/Category"
:table_id (mt/id :users)
:name "PASSWORD"
:display_name "Password"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "sensitive"
:has_field_values "list"
:position 3
:database_position 3)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata?include_sensitive_fields=true" (mt/id :users))))
"Make sure that getting the User table *does* include info about the password field, but not actual values themselves"))))
(deftest sensitive-fields-not-included-test
(testing "GET api/table/:id/query_metadata"
(testing "Sensitive fields should not be included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:table_id (mt/id :users)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:table_id (mt/id :users)
:semantic_type "type/Name"
:name "NAME"
:display_name "Name"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "LAST_LOGIN"
:display_name "Last Login"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users))))
"Make sure that getting the User table does *not* include password info"))))
(deftest fk-target-permissions-test
(testing "GET /api/table/:id/query_metadata"
(testing (str "Check that FK fields belonging to Tables we don't have permissions for don't come back as hydrated "
"`:target`(#3867)")
;; create a temp DB with two tables; table-2 has an FK to table-1
(mt/with-temp* [Database [db]
Table [table-1 {:db_id (u/the-id db)}]
Table [table-2 {:db_id (u/the-id db)}]
Field [table-1-id {:table_id (u/the-id table-1), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-id {:table_id (u/the-id table-2), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-fk {:table_id (u/the-id table-2), :name "fk", :base_type :type/Integer, :semantic_type :type/FK, :fk_target_field_id (u/the-id table-1-id)}]]
;; grant permissions only to table-2
(perms/revoke-permissions! (perms-group/all-users) (u/the-id db))
(perms/grant-permissions! (perms-group/all-users) (u/the-id db) (:schema table-2) (u/the-id table-2))
;; metadata for table-2 should show all fields for table-2, but the FK target info shouldn't be hydrated
(is (= #{{:name "id", :target false}
{:name "fk", :target false}}
(set (for [field (:fields (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table-2))))]
(-> (select-keys field [:name :target])
(update :target boolean))))))))))
(deftest update-table-test
(testing "PUT /api/table/:id"
(mt/with-temp Table [table]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (u/the-id table))
{:display_name "Userz"
:visibility_type "hidden"
:description "What a nice table!"})
(is (= (merge
(-> (table-defaults)
(dissoc :segments :field_values :metrics :updated_at)
(assoc-in [:db :details] (:details (mt/db))))
(db/select-one [Table :id :schema :name :created_at] :id (u/the-id table))
{:description "What a nice table!"
:entity_type nil
:visibility_type "hidden"
:display_name "Userz"
:pk_field (table/pk-field-id table)})
(dissoc (mt/user-http-request :crowberto :get 200 (format "table/%d" (u/the-id table)))
:updated_at))))))
;; see how many times sync-table! gets called when we call the PUT endpoint. It should happen when you switch from
;; hidden -> not hidden at the spots marked below, twice total
(deftest update-table-sync-test
(testing "PUT /api/table/:id"
(testing "Table should get synced when it gets unhidden"
(mt/with-temp Table [table]
(let [called (atom 0)
;; original is private so a var will pick up the redef'd. need contents of var before
original (var-get #'table-api/sync-unhidden-tables)]
(with-redefs [table-api/sync-unhidden-tables
(fn [unhidden]
(when (seq unhidden)
(is (= (:id table)
(:id (first unhidden)))
"Unhidden callback did not get correct tables.")
(swap! called inc)
(let [fut (original unhidden)]
(when (future? fut)
(deref fut)))))]
(let [set-visibility (fn [state]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (:id table))
{:display_name "Userz"
:visibility_type state
:description "What a nice table!"}))]
(set-visibility "hidden")
(set-visibility nil) ; <- should get synced
(is (= 1
@called))
(set-visibility "hidden")
(set-visibility "cruft")
(set-visibility "technical")
(set-visibility nil) ; <- should get synced again
(is (= 2
@called))
(set-visibility "technical")
(is (= 2
@called))))))))
(testing "Bulk updating visibility"
(let [unhidden-ids (atom #{})]
(mt/with-temp* [Table [{id-1 :id} {}]
Table [{id-2 :id} {:visibility_type "hidden"}]]
(with-redefs [table-api/sync-unhidden-tables (fn [unhidden] (reset! unhidden-ids (set (map :id unhidden))))]
(let [set-many-vis (fn [ids state]
(reset! unhidden-ids #{})
(mt/user-http-request :crowberto :put 200 "table/"
{:ids ids :visibility_type state}))]
(set-many-vis [id-1 id-2] nil) ;; unhides only 2
(is (= @unhidden-ids #{id-2}))
(set-many-vis [id-1 id-2] "hidden")
(is (= @unhidden-ids #{})) ;; no syncing when they are hidden
(set-many-vis [id-1 id-2] nil) ;; both are made unhidden so both synced
(is (= @unhidden-ids #{id-1 id-2}))))))))
(deftest get-fks-test
(testing "GET /api/table/:id/fks"
(testing "We expect a single FK from CHECKINS.USER_ID -> USERS.ID"
(let [checkins-user-field (Field (mt/id :checkins :user_id))
users-id-field (Field (mt/id :users :id))
fk-field-defaults (dissoc (field-defaults) :target :dimension_options :default_dimension_option)]
(is (= [{:origin_id (:id checkins-user-field)
:destination_id (:id users-id-field)
:relationship "Mt1"
:origin (-> (fk-field-details checkins-user-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :checkins)
:name "USER_ID"
:display_name "User ID"
:database_type "INTEGER"
:base_type "type/Integer"
:effective_type "type/Integer"
:semantic_type "type/FK"
:database_position 2
:position 2
:table (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :checkins))
{:schema "PUBLIC"
:name "CHECKINS"
:display_name "Checkins"
:entity_type "entity/EventTable"})))
:destination (-> (fk-field-details users-id-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :users)
:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:database_type "BIGINT"
:semantic_type "type/PK"
:table (merge
(dissoc (table-defaults) :db :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"})))}]
(mt/user-http-request :rasta :get 200 (format "table/%d/fks" (mt/id :users)))))))
(testing "should just return nothing for 'virtual' tables"
(is (= []
(mt/user-http-request :crowberto :get 200 "table/card__1000/fks"))))))
(deftest basic-query-metadata-test
(testing "GET /api/table/:id/query_metadata"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :categories))
{:schema "PUBLIC"
:name "CATEGORIES"
:display_name "Categories"
:fields [(merge
(field-details (Field (mt/id :categories :id)))
{:table_id (mt/id :categories)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none"})
(merge
(field-details (Field (mt/id :categories :name)))
{:table_id (mt/id :categories)
:semantic_type "type/Name"
:name "NAME"
:display_name "Name"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:database_position 1
:position 1})]
:id (mt/id :categories)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))))))
(defn- with-field-literal-id [{field-name :name, base-type :base_type :as field}]
(assoc field :id ["field" field-name {:base-type base-type}]))
(defn- default-card-field-for-venues [table-id]
{:table_id table-id
:semantic_type nil
:default_dimension_option nil
:dimension_options []})
(defn- with-numeric-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/numeric-default-index)
:dimension_options (var-get #'table-api/numeric-dimension-indexes)))
(defn- with-coordinate-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/coordinate-default-index)
:dimension_options (var-get #'table-api/coordinate-dimension-indexes)))
;; Make sure metadata for 'virtual' tables comes back as expected
(deftest virtual-table-metadata-test
(testing "GET /api/table/:id/query_metadata"
(testing "Make sure metadata for 'virtual' tables comes back as expected"
(mt/with-temp Card [card {:name "Go Dubs!"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, ID, PRICE, LATITUDE FROM VENUES")}}}]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table"
(is (= (let [card-virtual-table-id (str "card__" (u/the-id card))]
{:display_name "Go Dubs!"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:moderated_status nil
:description nil
:dimension_options (default-dimension-options)
:fields (map (comp #(merge (default-card-field-for-venues card-virtual-table-id) %)
with-field-literal-id)
[{:name "NAME"
:display_name "NAME"
:base_type "type/Text"
:semantic_type "type/Name"
:fingerprint (:name mutil/venue-fingerprints)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:semantic_type nil
:fingerprint (:id mutil/venue-fingerprints)
:field_ref ["field" "ID" {:base-type "type/BigInteger"}]}
(with-numeric-dimension-options
{:name "PRICE"
:display_name "PRICE"
:base_type "type/Integer"
:semantic_type nil
:fingerprint (:price mutil/venue-fingerprints)
:field_ref ["field" "PRICE" {:base-type "type/Integer"}]})
(with-coordinate-dimension-options
{:name "LATITUDE"
:display_name "LATITUDE"
:base_type "type/Float"
:semantic_type "type/Latitude"
:fingerprint (:latitude mutil/venue-fingerprints)
:field_ref ["field" "LATITUDE" {:base-type "type/Float"}]})])})
(->> card
u/the-id
(format "table/card__%d/query_metadata")
(mt/user-http-request :crowberto :get 200)
(tu/round-fingerprint-cols [:fields])
(mt/round-all-decimals 2))))))))
(deftest include-date-dimensions-in-nested-query-test
(testing "GET /api/table/:id/query_metadata"
(testing "Test date dimensions being included with a nested query"
(mt/with-temp Card [card {:name "Users"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, LAST_LOGIN FROM USERS")}}}]
(let [card-virtual-table-id (str "card__" (u/the-id card))]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table" via the API
(let [[name-metadata last-login-metadata] (db/select-one-field :result_metadata Card :id (u/the-id card))]
(is (= {:display_name "Users"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:description nil
:moderated_status nil
:dimension_options (default-dimension-options)
:fields [{:name "NAME"
:display_name "NAME"
:base_type "type/Text"
:table_id card-virtual-table-id
:id ["field" "NAME" {:base-type "type/Text"}]
:semantic_type "type/Name"
:default_dimension_option nil
:dimension_options []
:fingerprint (:fingerprint name-metadata)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "LAST_LOGIN"
:display_name "LAST_LOGIN"
:base_type "type/DateTime"
:table_id card-virtual-table-id
:id ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]
:semantic_type nil
:default_dimension_option (var-get #'table-api/date-default-index)
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:fingerprint (:fingerprint last-login-metadata)
:field_ref ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]}]}
(mt/user-http-request :crowberto :get 200
(format "table/card__%d/query_metadata" (u/the-id card)))))))))))
(defn- narrow-fields [category-names api-response]
(for [field (:fields api-response)
:when (contains? (set category-names) (:name field))]
(-> field
(select-keys [:id :table_id :name :values :dimensions])
(update :dimensions (fn [dim]
(if (map? dim)
(dissoc dim :id :created_at :updated_at)
dim))))))
(defn- category-id-semantic-type
"Field values will only be returned when the field's semantic type is set to type/Category. This function will change
that for `category_id`, then invoke `f` and roll it back afterwards"
[semantic-type f]
(mt/with-temp-vals-in-db Field (mt/id :venues :category_id) {:semantic_type semantic-type}
(f)))
(deftest query-metadata-remappings-test
(testing "GET /api/table/:id/query_metadata"
(mt/with-column-remappings [venues.category_id (values-of categories.name)]
(testing "Ensure internal remapped dimensions and human_readable_values are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))))))))
(testing "Ensure internal remapped dimensions and human_readable_values are returned when type is enum"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Enum
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))
(mt/with-column-remappings [venues.category_id categories.name]
(testing "Ensure FK remappings are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID"
:field_id (mt/id :venues :category_id)
:human_readable_field_id (mt/id :categories :name)
:type "external"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))))
(deftest dimension-options-sort-test
(testing "Ensure dimensions options are sorted numerically, but returned as strings"
(testing "datetime indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/datetime-dimension-indexes))))
(var-get #'table-api/datetime-dimension-indexes))))
(testing "numeric indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/numeric-dimension-indexes))))
(var-get #'table-api/numeric-dimension-indexes))))))
(defn- dimension-options-for-field [response, ^String field-name]
(->> response
:fields
(m/find-first #(.equalsIgnoreCase field-name, ^String (:name %)))
:dimension_options))
(defn- extract-dimension-options
"For the given `field-name` find it's dimension_options following the indexes given in the field"
[response field-name]
(set
(for [dim-index (dimension-options-for-field response field-name)
:let [{clause :mbql} (get-in response [:dimension_options (keyword dim-index)])]]
clause)))
(deftest numeric-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for numeric fields"
(testing "Lat/Long fields should use bin-width rather than num-bins"
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "bin-width", :bin-width 10.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 0.1}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 1.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 20.0}}]
["field" nil {:binning {:strategy "default"}}]}
(extract-dimension-options response "latitude")))))
(testing "Number columns without a semantic type should use \"num-bins\""
(mt/with-temp-vals-in-db Field (mt/id :venues :price) {:semantic_type nil}
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "num-bins", :num-bins 50}}]
["field" nil {:binning {:strategy "default"}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 100}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 10}}]}
(extract-dimension-options response "price"))))))
(testing "Numeric fields without min/max values should not have binning options"
(let [fingerprint (db/select-one-field :fingerprint Field {:id (mt/id :venues :latitude)})
temp-fingerprint (-> fingerprint
(assoc-in [:type :type/Number :max] nil)
(assoc-in [:type :type/Number :min] nil))]
(mt/with-temp-vals-in-db Field (mt/id :venues :latitude) {:fingerprint temp-fingerprint}
(is (= []
(-> (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))
(get-in [:fields])
first
:dimension_options)))))))))
(deftest datetime-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for datetime fields"
(testing "should show up whether the backend supports binning of numeric values or not"
(mt/test-drivers #{:druid}
(tqpt/with-flattened-dbdef
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp")))))))
(testing "dates"
(mt/test-drivers (mt/normal-drivers)
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "date"))))))
(testing "unix timestamps"
(mt/dataset sad-toucan-incidents
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :incidents)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp"))))))
(testing "time columns"
(mt/test-drivers (mt/normal-drivers-except #{:sparksql :mongo :oracle :redshift})
(mt/dataset test-data-with-time
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users)))]
(is (= []
(dimension-options-for-field response "last_login_time"))))))))))
(deftest nested-queries-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for nested queries"
(mt/test-drivers (mt/normal-drivers-with-feature :binning :nested-queries)
(mt/with-temp Card [card {:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :query
:query {:source-query {:source-table (mt/id :venues)}}}}]
(letfn [(dimension-options []
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(map #(dimension-options-for-field response %) ["latitude" "longitude"])))]
(testing "Nested queries missing a fingerprint/results metadata should not show binning-options"
(mt/with-temp-vals-in-db Card (:id card) {:result_metadata nil}
;; By default result_metadata will be nil (and no fingerprint). Just asking for query_metadata after the
;; card was created but before it was ran should not allow binning
(is (= [nil nil]
(dimension-options)))))
(testing "Nested queries with a fingerprint should have dimension options for binning"
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(is (= (repeat 2 (var-get #'table-api/coordinate-dimension-indexes))
(dimension-options)))))))))))
(deftest related-test
(testing "GET /api/table/:id/related"
(testing "related/recommended entities"
(is (= #{:metrics :segments :linked-from :linking-to :tables}
(-> (mt/user-http-request :crowberto :get 200 (format "table/%s/related" (mt/id :venues))) keys set))))))
(deftest discard-values-test
(testing "POST /api/table/:id/discard_values"
(mt/with-temp* [Table [table {}]
Field [field {:table_id (u/the-id table)}]
FieldValues [field-values {:field_id (u/the-id field), :values ["A" "B" "C"]}]]
(let [url (format "table/%d/discard_values" (u/the-id table))]
(testing "Non-admin toucans should not be allowed to discard values"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 url)))
(testing "FieldValues should still exist"
(is (db/exists? FieldValues :id (u/the-id field-values)))))
(testing "Admins should be able to successfuly delete them"
(is (= {:status "success"}
(mt/user-http-request :crowberto :post 200 url)))
(testing "FieldValues should be gone"
(is (not (db/exists? FieldValues :id (u/the-id field-values))))))))
(testing "For tables that don't exist, we should return a 404."
(is (= "Not found."
(mt/user-http-request :crowberto :post 404 (format "table/%d/discard_values" Integer/MAX_VALUE)))))))
(deftest field-ordering-test
(let [original-field-order (db/select-one-field :field_order Table :id (mt/id :venues))]
(try
(testing "Cane we set alphabetical field ordering?"
(is (= ["CATEGORY_ID" "ID" "LATITUDE" "LONGITUDE" "NAME" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :alphabetical})
:fields
(map :name)))))
(testing "Cane we set smart field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :smart})
:fields
(map :name)))))
(testing "Cane we set database field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :database})
:fields
(map :name)))))
(testing "Cane we set custom field ordering?"
(let [custom-field-order [(mt/id :venues :price) (mt/id :venues :longitude) (mt/id :venues :id)
(mt/id :venues :category_id) (mt/id :venues :name) (mt/id :venues :latitude)]]
(mt/user-http-request :crowberto :put 200 (format "table/%s/fields/order" (mt/id :venues))
{:request-options {:body (json/encode custom-field-order)}})
(is (= custom-field-order
(->> (table/fields (Table (mt/id :venues)))
(map u/the-id))))))
(finally (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order original-field-order})))))
| 114980 | (ns metabase.api.table-test
"Tests for /api/table endpoints."
(:require [cheshire.core :as json]
[clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.api.table :as table-api]
[metabase.driver.util :as driver.u]
[metabase.http-client :as http]
[metabase.mbql.util :as mbql.u]
[metabase.models :refer [Card Database Field FieldValues Table]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.table :as table]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :as mutil]
[metabase.test.util :as tu]
[metabase.timeseries-query-processor-test.util :as tqpt]
[metabase.util :as u]
[toucan.db :as db]))
;; ## /api/org/* AUTHENTICATION Tests
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest unauthenticated-test
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "table")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 (format "table/%d" (mt/id :users))))))
(defn- db-details []
(merge
(select-keys (mt/db) [:id :created_at :updated_at :timezone])
{:engine "h2"
:name "test-data"
:is_sample false
:is_full_sync true
:is_on_demand false
:description nil
:caveats nil
:points_of_interest nil
:features (mapv u/qualified-name (driver.u/features :h2 (mt/db)))
:cache_field_values_schedule "0 50 0 * * ? *"
:metadata_sync_schedule "0 50 * * * ? *"
:options nil
:refingerprint nil
:auto_run_queries true}))
(defn- table-defaults []
(merge
(mt/object-defaults Table)
{:db (db-details)
:entity_type "entity/GenericTable"
:field_order "database"
:metrics []
:segments []}))
(defn- field-defaults []
(merge
(mt/object-defaults Field)
{:default_dimension_option nil
:dimension_options []
:dimensions []
:position 0
:target nil
:visibility_type "normal"}))
(defn- field-details [field]
(merge
(field-defaults)
(select-keys
field
[:created_at :fingerprint :fingerprint_version :fk_target_field_id :id :last_analyzed :updated_at])))
(defn- fk-field-details [field]
(-> (field-details field)
(dissoc :dimension_options :default_dimension_option)))
(deftest list-table-test
(testing "GET /api/table"
(testing "These should come back in alphabetical order and include relevant metadata"
(is (= #{{:name (mt/format-name "categories")
:display_name "Categories"
:id (mt/id :categories)
:entity_type "entity/GenericTable"}
{:name (mt/format-name "checkins")
:display_name "Checkins"
:id (mt/id :checkins)
:entity_type "entity/EventTable"}
{:name (mt/format-name "users")
:display_name "Users"
:id (mt/id :users)
:entity_type "entity/UserTable"}
{:name (mt/format-name "venues")
:display_name "Venues"
:id (mt/id :venues)
:entity_type "entity/GenericTable"}}
(->> (mt/user-http-request :rasta :get 200 "table")
(filter #(= (:db_id %) (mt/id))) ; prevent stray tables from affecting unit test results
(map #(select-keys % [:name :display_name :id :entity_type]))
set))))))
(deftest get-table-test
(testing "GET /api/table/:id"
(is (= (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :created_at :updated_at] :id (mt/id :venues))
{:schema "PUBLIC"
:name "VENUES"
:display_name "Venues"
:pk_field (table/pk-field-id (Table (mt/id :venues)))
:id (mt/id :venues)
:db_id (mt/id)})
(mt/user-http-request :rasta :get 200 (format "table/%d" (mt/id :venues)))))
(testing " should return a 403 for a user that doesn't have read permissions for the table"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]]
(perms/revoke-permissions! (perms-group/all-users) database-id)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "table/" table-id))))))))
(defn- default-dimension-options []
(as-> @#'table-api/dimension-options-for-response options
(m/map-vals #(update % :name str) options)
(walk/keywordize-keys options)
;; since we're comparing API responses, need to de-keywordize the `:field` clauses
(mbql.u/replace options :field (mt/obj->json->obj &match))))
(defn- query-metadata-defaults []
(-> (table-defaults)
(assoc :dimension_options (default-dimension-options))))
(deftest sensitive-fields-included-test
(testing "GET api/table/:id/query_metadata?include_sensitive_fields"
(testing "Sensitive fields are included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "<NAME>"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:semantic_type "type/PK"
:table_id (mt/id :users)
:name "<NAME>"
:display_name "<NAME>"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:visibility_type "normal"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:semantic_type "type/Name"
:table_id (mt/id :users)
:name "<NAME>"
:display_name "<NAME>"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "normal"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "<NAME>"
:display_name "<NAME>"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:visibility_type "normal"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)
(assoc (field-details (Field :table_id (mt/id :users), :name "PASSWORD"))
:semantic_type "type/Category"
:table_id (mt/id :users)
:name "PASSWORD"
:display_name "Password"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "sensitive"
:has_field_values "list"
:position 3
:database_position 3)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata?include_sensitive_fields=true" (mt/id :users))))
"Make sure that getting the User table *does* include info about the password field, but not actual values themselves"))))
(deftest sensitive-fields-not-included-test
(testing "GET api/table/:id/query_metadata"
(testing "Sensitive fields should not be included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:table_id (mt/id :users)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:table_id (mt/id :users)
:semantic_type "type/Name"
:name "NAME"
:display_name "Name"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "<NAME>"
:display_name "<NAME>"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users))))
"Make sure that getting the User table does *not* include password info"))))
(deftest fk-target-permissions-test
(testing "GET /api/table/:id/query_metadata"
(testing (str "Check that FK fields belonging to Tables we don't have permissions for don't come back as hydrated "
"`:target`(#3867)")
;; create a temp DB with two tables; table-2 has an FK to table-1
(mt/with-temp* [Database [db]
Table [table-1 {:db_id (u/the-id db)}]
Table [table-2 {:db_id (u/the-id db)}]
Field [table-1-id {:table_id (u/the-id table-1), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-id {:table_id (u/the-id table-2), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-fk {:table_id (u/the-id table-2), :name "fk", :base_type :type/Integer, :semantic_type :type/FK, :fk_target_field_id (u/the-id table-1-id)}]]
;; grant permissions only to table-2
(perms/revoke-permissions! (perms-group/all-users) (u/the-id db))
(perms/grant-permissions! (perms-group/all-users) (u/the-id db) (:schema table-2) (u/the-id table-2))
;; metadata for table-2 should show all fields for table-2, but the FK target info shouldn't be hydrated
(is (= #{{:name "id", :target false}
{:name "fk", :target false}}
(set (for [field (:fields (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table-2))))]
(-> (select-keys field [:name :target])
(update :target boolean))))))))))
(deftest update-table-test
(testing "PUT /api/table/:id"
(mt/with-temp Table [table]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (u/the-id table))
{:display_name "<NAME>"
:visibility_type "hidden"
:description "What a nice table!"})
(is (= (merge
(-> (table-defaults)
(dissoc :segments :field_values :metrics :updated_at)
(assoc-in [:db :details] (:details (mt/db))))
(db/select-one [Table :id :schema :name :created_at] :id (u/the-id table))
{:description "What a nice table!"
:entity_type nil
:visibility_type "hidden"
:display_name "<NAME>"
:pk_field (table/pk-field-id table)})
(dissoc (mt/user-http-request :crowberto :get 200 (format "table/%d" (u/the-id table)))
:updated_at))))))
;; see how many times sync-table! gets called when we call the PUT endpoint. It should happen when you switch from
;; hidden -> not hidden at the spots marked below, twice total
(deftest update-table-sync-test
(testing "PUT /api/table/:id"
(testing "Table should get synced when it gets unhidden"
(mt/with-temp Table [table]
(let [called (atom 0)
;; original is private so a var will pick up the redef'd. need contents of var before
original (var-get #'table-api/sync-unhidden-tables)]
(with-redefs [table-api/sync-unhidden-tables
(fn [unhidden]
(when (seq unhidden)
(is (= (:id table)
(:id (first unhidden)))
"Unhidden callback did not get correct tables.")
(swap! called inc)
(let [fut (original unhidden)]
(when (future? fut)
(deref fut)))))]
(let [set-visibility (fn [state]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (:id table))
{:display_name "<NAME>"
:visibility_type state
:description "What a nice table!"}))]
(set-visibility "hidden")
(set-visibility nil) ; <- should get synced
(is (= 1
@called))
(set-visibility "hidden")
(set-visibility "cruft")
(set-visibility "technical")
(set-visibility nil) ; <- should get synced again
(is (= 2
@called))
(set-visibility "technical")
(is (= 2
@called))))))))
(testing "Bulk updating visibility"
(let [unhidden-ids (atom #{})]
(mt/with-temp* [Table [{id-1 :id} {}]
Table [{id-2 :id} {:visibility_type "hidden"}]]
(with-redefs [table-api/sync-unhidden-tables (fn [unhidden] (reset! unhidden-ids (set (map :id unhidden))))]
(let [set-many-vis (fn [ids state]
(reset! unhidden-ids #{})
(mt/user-http-request :crowberto :put 200 "table/"
{:ids ids :visibility_type state}))]
(set-many-vis [id-1 id-2] nil) ;; unhides only 2
(is (= @unhidden-ids #{id-2}))
(set-many-vis [id-1 id-2] "hidden")
(is (= @unhidden-ids #{})) ;; no syncing when they are hidden
(set-many-vis [id-1 id-2] nil) ;; both are made unhidden so both synced
(is (= @unhidden-ids #{id-1 id-2}))))))))
(deftest get-fks-test
(testing "GET /api/table/:id/fks"
(testing "We expect a single FK from CHECKINS.USER_ID -> USERS.ID"
(let [checkins-user-field (Field (mt/id :checkins :user_id))
users-id-field (Field (mt/id :users :id))
fk-field-defaults (dissoc (field-defaults) :target :dimension_options :default_dimension_option)]
(is (= [{:origin_id (:id checkins-user-field)
:destination_id (:id users-id-field)
:relationship "Mt1"
:origin (-> (fk-field-details checkins-user-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :checkins)
:name "USER_ID"
:display_name "<NAME> ID"
:database_type "INTEGER"
:base_type "type/Integer"
:effective_type "type/Integer"
:semantic_type "type/FK"
:database_position 2
:position 2
:table (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :checkins))
{:schema "PUBLIC"
:name "CHECKINS"
:display_name "Checkins"
:entity_type "entity/EventTable"})))
:destination (-> (fk-field-details users-id-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :users)
:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:database_type "BIGINT"
:semantic_type "type/PK"
:table (merge
(dissoc (table-defaults) :db :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"})))}]
(mt/user-http-request :rasta :get 200 (format "table/%d/fks" (mt/id :users)))))))
(testing "should just return nothing for 'virtual' tables"
(is (= []
(mt/user-http-request :crowberto :get 200 "table/card__1000/fks"))))))
(deftest basic-query-metadata-test
(testing "GET /api/table/:id/query_metadata"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :categories))
{:schema "PUBLIC"
:name "CATEGORIES"
:display_name "Categories"
:fields [(merge
(field-details (Field (mt/id :categories :id)))
{:table_id (mt/id :categories)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none"})
(merge
(field-details (Field (mt/id :categories :name)))
{:table_id (mt/id :categories)
:semantic_type "type/Name"
:name "<NAME>"
:display_name "<NAME>"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:database_position 1
:position 1})]
:id (mt/id :categories)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))))))
(defn- with-field-literal-id [{field-name :name, base-type :base_type :as field}]
(assoc field :id ["field" field-name {:base-type base-type}]))
(defn- default-card-field-for-venues [table-id]
{:table_id table-id
:semantic_type nil
:default_dimension_option nil
:dimension_options []})
(defn- with-numeric-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/numeric-default-index)
:dimension_options (var-get #'table-api/numeric-dimension-indexes)))
(defn- with-coordinate-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/coordinate-default-index)
:dimension_options (var-get #'table-api/coordinate-dimension-indexes)))
;; Make sure metadata for 'virtual' tables comes back as expected
(deftest virtual-table-metadata-test
(testing "GET /api/table/:id/query_metadata"
(testing "Make sure metadata for 'virtual' tables comes back as expected"
(mt/with-temp Card [card {:name "Go Dubs!"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, ID, PRICE, LATITUDE FROM VENUES")}}}]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table"
(is (= (let [card-virtual-table-id (str "card__" (u/the-id card))]
{:display_name "<NAME>!"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:moderated_status nil
:description nil
:dimension_options (default-dimension-options)
:fields (map (comp #(merge (default-card-field-for-venues card-virtual-table-id) %)
with-field-literal-id)
[{:name "<NAME>"
:display_name "<NAME>"
:base_type "type/Text"
:semantic_type "type/Name"
:fingerprint (:name mutil/venue-fingerprints)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:semantic_type nil
:fingerprint (:id mutil/venue-fingerprints)
:field_ref ["field" "ID" {:base-type "type/BigInteger"}]}
(with-numeric-dimension-options
{:name "PRICE"
:display_name "PRICE"
:base_type "type/Integer"
:semantic_type nil
:fingerprint (:price mutil/venue-fingerprints)
:field_ref ["field" "PRICE" {:base-type "type/Integer"}]})
(with-coordinate-dimension-options
{:name "LATITUDE"
:display_name "LATITUDE"
:base_type "type/Float"
:semantic_type "type/Latitude"
:fingerprint (:latitude mutil/venue-fingerprints)
:field_ref ["field" "LATITUDE" {:base-type "type/Float"}]})])})
(->> card
u/the-id
(format "table/card__%d/query_metadata")
(mt/user-http-request :crowberto :get 200)
(tu/round-fingerprint-cols [:fields])
(mt/round-all-decimals 2))))))))
(deftest include-date-dimensions-in-nested-query-test
(testing "GET /api/table/:id/query_metadata"
(testing "Test date dimensions being included with a nested query"
(mt/with-temp Card [card {:name "<NAME>"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, LAST_LOGIN FROM USERS")}}}]
(let [card-virtual-table-id (str "card__" (u/the-id card))]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table" via the API
(let [[name-metadata last-login-metadata] (db/select-one-field :result_metadata Card :id (u/the-id card))]
(is (= {:display_name "<NAME>"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:description nil
:moderated_status nil
:dimension_options (default-dimension-options)
:fields [{:name "<NAME>"
:display_name "<NAME>"
:base_type "type/Text"
:table_id card-virtual-table-id
:id ["field" "NAME" {:base-type "type/Text"}]
:semantic_type "type/Name"
:default_dimension_option nil
:dimension_options []
:fingerprint (:fingerprint name-metadata)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "<NAME>"
:display_name "<NAME>"
:base_type "type/DateTime"
:table_id card-virtual-table-id
:id ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]
:semantic_type nil
:default_dimension_option (var-get #'table-api/date-default-index)
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:fingerprint (:fingerprint last-login-metadata)
:field_ref ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]}]}
(mt/user-http-request :crowberto :get 200
(format "table/card__%d/query_metadata" (u/the-id card)))))))))))
(defn- narrow-fields [category-names api-response]
(for [field (:fields api-response)
:when (contains? (set category-names) (:name field))]
(-> field
(select-keys [:id :table_id :name :values :dimensions])
(update :dimensions (fn [dim]
(if (map? dim)
(dissoc dim :id :created_at :updated_at)
dim))))))
(defn- category-id-semantic-type
"Field values will only be returned when the field's semantic type is set to type/Category. This function will change
that for `category_id`, then invoke `f` and roll it back afterwards"
[semantic-type f]
(mt/with-temp-vals-in-db Field (mt/id :venues :category_id) {:semantic_type semantic-type}
(f)))
(deftest query-metadata-remappings-test
(testing "GET /api/table/:id/query_metadata"
(mt/with-column-remappings [venues.category_id (values-of categories.name)]
(testing "Ensure internal remapped dimensions and human_readable_values are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))))))))
(testing "Ensure internal remapped dimensions and human_readable_values are returned when type is enum"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Enum
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))
(mt/with-column-remappings [venues.category_id categories.name]
(testing "Ensure FK remappings are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID"
:field_id (mt/id :venues :category_id)
:human_readable_field_id (mt/id :categories :name)
:type "external"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))))
(deftest dimension-options-sort-test
(testing "Ensure dimensions options are sorted numerically, but returned as strings"
(testing "datetime indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/datetime-dimension-indexes))))
(var-get #'table-api/datetime-dimension-indexes))))
(testing "numeric indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/numeric-dimension-indexes))))
(var-get #'table-api/numeric-dimension-indexes))))))
(defn- dimension-options-for-field [response, ^String field-name]
(->> response
:fields
(m/find-first #(.equalsIgnoreCase field-name, ^String (:name %)))
:dimension_options))
(defn- extract-dimension-options
"For the given `field-name` find it's dimension_options following the indexes given in the field"
[response field-name]
(set
(for [dim-index (dimension-options-for-field response field-name)
:let [{clause :mbql} (get-in response [:dimension_options (keyword dim-index)])]]
clause)))
(deftest numeric-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for numeric fields"
(testing "Lat/Long fields should use bin-width rather than num-bins"
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "bin-width", :bin-width 10.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 0.1}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 1.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 20.0}}]
["field" nil {:binning {:strategy "default"}}]}
(extract-dimension-options response "latitude")))))
(testing "Number columns without a semantic type should use \"num-bins\""
(mt/with-temp-vals-in-db Field (mt/id :venues :price) {:semantic_type nil}
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "num-bins", :num-bins 50}}]
["field" nil {:binning {:strategy "default"}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 100}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 10}}]}
(extract-dimension-options response "price"))))))
(testing "Numeric fields without min/max values should not have binning options"
(let [fingerprint (db/select-one-field :fingerprint Field {:id (mt/id :venues :latitude)})
temp-fingerprint (-> fingerprint
(assoc-in [:type :type/Number :max] nil)
(assoc-in [:type :type/Number :min] nil))]
(mt/with-temp-vals-in-db Field (mt/id :venues :latitude) {:fingerprint temp-fingerprint}
(is (= []
(-> (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))
(get-in [:fields])
first
:dimension_options)))))))))
(deftest datetime-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for datetime fields"
(testing "should show up whether the backend supports binning of numeric values or not"
(mt/test-drivers #{:druid}
(tqpt/with-flattened-dbdef
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp")))))))
(testing "dates"
(mt/test-drivers (mt/normal-drivers)
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "date"))))))
(testing "unix timestamps"
(mt/dataset sad-toucan-incidents
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :incidents)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp"))))))
(testing "time columns"
(mt/test-drivers (mt/normal-drivers-except #{:sparksql :mongo :oracle :redshift})
(mt/dataset test-data-with-time
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users)))]
(is (= []
(dimension-options-for-field response "last_login_time"))))))))))
(deftest nested-queries-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for nested queries"
(mt/test-drivers (mt/normal-drivers-with-feature :binning :nested-queries)
(mt/with-temp Card [card {:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :query
:query {:source-query {:source-table (mt/id :venues)}}}}]
(letfn [(dimension-options []
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(map #(dimension-options-for-field response %) ["latitude" "longitude"])))]
(testing "Nested queries missing a fingerprint/results metadata should not show binning-options"
(mt/with-temp-vals-in-db Card (:id card) {:result_metadata nil}
;; By default result_metadata will be nil (and no fingerprint). Just asking for query_metadata after the
;; card was created but before it was ran should not allow binning
(is (= [nil nil]
(dimension-options)))))
(testing "Nested queries with a fingerprint should have dimension options for binning"
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(is (= (repeat 2 (var-get #'table-api/coordinate-dimension-indexes))
(dimension-options)))))))))))
(deftest related-test
(testing "GET /api/table/:id/related"
(testing "related/recommended entities"
(is (= #{:metrics :segments :linked-from :linking-to :tables}
(-> (mt/user-http-request :crowberto :get 200 (format "table/%s/related" (mt/id :venues))) keys set))))))
(deftest discard-values-test
(testing "POST /api/table/:id/discard_values"
(mt/with-temp* [Table [table {}]
Field [field {:table_id (u/the-id table)}]
FieldValues [field-values {:field_id (u/the-id field), :values ["A" "B" "C"]}]]
(let [url (format "table/%d/discard_values" (u/the-id table))]
(testing "Non-admin toucans should not be allowed to discard values"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 url)))
(testing "FieldValues should still exist"
(is (db/exists? FieldValues :id (u/the-id field-values)))))
(testing "Admins should be able to successfuly delete them"
(is (= {:status "success"}
(mt/user-http-request :crowberto :post 200 url)))
(testing "FieldValues should be gone"
(is (not (db/exists? FieldValues :id (u/the-id field-values))))))))
(testing "For tables that don't exist, we should return a 404."
(is (= "Not found."
(mt/user-http-request :crowberto :post 404 (format "table/%d/discard_values" Integer/MAX_VALUE)))))))
(deftest field-ordering-test
(let [original-field-order (db/select-one-field :field_order Table :id (mt/id :venues))]
(try
(testing "Cane we set alphabetical field ordering?"
(is (= ["CATEGORY_ID" "ID" "LATITUDE" "LONGITUDE" "NAME" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :alphabetical})
:fields
(map :name)))))
(testing "Cane we set smart field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :smart})
:fields
(map :name)))))
(testing "Cane we set database field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :database})
:fields
(map :name)))))
(testing "Cane we set custom field ordering?"
(let [custom-field-order [(mt/id :venues :price) (mt/id :venues :longitude) (mt/id :venues :id)
(mt/id :venues :category_id) (mt/id :venues :name) (mt/id :venues :latitude)]]
(mt/user-http-request :crowberto :put 200 (format "table/%s/fields/order" (mt/id :venues))
{:request-options {:body (json/encode custom-field-order)}})
(is (= custom-field-order
(->> (table/fields (Table (mt/id :venues)))
(map u/the-id))))))
(finally (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order original-field-order})))))
| true | (ns metabase.api.table-test
"Tests for /api/table endpoints."
(:require [cheshire.core :as json]
[clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.api.table :as table-api]
[metabase.driver.util :as driver.u]
[metabase.http-client :as http]
[metabase.mbql.util :as mbql.u]
[metabase.models :refer [Card Database Field FieldValues Table]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.table :as table]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :as mutil]
[metabase.test.util :as tu]
[metabase.timeseries-query-processor-test.util :as tqpt]
[metabase.util :as u]
[toucan.db :as db]))
;; ## /api/org/* AUTHENTICATION Tests
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest unauthenticated-test
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "table")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 (format "table/%d" (mt/id :users))))))
(defn- db-details []
(merge
(select-keys (mt/db) [:id :created_at :updated_at :timezone])
{:engine "h2"
:name "test-data"
:is_sample false
:is_full_sync true
:is_on_demand false
:description nil
:caveats nil
:points_of_interest nil
:features (mapv u/qualified-name (driver.u/features :h2 (mt/db)))
:cache_field_values_schedule "0 50 0 * * ? *"
:metadata_sync_schedule "0 50 * * * ? *"
:options nil
:refingerprint nil
:auto_run_queries true}))
(defn- table-defaults []
(merge
(mt/object-defaults Table)
{:db (db-details)
:entity_type "entity/GenericTable"
:field_order "database"
:metrics []
:segments []}))
(defn- field-defaults []
(merge
(mt/object-defaults Field)
{:default_dimension_option nil
:dimension_options []
:dimensions []
:position 0
:target nil
:visibility_type "normal"}))
(defn- field-details [field]
(merge
(field-defaults)
(select-keys
field
[:created_at :fingerprint :fingerprint_version :fk_target_field_id :id :last_analyzed :updated_at])))
(defn- fk-field-details [field]
(-> (field-details field)
(dissoc :dimension_options :default_dimension_option)))
(deftest list-table-test
(testing "GET /api/table"
(testing "These should come back in alphabetical order and include relevant metadata"
(is (= #{{:name (mt/format-name "categories")
:display_name "Categories"
:id (mt/id :categories)
:entity_type "entity/GenericTable"}
{:name (mt/format-name "checkins")
:display_name "Checkins"
:id (mt/id :checkins)
:entity_type "entity/EventTable"}
{:name (mt/format-name "users")
:display_name "Users"
:id (mt/id :users)
:entity_type "entity/UserTable"}
{:name (mt/format-name "venues")
:display_name "Venues"
:id (mt/id :venues)
:entity_type "entity/GenericTable"}}
(->> (mt/user-http-request :rasta :get 200 "table")
(filter #(= (:db_id %) (mt/id))) ; prevent stray tables from affecting unit test results
(map #(select-keys % [:name :display_name :id :entity_type]))
set))))))
(deftest get-table-test
(testing "GET /api/table/:id"
(is (= (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :created_at :updated_at] :id (mt/id :venues))
{:schema "PUBLIC"
:name "VENUES"
:display_name "Venues"
:pk_field (table/pk-field-id (Table (mt/id :venues)))
:id (mt/id :venues)
:db_id (mt/id)})
(mt/user-http-request :rasta :get 200 (format "table/%d" (mt/id :venues)))))
(testing " should return a 403 for a user that doesn't have read permissions for the table"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]]
(perms/revoke-permissions! (perms-group/all-users) database-id)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "table/" table-id))))))))
(defn- default-dimension-options []
(as-> @#'table-api/dimension-options-for-response options
(m/map-vals #(update % :name str) options)
(walk/keywordize-keys options)
;; since we're comparing API responses, need to de-keywordize the `:field` clauses
(mbql.u/replace options :field (mt/obj->json->obj &match))))
(defn- query-metadata-defaults []
(-> (table-defaults)
(assoc :dimension_options (default-dimension-options))))
(deftest sensitive-fields-included-test
(testing "GET api/table/:id/query_metadata?include_sensitive_fields"
(testing "Sensitive fields are included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "PI:NAME:<NAME>END_PI"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:semantic_type "type/PK"
:table_id (mt/id :users)
:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:visibility_type "normal"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:semantic_type "type/Name"
:table_id (mt/id :users)
:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "normal"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:visibility_type "normal"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)
(assoc (field-details (Field :table_id (mt/id :users), :name "PASSWORD"))
:semantic_type "type/Category"
:table_id (mt/id :users)
:name "PASSWORD"
:display_name "Password"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:visibility_type "sensitive"
:has_field_values "list"
:position 3
:database_position 3)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata?include_sensitive_fields=true" (mt/id :users))))
"Make sure that getting the User table *does* include info about the password field, but not actual values themselves"))))
(deftest sensitive-fields-not-included-test
(testing "GET api/table/:id/query_metadata"
(testing "Sensitive fields should not be included"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"
:fields [(assoc (field-details (Field (mt/id :users :id)))
:table_id (mt/id :users)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none")
(assoc (field-details (Field (mt/id :users :name)))
:table_id (mt/id :users)
:semantic_type "type/Name"
:name "NAME"
:display_name "Name"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:has_field_values "list"
:position 1
:database_position 1)
(assoc (field-details (Field (mt/id :users :last_login)))
:table_id (mt/id :users)
:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:database_type "TIMESTAMP"
:base_type "type/DateTime"
:effective_type "type/DateTime"
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:default_dimension_option (var-get #'table-api/date-default-index)
:has_field_values "none"
:position 2
:database_position 2)]
:id (mt/id :users)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users))))
"Make sure that getting the User table does *not* include password info"))))
(deftest fk-target-permissions-test
(testing "GET /api/table/:id/query_metadata"
(testing (str "Check that FK fields belonging to Tables we don't have permissions for don't come back as hydrated "
"`:target`(#3867)")
;; create a temp DB with two tables; table-2 has an FK to table-1
(mt/with-temp* [Database [db]
Table [table-1 {:db_id (u/the-id db)}]
Table [table-2 {:db_id (u/the-id db)}]
Field [table-1-id {:table_id (u/the-id table-1), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-id {:table_id (u/the-id table-2), :name "id", :base_type :type/Integer, :semantic_type :type/PK}]
Field [table-2-fk {:table_id (u/the-id table-2), :name "fk", :base_type :type/Integer, :semantic_type :type/FK, :fk_target_field_id (u/the-id table-1-id)}]]
;; grant permissions only to table-2
(perms/revoke-permissions! (perms-group/all-users) (u/the-id db))
(perms/grant-permissions! (perms-group/all-users) (u/the-id db) (:schema table-2) (u/the-id table-2))
;; metadata for table-2 should show all fields for table-2, but the FK target info shouldn't be hydrated
(is (= #{{:name "id", :target false}
{:name "fk", :target false}}
(set (for [field (:fields (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table-2))))]
(-> (select-keys field [:name :target])
(update :target boolean))))))))))
(deftest update-table-test
(testing "PUT /api/table/:id"
(mt/with-temp Table [table]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (u/the-id table))
{:display_name "PI:NAME:<NAME>END_PI"
:visibility_type "hidden"
:description "What a nice table!"})
(is (= (merge
(-> (table-defaults)
(dissoc :segments :field_values :metrics :updated_at)
(assoc-in [:db :details] (:details (mt/db))))
(db/select-one [Table :id :schema :name :created_at] :id (u/the-id table))
{:description "What a nice table!"
:entity_type nil
:visibility_type "hidden"
:display_name "PI:NAME:<NAME>END_PI"
:pk_field (table/pk-field-id table)})
(dissoc (mt/user-http-request :crowberto :get 200 (format "table/%d" (u/the-id table)))
:updated_at))))))
;; see how many times sync-table! gets called when we call the PUT endpoint. It should happen when you switch from
;; hidden -> not hidden at the spots marked below, twice total
(deftest update-table-sync-test
(testing "PUT /api/table/:id"
(testing "Table should get synced when it gets unhidden"
(mt/with-temp Table [table]
(let [called (atom 0)
;; original is private so a var will pick up the redef'd. need contents of var before
original (var-get #'table-api/sync-unhidden-tables)]
(with-redefs [table-api/sync-unhidden-tables
(fn [unhidden]
(when (seq unhidden)
(is (= (:id table)
(:id (first unhidden)))
"Unhidden callback did not get correct tables.")
(swap! called inc)
(let [fut (original unhidden)]
(when (future? fut)
(deref fut)))))]
(let [set-visibility (fn [state]
(mt/user-http-request :crowberto :put 200 (format "table/%d" (:id table))
{:display_name "PI:NAME:<NAME>END_PI"
:visibility_type state
:description "What a nice table!"}))]
(set-visibility "hidden")
(set-visibility nil) ; <- should get synced
(is (= 1
@called))
(set-visibility "hidden")
(set-visibility "cruft")
(set-visibility "technical")
(set-visibility nil) ; <- should get synced again
(is (= 2
@called))
(set-visibility "technical")
(is (= 2
@called))))))))
(testing "Bulk updating visibility"
(let [unhidden-ids (atom #{})]
(mt/with-temp* [Table [{id-1 :id} {}]
Table [{id-2 :id} {:visibility_type "hidden"}]]
(with-redefs [table-api/sync-unhidden-tables (fn [unhidden] (reset! unhidden-ids (set (map :id unhidden))))]
(let [set-many-vis (fn [ids state]
(reset! unhidden-ids #{})
(mt/user-http-request :crowberto :put 200 "table/"
{:ids ids :visibility_type state}))]
(set-many-vis [id-1 id-2] nil) ;; unhides only 2
(is (= @unhidden-ids #{id-2}))
(set-many-vis [id-1 id-2] "hidden")
(is (= @unhidden-ids #{})) ;; no syncing when they are hidden
(set-many-vis [id-1 id-2] nil) ;; both are made unhidden so both synced
(is (= @unhidden-ids #{id-1 id-2}))))))))
(deftest get-fks-test
(testing "GET /api/table/:id/fks"
(testing "We expect a single FK from CHECKINS.USER_ID -> USERS.ID"
(let [checkins-user-field (Field (mt/id :checkins :user_id))
users-id-field (Field (mt/id :users :id))
fk-field-defaults (dissoc (field-defaults) :target :dimension_options :default_dimension_option)]
(is (= [{:origin_id (:id checkins-user-field)
:destination_id (:id users-id-field)
:relationship "Mt1"
:origin (-> (fk-field-details checkins-user-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :checkins)
:name "USER_ID"
:display_name "PI:NAME:<NAME>END_PI ID"
:database_type "INTEGER"
:base_type "type/Integer"
:effective_type "type/Integer"
:semantic_type "type/FK"
:database_position 2
:position 2
:table (merge
(dissoc (table-defaults) :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :checkins))
{:schema "PUBLIC"
:name "CHECKINS"
:display_name "Checkins"
:entity_type "entity/EventTable"})))
:destination (-> (fk-field-details users-id-field)
(dissoc :target :dimensions :values)
(assoc :table_id (mt/id :users)
:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:database_type "BIGINT"
:semantic_type "type/PK"
:table (merge
(dissoc (table-defaults) :db :segments :field_values :metrics)
(db/select-one [Table :id :created_at :updated_at]
:id (mt/id :users))
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
:entity_type "entity/UserTable"})))}]
(mt/user-http-request :rasta :get 200 (format "table/%d/fks" (mt/id :users)))))))
(testing "should just return nothing for 'virtual' tables"
(is (= []
(mt/user-http-request :crowberto :get 200 "table/card__1000/fks"))))))
(deftest basic-query-metadata-test
(testing "GET /api/table/:id/query_metadata"
(is (= (merge
(query-metadata-defaults)
(db/select-one [Table :created_at :updated_at] :id (mt/id :categories))
{:schema "PUBLIC"
:name "CATEGORIES"
:display_name "Categories"
:fields [(merge
(field-details (Field (mt/id :categories :id)))
{:table_id (mt/id :categories)
:semantic_type "type/PK"
:name "ID"
:display_name "ID"
:database_type "BIGINT"
:base_type "type/BigInteger"
:effective_type "type/BigInteger"
:has_field_values "none"})
(merge
(field-details (Field (mt/id :categories :name)))
{:table_id (mt/id :categories)
:semantic_type "type/Name"
:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:database_type "VARCHAR"
:base_type "type/Text"
:effective_type "type/Text"
:dimension_options []
:default_dimension_option nil
:has_field_values "list"
:database_position 1
:position 1})]
:id (mt/id :categories)})
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))))))
(defn- with-field-literal-id [{field-name :name, base-type :base_type :as field}]
(assoc field :id ["field" field-name {:base-type base-type}]))
(defn- default-card-field-for-venues [table-id]
{:table_id table-id
:semantic_type nil
:default_dimension_option nil
:dimension_options []})
(defn- with-numeric-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/numeric-default-index)
:dimension_options (var-get #'table-api/numeric-dimension-indexes)))
(defn- with-coordinate-dimension-options [field]
(assoc field
:default_dimension_option (var-get #'table-api/coordinate-default-index)
:dimension_options (var-get #'table-api/coordinate-dimension-indexes)))
;; Make sure metadata for 'virtual' tables comes back as expected
(deftest virtual-table-metadata-test
(testing "GET /api/table/:id/query_metadata"
(testing "Make sure metadata for 'virtual' tables comes back as expected"
(mt/with-temp Card [card {:name "Go Dubs!"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, ID, PRICE, LATITUDE FROM VENUES")}}}]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table"
(is (= (let [card-virtual-table-id (str "card__" (u/the-id card))]
{:display_name "PI:NAME:<NAME>END_PI!"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:moderated_status nil
:description nil
:dimension_options (default-dimension-options)
:fields (map (comp #(merge (default-card-field-for-venues card-virtual-table-id) %)
with-field-literal-id)
[{:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:base_type "type/Text"
:semantic_type "type/Name"
:fingerprint (:name mutil/venue-fingerprints)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "ID"
:display_name "ID"
:base_type "type/BigInteger"
:semantic_type nil
:fingerprint (:id mutil/venue-fingerprints)
:field_ref ["field" "ID" {:base-type "type/BigInteger"}]}
(with-numeric-dimension-options
{:name "PRICE"
:display_name "PRICE"
:base_type "type/Integer"
:semantic_type nil
:fingerprint (:price mutil/venue-fingerprints)
:field_ref ["field" "PRICE" {:base-type "type/Integer"}]})
(with-coordinate-dimension-options
{:name "LATITUDE"
:display_name "LATITUDE"
:base_type "type/Float"
:semantic_type "type/Latitude"
:fingerprint (:latitude mutil/venue-fingerprints)
:field_ref ["field" "LATITUDE" {:base-type "type/Float"}]})])})
(->> card
u/the-id
(format "table/card__%d/query_metadata")
(mt/user-http-request :crowberto :get 200)
(tu/round-fingerprint-cols [:fields])
(mt/round-all-decimals 2))))))))
(deftest include-date-dimensions-in-nested-query-test
(testing "GET /api/table/:id/query_metadata"
(testing "Test date dimensions being included with a nested query"
(mt/with-temp Card [card {:name "PI:NAME:<NAME>END_PI"
:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :native
:native {:query (format "SELECT NAME, LAST_LOGIN FROM USERS")}}}]
(let [card-virtual-table-id (str "card__" (u/the-id card))]
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
;; Now fetch the metadata for this "table" via the API
(let [[name-metadata last-login-metadata] (db/select-one-field :result_metadata Card :id (u/the-id card))]
(is (= {:display_name "PI:NAME:<NAME>END_PI"
:schema "Everything else"
:db_id (:database_id card)
:id card-virtual-table-id
:description nil
:moderated_status nil
:dimension_options (default-dimension-options)
:fields [{:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:base_type "type/Text"
:table_id card-virtual-table-id
:id ["field" "NAME" {:base-type "type/Text"}]
:semantic_type "type/Name"
:default_dimension_option nil
:dimension_options []
:fingerprint (:fingerprint name-metadata)
:field_ref ["field" "NAME" {:base-type "type/Text"}]}
{:name "PI:NAME:<NAME>END_PI"
:display_name "PI:NAME:<NAME>END_PI"
:base_type "type/DateTime"
:table_id card-virtual-table-id
:id ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]
:semantic_type nil
:default_dimension_option (var-get #'table-api/date-default-index)
:dimension_options (var-get #'table-api/datetime-dimension-indexes)
:fingerprint (:fingerprint last-login-metadata)
:field_ref ["field" "LAST_LOGIN" {:base-type "type/DateTime"}]}]}
(mt/user-http-request :crowberto :get 200
(format "table/card__%d/query_metadata" (u/the-id card)))))))))))
(defn- narrow-fields [category-names api-response]
(for [field (:fields api-response)
:when (contains? (set category-names) (:name field))]
(-> field
(select-keys [:id :table_id :name :values :dimensions])
(update :dimensions (fn [dim]
(if (map? dim)
(dissoc dim :id :created_at :updated_at)
dim))))))
(defn- category-id-semantic-type
"Field values will only be returned when the field's semantic type is set to type/Category. This function will change
that for `category_id`, then invoke `f` and roll it back afterwards"
[semantic-type f]
(mt/with-temp-vals-in-db Field (mt/id :venues :category_id) {:semantic_type semantic-type}
(f)))
(deftest query-metadata-remappings-test
(testing "GET /api/table/:id/query_metadata"
(mt/with-column-remappings [venues.category_id (values-of categories.name)]
(testing "Ensure internal remapped dimensions and human_readable_values are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))))))))
(testing "Ensure internal remapped dimensions and human_readable_values are returned when type is enum"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID", :field_id (mt/id :venues :category_id), :human_readable_field_id nil, :type "internal"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Enum
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))
(mt/with-column-remappings [venues.category_id categories.name]
(testing "Ensure FK remappings are returned"
(is (= [{:table_id (mt/id :venues)
:id (mt/id :venues :category_id)
:name "CATEGORY_ID"
:dimensions {:name "Category ID"
:field_id (mt/id :venues :category_id)
:human_readable_field_id (mt/id :categories :name)
:type "external"}}
{:id (mt/id :venues :price)
:table_id (mt/id :venues)
:name "PRICE"
:dimensions []}]
(category-id-semantic-type
:type/Category
(fn []
(narrow-fields ["PRICE" "CATEGORY_ID"]
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues))))))))))))
(deftest dimension-options-sort-test
(testing "Ensure dimensions options are sorted numerically, but returned as strings"
(testing "datetime indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/datetime-dimension-indexes))))
(var-get #'table-api/datetime-dimension-indexes))))
(testing "numeric indexes"
(is (= (map str (sort (map #(Long/parseLong %) (var-get #'table-api/numeric-dimension-indexes))))
(var-get #'table-api/numeric-dimension-indexes))))))
(defn- dimension-options-for-field [response, ^String field-name]
(->> response
:fields
(m/find-first #(.equalsIgnoreCase field-name, ^String (:name %)))
:dimension_options))
(defn- extract-dimension-options
"For the given `field-name` find it's dimension_options following the indexes given in the field"
[response field-name]
(set
(for [dim-index (dimension-options-for-field response field-name)
:let [{clause :mbql} (get-in response [:dimension_options (keyword dim-index)])]]
clause)))
(deftest numeric-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for numeric fields"
(testing "Lat/Long fields should use bin-width rather than num-bins"
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "bin-width", :bin-width 10.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 0.1}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 1.0}}]
["field" nil {:binning {:strategy "bin-width", :bin-width 20.0}}]
["field" nil {:binning {:strategy "default"}}]}
(extract-dimension-options response "latitude")))))
(testing "Number columns without a semantic type should use \"num-bins\""
(mt/with-temp-vals-in-db Field (mt/id :venues :price) {:semantic_type nil}
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))]
(is (= #{nil
["field" nil {:binning {:strategy "num-bins", :num-bins 50}}]
["field" nil {:binning {:strategy "default"}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 100}}]
["field" nil {:binning {:strategy "num-bins", :num-bins 10}}]}
(extract-dimension-options response "price"))))))
(testing "Numeric fields without min/max values should not have binning options"
(let [fingerprint (db/select-one-field :fingerprint Field {:id (mt/id :venues :latitude)})
temp-fingerprint (-> fingerprint
(assoc-in [:type :type/Number :max] nil)
(assoc-in [:type :type/Number :min] nil))]
(mt/with-temp-vals-in-db Field (mt/id :venues :latitude) {:fingerprint temp-fingerprint}
(is (= []
(-> (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories)))
(get-in [:fields])
first
:dimension_options)))))))))
(deftest datetime-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for datetime fields"
(testing "should show up whether the backend supports binning of numeric values or not"
(mt/test-drivers #{:druid}
(tqpt/with-flattened-dbdef
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp")))))))
(testing "dates"
(mt/test-drivers (mt/normal-drivers)
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :checkins)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "date"))))))
(testing "unix timestamps"
(mt/dataset sad-toucan-incidents
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :incidents)))]
(is (= @#'table-api/datetime-dimension-indexes
(dimension-options-for-field response "timestamp"))))))
(testing "time columns"
(mt/test-drivers (mt/normal-drivers-except #{:sparksql :mongo :oracle :redshift})
(mt/dataset test-data-with-time
(let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :users)))]
(is (= []
(dimension-options-for-field response "last_login_time"))))))))))
(deftest nested-queries-binning-options-test
(testing "GET /api/table/:id/query_metadata"
(testing "binning options for nested queries"
(mt/test-drivers (mt/normal-drivers-with-feature :binning :nested-queries)
(mt/with-temp Card [card {:database_id (mt/id)
:dataset_query {:database (mt/id)
:type :query
:query {:source-query {:source-table (mt/id :venues)}}}}]
(letfn [(dimension-options []
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(map #(dimension-options-for-field response %) ["latitude" "longitude"])))]
(testing "Nested queries missing a fingerprint/results metadata should not show binning-options"
(mt/with-temp-vals-in-db Card (:id card) {:result_metadata nil}
;; By default result_metadata will be nil (and no fingerprint). Just asking for query_metadata after the
;; card was created but before it was ran should not allow binning
(is (= [nil nil]
(dimension-options)))))
(testing "Nested queries with a fingerprint should have dimension options for binning"
;; run the Card which will populate its result_metadata column
(mt/user-http-request :crowberto :post 202 (format "card/%d/query" (u/the-id card)))
(let [response (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" (u/the-id card)))]
(is (= (repeat 2 (var-get #'table-api/coordinate-dimension-indexes))
(dimension-options)))))))))))
(deftest related-test
(testing "GET /api/table/:id/related"
(testing "related/recommended entities"
(is (= #{:metrics :segments :linked-from :linking-to :tables}
(-> (mt/user-http-request :crowberto :get 200 (format "table/%s/related" (mt/id :venues))) keys set))))))
(deftest discard-values-test
(testing "POST /api/table/:id/discard_values"
(mt/with-temp* [Table [table {}]
Field [field {:table_id (u/the-id table)}]
FieldValues [field-values {:field_id (u/the-id field), :values ["A" "B" "C"]}]]
(let [url (format "table/%d/discard_values" (u/the-id table))]
(testing "Non-admin toucans should not be allowed to discard values"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 url)))
(testing "FieldValues should still exist"
(is (db/exists? FieldValues :id (u/the-id field-values)))))
(testing "Admins should be able to successfuly delete them"
(is (= {:status "success"}
(mt/user-http-request :crowberto :post 200 url)))
(testing "FieldValues should be gone"
(is (not (db/exists? FieldValues :id (u/the-id field-values))))))))
(testing "For tables that don't exist, we should return a 404."
(is (= "Not found."
(mt/user-http-request :crowberto :post 404 (format "table/%d/discard_values" Integer/MAX_VALUE)))))))
(deftest field-ordering-test
(let [original-field-order (db/select-one-field :field_order Table :id (mt/id :venues))]
(try
(testing "Cane we set alphabetical field ordering?"
(is (= ["CATEGORY_ID" "ID" "LATITUDE" "LONGITUDE" "NAME" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :alphabetical})
:fields
(map :name)))))
(testing "Cane we set smart field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :smart})
:fields
(map :name)))))
(testing "Cane we set database field ordering?"
(is (= ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]
(->> (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order :database})
:fields
(map :name)))))
(testing "Cane we set custom field ordering?"
(let [custom-field-order [(mt/id :venues :price) (mt/id :venues :longitude) (mt/id :venues :id)
(mt/id :venues :category_id) (mt/id :venues :name) (mt/id :venues :latitude)]]
(mt/user-http-request :crowberto :put 200 (format "table/%s/fields/order" (mt/id :venues))
{:request-options {:body (json/encode custom-field-order)}})
(is (= custom-field-order
(->> (table/fields (Table (mt/id :venues)))
(map u/the-id))))))
(finally (mt/user-http-request :crowberto :put 200 (format "table/%s" (mt/id :venues))
{:field_order original-field-order})))))
|
[
{
"context": "greeting \"Good morning\" \"Clojure\")))\n\n(println \"=> Allez Gut!\")\n\n(defn my-identity [x] x)\n(println (my-identit",
"end": 1034,
"score": 0.994843065738678,
"start": 1025,
"tag": "NAME",
"value": "Allez Gut"
},
{
"context": "assert (= n (apply f 123 (range)))))\n\n(println \"=> Allez OK!\")\n\n(defn triplicate [f]\n (f) (f) (f))\n(tripl",
"end": 1382,
"score": 0.9902661442756653,
"start": 1377,
"tag": "NAME",
"value": "Allez"
}
] | clojure/clojure.clj | scorphus/sparring | 2 | (use '[clojure.string :only (join upper-case)])
(defn messenger-builder [greeting func]
(fn [who] (func greeting who))) ; closes over greeting
;; greeting provided here, then goes out of scope
(def hello-er (messenger-builder "Hello" println))
;; greeting value still available because hello-er is a closure
(println (hello-er "world!"))
;; Hello world!
;; nil
(def hello-er (messenger-builder "Hello" str))
(println (hello-er "world!"))
(def hello-er (messenger-builder "Hello" #(join " " %&)))
(println (hello-er "world!"))
(defn joiner [& args]
(join " " args))
(def hello-er (messenger-builder "Hello" joiner))
(println (hello-er "world!"))
(def greet (fn [] (println "Hello")))
(greet)
(def greet #(println "Hello"))
(greet)
(defn greeting
([] (greeting "World"))
([x] (greeting "Hello" x))
([x, y] (str x ", " y "!")))
(assert (= "Hello, World!" (greeting)))
(assert (= "Hello, Clojure!" (greeting "Clojure")))
(assert (= "Good morning, Clojure!" (greeting "Good morning" "Clojure")))
(println "=> Allez Gut!")
(defn my-identity [x] x)
(println (my-identity 359))
(defn always-thing [& _] 5759)
(println (always-thing 89 179 359 791 1439 2879))
(defn my-constantly [x] (fn [& _] x))
(let [n (rand-int Integer/MAX_VALUE)
f (my-constantly n)]
(assert (= n (f)))
(assert (= n (f 123)))
(assert (= n (apply f 123 (range)))))
(println "=> Allez OK!")
(defn triplicate [f]
(f) (f) (f))
(triplicate #(println "ding!"))
(defn my-complement [f]
(fn [& args] (not (apply f args))))
(let [f (my-complement (fn [] true))]
(println (f)))
(let [f (my-complement #(my-identity false))]
(println (f)))
(let [f (my-complement #(and %1 %2))]
(println (f true true)))
(let [f (my-complement #(and %1 %2))]
(println (f true false)))
(let [f (my-complement #(reduce (fn [a b] (and a b)) %&))]
(println (f true true true false)))
(defn triplicate2 [f & args]
(triplicate #(apply f args)))
(triplicate2 println "ding" "again!")
(println "The cosine of pi is:" (Math/cos Math/PI))
(let [a (Math/pow (Math/cos 359) 2)
b (Math/pow (Math/sin 359) 2)]
(println "For some x, sin(x)^2 + cos(x)^2:" (+ a b)))
(defn http-get [url]
(slurp
(.openStream
(java.net.URL. url))))
(println (http-get "https://api.ipify.org/"))
(defn one-less-arg [f x]
(fn [& args] (apply f x args)))
(def foo (one-less-arg println "first"))
(foo "second")
(defn two-fns [f g]
(fn [arg] (f (g arg))))
(let [foo (two-fns println upper-case)]
(foo "foo"))
| 6056 | (use '[clojure.string :only (join upper-case)])
(defn messenger-builder [greeting func]
(fn [who] (func greeting who))) ; closes over greeting
;; greeting provided here, then goes out of scope
(def hello-er (messenger-builder "Hello" println))
;; greeting value still available because hello-er is a closure
(println (hello-er "world!"))
;; Hello world!
;; nil
(def hello-er (messenger-builder "Hello" str))
(println (hello-er "world!"))
(def hello-er (messenger-builder "Hello" #(join " " %&)))
(println (hello-er "world!"))
(defn joiner [& args]
(join " " args))
(def hello-er (messenger-builder "Hello" joiner))
(println (hello-er "world!"))
(def greet (fn [] (println "Hello")))
(greet)
(def greet #(println "Hello"))
(greet)
(defn greeting
([] (greeting "World"))
([x] (greeting "Hello" x))
([x, y] (str x ", " y "!")))
(assert (= "Hello, World!" (greeting)))
(assert (= "Hello, Clojure!" (greeting "Clojure")))
(assert (= "Good morning, Clojure!" (greeting "Good morning" "Clojure")))
(println "=> <NAME>!")
(defn my-identity [x] x)
(println (my-identity 359))
(defn always-thing [& _] 5759)
(println (always-thing 89 179 359 791 1439 2879))
(defn my-constantly [x] (fn [& _] x))
(let [n (rand-int Integer/MAX_VALUE)
f (my-constantly n)]
(assert (= n (f)))
(assert (= n (f 123)))
(assert (= n (apply f 123 (range)))))
(println "=> <NAME> OK!")
(defn triplicate [f]
(f) (f) (f))
(triplicate #(println "ding!"))
(defn my-complement [f]
(fn [& args] (not (apply f args))))
(let [f (my-complement (fn [] true))]
(println (f)))
(let [f (my-complement #(my-identity false))]
(println (f)))
(let [f (my-complement #(and %1 %2))]
(println (f true true)))
(let [f (my-complement #(and %1 %2))]
(println (f true false)))
(let [f (my-complement #(reduce (fn [a b] (and a b)) %&))]
(println (f true true true false)))
(defn triplicate2 [f & args]
(triplicate #(apply f args)))
(triplicate2 println "ding" "again!")
(println "The cosine of pi is:" (Math/cos Math/PI))
(let [a (Math/pow (Math/cos 359) 2)
b (Math/pow (Math/sin 359) 2)]
(println "For some x, sin(x)^2 + cos(x)^2:" (+ a b)))
(defn http-get [url]
(slurp
(.openStream
(java.net.URL. url))))
(println (http-get "https://api.ipify.org/"))
(defn one-less-arg [f x]
(fn [& args] (apply f x args)))
(def foo (one-less-arg println "first"))
(foo "second")
(defn two-fns [f g]
(fn [arg] (f (g arg))))
(let [foo (two-fns println upper-case)]
(foo "foo"))
| true | (use '[clojure.string :only (join upper-case)])
(defn messenger-builder [greeting func]
(fn [who] (func greeting who))) ; closes over greeting
;; greeting provided here, then goes out of scope
(def hello-er (messenger-builder "Hello" println))
;; greeting value still available because hello-er is a closure
(println (hello-er "world!"))
;; Hello world!
;; nil
(def hello-er (messenger-builder "Hello" str))
(println (hello-er "world!"))
(def hello-er (messenger-builder "Hello" #(join " " %&)))
(println (hello-er "world!"))
(defn joiner [& args]
(join " " args))
(def hello-er (messenger-builder "Hello" joiner))
(println (hello-er "world!"))
(def greet (fn [] (println "Hello")))
(greet)
(def greet #(println "Hello"))
(greet)
(defn greeting
([] (greeting "World"))
([x] (greeting "Hello" x))
([x, y] (str x ", " y "!")))
(assert (= "Hello, World!" (greeting)))
(assert (= "Hello, Clojure!" (greeting "Clojure")))
(assert (= "Good morning, Clojure!" (greeting "Good morning" "Clojure")))
(println "=> PI:NAME:<NAME>END_PI!")
(defn my-identity [x] x)
(println (my-identity 359))
(defn always-thing [& _] 5759)
(println (always-thing 89 179 359 791 1439 2879))
(defn my-constantly [x] (fn [& _] x))
(let [n (rand-int Integer/MAX_VALUE)
f (my-constantly n)]
(assert (= n (f)))
(assert (= n (f 123)))
(assert (= n (apply f 123 (range)))))
(println "=> PI:NAME:<NAME>END_PI OK!")
(defn triplicate [f]
(f) (f) (f))
(triplicate #(println "ding!"))
(defn my-complement [f]
(fn [& args] (not (apply f args))))
(let [f (my-complement (fn [] true))]
(println (f)))
(let [f (my-complement #(my-identity false))]
(println (f)))
(let [f (my-complement #(and %1 %2))]
(println (f true true)))
(let [f (my-complement #(and %1 %2))]
(println (f true false)))
(let [f (my-complement #(reduce (fn [a b] (and a b)) %&))]
(println (f true true true false)))
(defn triplicate2 [f & args]
(triplicate #(apply f args)))
(triplicate2 println "ding" "again!")
(println "The cosine of pi is:" (Math/cos Math/PI))
(let [a (Math/pow (Math/cos 359) 2)
b (Math/pow (Math/sin 359) 2)]
(println "For some x, sin(x)^2 + cos(x)^2:" (+ a b)))
(defn http-get [url]
(slurp
(.openStream
(java.net.URL. url))))
(println (http-get "https://api.ipify.org/"))
(defn one-less-arg [f x]
(fn [& args] (apply f x args)))
(def foo (one-less-arg println "first"))
(foo "second")
(defn two-fns [f g]
(fn [arg] (f (g arg))))
(let [foo (two-fns println upper-case)]
(foo "foo"))
|
[
{
"context": "client name is injected\"\n (let [client-name \"CLIENT_NAME\"\n client-name-elements (-> (th/create-",
"end": 1718,
"score": 0.7551993727684021,
"start": 1707,
"tag": "USERNAME",
"value": "CLIENT_NAME"
},
{
"context": " (assoc-in [:context :user-login] \"valid@web.co.uk\")\n (assoc-in [:context :user",
"end": 2985,
"score": 0.9999219179153442,
"start": 2970,
"tag": "EMAIL",
"value": "valid@web.co.uk"
},
{
"context": " (assoc-in [:context :user-first-name] \"Frank\")\n (assoc-in [:context :user",
"end": 3054,
"score": 0.999748945236206,
"start": 3049,
"tag": "NAME",
"value": "Frank"
},
{
"context": " (assoc-in [:context :user-last-name] \"Lasty\")\n (assoc-in [:context :user",
"end": 3122,
"score": 0.9996596574783325,
"start": 3117,
"tag": "NAME",
"value": "Lasty"
},
{
"context": "/select [:.clj--card-email]) first html/text) => \"valid@web.co.uk\")\n\n (fact \"it should display full name\"\n ",
"end": 3407,
"score": 0.9999231100082397,
"start": 3392,
"tag": "EMAIL",
"value": "valid@web.co.uk"
},
{
"context": "l/select [:.clj--card-name]) first html/text) => \"Frank Lasty\")\n\n (fact \"it should display profile pict",
"end": 3545,
"score": 0.9997148513793945,
"start": 3534,
"tag": "NAME",
"value": "Frank Lasty"
}
] | test/stonecutter/test/view/authorise.clj | d-cent/stonecutter | 39 | (ns stonecutter.test.view.authorise
(:require [midje.sweet :refer :all]
[net.cgrand.enlive-html :as html]
[stonecutter.routes :as r]
[stonecutter.test.view.test-helpers :as th]
[stonecutter.translation :as t]
[stonecutter.view.authorise :refer [authorise-form]]
[stonecutter.helper :as helper]))
(fact "authorise should return some html"
(let [page (-> (th/create-request) authorise-form)]
(html/select page [:body]) =not=> empty?))
(fact "work in progress should be removed from page"
(let [page (-> (th/create-request) authorise-form)]
page => th/work-in-progress-removed))
(fact "there are no missing translations"
(let [translator (t/translations-fn t/translation-map)
page (-> (th/create-request) authorise-form (helper/enlive-response {:translator translator}) :body)]
page => th/no-untranslated-strings))
(fact "authorise form posts to correct endpoint"
(let [page (-> (th/create-request) authorise-form)]
page => (th/has-form-action? [:.func--authorise__form] (r/path :authorise-client))))
(fact "cancel link should go to correct endpoint"
(let [params {:client_id "CLIENT_ID" :redirect_uri "http://where.to.now"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/links-to? [:.func--authorise-cancel__link] (str (r/path :show-authorise-failure)
"?client_id=CLIENT_ID"
"&redirect_uri=http://where.to.now"))))
(fact "client name is injected"
(let [client-name "CLIENT_NAME"
client-name-elements (-> (th/create-request)
(assoc-in [:context :client :name] client-name)
authorise-form
(html/select [:.clj--client-name]))
client-name-is-correct-fn (fn [element] (= (html/text element) client-name))]
client-name-elements =not=> empty?
client-name-elements => (has every? client-name-is-correct-fn)))
(fact "hidden parameters are set"
(let [params {:client_id "CLIENT_ID"
:response_type "RESPONSE_TYPE"
:redirect_uri "REDIRECT_URI"
:scope "SCOPE"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/has-attr? [:.clj--authorise-client-id__input] :value "CLIENT_ID")
page => (th/has-attr? [:.clj--authorise-response-type__input] :value "RESPONSE_TYPE")
page => (th/has-attr? [:.clj--authorise-redirect-uri__input] :value "REDIRECT_URI")
page => (th/has-attr? [:.clj--authorise-scope__input] :value "SCOPE")))
(facts "about displaying profile card"
(let [page (-> (th/create-request)
(assoc-in [:context :user-login] "valid@web.co.uk")
(assoc-in [:context :user-first-name] "Frank")
(assoc-in [:context :user-last-name] "Lasty")
(assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png")
authorise-form)]
(fact "it should display email address"
(-> page (html/select [:.clj--card-email]) first html/text) => "valid@web.co.uk")
(fact "it should display full name"
(-> page (html/select [:.clj--card-name]) first html/text) => "Frank Lasty")
(fact "it should display profile picture"
(-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png"))) | 119965 | (ns stonecutter.test.view.authorise
(:require [midje.sweet :refer :all]
[net.cgrand.enlive-html :as html]
[stonecutter.routes :as r]
[stonecutter.test.view.test-helpers :as th]
[stonecutter.translation :as t]
[stonecutter.view.authorise :refer [authorise-form]]
[stonecutter.helper :as helper]))
(fact "authorise should return some html"
(let [page (-> (th/create-request) authorise-form)]
(html/select page [:body]) =not=> empty?))
(fact "work in progress should be removed from page"
(let [page (-> (th/create-request) authorise-form)]
page => th/work-in-progress-removed))
(fact "there are no missing translations"
(let [translator (t/translations-fn t/translation-map)
page (-> (th/create-request) authorise-form (helper/enlive-response {:translator translator}) :body)]
page => th/no-untranslated-strings))
(fact "authorise form posts to correct endpoint"
(let [page (-> (th/create-request) authorise-form)]
page => (th/has-form-action? [:.func--authorise__form] (r/path :authorise-client))))
(fact "cancel link should go to correct endpoint"
(let [params {:client_id "CLIENT_ID" :redirect_uri "http://where.to.now"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/links-to? [:.func--authorise-cancel__link] (str (r/path :show-authorise-failure)
"?client_id=CLIENT_ID"
"&redirect_uri=http://where.to.now"))))
(fact "client name is injected"
(let [client-name "CLIENT_NAME"
client-name-elements (-> (th/create-request)
(assoc-in [:context :client :name] client-name)
authorise-form
(html/select [:.clj--client-name]))
client-name-is-correct-fn (fn [element] (= (html/text element) client-name))]
client-name-elements =not=> empty?
client-name-elements => (has every? client-name-is-correct-fn)))
(fact "hidden parameters are set"
(let [params {:client_id "CLIENT_ID"
:response_type "RESPONSE_TYPE"
:redirect_uri "REDIRECT_URI"
:scope "SCOPE"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/has-attr? [:.clj--authorise-client-id__input] :value "CLIENT_ID")
page => (th/has-attr? [:.clj--authorise-response-type__input] :value "RESPONSE_TYPE")
page => (th/has-attr? [:.clj--authorise-redirect-uri__input] :value "REDIRECT_URI")
page => (th/has-attr? [:.clj--authorise-scope__input] :value "SCOPE")))
(facts "about displaying profile card"
(let [page (-> (th/create-request)
(assoc-in [:context :user-login] "<EMAIL>")
(assoc-in [:context :user-first-name] "<NAME>")
(assoc-in [:context :user-last-name] "<NAME>")
(assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png")
authorise-form)]
(fact "it should display email address"
(-> page (html/select [:.clj--card-email]) first html/text) => "<EMAIL>")
(fact "it should display full name"
(-> page (html/select [:.clj--card-name]) first html/text) => "<NAME>")
(fact "it should display profile picture"
(-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png"))) | true | (ns stonecutter.test.view.authorise
(:require [midje.sweet :refer :all]
[net.cgrand.enlive-html :as html]
[stonecutter.routes :as r]
[stonecutter.test.view.test-helpers :as th]
[stonecutter.translation :as t]
[stonecutter.view.authorise :refer [authorise-form]]
[stonecutter.helper :as helper]))
(fact "authorise should return some html"
(let [page (-> (th/create-request) authorise-form)]
(html/select page [:body]) =not=> empty?))
(fact "work in progress should be removed from page"
(let [page (-> (th/create-request) authorise-form)]
page => th/work-in-progress-removed))
(fact "there are no missing translations"
(let [translator (t/translations-fn t/translation-map)
page (-> (th/create-request) authorise-form (helper/enlive-response {:translator translator}) :body)]
page => th/no-untranslated-strings))
(fact "authorise form posts to correct endpoint"
(let [page (-> (th/create-request) authorise-form)]
page => (th/has-form-action? [:.func--authorise__form] (r/path :authorise-client))))
(fact "cancel link should go to correct endpoint"
(let [params {:client_id "CLIENT_ID" :redirect_uri "http://where.to.now"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/links-to? [:.func--authorise-cancel__link] (str (r/path :show-authorise-failure)
"?client_id=CLIENT_ID"
"&redirect_uri=http://where.to.now"))))
(fact "client name is injected"
(let [client-name "CLIENT_NAME"
client-name-elements (-> (th/create-request)
(assoc-in [:context :client :name] client-name)
authorise-form
(html/select [:.clj--client-name]))
client-name-is-correct-fn (fn [element] (= (html/text element) client-name))]
client-name-elements =not=> empty?
client-name-elements => (has every? client-name-is-correct-fn)))
(fact "hidden parameters are set"
(let [params {:client_id "CLIENT_ID"
:response_type "RESPONSE_TYPE"
:redirect_uri "REDIRECT_URI"
:scope "SCOPE"}
page (-> (th/create-request {} nil params) authorise-form)]
page => (th/has-attr? [:.clj--authorise-client-id__input] :value "CLIENT_ID")
page => (th/has-attr? [:.clj--authorise-response-type__input] :value "RESPONSE_TYPE")
page => (th/has-attr? [:.clj--authorise-redirect-uri__input] :value "REDIRECT_URI")
page => (th/has-attr? [:.clj--authorise-scope__input] :value "SCOPE")))
(facts "about displaying profile card"
(let [page (-> (th/create-request)
(assoc-in [:context :user-login] "PI:EMAIL:<EMAIL>END_PI")
(assoc-in [:context :user-first-name] "PI:NAME:<NAME>END_PI")
(assoc-in [:context :user-last-name] "PI:NAME:<NAME>END_PI")
(assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png")
authorise-form)]
(fact "it should display email address"
(-> page (html/select [:.clj--card-email]) first html/text) => "PI:EMAIL:<EMAIL>END_PI")
(fact "it should display full name"
(-> page (html/select [:.clj--card-name]) first html/text) => "PI:NAME:<NAME>END_PI")
(fact "it should display profile picture"
(-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png"))) |
[
{
"context": ";; Copyright (C) 2018, 2019 by Vlad Kozin\n\n(ns arb\n (:require\n [medley.core :refer :all]",
"end": 41,
"score": 0.9998226165771484,
"start": 31,
"tag": "NAME",
"value": "Vlad Kozin"
}
] | src/arb.clj | vkz/bot | 1 | ;; Copyright (C) 2018, 2019 by Vlad Kozin
(ns arb
(:require
[medley.core :refer :all]
[clojure.test :refer [deftest is are]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :as exch :refer :all])
;;* Arb
;; TODO This is exchange dependent, so really I should pass exchange structures
;; around and extract relevant books.
(defn with-cost [book side price]
;; TODO exchange+book => fee
;; hardcoding for now
(let [taker-fee (/ 0.3M 100M)
;; withdrawal-fee 0
]
(decimal
(case side
(:buy :ask) (* price (+ 1 taker-fee))
(:sell :bid) (* price (- 1 taker-fee))))))
;; TODO too slow
(defn arb-step [bid-book ask-book]
(if (not
(= (:ticker bid-book)
(:ticker ask-book)))
;; Can happen if arbitrager thread starts before we book snapshots from
;; exchanges. Should I simply Thread/sleep here?
(do (println
(str "Ticker mismatch:\n"
"- Bid book ticker: " (:ticker bid-book) "\n"
"- Ask book ticker: " (:ticker ask-book) "\n"
"skipping"))
(flush)
nil)
(let [ticker
(:ticker bid-book)
{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
;; TODO assumes cost per 1 unit of size e.g. for :btc/eth that would be cost
;; in btc per 1 eth traded. Unless this assumption holds, may need to fix.
;; E.g. cost maybe proportional to a total value traded that is to price*size.
(cond
(and (some? bid-price)
(some? ask-price)
(pos?
(- (with-cost bid-book :bid bid-price)
(with-cost ask-book :ask ask-price))))
(let [trade-size
(min bid-size
ask-size)
bid-update
{:bids [[(decimal bid-price) (decimal (- bid-size trade-size))]]
:asks []}
ask-update
{:bids []
:asks [[(decimal ask-price) (decimal (- ask-size trade-size))]]}
bid-book
(exch/update->book bid-book bid-update)
ask-book
(exch/update->book ask-book ask-update)
buy-at
ask-price
sell-at
bid-price]
{:trade-size trade-size
:buy-at buy-at
:sell-at sell-at
:bid-book bid-book
:ask-book ask-book})
:else
nil))))
(defn arb [bid-book ask-book]
(loop [bid-book bid-book
ask-book ask-book
trades []]
(if-let [trade (arb-step bid-book
ask-book)]
(recur (:bid-book trade)
(:ask-book trade)
(conj trades trade))
(if (empty? trades)
nil
trades))))
(defn arb? [bid-book ask-book]
(when-let [ticker
(and (:ticker bid-book)
(:ticker ask-book))]
(let [{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
(and (some? bid-price)
(some? ask-price)
(pos?
(- bid-price
ask-price))
(- bid-price
ask-price)))))
(defn match [arb-trades]
(assoc-some
{:volume (->> arb-trades
(map #(let [{:keys [trade-size buy-at sell-at]} %]
{:buy-volume (* trade-size buy-at)
:sell-volume (* trade-size sell-at)}))
(reduce #(-> %1
(update :buy-volume + (:buy-volume %2))
(update :sell-volume + (:sell-volume %2)))
{:buy-volume 0M
:sell-volume 0M}))
:size (->> arb-trades
(map :trade-size)
(apply +))
:clear-buy-at (->> arb-trades
(map :buy-at)
(apply max))
:clear-sell-at (->> arb-trades
(map :sell-at)
(apply min))}
:ticker (some-> arb-trades first :bid-book :ticker ticker-kw)))
#_
(let [ticker (ticker :btc/eth)
ticker-kw (ticker-kw ticker)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})
arb-trades (arb bid-book ask-book)]
(match arb-trades))
(defn expect-profit [arb-trades]
(if (empty? arb-trades)
0
(let [{bid-book :bid-book
ask-book :ask-book}
(first arb-trades)
currency
(currency
(:ticker bid-book))]
[(->> arb-trades
(map (fn [{:keys [sell-at
buy-at
trade-size]}]
(-> (- (with-cost bid-book :sell sell-at)
(with-cost ask-book :buy buy-at))
(* trade-size))))
(apply +))
currency])))
(defn profit-threshold [currency]
(get
{:btc 0.03M
:usd 200M}
currency))
(defn run-arb
[ticker
{bid-conn :conn :as bid-exch}
{ask-conn :conn :as ask-exch}]
(when-not (connected? bid-conn) (connect bid-conn))
(when-not (connected? ask-conn) (connect ask-conn))
(let [bid-book (get-book bid-exch ticker)
ask-book (get-book ask-exch ticker)
ticker-kw (ticker-kw ticker)
bid-exch-name (get-name bid-exch)
ask-exch-name (get-name ask-exch)]
(book-sub bid-book)
(book-sub ask-book)
(let [bid-ch (async/chan 100)
ask-ch (async/chan 100)]
;; TODO Think I ought to test these with custom dropping channels to see if
;; I'm actually keeping up with updates.
(book-watch bid-book :book-update (fn [_ _] (async/put! bid-ch :bids-updated)))
(book-watch ask-book :book-update (fn [_ _] (async/put! ask-ch :asks-updated)))
(async/go
(loop []
(let [[v ch] (async/alts! [bid-ch ask-ch])]
(condp = ch
;; TODO log/debug instead
bid-ch (log/debug (format "Bid book updated at %s for %s" bid-exch-name ticker-kw))
ask-ch (log/debug (format "Ask book updated at %s for %s" ask-exch-name ticker-kw)))
(let [bid-snap (book-snapshot bid-book)
ask-snap (book-snapshot ask-book)]
;; NOTE Exchanges are symmetrical so we try both ways:
;; bid-exch BUY -> ask-exch SELL
;; ask-exch BUY -> bid-exch SELL
;; TODO When arb discovered we need to route orders correctly! Atm
;; we don't care which exch is BUY, which is SELL.
(when-some [arb-trades
(or
;; direct order
(arb bid-snap ask-snap)
;; reversed order
(arb ask-snap bid-snap))]
(let [[profit currency] (expect-profit arb-trades)]
(when (>= profit (profit-threshold currency))
;; TODO Send email notification instead
(log/info
(format
"Possible arb of %s - trade %s of %s"
[profit currency]
(:volume (match arb-trades))
ticker-kw))))))
(recur))))
(fn stop [& {unsub? :unsub?
disconnect? :disconnect?
:or {unsub? false
disconnect? false}}]
(book-unwatch bid-book :book-update)
(book-unwatch ask-book :book-update)
(when unsub?
(book-unsub bid-book)
(book-unsub ask-book))
(when disconnect?
(disconnect bid-conn)
(disconnect ask-conn))))))
;;* Tests
(deftest arbitrage
(let [ticker (ticker :btc/eth)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})]
;; calculating expected profit by hand for the above two books
;; * size (- sell buy)
(is (= 4.3575M
(+
(* 1 (- (with-cost 'any :sell 6)
(with-cost 'any :buy 4)))
(* 1 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4)))
(* 3 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4.5))))))
;; NOTE incidentally were I to perform this calculation in Clojure's default
;; double instead of decimal I'd get a result with rounding error:
;; 4.3575000000000035, so yeah, don't use float for money!
(is (= (with-cost 'b :ask 4)
(with-cost 'b :buy 4)))
(is (= (with-cost 'b :sell 5)
(with-cost 'b :bid 5)))
(is (arb? bid-book ask-book))
(is (=
[4.3575M :btc]
(expect-profit
(arb bid-book
ask-book))))))
| 54556 | ;; Copyright (C) 2018, 2019 by <NAME>
(ns arb
(:require
[medley.core :refer :all]
[clojure.test :refer [deftest is are]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :as exch :refer :all])
;;* Arb
;; TODO This is exchange dependent, so really I should pass exchange structures
;; around and extract relevant books.
(defn with-cost [book side price]
;; TODO exchange+book => fee
;; hardcoding for now
(let [taker-fee (/ 0.3M 100M)
;; withdrawal-fee 0
]
(decimal
(case side
(:buy :ask) (* price (+ 1 taker-fee))
(:sell :bid) (* price (- 1 taker-fee))))))
;; TODO too slow
(defn arb-step [bid-book ask-book]
(if (not
(= (:ticker bid-book)
(:ticker ask-book)))
;; Can happen if arbitrager thread starts before we book snapshots from
;; exchanges. Should I simply Thread/sleep here?
(do (println
(str "Ticker mismatch:\n"
"- Bid book ticker: " (:ticker bid-book) "\n"
"- Ask book ticker: " (:ticker ask-book) "\n"
"skipping"))
(flush)
nil)
(let [ticker
(:ticker bid-book)
{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
;; TODO assumes cost per 1 unit of size e.g. for :btc/eth that would be cost
;; in btc per 1 eth traded. Unless this assumption holds, may need to fix.
;; E.g. cost maybe proportional to a total value traded that is to price*size.
(cond
(and (some? bid-price)
(some? ask-price)
(pos?
(- (with-cost bid-book :bid bid-price)
(with-cost ask-book :ask ask-price))))
(let [trade-size
(min bid-size
ask-size)
bid-update
{:bids [[(decimal bid-price) (decimal (- bid-size trade-size))]]
:asks []}
ask-update
{:bids []
:asks [[(decimal ask-price) (decimal (- ask-size trade-size))]]}
bid-book
(exch/update->book bid-book bid-update)
ask-book
(exch/update->book ask-book ask-update)
buy-at
ask-price
sell-at
bid-price]
{:trade-size trade-size
:buy-at buy-at
:sell-at sell-at
:bid-book bid-book
:ask-book ask-book})
:else
nil))))
(defn arb [bid-book ask-book]
(loop [bid-book bid-book
ask-book ask-book
trades []]
(if-let [trade (arb-step bid-book
ask-book)]
(recur (:bid-book trade)
(:ask-book trade)
(conj trades trade))
(if (empty? trades)
nil
trades))))
(defn arb? [bid-book ask-book]
(when-let [ticker
(and (:ticker bid-book)
(:ticker ask-book))]
(let [{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
(and (some? bid-price)
(some? ask-price)
(pos?
(- bid-price
ask-price))
(- bid-price
ask-price)))))
(defn match [arb-trades]
(assoc-some
{:volume (->> arb-trades
(map #(let [{:keys [trade-size buy-at sell-at]} %]
{:buy-volume (* trade-size buy-at)
:sell-volume (* trade-size sell-at)}))
(reduce #(-> %1
(update :buy-volume + (:buy-volume %2))
(update :sell-volume + (:sell-volume %2)))
{:buy-volume 0M
:sell-volume 0M}))
:size (->> arb-trades
(map :trade-size)
(apply +))
:clear-buy-at (->> arb-trades
(map :buy-at)
(apply max))
:clear-sell-at (->> arb-trades
(map :sell-at)
(apply min))}
:ticker (some-> arb-trades first :bid-book :ticker ticker-kw)))
#_
(let [ticker (ticker :btc/eth)
ticker-kw (ticker-kw ticker)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})
arb-trades (arb bid-book ask-book)]
(match arb-trades))
(defn expect-profit [arb-trades]
(if (empty? arb-trades)
0
(let [{bid-book :bid-book
ask-book :ask-book}
(first arb-trades)
currency
(currency
(:ticker bid-book))]
[(->> arb-trades
(map (fn [{:keys [sell-at
buy-at
trade-size]}]
(-> (- (with-cost bid-book :sell sell-at)
(with-cost ask-book :buy buy-at))
(* trade-size))))
(apply +))
currency])))
(defn profit-threshold [currency]
(get
{:btc 0.03M
:usd 200M}
currency))
(defn run-arb
[ticker
{bid-conn :conn :as bid-exch}
{ask-conn :conn :as ask-exch}]
(when-not (connected? bid-conn) (connect bid-conn))
(when-not (connected? ask-conn) (connect ask-conn))
(let [bid-book (get-book bid-exch ticker)
ask-book (get-book ask-exch ticker)
ticker-kw (ticker-kw ticker)
bid-exch-name (get-name bid-exch)
ask-exch-name (get-name ask-exch)]
(book-sub bid-book)
(book-sub ask-book)
(let [bid-ch (async/chan 100)
ask-ch (async/chan 100)]
;; TODO Think I ought to test these with custom dropping channels to see if
;; I'm actually keeping up with updates.
(book-watch bid-book :book-update (fn [_ _] (async/put! bid-ch :bids-updated)))
(book-watch ask-book :book-update (fn [_ _] (async/put! ask-ch :asks-updated)))
(async/go
(loop []
(let [[v ch] (async/alts! [bid-ch ask-ch])]
(condp = ch
;; TODO log/debug instead
bid-ch (log/debug (format "Bid book updated at %s for %s" bid-exch-name ticker-kw))
ask-ch (log/debug (format "Ask book updated at %s for %s" ask-exch-name ticker-kw)))
(let [bid-snap (book-snapshot bid-book)
ask-snap (book-snapshot ask-book)]
;; NOTE Exchanges are symmetrical so we try both ways:
;; bid-exch BUY -> ask-exch SELL
;; ask-exch BUY -> bid-exch SELL
;; TODO When arb discovered we need to route orders correctly! Atm
;; we don't care which exch is BUY, which is SELL.
(when-some [arb-trades
(or
;; direct order
(arb bid-snap ask-snap)
;; reversed order
(arb ask-snap bid-snap))]
(let [[profit currency] (expect-profit arb-trades)]
(when (>= profit (profit-threshold currency))
;; TODO Send email notification instead
(log/info
(format
"Possible arb of %s - trade %s of %s"
[profit currency]
(:volume (match arb-trades))
ticker-kw))))))
(recur))))
(fn stop [& {unsub? :unsub?
disconnect? :disconnect?
:or {unsub? false
disconnect? false}}]
(book-unwatch bid-book :book-update)
(book-unwatch ask-book :book-update)
(when unsub?
(book-unsub bid-book)
(book-unsub ask-book))
(when disconnect?
(disconnect bid-conn)
(disconnect ask-conn))))))
;;* Tests
(deftest arbitrage
(let [ticker (ticker :btc/eth)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})]
;; calculating expected profit by hand for the above two books
;; * size (- sell buy)
(is (= 4.3575M
(+
(* 1 (- (with-cost 'any :sell 6)
(with-cost 'any :buy 4)))
(* 1 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4)))
(* 3 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4.5))))))
;; NOTE incidentally were I to perform this calculation in Clojure's default
;; double instead of decimal I'd get a result with rounding error:
;; 4.3575000000000035, so yeah, don't use float for money!
(is (= (with-cost 'b :ask 4)
(with-cost 'b :buy 4)))
(is (= (with-cost 'b :sell 5)
(with-cost 'b :bid 5)))
(is (arb? bid-book ask-book))
(is (=
[4.3575M :btc]
(expect-profit
(arb bid-book
ask-book))))))
| true | ;; Copyright (C) 2018, 2019 by PI:NAME:<NAME>END_PI
(ns arb
(:require
[medley.core :refer :all]
[clojure.test :refer [deftest is are]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :as exch :refer :all])
;;* Arb
;; TODO This is exchange dependent, so really I should pass exchange structures
;; around and extract relevant books.
(defn with-cost [book side price]
;; TODO exchange+book => fee
;; hardcoding for now
(let [taker-fee (/ 0.3M 100M)
;; withdrawal-fee 0
]
(decimal
(case side
(:buy :ask) (* price (+ 1 taker-fee))
(:sell :bid) (* price (- 1 taker-fee))))))
;; TODO too slow
(defn arb-step [bid-book ask-book]
(if (not
(= (:ticker bid-book)
(:ticker ask-book)))
;; Can happen if arbitrager thread starts before we book snapshots from
;; exchanges. Should I simply Thread/sleep here?
(do (println
(str "Ticker mismatch:\n"
"- Bid book ticker: " (:ticker bid-book) "\n"
"- Ask book ticker: " (:ticker ask-book) "\n"
"skipping"))
(flush)
nil)
(let [ticker
(:ticker bid-book)
{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
;; TODO assumes cost per 1 unit of size e.g. for :btc/eth that would be cost
;; in btc per 1 eth traded. Unless this assumption holds, may need to fix.
;; E.g. cost maybe proportional to a total value traded that is to price*size.
(cond
(and (some? bid-price)
(some? ask-price)
(pos?
(- (with-cost bid-book :bid bid-price)
(with-cost ask-book :ask ask-price))))
(let [trade-size
(min bid-size
ask-size)
bid-update
{:bids [[(decimal bid-price) (decimal (- bid-size trade-size))]]
:asks []}
ask-update
{:bids []
:asks [[(decimal ask-price) (decimal (- ask-size trade-size))]]}
bid-book
(exch/update->book bid-book bid-update)
ask-book
(exch/update->book ask-book ask-update)
buy-at
ask-price
sell-at
bid-price]
{:trade-size trade-size
:buy-at buy-at
:sell-at sell-at
:bid-book bid-book
:ask-book ask-book})
:else
nil))))
(defn arb [bid-book ask-book]
(loop [bid-book bid-book
ask-book ask-book
trades []]
(if-let [trade (arb-step bid-book
ask-book)]
(recur (:bid-book trade)
(:ask-book trade)
(conj trades trade))
(if (empty? trades)
nil
trades))))
(defn arb? [bid-book ask-book]
(when-let [ticker
(and (:ticker bid-book)
(:ticker ask-book))]
(let [{bids :bids}
bid-book
[bid & bids]
bids
[bid-price bid-size]
bid
{asks :asks}
ask-book
[ask & asks]
asks
[ask-price ask-size]
ask]
(and (some? bid-price)
(some? ask-price)
(pos?
(- bid-price
ask-price))
(- bid-price
ask-price)))))
(defn match [arb-trades]
(assoc-some
{:volume (->> arb-trades
(map #(let [{:keys [trade-size buy-at sell-at]} %]
{:buy-volume (* trade-size buy-at)
:sell-volume (* trade-size sell-at)}))
(reduce #(-> %1
(update :buy-volume + (:buy-volume %2))
(update :sell-volume + (:sell-volume %2)))
{:buy-volume 0M
:sell-volume 0M}))
:size (->> arb-trades
(map :trade-size)
(apply +))
:clear-buy-at (->> arb-trades
(map :buy-at)
(apply max))
:clear-sell-at (->> arb-trades
(map :sell-at)
(apply min))}
:ticker (some-> arb-trades first :bid-book :ticker ticker-kw)))
#_
(let [ticker (ticker :btc/eth)
ticker-kw (ticker-kw ticker)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})
arb-trades (arb bid-book ask-book)]
(match arb-trades))
(defn expect-profit [arb-trades]
(if (empty? arb-trades)
0
(let [{bid-book :bid-book
ask-book :ask-book}
(first arb-trades)
currency
(currency
(:ticker bid-book))]
[(->> arb-trades
(map (fn [{:keys [sell-at
buy-at
trade-size]}]
(-> (- (with-cost bid-book :sell sell-at)
(with-cost ask-book :buy buy-at))
(* trade-size))))
(apply +))
currency])))
(defn profit-threshold [currency]
(get
{:btc 0.03M
:usd 200M}
currency))
(defn run-arb
[ticker
{bid-conn :conn :as bid-exch}
{ask-conn :conn :as ask-exch}]
(when-not (connected? bid-conn) (connect bid-conn))
(when-not (connected? ask-conn) (connect ask-conn))
(let [bid-book (get-book bid-exch ticker)
ask-book (get-book ask-exch ticker)
ticker-kw (ticker-kw ticker)
bid-exch-name (get-name bid-exch)
ask-exch-name (get-name ask-exch)]
(book-sub bid-book)
(book-sub ask-book)
(let [bid-ch (async/chan 100)
ask-ch (async/chan 100)]
;; TODO Think I ought to test these with custom dropping channels to see if
;; I'm actually keeping up with updates.
(book-watch bid-book :book-update (fn [_ _] (async/put! bid-ch :bids-updated)))
(book-watch ask-book :book-update (fn [_ _] (async/put! ask-ch :asks-updated)))
(async/go
(loop []
(let [[v ch] (async/alts! [bid-ch ask-ch])]
(condp = ch
;; TODO log/debug instead
bid-ch (log/debug (format "Bid book updated at %s for %s" bid-exch-name ticker-kw))
ask-ch (log/debug (format "Ask book updated at %s for %s" ask-exch-name ticker-kw)))
(let [bid-snap (book-snapshot bid-book)
ask-snap (book-snapshot ask-book)]
;; NOTE Exchanges are symmetrical so we try both ways:
;; bid-exch BUY -> ask-exch SELL
;; ask-exch BUY -> bid-exch SELL
;; TODO When arb discovered we need to route orders correctly! Atm
;; we don't care which exch is BUY, which is SELL.
(when-some [arb-trades
(or
;; direct order
(arb bid-snap ask-snap)
;; reversed order
(arb ask-snap bid-snap))]
(let [[profit currency] (expect-profit arb-trades)]
(when (>= profit (profit-threshold currency))
;; TODO Send email notification instead
(log/info
(format
"Possible arb of %s - trade %s of %s"
[profit currency]
(:volume (match arb-trades))
ticker-kw))))))
(recur))))
(fn stop [& {unsub? :unsub?
disconnect? :disconnect?
:or {unsub? false
disconnect? false}}]
(book-unwatch bid-book :book-update)
(book-unwatch ask-book :book-update)
(when unsub?
(book-unsub bid-book)
(book-unsub ask-book))
(when disconnect?
(disconnect bid-conn)
(disconnect ask-conn))))))
;;* Tests
(deftest arbitrage
(let [ticker (ticker :btc/eth)
bid-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids [[6 1]
[5 4]
[4 1]
[3 10]]
:asks []
:ticker ticker})
ask-book (exch/snapshot->book
(exch/empty-book ticker)
{:bids []
:asks [[4 2]
[4.5 4]
[5 5]
[6 10]]
:ticker ticker})]
;; calculating expected profit by hand for the above two books
;; * size (- sell buy)
(is (= 4.3575M
(+
(* 1 (- (with-cost 'any :sell 6)
(with-cost 'any :buy 4)))
(* 1 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4)))
(* 3 (- (with-cost 'any :sell 5)
(with-cost 'any :buy 4.5))))))
;; NOTE incidentally were I to perform this calculation in Clojure's default
;; double instead of decimal I'd get a result with rounding error:
;; 4.3575000000000035, so yeah, don't use float for money!
(is (= (with-cost 'b :ask 4)
(with-cost 'b :buy 4)))
(is (= (with-cost 'b :sell 5)
(with-cost 'b :bid 5)))
(is (arb? bid-book ask-book))
(is (=
[4.3575M :btc]
(expect-profit
(arb bid-book
ask-book))))))
|
[
{
"context": "le tables at once\n\n (db/transact {:author/name \\\"test\\\"\n :author/email \\\"test@test.com\\\"",
"end": 11254,
"score": 0.9871771335601807,
"start": 11250,
"tag": "USERNAME",
"value": "test"
},
{
"context": "hor/name \\\"test\\\"\n :author/email \\\"test@test.com\\\"\n :author/posts [{:post/title \\\"t",
"end": 11302,
"score": 0.9999082684516907,
"start": 11289,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "})\n\n or just one\n\n (db/transact {:author/name \\\"test2\\\"\n :author/email \\\"test2@test.com\\",
"end": 11467,
"score": 0.9995968341827393,
"start": 11462,
"tag": "USERNAME",
"value": "test2"
},
{
"context": "or/name \\\"test2\\\"\n :author/email \\\"test2@test.com\\\"})\n\n Retrieve nested rows\n\n (db/pull '[author/",
"end": 11516,
"score": 0.9998955726623535,
"start": 11502,
"tag": "EMAIL",
"value": "test2@test.com"
},
{
"context": "id 1\n :post/author [:author/name \\\"test2\\\"]})\n\n or the equivalent\n\n (db/transact {:post/",
"end": 11801,
"score": 0.9983251094818115,
"start": 11796,
"tag": "USERNAME",
"value": "test2"
}
] | src/coast/db.clj | dawran6/coast | 0 | (ns coast.db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as string]
[clojure.walk :as walk]
[clojure.data.json :as json]
[clojure.instant :as instant]
[coast.db.queries :as queries]
[coast.db.transact :as db.transact]
[coast.db.connection :as db.connection :refer [connection spec]]
[coast.db.update :as db.update]
[coast.db.insert :as db.insert]
[coast.db.schema :as db.schema]
[coast.db.sql :as sql]
[coast.db.helpers :as helpers]
[coast.migrations :as migrations]
[coast.utils :as utils]
[coast.error :refer [raise rescue]]
[clojure.java.shell :as shell]
[clojure.java.io :as io])
(:import (java.io File)
(java.time Instant)
(java.text SimpleDateFormat))
(:refer-clojure :exclude [drop update]))
(defn sql-vec? [v]
(and (vector? v)
(string? (first v))
(not (string/blank? (first v)))))
(defn query
([conn v opts]
(if (and (sql-vec? v) (map? opts))
(jdbc/query conn v (merge {:keywordize? true
:identifiers utils/kebab} opts))
(empty list)))
([conn v]
(query conn v {})))
(defn create-root-var [name value]
; shamelessly stolen from yesql
(intern *ns*
(with-meta (symbol name)
(meta value))
value))
(defn query-fn [{:keys [sql f]}]
(fn [& [m]]
(->> (queries/sql-vec sql m)
(query (connection))
(f))))
(defn query-fns [filename]
(doall (->> (queries/slurp-resource filename)
(queries/parse)
(map #(assoc % :ns *ns*))
(map #(create-root-var (:name %) (query-fn %))))))
(defmacro defq
([n filename]
`(let [q-fn# (-> (queries/query ~(str n) ~filename)
(assoc :ns *ns*)
(query-fn))]
(create-root-var ~(str n) q-fn#)))
([filename]
`(query-fns ~filename)))
(defn first! [coll]
(or (first coll)
(raise "Record not found" {:coast.router/error :404
:404 true
:not-found true
:type :404
::error :not-found})))
(defn create
"Creates a new database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "touch"
(= (spec :adapter) "postgres") "createdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " created successfully")
(:err m))))
([]
(create (spec :database))))
(defn drop
"Drops an existing database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "rm"
(= (spec :adapter) "postgres") "dropdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " dropped successfully")
(:err m))))
([]
(drop (spec :database))))
(defn single [coll]
(if (and (= 1 (count coll))
(coll? coll))
(first coll)
coll))
(defn qualify-col [s]
(if (.contains s "$")
(let [parts (string/split s #"\$")
k-ns (first (map #(string/replace % #"_" "-") parts))
k-n (->> (rest parts)
(map #(string/replace % #"_" "-"))
(string/join "-"))]
(keyword k-ns k-n))
(keyword s)))
(defn qualify-map [k-ns m]
(->> (map (fn [[k v]] [(keyword k-ns (name k)) v]) m)
(into (empty m))))
; TODO fix pull queries for foreign key references
(defn one-first [schema val]
(if (and (vector? val)
(= :one (:db/type (get schema (first val))))
(vector? (second val)))
[(first val) (first (second val))]
val))
(defn coerce-inst
"Coerce json iso8601 to clojure #inst"
[val]
(if (string? val)
(try
(instant/read-instant-timestamp val)
(catch Exception e
val))
val))
(defn coerce-timestamp-inst
"Coerce timestamps to clojure #inst"
[val]
(if (string? val)
(try
(let [fmt (SimpleDateFormat. "yyyy-MM-dd HH:mm:ss")]
(.parse fmt val))
(catch Exception e
val))
val))
(defn parse-json
"Parses json from pull queries"
[associations val]
(if (and (sequential? val)
(= 2 (count val))
(or (contains? (get associations (first val)) :has-many)
(contains? (get associations (first val)) :belongs-to))
(string? (second val)))
[(first val) (json/read-str (second val) :key-fn qualify-col)]
val))
(def col-query
{"sqlite" ["select
m.name as table_name,
p.name as column_name
from sqlite_master m
left outer join pragma_table_info((m.name)) p on m.name <> p.name
order by table_name, column_name"]
"postgres" ["select table_name, column_name
from information_schema.columns
order by table_name, column_name"]})
(defn col-map [conn adapter]
(let [rows (jdbc/query conn (get col-query adapter))]
(->> (group-by :table_name rows)
(mapv (fn [[k v]]
[(keyword (utils/kebab-case k)) (->> (map :column_name v)
(map utils/kebab-case)
(map #(keyword (utils/kebab-case k) %)))]))
(into {}))))
(defmacro transaction [binder & body]
`(jdbc/with-db-transaction [~binder (connection)]
~@body))
(defn sql-vec
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)]
(if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))))
([v params]
(if (and (vector? v)
(map? params))
(sql-vec nil v params)
(sql-vec v params {})))
([v]
(sql-vec nil v nil)))
(defn q
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)
sql-vec (if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))
_ (when (true? debug)
(println sql-vec))
rows (query conn
sql-vec
{:keywordize? false
:identifiers qualify-col})]
(walk/postwalk #(-> % coerce-inst coerce-timestamp-inst)
(walk/prewalk #(->> (one-first associations %) (parse-json associations))
rows))))
([v params]
(if (and (vector? v)
(map? params))
(q nil v params)
(q v params {})))
([v]
(q nil v nil)))
(defn execute!
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
sql-vec (sql/sql-vec adapter {} {} v params)]
(when (true? debug)
(println sql-vec))
(jdbc/execute! conn sql-vec)))
([v params]
(if (and (vector? v)
(map? params))
(execute! nil v params)
(execute! v params {})))
([v]
(execute! nil v {})))
(defn pluck
([conn v params]
(first
(q conn v params)))
([v params]
(if (and (vector? v)
(map? params))
(pluck nil v params)
(pluck v params {})))
([v]
(pluck nil v {})))
(defn fetch
([conn k id]
(when (and (ident? k)
(some? id))
(first
(q conn '[:select *
:from ?from
:where [id ?id]
:limit 1]
{:from k
:id id}))))
([k id]
(fetch nil k id)))
(defn find-by
([conn k m]
(when (and (ident? k)
(map? m))
(first
(q conn [:select :*
:from k
:where (mapv identity m)
:limit 1]
{}))))
([k m]
(find-by nil k m)))
(defn select-rels [m]
(let [schema (db.schema/fetch)]
(select-keys m (->> (:joins schema)
(filter (fn [[_ v]] (qualified-ident? v)))
(into {})
(keys)))))
(defn resolve-select-rels [m]
(let [queries (->> (filter (fn [[_ v]] (vector? v)) m)
(db.transact/selects))
ids (->> (filter (fn [[_ v]] (number? v)) m)
(mapv (fn [[k v]] [(keyword (namespace k) (name k)) v]))
(into {}))
results (->> (map #(query (db.connection/connection) % {:keywordize? false
:identifiers qualify-col})
queries)
(map first)
(apply merge))]
(merge ids results)))
(defn many-rels [m]
(select-keys m (->> (db.schema/fetch)
(filter (fn [[_ v]] (and (or (contains? v :db/ref) (contains? v :db/joins))
(= :many (:db/type v)))))
(map first))))
(defn upsert-rel [parent [k v]]
(if (empty? v)
(let [schema (db.schema/fetch)
jk (or (get-in schema [k :db/joins])
(get-in schema [k :db/ref]))
k-ns (-> jk namespace utils/snake)
join-ns (-> jk name utils/snake)
_ (query (connection) [(str "delete from " k-ns " where " join-ns " = ? returning *") (get parent (keyword join-ns "id"))])]
[k []])
(let [k-ns (->> v first keys (filter qualified-ident?) first namespace)
parent-map (->> (filter (fn [[k _]] (= (name k) "id")) parent)
(map (fn [[k* v]] [(keyword k-ns (namespace k*)) v]))
(into {}))
v* (mapv #(merge parent-map %) v)
sql-vec (db.transact/sql-vec v*)
rows (->> (query (connection) sql-vec)
(mapv #(qualify-map k-ns %)))]
[k rows])))
(defn upsert-rels [parent m]
(->> (map #(upsert-rel parent %) m)
(into {})))
(defn transact [m]
"This function resolves foreign keys (or hydrates), it also deletes related rows based on idents as well as inserting and updating rows.
Here are some concrete examples:
Given this schema:
[{:db/ident :author/name
:db/type \"citext\"}
{:db/ident :author/email
:db/type \"citext\"}
{:db/rel :author/posts
:db/joins :post/author
:db/type :many}
{:db/col :post/title
:db/type \"text\"}
{:db/col :post/body
:db/type \"text\"}]
Insert multiple tables at once
(db/transact {:author/name \"test\"
:author/email \"test@test.com\"
:author/posts [{:post/title \"title\"
:post/body \"body\"}]})
or just one
(db/transact {:author/name \"test2\"
:author/email \"test2@test.com\"})
Retrieve nested rows
(db/pull '[author/id author/name author/email
{:author/posts [post/id post/title post/body]}]
[:author/name \"test\"])
Update with the same command
(db/transact {:post/id 1
:post/author [:author/name \"test2\"]})
or the equivalent
(db/transact {:post/id 1
:post/author 2})
Delete multiple nested rows with one function
(db/transact {:author/id 2
:author/posts []})"
(let [k-ns (->> m keys (filter qualified-ident?) first namespace)
s-rels (select-rels m)
s-rel-results (resolve-select-rels s-rels) ; foreign keys
m-rels (many-rels m)
m* (merge m s-rel-results)
m* (apply dissoc m* (keys m-rels))
row (when (not (empty? (db.update/idents (map identity m*))))
(->> (db.update/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single)))
row (if (empty? row)
(->> (db.insert/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single))
row)
rel-rows (upsert-rels row m-rels)]
(merge row rel-rows)))
(defn insert
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/insert arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(insert nil arg)))
(defn update
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/update arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))
id (if (sequential? arg)
(get-in arg [0 (keyword table "id")])
(get arg (keyword table "id")))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(update nil arg)))
(defn unique-column-names [s]
(->> (string/split s #",")
(filter #(string/includes? % "unique"))
(map string/trim)
(map #(string/split % #" "))
(map first)))
(defn upsert
([conn arg opts]
(let [table-name (if (sequential? arg)
(-> arg first keys first utils/namespace*)
(-> arg keys first utils/namespace*))
{:keys [adapter]} (db.connection/spec)]
(when (nil? table-name)
(throw (Exception. "coast/upsert expects a map with qualified keywords")))
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(let [{sql :sql} (pluck c ["select sql from sqlite_master where type = ? and name = ?" "table" table-name])
on-conflict (if (list? (:on-conflict opts))
(:on-conflict opts)
(unique-column-names sql))
v (helpers/upsert arg {:on-conflict on-conflict})]
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
id (if (zero? id)
(get (find-by c (keyword table-name) (select-keys arg (mapv #(keyword table-name %) on-conflict)))
(keyword table-name "id"))
id)
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id))))
(execute! conn (apply helpers/upsert arg opts)))
"postgres" (if (nil? conn)
(transaction c
(let [{indexdef :indexdef} (pluck c ["select indexdef from pg_indexes where tablename = ?" table-name])
on-conflict (-> (re-find #"\((.*)\)" indexdef)
(last)
(string/split #","))
v (helpers/upsert arg {:on-conflict on-conflict})
v (conj v :returning :*)]
(q c v)))
(q conn (conj (helpers/upsert arg opts)
:returning :*))))))
([arg]
(upsert nil arg {})))
(defn delete
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/delete arg)]
(condp = adapter
"sqlite" (first
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(delete nil arg)))
(defn pull [v ident]
(pluck
[:pull v
:from (-> ident first namespace)
:where ident]))
(defn any-rows? [table]
(some?
(pluck
[:select :*
:from (keyword table)
:limit 1])))
(def migrate migrations/migrate)
(def rollback migrations/rollback)
(def reconnect! db.connection/reconnect!)
(defn -main [& [action db-name]]
(case action
"create" (println (create (or db-name (spec :database))))
"drop" (println (drop (or db-name (spec :database))))
"")
(System/exit 0))
| 62384 | (ns coast.db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as string]
[clojure.walk :as walk]
[clojure.data.json :as json]
[clojure.instant :as instant]
[coast.db.queries :as queries]
[coast.db.transact :as db.transact]
[coast.db.connection :as db.connection :refer [connection spec]]
[coast.db.update :as db.update]
[coast.db.insert :as db.insert]
[coast.db.schema :as db.schema]
[coast.db.sql :as sql]
[coast.db.helpers :as helpers]
[coast.migrations :as migrations]
[coast.utils :as utils]
[coast.error :refer [raise rescue]]
[clojure.java.shell :as shell]
[clojure.java.io :as io])
(:import (java.io File)
(java.time Instant)
(java.text SimpleDateFormat))
(:refer-clojure :exclude [drop update]))
(defn sql-vec? [v]
(and (vector? v)
(string? (first v))
(not (string/blank? (first v)))))
(defn query
([conn v opts]
(if (and (sql-vec? v) (map? opts))
(jdbc/query conn v (merge {:keywordize? true
:identifiers utils/kebab} opts))
(empty list)))
([conn v]
(query conn v {})))
(defn create-root-var [name value]
; shamelessly stolen from yesql
(intern *ns*
(with-meta (symbol name)
(meta value))
value))
(defn query-fn [{:keys [sql f]}]
(fn [& [m]]
(->> (queries/sql-vec sql m)
(query (connection))
(f))))
(defn query-fns [filename]
(doall (->> (queries/slurp-resource filename)
(queries/parse)
(map #(assoc % :ns *ns*))
(map #(create-root-var (:name %) (query-fn %))))))
(defmacro defq
([n filename]
`(let [q-fn# (-> (queries/query ~(str n) ~filename)
(assoc :ns *ns*)
(query-fn))]
(create-root-var ~(str n) q-fn#)))
([filename]
`(query-fns ~filename)))
(defn first! [coll]
(or (first coll)
(raise "Record not found" {:coast.router/error :404
:404 true
:not-found true
:type :404
::error :not-found})))
(defn create
"Creates a new database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "touch"
(= (spec :adapter) "postgres") "createdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " created successfully")
(:err m))))
([]
(create (spec :database))))
(defn drop
"Drops an existing database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "rm"
(= (spec :adapter) "postgres") "dropdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " dropped successfully")
(:err m))))
([]
(drop (spec :database))))
(defn single [coll]
(if (and (= 1 (count coll))
(coll? coll))
(first coll)
coll))
(defn qualify-col [s]
(if (.contains s "$")
(let [parts (string/split s #"\$")
k-ns (first (map #(string/replace % #"_" "-") parts))
k-n (->> (rest parts)
(map #(string/replace % #"_" "-"))
(string/join "-"))]
(keyword k-ns k-n))
(keyword s)))
(defn qualify-map [k-ns m]
(->> (map (fn [[k v]] [(keyword k-ns (name k)) v]) m)
(into (empty m))))
; TODO fix pull queries for foreign key references
(defn one-first [schema val]
(if (and (vector? val)
(= :one (:db/type (get schema (first val))))
(vector? (second val)))
[(first val) (first (second val))]
val))
(defn coerce-inst
"Coerce json iso8601 to clojure #inst"
[val]
(if (string? val)
(try
(instant/read-instant-timestamp val)
(catch Exception e
val))
val))
(defn coerce-timestamp-inst
"Coerce timestamps to clojure #inst"
[val]
(if (string? val)
(try
(let [fmt (SimpleDateFormat. "yyyy-MM-dd HH:mm:ss")]
(.parse fmt val))
(catch Exception e
val))
val))
(defn parse-json
"Parses json from pull queries"
[associations val]
(if (and (sequential? val)
(= 2 (count val))
(or (contains? (get associations (first val)) :has-many)
(contains? (get associations (first val)) :belongs-to))
(string? (second val)))
[(first val) (json/read-str (second val) :key-fn qualify-col)]
val))
(def col-query
{"sqlite" ["select
m.name as table_name,
p.name as column_name
from sqlite_master m
left outer join pragma_table_info((m.name)) p on m.name <> p.name
order by table_name, column_name"]
"postgres" ["select table_name, column_name
from information_schema.columns
order by table_name, column_name"]})
(defn col-map [conn adapter]
(let [rows (jdbc/query conn (get col-query adapter))]
(->> (group-by :table_name rows)
(mapv (fn [[k v]]
[(keyword (utils/kebab-case k)) (->> (map :column_name v)
(map utils/kebab-case)
(map #(keyword (utils/kebab-case k) %)))]))
(into {}))))
(defmacro transaction [binder & body]
`(jdbc/with-db-transaction [~binder (connection)]
~@body))
(defn sql-vec
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)]
(if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))))
([v params]
(if (and (vector? v)
(map? params))
(sql-vec nil v params)
(sql-vec v params {})))
([v]
(sql-vec nil v nil)))
(defn q
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)
sql-vec (if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))
_ (when (true? debug)
(println sql-vec))
rows (query conn
sql-vec
{:keywordize? false
:identifiers qualify-col})]
(walk/postwalk #(-> % coerce-inst coerce-timestamp-inst)
(walk/prewalk #(->> (one-first associations %) (parse-json associations))
rows))))
([v params]
(if (and (vector? v)
(map? params))
(q nil v params)
(q v params {})))
([v]
(q nil v nil)))
(defn execute!
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
sql-vec (sql/sql-vec adapter {} {} v params)]
(when (true? debug)
(println sql-vec))
(jdbc/execute! conn sql-vec)))
([v params]
(if (and (vector? v)
(map? params))
(execute! nil v params)
(execute! v params {})))
([v]
(execute! nil v {})))
(defn pluck
([conn v params]
(first
(q conn v params)))
([v params]
(if (and (vector? v)
(map? params))
(pluck nil v params)
(pluck v params {})))
([v]
(pluck nil v {})))
(defn fetch
([conn k id]
(when (and (ident? k)
(some? id))
(first
(q conn '[:select *
:from ?from
:where [id ?id]
:limit 1]
{:from k
:id id}))))
([k id]
(fetch nil k id)))
(defn find-by
([conn k m]
(when (and (ident? k)
(map? m))
(first
(q conn [:select :*
:from k
:where (mapv identity m)
:limit 1]
{}))))
([k m]
(find-by nil k m)))
(defn select-rels [m]
(let [schema (db.schema/fetch)]
(select-keys m (->> (:joins schema)
(filter (fn [[_ v]] (qualified-ident? v)))
(into {})
(keys)))))
(defn resolve-select-rels [m]
(let [queries (->> (filter (fn [[_ v]] (vector? v)) m)
(db.transact/selects))
ids (->> (filter (fn [[_ v]] (number? v)) m)
(mapv (fn [[k v]] [(keyword (namespace k) (name k)) v]))
(into {}))
results (->> (map #(query (db.connection/connection) % {:keywordize? false
:identifiers qualify-col})
queries)
(map first)
(apply merge))]
(merge ids results)))
(defn many-rels [m]
(select-keys m (->> (db.schema/fetch)
(filter (fn [[_ v]] (and (or (contains? v :db/ref) (contains? v :db/joins))
(= :many (:db/type v)))))
(map first))))
(defn upsert-rel [parent [k v]]
(if (empty? v)
(let [schema (db.schema/fetch)
jk (or (get-in schema [k :db/joins])
(get-in schema [k :db/ref]))
k-ns (-> jk namespace utils/snake)
join-ns (-> jk name utils/snake)
_ (query (connection) [(str "delete from " k-ns " where " join-ns " = ? returning *") (get parent (keyword join-ns "id"))])]
[k []])
(let [k-ns (->> v first keys (filter qualified-ident?) first namespace)
parent-map (->> (filter (fn [[k _]] (= (name k) "id")) parent)
(map (fn [[k* v]] [(keyword k-ns (namespace k*)) v]))
(into {}))
v* (mapv #(merge parent-map %) v)
sql-vec (db.transact/sql-vec v*)
rows (->> (query (connection) sql-vec)
(mapv #(qualify-map k-ns %)))]
[k rows])))
(defn upsert-rels [parent m]
(->> (map #(upsert-rel parent %) m)
(into {})))
(defn transact [m]
"This function resolves foreign keys (or hydrates), it also deletes related rows based on idents as well as inserting and updating rows.
Here are some concrete examples:
Given this schema:
[{:db/ident :author/name
:db/type \"citext\"}
{:db/ident :author/email
:db/type \"citext\"}
{:db/rel :author/posts
:db/joins :post/author
:db/type :many}
{:db/col :post/title
:db/type \"text\"}
{:db/col :post/body
:db/type \"text\"}]
Insert multiple tables at once
(db/transact {:author/name \"test\"
:author/email \"<EMAIL>\"
:author/posts [{:post/title \"title\"
:post/body \"body\"}]})
or just one
(db/transact {:author/name \"test2\"
:author/email \"<EMAIL>\"})
Retrieve nested rows
(db/pull '[author/id author/name author/email
{:author/posts [post/id post/title post/body]}]
[:author/name \"test\"])
Update with the same command
(db/transact {:post/id 1
:post/author [:author/name \"test2\"]})
or the equivalent
(db/transact {:post/id 1
:post/author 2})
Delete multiple nested rows with one function
(db/transact {:author/id 2
:author/posts []})"
(let [k-ns (->> m keys (filter qualified-ident?) first namespace)
s-rels (select-rels m)
s-rel-results (resolve-select-rels s-rels) ; foreign keys
m-rels (many-rels m)
m* (merge m s-rel-results)
m* (apply dissoc m* (keys m-rels))
row (when (not (empty? (db.update/idents (map identity m*))))
(->> (db.update/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single)))
row (if (empty? row)
(->> (db.insert/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single))
row)
rel-rows (upsert-rels row m-rels)]
(merge row rel-rows)))
(defn insert
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/insert arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(insert nil arg)))
(defn update
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/update arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))
id (if (sequential? arg)
(get-in arg [0 (keyword table "id")])
(get arg (keyword table "id")))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(update nil arg)))
(defn unique-column-names [s]
(->> (string/split s #",")
(filter #(string/includes? % "unique"))
(map string/trim)
(map #(string/split % #" "))
(map first)))
(defn upsert
([conn arg opts]
(let [table-name (if (sequential? arg)
(-> arg first keys first utils/namespace*)
(-> arg keys first utils/namespace*))
{:keys [adapter]} (db.connection/spec)]
(when (nil? table-name)
(throw (Exception. "coast/upsert expects a map with qualified keywords")))
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(let [{sql :sql} (pluck c ["select sql from sqlite_master where type = ? and name = ?" "table" table-name])
on-conflict (if (list? (:on-conflict opts))
(:on-conflict opts)
(unique-column-names sql))
v (helpers/upsert arg {:on-conflict on-conflict})]
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
id (if (zero? id)
(get (find-by c (keyword table-name) (select-keys arg (mapv #(keyword table-name %) on-conflict)))
(keyword table-name "id"))
id)
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id))))
(execute! conn (apply helpers/upsert arg opts)))
"postgres" (if (nil? conn)
(transaction c
(let [{indexdef :indexdef} (pluck c ["select indexdef from pg_indexes where tablename = ?" table-name])
on-conflict (-> (re-find #"\((.*)\)" indexdef)
(last)
(string/split #","))
v (helpers/upsert arg {:on-conflict on-conflict})
v (conj v :returning :*)]
(q c v)))
(q conn (conj (helpers/upsert arg opts)
:returning :*))))))
([arg]
(upsert nil arg {})))
(defn delete
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/delete arg)]
(condp = adapter
"sqlite" (first
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(delete nil arg)))
(defn pull [v ident]
(pluck
[:pull v
:from (-> ident first namespace)
:where ident]))
(defn any-rows? [table]
(some?
(pluck
[:select :*
:from (keyword table)
:limit 1])))
(def migrate migrations/migrate)
(def rollback migrations/rollback)
(def reconnect! db.connection/reconnect!)
(defn -main [& [action db-name]]
(case action
"create" (println (create (or db-name (spec :database))))
"drop" (println (drop (or db-name (spec :database))))
"")
(System/exit 0))
| true | (ns coast.db
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as string]
[clojure.walk :as walk]
[clojure.data.json :as json]
[clojure.instant :as instant]
[coast.db.queries :as queries]
[coast.db.transact :as db.transact]
[coast.db.connection :as db.connection :refer [connection spec]]
[coast.db.update :as db.update]
[coast.db.insert :as db.insert]
[coast.db.schema :as db.schema]
[coast.db.sql :as sql]
[coast.db.helpers :as helpers]
[coast.migrations :as migrations]
[coast.utils :as utils]
[coast.error :refer [raise rescue]]
[clojure.java.shell :as shell]
[clojure.java.io :as io])
(:import (java.io File)
(java.time Instant)
(java.text SimpleDateFormat))
(:refer-clojure :exclude [drop update]))
(defn sql-vec? [v]
(and (vector? v)
(string? (first v))
(not (string/blank? (first v)))))
(defn query
([conn v opts]
(if (and (sql-vec? v) (map? opts))
(jdbc/query conn v (merge {:keywordize? true
:identifiers utils/kebab} opts))
(empty list)))
([conn v]
(query conn v {})))
(defn create-root-var [name value]
; shamelessly stolen from yesql
(intern *ns*
(with-meta (symbol name)
(meta value))
value))
(defn query-fn [{:keys [sql f]}]
(fn [& [m]]
(->> (queries/sql-vec sql m)
(query (connection))
(f))))
(defn query-fns [filename]
(doall (->> (queries/slurp-resource filename)
(queries/parse)
(map #(assoc % :ns *ns*))
(map #(create-root-var (:name %) (query-fn %))))))
(defmacro defq
([n filename]
`(let [q-fn# (-> (queries/query ~(str n) ~filename)
(assoc :ns *ns*)
(query-fn))]
(create-root-var ~(str n) q-fn#)))
([filename]
`(query-fns ~filename)))
(defn first! [coll]
(or (first coll)
(raise "Record not found" {:coast.router/error :404
:404 true
:not-found true
:type :404
::error :not-found})))
(defn create
"Creates a new database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "touch"
(= (spec :adapter) "postgres") "createdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " created successfully")
(:err m))))
([]
(create (spec :database))))
(defn drop
"Drops an existing database"
([s]
(let [s (if (string/blank? s) (spec :database) s)
cmd (cond
(= (spec :adapter) "sqlite") "rm"
(= (spec :adapter) "postgres") "dropdb"
:else "")
m (shell/sh cmd s)]
(if (= 0 (:exit m))
(str s " dropped successfully")
(:err m))))
([]
(drop (spec :database))))
(defn single [coll]
(if (and (= 1 (count coll))
(coll? coll))
(first coll)
coll))
(defn qualify-col [s]
(if (.contains s "$")
(let [parts (string/split s #"\$")
k-ns (first (map #(string/replace % #"_" "-") parts))
k-n (->> (rest parts)
(map #(string/replace % #"_" "-"))
(string/join "-"))]
(keyword k-ns k-n))
(keyword s)))
(defn qualify-map [k-ns m]
(->> (map (fn [[k v]] [(keyword k-ns (name k)) v]) m)
(into (empty m))))
; TODO fix pull queries for foreign key references
(defn one-first [schema val]
(if (and (vector? val)
(= :one (:db/type (get schema (first val))))
(vector? (second val)))
[(first val) (first (second val))]
val))
(defn coerce-inst
"Coerce json iso8601 to clojure #inst"
[val]
(if (string? val)
(try
(instant/read-instant-timestamp val)
(catch Exception e
val))
val))
(defn coerce-timestamp-inst
"Coerce timestamps to clojure #inst"
[val]
(if (string? val)
(try
(let [fmt (SimpleDateFormat. "yyyy-MM-dd HH:mm:ss")]
(.parse fmt val))
(catch Exception e
val))
val))
(defn parse-json
"Parses json from pull queries"
[associations val]
(if (and (sequential? val)
(= 2 (count val))
(or (contains? (get associations (first val)) :has-many)
(contains? (get associations (first val)) :belongs-to))
(string? (second val)))
[(first val) (json/read-str (second val) :key-fn qualify-col)]
val))
(def col-query
{"sqlite" ["select
m.name as table_name,
p.name as column_name
from sqlite_master m
left outer join pragma_table_info((m.name)) p on m.name <> p.name
order by table_name, column_name"]
"postgres" ["select table_name, column_name
from information_schema.columns
order by table_name, column_name"]})
(defn col-map [conn adapter]
(let [rows (jdbc/query conn (get col-query adapter))]
(->> (group-by :table_name rows)
(mapv (fn [[k v]]
[(keyword (utils/kebab-case k)) (->> (map :column_name v)
(map utils/kebab-case)
(map #(keyword (utils/kebab-case k) %)))]))
(into {}))))
(defmacro transaction [binder & body]
`(jdbc/with-db-transaction [~binder (connection)]
~@body))
(defn sql-vec
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)]
(if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))))
([v params]
(if (and (vector? v)
(map? params))
(sql-vec nil v params)
(sql-vec v params {})))
([v]
(sql-vec nil v nil)))
(defn q
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
associations-fn (load-string (slurp (or (io/resource "associations.clj")
"db/associations.clj")))
associations (if (some? associations-fn)
(associations-fn)
{})
col-map (col-map conn adapter)
sql-vec (if (sql-vec? v)
v
(sql/sql-vec adapter col-map associations v params))
_ (when (true? debug)
(println sql-vec))
rows (query conn
sql-vec
{:keywordize? false
:identifiers qualify-col})]
(walk/postwalk #(-> % coerce-inst coerce-timestamp-inst)
(walk/prewalk #(->> (one-first associations %) (parse-json associations))
rows))))
([v params]
(if (and (vector? v)
(map? params))
(q nil v params)
(q v params {})))
([v]
(q nil v nil)))
(defn execute!
([conn v params]
(let [conn (or conn (connection))
{:keys [adapter debug]} (db.connection/spec)
sql-vec (sql/sql-vec adapter {} {} v params)]
(when (true? debug)
(println sql-vec))
(jdbc/execute! conn sql-vec)))
([v params]
(if (and (vector? v)
(map? params))
(execute! nil v params)
(execute! v params {})))
([v]
(execute! nil v {})))
(defn pluck
([conn v params]
(first
(q conn v params)))
([v params]
(if (and (vector? v)
(map? params))
(pluck nil v params)
(pluck v params {})))
([v]
(pluck nil v {})))
(defn fetch
([conn k id]
(when (and (ident? k)
(some? id))
(first
(q conn '[:select *
:from ?from
:where [id ?id]
:limit 1]
{:from k
:id id}))))
([k id]
(fetch nil k id)))
(defn find-by
([conn k m]
(when (and (ident? k)
(map? m))
(first
(q conn [:select :*
:from k
:where (mapv identity m)
:limit 1]
{}))))
([k m]
(find-by nil k m)))
(defn select-rels [m]
(let [schema (db.schema/fetch)]
(select-keys m (->> (:joins schema)
(filter (fn [[_ v]] (qualified-ident? v)))
(into {})
(keys)))))
(defn resolve-select-rels [m]
(let [queries (->> (filter (fn [[_ v]] (vector? v)) m)
(db.transact/selects))
ids (->> (filter (fn [[_ v]] (number? v)) m)
(mapv (fn [[k v]] [(keyword (namespace k) (name k)) v]))
(into {}))
results (->> (map #(query (db.connection/connection) % {:keywordize? false
:identifiers qualify-col})
queries)
(map first)
(apply merge))]
(merge ids results)))
(defn many-rels [m]
(select-keys m (->> (db.schema/fetch)
(filter (fn [[_ v]] (and (or (contains? v :db/ref) (contains? v :db/joins))
(= :many (:db/type v)))))
(map first))))
(defn upsert-rel [parent [k v]]
(if (empty? v)
(let [schema (db.schema/fetch)
jk (or (get-in schema [k :db/joins])
(get-in schema [k :db/ref]))
k-ns (-> jk namespace utils/snake)
join-ns (-> jk name utils/snake)
_ (query (connection) [(str "delete from " k-ns " where " join-ns " = ? returning *") (get parent (keyword join-ns "id"))])]
[k []])
(let [k-ns (->> v first keys (filter qualified-ident?) first namespace)
parent-map (->> (filter (fn [[k _]] (= (name k) "id")) parent)
(map (fn [[k* v]] [(keyword k-ns (namespace k*)) v]))
(into {}))
v* (mapv #(merge parent-map %) v)
sql-vec (db.transact/sql-vec v*)
rows (->> (query (connection) sql-vec)
(mapv #(qualify-map k-ns %)))]
[k rows])))
(defn upsert-rels [parent m]
(->> (map #(upsert-rel parent %) m)
(into {})))
(defn transact [m]
"This function resolves foreign keys (or hydrates), it also deletes related rows based on idents as well as inserting and updating rows.
Here are some concrete examples:
Given this schema:
[{:db/ident :author/name
:db/type \"citext\"}
{:db/ident :author/email
:db/type \"citext\"}
{:db/rel :author/posts
:db/joins :post/author
:db/type :many}
{:db/col :post/title
:db/type \"text\"}
{:db/col :post/body
:db/type \"text\"}]
Insert multiple tables at once
(db/transact {:author/name \"test\"
:author/email \"PI:EMAIL:<EMAIL>END_PI\"
:author/posts [{:post/title \"title\"
:post/body \"body\"}]})
or just one
(db/transact {:author/name \"test2\"
:author/email \"PI:EMAIL:<EMAIL>END_PI\"})
Retrieve nested rows
(db/pull '[author/id author/name author/email
{:author/posts [post/id post/title post/body]}]
[:author/name \"test\"])
Update with the same command
(db/transact {:post/id 1
:post/author [:author/name \"test2\"]})
or the equivalent
(db/transact {:post/id 1
:post/author 2})
Delete multiple nested rows with one function
(db/transact {:author/id 2
:author/posts []})"
(let [k-ns (->> m keys (filter qualified-ident?) first namespace)
s-rels (select-rels m)
s-rel-results (resolve-select-rels s-rels) ; foreign keys
m-rels (many-rels m)
m* (merge m s-rel-results)
m* (apply dissoc m* (keys m-rels))
row (when (not (empty? (db.update/idents (map identity m*))))
(->> (db.update/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single)))
row (if (empty? row)
(->> (db.insert/sql-vec m*)
(query (connection))
(map #(qualify-map k-ns %))
(single))
row)
rel-rows (upsert-rels row m-rels)]
(merge row rel-rows)))
(defn insert
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/insert arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(insert nil arg)))
(defn update
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/update arg)]
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(execute! c v)
(let [table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))
id (if (sequential? arg)
(get-in arg [0 (keyword table "id")])
(get arg (keyword table "id")))]
(fetch c (keyword table) id)))
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(update nil arg)))
(defn unique-column-names [s]
(->> (string/split s #",")
(filter #(string/includes? % "unique"))
(map string/trim)
(map #(string/split % #" "))
(map first)))
(defn upsert
([conn arg opts]
(let [table-name (if (sequential? arg)
(-> arg first keys first utils/namespace*)
(-> arg keys first utils/namespace*))
{:keys [adapter]} (db.connection/spec)]
(when (nil? table-name)
(throw (Exception. "coast/upsert expects a map with qualified keywords")))
(condp = adapter
"sqlite" (if (nil? conn)
(transaction c
(let [{sql :sql} (pluck c ["select sql from sqlite_master where type = ? and name = ?" "table" table-name])
on-conflict (if (list? (:on-conflict opts))
(:on-conflict opts)
(unique-column-names sql))
v (helpers/upsert arg {:on-conflict on-conflict})]
(execute! c v)
(let [{id :id} (pluck c ["select last_insert_rowid() as id"])
id (if (zero? id)
(get (find-by c (keyword table-name) (select-keys arg (mapv #(keyword table-name %) on-conflict)))
(keyword table-name "id"))
id)
table (if (sequential? arg)
(-> arg first keys first namespace)
(-> arg keys first namespace))]
(fetch c (keyword table) id))))
(execute! conn (apply helpers/upsert arg opts)))
"postgres" (if (nil? conn)
(transaction c
(let [{indexdef :indexdef} (pluck c ["select indexdef from pg_indexes where tablename = ?" table-name])
on-conflict (-> (re-find #"\((.*)\)" indexdef)
(last)
(string/split #","))
v (helpers/upsert arg {:on-conflict on-conflict})
v (conj v :returning :*)]
(q c v)))
(q conn (conj (helpers/upsert arg opts)
:returning :*))))))
([arg]
(upsert nil arg {})))
(defn delete
([conn arg]
(let [{:keys [adapter]} (db.connection/spec)
v (helpers/delete arg)]
(condp = adapter
"sqlite" (first
(execute! conn v))
"postgres" (let [v (conj v :returning :*)]
(q conn v)))))
([arg]
(delete nil arg)))
(defn pull [v ident]
(pluck
[:pull v
:from (-> ident first namespace)
:where ident]))
(defn any-rows? [table]
(some?
(pluck
[:select :*
:from (keyword table)
:limit 1])))
(def migrate migrations/migrate)
(def rollback migrations/rollback)
(def reconnect! db.connection/reconnect!)
(defn -main [& [action db-name]]
(case action
"create" (println (create (or db-name (spec :database))))
"drop" (println (drop (or db-name (spec :database))))
"")
(System/exit 0))
|
[
{
"context": "mple sysex librarian.\"]\n [:p \"Copyright (c) 2020 Daniel Appelt\"]\n [:p \"It is released under the \"\n [:a {:hr",
"end": 2412,
"score": 0.9997954964637756,
"start": 2399,
"tag": "NAME",
"value": "Daniel Appelt"
},
{
"context": "ed under the \"\n [:a {:href \"https://github.com/danielappelt/midi-spider/blob/master/LICENSE\"} \"MIT license\"]\n",
"end": 2497,
"score": 0.9994840621948242,
"start": 2485,
"tag": "USERNAME",
"value": "danielappelt"
},
{
"context": "heck out its \"\n [:a {:href \"https://github.com/danielappelt/midi-spider\"} \"source code\"]\n \".\"]\n ])\n\n(def",
"end": 2617,
"score": 0.9976665377616882,
"start": 2605,
"tag": "USERNAME",
"value": "danielappelt"
}
] | src/cljs/midi_spider/views.cljs | danielappelt/midi-spider | 3 | (ns midi-spider.views
(:require
[clojure.string :as str]
[re-frame.core :as re-frame]
[midi-spider.events :as events]
[midi-spider.routes :as routes]
[midi-spider.subs :as subs]
))
(defn midi-port [port]
[:option {:value (.-id port)} (.-name port)])
(defn midi-ports [label subscription event]
(let [ports (re-frame/subscribe [subscription])
id (name subscription)]
;; Use list to return multiple top-level nodes (see https://purelyfunctional.tv/mini-guide/hiccup-tips/#multiple-tags)
(list
^{:key (str id "-label")}
[:label {:for id} label]
^{:key (str id "-select")}
[:select {:id id
:on-change #(re-frame/dispatch [event (.-value (.-currentTarget %))])}
(for [port @ports]
^{:key (.-id port)}
[midi-port port])])))
(defn home-panel []
[:div {:class "home"}
[:h1 "MIDI Spider"]
[:a {:href (routes/path-for ::about)} "About"]
[:div
(midi-ports "Output:" ::subs/outputs ::events/select-output)
;; A file input to load sysex from file
[:input {:type "file" :accept ".syx"
:on-change #(re-frame/dispatch [::events/change-out-file
(aget (.-files (.-target %)) 0)])}]
;; Provide a key in order to trigger re-rendering on out-buffer-text changes.
;; Please note that we need to make sure this key changes in order to trigger
;; a re-render.
^{:key @(re-frame/subscribe [::subs/out-update-time])}
[:textarea {:defaultValue @(re-frame/subscribe [::subs/out-buffer-text])
:on-blur #(re-frame/dispatch [::events/change-out-buffer-text
(.-value (.-target %))])}]
[:input {:type "submit"
:on-click #(re-frame/dispatch [::events/send-buffer])}]]
[:div
(midi-ports "Input:" ::subs/inputs ::events/select-input)
[:textarea {:value @(re-frame/subscribe [::subs/in-buffer-text])
:readOnly true}]
[:a {:href @(re-frame/subscribe [::subs/download-url])
:download "download.syx"} "Download"]]])
(defn about-panel []
[:div {:class "about"}
[:h1 "MIDI Spider - About"]
[:a {:href (routes/path-for ::home)} "Home Page"]
[:p "MIDI Spider is a web application that enables easy data exchange with "
"MIDI devices. It can be used as a simple sysex librarian."]
[:p "Copyright (c) 2020 Daniel Appelt"]
[:p "It is released under the "
[:a {:href "https://github.com/danielappelt/midi-spider/blob/master/LICENSE"} "MIT license"]
". Check out its "
[:a {:href "https://github.com/danielappelt/midi-spider"} "source code"]
"."]
])
(defn- show-panel [panel-name]
(case panel-name
::home [home-panel]
::about [about-panel]
[:div [:h1 "MIDI Spider (fallback panel)"]]))
(defn main-panel []
(let [active-panel (re-frame/subscribe [::subs/active-panel])]
[show-panel @active-panel]))
| 55412 | (ns midi-spider.views
(:require
[clojure.string :as str]
[re-frame.core :as re-frame]
[midi-spider.events :as events]
[midi-spider.routes :as routes]
[midi-spider.subs :as subs]
))
(defn midi-port [port]
[:option {:value (.-id port)} (.-name port)])
(defn midi-ports [label subscription event]
(let [ports (re-frame/subscribe [subscription])
id (name subscription)]
;; Use list to return multiple top-level nodes (see https://purelyfunctional.tv/mini-guide/hiccup-tips/#multiple-tags)
(list
^{:key (str id "-label")}
[:label {:for id} label]
^{:key (str id "-select")}
[:select {:id id
:on-change #(re-frame/dispatch [event (.-value (.-currentTarget %))])}
(for [port @ports]
^{:key (.-id port)}
[midi-port port])])))
(defn home-panel []
[:div {:class "home"}
[:h1 "MIDI Spider"]
[:a {:href (routes/path-for ::about)} "About"]
[:div
(midi-ports "Output:" ::subs/outputs ::events/select-output)
;; A file input to load sysex from file
[:input {:type "file" :accept ".syx"
:on-change #(re-frame/dispatch [::events/change-out-file
(aget (.-files (.-target %)) 0)])}]
;; Provide a key in order to trigger re-rendering on out-buffer-text changes.
;; Please note that we need to make sure this key changes in order to trigger
;; a re-render.
^{:key @(re-frame/subscribe [::subs/out-update-time])}
[:textarea {:defaultValue @(re-frame/subscribe [::subs/out-buffer-text])
:on-blur #(re-frame/dispatch [::events/change-out-buffer-text
(.-value (.-target %))])}]
[:input {:type "submit"
:on-click #(re-frame/dispatch [::events/send-buffer])}]]
[:div
(midi-ports "Input:" ::subs/inputs ::events/select-input)
[:textarea {:value @(re-frame/subscribe [::subs/in-buffer-text])
:readOnly true}]
[:a {:href @(re-frame/subscribe [::subs/download-url])
:download "download.syx"} "Download"]]])
(defn about-panel []
[:div {:class "about"}
[:h1 "MIDI Spider - About"]
[:a {:href (routes/path-for ::home)} "Home Page"]
[:p "MIDI Spider is a web application that enables easy data exchange with "
"MIDI devices. It can be used as a simple sysex librarian."]
[:p "Copyright (c) 2020 <NAME>"]
[:p "It is released under the "
[:a {:href "https://github.com/danielappelt/midi-spider/blob/master/LICENSE"} "MIT license"]
". Check out its "
[:a {:href "https://github.com/danielappelt/midi-spider"} "source code"]
"."]
])
(defn- show-panel [panel-name]
(case panel-name
::home [home-panel]
::about [about-panel]
[:div [:h1 "MIDI Spider (fallback panel)"]]))
(defn main-panel []
(let [active-panel (re-frame/subscribe [::subs/active-panel])]
[show-panel @active-panel]))
| true | (ns midi-spider.views
(:require
[clojure.string :as str]
[re-frame.core :as re-frame]
[midi-spider.events :as events]
[midi-spider.routes :as routes]
[midi-spider.subs :as subs]
))
(defn midi-port [port]
[:option {:value (.-id port)} (.-name port)])
(defn midi-ports [label subscription event]
(let [ports (re-frame/subscribe [subscription])
id (name subscription)]
;; Use list to return multiple top-level nodes (see https://purelyfunctional.tv/mini-guide/hiccup-tips/#multiple-tags)
(list
^{:key (str id "-label")}
[:label {:for id} label]
^{:key (str id "-select")}
[:select {:id id
:on-change #(re-frame/dispatch [event (.-value (.-currentTarget %))])}
(for [port @ports]
^{:key (.-id port)}
[midi-port port])])))
(defn home-panel []
[:div {:class "home"}
[:h1 "MIDI Spider"]
[:a {:href (routes/path-for ::about)} "About"]
[:div
(midi-ports "Output:" ::subs/outputs ::events/select-output)
;; A file input to load sysex from file
[:input {:type "file" :accept ".syx"
:on-change #(re-frame/dispatch [::events/change-out-file
(aget (.-files (.-target %)) 0)])}]
;; Provide a key in order to trigger re-rendering on out-buffer-text changes.
;; Please note that we need to make sure this key changes in order to trigger
;; a re-render.
^{:key @(re-frame/subscribe [::subs/out-update-time])}
[:textarea {:defaultValue @(re-frame/subscribe [::subs/out-buffer-text])
:on-blur #(re-frame/dispatch [::events/change-out-buffer-text
(.-value (.-target %))])}]
[:input {:type "submit"
:on-click #(re-frame/dispatch [::events/send-buffer])}]]
[:div
(midi-ports "Input:" ::subs/inputs ::events/select-input)
[:textarea {:value @(re-frame/subscribe [::subs/in-buffer-text])
:readOnly true}]
[:a {:href @(re-frame/subscribe [::subs/download-url])
:download "download.syx"} "Download"]]])
(defn about-panel []
[:div {:class "about"}
[:h1 "MIDI Spider - About"]
[:a {:href (routes/path-for ::home)} "Home Page"]
[:p "MIDI Spider is a web application that enables easy data exchange with "
"MIDI devices. It can be used as a simple sysex librarian."]
[:p "Copyright (c) 2020 PI:NAME:<NAME>END_PI"]
[:p "It is released under the "
[:a {:href "https://github.com/danielappelt/midi-spider/blob/master/LICENSE"} "MIT license"]
". Check out its "
[:a {:href "https://github.com/danielappelt/midi-spider"} "source code"]
"."]
])
(defn- show-panel [panel-name]
(case panel-name
::home [home-panel]
::about [about-panel]
[:div [:h1 "MIDI Spider (fallback panel)"]]))
(defn main-panel []
(let [active-panel (re-frame/subscribe [::subs/active-panel])]
[show-panel @active-panel]))
|
[
{
"context": "\n :change-on-blur? false\n :placeholder \"username\"\n :model @(re-frame/subscribe [:login-userna",
"end": 2086,
"score": 0.9969559907913208,
"start": 2078,
"tag": "USERNAME",
"value": "username"
},
{
"context": "status-tooltip status-tooltip\n :placeholder \"password\"\n :change-on-blur? false\n :model @(re-f",
"end": 2701,
"score": 0.9864409565925598,
"start": 2693,
"tag": "PASSWORD",
"value": "password"
}
] | src/dativetop/gui/src/dativetop_gui/login.cljs | jrwdunham/dative-toga | 1 | ;; View functions for Dative's login panel
;; Functions that return re-com widget components which react (i.e., modify the
;; DOM, or subscribe) to events emitted by the app database and which trigger
;; events based on a user's interaction with the GUI.
;; All Dative view modules should define a ``panel`` function.
(ns dativetop-gui.login
(:require [re-com.core :refer [h-box v-box box gap line title label
hyperlink-href input-text input-password
button p single-dropdown]]
[re-frame.core :as re-frame]
[dativetop-gui.utils :refer [panel-title title2 RHS-column-style
center-gap-px]]
[dativetop-gui.subs :as subs]))
(defn key-up-login-input
[e]
(when (= "Enter" (.-key e))
(re-frame/dispatch [:user-pressed-enter-in-login])))
(defn old-instance-select
[]
[h-box
:gap "10px"
:align :center
:children [[box
:child [single-dropdown
:width "250px"
:choices @(re-frame/subscribe [:old-instances-vec])
:model @(re-frame/subscribe [:current-old-instance])
:on-change #(re-frame/dispatch
[:user-changed-current-old-instance %])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])]]
[v-box
:children
[[gap :size "10px"]
[p
RHS-column-style
@(re-frame/subscribe [:current-old-instance-url])]]]]])
(defn username-input
[]
(let [status-meta @(re-frame/subscribe [:login-username-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-text
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:change-on-blur? false
:placeholder "username"
:model @(re-frame/subscribe [:login-username])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-username %])]]))
(defn password-input
[]
(let [status-meta @(re-frame/subscribe [:login-password-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-password
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:placeholder "password"
:change-on-blur? false
:model @(re-frame/subscribe [:login-password])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-password %])]]))
(defn login-button
[]
[box
:child
[button
:label "Login"
:disabled? @(re-frame/subscribe [:login-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-login]))]])
(defn logout-button
[]
[box
:child
[button
:label "Logout"
:disabled? @(re-frame/subscribe [:logout-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-logout]))]])
(defn login-panel
[]
[v-box
:children [[panel-title "Login"]
[gap :size "10px"]
[old-instance-select]
[gap :size "10px"]
[username-input]
[gap :size "10px"]
[password-input]
[gap :size "10px"]
[h-box
:children [[login-button]
[logout-button]]
:gap "5px"]]])
(defn panel
[]
[login-panel])
| 121136 | ;; View functions for Dative's login panel
;; Functions that return re-com widget components which react (i.e., modify the
;; DOM, or subscribe) to events emitted by the app database and which trigger
;; events based on a user's interaction with the GUI.
;; All Dative view modules should define a ``panel`` function.
(ns dativetop-gui.login
(:require [re-com.core :refer [h-box v-box box gap line title label
hyperlink-href input-text input-password
button p single-dropdown]]
[re-frame.core :as re-frame]
[dativetop-gui.utils :refer [panel-title title2 RHS-column-style
center-gap-px]]
[dativetop-gui.subs :as subs]))
(defn key-up-login-input
[e]
(when (= "Enter" (.-key e))
(re-frame/dispatch [:user-pressed-enter-in-login])))
(defn old-instance-select
[]
[h-box
:gap "10px"
:align :center
:children [[box
:child [single-dropdown
:width "250px"
:choices @(re-frame/subscribe [:old-instances-vec])
:model @(re-frame/subscribe [:current-old-instance])
:on-change #(re-frame/dispatch
[:user-changed-current-old-instance %])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])]]
[v-box
:children
[[gap :size "10px"]
[p
RHS-column-style
@(re-frame/subscribe [:current-old-instance-url])]]]]])
(defn username-input
[]
(let [status-meta @(re-frame/subscribe [:login-username-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-text
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:change-on-blur? false
:placeholder "username"
:model @(re-frame/subscribe [:login-username])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-username %])]]))
(defn password-input
[]
(let [status-meta @(re-frame/subscribe [:login-password-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-password
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:placeholder "<PASSWORD>"
:change-on-blur? false
:model @(re-frame/subscribe [:login-password])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-password %])]]))
(defn login-button
[]
[box
:child
[button
:label "Login"
:disabled? @(re-frame/subscribe [:login-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-login]))]])
(defn logout-button
[]
[box
:child
[button
:label "Logout"
:disabled? @(re-frame/subscribe [:logout-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-logout]))]])
(defn login-panel
[]
[v-box
:children [[panel-title "Login"]
[gap :size "10px"]
[old-instance-select]
[gap :size "10px"]
[username-input]
[gap :size "10px"]
[password-input]
[gap :size "10px"]
[h-box
:children [[login-button]
[logout-button]]
:gap "5px"]]])
(defn panel
[]
[login-panel])
| true | ;; View functions for Dative's login panel
;; Functions that return re-com widget components which react (i.e., modify the
;; DOM, or subscribe) to events emitted by the app database and which trigger
;; events based on a user's interaction with the GUI.
;; All Dative view modules should define a ``panel`` function.
(ns dativetop-gui.login
(:require [re-com.core :refer [h-box v-box box gap line title label
hyperlink-href input-text input-password
button p single-dropdown]]
[re-frame.core :as re-frame]
[dativetop-gui.utils :refer [panel-title title2 RHS-column-style
center-gap-px]]
[dativetop-gui.subs :as subs]))
(defn key-up-login-input
[e]
(when (= "Enter" (.-key e))
(re-frame/dispatch [:user-pressed-enter-in-login])))
(defn old-instance-select
[]
[h-box
:gap "10px"
:align :center
:children [[box
:child [single-dropdown
:width "250px"
:choices @(re-frame/subscribe [:old-instances-vec])
:model @(re-frame/subscribe [:current-old-instance])
:on-change #(re-frame/dispatch
[:user-changed-current-old-instance %])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])]]
[v-box
:children
[[gap :size "10px"]
[p
RHS-column-style
@(re-frame/subscribe [:current-old-instance-url])]]]]])
(defn username-input
[]
(let [status-meta @(re-frame/subscribe [:login-username-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-text
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:change-on-blur? false
:placeholder "username"
:model @(re-frame/subscribe [:login-username])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-username %])]]))
(defn password-input
[]
(let [status-meta @(re-frame/subscribe [:login-password-status])
status (first status-meta)
status-icon? (boolean status)
status-tooltip (or (second status-meta) "")]
[box
:child
[input-password
:attr {:on-key-up key-up-login-input}
:status status
:status-icon? status-icon?
:status-tooltip status-tooltip
:placeholder "PI:PASSWORD:<PASSWORD>END_PI"
:change-on-blur? false
:model @(re-frame/subscribe [:login-password])
:disabled? @(re-frame/subscribe [:login-inputs-disabled?])
:on-change #(re-frame/dispatch [:user-changed-password %])]]))
(defn login-button
[]
[box
:child
[button
:label "Login"
:disabled? @(re-frame/subscribe [:login-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-login]))]])
(defn logout-button
[]
[box
:child
[button
:label "Logout"
:disabled? @(re-frame/subscribe [:logout-disabled?])
:on-click (fn [e] (re-frame/dispatch [:user-clicked-logout]))]])
(defn login-panel
[]
[v-box
:children [[panel-title "Login"]
[gap :size "10px"]
[old-instance-select]
[gap :size "10px"]
[username-input]
[gap :size "10px"]
[password-input]
[gap :size "10px"]
[h-box
:children [[login-button]
[logout-button]]
:gap "5px"]]])
(defn panel
[]
[login-panel])
|
[
{
"context": "cebook-user [ctx facebook-user]\n (let [{:keys [id first_name last_name email locale]} facebook-user\n ",
"end": 914,
"score": 0.9665523767471313,
"start": 909,
"tag": "NAME",
"value": "first"
},
{
"context": " [ctx facebook-user]\n (let [{:keys [id first_name last_name email locale]} facebook-user\n email (",
"end": 924,
"score": 0.9435194134712219,
"start": 920,
"tag": "NAME",
"value": "last"
},
{
"context": "auth_user_id id\n :email email\n :first_name first_name\n :last_name last_name\n :country coun",
"end": 1552,
"score": 0.9704095125198364,
"start": 1547,
"tag": "NAME",
"value": "first"
},
{
"context": "er_id id\n :email email\n :first_name first_name\n :last_name last_name\n :country country\n ",
"end": 1557,
"score": 0.6205434203147888,
"start": 1553,
"tag": "NAME",
"value": "name"
},
{
"context": " email\n :first_name first_name\n :last_name last_name\n :country country\n :language languag",
"end": 1578,
"score": 0.9703031778335571,
"start": 1574,
"tag": "NAME",
"value": "last"
},
{
"context": "\n :first_name first_name\n :last_name last_name\n :country country\n :language language\n ",
"end": 1583,
"score": 0.5599177479743958,
"start": 1579,
"tag": "NAME",
"value": "name"
}
] | src/clj/salava/oauth/facebook.clj | discendum/salava | 17 | (ns salava.oauth.facebook
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def facebook-base-url "https://graph.facebook.com/v2.6")
(defn facebook-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :facebook :app-id])
app-secret (get-in ctx [:config :oauth :facebook :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url}}]
(d/access-token :get (str facebook-base-url "/oauth/access_token") opts)))
(defn parse-facebook-user [ctx facebook-user]
(let [{:keys [id first_name last_name email locale]} facebook-user
email (or email (str id "@facebook.com"))
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})_([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name first_name
:last_name last_name
:country country
:language language
:picture_url (get-in facebook-user [:picture :data :url])}))
(defn facebook-login [ctx code current-user-id error]
(try+
(if (or error (not code))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (facebook-access-token ctx code "/oauth/facebook")
facebook-user (d/oauth-user ctx (str facebook-base-url "/me") {:query-params {:access_token access-token :fields "id,email,first_name,last_name,picture,locale"}} parse-facebook-user)
user (d/get-or-create-user ctx "facebook" facebook-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id})))
(catch Object _
{:status "error" :message _})))
(defn facebook-deauthorize [ctx code current-user-id]
(try+
(let [access-token (facebook-access-token ctx code "/oauth/facebook/deauthorize")]
(d/oauth-request :delete (str facebook-base-url "/me/permissions") {:query-params {:access_token access-token}})
(d/remove-oauth-user ctx current-user-id "facebook")
{:status "success"})
(catch Object _
{:status "error" :message _})))
| 105762 | (ns salava.oauth.facebook
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def facebook-base-url "https://graph.facebook.com/v2.6")
(defn facebook-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :facebook :app-id])
app-secret (get-in ctx [:config :oauth :facebook :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url}}]
(d/access-token :get (str facebook-base-url "/oauth/access_token") opts)))
(defn parse-facebook-user [ctx facebook-user]
(let [{:keys [id <NAME>_name <NAME>_name email locale]} facebook-user
email (or email (str id "@facebook.com"))
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})_([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name <NAME>_<NAME>
:last_name <NAME>_<NAME>
:country country
:language language
:picture_url (get-in facebook-user [:picture :data :url])}))
(defn facebook-login [ctx code current-user-id error]
(try+
(if (or error (not code))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (facebook-access-token ctx code "/oauth/facebook")
facebook-user (d/oauth-user ctx (str facebook-base-url "/me") {:query-params {:access_token access-token :fields "id,email,first_name,last_name,picture,locale"}} parse-facebook-user)
user (d/get-or-create-user ctx "facebook" facebook-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id})))
(catch Object _
{:status "error" :message _})))
(defn facebook-deauthorize [ctx code current-user-id]
(try+
(let [access-token (facebook-access-token ctx code "/oauth/facebook/deauthorize")]
(d/oauth-request :delete (str facebook-base-url "/me/permissions") {:query-params {:access_token access-token}})
(d/remove-oauth-user ctx current-user-id "facebook")
{:status "success"})
(catch Object _
{:status "error" :message _})))
| true | (ns salava.oauth.facebook
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def facebook-base-url "https://graph.facebook.com/v2.6")
(defn facebook-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :facebook :app-id])
app-secret (get-in ctx [:config :oauth :facebook :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url}}]
(d/access-token :get (str facebook-base-url "/oauth/access_token") opts)))
(defn parse-facebook-user [ctx facebook-user]
(let [{:keys [id PI:NAME:<NAME>END_PI_name PI:NAME:<NAME>END_PI_name email locale]} facebook-user
email (or email (str id "@facebook.com"))
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})_([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI
:last_name PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI
:country country
:language language
:picture_url (get-in facebook-user [:picture :data :url])}))
(defn facebook-login [ctx code current-user-id error]
(try+
(if (or error (not code))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (facebook-access-token ctx code "/oauth/facebook")
facebook-user (d/oauth-user ctx (str facebook-base-url "/me") {:query-params {:access_token access-token :fields "id,email,first_name,last_name,picture,locale"}} parse-facebook-user)
user (d/get-or-create-user ctx "facebook" facebook-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id})))
(catch Object _
{:status "error" :message _})))
(defn facebook-deauthorize [ctx code current-user-id]
(try+
(let [access-token (facebook-access-token ctx code "/oauth/facebook/deauthorize")]
(d/oauth-request :delete (str facebook-base-url "/me/permissions") {:query-params {:access_token access-token}})
(d/remove-oauth-user ctx current-user-id "facebook")
{:status "success"})
(catch Object _
{:status "error" :message _})))
|
[
{
"context": "el \"alternate\"\n :title \"Evolving Ideas - Kevin Litwack's Blog\"\n :type \"application/atom+xml\"}]\n",
"end": 1614,
"score": 0.9997955560684204,
"start": 1601,
"tag": "NAME",
"value": "Kevin Litwack"
},
{
"context": "t col-xs-12 col-sm-6 col-md-6\"}\n \"Copyright © Kevin Litwack, 2014\"]\n [:div {:class \"col-xs-12 col-sm-6 co",
"end": 2746,
"score": 0.9996574521064758,
"start": 2733,
"tag": "NAME",
"value": "Kevin Litwack"
}
] | template/layouts/default.clj | Geeber/kevinlitwack.com | 0 | ; @title default title
; @format html5
(defn menu []
(list
[:button
{:type "button"
:class "navbar-toggle btn-navbar collapsed"
:data-toggle "collapse"
:data-target ".primary .navbar-collapse"}
[:span.text "Menu"]
[:span.icon-bar]
[:span.icon-bar]
[:span.icon-bar]]
[:nav {:class "collapse collapsing navbar-collapse"}
[:ul {:class "nav navbar-nav navbar-center"}
[:li.parent
(link "Personal" "personal/about.html")
[:ul.sub
[:li (link "About Me" "personal/about.html")]
[:li (link "Burning Man" "personal/burningman.html")]
[:li (link "Kallisti" "personal/kallisti.html")]]]
[:li.parent
(link "Professional" "professional/keen.html")
[:ul.sub
[:li (link "Keen" "professional/keen.html")]
[:li (link "Consulting" "professional/consulting.html")]
[:li (link "Resume" "professional/resume.html")]]]
[:li.parent
(link "Blog" "blog/index.html")
[:ul.sub
[:li (link "Tags" "blog/tags.html")]
[:li (link "Atom Feed" "atom.xml")]]]
[:li (link "Contact" "contact.html")]]]))
[:head
[:title
(if (= (:title site) "home")
(:site-title site)
(str (:site-title site) " - " (:title site)))]
[:meta {:class "viewport"
:name "viewport"
:content "width=device-width, initial-scale=1.0"}]
[:meta {:content "IE=edge" :http-equiv="X-UA-Compatible"}]
[:meta {:charset (:charset site)}]
[:link {:rel "shortcut icon"
:href "/img/favicon.png"}]
[:link {:href "/atom.xml"
:rel "alternate"
:title "Evolving Ideas - Kevin Litwack's Blog"
:type "application/atom+xml"}]
(css ["/css/prettify.css" (:css site ()) (:extra-css site ())])
; (css {:media "only screen and (max-device-width:480px)"} (:device-css site))
(css "/css/ie/ie.css")]
; /head
[:body.fixed-header
[:div.page-box
[:div.page-box-content
[:header {:class "header header-two"}
[:div.container
[:div.row
[:div {:class "col-xs-6 col-md-3 col-lg-3 logo-box"}
[:div.logo
[:a {:href "/"}
[:img {:src "/img/logo2.png" :class "logo-img" :alt ""}]
]]]
[:div {:class "col-xs-6 col-md-6 col-lg-6 right-box"}
[:div.right-box-wrapper
[:div.primary
[:div {:class "navbar navbar-default" :role "navigation"}
(menu)]]]]]]]
[:section#main
[:header.page-header
[:div.container
[:h1.title (:title site)]]]
[:div.container
[:div.row
[:article {:class "content col-sm-12 col-md-9 col-lg-8"} contents]]]]]]
[:footer#footer
[:div.footer-bottom
[:div.container
[:div.row
[:div {:class "copyright col-xs-12 col-sm-6 col-md-6"}
"Copyright © Kevin Litwack, 2014"]
[:div {:class "col-xs-12 col-sm-6 col-md-6"}
[:a {:href "#" :class "up"}
[:span {:class "glyphicon glyphicon-arrow-up"}]]]]]]]
;(link (str "@" (:twitter site)) (str "http://twitter.com/" (:twitter site)))
(js ["/js/prettify.js"
"/js/lang-clj.js"
(:js site ())])]
; /body
| 16074 | ; @title default title
; @format html5
(defn menu []
(list
[:button
{:type "button"
:class "navbar-toggle btn-navbar collapsed"
:data-toggle "collapse"
:data-target ".primary .navbar-collapse"}
[:span.text "Menu"]
[:span.icon-bar]
[:span.icon-bar]
[:span.icon-bar]]
[:nav {:class "collapse collapsing navbar-collapse"}
[:ul {:class "nav navbar-nav navbar-center"}
[:li.parent
(link "Personal" "personal/about.html")
[:ul.sub
[:li (link "About Me" "personal/about.html")]
[:li (link "Burning Man" "personal/burningman.html")]
[:li (link "Kallisti" "personal/kallisti.html")]]]
[:li.parent
(link "Professional" "professional/keen.html")
[:ul.sub
[:li (link "Keen" "professional/keen.html")]
[:li (link "Consulting" "professional/consulting.html")]
[:li (link "Resume" "professional/resume.html")]]]
[:li.parent
(link "Blog" "blog/index.html")
[:ul.sub
[:li (link "Tags" "blog/tags.html")]
[:li (link "Atom Feed" "atom.xml")]]]
[:li (link "Contact" "contact.html")]]]))
[:head
[:title
(if (= (:title site) "home")
(:site-title site)
(str (:site-title site) " - " (:title site)))]
[:meta {:class "viewport"
:name "viewport"
:content "width=device-width, initial-scale=1.0"}]
[:meta {:content "IE=edge" :http-equiv="X-UA-Compatible"}]
[:meta {:charset (:charset site)}]
[:link {:rel "shortcut icon"
:href "/img/favicon.png"}]
[:link {:href "/atom.xml"
:rel "alternate"
:title "Evolving Ideas - <NAME>'s Blog"
:type "application/atom+xml"}]
(css ["/css/prettify.css" (:css site ()) (:extra-css site ())])
; (css {:media "only screen and (max-device-width:480px)"} (:device-css site))
(css "/css/ie/ie.css")]
; /head
[:body.fixed-header
[:div.page-box
[:div.page-box-content
[:header {:class "header header-two"}
[:div.container
[:div.row
[:div {:class "col-xs-6 col-md-3 col-lg-3 logo-box"}
[:div.logo
[:a {:href "/"}
[:img {:src "/img/logo2.png" :class "logo-img" :alt ""}]
]]]
[:div {:class "col-xs-6 col-md-6 col-lg-6 right-box"}
[:div.right-box-wrapper
[:div.primary
[:div {:class "navbar navbar-default" :role "navigation"}
(menu)]]]]]]]
[:section#main
[:header.page-header
[:div.container
[:h1.title (:title site)]]]
[:div.container
[:div.row
[:article {:class "content col-sm-12 col-md-9 col-lg-8"} contents]]]]]]
[:footer#footer
[:div.footer-bottom
[:div.container
[:div.row
[:div {:class "copyright col-xs-12 col-sm-6 col-md-6"}
"Copyright © <NAME>, 2014"]
[:div {:class "col-xs-12 col-sm-6 col-md-6"}
[:a {:href "#" :class "up"}
[:span {:class "glyphicon glyphicon-arrow-up"}]]]]]]]
;(link (str "@" (:twitter site)) (str "http://twitter.com/" (:twitter site)))
(js ["/js/prettify.js"
"/js/lang-clj.js"
(:js site ())])]
; /body
| true | ; @title default title
; @format html5
(defn menu []
(list
[:button
{:type "button"
:class "navbar-toggle btn-navbar collapsed"
:data-toggle "collapse"
:data-target ".primary .navbar-collapse"}
[:span.text "Menu"]
[:span.icon-bar]
[:span.icon-bar]
[:span.icon-bar]]
[:nav {:class "collapse collapsing navbar-collapse"}
[:ul {:class "nav navbar-nav navbar-center"}
[:li.parent
(link "Personal" "personal/about.html")
[:ul.sub
[:li (link "About Me" "personal/about.html")]
[:li (link "Burning Man" "personal/burningman.html")]
[:li (link "Kallisti" "personal/kallisti.html")]]]
[:li.parent
(link "Professional" "professional/keen.html")
[:ul.sub
[:li (link "Keen" "professional/keen.html")]
[:li (link "Consulting" "professional/consulting.html")]
[:li (link "Resume" "professional/resume.html")]]]
[:li.parent
(link "Blog" "blog/index.html")
[:ul.sub
[:li (link "Tags" "blog/tags.html")]
[:li (link "Atom Feed" "atom.xml")]]]
[:li (link "Contact" "contact.html")]]]))
[:head
[:title
(if (= (:title site) "home")
(:site-title site)
(str (:site-title site) " - " (:title site)))]
[:meta {:class "viewport"
:name "viewport"
:content "width=device-width, initial-scale=1.0"}]
[:meta {:content "IE=edge" :http-equiv="X-UA-Compatible"}]
[:meta {:charset (:charset site)}]
[:link {:rel "shortcut icon"
:href "/img/favicon.png"}]
[:link {:href "/atom.xml"
:rel "alternate"
:title "Evolving Ideas - PI:NAME:<NAME>END_PI's Blog"
:type "application/atom+xml"}]
(css ["/css/prettify.css" (:css site ()) (:extra-css site ())])
; (css {:media "only screen and (max-device-width:480px)"} (:device-css site))
(css "/css/ie/ie.css")]
; /head
[:body.fixed-header
[:div.page-box
[:div.page-box-content
[:header {:class "header header-two"}
[:div.container
[:div.row
[:div {:class "col-xs-6 col-md-3 col-lg-3 logo-box"}
[:div.logo
[:a {:href "/"}
[:img {:src "/img/logo2.png" :class "logo-img" :alt ""}]
]]]
[:div {:class "col-xs-6 col-md-6 col-lg-6 right-box"}
[:div.right-box-wrapper
[:div.primary
[:div {:class "navbar navbar-default" :role "navigation"}
(menu)]]]]]]]
[:section#main
[:header.page-header
[:div.container
[:h1.title (:title site)]]]
[:div.container
[:div.row
[:article {:class "content col-sm-12 col-md-9 col-lg-8"} contents]]]]]]
[:footer#footer
[:div.footer-bottom
[:div.container
[:div.row
[:div {:class "copyright col-xs-12 col-sm-6 col-md-6"}
"Copyright © PI:NAME:<NAME>END_PI, 2014"]
[:div {:class "col-xs-12 col-sm-6 col-md-6"}
[:a {:href "#" :class "up"}
[:span {:class "glyphicon glyphicon-arrow-up"}]]]]]]]
;(link (str "@" (:twitter site)) (str "http://twitter.com/" (:twitter site)))
(js ["/js/prettify.js"
"/js/lang-clj.js"
(:js site ())])]
; /body
|
[
{
"context": "rium.core)\n (def s (cell {:label \"root name\"} \"Howard\"))\n (def u (cell {:label \"upper-case\"}\n ",
"end": 11741,
"score": 0.9863091707229614,
"start": 11735,
"tag": "NAME",
"value": "Howard"
},
{
"context": "nge! r #(println \"r changed to\" %)))\n (force! s \"Suzy\")\n (force! s \"Jacob\")\n (force! s \"JACob\")\n )",
"end": 12264,
"score": 0.9997563362121582,
"start": 12260,
"tag": "NAME",
"value": "Suzy"
},
{
"context": "changed to\" %)))\n (force! s \"Suzy\")\n (force! s \"Jacob\")\n (force! s \"JACob\")\n )",
"end": 12285,
"score": 0.999448299407959,
"start": 12280,
"tag": "NAME",
"value": "Jacob"
},
{
"context": "orce! s \"Suzy\")\n (force! s \"Jacob\")\n (force! s \"JACob\")\n )",
"end": 12306,
"score": 0.9997725486755371,
"start": 12301,
"tag": "NAME",
"value": "JACob"
}
] | src/io/aviso/frappe.clj | AvisoNovate/frappe | 0 | (ns io.aviso.frappe
"A take on server-side functional/reactive programming, with an eye towards smart publishing."
(:require [io.aviso.toolchest.macros :refer [cond-let]]
[com.stuartsierra.dependency :as dep]
[clojure.pprint :as pp]
[medley.core :as medley]
[clojure.set :as set]
[clojure.tools.logging :as l]
[clojure.string :as str])
(:import [clojure.lang IDeref]
[java.io Writer]
[java.util.concurrent.atomic AtomicInteger]))
(def ^:dynamic ^:no-doc *defining-cell*
"Identifies the cell that is currently being defined (and executed) to establish dependencies."
nil)
(def ^:no-doc empty-reaction
{:dirty-cells #{}
:pending-recalcs #{}
:pending-callbacks []})
(def ^:dynamic ^:no-doc *reaction*
"A atom that tracks information about the current reactive transaction."
nil)
(defprotocol Cell
"Defines the behavior of a Cell, which is a value computed from other Cells. These are largely internal
and should not be directly invoked by user code."
(on-change! [this callback]
"Adds a callback to the cell; the callback is only invoked when the value for the cell changes.
The callback is a function of a single argument: the new value for the cell.
The callback is also invoked when it is first added to the Cell.
The order in which callbacks are invoked (when changes do occur) is not specified.
Returns the cell.")
(recalc! [this]
"Forces the cell to recalculate its value, when a dependent cell changes. This will
in turn invoke [[force!]], which can then inform other cells and listeners.")
(force! [this new-value]
"Forces a change to a cell, which should only occur for edges (cells with constant values
and no dependencies).
The current value of the cell will change, and listeners and dependent cells will be notified.
Returns the cell.")
(add-dependant! [this other]
"Adds another cell as a dependant of the this cell. When this cell's value changes,
each dependant is notified to recompute its value.
Returns this cell.")
(dependants [this]
"Returns the dependants of this cell; cells whose value depends on this cell."))
(defn- add-if-not-pending-recalc [reaction cell]
(if (-> reaction :pending-recalcs (contains? cell))
reaction
(update reaction :dirty-cells conj cell)))
(defn- add-dirty-cell!
[cell]
(swap! *reaction* add-if-not-pending-recalc cell))
(defn- add-callback!
[callback cell-value]
(swap! *reaction* update :pending-callbacks conj [callback cell-value]))
(defn ^:no-doc finish-reaction!
[]
(loop [i 0]
(cond-let
(= 10 i)
(throw (ex-info "Reaction did not settle after 10 cycles."
{:reaction @*reaction*}))
[{:keys [dirty-cells pending-callbacks]} @*reaction*]
(and (empty? dirty-cells)
(empty? pending-callbacks))
nil
:else
(do
;; This is an optimization designed to minimize unnecessary (or transitional) recalculations of a cell.
;; If cell A depends on cell B and cell C, then order counts. You want cells B and C to recalc before A.
;; We use dependency ordering here; we identify that A is a dependant of B (that is, A depends on B)
;; which ensures that A will recalc after B. Same for C. We cull out edges
(let [dependency-pairs (for [cell dirty-cells
dependant (dependants cell)
:when (dirty-cells dependant)]
[cell dependant])
graph (reduce (fn [g [dependency cell]] (dep/depend g cell dependency))
(dep/graph)
dependency-pairs)
comparator (dep/topo-comparator graph)
;; Order dependants before dependencies, with everything else in arbitrary order at
;; the end.
recalc-order (sort comparator dirty-cells)]
;; Any cell in the current iteration that gets marked dirty will be ignored and not
;; added to the next iteration.
(reset! *reaction* (assoc empty-reaction :pending-recalcs dirty-cells))
(doseq [cell recalc-order]
(recalc! cell)))
(doseq [[callback value] pending-callbacks]
(callback value))
;; Those cells & callbacks may have changed other things resulting in
;; further dirty cells & callbacks.
(recur (inc i))))))
(defmacro reaction
"A reaction is a reactive transaction; it is useful when invoking [[force!]] on several
cells to handle the notifications as a single unit, which reduces the number of iterations necessary
to propogate changes through the graph, and helps reduce the chances of an redundant recalc."
[& body]
`(binding [*reaction* (atom empty-reaction)]
(let [result# (do ~@body)]
(finish-reaction!)
result#)))
(defrecord CellData [dependants change-listeners current-value])
(defrecord ^:no-doc CellImpl [id f label cell-data]
Cell
(on-change! [this callback]
(swap! cell-data update :change-listeners conj callback)
(callback @this)
this)
(add-dependant! [this other]
(swap! cell-data update :dependants conj other)
this)
(dependants [_] (:dependants @cell-data))
(recalc! [this]
(l/debugf "Forced recalculation of %s." (pr-str this))
(force! this (f)))
(force! [this new-value]
(cond
;; In many cases, the new computed value is the same as the prior value so
;; there's no need to go further.
(= (:current-value @cell-data) new-value)
nil
;; Create, as needed, a reactive transaction.
(nil? *reaction*)
(reaction
(force! this new-value))
:else
(let [{:keys [change-listeners dependants]} (swap! cell-data assoc :current-value new-value)]
(if-not (= *defining-cell* this)
(l/debugf "%s has changed, affecting %s."
(pr-str this)
(if (empty? dependants)
"no other cells"
(->> dependants
(map pr-str)
(str/join ", ")))))
;; These behaviors are deferred to help avoid redundant work.
(doseq [listener change-listeners]
(add-callback! listener new-value))
(doseq [cell dependants]
(add-dirty-cell! cell))))
this)
IDeref
(deref [this]
(when *defining-cell*
;; This cell was dereferenced while defining another cell. That means
;; the cell being defined is a dependant of this cell, and should recalc
;; when this cell changes.
(add-dependant! this *defining-cell*))
(:current-value @cell-data)))
(defmethod print-method CellImpl [cell ^Writer w]
(let [{:keys [id label]} cell]
(.write w (str "Cell[" id
(if label
(str " - " label))
"]"))))
(defmethod pp/simple-dispatch CellImpl
[cell]
(let [cell-data (-> cell :cell-data deref)]
(pp/simple-dispatch
(-> cell-data
(select-keys [:current-value :change-listeners])
(merge (select-keys cell [:id :label]))
(assoc :dependants (map :id (:dependants cell-data)))))))
(defonce ^:private next-cell-id (AtomicInteger. 0))
(defn cell*
"Creates a new cell around a function of no arguments that computes its value.
The function is almost always a closure that can reference other cells.
The options map currently supports a single key, :label, a string used
when printing the cell.
A cell may be dereferenced (use the @ reader macro, or deref special form)."
[options f]
(let [cell (->CellImpl (.incrementAndGet next-cell-id)
f
(:label options)
(atom (->CellData #{} [] nil)))]
;; This forces an evaluation of the cell, which will trigger any dependencies, letting
;; us build up the graph.
(binding [*defining-cell* cell]
(force! cell (f)))
cell))
(defmacro cell
"Creates a cell, wrapping the body up as the necessary function used by [[cell*]].
If there are two or more forms in the body and the first form is a map, then the first
form will be used as the options for the new cell.
The only current option is :label, a string used when printing the cell."
[& body]
(if (and (< 1 (count body))
(map? (first body)))
(let [[options & more-body] body]
`(cell* ~options (fn [] ~@more-body)))
`(cell* nil (fn [] ~@body))))
;;; This is feeling like something that should be dealt with using transducers.
(defn cmap
"Given a cell that contains a map of keys to cells, returns a new map with the same keys,
but new cells with the cell values transformed by the value-transform function."
[value-transform source-cell]
(cell (medley/map-vals
(fn [value-cell]
(cell (value-transform @value-cell)))
@source-cell)))
(defn project
"Given a cell containing a map of keys to cells, returns a new cell with the same value as the cell
with the given key."
[source-cell k]
(let [source-map @source-cell]
(cell (get source-map k))))
(defn accumulate
"Accumulates a map from a map in the source cell. On each change to the source-cell, its current
state is merged into the value for this cell."
[source-cell]
(let [prev-map (atom {})]
(cell
(swap! prev-map merge @source-cell))))
(defn delta
"Given a source cell containing a map of keys to cells, returns a new cell
containing a map of just the added keys and values (on any change to the source-cell)."
[source-cell]
(let [prior-keys (atom nil)]
(cell
(let [source-map @source-cell
source-keys (set (keys source-map))
added-keys (set/difference source-keys @prior-keys)]
;; Save the current set of keys for the next go-around.
(reset! prior-keys source-keys)
(select-keys source-map added-keys)))))
(defmacro ignoring-dependencies
"Creates a block where dependencies are not tracked, which is typically used when a container of cells is defined in terms
of another container of cells, and a transform applied to the cells. The new container should depend on just the old container and not
on the cells inside the old container.
For example, this is used by [[map-values]]."
[& body]
`(binding [*defining-cell* nil] ~@body))
(defn map-values
"Given a cell containing a map, returns a new map.
Each new value is the result of passing the old value through a transformation function.
Generally, the map values will themselves be cells.
The returned map cell will only have a dependency on the incoming map cell,
even when the provided map values are cells and the transform function dereferences the cells."
[value-xform map-cell]
(cell
(medley/map-vals
;; This is used to prevent the returned map cell from depending on each transformed cell.
;; It should only depend on the incoming map cell.
(fn [v]
(ignoring-dependencies (value-xform v)))
@map-cell)))
(defn cfilter
"Creates a new cell from a source cell containing a map. The new cell
contains a subset of the keys from the source cell, based on the key filter."
[key-filter source-cell]
(cell
(medley/filter-keys key-filter @source-cell)))
(comment
(do
(require '[clojure.string :as str])
(use 'clojure.pprint)
(use 'clojure.repl)
(use 'criterium.core)
(def s (cell {:label "root name"} "Howard"))
(def u (cell {:label "upper-case"}
(println "recalc: u")
(str/upper-case @s)))
(def r (cell {:label "reversed"}
(println "recalc: r")
(apply str (reverse @u))))
(def c (cell {:label "combined"}
(println "recalc: c")
(str @r
"-"
@s)))
(on-change! u #(println "u changed to" %))
(on-change! c #(println "c changed to" %))
(on-change! r #(println "r changed to" %)))
(force! s "Suzy")
(force! s "Jacob")
(force! s "JACob")
) | 29982 | (ns io.aviso.frappe
"A take on server-side functional/reactive programming, with an eye towards smart publishing."
(:require [io.aviso.toolchest.macros :refer [cond-let]]
[com.stuartsierra.dependency :as dep]
[clojure.pprint :as pp]
[medley.core :as medley]
[clojure.set :as set]
[clojure.tools.logging :as l]
[clojure.string :as str])
(:import [clojure.lang IDeref]
[java.io Writer]
[java.util.concurrent.atomic AtomicInteger]))
(def ^:dynamic ^:no-doc *defining-cell*
"Identifies the cell that is currently being defined (and executed) to establish dependencies."
nil)
(def ^:no-doc empty-reaction
{:dirty-cells #{}
:pending-recalcs #{}
:pending-callbacks []})
(def ^:dynamic ^:no-doc *reaction*
"A atom that tracks information about the current reactive transaction."
nil)
(defprotocol Cell
"Defines the behavior of a Cell, which is a value computed from other Cells. These are largely internal
and should not be directly invoked by user code."
(on-change! [this callback]
"Adds a callback to the cell; the callback is only invoked when the value for the cell changes.
The callback is a function of a single argument: the new value for the cell.
The callback is also invoked when it is first added to the Cell.
The order in which callbacks are invoked (when changes do occur) is not specified.
Returns the cell.")
(recalc! [this]
"Forces the cell to recalculate its value, when a dependent cell changes. This will
in turn invoke [[force!]], which can then inform other cells and listeners.")
(force! [this new-value]
"Forces a change to a cell, which should only occur for edges (cells with constant values
and no dependencies).
The current value of the cell will change, and listeners and dependent cells will be notified.
Returns the cell.")
(add-dependant! [this other]
"Adds another cell as a dependant of the this cell. When this cell's value changes,
each dependant is notified to recompute its value.
Returns this cell.")
(dependants [this]
"Returns the dependants of this cell; cells whose value depends on this cell."))
(defn- add-if-not-pending-recalc [reaction cell]
(if (-> reaction :pending-recalcs (contains? cell))
reaction
(update reaction :dirty-cells conj cell)))
(defn- add-dirty-cell!
[cell]
(swap! *reaction* add-if-not-pending-recalc cell))
(defn- add-callback!
[callback cell-value]
(swap! *reaction* update :pending-callbacks conj [callback cell-value]))
(defn ^:no-doc finish-reaction!
[]
(loop [i 0]
(cond-let
(= 10 i)
(throw (ex-info "Reaction did not settle after 10 cycles."
{:reaction @*reaction*}))
[{:keys [dirty-cells pending-callbacks]} @*reaction*]
(and (empty? dirty-cells)
(empty? pending-callbacks))
nil
:else
(do
;; This is an optimization designed to minimize unnecessary (or transitional) recalculations of a cell.
;; If cell A depends on cell B and cell C, then order counts. You want cells B and C to recalc before A.
;; We use dependency ordering here; we identify that A is a dependant of B (that is, A depends on B)
;; which ensures that A will recalc after B. Same for C. We cull out edges
(let [dependency-pairs (for [cell dirty-cells
dependant (dependants cell)
:when (dirty-cells dependant)]
[cell dependant])
graph (reduce (fn [g [dependency cell]] (dep/depend g cell dependency))
(dep/graph)
dependency-pairs)
comparator (dep/topo-comparator graph)
;; Order dependants before dependencies, with everything else in arbitrary order at
;; the end.
recalc-order (sort comparator dirty-cells)]
;; Any cell in the current iteration that gets marked dirty will be ignored and not
;; added to the next iteration.
(reset! *reaction* (assoc empty-reaction :pending-recalcs dirty-cells))
(doseq [cell recalc-order]
(recalc! cell)))
(doseq [[callback value] pending-callbacks]
(callback value))
;; Those cells & callbacks may have changed other things resulting in
;; further dirty cells & callbacks.
(recur (inc i))))))
(defmacro reaction
"A reaction is a reactive transaction; it is useful when invoking [[force!]] on several
cells to handle the notifications as a single unit, which reduces the number of iterations necessary
to propogate changes through the graph, and helps reduce the chances of an redundant recalc."
[& body]
`(binding [*reaction* (atom empty-reaction)]
(let [result# (do ~@body)]
(finish-reaction!)
result#)))
(defrecord CellData [dependants change-listeners current-value])
(defrecord ^:no-doc CellImpl [id f label cell-data]
Cell
(on-change! [this callback]
(swap! cell-data update :change-listeners conj callback)
(callback @this)
this)
(add-dependant! [this other]
(swap! cell-data update :dependants conj other)
this)
(dependants [_] (:dependants @cell-data))
(recalc! [this]
(l/debugf "Forced recalculation of %s." (pr-str this))
(force! this (f)))
(force! [this new-value]
(cond
;; In many cases, the new computed value is the same as the prior value so
;; there's no need to go further.
(= (:current-value @cell-data) new-value)
nil
;; Create, as needed, a reactive transaction.
(nil? *reaction*)
(reaction
(force! this new-value))
:else
(let [{:keys [change-listeners dependants]} (swap! cell-data assoc :current-value new-value)]
(if-not (= *defining-cell* this)
(l/debugf "%s has changed, affecting %s."
(pr-str this)
(if (empty? dependants)
"no other cells"
(->> dependants
(map pr-str)
(str/join ", ")))))
;; These behaviors are deferred to help avoid redundant work.
(doseq [listener change-listeners]
(add-callback! listener new-value))
(doseq [cell dependants]
(add-dirty-cell! cell))))
this)
IDeref
(deref [this]
(when *defining-cell*
;; This cell was dereferenced while defining another cell. That means
;; the cell being defined is a dependant of this cell, and should recalc
;; when this cell changes.
(add-dependant! this *defining-cell*))
(:current-value @cell-data)))
(defmethod print-method CellImpl [cell ^Writer w]
(let [{:keys [id label]} cell]
(.write w (str "Cell[" id
(if label
(str " - " label))
"]"))))
(defmethod pp/simple-dispatch CellImpl
[cell]
(let [cell-data (-> cell :cell-data deref)]
(pp/simple-dispatch
(-> cell-data
(select-keys [:current-value :change-listeners])
(merge (select-keys cell [:id :label]))
(assoc :dependants (map :id (:dependants cell-data)))))))
(defonce ^:private next-cell-id (AtomicInteger. 0))
(defn cell*
"Creates a new cell around a function of no arguments that computes its value.
The function is almost always a closure that can reference other cells.
The options map currently supports a single key, :label, a string used
when printing the cell.
A cell may be dereferenced (use the @ reader macro, or deref special form)."
[options f]
(let [cell (->CellImpl (.incrementAndGet next-cell-id)
f
(:label options)
(atom (->CellData #{} [] nil)))]
;; This forces an evaluation of the cell, which will trigger any dependencies, letting
;; us build up the graph.
(binding [*defining-cell* cell]
(force! cell (f)))
cell))
(defmacro cell
"Creates a cell, wrapping the body up as the necessary function used by [[cell*]].
If there are two or more forms in the body and the first form is a map, then the first
form will be used as the options for the new cell.
The only current option is :label, a string used when printing the cell."
[& body]
(if (and (< 1 (count body))
(map? (first body)))
(let [[options & more-body] body]
`(cell* ~options (fn [] ~@more-body)))
`(cell* nil (fn [] ~@body))))
;;; This is feeling like something that should be dealt with using transducers.
(defn cmap
"Given a cell that contains a map of keys to cells, returns a new map with the same keys,
but new cells with the cell values transformed by the value-transform function."
[value-transform source-cell]
(cell (medley/map-vals
(fn [value-cell]
(cell (value-transform @value-cell)))
@source-cell)))
(defn project
"Given a cell containing a map of keys to cells, returns a new cell with the same value as the cell
with the given key."
[source-cell k]
(let [source-map @source-cell]
(cell (get source-map k))))
(defn accumulate
"Accumulates a map from a map in the source cell. On each change to the source-cell, its current
state is merged into the value for this cell."
[source-cell]
(let [prev-map (atom {})]
(cell
(swap! prev-map merge @source-cell))))
(defn delta
"Given a source cell containing a map of keys to cells, returns a new cell
containing a map of just the added keys and values (on any change to the source-cell)."
[source-cell]
(let [prior-keys (atom nil)]
(cell
(let [source-map @source-cell
source-keys (set (keys source-map))
added-keys (set/difference source-keys @prior-keys)]
;; Save the current set of keys for the next go-around.
(reset! prior-keys source-keys)
(select-keys source-map added-keys)))))
(defmacro ignoring-dependencies
"Creates a block where dependencies are not tracked, which is typically used when a container of cells is defined in terms
of another container of cells, and a transform applied to the cells. The new container should depend on just the old container and not
on the cells inside the old container.
For example, this is used by [[map-values]]."
[& body]
`(binding [*defining-cell* nil] ~@body))
(defn map-values
"Given a cell containing a map, returns a new map.
Each new value is the result of passing the old value through a transformation function.
Generally, the map values will themselves be cells.
The returned map cell will only have a dependency on the incoming map cell,
even when the provided map values are cells and the transform function dereferences the cells."
[value-xform map-cell]
(cell
(medley/map-vals
;; This is used to prevent the returned map cell from depending on each transformed cell.
;; It should only depend on the incoming map cell.
(fn [v]
(ignoring-dependencies (value-xform v)))
@map-cell)))
(defn cfilter
"Creates a new cell from a source cell containing a map. The new cell
contains a subset of the keys from the source cell, based on the key filter."
[key-filter source-cell]
(cell
(medley/filter-keys key-filter @source-cell)))
(comment
(do
(require '[clojure.string :as str])
(use 'clojure.pprint)
(use 'clojure.repl)
(use 'criterium.core)
(def s (cell {:label "root name"} "<NAME>"))
(def u (cell {:label "upper-case"}
(println "recalc: u")
(str/upper-case @s)))
(def r (cell {:label "reversed"}
(println "recalc: r")
(apply str (reverse @u))))
(def c (cell {:label "combined"}
(println "recalc: c")
(str @r
"-"
@s)))
(on-change! u #(println "u changed to" %))
(on-change! c #(println "c changed to" %))
(on-change! r #(println "r changed to" %)))
(force! s "<NAME>")
(force! s "<NAME>")
(force! s "<NAME>")
) | true | (ns io.aviso.frappe
"A take on server-side functional/reactive programming, with an eye towards smart publishing."
(:require [io.aviso.toolchest.macros :refer [cond-let]]
[com.stuartsierra.dependency :as dep]
[clojure.pprint :as pp]
[medley.core :as medley]
[clojure.set :as set]
[clojure.tools.logging :as l]
[clojure.string :as str])
(:import [clojure.lang IDeref]
[java.io Writer]
[java.util.concurrent.atomic AtomicInteger]))
(def ^:dynamic ^:no-doc *defining-cell*
"Identifies the cell that is currently being defined (and executed) to establish dependencies."
nil)
(def ^:no-doc empty-reaction
{:dirty-cells #{}
:pending-recalcs #{}
:pending-callbacks []})
(def ^:dynamic ^:no-doc *reaction*
"A atom that tracks information about the current reactive transaction."
nil)
(defprotocol Cell
"Defines the behavior of a Cell, which is a value computed from other Cells. These are largely internal
and should not be directly invoked by user code."
(on-change! [this callback]
"Adds a callback to the cell; the callback is only invoked when the value for the cell changes.
The callback is a function of a single argument: the new value for the cell.
The callback is also invoked when it is first added to the Cell.
The order in which callbacks are invoked (when changes do occur) is not specified.
Returns the cell.")
(recalc! [this]
"Forces the cell to recalculate its value, when a dependent cell changes. This will
in turn invoke [[force!]], which can then inform other cells and listeners.")
(force! [this new-value]
"Forces a change to a cell, which should only occur for edges (cells with constant values
and no dependencies).
The current value of the cell will change, and listeners and dependent cells will be notified.
Returns the cell.")
(add-dependant! [this other]
"Adds another cell as a dependant of the this cell. When this cell's value changes,
each dependant is notified to recompute its value.
Returns this cell.")
(dependants [this]
"Returns the dependants of this cell; cells whose value depends on this cell."))
(defn- add-if-not-pending-recalc [reaction cell]
(if (-> reaction :pending-recalcs (contains? cell))
reaction
(update reaction :dirty-cells conj cell)))
(defn- add-dirty-cell!
[cell]
(swap! *reaction* add-if-not-pending-recalc cell))
(defn- add-callback!
[callback cell-value]
(swap! *reaction* update :pending-callbacks conj [callback cell-value]))
(defn ^:no-doc finish-reaction!
[]
(loop [i 0]
(cond-let
(= 10 i)
(throw (ex-info "Reaction did not settle after 10 cycles."
{:reaction @*reaction*}))
[{:keys [dirty-cells pending-callbacks]} @*reaction*]
(and (empty? dirty-cells)
(empty? pending-callbacks))
nil
:else
(do
;; This is an optimization designed to minimize unnecessary (or transitional) recalculations of a cell.
;; If cell A depends on cell B and cell C, then order counts. You want cells B and C to recalc before A.
;; We use dependency ordering here; we identify that A is a dependant of B (that is, A depends on B)
;; which ensures that A will recalc after B. Same for C. We cull out edges
(let [dependency-pairs (for [cell dirty-cells
dependant (dependants cell)
:when (dirty-cells dependant)]
[cell dependant])
graph (reduce (fn [g [dependency cell]] (dep/depend g cell dependency))
(dep/graph)
dependency-pairs)
comparator (dep/topo-comparator graph)
;; Order dependants before dependencies, with everything else in arbitrary order at
;; the end.
recalc-order (sort comparator dirty-cells)]
;; Any cell in the current iteration that gets marked dirty will be ignored and not
;; added to the next iteration.
(reset! *reaction* (assoc empty-reaction :pending-recalcs dirty-cells))
(doseq [cell recalc-order]
(recalc! cell)))
(doseq [[callback value] pending-callbacks]
(callback value))
;; Those cells & callbacks may have changed other things resulting in
;; further dirty cells & callbacks.
(recur (inc i))))))
(defmacro reaction
"A reaction is a reactive transaction; it is useful when invoking [[force!]] on several
cells to handle the notifications as a single unit, which reduces the number of iterations necessary
to propogate changes through the graph, and helps reduce the chances of an redundant recalc."
[& body]
`(binding [*reaction* (atom empty-reaction)]
(let [result# (do ~@body)]
(finish-reaction!)
result#)))
(defrecord CellData [dependants change-listeners current-value])
(defrecord ^:no-doc CellImpl [id f label cell-data]
Cell
(on-change! [this callback]
(swap! cell-data update :change-listeners conj callback)
(callback @this)
this)
(add-dependant! [this other]
(swap! cell-data update :dependants conj other)
this)
(dependants [_] (:dependants @cell-data))
(recalc! [this]
(l/debugf "Forced recalculation of %s." (pr-str this))
(force! this (f)))
(force! [this new-value]
(cond
;; In many cases, the new computed value is the same as the prior value so
;; there's no need to go further.
(= (:current-value @cell-data) new-value)
nil
;; Create, as needed, a reactive transaction.
(nil? *reaction*)
(reaction
(force! this new-value))
:else
(let [{:keys [change-listeners dependants]} (swap! cell-data assoc :current-value new-value)]
(if-not (= *defining-cell* this)
(l/debugf "%s has changed, affecting %s."
(pr-str this)
(if (empty? dependants)
"no other cells"
(->> dependants
(map pr-str)
(str/join ", ")))))
;; These behaviors are deferred to help avoid redundant work.
(doseq [listener change-listeners]
(add-callback! listener new-value))
(doseq [cell dependants]
(add-dirty-cell! cell))))
this)
IDeref
(deref [this]
(when *defining-cell*
;; This cell was dereferenced while defining another cell. That means
;; the cell being defined is a dependant of this cell, and should recalc
;; when this cell changes.
(add-dependant! this *defining-cell*))
(:current-value @cell-data)))
(defmethod print-method CellImpl [cell ^Writer w]
(let [{:keys [id label]} cell]
(.write w (str "Cell[" id
(if label
(str " - " label))
"]"))))
(defmethod pp/simple-dispatch CellImpl
[cell]
(let [cell-data (-> cell :cell-data deref)]
(pp/simple-dispatch
(-> cell-data
(select-keys [:current-value :change-listeners])
(merge (select-keys cell [:id :label]))
(assoc :dependants (map :id (:dependants cell-data)))))))
(defonce ^:private next-cell-id (AtomicInteger. 0))
(defn cell*
"Creates a new cell around a function of no arguments that computes its value.
The function is almost always a closure that can reference other cells.
The options map currently supports a single key, :label, a string used
when printing the cell.
A cell may be dereferenced (use the @ reader macro, or deref special form)."
[options f]
(let [cell (->CellImpl (.incrementAndGet next-cell-id)
f
(:label options)
(atom (->CellData #{} [] nil)))]
;; This forces an evaluation of the cell, which will trigger any dependencies, letting
;; us build up the graph.
(binding [*defining-cell* cell]
(force! cell (f)))
cell))
(defmacro cell
"Creates a cell, wrapping the body up as the necessary function used by [[cell*]].
If there are two or more forms in the body and the first form is a map, then the first
form will be used as the options for the new cell.
The only current option is :label, a string used when printing the cell."
[& body]
(if (and (< 1 (count body))
(map? (first body)))
(let [[options & more-body] body]
`(cell* ~options (fn [] ~@more-body)))
`(cell* nil (fn [] ~@body))))
;;; This is feeling like something that should be dealt with using transducers.
(defn cmap
"Given a cell that contains a map of keys to cells, returns a new map with the same keys,
but new cells with the cell values transformed by the value-transform function."
[value-transform source-cell]
(cell (medley/map-vals
(fn [value-cell]
(cell (value-transform @value-cell)))
@source-cell)))
(defn project
"Given a cell containing a map of keys to cells, returns a new cell with the same value as the cell
with the given key."
[source-cell k]
(let [source-map @source-cell]
(cell (get source-map k))))
(defn accumulate
"Accumulates a map from a map in the source cell. On each change to the source-cell, its current
state is merged into the value for this cell."
[source-cell]
(let [prev-map (atom {})]
(cell
(swap! prev-map merge @source-cell))))
(defn delta
"Given a source cell containing a map of keys to cells, returns a new cell
containing a map of just the added keys and values (on any change to the source-cell)."
[source-cell]
(let [prior-keys (atom nil)]
(cell
(let [source-map @source-cell
source-keys (set (keys source-map))
added-keys (set/difference source-keys @prior-keys)]
;; Save the current set of keys for the next go-around.
(reset! prior-keys source-keys)
(select-keys source-map added-keys)))))
(defmacro ignoring-dependencies
"Creates a block where dependencies are not tracked, which is typically used when a container of cells is defined in terms
of another container of cells, and a transform applied to the cells. The new container should depend on just the old container and not
on the cells inside the old container.
For example, this is used by [[map-values]]."
[& body]
`(binding [*defining-cell* nil] ~@body))
(defn map-values
"Given a cell containing a map, returns a new map.
Each new value is the result of passing the old value through a transformation function.
Generally, the map values will themselves be cells.
The returned map cell will only have a dependency on the incoming map cell,
even when the provided map values are cells and the transform function dereferences the cells."
[value-xform map-cell]
(cell
(medley/map-vals
;; This is used to prevent the returned map cell from depending on each transformed cell.
;; It should only depend on the incoming map cell.
(fn [v]
(ignoring-dependencies (value-xform v)))
@map-cell)))
(defn cfilter
"Creates a new cell from a source cell containing a map. The new cell
contains a subset of the keys from the source cell, based on the key filter."
[key-filter source-cell]
(cell
(medley/filter-keys key-filter @source-cell)))
(comment
(do
(require '[clojure.string :as str])
(use 'clojure.pprint)
(use 'clojure.repl)
(use 'criterium.core)
(def s (cell {:label "root name"} "PI:NAME:<NAME>END_PI"))
(def u (cell {:label "upper-case"}
(println "recalc: u")
(str/upper-case @s)))
(def r (cell {:label "reversed"}
(println "recalc: r")
(apply str (reverse @u))))
(def c (cell {:label "combined"}
(println "recalc: c")
(str @r
"-"
@s)))
(on-change! u #(println "u changed to" %))
(on-change! c #(println "c changed to" %))
(on-change! r #(println "r changed to" %)))
(force! s "PI:NAME:<NAME>END_PI")
(force! s "PI:NAME:<NAME>END_PI")
(force! s "PI:NAME:<NAME>END_PI")
) |
[
{
"context": "on to retrieve values\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :re",
"end": 558,
"score": 0.9996790885925293,
"start": 552,
"tag": "NAME",
"value": "Batman"
},
{
"context": "values\n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n ",
"end": 578,
"score": 0.9997729063034058,
"start": 567,
"tag": "NAME",
"value": "Bruce Wayne"
},
{
"context": "{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"",
"end": 603,
"score": 0.9949324727058411,
"start": 593,
"tag": "NAME",
"value": "Spider-Man"
},
{
"context": "eal \"Bruce Wayne\"}\n {:alias \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias",
"end": 624,
"score": 0.9996800422668457,
"start": 612,
"tag": "NAME",
"value": "Peter Parker"
},
{
"context": "as \"Spider-Man\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :rea",
"end": 644,
"score": 0.9955881834030151,
"start": 639,
"tag": "NAME",
"value": "Santa"
},
{
"context": "\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :real \"Your dad\"}])\n\n;; Use reduce to transform ",
"end": 688,
"score": 0.9943515062332153,
"start": 676,
"tag": "NAME",
"value": "Easter Bunny"
},
{
"context": "makes-blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pulse? tru",
"end": 1542,
"score": 0.963870108127594,
"start": 1532,
"tag": "NAME",
"value": "McFishwich"
},
{
"context": "makes-blood-puns? false, :has-pulse? true :name \"McMackson\"}\n 2 {:makes-blood-puns? true, :has-pulse? fal",
"end": 1611,
"score": 0.9959973692893982,
"start": 1602,
"tag": "NAME",
"value": "McMackson"
},
{
"context": "makes-blood-puns? true, :has-pulse? false :name \"Damon Salvatore\"}\n 3 {:makes-blood-puns? true, :has-pulse? tru",
"end": 1686,
"score": 0.9996736645698547,
"start": 1671,
"tag": "NAME",
"value": "Damon Salvatore"
},
{
"context": "makes-blood-puns? true, :has-pulse? true :name \"Mickey Mouse\"}})\n\n(defn vampire-related-details\n [social-secu",
"end": 1758,
"score": 0.9994390606880188,
"start": 1746,
"tag": "NAME",
"value": "Mickey Mouse"
},
{
"context": "e 0 1000000))))\n\n(concat (take 8 (repeat \"na\")) [\"Batman!\"])\n\n(take 3 (repeatedly (fn [] (rand-int 10))))\n\n",
"end": 2286,
"score": 0.9368008971214294,
"start": 2280,
"tag": "NAME",
"value": "Batman"
}
] | chapter4/src/chapter4/core.clj | thorsilver/Clojure-Learning | 0 | (ns chapter4.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(defn titleize
[topic]
(str topic " for the Brave and True"))
(def human-consumption [8.1 7.3 6.6 5.0])
(def critter-consumption [0.0 0.2 0.3 1.1])
(defn unify-diet-data
[human critter]
{:human human :critter critter})
(def sum #(reduce + %))
(def avg #(/ (sum %) (count %)))
(defn stats
[numbers]
(map #(% numbers) [sum count avg]))
;; Use map keyword as function to retrieve values
(def identities
[{:alias "Batman" :real "Bruce Wayne"}
{:alias "Spider-Man" :real "Peter Parker"}
{:alias "Santa" :real "Your mom"}
{:alias "Easter Bunny" :real "Your dad"}])
;; Use reduce to transform a map's values
(reduce (fn [new-map [key val]]
(assoc new-map key (inc val)))
{}
{:max 30 :min 10})
;; Use reduce to filter out keys from map based on values
(reduce (fn [new-map [key val]]
(if (> val 4)
(assoc new-map key val) new-map))
{}
{:human 4.1 :critter 3.9})
(def food-journal
[{:month 1 :day 1 :human 5.3 :critter 2.3}
{:month 1 :day 2 :human 5.1 :critter 2.0}
{:month 2 :day 1 :human 4.9 :critter 2.1}
{:month 2 :day 2 :human 5.0 :critter 2.5}
{:month 3 :day 1 :human 4.2 :critter 3.3}
{:month 3 :day 2 :human 4.0 :critter 3.8}
{:month 4 :day 1 :human 3.7 :critter 3.9}
{:month 4 :day 2 :human 3.7 :critter 3.6}])
(def vampire-database
{0 {:makes-blood-puns? false, :has-pulse? true :name "McFishwich"}
1 {:makes-blood-puns? false, :has-pulse? true :name "McMackson"}
2 {:makes-blood-puns? true, :has-pulse? false :name "Damon Salvatore"}
3 {:makes-blood-puns? true, :has-pulse? true :name "Mickey Mouse"}})
(defn vampire-related-details
[social-security-number]
(Thread/sleep 100)
(get vampire-database social-security-number))
(defn vampire?
[record]
(and (:makes-blood-puns? record)
(not (:has-pulse? record))
record))
(defn identify-vampire
[social-security-numbers]
(first (filter vampire? (map vampire-related-details
social-security-numbers))))
(time (def mapped-details (map vampire-related-details (range 0 1000000))))
(concat (take 8 (repeat "na")) ["Batman!"])
(take 3 (repeatedly (fn [] (rand-int 10))))
(defn even-numbers
([] (even-numbers 0))
([n] (cons n (lazy-seq (even-numbers (+ n 2))))))
;; Use into to add elements to a map
(into {:favourite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]])
;; Use into to add elements to a vector
(into ["cherry"] '("pine" "spruce"))
;;Comparing functionality of conj and into
;; conj takes rest parameter, into takes seq-able data structure
(conj [1] [0])
(into [1] [0])
(conj [1] 0)
(conj [0] 1 2 3 4)
(conj {:time "midnight"} [:place "ye olde cemetarium"])
(defn my-conj
[target & additions]
(into target additions))
(my-conj [0] 1 2 3)
;; Using apply
;; Apply explodes a seq-able data structure into a rest parameter
(max 0 1 2)
(max [0 1 2])
(apply max [0 1 2])
;; Using apply to define into in terms of conj
(defn my-into
[target additions]
(apply conj target additions))
(my-into [0] [1 2 3])
;; Partial takes a func and arguments returns a new func
(def add10 (partial + 10))
(add10 3)
(add10 5)
(def add-missing-elements
(partial conj ["water" "earth" "air"]))
(add-missing-elements "unobtainium" "adamantium")
(defn my-partial
[partialed-fn & args]
(fn [& more-args]
(apply partialed-fn (into args more-args))))
(def add20 (my-partial + 20))
(add20 3)
;; Use partial to specialise a logging function
(defn lousy-logger
[log-level message]
(condp = log-level
:warn (clojure.string/lower-case message)
:emergency (clojure.string/upper-case message)))
(def warn (partial lousy-logger :warn))
(warn "Red light ahead")
;; A function to find all humans
(defn identify-humans-test
[social-security-numbers]
(filter #(not (vampire? %))
(map vampire-related-details social-security-numbers)))
;; Using complement
(def not-vampire? (complement vampire?))
(defn identify-humans
[social-security-numbers]
(filter not-vampire?
(map vampire-related-details social-security-numbers)))
;; Implementing complement + example
(defn my-complement
[fun]
(fn [& args]
(not (apply fun args))))
(def my-pos? (complement neg?))
(my-pos? 1)
(my-pos? -1)
| 44481 | (ns chapter4.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(defn titleize
[topic]
(str topic " for the Brave and True"))
(def human-consumption [8.1 7.3 6.6 5.0])
(def critter-consumption [0.0 0.2 0.3 1.1])
(defn unify-diet-data
[human critter]
{:human human :critter critter})
(def sum #(reduce + %))
(def avg #(/ (sum %) (count %)))
(defn stats
[numbers]
(map #(% numbers) [sum count avg]))
;; Use map keyword as function to retrieve values
(def identities
[{:alias "<NAME>" :real "<NAME>"}
{:alias "<NAME>" :real "<NAME>"}
{:alias "<NAME>" :real "Your mom"}
{:alias "<NAME>" :real "Your dad"}])
;; Use reduce to transform a map's values
(reduce (fn [new-map [key val]]
(assoc new-map key (inc val)))
{}
{:max 30 :min 10})
;; Use reduce to filter out keys from map based on values
(reduce (fn [new-map [key val]]
(if (> val 4)
(assoc new-map key val) new-map))
{}
{:human 4.1 :critter 3.9})
(def food-journal
[{:month 1 :day 1 :human 5.3 :critter 2.3}
{:month 1 :day 2 :human 5.1 :critter 2.0}
{:month 2 :day 1 :human 4.9 :critter 2.1}
{:month 2 :day 2 :human 5.0 :critter 2.5}
{:month 3 :day 1 :human 4.2 :critter 3.3}
{:month 3 :day 2 :human 4.0 :critter 3.8}
{:month 4 :day 1 :human 3.7 :critter 3.9}
{:month 4 :day 2 :human 3.7 :critter 3.6}])
(def vampire-database
{0 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>"}
1 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>"}
2 {:makes-blood-puns? true, :has-pulse? false :name "<NAME>"}
3 {:makes-blood-puns? true, :has-pulse? true :name "<NAME>"}})
(defn vampire-related-details
[social-security-number]
(Thread/sleep 100)
(get vampire-database social-security-number))
(defn vampire?
[record]
(and (:makes-blood-puns? record)
(not (:has-pulse? record))
record))
(defn identify-vampire
[social-security-numbers]
(first (filter vampire? (map vampire-related-details
social-security-numbers))))
(time (def mapped-details (map vampire-related-details (range 0 1000000))))
(concat (take 8 (repeat "na")) ["<NAME>!"])
(take 3 (repeatedly (fn [] (rand-int 10))))
(defn even-numbers
([] (even-numbers 0))
([n] (cons n (lazy-seq (even-numbers (+ n 2))))))
;; Use into to add elements to a map
(into {:favourite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]])
;; Use into to add elements to a vector
(into ["cherry"] '("pine" "spruce"))
;;Comparing functionality of conj and into
;; conj takes rest parameter, into takes seq-able data structure
(conj [1] [0])
(into [1] [0])
(conj [1] 0)
(conj [0] 1 2 3 4)
(conj {:time "midnight"} [:place "ye olde cemetarium"])
(defn my-conj
[target & additions]
(into target additions))
(my-conj [0] 1 2 3)
;; Using apply
;; Apply explodes a seq-able data structure into a rest parameter
(max 0 1 2)
(max [0 1 2])
(apply max [0 1 2])
;; Using apply to define into in terms of conj
(defn my-into
[target additions]
(apply conj target additions))
(my-into [0] [1 2 3])
;; Partial takes a func and arguments returns a new func
(def add10 (partial + 10))
(add10 3)
(add10 5)
(def add-missing-elements
(partial conj ["water" "earth" "air"]))
(add-missing-elements "unobtainium" "adamantium")
(defn my-partial
[partialed-fn & args]
(fn [& more-args]
(apply partialed-fn (into args more-args))))
(def add20 (my-partial + 20))
(add20 3)
;; Use partial to specialise a logging function
(defn lousy-logger
[log-level message]
(condp = log-level
:warn (clojure.string/lower-case message)
:emergency (clojure.string/upper-case message)))
(def warn (partial lousy-logger :warn))
(warn "Red light ahead")
;; A function to find all humans
(defn identify-humans-test
[social-security-numbers]
(filter #(not (vampire? %))
(map vampire-related-details social-security-numbers)))
;; Using complement
(def not-vampire? (complement vampire?))
(defn identify-humans
[social-security-numbers]
(filter not-vampire?
(map vampire-related-details social-security-numbers)))
;; Implementing complement + example
(defn my-complement
[fun]
(fn [& args]
(not (apply fun args))))
(def my-pos? (complement neg?))
(my-pos? 1)
(my-pos? -1)
| true | (ns chapter4.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
(defn titleize
[topic]
(str topic " for the Brave and True"))
(def human-consumption [8.1 7.3 6.6 5.0])
(def critter-consumption [0.0 0.2 0.3 1.1])
(defn unify-diet-data
[human critter]
{:human human :critter critter})
(def sum #(reduce + %))
(def avg #(/ (sum %) (count %)))
(defn stats
[numbers]
(map #(% numbers) [sum count avg]))
;; Use map keyword as function to retrieve values
(def identities
[{:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"}
{:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"}
{:alias "PI:NAME:<NAME>END_PI" :real "Your mom"}
{:alias "PI:NAME:<NAME>END_PI" :real "Your dad"}])
;; Use reduce to transform a map's values
(reduce (fn [new-map [key val]]
(assoc new-map key (inc val)))
{}
{:max 30 :min 10})
;; Use reduce to filter out keys from map based on values
(reduce (fn [new-map [key val]]
(if (> val 4)
(assoc new-map key val) new-map))
{}
{:human 4.1 :critter 3.9})
(def food-journal
[{:month 1 :day 1 :human 5.3 :critter 2.3}
{:month 1 :day 2 :human 5.1 :critter 2.0}
{:month 2 :day 1 :human 4.9 :critter 2.1}
{:month 2 :day 2 :human 5.0 :critter 2.5}
{:month 3 :day 1 :human 4.2 :critter 3.3}
{:month 3 :day 2 :human 4.0 :critter 3.8}
{:month 4 :day 1 :human 3.7 :critter 3.9}
{:month 4 :day 2 :human 3.7 :critter 3.6}])
(def vampire-database
{0 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"}
1 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"}
2 {:makes-blood-puns? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"}
3 {:makes-blood-puns? true, :has-pulse? true :name "PI:NAME:<NAME>END_PI"}})
(defn vampire-related-details
[social-security-number]
(Thread/sleep 100)
(get vampire-database social-security-number))
(defn vampire?
[record]
(and (:makes-blood-puns? record)
(not (:has-pulse? record))
record))
(defn identify-vampire
[social-security-numbers]
(first (filter vampire? (map vampire-related-details
social-security-numbers))))
(time (def mapped-details (map vampire-related-details (range 0 1000000))))
(concat (take 8 (repeat "na")) ["PI:NAME:<NAME>END_PI!"])
(take 3 (repeatedly (fn [] (rand-int 10))))
(defn even-numbers
([] (even-numbers 0))
([n] (cons n (lazy-seq (even-numbers (+ n 2))))))
;; Use into to add elements to a map
(into {:favourite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]])
;; Use into to add elements to a vector
(into ["cherry"] '("pine" "spruce"))
;;Comparing functionality of conj and into
;; conj takes rest parameter, into takes seq-able data structure
(conj [1] [0])
(into [1] [0])
(conj [1] 0)
(conj [0] 1 2 3 4)
(conj {:time "midnight"} [:place "ye olde cemetarium"])
(defn my-conj
[target & additions]
(into target additions))
(my-conj [0] 1 2 3)
;; Using apply
;; Apply explodes a seq-able data structure into a rest parameter
(max 0 1 2)
(max [0 1 2])
(apply max [0 1 2])
;; Using apply to define into in terms of conj
(defn my-into
[target additions]
(apply conj target additions))
(my-into [0] [1 2 3])
;; Partial takes a func and arguments returns a new func
(def add10 (partial + 10))
(add10 3)
(add10 5)
(def add-missing-elements
(partial conj ["water" "earth" "air"]))
(add-missing-elements "unobtainium" "adamantium")
(defn my-partial
[partialed-fn & args]
(fn [& more-args]
(apply partialed-fn (into args more-args))))
(def add20 (my-partial + 20))
(add20 3)
;; Use partial to specialise a logging function
(defn lousy-logger
[log-level message]
(condp = log-level
:warn (clojure.string/lower-case message)
:emergency (clojure.string/upper-case message)))
(def warn (partial lousy-logger :warn))
(warn "Red light ahead")
;; A function to find all humans
(defn identify-humans-test
[social-security-numbers]
(filter #(not (vampire? %))
(map vampire-related-details social-security-numbers)))
;; Using complement
(def not-vampire? (complement vampire?))
(defn identify-humans
[social-security-numbers]
(filter not-vampire?
(map vampire-related-details social-security-numbers)))
;; Implementing complement + example
(defn my-complement
[fun]
(fn [& args]
(not (apply fun args))))
(def my-pos? (complement neg?))
(my-pos? 1)
(my-pos? -1)
|
[
{
"context": "ls]\n [cat_file :as cf]))\n\n(def author \"Linus Torvalds <torvalds@transmeta.com> 1581997446 -0500\")\n(def ",
"end": 134,
"score": 0.9998809099197388,
"start": 120,
"tag": "NAME",
"value": "Linus Torvalds"
},
{
"context": "[cat_file :as cf]))\n\n(def author \"Linus Torvalds <torvalds@transmeta.com> 1581997446 -0500\")\n(def committer author)\n\n(defn",
"end": 158,
"score": 0.9999341368675232,
"start": 136,
"tag": "EMAIL",
"value": "torvalds@transmeta.com"
}
] | assignment3/src/commit_tree.clj | hybrezz54/comp590-145 | 0 | (ns commit_tree
(:require [clojure.java.io :as io])
(:require [utils]
[cat_file :as cf]))
(def author "Linus Torvalds <torvalds@transmeta.com> 1581997446 -0500")
(def committer author)
(defn commit-object
"Construct a new commit object"
[tree-addr author-str committer-str msg parent-str]
(let [commit-format (str "tree %s\n"
"%s"
"author %s\n"
"committer %s\n"
"\n"
"%s\n")
commit-str (format commit-format
tree-addr
parent-str
author-str
committer-str
msg)]
(format "commit %d\000%s"
(count commit-str)
commit-str)))
(defn create-commit
"Create and store a commit object in the database"
[dir db commit]
(let [commit-bytes (-> commit .getBytes utils/sha-bytes)
addr (-> commit-bytes utils/to-hex-string)]
(utils/create-object dir db addr commit)
addr))
(defn check-parents
"Check if valid parent commit addresses are given"
[dir db parents]
(loop [parents-seq (seq parents)]
(if parents-seq
(let [pair (first parents-seq)
flag (first pair)
addr (second pair)]
(if (= flag "-p")
(cond (not (.exists (io/file (utils/obj-path dir db addr)))) (str "Error: no commit object exists at address " addr ".")
(not= (cat_file/get-type dir db addr) "commit") (str "Error: an object exists at address " addr ", but it isn't a commit.")
:else (recur (next parents-seq)))
(str "Error: invalid command")))
nil)))
(defn main
"write a commit object based on the given tree"
[dir db n]
(let [[addr msg-flag msg & parents] n
addr-flag-pairs (partition 2 parents)
addrs (map second addr-flag-pairs)
db-path (str dir "/" db)]
(try
(cond (or (= addr "-h") (= addr "--help"))
(do (println "idiot commit-tree: write a commit object based on the given tree")
(println)
(println "Usage: idiot commit-tree <tree> -m \"message\" [(-p parent)...]")
(println)
(println "Arguments:")
(println " -h print this message")
(println " <tree> the address of the tree object to commit")
(println " -m \"<message>\" the commit message")
(println " -p <parent> the address of a parent commit"))
(not (.exists (io/file db-path))) (println "Error: could not find database. (Did you run `idiot init`?)")
(or (nil? addr) (= msg-flag addr)) (throw (Exception.))
(not (.exists (io/file (utils/obj-path dir db addr)))) (println "Error: no tree object exists at that address.")
(not= (cf/get-type dir db addr) "tree") (println "Error: an object exists at that address, but it isn't a tree.")
(not= msg-flag "-m") (println "Error: you must specify a message.")
(nil? msg) (println "Error: you must specify a message with the -m switch.")
(odd? (count parents)) (println "Error: you must specify a commit object with the -p switch.")
:else (if (not (nil? parents))
(let [results (check-parents dir db addr-flag-pairs)]
(if results
(println results)
(println (->> addrs
(map #(str "parent " % "\n"))
(reduce str)
(commit-object addr author committer msg)
(create-commit dir db)))))
(println (->> (commit-object addr author committer msg "")
(create-commit dir db)))))
(catch Exception e
e (println "Error: you must specify a tree address."))))) | 81685 | (ns commit_tree
(:require [clojure.java.io :as io])
(:require [utils]
[cat_file :as cf]))
(def author "<NAME> <<EMAIL>> 1581997446 -0500")
(def committer author)
(defn commit-object
"Construct a new commit object"
[tree-addr author-str committer-str msg parent-str]
(let [commit-format (str "tree %s\n"
"%s"
"author %s\n"
"committer %s\n"
"\n"
"%s\n")
commit-str (format commit-format
tree-addr
parent-str
author-str
committer-str
msg)]
(format "commit %d\000%s"
(count commit-str)
commit-str)))
(defn create-commit
"Create and store a commit object in the database"
[dir db commit]
(let [commit-bytes (-> commit .getBytes utils/sha-bytes)
addr (-> commit-bytes utils/to-hex-string)]
(utils/create-object dir db addr commit)
addr))
(defn check-parents
"Check if valid parent commit addresses are given"
[dir db parents]
(loop [parents-seq (seq parents)]
(if parents-seq
(let [pair (first parents-seq)
flag (first pair)
addr (second pair)]
(if (= flag "-p")
(cond (not (.exists (io/file (utils/obj-path dir db addr)))) (str "Error: no commit object exists at address " addr ".")
(not= (cat_file/get-type dir db addr) "commit") (str "Error: an object exists at address " addr ", but it isn't a commit.")
:else (recur (next parents-seq)))
(str "Error: invalid command")))
nil)))
(defn main
"write a commit object based on the given tree"
[dir db n]
(let [[addr msg-flag msg & parents] n
addr-flag-pairs (partition 2 parents)
addrs (map second addr-flag-pairs)
db-path (str dir "/" db)]
(try
(cond (or (= addr "-h") (= addr "--help"))
(do (println "idiot commit-tree: write a commit object based on the given tree")
(println)
(println "Usage: idiot commit-tree <tree> -m \"message\" [(-p parent)...]")
(println)
(println "Arguments:")
(println " -h print this message")
(println " <tree> the address of the tree object to commit")
(println " -m \"<message>\" the commit message")
(println " -p <parent> the address of a parent commit"))
(not (.exists (io/file db-path))) (println "Error: could not find database. (Did you run `idiot init`?)")
(or (nil? addr) (= msg-flag addr)) (throw (Exception.))
(not (.exists (io/file (utils/obj-path dir db addr)))) (println "Error: no tree object exists at that address.")
(not= (cf/get-type dir db addr) "tree") (println "Error: an object exists at that address, but it isn't a tree.")
(not= msg-flag "-m") (println "Error: you must specify a message.")
(nil? msg) (println "Error: you must specify a message with the -m switch.")
(odd? (count parents)) (println "Error: you must specify a commit object with the -p switch.")
:else (if (not (nil? parents))
(let [results (check-parents dir db addr-flag-pairs)]
(if results
(println results)
(println (->> addrs
(map #(str "parent " % "\n"))
(reduce str)
(commit-object addr author committer msg)
(create-commit dir db)))))
(println (->> (commit-object addr author committer msg "")
(create-commit dir db)))))
(catch Exception e
e (println "Error: you must specify a tree address."))))) | true | (ns commit_tree
(:require [clojure.java.io :as io])
(:require [utils]
[cat_file :as cf]))
(def author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> 1581997446 -0500")
(def committer author)
(defn commit-object
"Construct a new commit object"
[tree-addr author-str committer-str msg parent-str]
(let [commit-format (str "tree %s\n"
"%s"
"author %s\n"
"committer %s\n"
"\n"
"%s\n")
commit-str (format commit-format
tree-addr
parent-str
author-str
committer-str
msg)]
(format "commit %d\000%s"
(count commit-str)
commit-str)))
(defn create-commit
"Create and store a commit object in the database"
[dir db commit]
(let [commit-bytes (-> commit .getBytes utils/sha-bytes)
addr (-> commit-bytes utils/to-hex-string)]
(utils/create-object dir db addr commit)
addr))
(defn check-parents
"Check if valid parent commit addresses are given"
[dir db parents]
(loop [parents-seq (seq parents)]
(if parents-seq
(let [pair (first parents-seq)
flag (first pair)
addr (second pair)]
(if (= flag "-p")
(cond (not (.exists (io/file (utils/obj-path dir db addr)))) (str "Error: no commit object exists at address " addr ".")
(not= (cat_file/get-type dir db addr) "commit") (str "Error: an object exists at address " addr ", but it isn't a commit.")
:else (recur (next parents-seq)))
(str "Error: invalid command")))
nil)))
(defn main
"write a commit object based on the given tree"
[dir db n]
(let [[addr msg-flag msg & parents] n
addr-flag-pairs (partition 2 parents)
addrs (map second addr-flag-pairs)
db-path (str dir "/" db)]
(try
(cond (or (= addr "-h") (= addr "--help"))
(do (println "idiot commit-tree: write a commit object based on the given tree")
(println)
(println "Usage: idiot commit-tree <tree> -m \"message\" [(-p parent)...]")
(println)
(println "Arguments:")
(println " -h print this message")
(println " <tree> the address of the tree object to commit")
(println " -m \"<message>\" the commit message")
(println " -p <parent> the address of a parent commit"))
(not (.exists (io/file db-path))) (println "Error: could not find database. (Did you run `idiot init`?)")
(or (nil? addr) (= msg-flag addr)) (throw (Exception.))
(not (.exists (io/file (utils/obj-path dir db addr)))) (println "Error: no tree object exists at that address.")
(not= (cf/get-type dir db addr) "tree") (println "Error: an object exists at that address, but it isn't a tree.")
(not= msg-flag "-m") (println "Error: you must specify a message.")
(nil? msg) (println "Error: you must specify a message with the -m switch.")
(odd? (count parents)) (println "Error: you must specify a commit object with the -p switch.")
:else (if (not (nil? parents))
(let [results (check-parents dir db addr-flag-pairs)]
(if results
(println results)
(println (->> addrs
(map #(str "parent " % "\n"))
(reduce str)
(commit-object addr author committer msg)
(create-commit dir db)))))
(println (->> (commit-object addr author committer msg "")
(create-commit dir db)))))
(catch Exception e
e (println "Error: you must specify a tree address."))))) |
[
{
"context": "/accounts\"\n :headers {\"CB-ACCESS-KEY\" \"123123\", \n \"CB-ACCESS-SIGN\" \"aSRkZm",
"end": 1619,
"score": 0.9953979849815369,
"start": 1613,
"tag": "KEY",
"value": "123123"
},
{
"context": "23,\n \"CB-ACCESS-PASSPHRASE\" \"passphrase123\"}}\n (sign-request {:url \"https://api.gd",
"end": 1818,
"score": 0.9992355108261108,
"start": 1805,
"tag": "PASSWORD",
"value": "passphrase123"
},
{
"context": "s://api.gdax.com\"\n :key \"123123\"\n :secret \"aGVsbG8=\"\n ",
"end": 1914,
"score": 0.9732926487922668,
"start": 1908,
"tag": "KEY",
"value": "123123"
},
{
"context": " :key \"123123\"\n :secret \"aGVsbG8=\"\n :passphrase \"passphra",
"end": 1958,
"score": 0.9054668545722961,
"start": 1951,
"tag": "KEY",
"value": "aGVsbG8"
},
{
"context": "\"aGVsbG8=\"\n :passphrase \"passphrase123\"}\n {:method \"GET\"\n ",
"end": 2013,
"score": 0.9992332458496094,
"start": 2000,
"tag": "PASSWORD",
"value": "passphrase123"
},
{
"context": "o \"world\"}\n :headers {\"CB-ACCESS-KEY\" \"123123\",\n \"CB-ACCESS-SIGN\" \"feI9Pm5",
"end": 2306,
"score": 0.996089518070221,
"start": 2300,
"tag": "KEY",
"value": "123123"
},
{
"context": "123\n \"CB-ACCESS-PASSPHRASE\" \"passphrase123\"}}\n (sign-request {:url \"https://api.gd",
"end": 2503,
"score": 0.9991579055786133,
"start": 2490,
"tag": "PASSWORD",
"value": "passphrase123"
},
{
"context": "s://api.gdax.com\"\n :key \"123123\"\n :secret \"aGVsbG8=\"\n ",
"end": 2599,
"score": 0.8133208751678467,
"start": 2593,
"tag": "KEY",
"value": "123123"
},
{
"context": " :key \"123123\"\n :secret \"aGVsbG8=\"\n :passphrase \"passphra",
"end": 2643,
"score": 0.8759685754776001,
"start": 2636,
"tag": "KEY",
"value": "aGVsbG8"
},
{
"context": "\"aGVsbG8=\"\n :passphrase \"passphrase123\"}\n {:method \"POST\"\n ",
"end": 2698,
"score": 0.9992902874946594,
"start": 2685,
"tag": "PASSWORD",
"value": "passphrase123"
}
] | test/coinbase_pro_clj/authentication_test.clj | bpringe/coinbase-pro-clojure | 21 | (ns coinbase-pro-clj.authentication-test
(:require [clojure.test :refer :all]
[coinbase-pro-clj.authentication :refer :all]))
(deftest create-prehash-string-test
(is (= "123GET/time"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "GET" :url "https://api.gdax.com/time"}))
"without request body")
(is (= "123POST/orders{:hello \"world\"}"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body"))
(deftest create-http-signature-test
(is (= "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body")
(is (= "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "GET" :url "https://api.gdax.com/accounts"}))
"without request body"))
(deftest create-websocket-signature-test
(is (= "C1DZ6pZxgL7VxLvMCCs+8XRCC+lZjYHa1NsATV8kbLc="
(#'coinbase-pro-clj.authentication/create-websocket-signature
"aGVsbG8="
123))))
(deftest sign-request-test
(with-redefs [coinbase-pro-clj.utilities/get-timestamp (constantly 123)]
(is (= {:method "GET"
:url "https://api.gdax.com/accounts"
:headers {"CB-ACCESS-KEY" "123123",
"CB-ACCESS-SIGN" "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro=",
"CB-ACCESS-TIMESTAMP" 123,
"CB-ACCESS-PASSPHRASE" "passphrase123"}}
(sign-request {:url "https://api.gdax.com"
:key "123123"
:secret "aGVsbG8="
:passphrase "passphrase123"}
{:method "GET"
:url "https://api.gdax.com/accounts"}))
"without request body")
(is (= {:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}
:headers {"CB-ACCESS-KEY" "123123",
"CB-ACCESS-SIGN" "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4=",
"CB-ACCESS-TIMESTAMP" 123
"CB-ACCESS-PASSPHRASE" "passphrase123"}}
(sign-request {:url "https://api.gdax.com"
:key "123123"
:secret "aGVsbG8="
:passphrase "passphrase123"}
{:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}}))
"with request body")))
;; Write tests for sign-message if decide to keep implementation tests
;; Currently switching to only test surface level api, which inherently tests implementation
;; This makes changing implementation much easier while still making sure no
;; breaking changes occur
| 77242 | (ns coinbase-pro-clj.authentication-test
(:require [clojure.test :refer :all]
[coinbase-pro-clj.authentication :refer :all]))
(deftest create-prehash-string-test
(is (= "123GET/time"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "GET" :url "https://api.gdax.com/time"}))
"without request body")
(is (= "123POST/orders{:hello \"world\"}"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body"))
(deftest create-http-signature-test
(is (= "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body")
(is (= "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "GET" :url "https://api.gdax.com/accounts"}))
"without request body"))
(deftest create-websocket-signature-test
(is (= "C1DZ6pZxgL7VxLvMCCs+8XRCC+lZjYHa1NsATV8kbLc="
(#'coinbase-pro-clj.authentication/create-websocket-signature
"aGVsbG8="
123))))
(deftest sign-request-test
(with-redefs [coinbase-pro-clj.utilities/get-timestamp (constantly 123)]
(is (= {:method "GET"
:url "https://api.gdax.com/accounts"
:headers {"CB-ACCESS-KEY" "<KEY>",
"CB-ACCESS-SIGN" "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro=",
"CB-ACCESS-TIMESTAMP" 123,
"CB-ACCESS-PASSPHRASE" "<PASSWORD>"}}
(sign-request {:url "https://api.gdax.com"
:key "<KEY>"
:secret "<KEY>="
:passphrase "<PASSWORD>"}
{:method "GET"
:url "https://api.gdax.com/accounts"}))
"without request body")
(is (= {:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}
:headers {"CB-ACCESS-KEY" "<KEY>",
"CB-ACCESS-SIGN" "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4=",
"CB-ACCESS-TIMESTAMP" 123
"CB-ACCESS-PASSPHRASE" "<PASSWORD>"}}
(sign-request {:url "https://api.gdax.com"
:key "<KEY>"
:secret "<KEY>="
:passphrase "<PASSWORD>"}
{:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}}))
"with request body")))
;; Write tests for sign-message if decide to keep implementation tests
;; Currently switching to only test surface level api, which inherently tests implementation
;; This makes changing implementation much easier while still making sure no
;; breaking changes occur
| true | (ns coinbase-pro-clj.authentication-test
(:require [clojure.test :refer :all]
[coinbase-pro-clj.authentication :refer :all]))
(deftest create-prehash-string-test
(is (= "123GET/time"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "GET" :url "https://api.gdax.com/time"}))
"without request body")
(is (= "123POST/orders{:hello \"world\"}"
(#'coinbase-pro-clj.authentication/create-prehash-string
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body"))
(deftest create-http-signature-test
(is (= "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "POST" :url "https://api.gdax.com/orders" :body {:hello "world"}}))
"with request body")
(is (= "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro="
(#'coinbase-pro-clj.authentication/create-http-signature
"aGVsbG8="
123
{:method "GET" :url "https://api.gdax.com/accounts"}))
"without request body"))
(deftest create-websocket-signature-test
(is (= "C1DZ6pZxgL7VxLvMCCs+8XRCC+lZjYHa1NsATV8kbLc="
(#'coinbase-pro-clj.authentication/create-websocket-signature
"aGVsbG8="
123))))
(deftest sign-request-test
(with-redefs [coinbase-pro-clj.utilities/get-timestamp (constantly 123)]
(is (= {:method "GET"
:url "https://api.gdax.com/accounts"
:headers {"CB-ACCESS-KEY" "PI:KEY:<KEY>END_PI",
"CB-ACCESS-SIGN" "aSRkZmpa6LE+0TL3lShoAASVS0jSZIWKVQr42u5KKro=",
"CB-ACCESS-TIMESTAMP" 123,
"CB-ACCESS-PASSPHRASE" "PI:PASSWORD:<PASSWORD>END_PI"}}
(sign-request {:url "https://api.gdax.com"
:key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI="
:passphrase "PI:PASSWORD:<PASSWORD>END_PI"}
{:method "GET"
:url "https://api.gdax.com/accounts"}))
"without request body")
(is (= {:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}
:headers {"CB-ACCESS-KEY" "PI:KEY:<KEY>END_PI",
"CB-ACCESS-SIGN" "feI9Pm5uupzIiDq9p80pL1/z36vwBwIlVrSiXwa14k4=",
"CB-ACCESS-TIMESTAMP" 123
"CB-ACCESS-PASSPHRASE" "PI:PASSWORD:<PASSWORD>END_PI"}}
(sign-request {:url "https://api.gdax.com"
:key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI="
:passphrase "PI:PASSWORD:<PASSWORD>END_PI"}
{:method "POST"
:url "https://api.gdax.com/orders"
:body {:hello "world"}}))
"with request body")))
;; Write tests for sign-message if decide to keep implementation tests
;; Currently switching to only test surface level api, which inherently tests implementation
;; This makes changing implementation much easier while still making sure no
;; breaking changes occur
|
[
{
"context": "The Fibonacci Numbers as a lazy sequence. Credit: Christophe Grand as\n mention in 'Programming Clojure', pg. 137.\"\n",
"end": 1161,
"score": 0.9997809529304504,
"start": 1145,
"tag": "NAME",
"value": "Christophe Grand"
}
] | src/project_euler_solutions/core.clj | evanspa/Project-Euler-Solutions | 0 | (ns project-euler-solutions.core
(:require [clojure.math.numeric-tower :as math]))
(defmacro bench
"Times the execution of forms, discarding their output and returning
a long in nanoseconds."
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(- (System/nanoTime) start#))))
(defn partial-sum
"Returns the partial sum of a sequence. If start is not provided, 1 is used."
([start num-terms end]
(/ (* num-terms (+ start end)) 2))
([num-terms end]
(partial-sum 1 num-terms end)))
(defn nth-partial-sum
"Returns the nth partial sum of a sequence. If start is not provided, 1 is
used. If multiple is not provided, 1 is used."
([start multiple nth]
(let [end (+ (* multiple nth) start)
num-terms (inc nth)]
(partial-sum start num-terms end)))
([start nth]
(nth-partial-sum start 1 nth))
([nth]
(nth-partial-sum 1 nth)))
(defn sum-multiples
"Returns the sum of the k multiples up-to and including n."
[k n]
(let [n (math/floor (/ n k))]
(* k (partial-sum 1 n n))))
(def fibonacci-numbers
"The Fibonacci Numbers as a lazy sequence. Credit: Christophe Grand as
mention in 'Programming Clojure', pg. 137."
(map first (iterate (fn [[a b]] [b (+' a b)]) [0 1])))
| 79652 | (ns project-euler-solutions.core
(:require [clojure.math.numeric-tower :as math]))
(defmacro bench
"Times the execution of forms, discarding their output and returning
a long in nanoseconds."
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(- (System/nanoTime) start#))))
(defn partial-sum
"Returns the partial sum of a sequence. If start is not provided, 1 is used."
([start num-terms end]
(/ (* num-terms (+ start end)) 2))
([num-terms end]
(partial-sum 1 num-terms end)))
(defn nth-partial-sum
"Returns the nth partial sum of a sequence. If start is not provided, 1 is
used. If multiple is not provided, 1 is used."
([start multiple nth]
(let [end (+ (* multiple nth) start)
num-terms (inc nth)]
(partial-sum start num-terms end)))
([start nth]
(nth-partial-sum start 1 nth))
([nth]
(nth-partial-sum 1 nth)))
(defn sum-multiples
"Returns the sum of the k multiples up-to and including n."
[k n]
(let [n (math/floor (/ n k))]
(* k (partial-sum 1 n n))))
(def fibonacci-numbers
"The Fibonacci Numbers as a lazy sequence. Credit: <NAME> as
mention in 'Programming Clojure', pg. 137."
(map first (iterate (fn [[a b]] [b (+' a b)]) [0 1])))
| true | (ns project-euler-solutions.core
(:require [clojure.math.numeric-tower :as math]))
(defmacro bench
"Times the execution of forms, discarding their output and returning
a long in nanoseconds."
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(- (System/nanoTime) start#))))
(defn partial-sum
"Returns the partial sum of a sequence. If start is not provided, 1 is used."
([start num-terms end]
(/ (* num-terms (+ start end)) 2))
([num-terms end]
(partial-sum 1 num-terms end)))
(defn nth-partial-sum
"Returns the nth partial sum of a sequence. If start is not provided, 1 is
used. If multiple is not provided, 1 is used."
([start multiple nth]
(let [end (+ (* multiple nth) start)
num-terms (inc nth)]
(partial-sum start num-terms end)))
([start nth]
(nth-partial-sum start 1 nth))
([nth]
(nth-partial-sum 1 nth)))
(defn sum-multiples
"Returns the sum of the k multiples up-to and including n."
[k n]
(let [n (math/floor (/ n k))]
(* k (partial-sum 1 n n))))
(def fibonacci-numbers
"The Fibonacci Numbers as a lazy sequence. Credit: PI:NAME:<NAME>END_PI as
mention in 'Programming Clojure', pg. 137."
(map first (iterate (fn [[a b]] [b (+' a b)]) [0 1])))
|
[
{
"context": "imaryFire>\n\t\t<Primary Device=\\\"068EC010\\\" Key=\\\"Joy_1\\\" />\n\t\t<Secondary Device=\\\"{NoDevice}\\\" Key=\\\"\\\" ",
"end": 644,
"score": 0.9098432064056396,
"start": 641,
"tag": "KEY",
"value": "y_1"
},
{
"context": "\n// PrimaryFire {:Key \\\"Joy_1\\\", :Device \\\"068EC010\\\"}\n\n// Unbound commands ---",
"end": 1534,
"score": 0.908339262008667,
"start": 1531,
"tag": "KEY",
"value": "y_1"
},
{
"context": "--\n// PrimaryFire {:Key \\\"Joy_1\\\", :Device \\\"068EC010\\\"}\n\n// Unbound commands ---",
"end": 2587,
"score": 0.9582330584526062,
"start": 2582,
"tag": "KEY",
"value": "Joy_1"
}
] | test/edcmcgen/main_tests.clj | imrekoszo/edcmcgen | 0 | (ns edcmcgen.main-tests
(:require [edcmcgen.main :refer [process]]
[clojure.test :refer :all])
(:import (java.io ByteArrayInputStream)))
(def binds-content
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<Root PresetName=\"Custom\">
<CamTranslateUp>
<Primary Device=\"Keyboard\" Key=\"Key_D\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateUp>
<CamTranslateDown>
<Primary Device=\"Keyboard\" Key=\"Key_M\">
<Modifier Device=\"Keyboard\" Key=\"Key_LeftShift\" />
</Primary>
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateDown>
<PrimaryFire>
<Primary Device=\"068EC010\" Key=\"Joy_1\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</PrimaryFire>
<BackwardKey>
<Primary Device=\"{NoDevice}\" Key=\"\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</BackwardKey>
<IncreaseEnginesPower>
<Primary Device=\"Keyboard\" Key=\"Key_2\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</IncreaseEnginesPower>
<ResetPowerDistribution>
<Primary Device=\"Keyboard\" Key=\"Key_4\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</ResetPowerDistribution>
</Root>")
(def simple-output
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"Joy_1\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(def static-content
"// Hidden commands
hShowFPS CTL f")
(def macros-content
"{:mPowerPresetEngines1 [:ResetPowerDistribution CHARDLY :IncreaseEnginesPower CHARDLY :IncreaseEnginesPower]}")
(def output-with-macros-and-static-content
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Macros ----------------------------------------------------------------------
mPowerPresetEngines1 4 CHARDLY 2 CHARDLY 2
// Static content --------------------------------------------------------------
// Hidden commands
hShowFPS CTL f
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"Joy_1\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(defn string-stream [s]
(ByteArrayInputStream. (.getBytes s)))
(defn do-process [m]
(with-out-str (process (update m :elite-bindings string-stream))))
(deftest can-process-bindings
(is (= simple-output
(do-process {:elite-bindings binds-content}))))
(deftest can-process-macros-and-static-content
(is (= output-with-macros-and-static-content
(do-process {:elite-bindings binds-content
:macro-definitions macros-content
:static-cmc static-content}))))
| 15146 | (ns edcmcgen.main-tests
(:require [edcmcgen.main :refer [process]]
[clojure.test :refer :all])
(:import (java.io ByteArrayInputStream)))
(def binds-content
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<Root PresetName=\"Custom\">
<CamTranslateUp>
<Primary Device=\"Keyboard\" Key=\"Key_D\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateUp>
<CamTranslateDown>
<Primary Device=\"Keyboard\" Key=\"Key_M\">
<Modifier Device=\"Keyboard\" Key=\"Key_LeftShift\" />
</Primary>
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateDown>
<PrimaryFire>
<Primary Device=\"068EC010\" Key=\"Jo<KEY>\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</PrimaryFire>
<BackwardKey>
<Primary Device=\"{NoDevice}\" Key=\"\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</BackwardKey>
<IncreaseEnginesPower>
<Primary Device=\"Keyboard\" Key=\"Key_2\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</IncreaseEnginesPower>
<ResetPowerDistribution>
<Primary Device=\"Keyboard\" Key=\"Key_4\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</ResetPowerDistribution>
</Root>")
(def simple-output
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"Jo<KEY>\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(def static-content
"// Hidden commands
hShowFPS CTL f")
(def macros-content
"{:mPowerPresetEngines1 [:ResetPowerDistribution CHARDLY :IncreaseEnginesPower CHARDLY :IncreaseEnginesPower]}")
(def output-with-macros-and-static-content
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Macros ----------------------------------------------------------------------
mPowerPresetEngines1 4 CHARDLY 2 CHARDLY 2
// Static content --------------------------------------------------------------
// Hidden commands
hShowFPS CTL f
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"<KEY>\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(defn string-stream [s]
(ByteArrayInputStream. (.getBytes s)))
(defn do-process [m]
(with-out-str (process (update m :elite-bindings string-stream))))
(deftest can-process-bindings
(is (= simple-output
(do-process {:elite-bindings binds-content}))))
(deftest can-process-macros-and-static-content
(is (= output-with-macros-and-static-content
(do-process {:elite-bindings binds-content
:macro-definitions macros-content
:static-cmc static-content}))))
| true | (ns edcmcgen.main-tests
(:require [edcmcgen.main :refer [process]]
[clojure.test :refer :all])
(:import (java.io ByteArrayInputStream)))
(def binds-content
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<Root PresetName=\"Custom\">
<CamTranslateUp>
<Primary Device=\"Keyboard\" Key=\"Key_D\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateUp>
<CamTranslateDown>
<Primary Device=\"Keyboard\" Key=\"Key_M\">
<Modifier Device=\"Keyboard\" Key=\"Key_LeftShift\" />
</Primary>
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</CamTranslateDown>
<PrimaryFire>
<Primary Device=\"068EC010\" Key=\"JoPI:KEY:<KEY>END_PI\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</PrimaryFire>
<BackwardKey>
<Primary Device=\"{NoDevice}\" Key=\"\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</BackwardKey>
<IncreaseEnginesPower>
<Primary Device=\"Keyboard\" Key=\"Key_2\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</IncreaseEnginesPower>
<ResetPowerDistribution>
<Primary Device=\"Keyboard\" Key=\"Key_4\" />
<Secondary Device=\"{NoDevice}\" Key=\"\" />
</ResetPowerDistribution>
</Root>")
(def simple-output
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"JoPI:KEY:<KEY>END_PI\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(def static-content
"// Hidden commands
hShowFPS CTL f")
(def macros-content
"{:mPowerPresetEngines1 [:ResetPowerDistribution CHARDLY :IncreaseEnginesPower CHARDLY :IncreaseEnginesPower]}")
(def output-with-macros-and-static-content
"// Commands bound to keys ------------------------------------------------------
CamTranslateDown LSHF m
CamTranslateUp d
IncreaseEnginesPower 2
ResetPowerDistribution 4
// Macros ----------------------------------------------------------------------
mPowerPresetEngines1 4 CHARDLY 2 CHARDLY 2
// Static content --------------------------------------------------------------
// Hidden commands
hShowFPS CTL f
// Commands bound to controller or mouse buttons -------------------------------
// PrimaryFire {:Key \"PI:KEY:<KEY>END_PI\", :Device \"068EC010\"}
// Unbound commands ------------------------------------------------------------
// BackwardKey
")
(defn string-stream [s]
(ByteArrayInputStream. (.getBytes s)))
(defn do-process [m]
(with-out-str (process (update m :elite-bindings string-stream))))
(deftest can-process-bindings
(is (= simple-output
(do-process {:elite-bindings binds-content}))))
(deftest can-process-macros-and-static-content
(is (= output-with-macros-and-static-content
(do-process {:elite-bindings binds-content
:macro-definitions macros-content
:static-cmc static-content}))))
|
[
{
"context": " test-modify-vals\n (let [m (u/modify-vals {:ip \"1.2.3.4\"\n :url \"http://1.2.3.4/u",
"end": 206,
"score": 0.9993993639945984,
"start": 199,
"tag": "IP_ADDRESS",
"value": "1.2.3.4"
},
{
"context": "tps://example.com\"}\n #{[#\"1.2.3.4\" \"4.3.2.1\"]\n [#\"example",
"end": 351,
"score": 0.9996418356895447,
"start": 344,
"tag": "IP_ADDRESS",
"value": "1.2.3.4"
},
{
"context": "ple.com\"}\n #{[#\"1.2.3.4\" \"4.3.2.1\"]\n [#\"example.com\" \"nuv",
"end": 361,
"score": 0.9994013905525208,
"start": 354,
"tag": "IP_ADDRESS",
"value": "4.3.2.1"
},
{
"context": " [#\"example.com\" \"nuv.la\"]})]\n (is (= \"4.3.2.1\" (:ip m)))\n (is (= \"http://4.3.2.1/uri\" (:url ",
"end": 439,
"score": 0.9985359311103821,
"start": 432,
"tag": "IP_ADDRESS",
"value": "4.3.2.1"
}
] | cimi-tools/test/com/sixsq/slipstream/tools/cli/utils_test.clj | slipstream/cimi-mf2c | 0 | (ns com.sixsq.slipstream.tools.cli.utils-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.tools.cli.utils :as u]))
(deftest test-modify-vals
(let [m (u/modify-vals {:ip "1.2.3.4"
:url "http://1.2.3.4/uri"
:dns "https://example.com"}
#{[#"1.2.3.4" "4.3.2.1"]
[#"example.com" "nuv.la"]})]
(is (= "4.3.2.1" (:ip m)))
(is (= "http://4.3.2.1/uri" (:url m)))
(is (= "https://nuv.la" (:dns m)))))
(deftest test-->config-resource
(is (= "/configuration" (u/->config-resource ""))))
(deftest test-remove-attrs
(is (= {} (u/remove-attrs {})))
(is (= {:foo "bar"} (u/remove-attrs {:foo "bar"})))
(is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"})))
(is (not (contains? (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"}) :securityGroup)))
(is (not (contains? (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}) :pdiskEndpoint))))
(deftest test-->re-match-replace
(let [[m r] (u/->re-match-replace "a=b")]
(is (= java.util.regex.Pattern (type m)))
(is (= "a" (str m)))
(is (= "b" r))))
| 98610 | (ns com.sixsq.slipstream.tools.cli.utils-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.tools.cli.utils :as u]))
(deftest test-modify-vals
(let [m (u/modify-vals {:ip "192.168.127.12"
:url "http://1.2.3.4/uri"
:dns "https://example.com"}
#{[#"192.168.127.12" "172.16.31.10"]
[#"example.com" "nuv.la"]})]
(is (= "172.16.31.10" (:ip m)))
(is (= "http://4.3.2.1/uri" (:url m)))
(is (= "https://nuv.la" (:dns m)))))
(deftest test-->config-resource
(is (= "/configuration" (u/->config-resource ""))))
(deftest test-remove-attrs
(is (= {} (u/remove-attrs {})))
(is (= {:foo "bar"} (u/remove-attrs {:foo "bar"})))
(is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"})))
(is (not (contains? (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"}) :securityGroup)))
(is (not (contains? (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}) :pdiskEndpoint))))
(deftest test-->re-match-replace
(let [[m r] (u/->re-match-replace "a=b")]
(is (= java.util.regex.Pattern (type m)))
(is (= "a" (str m)))
(is (= "b" r))))
| true | (ns com.sixsq.slipstream.tools.cli.utils-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.tools.cli.utils :as u]))
(deftest test-modify-vals
(let [m (u/modify-vals {:ip "PI:IP_ADDRESS:192.168.127.12END_PI"
:url "http://1.2.3.4/uri"
:dns "https://example.com"}
#{[#"PI:IP_ADDRESS:192.168.127.12END_PI" "PI:IP_ADDRESS:172.16.31.10END_PI"]
[#"example.com" "nuv.la"]})]
(is (= "PI:IP_ADDRESS:172.16.31.10END_PI" (:ip m)))
(is (= "http://4.3.2.1/uri" (:url m)))
(is (= "https://nuv.la" (:dns m)))))
(deftest test-->config-resource
(is (= "/configuration" (u/->config-resource ""))))
(deftest test-remove-attrs
(is (= {} (u/remove-attrs {})))
(is (= {:foo "bar"} (u/remove-attrs {:foo "bar"})))
(is (= {:cloudServiceType "foo"} (u/remove-attrs {:cloudServiceType "foo"})))
(is (not (contains? (u/remove-attrs {:cloudServiceType "ec2" :securityGroup "secure"}) :securityGroup)))
(is (not (contains? (u/remove-attrs {:cloudServiceType "nuvlabox" :pdiskEndpoint "endpoint"}) :pdiskEndpoint))))
(deftest test-->re-match-replace
(let [[m r] (u/->re-match-replace "a=b")]
(is (= java.util.regex.Pattern (type m)))
(is (= "a" (str m)))
(is (= "b" r))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998130798339844,
"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.9998221397399902,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/test/editor/scene_layout_test.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.scene-layout-test
(:require [clojure.test :refer :all]
[editor.scene-layout :as layout]
[editor.types :refer [->Region]])
(:import [editor.types Region]))
; left right top bottom
(def ^:private viewport (->Region 0 640 0 480))
(deftest hsplit []
(let [desc {:type :hbox
:children [{:id :test1}
{:id :test2}]}
result (layout/layout desc viewport)]
(is (= (:test1 result) (->Region 0 320 0 480)))
(is (= (:test2 result) (->Region 320 640 0 480)))))
(deftest anchor []
(let [desc {:id :parent
:anchors {:bottom 0}
:max-height 20
:children [{:id :child}]}
result (layout/layout desc viewport)]
(is (= (:parent result) (->Region 0 640 460 480)))
(is (= (:child result) (->Region 0 640 460 480)))))
(deftest timeline []
(let [desc {:anchors {:bottom 0}
:padding 20
:max-height 72
:children [{:id :play
:max-width 32}
{:id :timeline}]}
result (layout/layout desc viewport)]
(is (= (:play result) (->Region 20 52 428 460)))
(is (= (:timeline result) (->Region 52 620 428 460)))))
| 69961 | ;; 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.scene-layout-test
(:require [clojure.test :refer :all]
[editor.scene-layout :as layout]
[editor.types :refer [->Region]])
(:import [editor.types Region]))
; left right top bottom
(def ^:private viewport (->Region 0 640 0 480))
(deftest hsplit []
(let [desc {:type :hbox
:children [{:id :test1}
{:id :test2}]}
result (layout/layout desc viewport)]
(is (= (:test1 result) (->Region 0 320 0 480)))
(is (= (:test2 result) (->Region 320 640 0 480)))))
(deftest anchor []
(let [desc {:id :parent
:anchors {:bottom 0}
:max-height 20
:children [{:id :child}]}
result (layout/layout desc viewport)]
(is (= (:parent result) (->Region 0 640 460 480)))
(is (= (:child result) (->Region 0 640 460 480)))))
(deftest timeline []
(let [desc {:anchors {:bottom 0}
:padding 20
:max-height 72
:children [{:id :play
:max-width 32}
{:id :timeline}]}
result (layout/layout desc viewport)]
(is (= (:play result) (->Region 20 52 428 460)))
(is (= (:timeline result) (->Region 52 620 428 460)))))
| 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.scene-layout-test
(:require [clojure.test :refer :all]
[editor.scene-layout :as layout]
[editor.types :refer [->Region]])
(:import [editor.types Region]))
; left right top bottom
(def ^:private viewport (->Region 0 640 0 480))
(deftest hsplit []
(let [desc {:type :hbox
:children [{:id :test1}
{:id :test2}]}
result (layout/layout desc viewport)]
(is (= (:test1 result) (->Region 0 320 0 480)))
(is (= (:test2 result) (->Region 320 640 0 480)))))
(deftest anchor []
(let [desc {:id :parent
:anchors {:bottom 0}
:max-height 20
:children [{:id :child}]}
result (layout/layout desc viewport)]
(is (= (:parent result) (->Region 0 640 460 480)))
(is (= (:child result) (->Region 0 640 460 480)))))
(deftest timeline []
(let [desc {:anchors {:bottom 0}
:padding 20
:max-height 72
:children [{:id :play
:max-width 32}
{:id :timeline}]}
result (layout/layout desc viewport)]
(is (= (:play result) (->Region 20 52 428 460)))
(is (= (:timeline result) (->Region 52 620 428 460)))))
|
[
{
"context": "; Copyright (C) 2013-2015 Joseph Fosco. All Rights Reserved\n;\n; This program is free ",
"end": 42,
"score": 0.9998245239257812,
"start": 30,
"tag": "NAME",
"value": "Joseph Fosco"
}
] | data/test/clojure/351cda42abfe457cc4e411ce4e8c80423ba07580segment.clj | harshp8l/deep-learning-lang-detection | 84 | ; Copyright (C) 2013-2015 Joseph Fosco. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transport.segment
(:require
[transport.behavior :refer [get-behavior-action get-behavior-player-id]]
[transport.constants :refer :all]
[transport.behaviors :refer [select-first-behavior select-behavior]]
[transport.dur-info :refer [get-dur-millis]]
[transport.instrument :refer [get-instrument-range-hi get-instrument-range-lo select-instrument select-random-instrument]]
[transport.melody :refer [adjust-melody-char-range select-melody-characteristics select-random-melody-characteristics]]
[transport.melodychar :refer [get-melody-char-range-lo get-melody-char-range-hi]]
[transport.melodyevent :refer [get-dur-info-for-event get-note-event-time-for-event get-seg-num-for-event]]
[transport.pitch :refer [select-key select-random-key select-scale select-random-scale]]
[transport.players :refer :all]
[transport.random :refer [random-int]]
[transport.rhythm :refer [select-metronome select-metronome-mm select-mm]]
))
(def min-segment-len 5000) ;minimum segment length in milliseconds (5 seconds)
(def max-segment-len 20000) ;maximum segment length in milliseconds (20 seconds)
(defn select-segment-length
[]
(random-int min-segment-len max-segment-len))
(defn copy-following-info
[player]
(merge player (get-following-info-from-player (get-player-map (get-behavior-player-id (get-behavior player)))))
)
(defn first-segment
"Used only the first time a player is created.
After the first time, use new-segment.
player - the player to create the segment for"
[player]
(let [new-behavior (select-first-behavior player)
new-instrument (select-random-instrument)
rnd-mm (select-mm)
]
(assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:instrument-info new-instrument
:key (select-random-key)
:melody-char (select-random-melody-characteristics (get-instrument-range-lo new-instrument) (get-instrument-range-hi new-instrument))
:metronome (select-metronome-mm rnd-mm)
:mm rnd-mm
:seg-len (select-segment-length)
:seg-num 1
:seg-start 0
:scale (select-random-scale))))
(defn get-contrasting-info-for-player
"Returns a map of key value pairs for a player that must
CONTRAST another player
player - player to get info for"
[player cntrst-player]
(let [new-melody-char (select-melody-characteristics player)]
{
:instrument-info (select-instrument player new-melody-char
:cntrst-plyr-inst-info (get-instrument-info cntrst-player)
)
:melody-char new-melody-char
}
)
)
(defn new-segment?
"Returns true if player is starting a new segment, else returns false
player - the player to check a new segment for"
[player]
(let [melody-event (get-last-melody-event player)]
(if (>= (+ (get-note-event-time-for-event melody-event) (get-dur-millis (get-dur-info-for-event melody-event)))
(+ (get-seg-start player) (get-seg-len player)))
true
false))
)
(defn new-segment
"Returns player map with new segment info in it
player - player map to get (and return) new segment info for"
[player event-time]
(let [new-behavior (select-behavior player)
behavior-action (get-behavior-action new-behavior)
upd-player (assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:seg-len (select-segment-length)
:seg-num (inc (get-seg-num player))
:seg-start event-time
)
]
(cond
(= behavior-action FOLLOW-PLAYER)
(let [following-player-id (get-behavior-player-id new-behavior)]
(merge upd-player
(get-following-info-from-player (get-player-map following-player-id))))
(= behavior-action SIMILAR-PLAYER)
(let [similar-player-info (get-similar-info-from-player (get-player-map (get-behavior-player-id new-behavior)))
similar-melody-char (:melody-char similar-player-info)
new-instrument (select-instrument upd-player similar-melody-char)
new-melody-char (adjust-melody-char-range similar-melody-char new-instrument)
new-similar-info (assoc similar-player-info :melody-char new-melody-char)
]
(merge (assoc upd-player
:instrument-info new-instrument
)
new-similar-info)
)
:else ;; IGNORE-ALL or CONTRAST-PLAYER or SIMILAR-ENSEMBLE or CONTRAST-ENSEMBLE
(let [new-melody-char (select-melody-characteristics upd-player)
new-instrument (if (= behavior-action CONTRAST-PLAYER)
(select-instrument upd-player
new-melody-char
:cntrst-plyr (get-behavior-player-id upd-player))
(select-instrument upd-player new-melody-char))
new-mm (select-mm upd-player)
]
(assoc upd-player
:instrument-info new-instrument
:key (select-key upd-player)
:melody-char (adjust-melody-char-range new-melody-char new-instrument)
:metronome (select-metronome upd-player)
:mm new-mm
:scale (select-scale upd-player)
)))))
| 97897 | ; Copyright (C) 2013-2015 <NAME>. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transport.segment
(:require
[transport.behavior :refer [get-behavior-action get-behavior-player-id]]
[transport.constants :refer :all]
[transport.behaviors :refer [select-first-behavior select-behavior]]
[transport.dur-info :refer [get-dur-millis]]
[transport.instrument :refer [get-instrument-range-hi get-instrument-range-lo select-instrument select-random-instrument]]
[transport.melody :refer [adjust-melody-char-range select-melody-characteristics select-random-melody-characteristics]]
[transport.melodychar :refer [get-melody-char-range-lo get-melody-char-range-hi]]
[transport.melodyevent :refer [get-dur-info-for-event get-note-event-time-for-event get-seg-num-for-event]]
[transport.pitch :refer [select-key select-random-key select-scale select-random-scale]]
[transport.players :refer :all]
[transport.random :refer [random-int]]
[transport.rhythm :refer [select-metronome select-metronome-mm select-mm]]
))
(def min-segment-len 5000) ;minimum segment length in milliseconds (5 seconds)
(def max-segment-len 20000) ;maximum segment length in milliseconds (20 seconds)
(defn select-segment-length
[]
(random-int min-segment-len max-segment-len))
(defn copy-following-info
[player]
(merge player (get-following-info-from-player (get-player-map (get-behavior-player-id (get-behavior player)))))
)
(defn first-segment
"Used only the first time a player is created.
After the first time, use new-segment.
player - the player to create the segment for"
[player]
(let [new-behavior (select-first-behavior player)
new-instrument (select-random-instrument)
rnd-mm (select-mm)
]
(assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:instrument-info new-instrument
:key (select-random-key)
:melody-char (select-random-melody-characteristics (get-instrument-range-lo new-instrument) (get-instrument-range-hi new-instrument))
:metronome (select-metronome-mm rnd-mm)
:mm rnd-mm
:seg-len (select-segment-length)
:seg-num 1
:seg-start 0
:scale (select-random-scale))))
(defn get-contrasting-info-for-player
"Returns a map of key value pairs for a player that must
CONTRAST another player
player - player to get info for"
[player cntrst-player]
(let [new-melody-char (select-melody-characteristics player)]
{
:instrument-info (select-instrument player new-melody-char
:cntrst-plyr-inst-info (get-instrument-info cntrst-player)
)
:melody-char new-melody-char
}
)
)
(defn new-segment?
"Returns true if player is starting a new segment, else returns false
player - the player to check a new segment for"
[player]
(let [melody-event (get-last-melody-event player)]
(if (>= (+ (get-note-event-time-for-event melody-event) (get-dur-millis (get-dur-info-for-event melody-event)))
(+ (get-seg-start player) (get-seg-len player)))
true
false))
)
(defn new-segment
"Returns player map with new segment info in it
player - player map to get (and return) new segment info for"
[player event-time]
(let [new-behavior (select-behavior player)
behavior-action (get-behavior-action new-behavior)
upd-player (assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:seg-len (select-segment-length)
:seg-num (inc (get-seg-num player))
:seg-start event-time
)
]
(cond
(= behavior-action FOLLOW-PLAYER)
(let [following-player-id (get-behavior-player-id new-behavior)]
(merge upd-player
(get-following-info-from-player (get-player-map following-player-id))))
(= behavior-action SIMILAR-PLAYER)
(let [similar-player-info (get-similar-info-from-player (get-player-map (get-behavior-player-id new-behavior)))
similar-melody-char (:melody-char similar-player-info)
new-instrument (select-instrument upd-player similar-melody-char)
new-melody-char (adjust-melody-char-range similar-melody-char new-instrument)
new-similar-info (assoc similar-player-info :melody-char new-melody-char)
]
(merge (assoc upd-player
:instrument-info new-instrument
)
new-similar-info)
)
:else ;; IGNORE-ALL or CONTRAST-PLAYER or SIMILAR-ENSEMBLE or CONTRAST-ENSEMBLE
(let [new-melody-char (select-melody-characteristics upd-player)
new-instrument (if (= behavior-action CONTRAST-PLAYER)
(select-instrument upd-player
new-melody-char
:cntrst-plyr (get-behavior-player-id upd-player))
(select-instrument upd-player new-melody-char))
new-mm (select-mm upd-player)
]
(assoc upd-player
:instrument-info new-instrument
:key (select-key upd-player)
:melody-char (adjust-melody-char-range new-melody-char new-instrument)
:metronome (select-metronome upd-player)
:mm new-mm
:scale (select-scale upd-player)
)))))
| true | ; Copyright (C) 2013-2015 PI:NAME:<NAME>END_PI. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transport.segment
(:require
[transport.behavior :refer [get-behavior-action get-behavior-player-id]]
[transport.constants :refer :all]
[transport.behaviors :refer [select-first-behavior select-behavior]]
[transport.dur-info :refer [get-dur-millis]]
[transport.instrument :refer [get-instrument-range-hi get-instrument-range-lo select-instrument select-random-instrument]]
[transport.melody :refer [adjust-melody-char-range select-melody-characteristics select-random-melody-characteristics]]
[transport.melodychar :refer [get-melody-char-range-lo get-melody-char-range-hi]]
[transport.melodyevent :refer [get-dur-info-for-event get-note-event-time-for-event get-seg-num-for-event]]
[transport.pitch :refer [select-key select-random-key select-scale select-random-scale]]
[transport.players :refer :all]
[transport.random :refer [random-int]]
[transport.rhythm :refer [select-metronome select-metronome-mm select-mm]]
))
(def min-segment-len 5000) ;minimum segment length in milliseconds (5 seconds)
(def max-segment-len 20000) ;maximum segment length in milliseconds (20 seconds)
(defn select-segment-length
[]
(random-int min-segment-len max-segment-len))
(defn copy-following-info
[player]
(merge player (get-following-info-from-player (get-player-map (get-behavior-player-id (get-behavior player)))))
)
(defn first-segment
"Used only the first time a player is created.
After the first time, use new-segment.
player - the player to create the segment for"
[player]
(let [new-behavior (select-first-behavior player)
new-instrument (select-random-instrument)
rnd-mm (select-mm)
]
(assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:instrument-info new-instrument
:key (select-random-key)
:melody-char (select-random-melody-characteristics (get-instrument-range-lo new-instrument) (get-instrument-range-hi new-instrument))
:metronome (select-metronome-mm rnd-mm)
:mm rnd-mm
:seg-len (select-segment-length)
:seg-num 1
:seg-start 0
:scale (select-random-scale))))
(defn get-contrasting-info-for-player
"Returns a map of key value pairs for a player that must
CONTRAST another player
player - player to get info for"
[player cntrst-player]
(let [new-melody-char (select-melody-characteristics player)]
{
:instrument-info (select-instrument player new-melody-char
:cntrst-plyr-inst-info (get-instrument-info cntrst-player)
)
:melody-char new-melody-char
}
)
)
(defn new-segment?
"Returns true if player is starting a new segment, else returns false
player - the player to check a new segment for"
[player]
(let [melody-event (get-last-melody-event player)]
(if (>= (+ (get-note-event-time-for-event melody-event) (get-dur-millis (get-dur-info-for-event melody-event)))
(+ (get-seg-start player) (get-seg-len player)))
true
false))
)
(defn new-segment
"Returns player map with new segment info in it
player - player map to get (and return) new segment info for"
[player event-time]
(let [new-behavior (select-behavior player)
behavior-action (get-behavior-action new-behavior)
upd-player (assoc player
:behavior new-behavior
:change-follow-info-notes []
:change-follow-info []
:seg-len (select-segment-length)
:seg-num (inc (get-seg-num player))
:seg-start event-time
)
]
(cond
(= behavior-action FOLLOW-PLAYER)
(let [following-player-id (get-behavior-player-id new-behavior)]
(merge upd-player
(get-following-info-from-player (get-player-map following-player-id))))
(= behavior-action SIMILAR-PLAYER)
(let [similar-player-info (get-similar-info-from-player (get-player-map (get-behavior-player-id new-behavior)))
similar-melody-char (:melody-char similar-player-info)
new-instrument (select-instrument upd-player similar-melody-char)
new-melody-char (adjust-melody-char-range similar-melody-char new-instrument)
new-similar-info (assoc similar-player-info :melody-char new-melody-char)
]
(merge (assoc upd-player
:instrument-info new-instrument
)
new-similar-info)
)
:else ;; IGNORE-ALL or CONTRAST-PLAYER or SIMILAR-ENSEMBLE or CONTRAST-ENSEMBLE
(let [new-melody-char (select-melody-characteristics upd-player)
new-instrument (if (= behavior-action CONTRAST-PLAYER)
(select-instrument upd-player
new-melody-char
:cntrst-plyr (get-behavior-player-id upd-player))
(select-instrument upd-player new-melody-char))
new-mm (select-mm upd-player)
]
(assoc upd-player
:instrument-info new-instrument
:key (select-key upd-player)
:melody-char (adjust-melody-char-range new-melody-char new-instrument)
:metronome (select-metronome upd-player)
:mm new-mm
:scale (select-scale upd-player)
)))))
|
[
{
"context": "\n; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk)\n;\n; Licensed under the Ap",
"end": 34,
"score": 0.9998716115951538,
"start": 18,
"tag": "NAME",
"value": "Anthony Campbell"
},
{
"context": "\n; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk)\n;\n; Licensed under the Apache License, Version 2",
"end": 57,
"score": 0.9593700766563416,
"start": 36,
"tag": "EMAIL",
"value": "anthonycampbell.co.uk"
}
] | src/uk/co/anthonycampbell/imdb/cast_parser.clj | acampbell3000/clojure-imdb-parser | 1 |
; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk)
;
; 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 uk.co.anthonycampbell.imdb.cast-parser
(:use uk.co.anthonycampbell.imdb.request)
(:use clojure.tools.logging)
(:use clj-logging-config.log4j)
(:require [clj-http.client :as client])
(:require [net.cgrand.enlive-html :as html])
(:require [net.cgrand.xml :as xml])
(:require [clojure.string])
(:require [clojure.contrib.string :as ccstring]))
(defn construct-cast
"Construct a cast string based on the provided parsed page content"
[page-content]
(debug "- Looking for cast table...")
(if (not-empty page-content)
(let [cast-table (html/select page-content [:table.cast])]
; Parse cast list
(loop [cast-list []
cast-rows (html/select cast-table [:tr])]
(if (not-empty cast-rows)
; Recurrsively compile cast list
(recur (concat cast-list
(let [cast-name (html/select (first cast-rows) [:td.nm])
cast-character (html/select (first cast-rows) [:td.char])]
; Only persist if we're dealing with a 'real' character
(if (not-empty cast-character)
(let [cast-name-value (:content (first cast-name))
cast-character-value (:content (first cast-character))]
(debug "----" cast-name-value)
(if (not-empty cast-name-value)
(if (not-empty (html/select cast-name-value [:a]))
[(ccstring/trim (first (:content (first cast-name-value))))]
(if (not-empty (html/select cast-name-value [:span]))
[(ccstring/trim (first (:content (first cast-name-value))))]
[(ccstring/trim cast-name-value)])))))))
; Next row
(let [cast-character (html/select (first cast-rows) [:td.char])]
(if (not-empty cast-character)
; We don't want too many cast entries
(if (<= (count cast-list) 20)
(rest cast-rows))
(rest cast-rows))))
; Convert list to string
(loop [cast-string ""
cast-list-temp cast-list]
(if (not-empty cast-list-temp)
; Recurrsively compile cast string
(recur (str cast-string (str ", " (first cast-list-temp)))
; Next element
(rest cast-list-temp))
; Finaly clean up
(if (not-empty cast-string)
(ccstring/trim (subs cast-string 2))))))))))
(defn search-for-directors
"Searches through all of the provided cast tables until we find the
director sub section."
[list]
(if (not-empty list)
(let [table-links (html/select (first list) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Directed by")
(let [directors (rest table-links)]
; Return directors
(debug "----" directors)
directors)
; Move onto next article
(search-for-directors (rest list)))
(search-for-directors (rest list))))))
(defn construct-directors
"Construct a directors string based on the provided parsed page content"
[page-content]
(debug "- Looking for directors...")
(if (not-empty page-content)
; Parse list of directors
(loop [director-string ""
director-list (search-for-directors (html/select page-content [:table]))]
(if (not-empty director-list)
; Recurrsively compile director string
(recur (str director-string (str ", " (first (:content (first director-list)))))
(rest director-list))
; Final clean up
(if (not-empty director-string)
(ccstring/trim (subs director-string 2)))))))
(defn search-for-producers
"Searches through all of the provided cast tables until we find the
producer sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Produced by")
; Return producers
(rest (html/select (first cast-tables) [:tr]))
; Move onto next article
(search-for-producers (rest cast-tables)))))))
(defn construct-producers
"Construct a producers string based on the provided parsed page content"
[page-content]
(debug "- Looking for producers...")
(if (not-empty page-content)
; Parse list of producers
(loop [producer-string ""
producer-list (search-for-producers (html/select page-content [:table]))]
(if (not-empty producer-list)
; Recurrsively compile producer string
(recur (str producer-string
(let [producers (html/select (first producer-list) [:a])]
(if (not-empty producers)
; If we have a type to work with lets validate
(if (> (count producers) 1)
(let [producer (first (:content (first producers)))
producer-type (first (:content (second producers)))]
; Only grab if type is executive or producer
(if (= (ccstring/lower-case producer-type) "producer")
(str ", " producer)
(if (= (ccstring/lower-case producer-type) "executive producer")
(str ", " producer)
"")))
(str ", " (first (:content (first producers))))))))
(rest producer-list))
; Final clean up
(if (not-empty producer-string)
(ccstring/trim (subs producer-string 2)))))))
(defn search-for-screen-writers
"Searches through all of the provided cast tables until we find the
writing credits sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Writing credits")
; Return directors
(rest table-links)
; Move onto next article
(search-for-screen-writers (rest cast-tables)))))))
(defn construct-screen-writers
"Construct a screen-writers string based on the provided parsed page content"
[page-content]
(debug "- Looking for screen writers...")
(if (not-empty page-content)
; Parse list of screen writers
(loop [screen-writer-set (sorted-set)
screen-writer-list (search-for-screen-writers (html/select page-content [:table]))]
(if (not-empty screen-writer-list)
; Recurrsively push screen writers into set to de-dupe items
(recur (conj screen-writer-set (first (:content (first screen-writer-list))))
(rest screen-writer-list))
(loop [screen-writer-string ""
screen-writer-set (disj screen-writer-set "WGA")]
(if (not-empty screen-writer-set)
; Compile screen writer string
(recur (str screen-writer-string ", " (first screen-writer-set))
(rest screen-writer-set))
; Final clean up
(if (not-empty screen-writer-string)
(ccstring/trim (subs screen-writer-string 2)))))))))
| 67976 |
; Copyright 2013 <NAME> (<EMAIL>)
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns uk.co.anthonycampbell.imdb.cast-parser
(:use uk.co.anthonycampbell.imdb.request)
(:use clojure.tools.logging)
(:use clj-logging-config.log4j)
(:require [clj-http.client :as client])
(:require [net.cgrand.enlive-html :as html])
(:require [net.cgrand.xml :as xml])
(:require [clojure.string])
(:require [clojure.contrib.string :as ccstring]))
(defn construct-cast
"Construct a cast string based on the provided parsed page content"
[page-content]
(debug "- Looking for cast table...")
(if (not-empty page-content)
(let [cast-table (html/select page-content [:table.cast])]
; Parse cast list
(loop [cast-list []
cast-rows (html/select cast-table [:tr])]
(if (not-empty cast-rows)
; Recurrsively compile cast list
(recur (concat cast-list
(let [cast-name (html/select (first cast-rows) [:td.nm])
cast-character (html/select (first cast-rows) [:td.char])]
; Only persist if we're dealing with a 'real' character
(if (not-empty cast-character)
(let [cast-name-value (:content (first cast-name))
cast-character-value (:content (first cast-character))]
(debug "----" cast-name-value)
(if (not-empty cast-name-value)
(if (not-empty (html/select cast-name-value [:a]))
[(ccstring/trim (first (:content (first cast-name-value))))]
(if (not-empty (html/select cast-name-value [:span]))
[(ccstring/trim (first (:content (first cast-name-value))))]
[(ccstring/trim cast-name-value)])))))))
; Next row
(let [cast-character (html/select (first cast-rows) [:td.char])]
(if (not-empty cast-character)
; We don't want too many cast entries
(if (<= (count cast-list) 20)
(rest cast-rows))
(rest cast-rows))))
; Convert list to string
(loop [cast-string ""
cast-list-temp cast-list]
(if (not-empty cast-list-temp)
; Recurrsively compile cast string
(recur (str cast-string (str ", " (first cast-list-temp)))
; Next element
(rest cast-list-temp))
; Finaly clean up
(if (not-empty cast-string)
(ccstring/trim (subs cast-string 2))))))))))
(defn search-for-directors
"Searches through all of the provided cast tables until we find the
director sub section."
[list]
(if (not-empty list)
(let [table-links (html/select (first list) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Directed by")
(let [directors (rest table-links)]
; Return directors
(debug "----" directors)
directors)
; Move onto next article
(search-for-directors (rest list)))
(search-for-directors (rest list))))))
(defn construct-directors
"Construct a directors string based on the provided parsed page content"
[page-content]
(debug "- Looking for directors...")
(if (not-empty page-content)
; Parse list of directors
(loop [director-string ""
director-list (search-for-directors (html/select page-content [:table]))]
(if (not-empty director-list)
; Recurrsively compile director string
(recur (str director-string (str ", " (first (:content (first director-list)))))
(rest director-list))
; Final clean up
(if (not-empty director-string)
(ccstring/trim (subs director-string 2)))))))
(defn search-for-producers
"Searches through all of the provided cast tables until we find the
producer sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Produced by")
; Return producers
(rest (html/select (first cast-tables) [:tr]))
; Move onto next article
(search-for-producers (rest cast-tables)))))))
(defn construct-producers
"Construct a producers string based on the provided parsed page content"
[page-content]
(debug "- Looking for producers...")
(if (not-empty page-content)
; Parse list of producers
(loop [producer-string ""
producer-list (search-for-producers (html/select page-content [:table]))]
(if (not-empty producer-list)
; Recurrsively compile producer string
(recur (str producer-string
(let [producers (html/select (first producer-list) [:a])]
(if (not-empty producers)
; If we have a type to work with lets validate
(if (> (count producers) 1)
(let [producer (first (:content (first producers)))
producer-type (first (:content (second producers)))]
; Only grab if type is executive or producer
(if (= (ccstring/lower-case producer-type) "producer")
(str ", " producer)
(if (= (ccstring/lower-case producer-type) "executive producer")
(str ", " producer)
"")))
(str ", " (first (:content (first producers))))))))
(rest producer-list))
; Final clean up
(if (not-empty producer-string)
(ccstring/trim (subs producer-string 2)))))))
(defn search-for-screen-writers
"Searches through all of the provided cast tables until we find the
writing credits sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Writing credits")
; Return directors
(rest table-links)
; Move onto next article
(search-for-screen-writers (rest cast-tables)))))))
(defn construct-screen-writers
"Construct a screen-writers string based on the provided parsed page content"
[page-content]
(debug "- Looking for screen writers...")
(if (not-empty page-content)
; Parse list of screen writers
(loop [screen-writer-set (sorted-set)
screen-writer-list (search-for-screen-writers (html/select page-content [:table]))]
(if (not-empty screen-writer-list)
; Recurrsively push screen writers into set to de-dupe items
(recur (conj screen-writer-set (first (:content (first screen-writer-list))))
(rest screen-writer-list))
(loop [screen-writer-string ""
screen-writer-set (disj screen-writer-set "WGA")]
(if (not-empty screen-writer-set)
; Compile screen writer string
(recur (str screen-writer-string ", " (first screen-writer-set))
(rest screen-writer-set))
; Final clean up
(if (not-empty screen-writer-string)
(ccstring/trim (subs screen-writer-string 2)))))))))
| true |
; Copyright 2013 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns uk.co.anthonycampbell.imdb.cast-parser
(:use uk.co.anthonycampbell.imdb.request)
(:use clojure.tools.logging)
(:use clj-logging-config.log4j)
(:require [clj-http.client :as client])
(:require [net.cgrand.enlive-html :as html])
(:require [net.cgrand.xml :as xml])
(:require [clojure.string])
(:require [clojure.contrib.string :as ccstring]))
(defn construct-cast
"Construct a cast string based on the provided parsed page content"
[page-content]
(debug "- Looking for cast table...")
(if (not-empty page-content)
(let [cast-table (html/select page-content [:table.cast])]
; Parse cast list
(loop [cast-list []
cast-rows (html/select cast-table [:tr])]
(if (not-empty cast-rows)
; Recurrsively compile cast list
(recur (concat cast-list
(let [cast-name (html/select (first cast-rows) [:td.nm])
cast-character (html/select (first cast-rows) [:td.char])]
; Only persist if we're dealing with a 'real' character
(if (not-empty cast-character)
(let [cast-name-value (:content (first cast-name))
cast-character-value (:content (first cast-character))]
(debug "----" cast-name-value)
(if (not-empty cast-name-value)
(if (not-empty (html/select cast-name-value [:a]))
[(ccstring/trim (first (:content (first cast-name-value))))]
(if (not-empty (html/select cast-name-value [:span]))
[(ccstring/trim (first (:content (first cast-name-value))))]
[(ccstring/trim cast-name-value)])))))))
; Next row
(let [cast-character (html/select (first cast-rows) [:td.char])]
(if (not-empty cast-character)
; We don't want too many cast entries
(if (<= (count cast-list) 20)
(rest cast-rows))
(rest cast-rows))))
; Convert list to string
(loop [cast-string ""
cast-list-temp cast-list]
(if (not-empty cast-list-temp)
; Recurrsively compile cast string
(recur (str cast-string (str ", " (first cast-list-temp)))
; Next element
(rest cast-list-temp))
; Finaly clean up
(if (not-empty cast-string)
(ccstring/trim (subs cast-string 2))))))))))
(defn search-for-directors
"Searches through all of the provided cast tables until we find the
director sub section."
[list]
(if (not-empty list)
(let [table-links (html/select (first list) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Directed by")
(let [directors (rest table-links)]
; Return directors
(debug "----" directors)
directors)
; Move onto next article
(search-for-directors (rest list)))
(search-for-directors (rest list))))))
(defn construct-directors
"Construct a directors string based on the provided parsed page content"
[page-content]
(debug "- Looking for directors...")
(if (not-empty page-content)
; Parse list of directors
(loop [director-string ""
director-list (search-for-directors (html/select page-content [:table]))]
(if (not-empty director-list)
; Recurrsively compile director string
(recur (str director-string (str ", " (first (:content (first director-list)))))
(rest director-list))
; Final clean up
(if (not-empty director-string)
(ccstring/trim (subs director-string 2)))))))
(defn search-for-producers
"Searches through all of the provided cast tables until we find the
producer sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Produced by")
; Return producers
(rest (html/select (first cast-tables) [:tr]))
; Move onto next article
(search-for-producers (rest cast-tables)))))))
(defn construct-producers
"Construct a producers string based on the provided parsed page content"
[page-content]
(debug "- Looking for producers...")
(if (not-empty page-content)
; Parse list of producers
(loop [producer-string ""
producer-list (search-for-producers (html/select page-content [:table]))]
(if (not-empty producer-list)
; Recurrsively compile producer string
(recur (str producer-string
(let [producers (html/select (first producer-list) [:a])]
(if (not-empty producers)
; If we have a type to work with lets validate
(if (> (count producers) 1)
(let [producer (first (:content (first producers)))
producer-type (first (:content (second producers)))]
; Only grab if type is executive or producer
(if (= (ccstring/lower-case producer-type) "producer")
(str ", " producer)
(if (= (ccstring/lower-case producer-type) "executive producer")
(str ", " producer)
"")))
(str ", " (first (:content (first producers))))))))
(rest producer-list))
; Final clean up
(if (not-empty producer-string)
(ccstring/trim (subs producer-string 2)))))))
(defn search-for-screen-writers
"Searches through all of the provided cast tables until we find the
writing credits sub section."
[cast-tables]
(if (not-empty cast-tables)
(let [table-links (html/select (first cast-tables) [:a])]
(if (not-empty table-links)
; Check whether this is the right article
(if (.contains (str (first (:content (first table-links)))) "Writing credits")
; Return directors
(rest table-links)
; Move onto next article
(search-for-screen-writers (rest cast-tables)))))))
(defn construct-screen-writers
"Construct a screen-writers string based on the provided parsed page content"
[page-content]
(debug "- Looking for screen writers...")
(if (not-empty page-content)
; Parse list of screen writers
(loop [screen-writer-set (sorted-set)
screen-writer-list (search-for-screen-writers (html/select page-content [:table]))]
(if (not-empty screen-writer-list)
; Recurrsively push screen writers into set to de-dupe items
(recur (conj screen-writer-set (first (:content (first screen-writer-list))))
(rest screen-writer-list))
(loop [screen-writer-string ""
screen-writer-set (disj screen-writer-set "WGA")]
(if (not-empty screen-writer-set)
; Compile screen writer string
(recur (str screen-writer-string ", " (first screen-writer-set))
(rest screen-writer-set))
; Final clean up
(if (not-empty screen-writer-string)
(ccstring/trim (subs screen-writer-string 2)))))))))
|
[
{
"context": "t x :_id)))))\n\n;; USER SCHEMA\n;; Example: {:name \"Pepe\" :username \"pepe\" :password \"password\" :rol \"us",
"end": 2086,
"score": 0.6718717217445374,
"start": 2084,
"tag": "NAME",
"value": "Pe"
},
{
"context": "x :_id)))))\n\n;; USER SCHEMA\n;; Example: {:name \"Pepe\" :username \"pepe\" :password \"password\" :rol \"user",
"end": 2088,
"score": 0.7233644723892212,
"start": 2086,
"tag": "USERNAME",
"value": "pe"
},
{
"context": " USER SCHEMA\n;; Example: {:name \"Pepe\" :username \"pepe\" :password \"password\" :rol \"user\" :location \"Spai",
"end": 2105,
"score": 0.9995594024658203,
"start": 2101,
"tag": "USERNAME",
"value": "pepe"
},
{
"context": "xample: {:name \"Pepe\" :username \"pepe\" :password \"password\" :rol \"user\" :location \"Spain\"}\n(defn- user-schem",
"end": 2126,
"score": 0.9996183514595032,
"start": 2118,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ": {:code '1', :content ({:rol 'admin', :username 'rsucasas', ...})}\n where :content is a clojure.lang.Laz",
"end": 7379,
"score": 0.9996877312660217,
"start": 7371,
"tag": "USERNAME",
"value": "rsucasas"
}
] | softcare-multimedia-repository/src/softcare/db/mongodb.clj | seaclouds-atos/softcare-final-implementation | 0 | (ns softcare.db.mongodb
(:use [softcare.globals]
[softcare.db.schemas])
(:require [monger.core :as mg]
[monger.credentials :as mcred]
[monger.collection :as mc]
[cheshire.core :refer [generate-string]]
[cheshire.generate :refer [add-encoder encode-str]]
[softcare.config :as config]
[softcare.logs.logs :as log]
[softcare.utilities.utils :as utils]
[crypto.password.bcrypt :as password])
(:import [org.bson.types ObjectId])
(:import [com.mongodb MongoOptions ServerAddress]))
;; changes behaviour of cheshire/generate-string method ==> http://siscia.github.io/2014/08/28/manage-mongodbs-objectid-and-json/
(add-encoder org.bson.types.ObjectId (fn [s g] (.writeString g (str s))))
;; CONSTANTS - DEFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Database connection:
;; using MongoOptions allows fine-tuning connection parameters,
;; like automatic reconnection (highly recommended for production environment)
;; ==> http://clojuremongodb.info/articles/connecting.html
(def ^:private db-conn
(let [^MongoOptions opts (mg/mongo-options {:threads-allowed-to-block-for-connection-multiplier 300})
^ServerAddress sa (mg/server-address config/get-mongodb-host config/get-mongodb-port)
conn (mg/connect sa opts (mcred/create config/get-mongodb-username config/get-mongodb-database (.toCharArray config/get-mongodb-password)))
db (mg/get-db conn config/get-mongodb-database)]
db))
;; elements to be removed from database queries
(def ^:private remove-elems-list [:password :_id])
;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function:
(defn- with-db
[op & args]
(apply op db-conn args))
;; Function:
(defn- get-all-by-field-withpsswd
[coll-name map-values]
(for [x (with-db mc/find-maps coll-name map-values)]
(assoc x :_id (generate-string (get x :_id)))))
;; USER SCHEMA
;; Example: {:name "Pepe" :username "pepe" :password "password" :rol "user" :location "Spain"}
(defn- user-schema-instance1
[body-doc operation id]
(let [doc-map (parse-user-schema body-doc)]
(cond
(= operation "update") (assoc doc-map
:password ((first (get-all-by-field-withpsswd "users" {:_id (ObjectId. id)})) :password))
:else {:message "- operation not implemented -"})))
;; DOCUMENT SCHEMA
;; Example: {:name "test" :desc "test" :url "https://www....." :type "video" :tags "test" :stored "false"}
(defn- document-schema-instance1
[body-doc operation]
(let [doc-map (parse-document-schema body-doc)]
(cond
(= operation "update") doc-map
:else {:message "- operation not implemented -"})))
;; MONGODB FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; QUERIES / TRANSACTIONS
;; Function: get all elements from collection / table
(defn get-all
[coll-name]
(case coll-name
"users" (for [x (with-db mc/find-maps coll-name)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password))
"documents" (with-db mc/find-maps coll-name {:type "video"})))
;; Function: get element from collection / table by id
(defn get-by-id
[coll-name id]
(case coll-name
"users" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(dissoc (assoc (with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}) :_id id) :password))
(gen-response CODE_ERROR {:message "warning: no users found"}))
"documents" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}))
(gen-response CODE_ERROR {:message "warning: no videos found"}))))
;; Function:
(defn get-doc-stored-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :stored])
"false")))
;; Function: Example (get-doc-publicid-by-id "56e957c2f06f6b31d884d175")
(defn get-doc-publicid-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :name])
"NotFound")))
;; Function: get elements by field(s)
(defn get-all-by-field
[coll-name map-values]
(case coll-name
"users" (gen-response CODE_OK
(for [x (with-db mc/find-maps coll-name map-values)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password)))
"documents" (gen-response CODE_OK (with-db mc/find-maps coll-name map-values))))
;; Function: insert new element
(defn- insert
[coll-name doc-map error-msg]
(if-not (empty? (with-db mc/insert-and-return coll-name doc-map))
(gen-response CODE_OK (get-all coll-name))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn insert-new
[coll-name body]
(case coll-name
"users" (let [doc-map (user-schema-instance body "new" "")]
(if (empty? ((get-all-by-field coll-name {:username (get doc-map :username)}) :content))
(insert coll-name doc-map "user was not created")
(gen-response CODE_ERROR {:message "error: user already exists"})))
"documents" (let [doc-map (document-schema-instance body "new")]
(if (empty? ((get-all-by-field coll-name {:name (get doc-map :name)}) :content))
(insert coll-name doc-map "video was not uploaded")
(gen-response CODE_ERROR {:message "error: (video) name already exists"})))))
;; Function: update element
(defn- update-elem
[coll-name id data error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/update-by-id coll-name (ObjectId. id) data)
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR (str "error: " error-msg))))
;; Function:
(defn update-by-id
[coll-name id body]
(case coll-name
"users" (update-elem "users" id (user-schema-instance1 body "update" id) "no users found")
"documents" (update-elem "documents" id (document-schema-instance1 body "update") "no documents found")))
;; Function: delete element
(defn- delete
[coll-name id error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/remove-by-id coll-name (ObjectId. id))
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn delete-by-id
[coll-name id]
(case coll-name
"users" (delete coll-name id "no users found")
"documents" (delete coll-name id "no documents found")))
;; Function: LOGIN ==> clojure.lang.PersistentArrayMap
(defn do-login
"returns [clojure.lang.PersistentArrayMap], example: {:code '1', :content ({:rol 'admin', :username 'rsucasas', ...})}
where :content is a clojure.lang.LazySeq"
[username password ip]
(let [res (get-all-by-field-withpsswd "users" {:username username})]
(if-not (empty? res)
(if (password/check password ((first res) :password))
(gen-response CODE_OK (map #(apply dissoc (into {} %) remove-elems-list) res) "jwt" ip)
(gen-response CODE_ERROR {:message "no users found - not valid username / password (1)"}))
(gen-response CODE_ERROR {:message "no users found - not valid username / password (2)"}))))
;; INITIALIZE DATABASE
;; Function: delete all and add new data to new collections
(defn initialize
[]
(log/debug "Initializing database: " config/get-mongodb-host ":" config/get-mongodb-port " " config/get-mongodb-database " ...")
(mc/drop db-conn "users")
(mc/drop db-conn "documents")
(do
(when-not (mc/exists? db-conn "users")
(with-db mc/insert-and-return "users" SUPER-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER2))
(when-not (mc/exists? db-conn "documents")
(with-db mc/insert-and-return "documents" DEFAULT-DOCUMENT)))
(gen-response CODE_OK {:message "database initialized"}))
| 56018 | (ns softcare.db.mongodb
(:use [softcare.globals]
[softcare.db.schemas])
(:require [monger.core :as mg]
[monger.credentials :as mcred]
[monger.collection :as mc]
[cheshire.core :refer [generate-string]]
[cheshire.generate :refer [add-encoder encode-str]]
[softcare.config :as config]
[softcare.logs.logs :as log]
[softcare.utilities.utils :as utils]
[crypto.password.bcrypt :as password])
(:import [org.bson.types ObjectId])
(:import [com.mongodb MongoOptions ServerAddress]))
;; changes behaviour of cheshire/generate-string method ==> http://siscia.github.io/2014/08/28/manage-mongodbs-objectid-and-json/
(add-encoder org.bson.types.ObjectId (fn [s g] (.writeString g (str s))))
;; CONSTANTS - DEFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Database connection:
;; using MongoOptions allows fine-tuning connection parameters,
;; like automatic reconnection (highly recommended for production environment)
;; ==> http://clojuremongodb.info/articles/connecting.html
(def ^:private db-conn
(let [^MongoOptions opts (mg/mongo-options {:threads-allowed-to-block-for-connection-multiplier 300})
^ServerAddress sa (mg/server-address config/get-mongodb-host config/get-mongodb-port)
conn (mg/connect sa opts (mcred/create config/get-mongodb-username config/get-mongodb-database (.toCharArray config/get-mongodb-password)))
db (mg/get-db conn config/get-mongodb-database)]
db))
;; elements to be removed from database queries
(def ^:private remove-elems-list [:password :_id])
;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function:
(defn- with-db
[op & args]
(apply op db-conn args))
;; Function:
(defn- get-all-by-field-withpsswd
[coll-name map-values]
(for [x (with-db mc/find-maps coll-name map-values)]
(assoc x :_id (generate-string (get x :_id)))))
;; USER SCHEMA
;; Example: {:name "<NAME>pe" :username "pepe" :password "<PASSWORD>" :rol "user" :location "Spain"}
(defn- user-schema-instance1
[body-doc operation id]
(let [doc-map (parse-user-schema body-doc)]
(cond
(= operation "update") (assoc doc-map
:password ((first (get-all-by-field-withpsswd "users" {:_id (ObjectId. id)})) :password))
:else {:message "- operation not implemented -"})))
;; DOCUMENT SCHEMA
;; Example: {:name "test" :desc "test" :url "https://www....." :type "video" :tags "test" :stored "false"}
(defn- document-schema-instance1
[body-doc operation]
(let [doc-map (parse-document-schema body-doc)]
(cond
(= operation "update") doc-map
:else {:message "- operation not implemented -"})))
;; MONGODB FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; QUERIES / TRANSACTIONS
;; Function: get all elements from collection / table
(defn get-all
[coll-name]
(case coll-name
"users" (for [x (with-db mc/find-maps coll-name)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password))
"documents" (with-db mc/find-maps coll-name {:type "video"})))
;; Function: get element from collection / table by id
(defn get-by-id
[coll-name id]
(case coll-name
"users" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(dissoc (assoc (with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}) :_id id) :password))
(gen-response CODE_ERROR {:message "warning: no users found"}))
"documents" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}))
(gen-response CODE_ERROR {:message "warning: no videos found"}))))
;; Function:
(defn get-doc-stored-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :stored])
"false")))
;; Function: Example (get-doc-publicid-by-id "56e957c2f06f6b31d884d175")
(defn get-doc-publicid-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :name])
"NotFound")))
;; Function: get elements by field(s)
(defn get-all-by-field
[coll-name map-values]
(case coll-name
"users" (gen-response CODE_OK
(for [x (with-db mc/find-maps coll-name map-values)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password)))
"documents" (gen-response CODE_OK (with-db mc/find-maps coll-name map-values))))
;; Function: insert new element
(defn- insert
[coll-name doc-map error-msg]
(if-not (empty? (with-db mc/insert-and-return coll-name doc-map))
(gen-response CODE_OK (get-all coll-name))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn insert-new
[coll-name body]
(case coll-name
"users" (let [doc-map (user-schema-instance body "new" "")]
(if (empty? ((get-all-by-field coll-name {:username (get doc-map :username)}) :content))
(insert coll-name doc-map "user was not created")
(gen-response CODE_ERROR {:message "error: user already exists"})))
"documents" (let [doc-map (document-schema-instance body "new")]
(if (empty? ((get-all-by-field coll-name {:name (get doc-map :name)}) :content))
(insert coll-name doc-map "video was not uploaded")
(gen-response CODE_ERROR {:message "error: (video) name already exists"})))))
;; Function: update element
(defn- update-elem
[coll-name id data error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/update-by-id coll-name (ObjectId. id) data)
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR (str "error: " error-msg))))
;; Function:
(defn update-by-id
[coll-name id body]
(case coll-name
"users" (update-elem "users" id (user-schema-instance1 body "update" id) "no users found")
"documents" (update-elem "documents" id (document-schema-instance1 body "update") "no documents found")))
;; Function: delete element
(defn- delete
[coll-name id error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/remove-by-id coll-name (ObjectId. id))
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn delete-by-id
[coll-name id]
(case coll-name
"users" (delete coll-name id "no users found")
"documents" (delete coll-name id "no documents found")))
;; Function: LOGIN ==> clojure.lang.PersistentArrayMap
(defn do-login
"returns [clojure.lang.PersistentArrayMap], example: {:code '1', :content ({:rol 'admin', :username 'rsucasas', ...})}
where :content is a clojure.lang.LazySeq"
[username password ip]
(let [res (get-all-by-field-withpsswd "users" {:username username})]
(if-not (empty? res)
(if (password/check password ((first res) :password))
(gen-response CODE_OK (map #(apply dissoc (into {} %) remove-elems-list) res) "jwt" ip)
(gen-response CODE_ERROR {:message "no users found - not valid username / password (1)"}))
(gen-response CODE_ERROR {:message "no users found - not valid username / password (2)"}))))
;; INITIALIZE DATABASE
;; Function: delete all and add new data to new collections
(defn initialize
[]
(log/debug "Initializing database: " config/get-mongodb-host ":" config/get-mongodb-port " " config/get-mongodb-database " ...")
(mc/drop db-conn "users")
(mc/drop db-conn "documents")
(do
(when-not (mc/exists? db-conn "users")
(with-db mc/insert-and-return "users" SUPER-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER2))
(when-not (mc/exists? db-conn "documents")
(with-db mc/insert-and-return "documents" DEFAULT-DOCUMENT)))
(gen-response CODE_OK {:message "database initialized"}))
| true | (ns softcare.db.mongodb
(:use [softcare.globals]
[softcare.db.schemas])
(:require [monger.core :as mg]
[monger.credentials :as mcred]
[monger.collection :as mc]
[cheshire.core :refer [generate-string]]
[cheshire.generate :refer [add-encoder encode-str]]
[softcare.config :as config]
[softcare.logs.logs :as log]
[softcare.utilities.utils :as utils]
[crypto.password.bcrypt :as password])
(:import [org.bson.types ObjectId])
(:import [com.mongodb MongoOptions ServerAddress]))
;; changes behaviour of cheshire/generate-string method ==> http://siscia.github.io/2014/08/28/manage-mongodbs-objectid-and-json/
(add-encoder org.bson.types.ObjectId (fn [s g] (.writeString g (str s))))
;; CONSTANTS - DEFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Database connection:
;; using MongoOptions allows fine-tuning connection parameters,
;; like automatic reconnection (highly recommended for production environment)
;; ==> http://clojuremongodb.info/articles/connecting.html
(def ^:private db-conn
(let [^MongoOptions opts (mg/mongo-options {:threads-allowed-to-block-for-connection-multiplier 300})
^ServerAddress sa (mg/server-address config/get-mongodb-host config/get-mongodb-port)
conn (mg/connect sa opts (mcred/create config/get-mongodb-username config/get-mongodb-database (.toCharArray config/get-mongodb-password)))
db (mg/get-db conn config/get-mongodb-database)]
db))
;; elements to be removed from database queries
(def ^:private remove-elems-list [:password :_id])
;; PRIVATE FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function:
(defn- with-db
[op & args]
(apply op db-conn args))
;; Function:
(defn- get-all-by-field-withpsswd
[coll-name map-values]
(for [x (with-db mc/find-maps coll-name map-values)]
(assoc x :_id (generate-string (get x :_id)))))
;; USER SCHEMA
;; Example: {:name "PI:NAME:<NAME>END_PIpe" :username "pepe" :password "PI:PASSWORD:<PASSWORD>END_PI" :rol "user" :location "Spain"}
(defn- user-schema-instance1
[body-doc operation id]
(let [doc-map (parse-user-schema body-doc)]
(cond
(= operation "update") (assoc doc-map
:password ((first (get-all-by-field-withpsswd "users" {:_id (ObjectId. id)})) :password))
:else {:message "- operation not implemented -"})))
;; DOCUMENT SCHEMA
;; Example: {:name "test" :desc "test" :url "https://www....." :type "video" :tags "test" :stored "false"}
(defn- document-schema-instance1
[body-doc operation]
(let [doc-map (parse-document-schema body-doc)]
(cond
(= operation "update") doc-map
:else {:message "- operation not implemented -"})))
;; MONGODB FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; QUERIES / TRANSACTIONS
;; Function: get all elements from collection / table
(defn get-all
[coll-name]
(case coll-name
"users" (for [x (with-db mc/find-maps coll-name)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password))
"documents" (with-db mc/find-maps coll-name {:type "video"})))
;; Function: get element from collection / table by id
(defn get-by-id
[coll-name id]
(case coll-name
"users" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(dissoc (assoc (with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}) :_id id) :password))
(gen-response CODE_ERROR {:message "warning: no users found"}))
"documents" (if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(gen-response CODE_OK
(with-db mc/find-one-as-map coll-name {:_id (ObjectId. id)}))
(gen-response CODE_ERROR {:message "warning: no videos found"}))))
;; Function:
(defn get-doc-stored-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :stored])
"false")))
;; Function: Example (get-doc-publicid-by-id "56e957c2f06f6b31d884d175")
(defn get-doc-publicid-by-id
[id]
(let [res (get-by-id "documents" id)]
(if (= CODE_OK (res :code))
(get-in res [:content :name])
"NotFound")))
;; Function: get elements by field(s)
(defn get-all-by-field
[coll-name map-values]
(case coll-name
"users" (gen-response CODE_OK
(for [x (with-db mc/find-maps coll-name map-values)]
(dissoc (assoc x :_id (generate-string (get x :_id))) :password)))
"documents" (gen-response CODE_OK (with-db mc/find-maps coll-name map-values))))
;; Function: insert new element
(defn- insert
[coll-name doc-map error-msg]
(if-not (empty? (with-db mc/insert-and-return coll-name doc-map))
(gen-response CODE_OK (get-all coll-name))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn insert-new
[coll-name body]
(case coll-name
"users" (let [doc-map (user-schema-instance body "new" "")]
(if (empty? ((get-all-by-field coll-name {:username (get doc-map :username)}) :content))
(insert coll-name doc-map "user was not created")
(gen-response CODE_ERROR {:message "error: user already exists"})))
"documents" (let [doc-map (document-schema-instance body "new")]
(if (empty? ((get-all-by-field coll-name {:name (get doc-map :name)}) :content))
(insert coll-name doc-map "video was not uploaded")
(gen-response CODE_ERROR {:message "error: (video) name already exists"})))))
;; Function: update element
(defn- update-elem
[coll-name id data error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/update-by-id coll-name (ObjectId. id) data)
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR (str "error: " error-msg))))
;; Function:
(defn update-by-id
[coll-name id body]
(case coll-name
"users" (update-elem "users" id (user-schema-instance1 body "update" id) "no users found")
"documents" (update-elem "documents" id (document-schema-instance1 body "update") "no documents found")))
;; Function: delete element
(defn- delete
[coll-name id error-msg]
(if (>= (with-db mc/count coll-name {:_id (ObjectId. id)}) 1)
(do (with-db mc/remove-by-id coll-name (ObjectId. id))
(gen-response CODE_OK (get-all coll-name)))
(gen-response CODE_ERROR {:message (str "error: " error-msg)})))
;; Function:
(defn delete-by-id
[coll-name id]
(case coll-name
"users" (delete coll-name id "no users found")
"documents" (delete coll-name id "no documents found")))
;; Function: LOGIN ==> clojure.lang.PersistentArrayMap
(defn do-login
"returns [clojure.lang.PersistentArrayMap], example: {:code '1', :content ({:rol 'admin', :username 'rsucasas', ...})}
where :content is a clojure.lang.LazySeq"
[username password ip]
(let [res (get-all-by-field-withpsswd "users" {:username username})]
(if-not (empty? res)
(if (password/check password ((first res) :password))
(gen-response CODE_OK (map #(apply dissoc (into {} %) remove-elems-list) res) "jwt" ip)
(gen-response CODE_ERROR {:message "no users found - not valid username / password (1)"}))
(gen-response CODE_ERROR {:message "no users found - not valid username / password (2)"}))))
;; INITIALIZE DATABASE
;; Function: delete all and add new data to new collections
(defn initialize
[]
(log/debug "Initializing database: " config/get-mongodb-host ":" config/get-mongodb-port " " config/get-mongodb-database " ...")
(mc/drop db-conn "users")
(mc/drop db-conn "documents")
(do
(when-not (mc/exists? db-conn "users")
(with-db mc/insert-and-return "users" SUPER-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER)
(with-db mc/insert-and-return "users" DEFAULT-ADMIN-USER2))
(when-not (mc/exists? db-conn "documents")
(with-db mc/insert-and-return "documents" DEFAULT-DOCUMENT)))
(gen-response CODE_OK {:message "database initialized"}))
|
[
{
"context": "erver-fixture [f]\n (redis/with-server\n {:host \"127.0.0.1\"\n :port 6379\n :db 15}\n ;; String value\n ",
"end": 192,
"score": 0.9995393753051758,
"start": 183,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "dis/set \"object_4\" \"four\")\n (redis/set \"name_1\" \"Derek\")\n (redis/set \"name_2\" \"Charlie\")\n (redis/set \"",
"end": 10152,
"score": 0.9996881484985352,
"start": 10147,
"tag": "NAME",
"value": "Derek"
},
{
"context": "edis/set \"name_1\" \"Derek\")\n (redis/set \"name_2\" \"Charlie\")\n (redis/set \"name_3\" \"Bob\")\n (redis/set \"name",
"end": 10185,
"score": 0.9996598958969116,
"start": 10178,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "is/set \"name_2\" \"Charlie\")\n (redis/set \"name_3\" \"Bob\")\n (redis/set \"name_4\" \"Alice\")\n\n (is (= [\"one\"",
"end": 10214,
"score": 0.9998641014099121,
"start": 10211,
"tag": "NAME",
"value": "Bob"
},
{
"context": "(redis/set \"name_3\" \"Bob\")\n (redis/set \"name_4\" \"Alice\")\n\n (is (= [\"one\" \"two\" \"three\"]\n (redis",
"end": 10245,
"score": 0.9998688697814941,
"start": 10240,
"tag": "NAME",
"value": "Alice"
}
] | client-libraries/clojure/src/redis/tests.clj | lixifun/redis-1.0-read | 60 | (ns redis.tests
(:refer-clojure :exclude [get set keys type sort])
(:require redis)
(:use [clojure.contrib.test-is]))
(defn server-fixture [f]
(redis/with-server
{:host "127.0.0.1"
:port 6379
:db 15}
;; String value
(redis/set "foo" "bar")
;; List with three items
(redis/rpush "list" "one")
(redis/rpush "list" "two")
(redis/rpush "list" "three")
;; Set with three members
(redis/sadd "set" "one")
(redis/sadd "set" "two")
(redis/sadd "set" "three")
(f)
(redis/flushdb)))
(use-fixtures :each server-fixture)
(deftest ping
(is (= "PONG" (redis/ping))))
(deftest set
(redis/set "bar" "foo")
(is (= "foo" (redis/get "bar")))
(redis/set "foo" "baz")
(is (= "baz" (redis/get "foo"))))
(deftest get
(is (= nil (redis/get "bar")))
(is (= "bar" (redis/get "foo"))))
(deftest getset
(is (= nil (redis/getset "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= "bar" (redis/getset "foo" "baz")))
(is (= "baz" (redis/get "foo"))))
(deftest mget
(is (= [nil] (redis/mget "bar")))
(redis/set "bar" "baz")
(redis/set "baz" "buz")
(is (= ["bar"] (redis/mget "foo")))
(is (= ["bar" "baz"] (redis/mget "foo" "bar")))
(is (= ["bar" "baz" "buz"] (redis/mget "foo" "bar" "baz")))
(is (= ["bar" nil "buz"] (redis/mget "foo" "bra" "baz")))
)
(deftest setnx
(is (= true (redis/setnx "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= false (redis/setnx "foo" "baz")))
(is (= "bar" (redis/get "foo"))))
(deftest incr
(is (= 1 (redis/incr "nonexistent")))
(is (= 1 (redis/incr "foo")))
(is (= 2 (redis/incr "foo"))))
(deftest incrby
(is (= 42 (redis/incrby "nonexistent" 42)))
(is (= 0 (redis/incrby "foo" 0)))
(is (= 5 (redis/incrby "foo" 5))))
(deftest decr
(is (= -1 (redis/decr "nonexistent")))
(is (= -1 (redis/decr "foo")))
(is (= -2 (redis/decr "foo"))))
(deftest decrby
(is (= -42 (redis/decrby "nonexistent" 42)))
(is (= 0 (redis/decrby "foo" 0)))
(is (= -5 (redis/decrby "foo" 5))))
(deftest exists
(is (= true (redis/exists "foo")))
(is (= false (redis/exists "nonexistent"))))
(deftest del
(is (= false (redis/del "nonexistent")))
(is (= true (redis/del "foo")))
(is (= nil (redis/get "foo"))))
(deftest type
(is (= :none (redis/type "nonexistent")))
(is (= :string (redis/type "foo")))
(is (= :list (redis/type "list")))
(is (= :set (redis/type "set"))))
(deftest keys
(is (= nil (redis/keys "a*")))
(is (= ["foo"] (redis/keys "f*")))
(is (= ["foo"] (redis/keys "f?o")))
(redis/set "fuu" "baz")
(is (= #{"foo" "fuu"} (clojure.core/set (redis/keys "f*")))))
(deftest randomkey
(redis/flushdb)
(redis/set "foo" "bar")
(is (= "foo" (redis/randomkey)))
(redis/flushdb)
(is (= "" (redis/randomkey))))
(deftest rename
(is (thrown? Exception (redis/rename "foo" "foo")))
(is (thrown? Exception (redis/rename "nonexistent" "foo")))
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
)
(deftest renamenx
(is (thrown? Exception (redis/renamenx "foo" "foo")))
(is (thrown? Exception (redis/renamenx "nonexistent" "foo")))
(is (= true (redis/renamenx "foo" "bar")))
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(is (= false (redis/renamenx "foo" "bar")))
)
(deftest dbsize
(let [size-before (redis/dbsize)]
(redis/set "anewkey" "value")
(let [size-after (redis/dbsize)]
(is (= size-after
(+ 1 size-before))))))
(deftest expire
(is (= true (redis/expire "foo" 1)))
(Thread/sleep 2000)
(is (= false (redis/exists "foo")))
(redis/set "foo" "bar")
(is (= true (redis/expire "foo" 20)))
(is (= false (redis/expire "foo" 10)))
(is (= false (redis/expire "nonexistent" 42)))
)
(deftest ttl
(is (= -1 (redis/ttl "nonexistent")))
(is (= -1 (redis/ttl "foo")))
(redis/expire "foo" 42)
(is (< 40 (redis/ttl "foo"))))
;;
;; List commands
;;
(deftest rpush
(is (thrown? Exception (redis/rpush "foo")))
(redis/rpush "newlist" "one")
(is (= 1 (redis/llen "newlist")))
(is (= "one" (redis/lindex "newlist" 0)))
(redis/del "newlist")
(redis/rpush "list" "item")
(is (= "item" (redis/rpop "list"))))
(deftest lpush
(is (thrown? Exception (redis/lpush "foo")))
(redis/lpush "newlist" "item")
(is (= 1 (redis/llen "newlist")))
(is (= "item" (redis/lindex "newlist" 0)))
(redis/lpush "list" "item")
(is (= "item" (redis/lpop "list"))))
(deftest llen
(is (thrown? Exception (redis/llen "foo")))
(is (= 0 (redis/llen "newlist")))
(is (= 3 (redis/llen "list"))))
(deftest lrange
(is (thrown? Exception (redis/lrange "foo" 0 1)))
(is (= nil (redis/lrange "newlist" 0 42)))
(is (= ["one"] (redis/lrange "list" 0 0)))
(is (= ["three"] (redis/lrange "list" -1 -1)))
(is (= ["one" "two"] (redis/lrange "list" 0 1)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 2)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 42)))
(is (= [] (redis/lrange "list" 42 0)))
)
;; TBD
(deftest ltrim
(is (thrown? Exception (redis/ltrim "foo" 0 0))))
(deftest lindex
(is (thrown? Exception (redis/lindex "foo" 0)))
(is (= nil (redis/lindex "list" 42)))
(is (= nil (redis/lindex "list" -4)))
(is (= "one" (redis/lindex "list" 0)))
(is (= "three" (redis/lindex "list" 2)))
(is (= "three" (redis/lindex "list" -1))))
(deftest lset
(is (thrown? Exception (redis/lset "foo" 0 "bar")))
(is (thrown? Exception (redis/lset "list" 42 "value")))
(redis/lset "list" 0 "test")
(is (= "test" (redis/lindex "list" 0)))
(redis/lset "list" 2 "test2")
(is (= "test2" (redis/lindex "list" 2)))
(redis/lset "list" -1 "test3")
(is (= "test3" (redis/lindex "list" 2))))
(deftest lrem
(is (thrown? Exception (redis/lrem "foo" 0 "bar")))
(is (= 0 (redis/lrem "newlist" 0 "")))
(is (= 1 (redis/lrem "list" 1 "two")))
(is (= 1 (redis/lrem "list" 42 "three")))
(is (= 1 (redis/llen "list"))))
(deftest lpop
(is (thrown? Exception (redis/lpop "foo")))
(is (= nil (redis/lpop "newlist")))
(is (= "one" (redis/lpop "list")))
(is (= 2 (redis/llen "list"))))
(deftest rpop
(is (thrown? Exception (redis/rpop "foo")))
(is (= nil (redis/rpop "newlist")))
(is (= "three" (redis/rpop "list")))
(is (= 2 (redis/llen "list"))))
;;
;; Set commands
;;
(deftest sadd
(is (thrown? Exception (redis/sadd "foo" "bar")))
(is (= true (redis/sadd "newset" "member")))
(is (= true (redis/sismember "newset" "member")))
(is (= false (redis/sadd "set" "two")))
(is (= true (redis/sadd "set" "four")))
(is (= true (redis/sismember "set" "four"))))
(deftest srem
(is (thrown? Exception (redis/srem "foo" "bar")))
(is (= false (redis/srem "newset" "member")))
(is (= true (redis/srem "set" "two")))
(is (= false (redis/sismember "set" "two")))
(is (= false (redis/srem "set" "blahonga"))))
(deftest spop
(is (thrown? Exception (redis/spop "foo" "bar")))
(is (= nil (redis/spop "newset")))
(is (contains? #{"one" "two" "three"} (redis/spop "set"))))
(deftest smove
(is (thrown? Exception (redis/smove "foo" "set" "one")))
(is (thrown? Exception (redis/smove "set" "foo" "one")))
(redis/sadd "set1" "two")
(is (= false (redis/smove "set" "set1" "four")))
(is (= #{"two"} (redis/smembers "set1")))
(is (= true (redis/smove "set" "set1" "one")))
(is (= #{"one" "two"} (redis/smembers "set1"))))
(deftest scard
(is (thrown? Exception (redis/scard "foo")))
(is (= 3 (redis/scard "set"))))
(deftest sismember
(is (thrown? Exception (redis/sismember "foo" "bar")))
(is (= false (redis/sismember "set" "blahonga")))
(is (= true (redis/sismember "set" "two"))))
(deftest sinter
(is (thrown? Exception (redis/sinter "foo" "set")))
(is (= #{} (redis/sinter "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sinter "set")))
(is (= #{"one"} (redis/sinter "set" "set1")))
(is (= #{} (redis/sinter "set" "set1" "nonexistent"))))
(deftest sinterstore
(redis/sinterstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sinterstore "newset" "set" "set1")
(is (= #{"one"} (redis/smembers "newset"))))
(deftest sunion
(is (thrown? Exception (redis/sunion "foo" "set")))
(is (= #{} (redis/sunion "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sunion "set")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1" "nonexistent"))))
(deftest sunionstore
(redis/sunionstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sunionstore "newset" "set" "set1")
(is (= #{"one" "two" "three" "four"} (redis/smembers "newset"))))
(deftest sdiff
(is (thrown? Exception (redis/sdiff "foo" "set")))
(is (= #{} (redis/sdiff "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sdiff "set")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1" "nonexistent"))))
(deftest sdiffstore
(redis/sdiffstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sdiffstore "newset" "set" "set1")
(is (= #{"two" "three"} (redis/smembers "newset"))))
(deftest smembers
(is (thrown? Exception (redis/smembers "foo")))
(is (= #{"one" "two" "three"} (redis/smembers "set"))))
;;
;; Sorting
;;
(deftest sort
(redis/lpush "ids" 1)
(redis/lpush "ids" 4)
(redis/lpush "ids" 2)
(redis/lpush "ids" 3)
(redis/set "object_1" "one")
(redis/set "object_2" "two")
(redis/set "object_3" "three")
(redis/set "object_4" "four")
(redis/set "name_1" "Derek")
(redis/set "name_2" "Charlie")
(redis/set "name_3" "Bob")
(redis/set "name_4" "Alice")
(is (= ["one" "two" "three"]
(redis/sort "list")))
(is (= ["one" "three" "two"]
(redis/sort "list" :alpha)))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids")))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids" :asc)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :desc)))
(is (= ["1" "2"]
(redis/sort "ids" :asc :limit 0 2)))
(is (= ["4" "3"]
(redis/sort "ids" :desc :limit 0 2)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :by "name_*" :alpha)))
(is (= ["one" "two" "three" "four"]
(redis/sort "ids" :get "object_*")))
(is (= ["one" "two"]
(redis/sort "ids" :by "name_*" :alpha :limit 0 2 :desc :get "object_*"))))
;;
;; Multiple database handling commands
;;
(deftest select
(redis/select 0)
(is (= nil (redis/get "akeythat_probably_doesnotexsistindb0"))))
(deftest flushdb
(redis/flushdb)
(is (= 0 (redis/dbsize))))
;;
;; Persistence commands
;;
(deftest save
(redis/save))
(deftest bgsave
(redis/bgsave))
(deftest lastsave
(let [ages-ago (new java.util.Date (long 1))]
(is (.before ages-ago (redis/lastsave)))))
| 57200 | (ns redis.tests
(:refer-clojure :exclude [get set keys type sort])
(:require redis)
(:use [clojure.contrib.test-is]))
(defn server-fixture [f]
(redis/with-server
{:host "127.0.0.1"
:port 6379
:db 15}
;; String value
(redis/set "foo" "bar")
;; List with three items
(redis/rpush "list" "one")
(redis/rpush "list" "two")
(redis/rpush "list" "three")
;; Set with three members
(redis/sadd "set" "one")
(redis/sadd "set" "two")
(redis/sadd "set" "three")
(f)
(redis/flushdb)))
(use-fixtures :each server-fixture)
(deftest ping
(is (= "PONG" (redis/ping))))
(deftest set
(redis/set "bar" "foo")
(is (= "foo" (redis/get "bar")))
(redis/set "foo" "baz")
(is (= "baz" (redis/get "foo"))))
(deftest get
(is (= nil (redis/get "bar")))
(is (= "bar" (redis/get "foo"))))
(deftest getset
(is (= nil (redis/getset "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= "bar" (redis/getset "foo" "baz")))
(is (= "baz" (redis/get "foo"))))
(deftest mget
(is (= [nil] (redis/mget "bar")))
(redis/set "bar" "baz")
(redis/set "baz" "buz")
(is (= ["bar"] (redis/mget "foo")))
(is (= ["bar" "baz"] (redis/mget "foo" "bar")))
(is (= ["bar" "baz" "buz"] (redis/mget "foo" "bar" "baz")))
(is (= ["bar" nil "buz"] (redis/mget "foo" "bra" "baz")))
)
(deftest setnx
(is (= true (redis/setnx "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= false (redis/setnx "foo" "baz")))
(is (= "bar" (redis/get "foo"))))
(deftest incr
(is (= 1 (redis/incr "nonexistent")))
(is (= 1 (redis/incr "foo")))
(is (= 2 (redis/incr "foo"))))
(deftest incrby
(is (= 42 (redis/incrby "nonexistent" 42)))
(is (= 0 (redis/incrby "foo" 0)))
(is (= 5 (redis/incrby "foo" 5))))
(deftest decr
(is (= -1 (redis/decr "nonexistent")))
(is (= -1 (redis/decr "foo")))
(is (= -2 (redis/decr "foo"))))
(deftest decrby
(is (= -42 (redis/decrby "nonexistent" 42)))
(is (= 0 (redis/decrby "foo" 0)))
(is (= -5 (redis/decrby "foo" 5))))
(deftest exists
(is (= true (redis/exists "foo")))
(is (= false (redis/exists "nonexistent"))))
(deftest del
(is (= false (redis/del "nonexistent")))
(is (= true (redis/del "foo")))
(is (= nil (redis/get "foo"))))
(deftest type
(is (= :none (redis/type "nonexistent")))
(is (= :string (redis/type "foo")))
(is (= :list (redis/type "list")))
(is (= :set (redis/type "set"))))
(deftest keys
(is (= nil (redis/keys "a*")))
(is (= ["foo"] (redis/keys "f*")))
(is (= ["foo"] (redis/keys "f?o")))
(redis/set "fuu" "baz")
(is (= #{"foo" "fuu"} (clojure.core/set (redis/keys "f*")))))
(deftest randomkey
(redis/flushdb)
(redis/set "foo" "bar")
(is (= "foo" (redis/randomkey)))
(redis/flushdb)
(is (= "" (redis/randomkey))))
(deftest rename
(is (thrown? Exception (redis/rename "foo" "foo")))
(is (thrown? Exception (redis/rename "nonexistent" "foo")))
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
)
(deftest renamenx
(is (thrown? Exception (redis/renamenx "foo" "foo")))
(is (thrown? Exception (redis/renamenx "nonexistent" "foo")))
(is (= true (redis/renamenx "foo" "bar")))
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(is (= false (redis/renamenx "foo" "bar")))
)
(deftest dbsize
(let [size-before (redis/dbsize)]
(redis/set "anewkey" "value")
(let [size-after (redis/dbsize)]
(is (= size-after
(+ 1 size-before))))))
(deftest expire
(is (= true (redis/expire "foo" 1)))
(Thread/sleep 2000)
(is (= false (redis/exists "foo")))
(redis/set "foo" "bar")
(is (= true (redis/expire "foo" 20)))
(is (= false (redis/expire "foo" 10)))
(is (= false (redis/expire "nonexistent" 42)))
)
(deftest ttl
(is (= -1 (redis/ttl "nonexistent")))
(is (= -1 (redis/ttl "foo")))
(redis/expire "foo" 42)
(is (< 40 (redis/ttl "foo"))))
;;
;; List commands
;;
(deftest rpush
(is (thrown? Exception (redis/rpush "foo")))
(redis/rpush "newlist" "one")
(is (= 1 (redis/llen "newlist")))
(is (= "one" (redis/lindex "newlist" 0)))
(redis/del "newlist")
(redis/rpush "list" "item")
(is (= "item" (redis/rpop "list"))))
(deftest lpush
(is (thrown? Exception (redis/lpush "foo")))
(redis/lpush "newlist" "item")
(is (= 1 (redis/llen "newlist")))
(is (= "item" (redis/lindex "newlist" 0)))
(redis/lpush "list" "item")
(is (= "item" (redis/lpop "list"))))
(deftest llen
(is (thrown? Exception (redis/llen "foo")))
(is (= 0 (redis/llen "newlist")))
(is (= 3 (redis/llen "list"))))
(deftest lrange
(is (thrown? Exception (redis/lrange "foo" 0 1)))
(is (= nil (redis/lrange "newlist" 0 42)))
(is (= ["one"] (redis/lrange "list" 0 0)))
(is (= ["three"] (redis/lrange "list" -1 -1)))
(is (= ["one" "two"] (redis/lrange "list" 0 1)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 2)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 42)))
(is (= [] (redis/lrange "list" 42 0)))
)
;; TBD
(deftest ltrim
(is (thrown? Exception (redis/ltrim "foo" 0 0))))
(deftest lindex
(is (thrown? Exception (redis/lindex "foo" 0)))
(is (= nil (redis/lindex "list" 42)))
(is (= nil (redis/lindex "list" -4)))
(is (= "one" (redis/lindex "list" 0)))
(is (= "three" (redis/lindex "list" 2)))
(is (= "three" (redis/lindex "list" -1))))
(deftest lset
(is (thrown? Exception (redis/lset "foo" 0 "bar")))
(is (thrown? Exception (redis/lset "list" 42 "value")))
(redis/lset "list" 0 "test")
(is (= "test" (redis/lindex "list" 0)))
(redis/lset "list" 2 "test2")
(is (= "test2" (redis/lindex "list" 2)))
(redis/lset "list" -1 "test3")
(is (= "test3" (redis/lindex "list" 2))))
(deftest lrem
(is (thrown? Exception (redis/lrem "foo" 0 "bar")))
(is (= 0 (redis/lrem "newlist" 0 "")))
(is (= 1 (redis/lrem "list" 1 "two")))
(is (= 1 (redis/lrem "list" 42 "three")))
(is (= 1 (redis/llen "list"))))
(deftest lpop
(is (thrown? Exception (redis/lpop "foo")))
(is (= nil (redis/lpop "newlist")))
(is (= "one" (redis/lpop "list")))
(is (= 2 (redis/llen "list"))))
(deftest rpop
(is (thrown? Exception (redis/rpop "foo")))
(is (= nil (redis/rpop "newlist")))
(is (= "three" (redis/rpop "list")))
(is (= 2 (redis/llen "list"))))
;;
;; Set commands
;;
(deftest sadd
(is (thrown? Exception (redis/sadd "foo" "bar")))
(is (= true (redis/sadd "newset" "member")))
(is (= true (redis/sismember "newset" "member")))
(is (= false (redis/sadd "set" "two")))
(is (= true (redis/sadd "set" "four")))
(is (= true (redis/sismember "set" "four"))))
(deftest srem
(is (thrown? Exception (redis/srem "foo" "bar")))
(is (= false (redis/srem "newset" "member")))
(is (= true (redis/srem "set" "two")))
(is (= false (redis/sismember "set" "two")))
(is (= false (redis/srem "set" "blahonga"))))
(deftest spop
(is (thrown? Exception (redis/spop "foo" "bar")))
(is (= nil (redis/spop "newset")))
(is (contains? #{"one" "two" "three"} (redis/spop "set"))))
(deftest smove
(is (thrown? Exception (redis/smove "foo" "set" "one")))
(is (thrown? Exception (redis/smove "set" "foo" "one")))
(redis/sadd "set1" "two")
(is (= false (redis/smove "set" "set1" "four")))
(is (= #{"two"} (redis/smembers "set1")))
(is (= true (redis/smove "set" "set1" "one")))
(is (= #{"one" "two"} (redis/smembers "set1"))))
(deftest scard
(is (thrown? Exception (redis/scard "foo")))
(is (= 3 (redis/scard "set"))))
(deftest sismember
(is (thrown? Exception (redis/sismember "foo" "bar")))
(is (= false (redis/sismember "set" "blahonga")))
(is (= true (redis/sismember "set" "two"))))
(deftest sinter
(is (thrown? Exception (redis/sinter "foo" "set")))
(is (= #{} (redis/sinter "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sinter "set")))
(is (= #{"one"} (redis/sinter "set" "set1")))
(is (= #{} (redis/sinter "set" "set1" "nonexistent"))))
(deftest sinterstore
(redis/sinterstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sinterstore "newset" "set" "set1")
(is (= #{"one"} (redis/smembers "newset"))))
(deftest sunion
(is (thrown? Exception (redis/sunion "foo" "set")))
(is (= #{} (redis/sunion "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sunion "set")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1" "nonexistent"))))
(deftest sunionstore
(redis/sunionstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sunionstore "newset" "set" "set1")
(is (= #{"one" "two" "three" "four"} (redis/smembers "newset"))))
(deftest sdiff
(is (thrown? Exception (redis/sdiff "foo" "set")))
(is (= #{} (redis/sdiff "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sdiff "set")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1" "nonexistent"))))
(deftest sdiffstore
(redis/sdiffstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sdiffstore "newset" "set" "set1")
(is (= #{"two" "three"} (redis/smembers "newset"))))
(deftest smembers
(is (thrown? Exception (redis/smembers "foo")))
(is (= #{"one" "two" "three"} (redis/smembers "set"))))
;;
;; Sorting
;;
(deftest sort
(redis/lpush "ids" 1)
(redis/lpush "ids" 4)
(redis/lpush "ids" 2)
(redis/lpush "ids" 3)
(redis/set "object_1" "one")
(redis/set "object_2" "two")
(redis/set "object_3" "three")
(redis/set "object_4" "four")
(redis/set "name_1" "<NAME>")
(redis/set "name_2" "<NAME>")
(redis/set "name_3" "<NAME>")
(redis/set "name_4" "<NAME>")
(is (= ["one" "two" "three"]
(redis/sort "list")))
(is (= ["one" "three" "two"]
(redis/sort "list" :alpha)))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids")))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids" :asc)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :desc)))
(is (= ["1" "2"]
(redis/sort "ids" :asc :limit 0 2)))
(is (= ["4" "3"]
(redis/sort "ids" :desc :limit 0 2)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :by "name_*" :alpha)))
(is (= ["one" "two" "three" "four"]
(redis/sort "ids" :get "object_*")))
(is (= ["one" "two"]
(redis/sort "ids" :by "name_*" :alpha :limit 0 2 :desc :get "object_*"))))
;;
;; Multiple database handling commands
;;
(deftest select
(redis/select 0)
(is (= nil (redis/get "akeythat_probably_doesnotexsistindb0"))))
(deftest flushdb
(redis/flushdb)
(is (= 0 (redis/dbsize))))
;;
;; Persistence commands
;;
(deftest save
(redis/save))
(deftest bgsave
(redis/bgsave))
(deftest lastsave
(let [ages-ago (new java.util.Date (long 1))]
(is (.before ages-ago (redis/lastsave)))))
| true | (ns redis.tests
(:refer-clojure :exclude [get set keys type sort])
(:require redis)
(:use [clojure.contrib.test-is]))
(defn server-fixture [f]
(redis/with-server
{:host "127.0.0.1"
:port 6379
:db 15}
;; String value
(redis/set "foo" "bar")
;; List with three items
(redis/rpush "list" "one")
(redis/rpush "list" "two")
(redis/rpush "list" "three")
;; Set with three members
(redis/sadd "set" "one")
(redis/sadd "set" "two")
(redis/sadd "set" "three")
(f)
(redis/flushdb)))
(use-fixtures :each server-fixture)
(deftest ping
(is (= "PONG" (redis/ping))))
(deftest set
(redis/set "bar" "foo")
(is (= "foo" (redis/get "bar")))
(redis/set "foo" "baz")
(is (= "baz" (redis/get "foo"))))
(deftest get
(is (= nil (redis/get "bar")))
(is (= "bar" (redis/get "foo"))))
(deftest getset
(is (= nil (redis/getset "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= "bar" (redis/getset "foo" "baz")))
(is (= "baz" (redis/get "foo"))))
(deftest mget
(is (= [nil] (redis/mget "bar")))
(redis/set "bar" "baz")
(redis/set "baz" "buz")
(is (= ["bar"] (redis/mget "foo")))
(is (= ["bar" "baz"] (redis/mget "foo" "bar")))
(is (= ["bar" "baz" "buz"] (redis/mget "foo" "bar" "baz")))
(is (= ["bar" nil "buz"] (redis/mget "foo" "bra" "baz")))
)
(deftest setnx
(is (= true (redis/setnx "bar" "foo")))
(is (= "foo" (redis/get "bar")))
(is (= false (redis/setnx "foo" "baz")))
(is (= "bar" (redis/get "foo"))))
(deftest incr
(is (= 1 (redis/incr "nonexistent")))
(is (= 1 (redis/incr "foo")))
(is (= 2 (redis/incr "foo"))))
(deftest incrby
(is (= 42 (redis/incrby "nonexistent" 42)))
(is (= 0 (redis/incrby "foo" 0)))
(is (= 5 (redis/incrby "foo" 5))))
(deftest decr
(is (= -1 (redis/decr "nonexistent")))
(is (= -1 (redis/decr "foo")))
(is (= -2 (redis/decr "foo"))))
(deftest decrby
(is (= -42 (redis/decrby "nonexistent" 42)))
(is (= 0 (redis/decrby "foo" 0)))
(is (= -5 (redis/decrby "foo" 5))))
(deftest exists
(is (= true (redis/exists "foo")))
(is (= false (redis/exists "nonexistent"))))
(deftest del
(is (= false (redis/del "nonexistent")))
(is (= true (redis/del "foo")))
(is (= nil (redis/get "foo"))))
(deftest type
(is (= :none (redis/type "nonexistent")))
(is (= :string (redis/type "foo")))
(is (= :list (redis/type "list")))
(is (= :set (redis/type "set"))))
(deftest keys
(is (= nil (redis/keys "a*")))
(is (= ["foo"] (redis/keys "f*")))
(is (= ["foo"] (redis/keys "f?o")))
(redis/set "fuu" "baz")
(is (= #{"foo" "fuu"} (clojure.core/set (redis/keys "f*")))))
(deftest randomkey
(redis/flushdb)
(redis/set "foo" "bar")
(is (= "foo" (redis/randomkey)))
(redis/flushdb)
(is (= "" (redis/randomkey))))
(deftest rename
(is (thrown? Exception (redis/rename "foo" "foo")))
(is (thrown? Exception (redis/rename "nonexistent" "foo")))
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(redis/rename "foo" "bar")
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
)
(deftest renamenx
(is (thrown? Exception (redis/renamenx "foo" "foo")))
(is (thrown? Exception (redis/renamenx "nonexistent" "foo")))
(is (= true (redis/renamenx "foo" "bar")))
(is (= "bar" (redis/get "bar")))
(is (= nil (redis/get "foo")))
(redis/set "foo" "bar")
(redis/set "bar" "baz")
(is (= false (redis/renamenx "foo" "bar")))
)
(deftest dbsize
(let [size-before (redis/dbsize)]
(redis/set "anewkey" "value")
(let [size-after (redis/dbsize)]
(is (= size-after
(+ 1 size-before))))))
(deftest expire
(is (= true (redis/expire "foo" 1)))
(Thread/sleep 2000)
(is (= false (redis/exists "foo")))
(redis/set "foo" "bar")
(is (= true (redis/expire "foo" 20)))
(is (= false (redis/expire "foo" 10)))
(is (= false (redis/expire "nonexistent" 42)))
)
(deftest ttl
(is (= -1 (redis/ttl "nonexistent")))
(is (= -1 (redis/ttl "foo")))
(redis/expire "foo" 42)
(is (< 40 (redis/ttl "foo"))))
;;
;; List commands
;;
(deftest rpush
(is (thrown? Exception (redis/rpush "foo")))
(redis/rpush "newlist" "one")
(is (= 1 (redis/llen "newlist")))
(is (= "one" (redis/lindex "newlist" 0)))
(redis/del "newlist")
(redis/rpush "list" "item")
(is (= "item" (redis/rpop "list"))))
(deftest lpush
(is (thrown? Exception (redis/lpush "foo")))
(redis/lpush "newlist" "item")
(is (= 1 (redis/llen "newlist")))
(is (= "item" (redis/lindex "newlist" 0)))
(redis/lpush "list" "item")
(is (= "item" (redis/lpop "list"))))
(deftest llen
(is (thrown? Exception (redis/llen "foo")))
(is (= 0 (redis/llen "newlist")))
(is (= 3 (redis/llen "list"))))
(deftest lrange
(is (thrown? Exception (redis/lrange "foo" 0 1)))
(is (= nil (redis/lrange "newlist" 0 42)))
(is (= ["one"] (redis/lrange "list" 0 0)))
(is (= ["three"] (redis/lrange "list" -1 -1)))
(is (= ["one" "two"] (redis/lrange "list" 0 1)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 2)))
(is (= ["one" "two" "three"] (redis/lrange "list" 0 42)))
(is (= [] (redis/lrange "list" 42 0)))
)
;; TBD
(deftest ltrim
(is (thrown? Exception (redis/ltrim "foo" 0 0))))
(deftest lindex
(is (thrown? Exception (redis/lindex "foo" 0)))
(is (= nil (redis/lindex "list" 42)))
(is (= nil (redis/lindex "list" -4)))
(is (= "one" (redis/lindex "list" 0)))
(is (= "three" (redis/lindex "list" 2)))
(is (= "three" (redis/lindex "list" -1))))
(deftest lset
(is (thrown? Exception (redis/lset "foo" 0 "bar")))
(is (thrown? Exception (redis/lset "list" 42 "value")))
(redis/lset "list" 0 "test")
(is (= "test" (redis/lindex "list" 0)))
(redis/lset "list" 2 "test2")
(is (= "test2" (redis/lindex "list" 2)))
(redis/lset "list" -1 "test3")
(is (= "test3" (redis/lindex "list" 2))))
(deftest lrem
(is (thrown? Exception (redis/lrem "foo" 0 "bar")))
(is (= 0 (redis/lrem "newlist" 0 "")))
(is (= 1 (redis/lrem "list" 1 "two")))
(is (= 1 (redis/lrem "list" 42 "three")))
(is (= 1 (redis/llen "list"))))
(deftest lpop
(is (thrown? Exception (redis/lpop "foo")))
(is (= nil (redis/lpop "newlist")))
(is (= "one" (redis/lpop "list")))
(is (= 2 (redis/llen "list"))))
(deftest rpop
(is (thrown? Exception (redis/rpop "foo")))
(is (= nil (redis/rpop "newlist")))
(is (= "three" (redis/rpop "list")))
(is (= 2 (redis/llen "list"))))
;;
;; Set commands
;;
(deftest sadd
(is (thrown? Exception (redis/sadd "foo" "bar")))
(is (= true (redis/sadd "newset" "member")))
(is (= true (redis/sismember "newset" "member")))
(is (= false (redis/sadd "set" "two")))
(is (= true (redis/sadd "set" "four")))
(is (= true (redis/sismember "set" "four"))))
(deftest srem
(is (thrown? Exception (redis/srem "foo" "bar")))
(is (= false (redis/srem "newset" "member")))
(is (= true (redis/srem "set" "two")))
(is (= false (redis/sismember "set" "two")))
(is (= false (redis/srem "set" "blahonga"))))
(deftest spop
(is (thrown? Exception (redis/spop "foo" "bar")))
(is (= nil (redis/spop "newset")))
(is (contains? #{"one" "two" "three"} (redis/spop "set"))))
(deftest smove
(is (thrown? Exception (redis/smove "foo" "set" "one")))
(is (thrown? Exception (redis/smove "set" "foo" "one")))
(redis/sadd "set1" "two")
(is (= false (redis/smove "set" "set1" "four")))
(is (= #{"two"} (redis/smembers "set1")))
(is (= true (redis/smove "set" "set1" "one")))
(is (= #{"one" "two"} (redis/smembers "set1"))))
(deftest scard
(is (thrown? Exception (redis/scard "foo")))
(is (= 3 (redis/scard "set"))))
(deftest sismember
(is (thrown? Exception (redis/sismember "foo" "bar")))
(is (= false (redis/sismember "set" "blahonga")))
(is (= true (redis/sismember "set" "two"))))
(deftest sinter
(is (thrown? Exception (redis/sinter "foo" "set")))
(is (= #{} (redis/sinter "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sinter "set")))
(is (= #{"one"} (redis/sinter "set" "set1")))
(is (= #{} (redis/sinter "set" "set1" "nonexistent"))))
(deftest sinterstore
(redis/sinterstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sinterstore "newset" "set" "set1")
(is (= #{"one"} (redis/smembers "newset"))))
(deftest sunion
(is (thrown? Exception (redis/sunion "foo" "set")))
(is (= #{} (redis/sunion "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sunion "set")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1")))
(is (= #{"one" "two" "three" "four"} (redis/sunion "set" "set1" "nonexistent"))))
(deftest sunionstore
(redis/sunionstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sunionstore "newset" "set" "set1")
(is (= #{"one" "two" "three" "four"} (redis/smembers "newset"))))
(deftest sdiff
(is (thrown? Exception (redis/sdiff "foo" "set")))
(is (= #{} (redis/sdiff "nonexistent")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(is (= #{"one" "two" "three"} (redis/sdiff "set")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1")))
(is (= #{"two" "three"} (redis/sdiff "set" "set1" "nonexistent"))))
(deftest sdiffstore
(redis/sdiffstore "foo" "set")
(is (= #{"one" "two" "three"} (redis/smembers "foo")))
(redis/sadd "set1" "one")
(redis/sadd "set1" "four")
(redis/sdiffstore "newset" "set" "set1")
(is (= #{"two" "three"} (redis/smembers "newset"))))
(deftest smembers
(is (thrown? Exception (redis/smembers "foo")))
(is (= #{"one" "two" "three"} (redis/smembers "set"))))
;;
;; Sorting
;;
(deftest sort
(redis/lpush "ids" 1)
(redis/lpush "ids" 4)
(redis/lpush "ids" 2)
(redis/lpush "ids" 3)
(redis/set "object_1" "one")
(redis/set "object_2" "two")
(redis/set "object_3" "three")
(redis/set "object_4" "four")
(redis/set "name_1" "PI:NAME:<NAME>END_PI")
(redis/set "name_2" "PI:NAME:<NAME>END_PI")
(redis/set "name_3" "PI:NAME:<NAME>END_PI")
(redis/set "name_4" "PI:NAME:<NAME>END_PI")
(is (= ["one" "two" "three"]
(redis/sort "list")))
(is (= ["one" "three" "two"]
(redis/sort "list" :alpha)))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids")))
(is (= ["1" "2" "3" "4"]
(redis/sort "ids" :asc)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :desc)))
(is (= ["1" "2"]
(redis/sort "ids" :asc :limit 0 2)))
(is (= ["4" "3"]
(redis/sort "ids" :desc :limit 0 2)))
(is (= ["4" "3" "2" "1"]
(redis/sort "ids" :by "name_*" :alpha)))
(is (= ["one" "two" "three" "four"]
(redis/sort "ids" :get "object_*")))
(is (= ["one" "two"]
(redis/sort "ids" :by "name_*" :alpha :limit 0 2 :desc :get "object_*"))))
;;
;; Multiple database handling commands
;;
(deftest select
(redis/select 0)
(is (= nil (redis/get "akeythat_probably_doesnotexsistindb0"))))
(deftest flushdb
(redis/flushdb)
(is (= 0 (redis/dbsize))))
;;
;; Persistence commands
;;
(deftest save
(redis/save))
(deftest bgsave
(redis/bgsave))
(deftest lastsave
(let [ages-ago (new java.util.Date (long 1))]
(is (.before ages-ago (redis/lastsave)))))
|
[
{
"context": "erty T/id 1)\n (ogre/property \"name\" \"marko\")\n (ogre/property \"age\" 29)\n ",
"end": 2365,
"score": 0.9996980428695679,
"start": 2360,
"tag": "NAME",
"value": "marko"
},
{
"context": "erty T/id 3)\n (ogre/property \"name\" \"lop\")\n (ogre/property \"lang\" \"clj\")\n ",
"end": 2585,
"score": 0.9995928406715393,
"start": 2582,
"tag": "NAME",
"value": "lop"
},
{
"context": "re/traverse\n g\n ogre/V\n (ogre/has :name \"marko\")\n (ogre/into-seq!))\n\n (ogre/traverse\n g\n ",
"end": 3870,
"score": 0.9983404278755188,
"start": 3865,
"tag": "NAME",
"value": "marko"
},
{
"context": "re/traverse\n g\n ogre/V\n (ogre/has :name \"marko\")\n (ogre/out :created)\n (ogre/values :name)",
"end": 3956,
"score": 0.9985809326171875,
"start": 3951,
"tag": "NAME",
"value": "marko"
}
] | dev-resources/src/mm/scylla/graph/repl.clj | oubiwann/scylla-graph | 3 | (ns mm.scylla.graph.repl
"Project development namespace."
(:require
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as string]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[clojusc.twig :as logger]
[clojurewerkz.ogre.core :as ogre]
[com.stuartsierra.component :as component]
[mm.scylla.graph.components.config :as config]
[mm.scylla.graph.components.core]
[mm.scylla.graph.components.janus :as janus]
[mm.scylla.graph.config :as config-lib]
[trifl.java :refer [show-methods]])
(:import
(java.net URI)
(java.nio.file Paths)
(java.security SecureRandom)
(org.apache.tinkerpop.gremlin.structure T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Initial Setup & Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def setup-options {
:init 'mm.scylla.graph.components.core/init
:after-refresh 'mm.scylla.graph.repl/init-and-startup
:throw-errors false})
(defn init
"This is used to set the options and any other global data.
This is defined in a function for re-use. For instance, when a REPL is
reloaded, the options will be lost and need to be re-applied."
[]
(logger/set-level! '[mm.scylla.graph] :debug)
(setup-manager setup-options))
(defn init-and-startup
"This is used as the 'after-refresh' function by the REPL tools library.
Not only do the options (and other global operations) need to be re-applied,
the system also needs to be started up, once these options have be set up."
[]
(init)
(startup))
;; It is not always desired that a system be started up upon REPL loading.
;; Thus, we set the options and perform any global operations with init,
;; and let the user determine when then want to bring up (a potentially
;; computationally intensive) system.
(init)
(defn banner
[]
(println (slurp (io/resource "text/banner.txt")))
:ok)
(comment
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
;; Creating a graph
(def graph (janus/db (system)))
(def g (ogre/traversal graph))
;; Created vertices
(def v1 (-> (ogre/addV g "person")
; (ogre/property T/id 1)
(ogre/property "name" "marko")
(ogre/property "age" 29)
(ogre/next!)))
(-> graph (.tx) (.commit))
(def v2 (-> (ogre/addV g "software")
; (ogre/property T/id 3)
(ogre/property "name" "lop")
(ogre/property "lang" "clj")
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Creating an edge
(def e (-> (ogre/addE g "created")
(ogre/from v1)
(ogre/to v2)
; (ogre/property T/id 9)
(ogre/property "weight" 0.4)
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Verify that changes have been made in the cluster:
$ docker exec -it ce332e5ce806 cqlsh -C --keyspace=janusgraph
cqlsh:janusgraph> SELECT * FROM graphindex;
cqlsh:janusgraph> SELECT * FROM edgestore;
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
;; Querying the graph
(ogre/traverse
g
ogre/V
(ogre/into-seq!))
;; From https://docs.janusgraph.org/latest/tx.html
;; Edges can't be accessed outside their original transaction, so
;; after the edge is committed, it needs to be refreshed:
(def e (ogre/traverse
g
(ogre/E e)))
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
(ogre/traverse
g
ogre/V
(ogre/values :name)
(ogre/into-seq!))
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
(ogre/traverse
g
ogre/V
(ogre/has :name "marko")
(ogre/into-seq!))
(ogre/traverse
g
ogre/V
(ogre/has :name "marko")
(ogre/out :created)
(ogre/values :name)
(ogre/into-seq!))
;; end comments
)
| 96967 | (ns mm.scylla.graph.repl
"Project development namespace."
(:require
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as string]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[clojusc.twig :as logger]
[clojurewerkz.ogre.core :as ogre]
[com.stuartsierra.component :as component]
[mm.scylla.graph.components.config :as config]
[mm.scylla.graph.components.core]
[mm.scylla.graph.components.janus :as janus]
[mm.scylla.graph.config :as config-lib]
[trifl.java :refer [show-methods]])
(:import
(java.net URI)
(java.nio.file Paths)
(java.security SecureRandom)
(org.apache.tinkerpop.gremlin.structure T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Initial Setup & Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def setup-options {
:init 'mm.scylla.graph.components.core/init
:after-refresh 'mm.scylla.graph.repl/init-and-startup
:throw-errors false})
(defn init
"This is used to set the options and any other global data.
This is defined in a function for re-use. For instance, when a REPL is
reloaded, the options will be lost and need to be re-applied."
[]
(logger/set-level! '[mm.scylla.graph] :debug)
(setup-manager setup-options))
(defn init-and-startup
"This is used as the 'after-refresh' function by the REPL tools library.
Not only do the options (and other global operations) need to be re-applied,
the system also needs to be started up, once these options have be set up."
[]
(init)
(startup))
;; It is not always desired that a system be started up upon REPL loading.
;; Thus, we set the options and perform any global operations with init,
;; and let the user determine when then want to bring up (a potentially
;; computationally intensive) system.
(init)
(defn banner
[]
(println (slurp (io/resource "text/banner.txt")))
:ok)
(comment
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
;; Creating a graph
(def graph (janus/db (system)))
(def g (ogre/traversal graph))
;; Created vertices
(def v1 (-> (ogre/addV g "person")
; (ogre/property T/id 1)
(ogre/property "name" "<NAME>")
(ogre/property "age" 29)
(ogre/next!)))
(-> graph (.tx) (.commit))
(def v2 (-> (ogre/addV g "software")
; (ogre/property T/id 3)
(ogre/property "name" "<NAME>")
(ogre/property "lang" "clj")
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Creating an edge
(def e (-> (ogre/addE g "created")
(ogre/from v1)
(ogre/to v2)
; (ogre/property T/id 9)
(ogre/property "weight" 0.4)
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Verify that changes have been made in the cluster:
$ docker exec -it ce332e5ce806 cqlsh -C --keyspace=janusgraph
cqlsh:janusgraph> SELECT * FROM graphindex;
cqlsh:janusgraph> SELECT * FROM edgestore;
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
;; Querying the graph
(ogre/traverse
g
ogre/V
(ogre/into-seq!))
;; From https://docs.janusgraph.org/latest/tx.html
;; Edges can't be accessed outside their original transaction, so
;; after the edge is committed, it needs to be refreshed:
(def e (ogre/traverse
g
(ogre/E e)))
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
(ogre/traverse
g
ogre/V
(ogre/values :name)
(ogre/into-seq!))
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
(ogre/traverse
g
ogre/V
(ogre/has :name "<NAME>")
(ogre/into-seq!))
(ogre/traverse
g
ogre/V
(ogre/has :name "<NAME>")
(ogre/out :created)
(ogre/values :name)
(ogre/into-seq!))
;; end comments
)
| true | (ns mm.scylla.graph.repl
"Project development namespace."
(:require
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as string]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[clojusc.twig :as logger]
[clojurewerkz.ogre.core :as ogre]
[com.stuartsierra.component :as component]
[mm.scylla.graph.components.config :as config]
[mm.scylla.graph.components.core]
[mm.scylla.graph.components.janus :as janus]
[mm.scylla.graph.config :as config-lib]
[trifl.java :refer [show-methods]])
(:import
(java.net URI)
(java.nio.file Paths)
(java.security SecureRandom)
(org.apache.tinkerpop.gremlin.structure T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Initial Setup & Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def setup-options {
:init 'mm.scylla.graph.components.core/init
:after-refresh 'mm.scylla.graph.repl/init-and-startup
:throw-errors false})
(defn init
"This is used to set the options and any other global data.
This is defined in a function for re-use. For instance, when a REPL is
reloaded, the options will be lost and need to be re-applied."
[]
(logger/set-level! '[mm.scylla.graph] :debug)
(setup-manager setup-options))
(defn init-and-startup
"This is used as the 'after-refresh' function by the REPL tools library.
Not only do the options (and other global operations) need to be re-applied,
the system also needs to be started up, once these options have be set up."
[]
(init)
(startup))
;; It is not always desired that a system be started up upon REPL loading.
;; Thus, we set the options and perform any global operations with init,
;; and let the user determine when then want to bring up (a potentially
;; computationally intensive) system.
(init)
(defn banner
[]
(println (slurp (io/resource "text/banner.txt")))
:ok)
(comment
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
;; Creating a graph
(def graph (janus/db (system)))
(def g (ogre/traversal graph))
;; Created vertices
(def v1 (-> (ogre/addV g "person")
; (ogre/property T/id 1)
(ogre/property "name" "PI:NAME:<NAME>END_PI")
(ogre/property "age" 29)
(ogre/next!)))
(-> graph (.tx) (.commit))
(def v2 (-> (ogre/addV g "software")
; (ogre/property T/id 3)
(ogre/property "name" "PI:NAME:<NAME>END_PI")
(ogre/property "lang" "clj")
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Creating an edge
(def e (-> (ogre/addE g "created")
(ogre/from v1)
(ogre/to v2)
; (ogre/property T/id 9)
(ogre/property "weight" 0.4)
(ogre/next!)))
(-> graph (.tx) (.commit))
;; Verify that changes have been made in the cluster:
$ docker exec -it ce332e5ce806 cqlsh -C --keyspace=janusgraph
cqlsh:janusgraph> SELECT * FROM graphindex;
cqlsh:janusgraph> SELECT * FROM edgestore;
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
;; Querying the graph
(ogre/traverse
g
ogre/V
(ogre/into-seq!))
;; From https://docs.janusgraph.org/latest/tx.html
;; Edges can't be accessed outside their original transaction, so
;; after the edge is committed, it needs to be refreshed:
(def e (ogre/traverse
g
(ogre/E e)))
;; From http://ogre.clojurewerkz.org/articles/getting_started.html#the_traversal
(ogre/traverse
g
ogre/V
(ogre/values :name)
(ogre/into-seq!))
;; From http://tinkerpop.apache.org/docs/current/tutorials/getting-started/
(ogre/traverse
g
ogre/V
(ogre/has :name "PI:NAME:<NAME>END_PI")
(ogre/into-seq!))
(ogre/traverse
g
ogre/V
(ogre/has :name "PI:NAME:<NAME>END_PI")
(ogre/out :created)
(ogre/values :name)
(ogre/into-seq!))
;; end comments
)
|
[
{
"context": " :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/wiki\"\n :user \"root\"\n ",
"end": 426,
"score": 0.9995214939117432,
"start": 417,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :user \"root\"\n :password \"root\"})\n\n\n(defn current-time []\n (let [date (new java",
"end": 496,
"score": 0.9990164041519165,
"start": 492,
"tag": "PASSWORD",
"value": "root"
},
{
"context": " {:title title\n :content content\n :author user\n :last_modified_by user\n :modified_time (",
"end": 787,
"score": 0.4343787729740143,
"start": 783,
"tag": "USERNAME",
"value": "user"
}
] | src/wiki/db/core.clj | pamu/wiki | 0 | (ns wiki.db.core
(:require [taoensso.timbre :as timbre]
[environ.core :refer [env]]
[clojure.java.jdbc :as j]))
(defonce data-error-message {:message "Unable to process Data"
:error_code 1
:error_message "Data Error"})
(def mysql-db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/wiki"
:user "root"
:password "root"})
(defn current-time []
(let [date (new java.util.Date)]
(let [sdf (new java.text.SimpleDateFormat "yyyyMMddHHmmss")]
(.format sdf (.getTime date)))))
(defn insert [user title content]
(j/insert! mysql-db :articles
{:title title
:content content
:author user
:last_modified_by user
:modified_time (current-time)
:creation_time (current-time)
:edits 0}))
(defn get-article [article-id]
(j/query mysql-db ["select * from articles where id = ?" article-id]))
(defn get-edits [article-id]
(first (j/query mysql-db ["select edits from articles where id = ?" article-id] :row-fn :edits)))
(defn get-title [article-id]
(first (j/query mysql-db ["select title from articles where id = ?" article-id] :row-fn :title)))
(defn get-content [article-id]
(first (j/query mysql-db ["select content from articles where id = ?" article-id]) :row-fn :content))
(defn update-edits [article-id edit-count]
(j/update! mysql-db :articles {:edits edit-count} ["id = ?" article-id]))
(defn increment-edits [article-id]
(j/with-db-transaction [t-con mysql-db]
(let [edits (get-edits article-id)]
(update-edits article-id (+ edits 1)))
))
(defn update-content [user article-id content]
(j/update! mysql-db :articles {:content content :last_modified_by user} ["id = ?" article-id]))
(defn update-modified-time [article-id]
(j/update! mysql-db :articles {:modified_time (current-time)} ["id = ?" article-id]))
(defn update-article [user article-id content]
(j/with-db-transaction [t-con mysql-db]
(do
(update-content user article-id content)
(update-modified-time article-id)
(increment-edits article-id))))
(defn parse-int [str]
(Integer. str))
(defn get-articles [page-size page-number]
(j/query mysql-db ["select * from articles order by id asc limit ?, ?"
(* (parse-int page-size) (- (parse-int page-number) 1))
(parse-int page-size)]))
(defn remove-article [article-id]
(j/delete! mysql-db :articles ["id=?" article-id]))
| 76904 | (ns wiki.db.core
(:require [taoensso.timbre :as timbre]
[environ.core :refer [env]]
[clojure.java.jdbc :as j]))
(defonce data-error-message {:message "Unable to process Data"
:error_code 1
:error_message "Data Error"})
(def mysql-db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/wiki"
:user "root"
:password "<PASSWORD>"})
(defn current-time []
(let [date (new java.util.Date)]
(let [sdf (new java.text.SimpleDateFormat "yyyyMMddHHmmss")]
(.format sdf (.getTime date)))))
(defn insert [user title content]
(j/insert! mysql-db :articles
{:title title
:content content
:author user
:last_modified_by user
:modified_time (current-time)
:creation_time (current-time)
:edits 0}))
(defn get-article [article-id]
(j/query mysql-db ["select * from articles where id = ?" article-id]))
(defn get-edits [article-id]
(first (j/query mysql-db ["select edits from articles where id = ?" article-id] :row-fn :edits)))
(defn get-title [article-id]
(first (j/query mysql-db ["select title from articles where id = ?" article-id] :row-fn :title)))
(defn get-content [article-id]
(first (j/query mysql-db ["select content from articles where id = ?" article-id]) :row-fn :content))
(defn update-edits [article-id edit-count]
(j/update! mysql-db :articles {:edits edit-count} ["id = ?" article-id]))
(defn increment-edits [article-id]
(j/with-db-transaction [t-con mysql-db]
(let [edits (get-edits article-id)]
(update-edits article-id (+ edits 1)))
))
(defn update-content [user article-id content]
(j/update! mysql-db :articles {:content content :last_modified_by user} ["id = ?" article-id]))
(defn update-modified-time [article-id]
(j/update! mysql-db :articles {:modified_time (current-time)} ["id = ?" article-id]))
(defn update-article [user article-id content]
(j/with-db-transaction [t-con mysql-db]
(do
(update-content user article-id content)
(update-modified-time article-id)
(increment-edits article-id))))
(defn parse-int [str]
(Integer. str))
(defn get-articles [page-size page-number]
(j/query mysql-db ["select * from articles order by id asc limit ?, ?"
(* (parse-int page-size) (- (parse-int page-number) 1))
(parse-int page-size)]))
(defn remove-article [article-id]
(j/delete! mysql-db :articles ["id=?" article-id]))
| true | (ns wiki.db.core
(:require [taoensso.timbre :as timbre]
[environ.core :refer [env]]
[clojure.java.jdbc :as j]))
(defonce data-error-message {:message "Unable to process Data"
:error_code 1
:error_message "Data Error"})
(def mysql-db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/wiki"
:user "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(defn current-time []
(let [date (new java.util.Date)]
(let [sdf (new java.text.SimpleDateFormat "yyyyMMddHHmmss")]
(.format sdf (.getTime date)))))
(defn insert [user title content]
(j/insert! mysql-db :articles
{:title title
:content content
:author user
:last_modified_by user
:modified_time (current-time)
:creation_time (current-time)
:edits 0}))
(defn get-article [article-id]
(j/query mysql-db ["select * from articles where id = ?" article-id]))
(defn get-edits [article-id]
(first (j/query mysql-db ["select edits from articles where id = ?" article-id] :row-fn :edits)))
(defn get-title [article-id]
(first (j/query mysql-db ["select title from articles where id = ?" article-id] :row-fn :title)))
(defn get-content [article-id]
(first (j/query mysql-db ["select content from articles where id = ?" article-id]) :row-fn :content))
(defn update-edits [article-id edit-count]
(j/update! mysql-db :articles {:edits edit-count} ["id = ?" article-id]))
(defn increment-edits [article-id]
(j/with-db-transaction [t-con mysql-db]
(let [edits (get-edits article-id)]
(update-edits article-id (+ edits 1)))
))
(defn update-content [user article-id content]
(j/update! mysql-db :articles {:content content :last_modified_by user} ["id = ?" article-id]))
(defn update-modified-time [article-id]
(j/update! mysql-db :articles {:modified_time (current-time)} ["id = ?" article-id]))
(defn update-article [user article-id content]
(j/with-db-transaction [t-con mysql-db]
(do
(update-content user article-id content)
(update-modified-time article-id)
(increment-edits article-id))))
(defn parse-int [str]
(Integer. str))
(defn get-articles [page-size page-number]
(j/query mysql-db ["select * from articles order by id asc limit ?, ?"
(* (parse-int page-size) (- (parse-int page-number) 1))
(parse-int page-size)]))
(defn remove-article [article-id]
(j/delete! mysql-db :articles ["id=?" article-id]))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-12-21\"\n :doc \"Greedy decision t",
"end": 105,
"score": 0.9998721480369568,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/main/clojure/taiga/split/numerical/numerical/xy.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-12-21"
:doc "Greedy decision tree splitting." }
taiga.split.numerical.numerical.xy
(:require [taiga.utils :as utils]
[taiga.tree.split.numerical :as numerical])
(:import [java.util List]
[clojure.lang IFn IFn$OD IFn$OL Keyword]
[zana.java.accumulator Accumulator]
[taiga.java.split.numerical XY]))
;;------------------------------------------------------------------------------
(defn allocate-cache [n] (make-array XY n))
;;------------------------------------------------------------------------------
(defn split [options]
(let [^IFn cost-factory (:cost-factory options)
^IFn feasible? (:feasible? options)
^IFn$OD y (:ground-truth options)
_(assert (instance? IFn$OD y))
[^Keyword kx ^IFn$OD x] (:this-predictor options)
_(assert (instance? IFn$OD x))
;; data is mutable!
^objects data-count (XY/cacheXY x y (:data options) (:xys options))
^objects data (aget data-count 0)
n (int (aget data-count 1))]
(assert (> n 0))
;; TODO: this is wrong --- it's assuming that feasible? depends on :mincount
;; TODO: move test to bud/split
(if (or (> (* 2 (int (:mincount options))) n))
{:cost Double/POSITIVE_INFINITY}
(let [^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)]
(dotimes [i n] (.add cost1 (.y ^XY (aget data i))))
(loop [i (int 0)
xmin Double/NEGATIVE_INFINITY
cmin (double (utils/feasible-cost feasible? cost0 cost1))
nleft (int 0)]
(let [^XY di (aget data i)
xi (.x di)
yi (.y di)
_ (.add cost0 yi)
_ (.delete cost1 yi)
;; move all tied x values from right to left
j (int
(loop [jj (int (+ i 1))]
(if (>= jj n)
jj
(let [^XY dj (aget data jj)
xj (.x dj)]
(if-not (== xi xj)
jj
(let [yj (.y dj)]
(.add cost0 yj)
(.delete cost1 yj)
(recur (inc jj))))))))]
(if (< j n)
(let [cost (double (utils/feasible-cost feasible? cost0 cost1))]
(if (< cost cmin)
(recur (int j) (.x ^XY (aget data i)) cost (int (.netCount cost0)))
(recur (int j) xmin cmin nleft)))
;; done
(if (and (> xmin Double/NEGATIVE_INFINITY)
(< cmin Double/POSITIVE_INFINITY))
{:split (numerical/make kx xmin nleft n) :cost cmin}
{:cost Double/POSITIVE_INFINITY}))))))))
;;------------------------------------------------------------------------------
| 114652 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-12-21"
:doc "Greedy decision tree splitting." }
taiga.split.numerical.numerical.xy
(:require [taiga.utils :as utils]
[taiga.tree.split.numerical :as numerical])
(:import [java.util List]
[clojure.lang IFn IFn$OD IFn$OL Keyword]
[zana.java.accumulator Accumulator]
[taiga.java.split.numerical XY]))
;;------------------------------------------------------------------------------
(defn allocate-cache [n] (make-array XY n))
;;------------------------------------------------------------------------------
(defn split [options]
(let [^IFn cost-factory (:cost-factory options)
^IFn feasible? (:feasible? options)
^IFn$OD y (:ground-truth options)
_(assert (instance? IFn$OD y))
[^Keyword kx ^IFn$OD x] (:this-predictor options)
_(assert (instance? IFn$OD x))
;; data is mutable!
^objects data-count (XY/cacheXY x y (:data options) (:xys options))
^objects data (aget data-count 0)
n (int (aget data-count 1))]
(assert (> n 0))
;; TODO: this is wrong --- it's assuming that feasible? depends on :mincount
;; TODO: move test to bud/split
(if (or (> (* 2 (int (:mincount options))) n))
{:cost Double/POSITIVE_INFINITY}
(let [^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)]
(dotimes [i n] (.add cost1 (.y ^XY (aget data i))))
(loop [i (int 0)
xmin Double/NEGATIVE_INFINITY
cmin (double (utils/feasible-cost feasible? cost0 cost1))
nleft (int 0)]
(let [^XY di (aget data i)
xi (.x di)
yi (.y di)
_ (.add cost0 yi)
_ (.delete cost1 yi)
;; move all tied x values from right to left
j (int
(loop [jj (int (+ i 1))]
(if (>= jj n)
jj
(let [^XY dj (aget data jj)
xj (.x dj)]
(if-not (== xi xj)
jj
(let [yj (.y dj)]
(.add cost0 yj)
(.delete cost1 yj)
(recur (inc jj))))))))]
(if (< j n)
(let [cost (double (utils/feasible-cost feasible? cost0 cost1))]
(if (< cost cmin)
(recur (int j) (.x ^XY (aget data i)) cost (int (.netCount cost0)))
(recur (int j) xmin cmin nleft)))
;; done
(if (and (> xmin Double/NEGATIVE_INFINITY)
(< cmin Double/POSITIVE_INFINITY))
{:split (numerical/make kx xmin nleft n) :cost cmin}
{:cost Double/POSITIVE_INFINITY}))))))))
;;------------------------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-12-21"
:doc "Greedy decision tree splitting." }
taiga.split.numerical.numerical.xy
(:require [taiga.utils :as utils]
[taiga.tree.split.numerical :as numerical])
(:import [java.util List]
[clojure.lang IFn IFn$OD IFn$OL Keyword]
[zana.java.accumulator Accumulator]
[taiga.java.split.numerical XY]))
;;------------------------------------------------------------------------------
(defn allocate-cache [n] (make-array XY n))
;;------------------------------------------------------------------------------
(defn split [options]
(let [^IFn cost-factory (:cost-factory options)
^IFn feasible? (:feasible? options)
^IFn$OD y (:ground-truth options)
_(assert (instance? IFn$OD y))
[^Keyword kx ^IFn$OD x] (:this-predictor options)
_(assert (instance? IFn$OD x))
;; data is mutable!
^objects data-count (XY/cacheXY x y (:data options) (:xys options))
^objects data (aget data-count 0)
n (int (aget data-count 1))]
(assert (> n 0))
;; TODO: this is wrong --- it's assuming that feasible? depends on :mincount
;; TODO: move test to bud/split
(if (or (> (* 2 (int (:mincount options))) n))
{:cost Double/POSITIVE_INFINITY}
(let [^Accumulator cost0 (cost-factory)
^Accumulator cost1 (cost-factory)]
(dotimes [i n] (.add cost1 (.y ^XY (aget data i))))
(loop [i (int 0)
xmin Double/NEGATIVE_INFINITY
cmin (double (utils/feasible-cost feasible? cost0 cost1))
nleft (int 0)]
(let [^XY di (aget data i)
xi (.x di)
yi (.y di)
_ (.add cost0 yi)
_ (.delete cost1 yi)
;; move all tied x values from right to left
j (int
(loop [jj (int (+ i 1))]
(if (>= jj n)
jj
(let [^XY dj (aget data jj)
xj (.x dj)]
(if-not (== xi xj)
jj
(let [yj (.y dj)]
(.add cost0 yj)
(.delete cost1 yj)
(recur (inc jj))))))))]
(if (< j n)
(let [cost (double (utils/feasible-cost feasible? cost0 cost1))]
(if (< cost cmin)
(recur (int j) (.x ^XY (aget data i)) cost (int (.netCount cost0)))
(recur (int j) xmin cmin nleft)))
;; done
(if (and (> xmin Double/NEGATIVE_INFINITY)
(< cmin Double/POSITIVE_INFINITY))
{:split (numerical/make kx xmin nleft n) :cost cmin}
{:cost Double/POSITIVE_INFINITY}))))))))
;;------------------------------------------------------------------------------
|
[
{
"context": " :database \"mydb\"\n :password \"secret!\"\n :user \"root\"}\n :color true",
"end": 561,
"score": 0.9986010789871216,
"start": 555,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "ns\"}\n (init dummy-project {:db {:password \"secret!\"}}))\n\n(expect {:migration-dir \"migrations\"\n ",
"end": 708,
"score": 0.9992769956588745,
"start": 702,
"tag": "PASSWORD",
"value": "secret"
}
] | test/tern/config_test.clj | ldhough/lein-tern | 11 | (ns tern.config-test
(:require [tern.config :refer :all]
[expectations :refer :all]))
(def dummy-project
{:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:database "mydb"
:user "root"
:password ""}
:migration-dir "tern-migrations"})
(expect {:version-table "schema_versions"
:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:host "localhost"
:port 5432
:database "mydb"
:password "secret!"
:user "root"}
:color true
:migration-dir "tern-migrations"}
(init dummy-project {:db {:password "secret!"}}))
(expect {:migration-dir "migrations"
:version-table "schema_versions"
:color true
:db {:host "localhost"
:port 5432
:database "postgres"
:user "postgres"
:password ""
:subprotocol "postgresql"}}
(init nil {}))
| 35826 | (ns tern.config-test
(:require [tern.config :refer :all]
[expectations :refer :all]))
(def dummy-project
{:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:database "mydb"
:user "root"
:password ""}
:migration-dir "tern-migrations"})
(expect {:version-table "schema_versions"
:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:host "localhost"
:port 5432
:database "mydb"
:password "<PASSWORD>!"
:user "root"}
:color true
:migration-dir "tern-migrations"}
(init dummy-project {:db {:password "<PASSWORD>!"}}))
(expect {:migration-dir "migrations"
:version-table "schema_versions"
:color true
:db {:host "localhost"
:port 5432
:database "postgres"
:user "postgres"
:password ""
:subprotocol "postgresql"}}
(init nil {}))
| true | (ns tern.config-test
(:require [tern.config :refer :all]
[expectations :refer :all]))
(def dummy-project
{:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:database "mydb"
:user "root"
:password ""}
:migration-dir "tern-migrations"})
(expect {:version-table "schema_versions"
:db {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:host "localhost"
:port 5432
:database "mydb"
:password "PI:PASSWORD:<PASSWORD>END_PI!"
:user "root"}
:color true
:migration-dir "tern-migrations"}
(init dummy-project {:db {:password "PI:PASSWORD:<PASSWORD>END_PI!"}}))
(expect {:migration-dir "migrations"
:version-table "schema_versions"
:color true
:db {:host "localhost"
:port 5432
:database "postgres"
:user "postgres"
:password ""
:subprotocol "postgresql"}}
(init nil {}))
|
[
{
"context": "al massage) from geoJSON and wikipedia data.\"\n {\"Bavaria\" \"Bayern\"\n \"Hesse\" \"Hessen\" \n \"Lower Saxony\" ",
"end": 351,
"score": 0.9986190795898438,
"start": 344,
"tag": "NAME",
"value": "Bavaria"
},
{
"context": ") from geoJSON and wikipedia data.\"\n {\"Bavaria\" \"Bayern\"\n \"Hesse\" \"Hessen\" \n \"Lower Saxony\" \"Niedersa",
"end": 360,
"score": 0.9970284700393677,
"start": 354,
"tag": "NAME",
"value": "Bayern"
},
{
"context": "ON and wikipedia data.\"\n {\"Bavaria\" \"Bayern\"\n \"Hesse\" \"Hessen\" \n \"Lower Saxony\" \"Niedersachsen\"\n \"",
"end": 371,
"score": 0.999340295791626,
"start": 366,
"tag": "NAME",
"value": "Hesse"
},
{
"context": "ikipedia data.\"\n {\"Bavaria\" \"Bayern\"\n \"Hesse\" \"Hessen\" \n \"Lower Saxony\" \"Niedersachsen\"\n \"North Rhi",
"end": 380,
"score": 0.9994802474975586,
"start": 374,
"tag": "NAME",
"value": "Hessen"
},
{
"context": " \"Bayern\"\n \"Hesse\" \"Hessen\" \n \"Lower Saxony\" \"Niedersachsen\"\n \"North Rhine-Westphalia\" \"Nordrhein-Westfa",
"end": 412,
"score": 0.9217813014984131,
"start": 402,
"tag": "NAME",
"value": "Niedersach"
},
{
"context": "\"\n \"Rhineland-Palatinate\" \"Rheinland-Pfalz\"\n \"Saxony\" \"Sachsen\"\n \"Saxony-Anhalt\" \"Sachsen-Anhalt\"\n ",
"end": 521,
"score": 0.9980760216712952,
"start": 515,
"tag": "NAME",
"value": "Saxony"
},
{
"context": "neland-Palatinate\" \"Rheinland-Pfalz\"\n \"Saxony\" \"Sachsen\"\n \"Saxony-Anhalt\" \"Sachsen-Anhalt\"\n \"Schleswi",
"end": 531,
"score": 0.9982029795646667,
"start": 524,
"tag": "NAME",
"value": "Sachsen"
},
{
"context": "-Pfalz\"\n \"Saxony\" \"Sachsen\"\n \"Saxony-Anhalt\" \"Sachsen-Anhalt\"\n \"Schleswig Holstein\" \"Schleswig-Hol",
"end": 557,
"score": 0.742698073387146,
"start": 553,
"tag": "NAME",
"value": "Sach"
},
{
"context": " \"Saxony\" \"Sachsen\"\n \"Saxony-Anhalt\" \"Sachsen-Anhalt\"\n \"Schleswig Holstein\" \"Schleswig-Holstein\"\n ",
"end": 567,
"score": 0.7047227621078491,
"start": 563,
"tag": "NAME",
"value": "halt"
},
{
"context": "\"Sachsen\"\n \"Saxony-Anhalt\" \"Sachsen-Anhalt\"\n \"Schleswig Holstein\" \"Schleswig-Holstein\"\n \"Thuringia\" \"Thüringen\"}",
"end": 591,
"score": 0.9992529153823853,
"start": 573,
"tag": "NAME",
"value": "Schleswig Holstein"
},
{
"context": "Anhalt\" \"Sachsen-Anhalt\"\n \"Schleswig Holstein\" \"Schleswig-Holstein\"\n \"Thuringia\" \"Thüringen\"})\n\n;; from https://ww",
"end": 612,
"score": 0.9667583703994751,
"start": 594,
"tag": "NAME",
"value": "Schleswig-Holstein"
},
{
"context": "\n \"Schleswig Holstein\" \"Schleswig-Holstein\"\n \"Thuringia\" \"Thüringen\"})\n\n;; from https://www.rki.de/DE/Con",
"end": 627,
"score": 0.9975957870483398,
"start": 618,
"tag": "NAME",
"value": "Thuringia"
},
{
"context": "ig Holstein\" \"Schleswig-Holstein\"\n \"Thuringia\" \"Thüringen\"})\n\n;; from https://www.rki.de/DE/Content/InfAZ/N",
"end": 639,
"score": 0.9988459944725037,
"start": 630,
"tag": "NAME",
"value": "Thüringen"
}
] | src/appliedsciencestudio/covid19_clj_viz/deutschland.clj | namenu/covid19-clj-viz | 0 | (ns appliedsciencestudio.covid19-clj-viz.deutschland
(:require [clojure.data.csv :as csv]
[clojure.string :as string]))
(def normalize-bundesland
"Mappings to normalize English/German and typographic variation to standard German spelling.
Made with nonce code (and some digital massage) from geoJSON and wikipedia data."
{"Bavaria" "Bayern"
"Hesse" "Hessen"
"Lower Saxony" "Niedersachsen"
"North Rhine-Westphalia" "Nordrhein-Westfalen"
"Rhineland-Palatinate" "Rheinland-Pfalz"
"Saxony" "Sachsen"
"Saxony-Anhalt" "Sachsen-Anhalt"
"Schleswig Holstein" "Schleswig-Holstein"
"Thuringia" "Thüringen"})
;; from https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html
(def cases
(reduce (fn [acc [bundesland n]]
(assoc acc (get normalize-bundesland bundesland bundesland) (Integer/parseInt n)))
{}
(rest (csv/read-csv (slurp "resources/deutschland.covid19cases.tsv")
:separator \tab))))
;; from https://en.m.wikipedia.org/wiki/List_of_German_states_by_population
(def population
(->> (csv/read-csv (slurp (str "resources/deutschland.state-population.tsv"))
:separator \tab)
rest ;; drop the column header line
(map (juxt first last)) ;; only take the name of the state and 2018 population data:
(map #(mapv string/trim %))
(map (fn [[state pop-s]]
[(get normalize-bundesland state state)
(Integer/parseInt (string/replace pop-s "," ""))]))
(into {})))
(def bundeslaender-data
"Map from bundesland to population, cases, and cases-per-100k persons."
(reduce (fn [acc [bundesland cases]]
(assoc acc
bundesland
{:state-or-province bundesland
:population (population bundesland)
:cases cases
:cases-per-100k (double (/ cases (/ (population bundesland)
100000)))}))
{}
cases))
| 12239 | (ns appliedsciencestudio.covid19-clj-viz.deutschland
(:require [clojure.data.csv :as csv]
[clojure.string :as string]))
(def normalize-bundesland
"Mappings to normalize English/German and typographic variation to standard German spelling.
Made with nonce code (and some digital massage) from geoJSON and wikipedia data."
{"<NAME>" "<NAME>"
"<NAME>" "<NAME>"
"Lower Saxony" "<NAME>sen"
"North Rhine-Westphalia" "Nordrhein-Westfalen"
"Rhineland-Palatinate" "Rheinland-Pfalz"
"<NAME>" "<NAME>"
"Saxony-Anhalt" "<NAME>sen-An<NAME>"
"<NAME>" "<NAME>"
"<NAME>" "<NAME>"})
;; from https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html
(def cases
(reduce (fn [acc [bundesland n]]
(assoc acc (get normalize-bundesland bundesland bundesland) (Integer/parseInt n)))
{}
(rest (csv/read-csv (slurp "resources/deutschland.covid19cases.tsv")
:separator \tab))))
;; from https://en.m.wikipedia.org/wiki/List_of_German_states_by_population
(def population
(->> (csv/read-csv (slurp (str "resources/deutschland.state-population.tsv"))
:separator \tab)
rest ;; drop the column header line
(map (juxt first last)) ;; only take the name of the state and 2018 population data:
(map #(mapv string/trim %))
(map (fn [[state pop-s]]
[(get normalize-bundesland state state)
(Integer/parseInt (string/replace pop-s "," ""))]))
(into {})))
(def bundeslaender-data
"Map from bundesland to population, cases, and cases-per-100k persons."
(reduce (fn [acc [bundesland cases]]
(assoc acc
bundesland
{:state-or-province bundesland
:population (population bundesland)
:cases cases
:cases-per-100k (double (/ cases (/ (population bundesland)
100000)))}))
{}
cases))
| true | (ns appliedsciencestudio.covid19-clj-viz.deutschland
(:require [clojure.data.csv :as csv]
[clojure.string :as string]))
(def normalize-bundesland
"Mappings to normalize English/German and typographic variation to standard German spelling.
Made with nonce code (and some digital massage) from geoJSON and wikipedia data."
{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
"Lower Saxony" "PI:NAME:<NAME>END_PIsen"
"North Rhine-Westphalia" "Nordrhein-Westfalen"
"Rhineland-Palatinate" "Rheinland-Pfalz"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
"Saxony-Anhalt" "PI:NAME:<NAME>END_PIsen-AnPI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
;; from https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html
(def cases
(reduce (fn [acc [bundesland n]]
(assoc acc (get normalize-bundesland bundesland bundesland) (Integer/parseInt n)))
{}
(rest (csv/read-csv (slurp "resources/deutschland.covid19cases.tsv")
:separator \tab))))
;; from https://en.m.wikipedia.org/wiki/List_of_German_states_by_population
(def population
(->> (csv/read-csv (slurp (str "resources/deutschland.state-population.tsv"))
:separator \tab)
rest ;; drop the column header line
(map (juxt first last)) ;; only take the name of the state and 2018 population data:
(map #(mapv string/trim %))
(map (fn [[state pop-s]]
[(get normalize-bundesland state state)
(Integer/parseInt (string/replace pop-s "," ""))]))
(into {})))
(def bundeslaender-data
"Map from bundesland to population, cases, and cases-per-100k persons."
(reduce (fn [acc [bundesland cases]]
(assoc acc
bundesland
{:state-or-province bundesland
:population (population bundesland)
:cases cases
:cases-per-100k (double (/ cases (/ (population bundesland)
100000)))}))
{}
cases))
|
[
{
"context": "(ns ^{:author \"Alexander James King\",\n :doc \"Assertion functions wrapping spy.co",
"end": 35,
"score": 0.9998840093612671,
"start": 15,
"tag": "NAME",
"value": "Alexander James King"
}
] | src/clj/spy/assert.clj | zyegfryed/spy | 164 | (ns ^{:author "Alexander James King",
:doc "Assertion functions wrapping spy.core functions,
providing assertions using clojure.test/is and messages
to aid debugging when test expectations are not met.
Macros are used to ensure the clojure.test/is macro
appears in the calling code, otherwise line numbers
reported on failure will show as failures in the
library and not the calling code."}
spy.assert
(:require [spy.core :as spy]
[spy.assert-messages :as assert-messages]
[clojure.test :refer [is]]))
(defmacro called-n-times?
[f n]
`(is (spy/called-n-times? ~f ~n)
(assert-messages/expected-calls ~f ~n)))
(defmacro not-called?
[f]
`(is (spy/not-called? ~f)
(assert-messages/expected-calls ~f 0)))
(defmacro called-once?
[f]
`(is (spy/called-once? ~f)
(assert-messages/expected-calls ~f 1)))
(defmacro called-with?
[f & args]
`(is (spy/called-with? ~f ~@args)
(assert-messages/called-with ~f ~@args)))
(defmacro not-called-with?
[f & args]
`(is (spy/not-called-with? ~f ~@args)
(assert-messages/not-called-with ~f ~@args)))
(defmacro called-once-with?
[f & args]
`(is (spy/called-once-with? ~f ~@args)
(assert-messages/called-once-with ~f ~@args)))
(defmacro called-at-least-n-times?
[f n]
`(is (spy/called-at-least-n-times? ~f ~n)
(assert-messages/called-at-least-n-times ~f ~n)))
(defmacro called?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-at-least-once?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-no-more-than-n-times?
[f n]
`(is (spy/called-no-more-than-n-times? ~f ~n)
(assert-messages/called-no-more-than-n-times ~f ~n)))
(defmacro called-no-more-than-once?
[f]
`(called-no-more-than-n-times? ~f 1))
| 34805 | (ns ^{:author "<NAME>",
:doc "Assertion functions wrapping spy.core functions,
providing assertions using clojure.test/is and messages
to aid debugging when test expectations are not met.
Macros are used to ensure the clojure.test/is macro
appears in the calling code, otherwise line numbers
reported on failure will show as failures in the
library and not the calling code."}
spy.assert
(:require [spy.core :as spy]
[spy.assert-messages :as assert-messages]
[clojure.test :refer [is]]))
(defmacro called-n-times?
[f n]
`(is (spy/called-n-times? ~f ~n)
(assert-messages/expected-calls ~f ~n)))
(defmacro not-called?
[f]
`(is (spy/not-called? ~f)
(assert-messages/expected-calls ~f 0)))
(defmacro called-once?
[f]
`(is (spy/called-once? ~f)
(assert-messages/expected-calls ~f 1)))
(defmacro called-with?
[f & args]
`(is (spy/called-with? ~f ~@args)
(assert-messages/called-with ~f ~@args)))
(defmacro not-called-with?
[f & args]
`(is (spy/not-called-with? ~f ~@args)
(assert-messages/not-called-with ~f ~@args)))
(defmacro called-once-with?
[f & args]
`(is (spy/called-once-with? ~f ~@args)
(assert-messages/called-once-with ~f ~@args)))
(defmacro called-at-least-n-times?
[f n]
`(is (spy/called-at-least-n-times? ~f ~n)
(assert-messages/called-at-least-n-times ~f ~n)))
(defmacro called?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-at-least-once?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-no-more-than-n-times?
[f n]
`(is (spy/called-no-more-than-n-times? ~f ~n)
(assert-messages/called-no-more-than-n-times ~f ~n)))
(defmacro called-no-more-than-once?
[f]
`(called-no-more-than-n-times? ~f 1))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI",
:doc "Assertion functions wrapping spy.core functions,
providing assertions using clojure.test/is and messages
to aid debugging when test expectations are not met.
Macros are used to ensure the clojure.test/is macro
appears in the calling code, otherwise line numbers
reported on failure will show as failures in the
library and not the calling code."}
spy.assert
(:require [spy.core :as spy]
[spy.assert-messages :as assert-messages]
[clojure.test :refer [is]]))
(defmacro called-n-times?
[f n]
`(is (spy/called-n-times? ~f ~n)
(assert-messages/expected-calls ~f ~n)))
(defmacro not-called?
[f]
`(is (spy/not-called? ~f)
(assert-messages/expected-calls ~f 0)))
(defmacro called-once?
[f]
`(is (spy/called-once? ~f)
(assert-messages/expected-calls ~f 1)))
(defmacro called-with?
[f & args]
`(is (spy/called-with? ~f ~@args)
(assert-messages/called-with ~f ~@args)))
(defmacro not-called-with?
[f & args]
`(is (spy/not-called-with? ~f ~@args)
(assert-messages/not-called-with ~f ~@args)))
(defmacro called-once-with?
[f & args]
`(is (spy/called-once-with? ~f ~@args)
(assert-messages/called-once-with ~f ~@args)))
(defmacro called-at-least-n-times?
[f n]
`(is (spy/called-at-least-n-times? ~f ~n)
(assert-messages/called-at-least-n-times ~f ~n)))
(defmacro called?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-at-least-once?
[f]
`(called-at-least-n-times? ~f 1))
(defmacro called-no-more-than-n-times?
[f n]
`(is (spy/called-no-more-than-n-times? ~f ~n)
(assert-messages/called-no-more-than-n-times ~f ~n)))
(defmacro called-no-more-than-once?
[f]
`(called-no-more-than-n-times? ~f 1))
|
[
{
"context": "ftest test-encrypted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (ma",
"end": 5532,
"score": 0.9874460697174072,
"start": 5527,
"tag": "PASSWORD",
"value": "test1"
},
{
"context": "st-encrypted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (mapv #(vec",
"end": 5540,
"score": 0.9763153791427612,
"start": 5535,
"tag": "PASSWORD",
"value": "test2"
},
{
"context": "pted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (mapv #(vector :cac",
"end": 5548,
"score": 0.9726587533950806,
"start": 5543,
"tag": "PASSWORD",
"value": "test3"
}
] | waiter/test/waiter/kv_test.clj | geofft/waiter | 76 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.kv-test
(:require [clj-time.coerce :as tc]
[clj-time.core :as t]
[clojure.java.io :as io]
[clojure.test :refer :all]
[waiter.curator :as curator]
[waiter.kv :as kv]
[waiter.util.cache-utils :as cu])
(:import (java.util Arrays)
(org.apache.curator.framework CuratorFramework CuratorFrameworkFactory)
(org.apache.curator.retry RetryNTimes)))
(deftest test-local-kv-store
(let [test-store (kv/new-local-kv-store {})
bytes (byte-array 10)
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value bytes}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))))
(defn work-dir
"Returns the canonical path for the ./kv-store directory"
[]
(-> "./kv-store" (io/file) (.getCanonicalPath)))
(deftest test-file-based-kv-store
(let [target-file (str (work-dir) "/foo.bin")
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})
bytes (byte-array 10)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))
;; testing data was persisted in the file
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})]
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))))
(deftest test-encrypted-kv-store
(let [passwords ["test1" "test2" "test3"]
processed-passwords (mapv #(vector :cached %) passwords)
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
; store propagates to underlying store
(kv/store encrypted-kv-store :b 2)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store does not corrupt underlying store
(kv/store encrypted-kv-store :a 5)
(is (not (nil? (kv/fetch local-kv-store :a))))
(is (= 5 (kv/fetch encrypted-kv-store :a)))
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store updates underlying store
(kv/store encrypted-kv-store :b 11)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 11 (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= 2 (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :count])))
(is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :data])))))
; delete :a and :b
(kv/delete encrypted-kv-store :a)
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(kv/delete encrypted-kv-store :b)
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store])))
(kv/delete encrypted-kv-store :does-not-exist)))
(deftest test-cached-kv-store
(let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)}
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
{:keys [cache] :as cached-kv-store} (kv/new-cached-kv-store cache-config local-kv-store)
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))
time-3 (t/plus time-0 (t/seconds 3))
time-4 (t/plus time-0 (t/seconds 4))
time-5 (t/plus time-0 (t/seconds 5))]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store local-kv-store :a 1))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats local-kv-store :a)))
; cache looks up underlying store during miss
(is (kv/fetch local-kv-store :a))
(is (= 1 (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
; store to cache propagates to underlying store
(with-redefs [t/now (constantly time-2)]
(kv/store cached-kv-store :b 2))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-2)}
(kv/stats local-kv-store :b)))
(is (true? (cu/cache-contains? cache :b)))
(is (= 2 (kv/fetch cached-kv-store :b)))
(is (= 2 (kv/fetch local-kv-store :b)))
(with-redefs [t/now (constantly time-3)]
(kv/store cached-kv-store :b 11))
(is (= 11 (kv/fetch cached-kv-store :b)))
(is (= 11 (kv/fetch local-kv-store :b)))
; cache works with refresh call
(with-redefs [t/now (constantly time-4)]
(kv/store cached-kv-store :b 13))
(is (true? (cu/cache-contains? cache :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(with-redefs [t/now (constantly time-5)]
(kv/store local-kv-store :b 17))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
(kv/stats local-kv-store :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(is (= 17 (kv/fetch local-kv-store :b)))
(is (= 17 (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 2
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}
:b {:stats {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
:value 17}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))
; delete removes entry from cache
(kv/delete cached-kv-store :b)
(is (false? (cu/cache-contains? cache :b)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))))
(deftest test-validate-zk-key
(kv/validate-zk-key "test-key")
(is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key")))
(is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key ".."))))
(deftest test-key->zk-key
(is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah")))
(is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah"))))
(deftest test-zk-kv-store
(let [zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
services-base-path "/test-zk-kv-store/base-path"]
(is (kv/new-zk-kv-store {:curator curator
:base-path "/waiter-tokens"
:sync-timeout-ms 1}))
(try
(.start curator)
(testing "in-memory-zk"
(let [get-value-from-curator (fn [key]
(.forPath (.checkExists curator)
(kv/key->zk-path services-base-path key)))
test-store (kv/new-zk-kv-store {:curator curator
:base-path services-base-path
:sync-timeout-ms 1})
bytes (byte-array 10)
include-flags #{"data"}
creation-time-promise (promise)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(kv/store test-store "a" bytes)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= ctime mtime))
(deliver creation-time-promise ctime))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(kv/store test-store "a" 3)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= @creation-time-promise ctime))
(is (< @creation-time-promise mtime)))
(is (= 3 (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "a")
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "does-not-exist")
(is (nil? (get-value-from-curator "does-not-exist")))
(is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store include-flags)))))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-kv-store
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(is (= "bar" (kv/retrieve kv-store "foo" true)))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-zk-kv-store
(testing "Creating a new ZooKeeper key/value store"
(testing "should throw on non-integer sync-timeout-ms"
(is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework)
:base-path ""
:sync-timeout-ms 1.1}))))))
(deftest test-zk-keys
(testing "List ZK keys"
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(kv/store kv-store "foo2" "bar2")
(kv/store kv-store "foo3" "bar3")
(is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config))))))
(finally
(.close curator)
(.stop zk-server))))))
| 119553 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.kv-test
(:require [clj-time.coerce :as tc]
[clj-time.core :as t]
[clojure.java.io :as io]
[clojure.test :refer :all]
[waiter.curator :as curator]
[waiter.kv :as kv]
[waiter.util.cache-utils :as cu])
(:import (java.util Arrays)
(org.apache.curator.framework CuratorFramework CuratorFrameworkFactory)
(org.apache.curator.retry RetryNTimes)))
(deftest test-local-kv-store
(let [test-store (kv/new-local-kv-store {})
bytes (byte-array 10)
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value bytes}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))))
(defn work-dir
"Returns the canonical path for the ./kv-store directory"
[]
(-> "./kv-store" (io/file) (.getCanonicalPath)))
(deftest test-file-based-kv-store
(let [target-file (str (work-dir) "/foo.bin")
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})
bytes (byte-array 10)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))
;; testing data was persisted in the file
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})]
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))))
(deftest test-encrypted-kv-store
(let [passwords ["<PASSWORD>" "<PASSWORD>" "<PASSWORD>"]
processed-passwords (mapv #(vector :cached %) passwords)
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
; store propagates to underlying store
(kv/store encrypted-kv-store :b 2)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store does not corrupt underlying store
(kv/store encrypted-kv-store :a 5)
(is (not (nil? (kv/fetch local-kv-store :a))))
(is (= 5 (kv/fetch encrypted-kv-store :a)))
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store updates underlying store
(kv/store encrypted-kv-store :b 11)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 11 (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= 2 (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :count])))
(is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :data])))))
; delete :a and :b
(kv/delete encrypted-kv-store :a)
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(kv/delete encrypted-kv-store :b)
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store])))
(kv/delete encrypted-kv-store :does-not-exist)))
(deftest test-cached-kv-store
(let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)}
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
{:keys [cache] :as cached-kv-store} (kv/new-cached-kv-store cache-config local-kv-store)
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))
time-3 (t/plus time-0 (t/seconds 3))
time-4 (t/plus time-0 (t/seconds 4))
time-5 (t/plus time-0 (t/seconds 5))]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store local-kv-store :a 1))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats local-kv-store :a)))
; cache looks up underlying store during miss
(is (kv/fetch local-kv-store :a))
(is (= 1 (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
; store to cache propagates to underlying store
(with-redefs [t/now (constantly time-2)]
(kv/store cached-kv-store :b 2))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-2)}
(kv/stats local-kv-store :b)))
(is (true? (cu/cache-contains? cache :b)))
(is (= 2 (kv/fetch cached-kv-store :b)))
(is (= 2 (kv/fetch local-kv-store :b)))
(with-redefs [t/now (constantly time-3)]
(kv/store cached-kv-store :b 11))
(is (= 11 (kv/fetch cached-kv-store :b)))
(is (= 11 (kv/fetch local-kv-store :b)))
; cache works with refresh call
(with-redefs [t/now (constantly time-4)]
(kv/store cached-kv-store :b 13))
(is (true? (cu/cache-contains? cache :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(with-redefs [t/now (constantly time-5)]
(kv/store local-kv-store :b 17))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
(kv/stats local-kv-store :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(is (= 17 (kv/fetch local-kv-store :b)))
(is (= 17 (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 2
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}
:b {:stats {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
:value 17}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))
; delete removes entry from cache
(kv/delete cached-kv-store :b)
(is (false? (cu/cache-contains? cache :b)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))))
(deftest test-validate-zk-key
(kv/validate-zk-key "test-key")
(is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key")))
(is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key ".."))))
(deftest test-key->zk-key
(is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah")))
(is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah"))))
(deftest test-zk-kv-store
(let [zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
services-base-path "/test-zk-kv-store/base-path"]
(is (kv/new-zk-kv-store {:curator curator
:base-path "/waiter-tokens"
:sync-timeout-ms 1}))
(try
(.start curator)
(testing "in-memory-zk"
(let [get-value-from-curator (fn [key]
(.forPath (.checkExists curator)
(kv/key->zk-path services-base-path key)))
test-store (kv/new-zk-kv-store {:curator curator
:base-path services-base-path
:sync-timeout-ms 1})
bytes (byte-array 10)
include-flags #{"data"}
creation-time-promise (promise)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(kv/store test-store "a" bytes)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= ctime mtime))
(deliver creation-time-promise ctime))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(kv/store test-store "a" 3)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= @creation-time-promise ctime))
(is (< @creation-time-promise mtime)))
(is (= 3 (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "a")
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "does-not-exist")
(is (nil? (get-value-from-curator "does-not-exist")))
(is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store include-flags)))))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-kv-store
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(is (= "bar" (kv/retrieve kv-store "foo" true)))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-zk-kv-store
(testing "Creating a new ZooKeeper key/value store"
(testing "should throw on non-integer sync-timeout-ms"
(is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework)
:base-path ""
:sync-timeout-ms 1.1}))))))
(deftest test-zk-keys
(testing "List ZK keys"
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(kv/store kv-store "foo2" "bar2")
(kv/store kv-store "foo3" "bar3")
(is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config))))))
(finally
(.close curator)
(.stop zk-server))))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.kv-test
(:require [clj-time.coerce :as tc]
[clj-time.core :as t]
[clojure.java.io :as io]
[clojure.test :refer :all]
[waiter.curator :as curator]
[waiter.kv :as kv]
[waiter.util.cache-utils :as cu])
(:import (java.util Arrays)
(org.apache.curator.framework CuratorFramework CuratorFrameworkFactory)
(org.apache.curator.retry RetryNTimes)))
(deftest test-local-kv-store
(let [test-store (kv/new-local-kv-store {})
bytes (byte-array 10)
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value bytes}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "in-memory"}
(kv/state test-store include-flags)))))
(defn work-dir
"Returns the canonical path for the ./kv-store directory"
[]
(-> "./kv-store" (io/file) (.getCanonicalPath)))
(deftest test-file-based-kv-store
(let [target-file (str (work-dir) "/foo.bin")
include-flags #{"data"}
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))]
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})
bytes (byte-array 10)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store test-store :a bytes))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats test-store :a)))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store :a)))
(with-redefs [t/now (constantly time-2)]
(kv/store test-store :a 3))
(is (= 3 (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))
;; testing data was persisted in the file
(let [test-store (kv/new-file-based-kv-store {:target-file target-file})]
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
(kv/stats test-store :a)))
(is (= {:store {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-2)}
:value 3}}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags)))
(kv/delete test-store :a)
(is (nil? (kv/fetch test-store :a)))
(is (nil? (kv/fetch test-store :b)))
(kv/delete test-store :does-not-exist)
(is (= {:store {:count 0, :data {}}
:supported-include-params ["data"]
:variant "file-based"}
(kv/state test-store include-flags))))))
(deftest test-encrypted-kv-store
(let [passwords ["PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI"]
processed-passwords (mapv #(vector :cached %) passwords)
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
; store propagates to underlying store
(kv/store encrypted-kv-store :b 2)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store does not corrupt underlying store
(kv/store encrypted-kv-store :a 5)
(is (not (nil? (kv/fetch local-kv-store :a))))
(is (= 5 (kv/fetch encrypted-kv-store :a)))
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 2 (kv/fetch encrypted-kv-store :b)))
; store updates underlying store
(kv/store encrypted-kv-store :b 11)
(is (not (nil? (kv/fetch local-kv-store :b))))
(is (= 11 (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= 2 (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :count])))
(is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store :data])))))
; delete :a and :b
(kv/delete encrypted-kv-store :a)
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch encrypted-kv-store :a)))
(kv/delete encrypted-kv-store :b)
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch encrypted-kv-store :b)))
(is (= "encrypted" (get (kv/state encrypted-kv-store include-flags) :variant)))
(is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store include-flags) [:inner-state :store])))
(kv/delete encrypted-kv-store :does-not-exist)))
(deftest test-cached-kv-store
(let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)}
local-kv-store (kv/new-local-kv-store {})
include-flags #{"data"}
{:keys [cache] :as cached-kv-store} (kv/new-cached-kv-store cache-config local-kv-store)
time-0 (t/now)
time-1 (t/plus time-0 (t/seconds 1))
time-2 (t/plus time-0 (t/seconds 2))
time-3 (t/plus time-0 (t/seconds 3))
time-4 (t/plus time-0 (t/seconds 4))
time-5 (t/plus time-0 (t/seconds 5))]
(is (nil? (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
(with-redefs [t/now (constantly time-1)]
(kv/store local-kv-store :a 1))
(is (= {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
(kv/stats local-kv-store :a)))
; cache looks up underlying store during miss
(is (kv/fetch local-kv-store :a))
(is (= 1 (kv/fetch local-kv-store :a)))
(is (nil? (kv/fetch cached-kv-store :a)))
; store to cache propagates to underlying store
(with-redefs [t/now (constantly time-2)]
(kv/store cached-kv-store :b 2))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-2)}
(kv/stats local-kv-store :b)))
(is (true? (cu/cache-contains? cache :b)))
(is (= 2 (kv/fetch cached-kv-store :b)))
(is (= 2 (kv/fetch local-kv-store :b)))
(with-redefs [t/now (constantly time-3)]
(kv/store cached-kv-store :b 11))
(is (= 11 (kv/fetch cached-kv-store :b)))
(is (= 11 (kv/fetch local-kv-store :b)))
; cache works with refresh call
(with-redefs [t/now (constantly time-4)]
(kv/store cached-kv-store :b 13))
(is (true? (cu/cache-contains? cache :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(with-redefs [t/now (constantly time-5)]
(kv/store local-kv-store :b 17))
(is (= {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
(kv/stats local-kv-store :b)))
(is (= 13 (kv/fetch cached-kv-store :b)))
(is (= 17 (kv/fetch local-kv-store :b)))
(is (= 17 (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 2
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}
:b {:stats {:creation-time (tc/to-long time-2)
:modified-time (tc/to-long time-5)}
:value 17}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))
; delete removes entry from cache
(kv/delete cached-kv-store :b)
(is (false? (cu/cache-contains? cache :b)))
(is (nil? (kv/fetch local-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b)))
(is (nil? (kv/fetch cached-kv-store :b :refresh true)))
(is (= "cache" (get (kv/state cached-kv-store include-flags) :variant)))
(is (= {:count 1
:data {:a {:stats {:creation-time (tc/to-long time-1)
:modified-time (tc/to-long time-1)}
:value 1}}}
(get-in (kv/state cached-kv-store include-flags) [:inner-state :store])))))
(deftest test-validate-zk-key
(kv/validate-zk-key "test-key")
(is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key")))
(is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key ".."))))
(deftest test-key->zk-key
(is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah")))
(is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah"))))
(deftest test-zk-kv-store
(let [zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
services-base-path "/test-zk-kv-store/base-path"]
(is (kv/new-zk-kv-store {:curator curator
:base-path "/waiter-tokens"
:sync-timeout-ms 1}))
(try
(.start curator)
(testing "in-memory-zk"
(let [get-value-from-curator (fn [key]
(.forPath (.checkExists curator)
(kv/key->zk-path services-base-path key)))
test-store (kv/new-zk-kv-store {:curator curator
:base-path services-base-path
:sync-timeout-ms 1})
bytes (byte-array 10)
include-flags #{"data"}
creation-time-promise (promise)]
(Arrays/fill bytes (byte 1))
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(kv/store test-store "a" bytes)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= ctime mtime))
(deliver creation-time-promise ctime))
(is (Arrays/equals bytes ^bytes (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(kv/store test-store "a" 3)
(let [{:keys [stat]} (curator/read-path curator
(kv/key->zk-path services-base-path "a")
:nil-on-missing? true
:serializer :nippy)
{:keys [ctime mtime]} stat]
(is (= {:creation-time ctime :modified-time mtime}
(kv/stats test-store "a")))
(is (= @creation-time-promise ctime))
(is (< @creation-time-promise mtime)))
(is (= 3 (kv/fetch test-store "a")))
(is (not (nil? (get-value-from-curator "a"))))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "a")
(is (nil? (kv/fetch test-store "a")))
(is (nil? (get-value-from-curator "a")))
(is (nil? (kv/fetch test-store "b")))
(is (nil? (get-value-from-curator "b")))
(kv/delete test-store "does-not-exist")
(is (nil? (get-value-from-curator "does-not-exist")))
(is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store include-flags)))))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-kv-store
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(is (= "bar" (kv/retrieve kv-store "foo" true)))
(finally
(.close curator)
(.stop zk-server)))))
(deftest test-new-zk-kv-store
(testing "Creating a new ZooKeeper key/value store"
(testing "should throw on non-integer sync-timeout-ms"
(is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework)
:base-path ""
:sync-timeout-ms 1.1}))))))
(deftest test-zk-keys
(testing "List ZK keys"
(let [base-path "/waiter"
kv-config {:kind :zk
:zk {:factory-fn 'waiter.kv/new-zk-kv-store
:sync-timeout-ms 2000}
:relative-path "tokens"}
zk (curator/start-in-process-zookeeper)
zk-server (:zk-server zk)
curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100))
kv-store (kv/new-kv-store kv-config curator base-path nil)]
(try
(.start curator)
(kv/store kv-store "foo" "bar")
(kv/store kv-store "foo2" "bar2")
(kv/store kv-store "foo3" "bar3")
(is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config))))))
(finally
(.close curator)
(.stop zk-server))))))
|
[
{
"context": "est-migrate-user-organizations\n (is (= {:userid \"alice\" :userattrs {:something 42\n ",
"end": 883,
"score": 0.9937039613723755,
"start": 878,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "}}\n (migrate-user-organizations {:userid \"alice\"\n :userattrs",
"end": 1021,
"score": 0.9913572669029236,
"start": 1016,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " organizations even if empty\")\n (is (= {:userid \"alice\" :userattrs {:something 42\n ",
"end": 1157,
"score": 0.9903106689453125,
"start": 1152,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "}}\n (migrate-user-organizations {:userid \"alice\"\n :userattrs",
"end": 1323,
"score": 0.9921610355377197,
"start": 1318,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "d-user! rems.db.core/*db*\n {:user \"alice\"\n :userattrs (json/generate-strin",
"end": 2131,
"score": 0.9948139190673828,
"start": 2126,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " :userattrs (json/generate-string {:eppn \"alice\"\n ",
"end": 2196,
"score": 0.9935179948806763,
"start": 2191,
"tag": "NAME",
"value": "alice"
},
{
"context": " :mail \"alice@example.com\"\n ",
"end": 2273,
"score": 0.9999135136604309,
"start": 2256,
"tag": "EMAIL",
"value": "alice@example.com"
},
{
"context": " :commonName \"Alice Applicant\"\n ",
"end": 2354,
"score": 0.9996259808540344,
"start": 2339,
"tag": "NAME",
"value": "Alice Applicant"
}
] | src/clj/rems/migrations/multiple_organizations.clj | ossilva/rems | 31 | (ns rems.migrations.multiple-organizations
(:require [clojure.test :refer [deftest is]]
[hugsql.core :as hugsql]
[rems.json :as json]
[rems.db.core :as db]))
(hugsql/def-db-fns-from-string
"
-- :name get-users :? :*
SELECT
userId,
userAttrs::TEXT
FROM users
-- :name set-user-attributes! :!
UPDATE users SET userAttrs = :userattrs::jsonb WHERE userid = :userid;
")
(defn- migrate-user-organizations [{:keys [userid userattrs]}]
(let [existing-organizations (if (:organization userattrs)
[{:organization/id (:organization userattrs)}]
[])]
{:userid userid
:userattrs (-> userattrs
(assoc :organizations existing-organizations)
(dissoc :organization))}))
(deftest test-migrate-user-organizations
(is (= {:userid "alice" :userattrs {:something 42
:organizations []}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42}}))
"adds organizations even if empty")
(is (= {:userid "alice" :userattrs {:something 42
:organizations [{:organization/id "default"}]}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42
:organization "default"}}))))
(defn migrate-user-organizations! [conn users]
(doseq [{:keys [userattrs] :as user} users
:let [userattrs (json/parse-string userattrs)
user (assoc user :userattrs userattrs)]
:when (not (:organizations userattrs))]
(set-user-attributes! conn
(update (migrate-user-organizations user)
:userattrs
json/generate-string))))
(defn migrate-up [{:keys [conn]}]
(migrate-user-organizations! conn (get-users conn)))
(comment
(migrate-up {:conn rems.db.core/*db*})
(db/add-user! rems.db.core/*db*
{:user "alice"
:userattrs (json/generate-string {:eppn "alice"
:mail "alice@example.com"
:commonName "Alice Applicant"
:organization "default"})}))
| 11932 | (ns rems.migrations.multiple-organizations
(:require [clojure.test :refer [deftest is]]
[hugsql.core :as hugsql]
[rems.json :as json]
[rems.db.core :as db]))
(hugsql/def-db-fns-from-string
"
-- :name get-users :? :*
SELECT
userId,
userAttrs::TEXT
FROM users
-- :name set-user-attributes! :!
UPDATE users SET userAttrs = :userattrs::jsonb WHERE userid = :userid;
")
(defn- migrate-user-organizations [{:keys [userid userattrs]}]
(let [existing-organizations (if (:organization userattrs)
[{:organization/id (:organization userattrs)}]
[])]
{:userid userid
:userattrs (-> userattrs
(assoc :organizations existing-organizations)
(dissoc :organization))}))
(deftest test-migrate-user-organizations
(is (= {:userid "alice" :userattrs {:something 42
:organizations []}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42}}))
"adds organizations even if empty")
(is (= {:userid "alice" :userattrs {:something 42
:organizations [{:organization/id "default"}]}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42
:organization "default"}}))))
(defn migrate-user-organizations! [conn users]
(doseq [{:keys [userattrs] :as user} users
:let [userattrs (json/parse-string userattrs)
user (assoc user :userattrs userattrs)]
:when (not (:organizations userattrs))]
(set-user-attributes! conn
(update (migrate-user-organizations user)
:userattrs
json/generate-string))))
(defn migrate-up [{:keys [conn]}]
(migrate-user-organizations! conn (get-users conn)))
(comment
(migrate-up {:conn rems.db.core/*db*})
(db/add-user! rems.db.core/*db*
{:user "alice"
:userattrs (json/generate-string {:eppn "<NAME>"
:mail "<EMAIL>"
:commonName "<NAME>"
:organization "default"})}))
| true | (ns rems.migrations.multiple-organizations
(:require [clojure.test :refer [deftest is]]
[hugsql.core :as hugsql]
[rems.json :as json]
[rems.db.core :as db]))
(hugsql/def-db-fns-from-string
"
-- :name get-users :? :*
SELECT
userId,
userAttrs::TEXT
FROM users
-- :name set-user-attributes! :!
UPDATE users SET userAttrs = :userattrs::jsonb WHERE userid = :userid;
")
(defn- migrate-user-organizations [{:keys [userid userattrs]}]
(let [existing-organizations (if (:organization userattrs)
[{:organization/id (:organization userattrs)}]
[])]
{:userid userid
:userattrs (-> userattrs
(assoc :organizations existing-organizations)
(dissoc :organization))}))
(deftest test-migrate-user-organizations
(is (= {:userid "alice" :userattrs {:something 42
:organizations []}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42}}))
"adds organizations even if empty")
(is (= {:userid "alice" :userattrs {:something 42
:organizations [{:organization/id "default"}]}}
(migrate-user-organizations {:userid "alice"
:userattrs {:something 42
:organization "default"}}))))
(defn migrate-user-organizations! [conn users]
(doseq [{:keys [userattrs] :as user} users
:let [userattrs (json/parse-string userattrs)
user (assoc user :userattrs userattrs)]
:when (not (:organizations userattrs))]
(set-user-attributes! conn
(update (migrate-user-organizations user)
:userattrs
json/generate-string))))
(defn migrate-up [{:keys [conn]}]
(migrate-user-organizations! conn (get-users conn)))
(comment
(migrate-up {:conn rems.db.core/*db*})
(db/add-user! rems.db.core/*db*
{:user "alice"
:userattrs (json/generate-string {:eppn "PI:NAME:<NAME>END_PI"
:mail "PI:EMAIL:<EMAIL>END_PI"
:commonName "PI:NAME:<NAME>END_PI"
:organization "default"})}))
|
[
{
"context": "elpers.lib :refer :all]))\n\n; Originally written by Phil Potter and copied from the Overtone examples\n\n(defn stri",
"end": 153,
"score": 0.9998435974121094,
"start": 142,
"tag": "NAME",
"value": "Phil Potter"
}
] | src/whelmed/contrib/harpsichord.clj | ctford/whelmed | 32 | (ns whelmed.contrib.harpsichord
(:require
[overtone.live :refer :all]
[overtone.helpers.lib :refer :all]))
; Originally written by Phil Potter and copied from the Overtone examples
(defn string
[freq duration]
(with-overloaded-ugens
(+ (* (line:kr 1 1 duration)
(pluck (* (white-noise) (env-gen (perc 0.001 5) :action FREE))
1 1 (/ 1 freq) (* duration 2) 0.25)))))
(definst harpsichord [freq 440 vol 1.0 pan 0.0 wet 0.5 room 0.5 limit 5000]
(let [duration 1
snd (string freq duration)
t1 (* 0.2 (string (* 2/1 freq) duration))
t2 (* 0.15 (string (* 3/2 freq) duration))
t3 (* 0.1 (string (* 4/3 freq) duration))
t4 (* 0.1 (string (* 5/4 freq) duration))
full-snd (+ snd (mix [t1 t2 t3 t4]))]
(-> full-snd (* vol) (free-verb :mix wet :room room) (lpf limit) (pan2 pan))))
| 5300 | (ns whelmed.contrib.harpsichord
(:require
[overtone.live :refer :all]
[overtone.helpers.lib :refer :all]))
; Originally written by <NAME> and copied from the Overtone examples
(defn string
[freq duration]
(with-overloaded-ugens
(+ (* (line:kr 1 1 duration)
(pluck (* (white-noise) (env-gen (perc 0.001 5) :action FREE))
1 1 (/ 1 freq) (* duration 2) 0.25)))))
(definst harpsichord [freq 440 vol 1.0 pan 0.0 wet 0.5 room 0.5 limit 5000]
(let [duration 1
snd (string freq duration)
t1 (* 0.2 (string (* 2/1 freq) duration))
t2 (* 0.15 (string (* 3/2 freq) duration))
t3 (* 0.1 (string (* 4/3 freq) duration))
t4 (* 0.1 (string (* 5/4 freq) duration))
full-snd (+ snd (mix [t1 t2 t3 t4]))]
(-> full-snd (* vol) (free-verb :mix wet :room room) (lpf limit) (pan2 pan))))
| true | (ns whelmed.contrib.harpsichord
(:require
[overtone.live :refer :all]
[overtone.helpers.lib :refer :all]))
; Originally written by PI:NAME:<NAME>END_PI and copied from the Overtone examples
(defn string
[freq duration]
(with-overloaded-ugens
(+ (* (line:kr 1 1 duration)
(pluck (* (white-noise) (env-gen (perc 0.001 5) :action FREE))
1 1 (/ 1 freq) (* duration 2) 0.25)))))
(definst harpsichord [freq 440 vol 1.0 pan 0.0 wet 0.5 room 0.5 limit 5000]
(let [duration 1
snd (string freq duration)
t1 (* 0.2 (string (* 2/1 freq) duration))
t2 (* 0.15 (string (* 3/2 freq) duration))
t3 (* 0.1 (string (* 4/3 freq) duration))
t4 (* 0.1 (string (* 5/4 freq) duration))
full-snd (+ snd (mix [t1 t2 t3 t4]))]
(-> full-snd (* vol) (free-verb :mix wet :room room) (lpf limit) (pan2 pan))))
|
[
{
"context": ";; Copyright 2015 Timothy Brooks\n;;\n;; Licensed under the Apache License, Version ",
"end": 32,
"score": 0.9998632073402405,
"start": 18,
"tag": "NAME",
"value": "Timothy Brooks"
}
] | src/beehive_http/core.clj | tbrooks8/Beehive-http | 0 | ;; Copyright 2015 Timothy Brooks
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns beehive-http.core
(:require [beehive.future :as f])
(:import (java.util Map)
(java.util.concurrent TimeUnit)
(beehive_http Transformer HttpAsyncService)
(com.ning.http.client AsyncHttpClient
RequestBuilder
AsyncHttpProvider
AsyncHttpClientConfig$Builder)
(com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig
NettyAsyncHttpProvider)
(com.ning.http.client.providers.netty.response NettyResponse)
(net.uncontended.precipice ServiceProperties
RejectedActionException)
(org.jboss.netty.util HashedWheelTimer)))
(set! *warn-on-reflection* true)
(defn parse-response [^NettyResponse response]
{:status (.getStatusCode response)
:headers (.getHeaders response)
:body (.getResponseBody response)})
(def response-transformer
(reify Transformer
(transform [_ response]
(parse-response response))))
(defn async-http-client [& {:keys [socket-timeout]}]
(let [timer (HashedWheelTimer. 10 TimeUnit/MILLISECONDS)
netty-config (doto (NettyAsyncHttpProviderConfig.)
(.setNettyTimer timer))
client-config (.build
(doto (AsyncHttpClientConfig$Builder.)
(.setAsyncHttpClientProviderConfig netty-config)
(.setConnectTimeout (int (or socket-timeout 15)))
(.setReadTimeout (int (or socket-timeout 15)))))
provider (NettyAsyncHttpProvider. client-config)]
(AsyncHttpClient. ^AsyncHttpProvider provider)))
(defn format-headers [headers]
(into {} (mapv (fn [[k v]]
[k (if (sequential? v) v (vector v))])
headers)))
(defn request [url & {:keys [timeout headers body method]}]
(let [builder (RequestBuilder.)]
(.setUrl builder ^String url)
(when method (.setMethod builder ^String method))
(when headers (.setHeaders builder ^Map (format-headers headers)))
(when body (.setBody builder ^bytes body))
(when timeout (.setRequestTimeout builder (int timeout)))
(.build builder)))
(defn service [name & http-configs]
(let [properties (ServiceProperties.)]
(HttpAsyncService. name properties (apply async-http-client http-configs))))
(defn execute [^HttpAsyncService service request]
(try
(f/->BeehiveFuture
(.submitRequest service request response-transformer))
(catch RejectedActionException e
(f/->BeehiveRejectedFuture e (.reason e))))) | 121286 | ;; Copyright 2015 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns beehive-http.core
(:require [beehive.future :as f])
(:import (java.util Map)
(java.util.concurrent TimeUnit)
(beehive_http Transformer HttpAsyncService)
(com.ning.http.client AsyncHttpClient
RequestBuilder
AsyncHttpProvider
AsyncHttpClientConfig$Builder)
(com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig
NettyAsyncHttpProvider)
(com.ning.http.client.providers.netty.response NettyResponse)
(net.uncontended.precipice ServiceProperties
RejectedActionException)
(org.jboss.netty.util HashedWheelTimer)))
(set! *warn-on-reflection* true)
(defn parse-response [^NettyResponse response]
{:status (.getStatusCode response)
:headers (.getHeaders response)
:body (.getResponseBody response)})
(def response-transformer
(reify Transformer
(transform [_ response]
(parse-response response))))
(defn async-http-client [& {:keys [socket-timeout]}]
(let [timer (HashedWheelTimer. 10 TimeUnit/MILLISECONDS)
netty-config (doto (NettyAsyncHttpProviderConfig.)
(.setNettyTimer timer))
client-config (.build
(doto (AsyncHttpClientConfig$Builder.)
(.setAsyncHttpClientProviderConfig netty-config)
(.setConnectTimeout (int (or socket-timeout 15)))
(.setReadTimeout (int (or socket-timeout 15)))))
provider (NettyAsyncHttpProvider. client-config)]
(AsyncHttpClient. ^AsyncHttpProvider provider)))
(defn format-headers [headers]
(into {} (mapv (fn [[k v]]
[k (if (sequential? v) v (vector v))])
headers)))
(defn request [url & {:keys [timeout headers body method]}]
(let [builder (RequestBuilder.)]
(.setUrl builder ^String url)
(when method (.setMethod builder ^String method))
(when headers (.setHeaders builder ^Map (format-headers headers)))
(when body (.setBody builder ^bytes body))
(when timeout (.setRequestTimeout builder (int timeout)))
(.build builder)))
(defn service [name & http-configs]
(let [properties (ServiceProperties.)]
(HttpAsyncService. name properties (apply async-http-client http-configs))))
(defn execute [^HttpAsyncService service request]
(try
(f/->BeehiveFuture
(.submitRequest service request response-transformer))
(catch RejectedActionException e
(f/->BeehiveRejectedFuture e (.reason e))))) | true | ;; Copyright 2015 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns beehive-http.core
(:require [beehive.future :as f])
(:import (java.util Map)
(java.util.concurrent TimeUnit)
(beehive_http Transformer HttpAsyncService)
(com.ning.http.client AsyncHttpClient
RequestBuilder
AsyncHttpProvider
AsyncHttpClientConfig$Builder)
(com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig
NettyAsyncHttpProvider)
(com.ning.http.client.providers.netty.response NettyResponse)
(net.uncontended.precipice ServiceProperties
RejectedActionException)
(org.jboss.netty.util HashedWheelTimer)))
(set! *warn-on-reflection* true)
(defn parse-response [^NettyResponse response]
{:status (.getStatusCode response)
:headers (.getHeaders response)
:body (.getResponseBody response)})
(def response-transformer
(reify Transformer
(transform [_ response]
(parse-response response))))
(defn async-http-client [& {:keys [socket-timeout]}]
(let [timer (HashedWheelTimer. 10 TimeUnit/MILLISECONDS)
netty-config (doto (NettyAsyncHttpProviderConfig.)
(.setNettyTimer timer))
client-config (.build
(doto (AsyncHttpClientConfig$Builder.)
(.setAsyncHttpClientProviderConfig netty-config)
(.setConnectTimeout (int (or socket-timeout 15)))
(.setReadTimeout (int (or socket-timeout 15)))))
provider (NettyAsyncHttpProvider. client-config)]
(AsyncHttpClient. ^AsyncHttpProvider provider)))
(defn format-headers [headers]
(into {} (mapv (fn [[k v]]
[k (if (sequential? v) v (vector v))])
headers)))
(defn request [url & {:keys [timeout headers body method]}]
(let [builder (RequestBuilder.)]
(.setUrl builder ^String url)
(when method (.setMethod builder ^String method))
(when headers (.setHeaders builder ^Map (format-headers headers)))
(when body (.setBody builder ^bytes body))
(when timeout (.setRequestTimeout builder (int timeout)))
(.build builder)))
(defn service [name & http-configs]
(let [properties (ServiceProperties.)]
(HttpAsyncService. name properties (apply async-http-client http-configs))))
(defn execute [^HttpAsyncService service request]
(try
(f/->BeehiveFuture
(.submitRequest service request response-transformer))
(catch RejectedActionException e
(f/->BeehiveRejectedFuture e (.reason e))))) |
[
{
"context": ";; Copyright 2017 7bridges s.r.l.\n;;\n;; Licensed under the Apache License",
"end": 23,
"score": 0.818954586982727,
"start": 18,
"tag": "USERNAME",
"value": "7brid"
},
{
"context": "me odatetime)))\n\n(def oemb {:_class \"User\" :name \"Test\"})\n\n(def oemap {:test \"1\"})\n\n(def oridtree {:_ori",
"end": 1044,
"score": 0.9984396696090698,
"start": 1040,
"tag": "NAME",
"value": "Test"
}
] | test/clj_odbp/binary/serialize/types_test.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-test
(:require [clj-odbp.binary.serialize.types :as t]
[midje.sweet :refer :all])
(:import [java.text SimpleDateFormat]))
(defn format-date
[format s]
(let [formatter (SimpleDateFormat. format)]
(.parse formatter s)))
(def odatetime
(format-date "dd/MM/YYYY hh:mm:ss" "19/07/2017 10:30:00"))
(def odatetime-result
(t/serialize (.getTime odatetime)))
(def oemb {:_class "User" :name "Test"})
(def oemap {:test "1"})
(def oridtree {:_oridtree {:uuid-low 1 :uuid-high 2
:filed-id 3 :page-index 4
:page-offset 5
:changes [{:cluster-id 6 :record-position 7
:change-type 0 :change 8}
{:cluster-id 9 :record-position 10
:change-type 1 :change 11}]}})
(facts "Serialization of single types and record"
(fact "Short - short 1 should return [2]"
(t/serialize (short 1)) => [2])
(fact "Integer - integer 1 should return [20]"
(t/serialize (int 10)) => [20])
(fact "Long - long 1000000 should return [128 137 122]"
(t/serialize (long 1000000)) => [128 137 122])
(fact "Byte - byte 1 should return byte [1]"
(t/serialize (byte 1)) => [(byte 1)])
(fact "Boolean - boolean true should return byte 1"
(t/serialize true) => [(byte 1)])
(fact "Boolean - boolean false should return byte 0"
(t/serialize false) => [(byte 0)])
(fact "Float - float 2.50 should return the bytes [64, 32, 0, 0]"
(t/serialize (float 2.50)) => [64, 32, 0, 0])
(fact "Double - double 20000.50 should return the bytes [64 -45 -120 32 0 0 0 0]"
(t/serialize (double 20000.50)) => [64 -45 -120 32 0 0 0 0])
(fact "BigDecimal - bigdec 12.34M should return the bytes [0 0 0 2 0 0 0 2 4 -46]"
(t/serialize 12.34M) => [0 0 0 2 0 0 0 2 4 -46])
(fact "String - string 'test' should return [8 116 101 115 116]"
(t/serialize "test") => [8 116 101 115 116])
(fact "Keyword - keyword :test should return [8 116 101 115 116]"
(t/serialize :test) => [8 116 101 115 116])
(fact "Binary - orient-binary [1 2 3] should return [6 1 2 3]"
(t/serialize {:_obinary {:value [1 2 3]}}) => [6 1 2 3])
(fact "Vector - [1 2 3] should return [6 23 1 2 1 4 1 6]"
(t/serialize [1 2 3]) => [6 23 1 2 1 4 1 6])
(fact "Map - map {:name 'test'} should return [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116]"
(t/serialize {:name "test"}) => [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116])
(fact "DateTime - odatetime should return odatetime-result"
(t/serialize odatetime) => odatetime-result)
(fact "Embedded record - oemb should return [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116]"
(t/serialize oemb) => [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116])
(fact "Embedded list - (12 13 14) should return [6 23 1 24 1 26 1 28]"
(t/serialize '(12 13 14)) => [6 23 1 24 1 26 1 28])
(fact "Embedded set - #{12 13 14} should return [6 23 1 24 1 26 1 28]"
(t/serialize #{12 13 14}) =>
(just [6 23 1 24 1 26 1 28] :in-any-order))
(fact "Link - #33:0 should return [66 0]"
(t/serialize "#33:0") => [66 0])
(fact "Link list - (#33:1 #34:1) should return [4 66 2 68 2]"
(t/serialize (list "#33:1" "#34:1")) => [4 66 2 68 2])
(fact "Link set - #{#33:1 #34:1} should return [4 66 2 68 2]"
(t/serialize #{"#33:1" "#34:1"}) =>
(just [4 66 2 68 2] :in-any-order))
(fact "Link map - {'test' #33:1} should return [2 7 8 116 101 115 116 66 2]"
(t/serialize {"test" "#33:1"}) => [2 7 8 116 101 115 116 66 2])
(fact "RidBag - serialize embedded ORigBag"
(t/serialize {:_oridbag {:uuid-low 1 :uuid-high 2 :bag ["#2:3" "#4:5"]}})
=> [1 0 0 0 2 0 2 0 0 0 0 0 0 0 3 0 4 0 0 0 0 0 0 0 5])
(fact "RidTree - serialize ORidTree"
(t/serialize oridtree) => [0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 4 0 0 0 5 0 0 0 2 0 6 0
0 0 0 0 0 0 7 0 0 0 0 8 0 9 0 0 0 0 0 0 0 10 1 0 0 0 11])
(fact "Embedded map - oemap should return [2 7 8 116 101 115 116 0 0 0 12 7 2 49]"
(t/serialize oemap) => [2 7 8 116 101 115 116 0 0 0 12 7 2 49]))
| 44432 | ;; 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-test
(:require [clj-odbp.binary.serialize.types :as t]
[midje.sweet :refer :all])
(:import [java.text SimpleDateFormat]))
(defn format-date
[format s]
(let [formatter (SimpleDateFormat. format)]
(.parse formatter s)))
(def odatetime
(format-date "dd/MM/YYYY hh:mm:ss" "19/07/2017 10:30:00"))
(def odatetime-result
(t/serialize (.getTime odatetime)))
(def oemb {:_class "User" :name "<NAME>"})
(def oemap {:test "1"})
(def oridtree {:_oridtree {:uuid-low 1 :uuid-high 2
:filed-id 3 :page-index 4
:page-offset 5
:changes [{:cluster-id 6 :record-position 7
:change-type 0 :change 8}
{:cluster-id 9 :record-position 10
:change-type 1 :change 11}]}})
(facts "Serialization of single types and record"
(fact "Short - short 1 should return [2]"
(t/serialize (short 1)) => [2])
(fact "Integer - integer 1 should return [20]"
(t/serialize (int 10)) => [20])
(fact "Long - long 1000000 should return [128 137 122]"
(t/serialize (long 1000000)) => [128 137 122])
(fact "Byte - byte 1 should return byte [1]"
(t/serialize (byte 1)) => [(byte 1)])
(fact "Boolean - boolean true should return byte 1"
(t/serialize true) => [(byte 1)])
(fact "Boolean - boolean false should return byte 0"
(t/serialize false) => [(byte 0)])
(fact "Float - float 2.50 should return the bytes [64, 32, 0, 0]"
(t/serialize (float 2.50)) => [64, 32, 0, 0])
(fact "Double - double 20000.50 should return the bytes [64 -45 -120 32 0 0 0 0]"
(t/serialize (double 20000.50)) => [64 -45 -120 32 0 0 0 0])
(fact "BigDecimal - bigdec 12.34M should return the bytes [0 0 0 2 0 0 0 2 4 -46]"
(t/serialize 12.34M) => [0 0 0 2 0 0 0 2 4 -46])
(fact "String - string 'test' should return [8 116 101 115 116]"
(t/serialize "test") => [8 116 101 115 116])
(fact "Keyword - keyword :test should return [8 116 101 115 116]"
(t/serialize :test) => [8 116 101 115 116])
(fact "Binary - orient-binary [1 2 3] should return [6 1 2 3]"
(t/serialize {:_obinary {:value [1 2 3]}}) => [6 1 2 3])
(fact "Vector - [1 2 3] should return [6 23 1 2 1 4 1 6]"
(t/serialize [1 2 3]) => [6 23 1 2 1 4 1 6])
(fact "Map - map {:name 'test'} should return [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116]"
(t/serialize {:name "test"}) => [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116])
(fact "DateTime - odatetime should return odatetime-result"
(t/serialize odatetime) => odatetime-result)
(fact "Embedded record - oemb should return [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116]"
(t/serialize oemb) => [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116])
(fact "Embedded list - (12 13 14) should return [6 23 1 24 1 26 1 28]"
(t/serialize '(12 13 14)) => [6 23 1 24 1 26 1 28])
(fact "Embedded set - #{12 13 14} should return [6 23 1 24 1 26 1 28]"
(t/serialize #{12 13 14}) =>
(just [6 23 1 24 1 26 1 28] :in-any-order))
(fact "Link - #33:0 should return [66 0]"
(t/serialize "#33:0") => [66 0])
(fact "Link list - (#33:1 #34:1) should return [4 66 2 68 2]"
(t/serialize (list "#33:1" "#34:1")) => [4 66 2 68 2])
(fact "Link set - #{#33:1 #34:1} should return [4 66 2 68 2]"
(t/serialize #{"#33:1" "#34:1"}) =>
(just [4 66 2 68 2] :in-any-order))
(fact "Link map - {'test' #33:1} should return [2 7 8 116 101 115 116 66 2]"
(t/serialize {"test" "#33:1"}) => [2 7 8 116 101 115 116 66 2])
(fact "RidBag - serialize embedded ORigBag"
(t/serialize {:_oridbag {:uuid-low 1 :uuid-high 2 :bag ["#2:3" "#4:5"]}})
=> [1 0 0 0 2 0 2 0 0 0 0 0 0 0 3 0 4 0 0 0 0 0 0 0 5])
(fact "RidTree - serialize ORidTree"
(t/serialize oridtree) => [0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 4 0 0 0 5 0 0 0 2 0 6 0
0 0 0 0 0 0 7 0 0 0 0 8 0 9 0 0 0 0 0 0 0 10 1 0 0 0 11])
(fact "Embedded map - oemap should return [2 7 8 116 101 115 116 0 0 0 12 7 2 49]"
(t/serialize oemap) => [2 7 8 116 101 115 116 0 0 0 12 7 2 49]))
| 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-test
(:require [clj-odbp.binary.serialize.types :as t]
[midje.sweet :refer :all])
(:import [java.text SimpleDateFormat]))
(defn format-date
[format s]
(let [formatter (SimpleDateFormat. format)]
(.parse formatter s)))
(def odatetime
(format-date "dd/MM/YYYY hh:mm:ss" "19/07/2017 10:30:00"))
(def odatetime-result
(t/serialize (.getTime odatetime)))
(def oemb {:_class "User" :name "PI:NAME:<NAME>END_PI"})
(def oemap {:test "1"})
(def oridtree {:_oridtree {:uuid-low 1 :uuid-high 2
:filed-id 3 :page-index 4
:page-offset 5
:changes [{:cluster-id 6 :record-position 7
:change-type 0 :change 8}
{:cluster-id 9 :record-position 10
:change-type 1 :change 11}]}})
(facts "Serialization of single types and record"
(fact "Short - short 1 should return [2]"
(t/serialize (short 1)) => [2])
(fact "Integer - integer 1 should return [20]"
(t/serialize (int 10)) => [20])
(fact "Long - long 1000000 should return [128 137 122]"
(t/serialize (long 1000000)) => [128 137 122])
(fact "Byte - byte 1 should return byte [1]"
(t/serialize (byte 1)) => [(byte 1)])
(fact "Boolean - boolean true should return byte 1"
(t/serialize true) => [(byte 1)])
(fact "Boolean - boolean false should return byte 0"
(t/serialize false) => [(byte 0)])
(fact "Float - float 2.50 should return the bytes [64, 32, 0, 0]"
(t/serialize (float 2.50)) => [64, 32, 0, 0])
(fact "Double - double 20000.50 should return the bytes [64 -45 -120 32 0 0 0 0]"
(t/serialize (double 20000.50)) => [64 -45 -120 32 0 0 0 0])
(fact "BigDecimal - bigdec 12.34M should return the bytes [0 0 0 2 0 0 0 2 4 -46]"
(t/serialize 12.34M) => [0 0 0 2 0 0 0 2 4 -46])
(fact "String - string 'test' should return [8 116 101 115 116]"
(t/serialize "test") => [8 116 101 115 116])
(fact "Keyword - keyword :test should return [8 116 101 115 116]"
(t/serialize :test) => [8 116 101 115 116])
(fact "Binary - orient-binary [1 2 3] should return [6 1 2 3]"
(t/serialize {:_obinary {:value [1 2 3]}}) => [6 1 2 3])
(fact "Vector - [1 2 3] should return [6 23 1 2 1 4 1 6]"
(t/serialize [1 2 3]) => [6 23 1 2 1 4 1 6])
(fact "Map - map {:name 'test'} should return [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116]"
(t/serialize {:name "test"}) => [2 7 8 110 97 109 101 0 0 0 12 7 8 116 101 115 116])
(fact "DateTime - odatetime should return odatetime-result"
(t/serialize odatetime) => odatetime-result)
(fact "Embedded record - oemb should return [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116]"
(t/serialize oemb) => [0 8 85 115 101 114 8 110 97 109 101 0 0 0 17 7 0 8 84 101 115 116])
(fact "Embedded list - (12 13 14) should return [6 23 1 24 1 26 1 28]"
(t/serialize '(12 13 14)) => [6 23 1 24 1 26 1 28])
(fact "Embedded set - #{12 13 14} should return [6 23 1 24 1 26 1 28]"
(t/serialize #{12 13 14}) =>
(just [6 23 1 24 1 26 1 28] :in-any-order))
(fact "Link - #33:0 should return [66 0]"
(t/serialize "#33:0") => [66 0])
(fact "Link list - (#33:1 #34:1) should return [4 66 2 68 2]"
(t/serialize (list "#33:1" "#34:1")) => [4 66 2 68 2])
(fact "Link set - #{#33:1 #34:1} should return [4 66 2 68 2]"
(t/serialize #{"#33:1" "#34:1"}) =>
(just [4 66 2 68 2] :in-any-order))
(fact "Link map - {'test' #33:1} should return [2 7 8 116 101 115 116 66 2]"
(t/serialize {"test" "#33:1"}) => [2 7 8 116 101 115 116 66 2])
(fact "RidBag - serialize embedded ORigBag"
(t/serialize {:_oridbag {:uuid-low 1 :uuid-high 2 :bag ["#2:3" "#4:5"]}})
=> [1 0 0 0 2 0 2 0 0 0 0 0 0 0 3 0 4 0 0 0 0 0 0 0 5])
(fact "RidTree - serialize ORidTree"
(t/serialize oridtree) => [0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 4 0 0 0 5 0 0 0 2 0 6 0
0 0 0 0 0 0 7 0 0 0 0 8 0 9 0 0 0 0 0 0 0 10 1 0 0 0 11])
(fact "Embedded map - oemap should return [2 7 8 116 101 115 116 0 0 0 12 7 2 49]"
(t/serialize oemap) => [2 7 8 116 101 115 116 0 0 0 12 7 2 49]))
|
[
{
"context": "; Copyright (c) Gregg Reynolds. All rights reserved.\n; The use and distributio",
"end": 32,
"score": 0.9998798370361328,
"start": 18,
"tag": "NAME",
"value": "Gregg Reynolds"
},
{
"context": "ns ^{:doc \"Test html doc handling\"\n :author \"Gregg Reynolds\"}\n miraj.html.docs-test\n (:require [clojure.jav",
"end": 532,
"score": 0.9998841285705566,
"start": 518,
"tag": "NAME",
"value": "Gregg Reynolds"
}
] | test/miraj/html/docs_test.clj | miraj-project/miraj.html | 2 | ; Copyright (c) Gregg Reynolds. 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 ^{:doc "Test html doc handling"
:author "Gregg Reynolds"}
miraj.html.docs-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[miraj.html :as h]
[miraj.co-dom :refer :all :exclude [import require]]))
(def doc (element :html
(element :head
(element :meta {:application-name "co-dom test"})
(element :script {:src "foo/bar.js"}))
(element :body
(element :h1 "Hello world")
(element :script {:src "foo/baz.js"}))))
(deftest ^:docs doc-1
(let [doc (element :html
(element :head
(element :meta {:name "description"
:content "Search the world's information..."})
(element :body
(element :input))))]
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta content=\"Search the world's information...\" name=\"description\"><body><input></body></head></html>"))))
(deftest ^:docs serialize-1
(testing "serialize doc"
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta application-name=\"co-dom test\"><script src=\"foo/bar.js\"></script></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script></body></html>"))))
(deftest ^:docs optimize-1
(testing "JS optimizer adds charset, moves <script> elements from <head> to bottom of <body>."
(is (= (xsl-xform js-optimizer doc) ;; (normalize doc))
#miraj.co_dom.Element{:tag :html, :attrs {}, :content (#miraj.co_dom.Element{:tag :head, :attrs {}, :content (#miraj.co_dom.Element{:tag :meta, :attrs {:application-name "co-dom test"}, :content ()})} #miraj.co_dom.Element{:tag :body, :attrs {}, :content (#miraj.co_dom.Element{:tag :h1, :attrs {}, :content ("Hello world")} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/baz.js"}, :content ()} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/bar.js"}, :content ()})})}))))
(deftest ^:docs optimize-2
(testing "JS optimizer moves <script> elements from <head> to bottom of <body>."
(is (= "<!doctype html>\n<html><head><meta application-name=\"co-dom test\"></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script><script src=\"foo/bar.js\"></script></body></html>"
(serialize (xsl-xform js-optimizer doc))))))
;; #_(pprint (optimize :js (normalize doc))))
| 15476 | ; 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 ^{:doc "Test html doc handling"
:author "<NAME>"}
miraj.html.docs-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[miraj.html :as h]
[miraj.co-dom :refer :all :exclude [import require]]))
(def doc (element :html
(element :head
(element :meta {:application-name "co-dom test"})
(element :script {:src "foo/bar.js"}))
(element :body
(element :h1 "Hello world")
(element :script {:src "foo/baz.js"}))))
(deftest ^:docs doc-1
(let [doc (element :html
(element :head
(element :meta {:name "description"
:content "Search the world's information..."})
(element :body
(element :input))))]
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta content=\"Search the world's information...\" name=\"description\"><body><input></body></head></html>"))))
(deftest ^:docs serialize-1
(testing "serialize doc"
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta application-name=\"co-dom test\"><script src=\"foo/bar.js\"></script></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script></body></html>"))))
(deftest ^:docs optimize-1
(testing "JS optimizer adds charset, moves <script> elements from <head> to bottom of <body>."
(is (= (xsl-xform js-optimizer doc) ;; (normalize doc))
#miraj.co_dom.Element{:tag :html, :attrs {}, :content (#miraj.co_dom.Element{:tag :head, :attrs {}, :content (#miraj.co_dom.Element{:tag :meta, :attrs {:application-name "co-dom test"}, :content ()})} #miraj.co_dom.Element{:tag :body, :attrs {}, :content (#miraj.co_dom.Element{:tag :h1, :attrs {}, :content ("Hello world")} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/baz.js"}, :content ()} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/bar.js"}, :content ()})})}))))
(deftest ^:docs optimize-2
(testing "JS optimizer moves <script> elements from <head> to bottom of <body>."
(is (= "<!doctype html>\n<html><head><meta application-name=\"co-dom test\"></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script><script src=\"foo/bar.js\"></script></body></html>"
(serialize (xsl-xform js-optimizer doc))))))
;; #_(pprint (optimize :js (normalize doc))))
| 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 ^{:doc "Test html doc handling"
:author "PI:NAME:<NAME>END_PI"}
miraj.html.docs-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[miraj.html :as h]
[miraj.co-dom :refer :all :exclude [import require]]))
(def doc (element :html
(element :head
(element :meta {:application-name "co-dom test"})
(element :script {:src "foo/bar.js"}))
(element :body
(element :h1 "Hello world")
(element :script {:src "foo/baz.js"}))))
(deftest ^:docs doc-1
(let [doc (element :html
(element :head
(element :meta {:name "description"
:content "Search the world's information..."})
(element :body
(element :input))))]
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta content=\"Search the world's information...\" name=\"description\"><body><input></body></head></html>"))))
(deftest ^:docs serialize-1
(testing "serialize doc"
(is (= (serialize doc)
"<!doctype html>\n<html><head><meta application-name=\"co-dom test\"><script src=\"foo/bar.js\"></script></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script></body></html>"))))
(deftest ^:docs optimize-1
(testing "JS optimizer adds charset, moves <script> elements from <head> to bottom of <body>."
(is (= (xsl-xform js-optimizer doc) ;; (normalize doc))
#miraj.co_dom.Element{:tag :html, :attrs {}, :content (#miraj.co_dom.Element{:tag :head, :attrs {}, :content (#miraj.co_dom.Element{:tag :meta, :attrs {:application-name "co-dom test"}, :content ()})} #miraj.co_dom.Element{:tag :body, :attrs {}, :content (#miraj.co_dom.Element{:tag :h1, :attrs {}, :content ("Hello world")} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/baz.js"}, :content ()} #miraj.co_dom.Element{:tag :script, :attrs {:src "foo/bar.js"}, :content ()})})}))))
(deftest ^:docs optimize-2
(testing "JS optimizer moves <script> elements from <head> to bottom of <body>."
(is (= "<!doctype html>\n<html><head><meta application-name=\"co-dom test\"></head><body><h1>Hello world</h1><script src=\"foo/baz.js\"></script><script src=\"foo/bar.js\"></script></body></html>"
(serialize (xsl-xform js-optimizer doc))))))
;; #_(pprint (optimize :js (normalize doc))))
|
[
{
"context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde",
"end": 31,
"score": 0.9997678995132446,
"start": 19,
"tag": "NAME",
"value": "Hirokuni Kim"
},
{
"context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses",
"end": 64,
"score": 0.9998722076416016,
"start": 52,
"tag": "NAME",
"value": "Kevin Kredit"
}
] | clojure/p04-def/src/p04_def/core.clj | kkredit/pl-study | 0 | ;; Original author Hirokuni Kim
;; Modifications by Kevin Kredit
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#def
(ns p04-def.core)
(defn -main
"Main"
[]
(def object "light")
(println (str "God said let there be " object))
(def object "darkness")
(println (str "God said let there be " object)))
| 122548 | ;; Original author <NAME>
;; Modifications by <NAME>
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#def
(ns p04-def.core)
(defn -main
"Main"
[]
(def object "light")
(println (str "God said let there be " object))
(def object "darkness")
(println (str "God said let there be " object)))
| true | ;; Original author PI:NAME:<NAME>END_PI
;; Modifications by PI:NAME:<NAME>END_PI
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#def
(ns p04-def.core)
(defn -main
"Main"
[]
(def object "light")
(println (str "God said let there be " object))
(def object "darkness")
(println (str "God said let there be " object)))
|
[
{
"context": ";; Copyright (c) Rich Hickey and contributors. All rights reserved.\n;; The u",
"end": 30,
"score": 0.9998462796211243,
"start": 19,
"tag": "NAME",
"value": "Rich Hickey"
}
] | server/target/clojure/core/async/impl/channels.clj | OctavioBR/healthcheck | 0 | ;; Copyright (c) Rich Hickey and contributors. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:skip-wiki true}
clojure.core.async.impl.channels
(:require [clojure.core.async.impl.protocols :as impl]
[clojure.core.async.impl.dispatch :as dispatch]
[clojure.core.async.impl.mutex :as mutex])
(:import [java.util LinkedList Queue Iterator]
[java.util.concurrent.locks Lock]))
(set! *warn-on-reflection* true)
(defmacro assert-unlock [lock test msg]
`(when-not ~test
(.unlock ~lock)
(throw (new AssertionError (str "Assert failed: " ~msg "\n" (pr-str '~test))))))
(defn box [val]
(reify clojure.lang.IDeref
(deref [_] val)))
(defprotocol MMC
(cleanup [_])
(abort [_]))
(deftype ManyToManyChannel [^LinkedList takes ^LinkedList puts ^Queue buf closed ^Lock mutex add!]
MMC
(cleanup
[_]
(when-not (.isEmpty takes)
(let [iter (.iterator takes)]
(loop [taker (.next iter)]
(when-not (impl/active? taker)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter))))))
(when-not (.isEmpty puts)
(let [iter (.iterator puts)]
(loop [[putter] (.next iter)]
(when-not (impl/active? putter)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter)))))))
(abort
[this]
(let [iter (.iterator puts)]
(when (.hasNext iter)
(loop [^Lock putter (.next iter)]
(.lock putter)
(let [put-cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(when put-cb
(dispatch/run (fn [] (put-cb true))))
(when (.hasNext iter)
(recur (.next iter)))))))
(.clear puts)
(impl/close! this))
impl/WritePort
(put!
[this val handler]
(when (nil? val)
(throw (IllegalArgumentException. "Can't put nil on channel")))
(.lock mutex)
(cleanup this)
(if @closed
(do (.unlock mutex)
(box false))
(let [^Lock handler handler]
(if (and buf (not (impl/full? buf)) (not (.isEmpty takes)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(if (pos? (count buf))
(let [iter (.iterator takes)
take-cbs (loop [takers []]
(if (and (.hasNext iter) (pos? (count buf)))
(let [^Lock taker (.next iter)]
(.lock taker)
(let [ret (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(if ret
(let [val (impl/remove! buf)]
(.remove iter)
(recur (conj takers (fn [] (ret val)))))
(recur takers))))
takers))]
(if (seq take-cbs)
(do
(when done?
(abort this))
(.unlock mutex)
(doseq [f take-cbs]
(dispatch/run f)))
(do
(when done?
(abort this))
(.unlock mutex))))
(do
(when done?
(abort this))
(.unlock mutex)))
(box true))
(do (.unlock mutex)
nil))))
(let [iter (.iterator takes)
[put-cb take-cb] (when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id taker))
(do (.lock handler) (.lock taker))
(do (.lock taker) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? taker))
[(impl/commit handler) (impl/commit taker)])]
(.unlock handler)
(.unlock taker)
(if ret
(do
(.remove iter)
ret)
(when (.hasNext iter)
(recur (.next iter)))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run (fn [] (take-cb val)))
(box true))
(if (and buf (not (impl/full? buf)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(when done?
(abort this))
(.unlock mutex)
(box true))
(do (.unlock mutex)
nil))))
(do
(when (and (impl/active? handler) (impl/blockable? handler))
(assert-unlock mutex
(< (.size puts) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending puts are allowed on a single channel."
" Consider using a windowed buffer."))
(.add puts [handler val]))
(.unlock mutex)
nil))))))))
impl/ReadPort
(take!
[this handler]
(.lock mutex)
(cleanup this)
(let [^Lock handler handler
commit-handler (fn []
(.lock handler)
(let [take-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
take-cb))]
(if (and buf (pos? (count buf)))
(do
(if-let [take-cb (commit-handler)]
(let [val (impl/remove! buf)
iter (.iterator puts)
[done? cbs]
(when (.hasNext iter)
(loop [cbs []
[^Lock putter val] (.next iter)]
(.lock putter)
(let [cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(.remove iter)
(let [cbs (if cb (conj cbs cb) cbs)
done? (when cb (reduced? (add! buf val)))]
(if (and (not done?) (not (impl/full? buf)) (.hasNext iter))
(recur cbs (.next iter))
[done? cbs])))))]
(when done?
(abort this))
(.unlock mutex)
(doseq [cb cbs]
(dispatch/run #(cb true)))
(box val))
(do (.unlock mutex)
nil)))
(let [iter (.iterator puts)
[take-cb put-cb val]
(when (.hasNext iter)
(loop [[^Lock putter val] (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id putter))
(do (.lock handler) (.lock putter))
(do (.lock putter) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? putter))
[(impl/commit handler) (impl/commit putter) val])]
(.unlock handler)
(.unlock putter)
(if ret
(do
(.remove iter)
ret)
(when-not (impl/active? putter)
(.remove iter)
(when (.hasNext iter)
(recur (.next iter))))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run #(put-cb true))
(box val))
(if @closed
(do
(when buf (add! buf))
(let [has-val (and buf (pos? (count buf)))]
(if-let [take-cb (commit-handler)]
(let [val (when has-val (impl/remove! buf))]
(.unlock mutex)
(box val))
(do
(.unlock mutex)
nil))))
(do
(when (impl/blockable? handler)
(assert-unlock mutex
(< (.size takes) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending takes are allowed on a single channel."))
(.add takes handler))
(.unlock mutex)
nil)))))))
impl/Channel
(closed? [_] @closed)
(close!
[this]
(.lock mutex)
(cleanup this)
(if @closed
(do
(.unlock mutex)
nil)
(do
(reset! closed true)
(when (and buf (.isEmpty puts))
(add! buf))
(let [iter (.iterator takes)]
(when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(.lock taker)
(let [take-cb (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(when take-cb
(let [val (when (and buf (pos? (count buf))) (impl/remove! buf))]
(dispatch/run (fn [] (take-cb val)))))
(.remove iter)
(when (.hasNext iter)
(recur (.next iter)))))))
(when buf (impl/close-buf! buf))
(.unlock mutex)
nil))))
(defn- ex-handler [ex]
(-> (Thread/currentThread)
.getUncaughtExceptionHandler
(.uncaughtException (Thread/currentThread) ex))
nil)
(defn- handle [buf exh t]
(let [else ((or exh ex-handler) t)]
(if (nil? else)
buf
(impl/add! buf else))))
(defn chan
([buf] (chan buf nil))
([buf xform] (chan buf xform nil))
([buf xform exh]
(ManyToManyChannel.
(LinkedList.) (LinkedList.) buf (atom false) (mutex/mutex)
(let [add! (if xform (xform impl/add!) impl/add!)]
(fn
([buf]
(try
(add! buf)
(catch Throwable t
(handle buf exh t))))
([buf val]
(try
(add! buf val)
(catch Throwable t
(handle buf exh t)))))))))
| 113928 | ;; Copyright (c) <NAME> and contributors. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:skip-wiki true}
clojure.core.async.impl.channels
(:require [clojure.core.async.impl.protocols :as impl]
[clojure.core.async.impl.dispatch :as dispatch]
[clojure.core.async.impl.mutex :as mutex])
(:import [java.util LinkedList Queue Iterator]
[java.util.concurrent.locks Lock]))
(set! *warn-on-reflection* true)
(defmacro assert-unlock [lock test msg]
`(when-not ~test
(.unlock ~lock)
(throw (new AssertionError (str "Assert failed: " ~msg "\n" (pr-str '~test))))))
(defn box [val]
(reify clojure.lang.IDeref
(deref [_] val)))
(defprotocol MMC
(cleanup [_])
(abort [_]))
(deftype ManyToManyChannel [^LinkedList takes ^LinkedList puts ^Queue buf closed ^Lock mutex add!]
MMC
(cleanup
[_]
(when-not (.isEmpty takes)
(let [iter (.iterator takes)]
(loop [taker (.next iter)]
(when-not (impl/active? taker)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter))))))
(when-not (.isEmpty puts)
(let [iter (.iterator puts)]
(loop [[putter] (.next iter)]
(when-not (impl/active? putter)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter)))))))
(abort
[this]
(let [iter (.iterator puts)]
(when (.hasNext iter)
(loop [^Lock putter (.next iter)]
(.lock putter)
(let [put-cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(when put-cb
(dispatch/run (fn [] (put-cb true))))
(when (.hasNext iter)
(recur (.next iter)))))))
(.clear puts)
(impl/close! this))
impl/WritePort
(put!
[this val handler]
(when (nil? val)
(throw (IllegalArgumentException. "Can't put nil on channel")))
(.lock mutex)
(cleanup this)
(if @closed
(do (.unlock mutex)
(box false))
(let [^Lock handler handler]
(if (and buf (not (impl/full? buf)) (not (.isEmpty takes)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(if (pos? (count buf))
(let [iter (.iterator takes)
take-cbs (loop [takers []]
(if (and (.hasNext iter) (pos? (count buf)))
(let [^Lock taker (.next iter)]
(.lock taker)
(let [ret (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(if ret
(let [val (impl/remove! buf)]
(.remove iter)
(recur (conj takers (fn [] (ret val)))))
(recur takers))))
takers))]
(if (seq take-cbs)
(do
(when done?
(abort this))
(.unlock mutex)
(doseq [f take-cbs]
(dispatch/run f)))
(do
(when done?
(abort this))
(.unlock mutex))))
(do
(when done?
(abort this))
(.unlock mutex)))
(box true))
(do (.unlock mutex)
nil))))
(let [iter (.iterator takes)
[put-cb take-cb] (when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id taker))
(do (.lock handler) (.lock taker))
(do (.lock taker) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? taker))
[(impl/commit handler) (impl/commit taker)])]
(.unlock handler)
(.unlock taker)
(if ret
(do
(.remove iter)
ret)
(when (.hasNext iter)
(recur (.next iter)))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run (fn [] (take-cb val)))
(box true))
(if (and buf (not (impl/full? buf)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(when done?
(abort this))
(.unlock mutex)
(box true))
(do (.unlock mutex)
nil))))
(do
(when (and (impl/active? handler) (impl/blockable? handler))
(assert-unlock mutex
(< (.size puts) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending puts are allowed on a single channel."
" Consider using a windowed buffer."))
(.add puts [handler val]))
(.unlock mutex)
nil))))))))
impl/ReadPort
(take!
[this handler]
(.lock mutex)
(cleanup this)
(let [^Lock handler handler
commit-handler (fn []
(.lock handler)
(let [take-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
take-cb))]
(if (and buf (pos? (count buf)))
(do
(if-let [take-cb (commit-handler)]
(let [val (impl/remove! buf)
iter (.iterator puts)
[done? cbs]
(when (.hasNext iter)
(loop [cbs []
[^Lock putter val] (.next iter)]
(.lock putter)
(let [cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(.remove iter)
(let [cbs (if cb (conj cbs cb) cbs)
done? (when cb (reduced? (add! buf val)))]
(if (and (not done?) (not (impl/full? buf)) (.hasNext iter))
(recur cbs (.next iter))
[done? cbs])))))]
(when done?
(abort this))
(.unlock mutex)
(doseq [cb cbs]
(dispatch/run #(cb true)))
(box val))
(do (.unlock mutex)
nil)))
(let [iter (.iterator puts)
[take-cb put-cb val]
(when (.hasNext iter)
(loop [[^Lock putter val] (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id putter))
(do (.lock handler) (.lock putter))
(do (.lock putter) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? putter))
[(impl/commit handler) (impl/commit putter) val])]
(.unlock handler)
(.unlock putter)
(if ret
(do
(.remove iter)
ret)
(when-not (impl/active? putter)
(.remove iter)
(when (.hasNext iter)
(recur (.next iter))))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run #(put-cb true))
(box val))
(if @closed
(do
(when buf (add! buf))
(let [has-val (and buf (pos? (count buf)))]
(if-let [take-cb (commit-handler)]
(let [val (when has-val (impl/remove! buf))]
(.unlock mutex)
(box val))
(do
(.unlock mutex)
nil))))
(do
(when (impl/blockable? handler)
(assert-unlock mutex
(< (.size takes) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending takes are allowed on a single channel."))
(.add takes handler))
(.unlock mutex)
nil)))))))
impl/Channel
(closed? [_] @closed)
(close!
[this]
(.lock mutex)
(cleanup this)
(if @closed
(do
(.unlock mutex)
nil)
(do
(reset! closed true)
(when (and buf (.isEmpty puts))
(add! buf))
(let [iter (.iterator takes)]
(when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(.lock taker)
(let [take-cb (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(when take-cb
(let [val (when (and buf (pos? (count buf))) (impl/remove! buf))]
(dispatch/run (fn [] (take-cb val)))))
(.remove iter)
(when (.hasNext iter)
(recur (.next iter)))))))
(when buf (impl/close-buf! buf))
(.unlock mutex)
nil))))
(defn- ex-handler [ex]
(-> (Thread/currentThread)
.getUncaughtExceptionHandler
(.uncaughtException (Thread/currentThread) ex))
nil)
(defn- handle [buf exh t]
(let [else ((or exh ex-handler) t)]
(if (nil? else)
buf
(impl/add! buf else))))
(defn chan
([buf] (chan buf nil))
([buf xform] (chan buf xform nil))
([buf xform exh]
(ManyToManyChannel.
(LinkedList.) (LinkedList.) buf (atom false) (mutex/mutex)
(let [add! (if xform (xform impl/add!) impl/add!)]
(fn
([buf]
(try
(add! buf)
(catch Throwable t
(handle buf exh t))))
([buf val]
(try
(add! buf val)
(catch Throwable t
(handle buf exh t)))))))))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI and contributors. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:skip-wiki true}
clojure.core.async.impl.channels
(:require [clojure.core.async.impl.protocols :as impl]
[clojure.core.async.impl.dispatch :as dispatch]
[clojure.core.async.impl.mutex :as mutex])
(:import [java.util LinkedList Queue Iterator]
[java.util.concurrent.locks Lock]))
(set! *warn-on-reflection* true)
(defmacro assert-unlock [lock test msg]
`(when-not ~test
(.unlock ~lock)
(throw (new AssertionError (str "Assert failed: " ~msg "\n" (pr-str '~test))))))
(defn box [val]
(reify clojure.lang.IDeref
(deref [_] val)))
(defprotocol MMC
(cleanup [_])
(abort [_]))
(deftype ManyToManyChannel [^LinkedList takes ^LinkedList puts ^Queue buf closed ^Lock mutex add!]
MMC
(cleanup
[_]
(when-not (.isEmpty takes)
(let [iter (.iterator takes)]
(loop [taker (.next iter)]
(when-not (impl/active? taker)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter))))))
(when-not (.isEmpty puts)
(let [iter (.iterator puts)]
(loop [[putter] (.next iter)]
(when-not (impl/active? putter)
(.remove iter))
(when (.hasNext iter)
(recur (.next iter)))))))
(abort
[this]
(let [iter (.iterator puts)]
(when (.hasNext iter)
(loop [^Lock putter (.next iter)]
(.lock putter)
(let [put-cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(when put-cb
(dispatch/run (fn [] (put-cb true))))
(when (.hasNext iter)
(recur (.next iter)))))))
(.clear puts)
(impl/close! this))
impl/WritePort
(put!
[this val handler]
(when (nil? val)
(throw (IllegalArgumentException. "Can't put nil on channel")))
(.lock mutex)
(cleanup this)
(if @closed
(do (.unlock mutex)
(box false))
(let [^Lock handler handler]
(if (and buf (not (impl/full? buf)) (not (.isEmpty takes)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(if (pos? (count buf))
(let [iter (.iterator takes)
take-cbs (loop [takers []]
(if (and (.hasNext iter) (pos? (count buf)))
(let [^Lock taker (.next iter)]
(.lock taker)
(let [ret (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(if ret
(let [val (impl/remove! buf)]
(.remove iter)
(recur (conj takers (fn [] (ret val)))))
(recur takers))))
takers))]
(if (seq take-cbs)
(do
(when done?
(abort this))
(.unlock mutex)
(doseq [f take-cbs]
(dispatch/run f)))
(do
(when done?
(abort this))
(.unlock mutex))))
(do
(when done?
(abort this))
(.unlock mutex)))
(box true))
(do (.unlock mutex)
nil))))
(let [iter (.iterator takes)
[put-cb take-cb] (when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id taker))
(do (.lock handler) (.lock taker))
(do (.lock taker) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? taker))
[(impl/commit handler) (impl/commit taker)])]
(.unlock handler)
(.unlock taker)
(if ret
(do
(.remove iter)
ret)
(when (.hasNext iter)
(recur (.next iter)))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run (fn [] (take-cb val)))
(box true))
(if (and buf (not (impl/full? buf)))
(do
(.lock handler)
(let [put-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
(if put-cb
(let [done? (reduced? (add! buf val))]
(when done?
(abort this))
(.unlock mutex)
(box true))
(do (.unlock mutex)
nil))))
(do
(when (and (impl/active? handler) (impl/blockable? handler))
(assert-unlock mutex
(< (.size puts) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending puts are allowed on a single channel."
" Consider using a windowed buffer."))
(.add puts [handler val]))
(.unlock mutex)
nil))))))))
impl/ReadPort
(take!
[this handler]
(.lock mutex)
(cleanup this)
(let [^Lock handler handler
commit-handler (fn []
(.lock handler)
(let [take-cb (and (impl/active? handler) (impl/commit handler))]
(.unlock handler)
take-cb))]
(if (and buf (pos? (count buf)))
(do
(if-let [take-cb (commit-handler)]
(let [val (impl/remove! buf)
iter (.iterator puts)
[done? cbs]
(when (.hasNext iter)
(loop [cbs []
[^Lock putter val] (.next iter)]
(.lock putter)
(let [cb (and (impl/active? putter) (impl/commit putter))]
(.unlock putter)
(.remove iter)
(let [cbs (if cb (conj cbs cb) cbs)
done? (when cb (reduced? (add! buf val)))]
(if (and (not done?) (not (impl/full? buf)) (.hasNext iter))
(recur cbs (.next iter))
[done? cbs])))))]
(when done?
(abort this))
(.unlock mutex)
(doseq [cb cbs]
(dispatch/run #(cb true)))
(box val))
(do (.unlock mutex)
nil)))
(let [iter (.iterator puts)
[take-cb put-cb val]
(when (.hasNext iter)
(loop [[^Lock putter val] (.next iter)]
(if (< (impl/lock-id handler) (impl/lock-id putter))
(do (.lock handler) (.lock putter))
(do (.lock putter) (.lock handler)))
(let [ret (when (and (impl/active? handler) (impl/active? putter))
[(impl/commit handler) (impl/commit putter) val])]
(.unlock handler)
(.unlock putter)
(if ret
(do
(.remove iter)
ret)
(when-not (impl/active? putter)
(.remove iter)
(when (.hasNext iter)
(recur (.next iter))))))))]
(if (and put-cb take-cb)
(do
(.unlock mutex)
(dispatch/run #(put-cb true))
(box val))
(if @closed
(do
(when buf (add! buf))
(let [has-val (and buf (pos? (count buf)))]
(if-let [take-cb (commit-handler)]
(let [val (when has-val (impl/remove! buf))]
(.unlock mutex)
(box val))
(do
(.unlock mutex)
nil))))
(do
(when (impl/blockable? handler)
(assert-unlock mutex
(< (.size takes) impl/MAX-QUEUE-SIZE)
(str "No more than " impl/MAX-QUEUE-SIZE
" pending takes are allowed on a single channel."))
(.add takes handler))
(.unlock mutex)
nil)))))))
impl/Channel
(closed? [_] @closed)
(close!
[this]
(.lock mutex)
(cleanup this)
(if @closed
(do
(.unlock mutex)
nil)
(do
(reset! closed true)
(when (and buf (.isEmpty puts))
(add! buf))
(let [iter (.iterator takes)]
(when (.hasNext iter)
(loop [^Lock taker (.next iter)]
(.lock taker)
(let [take-cb (and (impl/active? taker) (impl/commit taker))]
(.unlock taker)
(when take-cb
(let [val (when (and buf (pos? (count buf))) (impl/remove! buf))]
(dispatch/run (fn [] (take-cb val)))))
(.remove iter)
(when (.hasNext iter)
(recur (.next iter)))))))
(when buf (impl/close-buf! buf))
(.unlock mutex)
nil))))
(defn- ex-handler [ex]
(-> (Thread/currentThread)
.getUncaughtExceptionHandler
(.uncaughtException (Thread/currentThread) ex))
nil)
(defn- handle [buf exh t]
(let [else ((or exh ex-handler) t)]
(if (nil? else)
buf
(impl/add! buf else))))
(defn chan
([buf] (chan buf nil))
([buf xform] (chan buf xform nil))
([buf xform exh]
(ManyToManyChannel.
(LinkedList.) (LinkedList.) buf (atom false) (mutex/mutex)
(let [add! (if xform (xform impl/add!) impl/add!)]
(fn
([buf]
(try
(add! buf)
(catch Throwable t
(handle buf exh t))))
([buf val]
(try
(add! buf val)
(catch Throwable t
(handle buf exh t)))))))))
|
[
{
"context": ";\n; Copyright © 2011-2014 Carlo Sciolla\n;\n; Licensed under the Apache License, Version 2.",
"end": 39,
"score": 0.9998776316642761,
"start": 26,
"tag": "NAME",
"value": "Carlo Sciolla"
},
{
"context": "itations under the License.\n;\n; Contributors:\n; Carlo Sciolla - initial implementation\n; Peter Monks - con",
"end": 622,
"score": 0.9998787045478821,
"start": 609,
"tag": "NAME",
"value": "Carlo Sciolla"
},
{
"context": ":\n; Carlo Sciolla - initial implementation\n; Peter Monks - contributor\n\n; Make sure these line up to tho",
"end": 664,
"score": 0.9998560547828674,
"start": 653,
"tag": "NAME",
"value": "Peter Monks"
},
{
"context": "Alfresco\"\n :url \"https://github.com/lambdalf/lambdalf\"\n :license { :name \"Apache Lic",
"end": 1102,
"score": 0.996940553188324,
"start": 1094,
"tag": "USERNAME",
"value": "lambdalf"
}
] | project.clj | lambdalf/lambdalf | 11 | ;
; Copyright © 2011-2014 Carlo Sciolla
;
; 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.
;
; Contributors:
; Carlo Sciolla - initial implementation
; Peter Monks - contributor
; Make sure these line up to those provided in the specified Alfresco version or weird things can happen...
(def alfresco-version "5.0.d")
(def spring-version "3.0.5.RELEASE")
(def spring-surf-version "5.0.d")
(defproject org.clojars.lambdalf/lambdalf "0.2.0-SNAPSHOT"
:title "lambdalf"
:description "Lambdalf -- Clojure support for Alfresco"
:url "https://github.com/lambdalf/lambdalf"
:license { :name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0" }
:min-lein-version "2.5.0"
:repositories [
["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]
]
:dependencies [
; Dependencies that will be included in the AMP - other dependencies should go in the appropriate profile below
[org.clojure/clojure "1.8.0"]
[org.clojure/tools.nrepl "0.2.12"]
]
:profiles {:dev { :plugins [[lein-amp "0.6.0"]] }
:test { :dependencies [
[clj-http "2.0.1"]
[tk.skuro.alfresco/h2-support "1.6"]
[com.h2database/h2 "1.4.190"]
[org.eclipse.jetty/jetty-runner "9.3.7.RC1" :exclusions [org.eclipse.jetty/jetty-jsp]]
] }
:provided { :dependencies [
[org.alfresco/alfresco-core ~alfresco-version]
[org.alfresco/alfresco-data-model ~alfresco-version]
[org.alfresco/alfresco-mbeans ~alfresco-version]
[org.alfresco/alfresco-remote-api ~alfresco-version]
[org.alfresco/alfresco-repository ~alfresco-version]
[org.springframework/spring-context ~spring-version]
[org.springframework/spring-beans ~spring-version]
[org.springframework.extensions.surf/spring-webscripts ~spring-surf-version]
] }
}
:aot [alfresco]
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:resource-paths ["src/resource"]
:amp-source-path "src/amp"
:amp-target-war [org.alfresco/alfresco ~alfresco-version :extension "war"]
:javac-target "1.7"
)
| 4684 | ;
; Copyright © 2011-2014 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; Contributors:
; <NAME> - initial implementation
; <NAME> - contributor
; Make sure these line up to those provided in the specified Alfresco version or weird things can happen...
(def alfresco-version "5.0.d")
(def spring-version "3.0.5.RELEASE")
(def spring-surf-version "5.0.d")
(defproject org.clojars.lambdalf/lambdalf "0.2.0-SNAPSHOT"
:title "lambdalf"
:description "Lambdalf -- Clojure support for Alfresco"
:url "https://github.com/lambdalf/lambdalf"
:license { :name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0" }
:min-lein-version "2.5.0"
:repositories [
["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]
]
:dependencies [
; Dependencies that will be included in the AMP - other dependencies should go in the appropriate profile below
[org.clojure/clojure "1.8.0"]
[org.clojure/tools.nrepl "0.2.12"]
]
:profiles {:dev { :plugins [[lein-amp "0.6.0"]] }
:test { :dependencies [
[clj-http "2.0.1"]
[tk.skuro.alfresco/h2-support "1.6"]
[com.h2database/h2 "1.4.190"]
[org.eclipse.jetty/jetty-runner "9.3.7.RC1" :exclusions [org.eclipse.jetty/jetty-jsp]]
] }
:provided { :dependencies [
[org.alfresco/alfresco-core ~alfresco-version]
[org.alfresco/alfresco-data-model ~alfresco-version]
[org.alfresco/alfresco-mbeans ~alfresco-version]
[org.alfresco/alfresco-remote-api ~alfresco-version]
[org.alfresco/alfresco-repository ~alfresco-version]
[org.springframework/spring-context ~spring-version]
[org.springframework/spring-beans ~spring-version]
[org.springframework.extensions.surf/spring-webscripts ~spring-surf-version]
] }
}
:aot [alfresco]
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:resource-paths ["src/resource"]
:amp-source-path "src/amp"
:amp-target-war [org.alfresco/alfresco ~alfresco-version :extension "war"]
:javac-target "1.7"
)
| true | ;
; Copyright © 2011-2014 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; Contributors:
; PI:NAME:<NAME>END_PI - initial implementation
; PI:NAME:<NAME>END_PI - contributor
; Make sure these line up to those provided in the specified Alfresco version or weird things can happen...
(def alfresco-version "5.0.d")
(def spring-version "3.0.5.RELEASE")
(def spring-surf-version "5.0.d")
(defproject org.clojars.lambdalf/lambdalf "0.2.0-SNAPSHOT"
:title "lambdalf"
:description "Lambdalf -- Clojure support for Alfresco"
:url "https://github.com/lambdalf/lambdalf"
:license { :name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0" }
:min-lein-version "2.5.0"
:repositories [
["alfresco.public" "https://artifacts.alfresco.com/nexus/content/groups/public/"]
]
:dependencies [
; Dependencies that will be included in the AMP - other dependencies should go in the appropriate profile below
[org.clojure/clojure "1.8.0"]
[org.clojure/tools.nrepl "0.2.12"]
]
:profiles {:dev { :plugins [[lein-amp "0.6.0"]] }
:test { :dependencies [
[clj-http "2.0.1"]
[tk.skuro.alfresco/h2-support "1.6"]
[com.h2database/h2 "1.4.190"]
[org.eclipse.jetty/jetty-runner "9.3.7.RC1" :exclusions [org.eclipse.jetty/jetty-jsp]]
] }
:provided { :dependencies [
[org.alfresco/alfresco-core ~alfresco-version]
[org.alfresco/alfresco-data-model ~alfresco-version]
[org.alfresco/alfresco-mbeans ~alfresco-version]
[org.alfresco/alfresco-remote-api ~alfresco-version]
[org.alfresco/alfresco-repository ~alfresco-version]
[org.springframework/spring-context ~spring-version]
[org.springframework/spring-beans ~spring-version]
[org.springframework.extensions.surf/spring-webscripts ~spring-surf-version]
] }
}
:aot [alfresco]
:source-paths ["src/clojure"]
:java-source-paths ["src/java"]
:resource-paths ["src/resource"]
:amp-source-path "src/amp"
:amp-target-war [org.alfresco/alfresco ~alfresco-version :extension "war"]
:javac-target "1.7"
)
|
[
{
"context": " :name])]\n (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author)),\n ",
"end": 868,
"score": 0.999781608581543,
"start": 860,
"tag": "NAME",
"value": "yuan jia"
},
{
"context": " (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author)),\n ",
"end": 880,
"score": 0.9942647814750671,
"start": 871,
"tag": "USERNAME",
"value": "yuanjiaCN"
},
{
"context": " (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author)),\n :da",
"end": 892,
"score": 0.9998456835746765,
"start": 883,
"tag": "NAME",
"value": "Mihu Seen"
},
{
"context": " (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author)),\n :date (let [ti",
"end": 903,
"score": 0.7034925818443298,
"start": 895,
"tag": "USERNAME",
"value": "MihuSeen"
},
{
"context": " (case author\n \"yuan jia\" \"yuanjiaCN\"\n \"Mihu See",
"end": 3248,
"score": 0.999758780002594,
"start": 3240,
"tag": "NAME",
"value": "yuan jia"
},
{
"context": "ase author\n \"yuan jia\" \"yuanjiaCN\"\n \"Mihu Seen\" \"MihuSeen",
"end": 3260,
"score": 0.9980170130729675,
"start": 3251,
"tag": "USERNAME",
"value": "yuanjiaCN"
},
{
"context": "yuan jia\" \"yuanjiaCN\"\n \"Mihu Seen\" \"MihuSeen\"\n \"Dave\" \"wa",
"end": 3299,
"score": 0.9998574256896973,
"start": 3290,
"tag": "NAME",
"value": "Mihu Seen"
},
{
"context": "uanjiaCN\"\n \"Mihu Seen\" \"MihuSeen\"\n \"Dave\" \"wangcch\"\n ",
"end": 3310,
"score": 0.9928171634674072,
"start": 3302,
"tag": "USERNAME",
"value": "MihuSeen"
},
{
"context": "Mihu Seen\" \"MihuSeen\"\n \"Dave\" \"wangcch\"\n \"yuelei\" \"Y",
"end": 3344,
"score": 0.9998080730438232,
"start": 3340,
"tag": "NAME",
"value": "Dave"
},
{
"context": "en\" \"MihuSeen\"\n \"Dave\" \"wangcch\"\n \"yuelei\" \"YueLei\"\n ",
"end": 3354,
"score": 0.9974832534790039,
"start": 3347,
"tag": "USERNAME",
"value": "wangcch"
},
{
"context": " \"Dave\" \"wangcch\"\n \"yuelei\" \"YueLei\"\n author))))\n ",
"end": 3390,
"score": 0.9765684604644775,
"start": 3384,
"tag": "USERNAME",
"value": "yuelei"
},
{
"context": "e\" \"wangcch\"\n \"yuelei\" \"YueLei\"\n author))))\n ",
"end": 3399,
"score": 0.9910212159156799,
"start": 3393,
"tag": "NAME",
"value": "YueLei"
},
{
"context": "r :name])]\n (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author))))\n ",
"end": 5586,
"score": 0.9995819330215454,
"start": 5578,
"tag": "NAME",
"value": "yuan jia"
},
{
"context": " (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author))))\n ",
"end": 5598,
"score": 0.9976485967636108,
"start": 5589,
"tag": "USERNAME",
"value": "yuanjiaCN"
},
{
"context": " (case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author))))\n (map-v",
"end": 5610,
"score": 0.9998581409454346,
"start": 5601,
"tag": "NAME",
"value": "Mihu Seen"
},
{
"context": "case author \"yuan jia\" \"yuanjiaCN\" \"Mihu Seen\" \"MihuSeen\" author))))\n (map-vals\n ",
"end": 5621,
"score": 0.6831426024436951,
"start": 5615,
"tag": "USERNAME",
"value": "huSeen"
}
] | cljs/src/app/main.cljs | jimengio/weekly-commits | 0 |
(ns app.main
(:require ["fs" :as fs]
["path" :as path]
[favored-edn.core :refer [write-edn]]
[medley.core :refer [map-vals map-kv]]
[clojure.string :as string]
["luxon" :refer [DateTime]]))
(defonce projects-commits
(js->clj
(js/JSON.parse
(fs/readFileSync (path/join js/__dirname "../../data/commits.json") "utf8"))
:keywordize-keys
true))
(defn daily-commits! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(map
(fn [record]
{:author (let [author (get-in record [:commit :author :name])]
(case author "yuan jia" "yuanjiaCN" "Mihu Seen" "MihuSeen" author)),
:date (let [time (.fromISO
DateTime
(get-in record [:commit :author :date]))]
(.toFormat time "yyyy-MM-dd")),
:repo (:repo record),
:add (get-in record [:stats :additions]),
:delete (get-in record [:stats :deletions])}))
(group-by :date)
(map-vals
(fn [records]
(->> records
(group-by :author)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :date :author)))
(vec)
(count)))))))
(map
(fn [[date info]]
[date
(let [time (.fromISO DateTime date)] (.toFormat time "ccc"))
info]))
(sort-by first)
(vec))]
(println (write-edn result))))
(defn display-number [n char]
(let [x (js/Math.ceil (/ n 200))] (str (string/join "" (repeat x char)) " " n)))
(defn format-records [info]
(->> info
(mapcat
(fn [[author work-info]]
(concat
["\n" author]
(->> work-info
(mapcat
(fn [[project changes]]
["\n"
" "
project
"\n"
" "
(display-number (:add changes) "+")
"\n"
" "
(display-number (:delete changes) "-")]))))))))
(defn display-graph! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author
"yuan jia" "yuanjiaCN"
"Mihu Seen" "MihuSeen"
"Dave" "wangcch"
"yuelei" "YueLei"
author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(reduce
(fn [acc record]
(if (or (> (:add record) 5000)
(> (- (:delete record) (:add record)) 500))
(do
(println "skip large changes" (pr-str record))
acc)
(-> acc
(update :add (fn [x0] (+ x0 (:add record))))
(update
:delete
(fn [x0] (+ x0 (:delete record)))))))
{:add 0, :delete 0}))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))
(println "Wrote to file result.edn .")
(println (string/join "" (format-records result)))))
(defn write-info! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author "yuan jia" "yuanjiaCN" "Mihu Seen" "MihuSeen" author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(vec))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))))
(defn analyze! [] (comment display-graph!) (comment write-info!) (daily-commits!))
(defn main! [] (println "Started.") (analyze!))
(defn reload! [] (.clear js/console) (println "Reloaded.") (analyze!))
| 71737 |
(ns app.main
(:require ["fs" :as fs]
["path" :as path]
[favored-edn.core :refer [write-edn]]
[medley.core :refer [map-vals map-kv]]
[clojure.string :as string]
["luxon" :refer [DateTime]]))
(defonce projects-commits
(js->clj
(js/JSON.parse
(fs/readFileSync (path/join js/__dirname "../../data/commits.json") "utf8"))
:keywordize-keys
true))
(defn daily-commits! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(map
(fn [record]
{:author (let [author (get-in record [:commit :author :name])]
(case author "<NAME>" "yuanjiaCN" "<NAME>" "MihuSeen" author)),
:date (let [time (.fromISO
DateTime
(get-in record [:commit :author :date]))]
(.toFormat time "yyyy-MM-dd")),
:repo (:repo record),
:add (get-in record [:stats :additions]),
:delete (get-in record [:stats :deletions])}))
(group-by :date)
(map-vals
(fn [records]
(->> records
(group-by :author)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :date :author)))
(vec)
(count)))))))
(map
(fn [[date info]]
[date
(let [time (.fromISO DateTime date)] (.toFormat time "ccc"))
info]))
(sort-by first)
(vec))]
(println (write-edn result))))
(defn display-number [n char]
(let [x (js/Math.ceil (/ n 200))] (str (string/join "" (repeat x char)) " " n)))
(defn format-records [info]
(->> info
(mapcat
(fn [[author work-info]]
(concat
["\n" author]
(->> work-info
(mapcat
(fn [[project changes]]
["\n"
" "
project
"\n"
" "
(display-number (:add changes) "+")
"\n"
" "
(display-number (:delete changes) "-")]))))))))
(defn display-graph! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author
"<NAME>" "yuanjiaCN"
"<NAME>" "MihuSeen"
"<NAME>" "wangcch"
"yuelei" "<NAME>"
author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(reduce
(fn [acc record]
(if (or (> (:add record) 5000)
(> (- (:delete record) (:add record)) 500))
(do
(println "skip large changes" (pr-str record))
acc)
(-> acc
(update :add (fn [x0] (+ x0 (:add record))))
(update
:delete
(fn [x0] (+ x0 (:delete record)))))))
{:add 0, :delete 0}))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))
(println "Wrote to file result.edn .")
(println (string/join "" (format-records result)))))
(defn write-info! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author "<NAME>" "yuanjiaCN" "<NAME>" "MihuSeen" author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(vec))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))))
(defn analyze! [] (comment display-graph!) (comment write-info!) (daily-commits!))
(defn main! [] (println "Started.") (analyze!))
(defn reload! [] (.clear js/console) (println "Reloaded.") (analyze!))
| true |
(ns app.main
(:require ["fs" :as fs]
["path" :as path]
[favored-edn.core :refer [write-edn]]
[medley.core :refer [map-vals map-kv]]
[clojure.string :as string]
["luxon" :refer [DateTime]]))
(defonce projects-commits
(js->clj
(js/JSON.parse
(fs/readFileSync (path/join js/__dirname "../../data/commits.json") "utf8"))
:keywordize-keys
true))
(defn daily-commits! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(map
(fn [record]
{:author (let [author (get-in record [:commit :author :name])]
(case author "PI:NAME:<NAME>END_PI" "yuanjiaCN" "PI:NAME:<NAME>END_PI" "MihuSeen" author)),
:date (let [time (.fromISO
DateTime
(get-in record [:commit :author :date]))]
(.toFormat time "yyyy-MM-dd")),
:repo (:repo record),
:add (get-in record [:stats :additions]),
:delete (get-in record [:stats :deletions])}))
(group-by :date)
(map-vals
(fn [records]
(->> records
(group-by :author)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :date :author)))
(vec)
(count)))))))
(map
(fn [[date info]]
[date
(let [time (.fromISO DateTime date)] (.toFormat time "ccc"))
info]))
(sort-by first)
(vec))]
(println (write-edn result))))
(defn display-number [n char]
(let [x (js/Math.ceil (/ n 200))] (str (string/join "" (repeat x char)) " " n)))
(defn format-records [info]
(->> info
(mapcat
(fn [[author work-info]]
(concat
["\n" author]
(->> work-info
(mapcat
(fn [[project changes]]
["\n"
" "
project
"\n"
" "
(display-number (:add changes) "+")
"\n"
" "
(display-number (:delete changes) "-")]))))))))
(defn display-graph! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author
"PI:NAME:<NAME>END_PI" "yuanjiaCN"
"PI:NAME:<NAME>END_PI" "MihuSeen"
"PI:NAME:<NAME>END_PI" "wangcch"
"yuelei" "PI:NAME:<NAME>END_PI"
author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(reduce
(fn [acc record]
(if (or (> (:add record) 5000)
(> (- (:delete record) (:add record)) 500))
(do
(println "skip large changes" (pr-str record))
acc)
(-> acc
(update :add (fn [x0] (+ x0 (:add record))))
(update
:delete
(fn [x0] (+ x0 (:delete record)))))))
{:add 0, :delete 0}))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))
(println "Wrote to file result.edn .")
(println (string/join "" (format-records result)))))
(defn write-info! []
(let [result (->> projects-commits
(map
(fn [[repo records]]
[repo (->> records (map (fn [record] (assoc record :repo repo))))]))
(mapcat last)
(group-by
(fn [info]
(let [author (get-in info [:commit :author :name])]
(case author "PI:NAME:<NAME>END_PI" "yuanjiaCN" "PI:NAME:<NAME>END_PI" "MihuSeen" author))))
(map-vals
(fn [v]
(->> v
(map
(fn [info]
{:repo (:repo info),
:add (get-in info [:stats :additions]),
:delete (get-in info [:stats :deletions]),
:message (get-in info [:commit :message])}))
(group-by :repo)
(map-vals
(fn [records]
(->> records
(map (fn [record] (dissoc record :repo :message)))
(vec))))))))]
(fs/writeFileSync (path/join js/__dirname "result.edn") (write-edn result))))
(defn analyze! [] (comment display-graph!) (comment write-info!) (daily-commits!))
(defn main! [] (println "Started.") (analyze!))
(defn reload! [] (.clear js/console) (println "Reloaded.") (analyze!))
|
[
{
"context": ".log))\n\n(fact\n (parse-log \"v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocat",
"end": 112,
"score": 0.9370553493499756,
"start": 108,
"tag": "USERNAME",
"value": "user"
},
{
"context": "k=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13",
"end": 203,
"score": 0.9687877297401428,
"start": 202,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": "+2 flail)\")\n => {:v \"0.13-a0\", :lv \"0.1\", :name \"user\", :race \"Naga\", :cls \"Warper\", :char \"NaWr\",\n ",
"end": 592,
"score": 0.9960057139396667,
"start": 588,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ations\", :sklev 3, :title \"Grasshopper\", :place \"D::2\", :br \"D\"\n :lvl 2, :absdepth 2, :hp -2, :mhp",
"end": 717,
"score": 0.9675299525260925,
"start": 716,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": " :goldspent 0, :sc 143, :ktyp \"mon\", :killer \"Terence\", :dam 6, :sdam 6, :tdam 6, :kaux \"a +0,+2 flail\"",
"end": 988,
"score": 0.9519248008728027,
"start": 981,
"tag": "NAME",
"value": "Terence"
},
{
"context": "ence (a +0,+2 flail)\")\n => {:v \"0.13-a0\", :name \"user\", :end \"20130504140401S\"})\n\n(fact\n (log->url (fn",
"end": 1695,
"score": 0.9902441501617432,
"start": 1691,
"tag": "USERNAME",
"value": "user"
},
{
"context": "\" v \"/games/\"))\n {:v \"0.13-a0\", :name \"user\", :end \"20130504140401S\"})\n => \"crawltp://0.13-a",
"end": 1830,
"score": 0.9925293922424316,
"start": 1826,
"tag": "USERNAME",
"value": "user"
},
{
"context": "xt\")\n\n(fact\n (log->rhf-url {:v \"0.13-a0\", :name \"user\", :end \"20130504140401S\"})\n => \"http://rl.heh.fi",
"end": 2760,
"score": 0.9982499480247498,
"start": 2756,
"tag": "USERNAME",
"value": "user"
}
] | test/clj_dcss/log_test.clj | myfreeweb/clj-dcss | 1 | (ns clj-dcss.log-test
(:use midje.sweet
clj-dcss.log))
(fact
(parse-log "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :lv "0.1", :name "user", :race "Naga", :cls "Warper", :char "NaWr",
:xl 2, :sk "Translocations", :sklev 3, :title "Grasshopper", :place "D::2", :br "D"
:lvl 2, :absdepth 2, :hp -2, :mhp 25, :mmhp 25, :str 13, :int 13, :dex 10, :ac 3, :ev 9, :sh 0
:start "20130504140219S", :dur 102, :turn 808, :aut 11015, :kills 12, :gold 129, :goldfound 79
:goldspent 0, :sc 143, :ktyp "mon", :killer "Terence", :dam 6, :sdam 6, :tdam 6, :kaux "a +0,+2 flail"
:end "20130504140401S", :killermap "uniq_terence", :tmsg "slain by Terence", :vmsg "slain by Terence (a +0,+2 flail)"})
(fact
(quick-parse-log-for-url "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :name "user", :end "20130504140401S"})
(fact
(log->url (fn [{:keys [v]}] (str "crawltp://" v "/games/"))
{:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "crawltp://0.13-a0/games/user/morgue-user-20130604-140401.txt") ; lol
(fact
(log->cao-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.akrasiac.org/rawdata/user/morgue-user-20130604-140401.txt")
(facts
(log->cdo-url {:v "0.12.1", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/0.12/user/morgue-user-20130604-140401.txt"
(log->cdo-url {:v "0.14-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/trunk/user/morgue-user-20130604-140401.txt")
(fact
(log->cszo-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://dobrazupa.org/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->clan-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.lantea.net/crawl/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->rhf-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://rl.heh.fi/morgue/user/morgue-user-20130604-140401.txt")
| 80120 | (ns clj-dcss.log-test
(:use midje.sweet
clj-dcss.log))
(fact
(parse-log "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :lv "0.1", :name "user", :race "Naga", :cls "Warper", :char "NaWr",
:xl 2, :sk "Translocations", :sklev 3, :title "Grasshopper", :place "D::2", :br "D"
:lvl 2, :absdepth 2, :hp -2, :mhp 25, :mmhp 25, :str 13, :int 13, :dex 10, :ac 3, :ev 9, :sh 0
:start "20130504140219S", :dur 102, :turn 808, :aut 11015, :kills 12, :gold 129, :goldfound 79
:goldspent 0, :sc 143, :ktyp "mon", :killer "<NAME>", :dam 6, :sdam 6, :tdam 6, :kaux "a +0,+2 flail"
:end "20130504140401S", :killermap "uniq_terence", :tmsg "slain by Terence", :vmsg "slain by Terence (a +0,+2 flail)"})
(fact
(quick-parse-log-for-url "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :name "user", :end "20130504140401S"})
(fact
(log->url (fn [{:keys [v]}] (str "crawltp://" v "/games/"))
{:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "crawltp://0.13-a0/games/user/morgue-user-20130604-140401.txt") ; lol
(fact
(log->cao-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.akrasiac.org/rawdata/user/morgue-user-20130604-140401.txt")
(facts
(log->cdo-url {:v "0.12.1", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/0.12/user/morgue-user-20130604-140401.txt"
(log->cdo-url {:v "0.14-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/trunk/user/morgue-user-20130604-140401.txt")
(fact
(log->cszo-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://dobrazupa.org/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->clan-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.lantea.net/crawl/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->rhf-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://rl.heh.fi/morgue/user/morgue-user-20130604-140401.txt")
| true | (ns clj-dcss.log-test
(:use midje.sweet
clj-dcss.log))
(fact
(parse-log "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :lv "0.1", :name "user", :race "Naga", :cls "Warper", :char "NaWr",
:xl 2, :sk "Translocations", :sklev 3, :title "Grasshopper", :place "D::2", :br "D"
:lvl 2, :absdepth 2, :hp -2, :mhp 25, :mmhp 25, :str 13, :int 13, :dex 10, :ac 3, :ev 9, :sh 0
:start "20130504140219S", :dur 102, :turn 808, :aut 11015, :kills 12, :gold 129, :goldfound 79
:goldspent 0, :sc 143, :ktyp "mon", :killer "PI:NAME:<NAME>END_PI", :dam 6, :sdam 6, :tdam 6, :kaux "a +0,+2 flail"
:end "20130504140401S", :killermap "uniq_terence", :tmsg "slain by Terence", :vmsg "slain by Terence (a +0,+2 flail)"})
(fact
(quick-parse-log-for-url "v=0.13-a0:lv=0.1:name=user:race=Naga:cls=Warper:char=NaWr:xl=2:sk=Translocations:sklev=3:title=Grasshopper:place=D::2:br=D:lvl=2:absdepth=2:hp=-2:mhp=25:mmhp=25:str=13:int=13:dex=10:ac=3:ev=9:sh=0:start=20130504140219S:dur=102:turn=808:aut=11015:kills=12:gold=129:goldfound=79:goldspent=0:sc=143:ktyp=mon:killer=Terence:dam=6:sdam=6:tdam=6:kaux=a +0,+2 flail:end=20130504140401S:killermap=uniq_terence:tmsg=slain by Terence:vmsg=slain by Terence (a +0,+2 flail)")
=> {:v "0.13-a0", :name "user", :end "20130504140401S"})
(fact
(log->url (fn [{:keys [v]}] (str "crawltp://" v "/games/"))
{:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "crawltp://0.13-a0/games/user/morgue-user-20130604-140401.txt") ; lol
(fact
(log->cao-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.akrasiac.org/rawdata/user/morgue-user-20130604-140401.txt")
(facts
(log->cdo-url {:v "0.12.1", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/0.12/user/morgue-user-20130604-140401.txt"
(log->cdo-url {:v "0.14-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.develz.org/morgues/trunk/user/morgue-user-20130604-140401.txt")
(fact
(log->cszo-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://dobrazupa.org/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->clan-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://crawl.lantea.net/crawl/morgue/user/morgue-user-20130604-140401.txt")
(fact
(log->rhf-url {:v "0.13-a0", :name "user", :end "20130504140401S"})
=> "http://rl.heh.fi/morgue/user/morgue-user-20130604-140401.txt")
|
[
{
"context": "um/count)\n\n(def df (louna.datasets.sql/seq->df [[\"michael\" 3000]\n [\"andy\" 4500]\n ",
"end": 3568,
"score": 0.7481275200843811,
"start": 3561,
"tag": "NAME",
"value": "michael"
},
{
"context": "sql/seq->df [[\"michael\" 3000]\n [\"andy\" 4500]\n [\"justin\" 3500]\n ",
"end": 3600,
"score": 0.9989143013954163,
"start": 3596,
"tag": "NAME",
"value": "andy"
},
{
"context": " [\"andy\" 4500]\n [\"justin\" 3500]\n [\"berta\" 4000]]\n ",
"end": 3634,
"score": 0.9889323115348816,
"start": 3628,
"tag": "NAME",
"value": "justin"
}
] | test/louna_tests/udaf.clj | tkaryadis/louna-spark | 3 | (ns louna-tests.udaf
(:require sparkdefinitive.init-settings
[louna.state.settings :as settings]
louna.datasets.schema
louna.datasets.sql)
(:use louna.datasets.column
louna.datasets.sql-functions
louna.q.run
louna.datasets.udf)
(:import (org.apache.spark.sql.types DataTypes)
(java.util ArrayList)
(org.apache.spark.sql.expressions UserDefinedAggregateFunction MutableAggregationBuffer)
(org.apache.spark.sql Row SparkSession)
(louna-tests.udafAvg MyAvg)))
(settings/set-local-session)
(settings/set-log-level "ERROR")
(settings/set-base-path "/home/white/IdeaProjects/louna-spark/")
;;Proxy doesn't worked,not seriliazeble exception
;;To create a udaf
;;1)class MyUdaf extends UserDefinedAggregateFunction
;;2)MutableAggregationBuffer buffer its argument that spark is using,when calling
;; my udaf,in that buffer i store temporary results or take the final result
;; its spark object like array for example buffer.getLong(0) //to get the first if its type is long
;;3)Implement those methods
;; 1)inputSchema()
;; schema of the input arguments
;; StructType(header) with structFields(columns) type of the Column where the
;; aggregation will be done
;; 2)bufferSchema()
;; schema of the temporary results,while aggregating
;; StructType with the field(Column) schema
;; 3)dataType represents the return DataType
;; the return Datatype,here we dont need schema,just the return type
;; 4)deterministic()
;; true if udaf always same result(with same args),false otherwise
;; 5)initialize(MutableAggregationBuffer buffer)
;; set the first value of the aggregation buffer
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; Row input is everytime what is left so far in the Collumn that we see as Row
;; we take for example the first value and change the buffer
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; merge the 2,by changing the buffer1
;; 8)evaluate will generate the final result of the aggregation
;; for example if the final result will be the 1 element of the buffer
;; return buffer.getLong(0)
;;Here the example will be to calculate the average of a long collumn
;;I read,longs,and the buffer holds 2 numbers,the sum and the count
;;when i finish i return sum/count
;; 1)inputSchema() returns StructType
;; inputSchema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["inputColumn" :long]])
;; 2)bufferSchema() returns StructType
;; buffer schema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["sum" :long] ["count" :long]])
;; (the 2 numbers we need the sum and the count)
;; 3)dataType()
;; return DataTypes.DoubleType; (we will return the average in the end=> double type)
;; 4)deterministic()
;; return true;
;; 5)initialize(MutableAggregationBuffer buffer)
;; buffer.update(0, 0L); //at 0 position ,which is the sum put 0
; buffer.update(1, 0L); //at 1 position,which is the count put 0
;; *our buffer has only 2 values
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; add the number on the sum
;; add 1 on count
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; sum1=sum1+sum2;
;; count1=count1+count2;s
;; 8)evaluate will generate the final result of the aggregation
;; return buffer.getLong(0)/buffer.getLong(1) (sum/count)
(def df (louna.datasets.sql/seq->df [["michael" 3000]
["andy" 4500]
["justin" 3500]
["berta" 4000]]
[["name"] ["salary" :long]]))
(defudaf myAverage (MyAvg.))
(q df
[((myAverage ?salary) ?av)]
.show) | 17999 | (ns louna-tests.udaf
(:require sparkdefinitive.init-settings
[louna.state.settings :as settings]
louna.datasets.schema
louna.datasets.sql)
(:use louna.datasets.column
louna.datasets.sql-functions
louna.q.run
louna.datasets.udf)
(:import (org.apache.spark.sql.types DataTypes)
(java.util ArrayList)
(org.apache.spark.sql.expressions UserDefinedAggregateFunction MutableAggregationBuffer)
(org.apache.spark.sql Row SparkSession)
(louna-tests.udafAvg MyAvg)))
(settings/set-local-session)
(settings/set-log-level "ERROR")
(settings/set-base-path "/home/white/IdeaProjects/louna-spark/")
;;Proxy doesn't worked,not seriliazeble exception
;;To create a udaf
;;1)class MyUdaf extends UserDefinedAggregateFunction
;;2)MutableAggregationBuffer buffer its argument that spark is using,when calling
;; my udaf,in that buffer i store temporary results or take the final result
;; its spark object like array for example buffer.getLong(0) //to get the first if its type is long
;;3)Implement those methods
;; 1)inputSchema()
;; schema of the input arguments
;; StructType(header) with structFields(columns) type of the Column where the
;; aggregation will be done
;; 2)bufferSchema()
;; schema of the temporary results,while aggregating
;; StructType with the field(Column) schema
;; 3)dataType represents the return DataType
;; the return Datatype,here we dont need schema,just the return type
;; 4)deterministic()
;; true if udaf always same result(with same args),false otherwise
;; 5)initialize(MutableAggregationBuffer buffer)
;; set the first value of the aggregation buffer
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; Row input is everytime what is left so far in the Collumn that we see as Row
;; we take for example the first value and change the buffer
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; merge the 2,by changing the buffer1
;; 8)evaluate will generate the final result of the aggregation
;; for example if the final result will be the 1 element of the buffer
;; return buffer.getLong(0)
;;Here the example will be to calculate the average of a long collumn
;;I read,longs,and the buffer holds 2 numbers,the sum and the count
;;when i finish i return sum/count
;; 1)inputSchema() returns StructType
;; inputSchema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["inputColumn" :long]])
;; 2)bufferSchema() returns StructType
;; buffer schema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["sum" :long] ["count" :long]])
;; (the 2 numbers we need the sum and the count)
;; 3)dataType()
;; return DataTypes.DoubleType; (we will return the average in the end=> double type)
;; 4)deterministic()
;; return true;
;; 5)initialize(MutableAggregationBuffer buffer)
;; buffer.update(0, 0L); //at 0 position ,which is the sum put 0
; buffer.update(1, 0L); //at 1 position,which is the count put 0
;; *our buffer has only 2 values
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; add the number on the sum
;; add 1 on count
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; sum1=sum1+sum2;
;; count1=count1+count2;s
;; 8)evaluate will generate the final result of the aggregation
;; return buffer.getLong(0)/buffer.getLong(1) (sum/count)
(def df (louna.datasets.sql/seq->df [["<NAME>" 3000]
["<NAME>" 4500]
["<NAME>" 3500]
["berta" 4000]]
[["name"] ["salary" :long]]))
(defudaf myAverage (MyAvg.))
(q df
[((myAverage ?salary) ?av)]
.show) | true | (ns louna-tests.udaf
(:require sparkdefinitive.init-settings
[louna.state.settings :as settings]
louna.datasets.schema
louna.datasets.sql)
(:use louna.datasets.column
louna.datasets.sql-functions
louna.q.run
louna.datasets.udf)
(:import (org.apache.spark.sql.types DataTypes)
(java.util ArrayList)
(org.apache.spark.sql.expressions UserDefinedAggregateFunction MutableAggregationBuffer)
(org.apache.spark.sql Row SparkSession)
(louna-tests.udafAvg MyAvg)))
(settings/set-local-session)
(settings/set-log-level "ERROR")
(settings/set-base-path "/home/white/IdeaProjects/louna-spark/")
;;Proxy doesn't worked,not seriliazeble exception
;;To create a udaf
;;1)class MyUdaf extends UserDefinedAggregateFunction
;;2)MutableAggregationBuffer buffer its argument that spark is using,when calling
;; my udaf,in that buffer i store temporary results or take the final result
;; its spark object like array for example buffer.getLong(0) //to get the first if its type is long
;;3)Implement those methods
;; 1)inputSchema()
;; schema of the input arguments
;; StructType(header) with structFields(columns) type of the Column where the
;; aggregation will be done
;; 2)bufferSchema()
;; schema of the temporary results,while aggregating
;; StructType with the field(Column) schema
;; 3)dataType represents the return DataType
;; the return Datatype,here we dont need schema,just the return type
;; 4)deterministic()
;; true if udaf always same result(with same args),false otherwise
;; 5)initialize(MutableAggregationBuffer buffer)
;; set the first value of the aggregation buffer
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; Row input is everytime what is left so far in the Collumn that we see as Row
;; we take for example the first value and change the buffer
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; merge the 2,by changing the buffer1
;; 8)evaluate will generate the final result of the aggregation
;; for example if the final result will be the 1 element of the buffer
;; return buffer.getLong(0)
;;Here the example will be to calculate the average of a long collumn
;;I read,longs,and the buffer holds 2 numbers,the sum and the count
;;when i finish i return sum/count
;; 1)inputSchema() returns StructType
;; inputSchema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["inputColumn" :long]])
;; 2)bufferSchema() returns StructType
;; buffer schema object will be on member of the class,and this method will return it
;; louna.schema/build-schema([["sum" :long] ["count" :long]])
;; (the 2 numbers we need the sum and the count)
;; 3)dataType()
;; return DataTypes.DoubleType; (we will return the average in the end=> double type)
;; 4)deterministic()
;; return true;
;; 5)initialize(MutableAggregationBuffer buffer)
;; buffer.update(0, 0L); //at 0 position ,which is the sum put 0
; buffer.update(1, 0L); //at 1 position,which is the count put 0
;; *our buffer has only 2 values
;; 6)update(MutableAggregationBuffer buffer, Row input)
;; add the number on the sum
;; add 1 on count
;; 7)merge(MutableAggregationBuffer buffer1, Row buffer2)
;; sum1=sum1+sum2;
;; count1=count1+count2;s
;; 8)evaluate will generate the final result of the aggregation
;; return buffer.getLong(0)/buffer.getLong(1) (sum/count)
(def df (louna.datasets.sql/seq->df [["PI:NAME:<NAME>END_PI" 3000]
["PI:NAME:<NAME>END_PI" 4500]
["PI:NAME:<NAME>END_PI" 3500]
["berta" 4000]]
[["name"] ["salary" :long]]))
(defudaf myAverage (MyAvg.))
(q df
[((myAverage ?salary) ?av)]
.show) |
[
{
"context": "lass))\n\n(defmacro project-data [key]\n ; HACK(Richo): This macro allows to read the project.clj file ",
"end": 743,
"score": 0.6707649827003479,
"start": 742,
"tag": "NAME",
"value": "o"
}
] | middleware/server/src/middleware/main.clj | GIRA/UziScript | 15 | (ns middleware.main
(:require [clojure.tools.logging :as log]
[clojure.tools.cli :as cli]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.java.browse :refer [browse-url]]
[middleware.server.http :as http]
[middleware.server.udp :as udp]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.ports.serial :as serial]
[middleware.device.ports.socket :as socket]
[middleware.utils.fs.common :as fs]
[middleware.utils.fs.jio :as jio]
[middleware.utils.eventlog :as elog])
(:gen-class))
(defmacro project-data [key]
; HACK(Richo): This macro allows to read the project.clj file at compile time
`~(let [data (-> "project.clj" slurp read-string)
name (str (nth data 1))
version (nth data 2)
rest (drop 3 data)]
((apply assoc {:name name, :version version} rest) key)))
(def project-name
(let [description (project-data :description)
version (project-data :version)]
(format "%s (%s)" description version)))
(def cli-options
[["-u" "--uzi PATH" "Uzi libraries folder (default: uzi)"
:default "uzi"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-w" "--web PATH" "Web resources folder (default: web)"
:default "web"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-s" "--server-port PORT" "Server port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-a" "--arduino-port PORT" "Arduino port name"
:default nil]
["-o" "--open-browser" "Open browser flag"]
["-h" "--help"]])
(defn usage [options-summary]
(->> [project-name
""
"Options:"
options-summary]
(str/join \newline)))
(defn error-msg [errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn exit [status msg]
(log/info msg)
(System/exit status))
(defn init-dependencies []
(fs/register-fs! #'jio/file)
(ports/register-constructors! #'socket/open-port
#'serial/open-port))
(defn start
[{:keys [uzi web server-port arduino-port open-browser]}]
(init-dependencies)
(log/info project-name)
(log/info "Starting server...")
(http/start :uzi-libraries uzi
:web-resources web
:server-port server-port)
(udp/start)
(log/info "Server started on port" server-port)
(when open-browser
(let [url (str "http://localhost:" server-port)]
(log/info "Opening browser on" url)
(browse-url url)))
(println)
(if arduino-port
(dc/connect! arduino-port)
(dc/start-port-scanning!)))
(defn add-shutdown-hook! []
(.addShutdownHook (Runtime/getRuntime)
(Thread. ^Runnable #(elog/append "SYSTEM/SHUTDOWN"))))
(defn -main [& args]
(let [{:keys [errors options summary]} (cli/parse-opts args cli-options)]
(when errors
(exit 1 (error-msg errors)))
(when (:help options)
(exit 0 (usage summary)))
(elog/append "SYSTEM/STARTUP")
(add-shutdown-hook!)
(start options)))
| 123549 | (ns middleware.main
(:require [clojure.tools.logging :as log]
[clojure.tools.cli :as cli]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.java.browse :refer [browse-url]]
[middleware.server.http :as http]
[middleware.server.udp :as udp]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.ports.serial :as serial]
[middleware.device.ports.socket :as socket]
[middleware.utils.fs.common :as fs]
[middleware.utils.fs.jio :as jio]
[middleware.utils.eventlog :as elog])
(:gen-class))
(defmacro project-data [key]
; HACK(Rich<NAME>): This macro allows to read the project.clj file at compile time
`~(let [data (-> "project.clj" slurp read-string)
name (str (nth data 1))
version (nth data 2)
rest (drop 3 data)]
((apply assoc {:name name, :version version} rest) key)))
(def project-name
(let [description (project-data :description)
version (project-data :version)]
(format "%s (%s)" description version)))
(def cli-options
[["-u" "--uzi PATH" "Uzi libraries folder (default: uzi)"
:default "uzi"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-w" "--web PATH" "Web resources folder (default: web)"
:default "web"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-s" "--server-port PORT" "Server port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-a" "--arduino-port PORT" "Arduino port name"
:default nil]
["-o" "--open-browser" "Open browser flag"]
["-h" "--help"]])
(defn usage [options-summary]
(->> [project-name
""
"Options:"
options-summary]
(str/join \newline)))
(defn error-msg [errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn exit [status msg]
(log/info msg)
(System/exit status))
(defn init-dependencies []
(fs/register-fs! #'jio/file)
(ports/register-constructors! #'socket/open-port
#'serial/open-port))
(defn start
[{:keys [uzi web server-port arduino-port open-browser]}]
(init-dependencies)
(log/info project-name)
(log/info "Starting server...")
(http/start :uzi-libraries uzi
:web-resources web
:server-port server-port)
(udp/start)
(log/info "Server started on port" server-port)
(when open-browser
(let [url (str "http://localhost:" server-port)]
(log/info "Opening browser on" url)
(browse-url url)))
(println)
(if arduino-port
(dc/connect! arduino-port)
(dc/start-port-scanning!)))
(defn add-shutdown-hook! []
(.addShutdownHook (Runtime/getRuntime)
(Thread. ^Runnable #(elog/append "SYSTEM/SHUTDOWN"))))
(defn -main [& args]
(let [{:keys [errors options summary]} (cli/parse-opts args cli-options)]
(when errors
(exit 1 (error-msg errors)))
(when (:help options)
(exit 0 (usage summary)))
(elog/append "SYSTEM/STARTUP")
(add-shutdown-hook!)
(start options)))
| true | (ns middleware.main
(:require [clojure.tools.logging :as log]
[clojure.tools.cli :as cli]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.java.browse :refer [browse-url]]
[middleware.server.http :as http]
[middleware.server.udp :as udp]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.ports.serial :as serial]
[middleware.device.ports.socket :as socket]
[middleware.utils.fs.common :as fs]
[middleware.utils.fs.jio :as jio]
[middleware.utils.eventlog :as elog])
(:gen-class))
(defmacro project-data [key]
; HACK(RichPI:NAME:<NAME>END_PI): This macro allows to read the project.clj file at compile time
`~(let [data (-> "project.clj" slurp read-string)
name (str (nth data 1))
version (nth data 2)
rest (drop 3 data)]
((apply assoc {:name name, :version version} rest) key)))
(def project-name
(let [description (project-data :description)
version (project-data :version)]
(format "%s (%s)" description version)))
(def cli-options
[["-u" "--uzi PATH" "Uzi libraries folder (default: uzi)"
:default "uzi"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-w" "--web PATH" "Web resources folder (default: web)"
:default "web"
:validate [#(.exists (io/file %)) "The directory doesn't exist"]]
["-s" "--server-port PORT" "Server port number"
:default 3000
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-a" "--arduino-port PORT" "Arduino port name"
:default nil]
["-o" "--open-browser" "Open browser flag"]
["-h" "--help"]])
(defn usage [options-summary]
(->> [project-name
""
"Options:"
options-summary]
(str/join \newline)))
(defn error-msg [errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn exit [status msg]
(log/info msg)
(System/exit status))
(defn init-dependencies []
(fs/register-fs! #'jio/file)
(ports/register-constructors! #'socket/open-port
#'serial/open-port))
(defn start
[{:keys [uzi web server-port arduino-port open-browser]}]
(init-dependencies)
(log/info project-name)
(log/info "Starting server...")
(http/start :uzi-libraries uzi
:web-resources web
:server-port server-port)
(udp/start)
(log/info "Server started on port" server-port)
(when open-browser
(let [url (str "http://localhost:" server-port)]
(log/info "Opening browser on" url)
(browse-url url)))
(println)
(if arduino-port
(dc/connect! arduino-port)
(dc/start-port-scanning!)))
(defn add-shutdown-hook! []
(.addShutdownHook (Runtime/getRuntime)
(Thread. ^Runnable #(elog/append "SYSTEM/SHUTDOWN"))))
(defn -main [& args]
(let [{:keys [errors options summary]} (cli/parse-opts args cli-options)]
(when errors
(exit 1 (error-msg errors)))
(when (:help options)
(exit 0 (usage summary)))
(elog/append "SYSTEM/STARTUP")
(add-shutdown-hook!)
(start options)))
|
[
{
"context": " ^{:doc \"Useful monitoring synths\"\n :author \"Sam Aaron\"}\n overtone.synth.monitor\n (:use [overtone.core",
"end": 66,
"score": 0.9998903870582581,
"start": 57,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/synth/monitor.clj | ABaldwinHunter/overtone | 3,870 | (ns
^{:doc "Useful monitoring synths"
:author "Sam Aaron"}
overtone.synth.monitor
(:use [overtone.core]))
(defsynth mono-audio-bus-level [in-a-bus 0 out-c-bus 0]
(let [sig (in:ar in-a-bus 1)
level (amplitude sig)
level (lag-ud level 0.1 0.3)]
(out:kr out-c-bus [(a2k level)])))
| 35845 | (ns
^{:doc "Useful monitoring synths"
:author "<NAME>"}
overtone.synth.monitor
(:use [overtone.core]))
(defsynth mono-audio-bus-level [in-a-bus 0 out-c-bus 0]
(let [sig (in:ar in-a-bus 1)
level (amplitude sig)
level (lag-ud level 0.1 0.3)]
(out:kr out-c-bus [(a2k level)])))
| true | (ns
^{:doc "Useful monitoring synths"
:author "PI:NAME:<NAME>END_PI"}
overtone.synth.monitor
(:use [overtone.core]))
(defsynth mono-audio-bus-level [in-a-bus 0 out-c-bus 0]
(let [sig (in:ar in-a-bus 1)
level (amplitude sig)
level (lag-ud level 0.1 0.3)]
(out:kr out-c-bus [(a2k level)])))
|
[
{
"context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde",
"end": 31,
"score": 0.9997513294219971,
"start": 19,
"tag": "NAME",
"value": "Hirokuni Kim"
},
{
"context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses",
"end": 64,
"score": 0.9998785853385925,
"start": 52,
"tag": "NAME",
"value": "Kevin Kredit"
}
] | clojure/p17-sets/src/p17_sets/core.clj | kkredit/pl-study | 0 | ;; Original author Hirokuni Kim
;; Modifications by Kevin Kredit
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#sets
(ns p17-sets.core
(:use [clojure.set]))
(defn -main
"Main"
[]
(println #{1 2 3})
; (println #{1 2 3 3}) ; IllegalArgumentException Duplicate key: 3
(println (conj #{1 2 3} 4))
(println (conj (conj #{1 2 3} 4) 4)) ; there is only one 4 in the result
(println (disj #{1 2 3} 1))
(println (disj #{1 2 3} 4))
(println (sort (conj #{1 2 3} 4)))
(println (contains? #{1 2 3} 1))
(println (clojure.set/subset? #{1 2} #{1 2 3 4}))
(println (clojure.set/superset? #{1 2 3} #{1 2}))
(println #{1 2 'a})
)
| 79598 | ;; Original author <NAME>
;; Modifications by <NAME>
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#sets
(ns p17-sets.core
(:use [clojure.set]))
(defn -main
"Main"
[]
(println #{1 2 3})
; (println #{1 2 3 3}) ; IllegalArgumentException Duplicate key: 3
(println (conj #{1 2 3} 4))
(println (conj (conj #{1 2 3} 4) 4)) ; there is only one 4 in the result
(println (disj #{1 2 3} 1))
(println (disj #{1 2 3} 4))
(println (sort (conj #{1 2 3} 4)))
(println (contains? #{1 2 3} 1))
(println (clojure.set/subset? #{1 2} #{1 2 3 4}))
(println (clojure.set/superset? #{1 2 3} #{1 2}))
(println #{1 2 'a})
)
| true | ;; Original author PI:NAME:<NAME>END_PI
;; Modifications by PI:NAME:<NAME>END_PI
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#sets
(ns p17-sets.core
(:use [clojure.set]))
(defn -main
"Main"
[]
(println #{1 2 3})
; (println #{1 2 3 3}) ; IllegalArgumentException Duplicate key: 3
(println (conj #{1 2 3} 4))
(println (conj (conj #{1 2 3} 4) 4)) ; there is only one 4 in the result
(println (disj #{1 2 3} 1))
(println (disj #{1 2 3} 4))
(println (sort (conj #{1 2 3} 4)))
(println (contains? #{1 2 3} 1))
(println (clojure.set/subset? #{1 2} #{1 2 3 4}))
(println (clojure.set/superset? #{1 2 3} #{1 2}))
(println #{1 2 'a})
)
|
[
{
"context": " [mui/link {:href \"https://samedhi.github.io/\"} \"Stephen Cagle\"]\n [mui/link {:href \"https://github.com/samedh",
"end": 1001,
"score": 0.7168677449226379,
"start": 988,
"tag": "NAME",
"value": "Stephen Cagle"
},
{
"context": " Cagle\"]\n [mui/link {:href \"https://github.com/samedhi\"} \"@github\"]\n [mui/link {:href \"https://www.li",
"end": 1052,
"score": 0.998786449432373,
"start": 1045,
"tag": "USERNAME",
"value": "samedhi"
},
{
"context": " [mui/link {:href \"https://www.linkedin.com/in/stephen-cagle-92b895102/\"} \"@linkedin\"]]\n [mui/typography \"Copyright 20",
"end": 1139,
"score": 0.9991812109947205,
"start": 1116,
"tag": "USERNAME",
"value": "stephen-cagle-92b895102"
}
] | src/ants/views/util.cljs | samedhi/ants | 0 | (ns ants.views.util
(:require
[re-frame.core :as re-frame]
[ants.config :as config]
[ants.mui :as mui]
[ants.subs :as subs]))
(defn code-block [o]
[:pre {:class "code-block"}
[:code o]])
(defn app-db-viewer []
(let [db @(re-frame/subscribe [:pretty-print-db])
db-ant-seq @(re-frame/subscribe [:pretty-print-ants-seq])
ants @(re-frame/subscribe [:ants])]
[mui/card
{:style {:margin "1rem 0"}}
[mui/card-content
[mui/typography {:color "textSecondary"} "Content of app-db is:"]
[code-block db]
[mui/typography {:color "textSecondary"}
"Ants state ("
(count ants)
":"
(->> ants vals (filter #(-> % :state (= :lost))) count)
")"]
[:div.ant-database-view
(for [[i db-ant] (map-indexed vector db-ant-seq)]
^{:key i}
[code-block db-ant])]]]))
(defn footer []
[mui/grid
{:class "footer"}
[mui/grid
[mui/link {:href "https://samedhi.github.io/"} "Stephen Cagle"]
[mui/link {:href "https://github.com/samedhi"} "@github"]
[mui/link {:href "https://www.linkedin.com/in/stephen-cagle-92b895102/"} "@linkedin"]]
[mui/typography "Copyright 2020"]])
(defn image
([image-map]
(image image-map :none))
([image-map facing]
(image image-map facing [0 0]))
([image-map facing coordinate]
(let [[row column] coordinate
{:keys [src width height rows columns] :or {rows 1 columns 1}} image-map
section-width (/ width columns)
section-height (/ height rows)]
[:div {:class :img-container
:style {:transform (str "rotate(" (config/facing->degrees facing) "deg)")}}
[:img {:src src
:style {:position :relative
:top (str "-" row "00%")
:left (str "-" column "00%")
:height (str rows "00%")
:width (str columns "00%")}}]])))
| 94763 | (ns ants.views.util
(:require
[re-frame.core :as re-frame]
[ants.config :as config]
[ants.mui :as mui]
[ants.subs :as subs]))
(defn code-block [o]
[:pre {:class "code-block"}
[:code o]])
(defn app-db-viewer []
(let [db @(re-frame/subscribe [:pretty-print-db])
db-ant-seq @(re-frame/subscribe [:pretty-print-ants-seq])
ants @(re-frame/subscribe [:ants])]
[mui/card
{:style {:margin "1rem 0"}}
[mui/card-content
[mui/typography {:color "textSecondary"} "Content of app-db is:"]
[code-block db]
[mui/typography {:color "textSecondary"}
"Ants state ("
(count ants)
":"
(->> ants vals (filter #(-> % :state (= :lost))) count)
")"]
[:div.ant-database-view
(for [[i db-ant] (map-indexed vector db-ant-seq)]
^{:key i}
[code-block db-ant])]]]))
(defn footer []
[mui/grid
{:class "footer"}
[mui/grid
[mui/link {:href "https://samedhi.github.io/"} "<NAME>"]
[mui/link {:href "https://github.com/samedhi"} "@github"]
[mui/link {:href "https://www.linkedin.com/in/stephen-cagle-92b895102/"} "@linkedin"]]
[mui/typography "Copyright 2020"]])
(defn image
([image-map]
(image image-map :none))
([image-map facing]
(image image-map facing [0 0]))
([image-map facing coordinate]
(let [[row column] coordinate
{:keys [src width height rows columns] :or {rows 1 columns 1}} image-map
section-width (/ width columns)
section-height (/ height rows)]
[:div {:class :img-container
:style {:transform (str "rotate(" (config/facing->degrees facing) "deg)")}}
[:img {:src src
:style {:position :relative
:top (str "-" row "00%")
:left (str "-" column "00%")
:height (str rows "00%")
:width (str columns "00%")}}]])))
| true | (ns ants.views.util
(:require
[re-frame.core :as re-frame]
[ants.config :as config]
[ants.mui :as mui]
[ants.subs :as subs]))
(defn code-block [o]
[:pre {:class "code-block"}
[:code o]])
(defn app-db-viewer []
(let [db @(re-frame/subscribe [:pretty-print-db])
db-ant-seq @(re-frame/subscribe [:pretty-print-ants-seq])
ants @(re-frame/subscribe [:ants])]
[mui/card
{:style {:margin "1rem 0"}}
[mui/card-content
[mui/typography {:color "textSecondary"} "Content of app-db is:"]
[code-block db]
[mui/typography {:color "textSecondary"}
"Ants state ("
(count ants)
":"
(->> ants vals (filter #(-> % :state (= :lost))) count)
")"]
[:div.ant-database-view
(for [[i db-ant] (map-indexed vector db-ant-seq)]
^{:key i}
[code-block db-ant])]]]))
(defn footer []
[mui/grid
{:class "footer"}
[mui/grid
[mui/link {:href "https://samedhi.github.io/"} "PI:NAME:<NAME>END_PI"]
[mui/link {:href "https://github.com/samedhi"} "@github"]
[mui/link {:href "https://www.linkedin.com/in/stephen-cagle-92b895102/"} "@linkedin"]]
[mui/typography "Copyright 2020"]])
(defn image
([image-map]
(image image-map :none))
([image-map facing]
(image image-map facing [0 0]))
([image-map facing coordinate]
(let [[row column] coordinate
{:keys [src width height rows columns] :or {rows 1 columns 1}} image-map
section-width (/ width columns)
section-height (/ height rows)]
[:div {:class :img-container
:style {:transform (str "rotate(" (config/facing->degrees facing) "deg)")}}
[:img {:src src
:style {:position :relative
:top (str "-" row "00%")
:left (str "-" column "00%")
:height (str rows "00%")
:width (str columns "00%")}}]])))
|
[
{
"context": "c in finite universes\n\n; Copyright (c) 2017 - 2018 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 134,
"score": 0.9998748898506165,
"start": 120,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] | src/lwb/pred/sat.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Satisfiability of formulas of predicate logic in finite universes
; Copyright (c) 2017 - 2018 Burkhardt Renz, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.sat
(:require [lwb.pred :refer :all]
[lwb.pred.kic :as kic]))
(defn sig->relations
"Map of symbols for predicates, propositions, functions and consts and
their corresponding Kodkod relations from the given signature.
During the function the bounds for the Kodkod relation are set as well."
[sig factory bounds]
(let [mapfn (fn [[key [type arity]]]
(cond
(and (= type :func) (zero? arity)) (kic/make-const key factory bounds)
(and (= type :func) (pos? arity)) (kic/make-func key arity factory bounds)
(and (= type :pred) (pos? arity)) (kic/make-pred key arity factory bounds)
(and (= type :pred) (zero? arity)) (kic/make-prop key factory bounds) ))]
(into {} (map mapfn sig))))
(defn func->constraint
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a function."
[key arity rels]
(let [vars (vec (map #(kic/variable (str "v" %)) (range 1 (inc arity))))
func ((symbol (name key)) rels)
part (loop [v vars result func]
(cond (empty? v) (kic/one result)
:else (recur (rest v) (kic/join (first v) result))))]
(kic/forall vars part) ))
(defn sig->constraints
"Vector of Kodkod formulas comprising the constraints for functions
in the given signature `sig` and the map of relations `rels`."
[sig rels]
(let [mapfn (fn [[key [type arity]]]
(if (and (= type :func) (pos? arity)) (func->constraint key arity rels)))]
(vec (keep identity (map mapfn sig)))))
(defn prop->fml
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a true proposition, i.e. has exactly one tuple."
[key rels]
(let [r ((symbol (name key)) rels)]
(kic/one r) ))
(defn vars->varmap
"Map of symbols to Kodkod variables."
[vars]
(zipmap vars (map kic/variable vars)))
(defn term->expression
"Kodkod expression representing the given expression of a phi."
[term sig env rels]
(if (or (symbol? term) (keyword? term) (int? term))
(cond
(logvar? term sig) (term env)
(func-0? term sig) (term rels)
(const? term) ((symbol (name term)) rels))
;; funcs
(cond
(func? (first term) sig)
(let [func ((first term) rels)
args (vec (map #(term->expression % sig env rels) (rest term)))]
(loop [v args result func]
(cond (empty? v) result
:else (recur (rest v) (kic/join (first v) result))))))))
(def ^:private kic-ops
{'not kic/not
'and kic/and
'or kic/or
'impl kic/impl
'equiv kic/equiv
'xor kic/xor
'ite kic/ite})
(defn phi->formula
"Kodkod formula representing the given formula `phi` of predicate
logic.
All variables of `phi` must be bound.
`sig` is the signature for `phi`.
`env` is the environment i.e. map of variables for `phi`.
`rels` is the map of the Kodkod relations from the signature of `phi`."
[phi sig env rels]
(if (or (symbol? phi) (keyword? phi) (int? phi)) ;; leaf
(cond
(prop? phi sig) (kic/one (phi rels)) )
;; list
(cond
;; operators
(op? (first phi)) (let [args (vec (map #(phi->formula % sig env rels) (rest phi)))] (apply ((first phi) kic-ops) args))
;; quantors
(quantor? (first phi))
(let [kic-quant (if (= 'forall (first phi)) kic/forall kic/exists)
varmap (vars->varmap (second phi))
env' (merge env varmap)]
(kic-quant (vec (vals varmap)) (phi->formula (nth phi 2) sig env' rels)))
;; equality
(= (first phi) '=) (kic/eq (term->expression (second phi) sig env rels) (term->expression (nth phi 2) sig env rels))
;; predicates
:else (let [pred ((first phi) rels)
terms (vec (map #(term->expression % sig env rels) (rest phi)))]
(kic/in (apply kic/product terms) pred)) )))
(defn sat-intern
"Implementation of sat."
[phi sig set mode]
(let [universe (kic/universe set)
factory (kic/factory universe)
bounds (kic/bounds universe)
rels (sig->relations sig factory bounds)
cons (sig->constraints sig rels)
phi' (phi->formula phi sig {} rels)
fmls (conj cons phi')
fml (apply kic/and fmls)]
(if (= mode :one)
(let [sol (kic/solve fml bounds)]
(kic/model universe sol))
(let [sols (kic/solve-all fml bounds)]
(seq (apply hash-set (keep identity (map #(kic/model universe %) sols))))))))
(defn sig->consts
"Set of consts in signature.
`[:func 0]' are consts in kodkod."
[sig]
(set (map key (filter #(= [:func 0] (val %)) sig))))
(defn fill-up
"Fills the given set with keywords `:e1, :e2...` until `size` is reached."
[set size]
(loop [s set, i 1]
(if (= (count s) size) s
(recur (conj s (keyword (str "e" i))) (inc i)))))
(defmulti sat
"Satisfiability of a formula of the predicate logic in a finite universe.
The one variant of the functions just gives the size of the universe, the
other an explicit vector with the elements of the universe."
(fn [_ _ utype & _]
(if (integer? utype) :int
(when (set? utype) :set))))
(defmethod sat :int
([phi sig usize]
(sat phi sig usize :one))
([phi sig usize mode]
(let [consts (sig->consts sig)
ssize (count consts)]
(if (< usize ssize)
(throw (Exception. "usize must be >= number of unary functions in the signature.")))
(sat-intern phi sig (fill-up consts usize) mode))))
(defmethod sat :set
([phi sig set]
(sat phi sig set :one))
([phi sig set mode]
(sat-intern phi sig set mode)))
(defn sat?
"Is `phi` satisfiable?"
[phi sig usize]
(if (nil? (sat phi sig usize)) false true))
(defn valid?
"Is `phi` valid?"
[phi sig usize]
(not (sat? (list 'not phi) sig usize)))
| 76048 | ; lwb Logic WorkBench -- Satisfiability of formulas of predicate logic in finite universes
; Copyright (c) 2017 - 2018 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.sat
(:require [lwb.pred :refer :all]
[lwb.pred.kic :as kic]))
(defn sig->relations
"Map of symbols for predicates, propositions, functions and consts and
their corresponding Kodkod relations from the given signature.
During the function the bounds for the Kodkod relation are set as well."
[sig factory bounds]
(let [mapfn (fn [[key [type arity]]]
(cond
(and (= type :func) (zero? arity)) (kic/make-const key factory bounds)
(and (= type :func) (pos? arity)) (kic/make-func key arity factory bounds)
(and (= type :pred) (pos? arity)) (kic/make-pred key arity factory bounds)
(and (= type :pred) (zero? arity)) (kic/make-prop key factory bounds) ))]
(into {} (map mapfn sig))))
(defn func->constraint
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a function."
[key arity rels]
(let [vars (vec (map #(kic/variable (str "v" %)) (range 1 (inc arity))))
func ((symbol (name key)) rels)
part (loop [v vars result func]
(cond (empty? v) (kic/one result)
:else (recur (rest v) (kic/join (first v) result))))]
(kic/forall vars part) ))
(defn sig->constraints
"Vector of Kodkod formulas comprising the constraints for functions
in the given signature `sig` and the map of relations `rels`."
[sig rels]
(let [mapfn (fn [[key [type arity]]]
(if (and (= type :func) (pos? arity)) (func->constraint key arity rels)))]
(vec (keep identity (map mapfn sig)))))
(defn prop->fml
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a true proposition, i.e. has exactly one tuple."
[key rels]
(let [r ((symbol (name key)) rels)]
(kic/one r) ))
(defn vars->varmap
"Map of symbols to Kodkod variables."
[vars]
(zipmap vars (map kic/variable vars)))
(defn term->expression
"Kodkod expression representing the given expression of a phi."
[term sig env rels]
(if (or (symbol? term) (keyword? term) (int? term))
(cond
(logvar? term sig) (term env)
(func-0? term sig) (term rels)
(const? term) ((symbol (name term)) rels))
;; funcs
(cond
(func? (first term) sig)
(let [func ((first term) rels)
args (vec (map #(term->expression % sig env rels) (rest term)))]
(loop [v args result func]
(cond (empty? v) result
:else (recur (rest v) (kic/join (first v) result))))))))
(def ^:private kic-ops
{'not kic/not
'and kic/and
'or kic/or
'impl kic/impl
'equiv kic/equiv
'xor kic/xor
'ite kic/ite})
(defn phi->formula
"Kodkod formula representing the given formula `phi` of predicate
logic.
All variables of `phi` must be bound.
`sig` is the signature for `phi`.
`env` is the environment i.e. map of variables for `phi`.
`rels` is the map of the Kodkod relations from the signature of `phi`."
[phi sig env rels]
(if (or (symbol? phi) (keyword? phi) (int? phi)) ;; leaf
(cond
(prop? phi sig) (kic/one (phi rels)) )
;; list
(cond
;; operators
(op? (first phi)) (let [args (vec (map #(phi->formula % sig env rels) (rest phi)))] (apply ((first phi) kic-ops) args))
;; quantors
(quantor? (first phi))
(let [kic-quant (if (= 'forall (first phi)) kic/forall kic/exists)
varmap (vars->varmap (second phi))
env' (merge env varmap)]
(kic-quant (vec (vals varmap)) (phi->formula (nth phi 2) sig env' rels)))
;; equality
(= (first phi) '=) (kic/eq (term->expression (second phi) sig env rels) (term->expression (nth phi 2) sig env rels))
;; predicates
:else (let [pred ((first phi) rels)
terms (vec (map #(term->expression % sig env rels) (rest phi)))]
(kic/in (apply kic/product terms) pred)) )))
(defn sat-intern
"Implementation of sat."
[phi sig set mode]
(let [universe (kic/universe set)
factory (kic/factory universe)
bounds (kic/bounds universe)
rels (sig->relations sig factory bounds)
cons (sig->constraints sig rels)
phi' (phi->formula phi sig {} rels)
fmls (conj cons phi')
fml (apply kic/and fmls)]
(if (= mode :one)
(let [sol (kic/solve fml bounds)]
(kic/model universe sol))
(let [sols (kic/solve-all fml bounds)]
(seq (apply hash-set (keep identity (map #(kic/model universe %) sols))))))))
(defn sig->consts
"Set of consts in signature.
`[:func 0]' are consts in kodkod."
[sig]
(set (map key (filter #(= [:func 0] (val %)) sig))))
(defn fill-up
"Fills the given set with keywords `:e1, :e2...` until `size` is reached."
[set size]
(loop [s set, i 1]
(if (= (count s) size) s
(recur (conj s (keyword (str "e" i))) (inc i)))))
(defmulti sat
"Satisfiability of a formula of the predicate logic in a finite universe.
The one variant of the functions just gives the size of the universe, the
other an explicit vector with the elements of the universe."
(fn [_ _ utype & _]
(if (integer? utype) :int
(when (set? utype) :set))))
(defmethod sat :int
([phi sig usize]
(sat phi sig usize :one))
([phi sig usize mode]
(let [consts (sig->consts sig)
ssize (count consts)]
(if (< usize ssize)
(throw (Exception. "usize must be >= number of unary functions in the signature.")))
(sat-intern phi sig (fill-up consts usize) mode))))
(defmethod sat :set
([phi sig set]
(sat phi sig set :one))
([phi sig set mode]
(sat-intern phi sig set mode)))
(defn sat?
"Is `phi` satisfiable?"
[phi sig usize]
(if (nil? (sat phi sig usize)) false true))
(defn valid?
"Is `phi` valid?"
[phi sig usize]
(not (sat? (list 'not phi) sig usize)))
| true | ; lwb Logic WorkBench -- Satisfiability of formulas of predicate logic in finite universes
; Copyright (c) 2017 - 2018 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.pred.sat
(:require [lwb.pred :refer :all]
[lwb.pred.kic :as kic]))
(defn sig->relations
"Map of symbols for predicates, propositions, functions and consts and
their corresponding Kodkod relations from the given signature.
During the function the bounds for the Kodkod relation are set as well."
[sig factory bounds]
(let [mapfn (fn [[key [type arity]]]
(cond
(and (= type :func) (zero? arity)) (kic/make-const key factory bounds)
(and (= type :func) (pos? arity)) (kic/make-func key arity factory bounds)
(and (= type :pred) (pos? arity)) (kic/make-pred key arity factory bounds)
(and (= type :pred) (zero? arity)) (kic/make-prop key factory bounds) ))]
(into {} (map mapfn sig))))
(defn func->constraint
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a function."
[key arity rels]
(let [vars (vec (map #(kic/variable (str "v" %)) (range 1 (inc arity))))
func ((symbol (name key)) rels)
part (loop [v vars result func]
(cond (empty? v) (kic/one result)
:else (recur (rest v) (kic/join (first v) result))))]
(kic/forall vars part) ))
(defn sig->constraints
"Vector of Kodkod formulas comprising the constraints for functions
in the given signature `sig` and the map of relations `rels`."
[sig rels]
(let [mapfn (fn [[key [type arity]]]
(if (and (= type :func) (pos? arity)) (func->constraint key arity rels)))]
(vec (keep identity (map mapfn sig)))))
(defn prop->fml
"Generates a Kodkod formula expressing that the relation with the given `key`
is actually a true proposition, i.e. has exactly one tuple."
[key rels]
(let [r ((symbol (name key)) rels)]
(kic/one r) ))
(defn vars->varmap
"Map of symbols to Kodkod variables."
[vars]
(zipmap vars (map kic/variable vars)))
(defn term->expression
"Kodkod expression representing the given expression of a phi."
[term sig env rels]
(if (or (symbol? term) (keyword? term) (int? term))
(cond
(logvar? term sig) (term env)
(func-0? term sig) (term rels)
(const? term) ((symbol (name term)) rels))
;; funcs
(cond
(func? (first term) sig)
(let [func ((first term) rels)
args (vec (map #(term->expression % sig env rels) (rest term)))]
(loop [v args result func]
(cond (empty? v) result
:else (recur (rest v) (kic/join (first v) result))))))))
(def ^:private kic-ops
{'not kic/not
'and kic/and
'or kic/or
'impl kic/impl
'equiv kic/equiv
'xor kic/xor
'ite kic/ite})
(defn phi->formula
"Kodkod formula representing the given formula `phi` of predicate
logic.
All variables of `phi` must be bound.
`sig` is the signature for `phi`.
`env` is the environment i.e. map of variables for `phi`.
`rels` is the map of the Kodkod relations from the signature of `phi`."
[phi sig env rels]
(if (or (symbol? phi) (keyword? phi) (int? phi)) ;; leaf
(cond
(prop? phi sig) (kic/one (phi rels)) )
;; list
(cond
;; operators
(op? (first phi)) (let [args (vec (map #(phi->formula % sig env rels) (rest phi)))] (apply ((first phi) kic-ops) args))
;; quantors
(quantor? (first phi))
(let [kic-quant (if (= 'forall (first phi)) kic/forall kic/exists)
varmap (vars->varmap (second phi))
env' (merge env varmap)]
(kic-quant (vec (vals varmap)) (phi->formula (nth phi 2) sig env' rels)))
;; equality
(= (first phi) '=) (kic/eq (term->expression (second phi) sig env rels) (term->expression (nth phi 2) sig env rels))
;; predicates
:else (let [pred ((first phi) rels)
terms (vec (map #(term->expression % sig env rels) (rest phi)))]
(kic/in (apply kic/product terms) pred)) )))
(defn sat-intern
"Implementation of sat."
[phi sig set mode]
(let [universe (kic/universe set)
factory (kic/factory universe)
bounds (kic/bounds universe)
rels (sig->relations sig factory bounds)
cons (sig->constraints sig rels)
phi' (phi->formula phi sig {} rels)
fmls (conj cons phi')
fml (apply kic/and fmls)]
(if (= mode :one)
(let [sol (kic/solve fml bounds)]
(kic/model universe sol))
(let [sols (kic/solve-all fml bounds)]
(seq (apply hash-set (keep identity (map #(kic/model universe %) sols))))))))
(defn sig->consts
"Set of consts in signature.
`[:func 0]' are consts in kodkod."
[sig]
(set (map key (filter #(= [:func 0] (val %)) sig))))
(defn fill-up
"Fills the given set with keywords `:e1, :e2...` until `size` is reached."
[set size]
(loop [s set, i 1]
(if (= (count s) size) s
(recur (conj s (keyword (str "e" i))) (inc i)))))
(defmulti sat
"Satisfiability of a formula of the predicate logic in a finite universe.
The one variant of the functions just gives the size of the universe, the
other an explicit vector with the elements of the universe."
(fn [_ _ utype & _]
(if (integer? utype) :int
(when (set? utype) :set))))
(defmethod sat :int
([phi sig usize]
(sat phi sig usize :one))
([phi sig usize mode]
(let [consts (sig->consts sig)
ssize (count consts)]
(if (< usize ssize)
(throw (Exception. "usize must be >= number of unary functions in the signature.")))
(sat-intern phi sig (fill-up consts usize) mode))))
(defmethod sat :set
([phi sig set]
(sat phi sig set :one))
([phi sig set mode]
(sat-intern phi sig set mode)))
(defn sat?
"Is `phi` satisfiable?"
[phi sig usize]
(if (nil? (sat phi sig usize)) false true))
(defn valid?
"Is `phi` valid?"
[phi sig usize]
(not (sat? (list 'not phi) sig usize)))
|
[
{
"context": " :config-format :raw))))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ",
"end": 1719,
"score": 0.9998701810836792,
"start": 1703,
"tag": "NAME",
"value": "Frederic Merizen"
}
] | test/ferje/config/raw_test.clj | chourave/clojyday | 0 | ;; Copyright and license information at end of file
(ns ferje.config.raw-test
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
[clojure.walk :refer [prewalk]]
[ferje.core :as ferje]
[ferje.config.raw :as raw-config]
[ferje.place :as place]
[ferje.spec-test-utils :refer [instrument-fixture]]
[java-time :as time])
(:import
(de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType
Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth
FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday
HinduHolidayType Holidays HolidayType IslamicHoliday
IslamicHolidayType Month MovingCondition RelativeToEasterSunday
RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With)))
;; Fixtures
(use-fixtures :once instrument-fixture)
;;
(deftest format?-test
(is (place/format? :raw)))
(deftest sort-map-test
(is (= "{:month :may, :day 1}"
(-> {:day 1, :month :may}
raw-config/sort-map
pr-str)))
(is (thrown-with-msg? Exception #"Unhandled keys :foo"
(raw-config/sort-map {:foo 1}))))
(deftest place-integration-test
(testing "Use a map literal configuration"
(is (ferje/holiday?
{:description "blah", :hierarchy :bl
:holidays [{:holiday :fixed
:month :july
:day 14}]}
(time/local-date 2017 7 14)
:type :any-holiday
:config-format :raw))))
;; Copyright 2018 Frederic Merizen
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
| 115362 | ;; Copyright and license information at end of file
(ns ferje.config.raw-test
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
[clojure.walk :refer [prewalk]]
[ferje.core :as ferje]
[ferje.config.raw :as raw-config]
[ferje.place :as place]
[ferje.spec-test-utils :refer [instrument-fixture]]
[java-time :as time])
(:import
(de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType
Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth
FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday
HinduHolidayType Holidays HolidayType IslamicHoliday
IslamicHolidayType Month MovingCondition RelativeToEasterSunday
RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With)))
;; Fixtures
(use-fixtures :once instrument-fixture)
;;
(deftest format?-test
(is (place/format? :raw)))
(deftest sort-map-test
(is (= "{:month :may, :day 1}"
(-> {:day 1, :month :may}
raw-config/sort-map
pr-str)))
(is (thrown-with-msg? Exception #"Unhandled keys :foo"
(raw-config/sort-map {:foo 1}))))
(deftest place-integration-test
(testing "Use a map literal configuration"
(is (ferje/holiday?
{:description "blah", :hierarchy :bl
:holidays [{:holiday :fixed
:month :july
:day 14}]}
(time/local-date 2017 7 14)
:type :any-holiday
:config-format :raw))))
;; Copyright 2018 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
| true | ;; Copyright and license information at end of file
(ns ferje.config.raw-test
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
[clojure.walk :refer [prewalk]]
[ferje.core :as ferje]
[ferje.config.raw :as raw-config]
[ferje.place :as place]
[ferje.spec-test-utils :refer [instrument-fixture]]
[java-time :as time])
(:import
(de.jollyday.config ChristianHoliday ChristianHolidayType ChronologyType Configuration
EthiopianOrthodoxHoliday EthiopianOrthodoxHolidayType
Fixed FixedWeekdayBetweenFixed FixedWeekdayInMonth
FixedWeekdayRelativeToFixed HebrewHoliday HinduHoliday
HinduHolidayType Holidays HolidayType IslamicHoliday
IslamicHolidayType Month MovingCondition RelativeToEasterSunday
RelativeToFixed RelativeToWeekdayInMonth Weekday When Which With)))
;; Fixtures
(use-fixtures :once instrument-fixture)
;;
(deftest format?-test
(is (place/format? :raw)))
(deftest sort-map-test
(is (= "{:month :may, :day 1}"
(-> {:day 1, :month :may}
raw-config/sort-map
pr-str)))
(is (thrown-with-msg? Exception #"Unhandled keys :foo"
(raw-config/sort-map {:foo 1}))))
(deftest place-integration-test
(testing "Use a map literal configuration"
(is (ferje/holiday?
{:description "blah", :hierarchy :bl
:holidays [{:holiday :fixed
:month :july
:day 14}]}
(time/local-date 2017 7 14)
:type :any-holiday
:config-format :raw))))
;; Copyright 2018 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
;; or implied. See the License for the specific language governing
;; permissions and limitations under the License.
|
[
{
"context": "butors\")\n {:basic-auth [(:username user-credentials) (:password user-credentials)]\n ",
"end": 1923,
"score": 0.9860149025917053,
"start": 1907,
"tag": "USERNAME",
"value": "user-credentials"
},
{
"context": "ntributor+user)\n login (:login contributor+user)\n stored-user+commit (id->user+commit! use",
"end": 4782,
"score": 0.8689110279083252,
"start": 4766,
"tag": "USERNAME",
"value": "contributor+user"
},
{
"context": "rs)))\n\n(defn -main [& args]\n (let [username (:username user-credentials)\n password (:passwo",
"end": 6436,
"score": 0.9932730197906494,
"start": 6426,
"tag": "USERNAME",
"value": "(:username"
},
{
"context": "n -main [& args]\n (let [username (:username user-credentials)\n password (:password user-credentia",
"end": 6453,
"score": 0.9968318343162537,
"start": 6437,
"tag": "USERNAME",
"value": "user-credentials"
},
{
"context": ":username user-credentials)\n password (:password user-credentials)\n parsed-opts (parse-o",
"end": 6488,
"score": 0.993765115737915,
"start": 6478,
"tag": "PASSWORD",
"value": "(:password"
},
{
"context": "ser-credentials)\n password (:password user-credentials)\n parsed-opts (parse-opts args cli-opti",
"end": 6505,
"score": 0.9969198703765869,
"start": 6489,
"tag": "PASSWORD",
"value": "user-credentials"
}
] | src/gh_contributors_cli/main.clj | cesarcneto/gh-contributors-cli | 0 | (ns gh-contributors-cli.main
(:gen-class)
(:require [babashka.curl :as curl]
[cheshire.core :as json]
[clojure.string :as str]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]))
(def user-credentials
{:username (System/getenv "GH_FETCH_CONTRIBUTORS_USER")
:password (System/getenv "GH_FETCH_CONTRIBUTORS_TOKEN")})
(def cli-options
[["-r" "--repo REPO" "Repository name. E.g.: apache/spark"
:validate [#(re-matches #"[\w,\-,\_]+\/[\w,\-,\_]+" %) "Must be a valid owner/repository name"]]
["-h" "--help"]])
(def output-attributes
[:html_url :email :name :most_recent_commit_date
:twitter_username :login :following :updated_at
:bio :contributions :location :blog
:followers :company :created_at])
(def application-gh-json "application/vnd.github.v3+json")
(def contributors-filename "contributors.json")
(def contributors+user-filename "contributors+user.json")
(def contributors+user+commit-filename "contributors+user+commit.json")
(def data-dir ".data")
(def contributors+user-dir "contributors+user")
(def user+commit-dir "user+commit")
(defn- repo->data-dir-meta
[repo]
(let [base-path (str data-dir "/" repo)]
{:base-dir-path (str data-dir "/" repo)
:contributors+user-dir-path (str base-path "/" contributors+user-dir)
:user+commit-dir-path (str base-path "/" user+commit-dir)}))
(defn- data-dir!
[cli-parameters]
(.mkdirs (io/as-file (:base-dir-path cli-parameters)))
(.mkdirs (io/as-file (:contributors+user-dir-path cli-parameters)))
(.mkdirs (io/as-file (:user+commit-dir-path cli-parameters)))
data-dir)
(defn- contributors!
([repo]
(contributors! repo 1))
([repo page]
(-> (curl/get (str "https://api.github.com/repos/" repo "/contributors")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:query-params {"page" (str page)
"per_page" (str 100)}
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))))
(defn- repo+filename->file
[repo filename]
(io/as-file (str data-dir "/" repo "/" filename)))
(defn- file->json!
[file]
(when (.exists file)
(-> (slurp file)
(json/parse-string true))))
(defn- json->file!
[json file]
(spit file (json/generate-string json))
json)
(defn all-contributors!
[repo]
(let [cf (repo+filename->file repo contributors-filename)
stored-contributors (file->json! cf)]
(if (some? stored-contributors)
stored-contributors
(do
(println (str "Fetching all " repo " contributors"))
(let [all-contributors (loop [page 1
acc []]
(println (str "Fetching page " page))
(let [contributors (contributors! repo page)]
(if (not-empty contributors)
(recur (inc page) (concat acc contributors))
acc)))]
(json->file! all-contributors cf)
(file->json! cf))))))
(defn- user-file
[user-file-path id]
(io/as-file (str user-file-path "/" id)))
(defn user!
[user-file-path contributor]
(let [id (:id contributor)
url (:url contributor)
stored-contributor+user (file->json! (user-file user-file-path id))]
(if (some? stored-contributor+user)
stored-contributor+user
(do
(println (str "Fetching user " (:url contributor)))
(try (let [user (-> (curl/get url {:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))
contributor+user (conj contributor user)]
(spit (user-file user-file-path id) (json/generate-string contributor+user))
(file->json! (user-file user-file-path id)))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor))))))))
(defn- user+commit-file
[user+commit-file-path id]
(io/as-file (str user+commit-file-path "/" id)))
(defn- id->user+commit!
[user+commit-file-path id]
(let [user+commit-file (user+commit-file user+commit-file-path id)]
(when (.exists user+commit-file)
(-> (slurp user+commit-file)
(json/parse-string true)))))
(defn user+commit!
[repo user+commit-dir-path contributor+user]
(let [id (:id contributor+user)
login (:login contributor+user)
stored-user+commit (id->user+commit! user+commit-dir-path id)]
(if (some? stored-user+commit)
stored-user+commit
(do
(println (str "Fetching latest commit of " login))
(try (let [most-recent-commit-date (-> (curl/get (str "https://api.github.com/repos/" repo "/commits")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}
:query-params {"page" "1"
"per_page" "5"
"author" login}})
:body
(json/parse-string true)
(first)
(get-in [:commit :author :date]))
user+commit (conj contributor+user {:most_recent_commit_date most-recent-commit-date})]
(spit (user+commit-file user+commit-dir-path id) (json/generate-string user+commit))
(id->user+commit! user+commit-dir-path id))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor+user))))))))
(defn- entry->csv-row
[map-entry]
(map #(str (get-in map-entry [%])) output-attributes))
(defn ->output-headers
[attrs]
(vec (map name attrs)))
(defn -main [& args]
(let [username (:username user-credentials)
password (:password user-credentials)
parsed-opts (parse-opts args cli-options)
cli-args (:options parsed-opts)
cli-parameters (merge (repo->data-dir-meta (:repo cli-args))
cli-args)
repo (:repo cli-parameters)]
(if (and username password cli-args)
(do
(data-dir! cli-parameters)
(let [contributors (all-contributors! repo)
contributors+user-file (repo+filename->file repo contributors+user-filename)
contributors+u+c-file (repo+filename->file repo contributors+user+commit-filename)
contributors+user-json (json->file! (map (partial user! (:contributors+user-dir-path cli-parameters))
contributors) contributors+user-file)
contributors+user+commit-json (json->file!
(map (partial user+commit! repo (:user+commit-dir-path cli-parameters))
contributors+user-json)
contributors+u+c-file)]
(with-open [csv-writer (io/writer (io/as-file
(str data-dir "/" repo "/result.csv")))]
(csv/write-csv csv-writer [(->output-headers output-attributes)])
(doseq [contributor contributors+user+commit-json]
(csv/write-csv csv-writer [(entry->csv-row contributor)])))))
(cond
(not-empty (:errors cli-args)) (println (str/join "\n" (:errors cli-args)))
(empty? (:options cli-args)) (println (:summary cli-args))
:else (println "GH_FETCH_CONTRIBUTORS_USER and GH_FETCH_CONTRIBUTORS_TOKEN env vars are not set.")))))
| 12891 | (ns gh-contributors-cli.main
(:gen-class)
(:require [babashka.curl :as curl]
[cheshire.core :as json]
[clojure.string :as str]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]))
(def user-credentials
{:username (System/getenv "GH_FETCH_CONTRIBUTORS_USER")
:password (System/getenv "GH_FETCH_CONTRIBUTORS_TOKEN")})
(def cli-options
[["-r" "--repo REPO" "Repository name. E.g.: apache/spark"
:validate [#(re-matches #"[\w,\-,\_]+\/[\w,\-,\_]+" %) "Must be a valid owner/repository name"]]
["-h" "--help"]])
(def output-attributes
[:html_url :email :name :most_recent_commit_date
:twitter_username :login :following :updated_at
:bio :contributions :location :blog
:followers :company :created_at])
(def application-gh-json "application/vnd.github.v3+json")
(def contributors-filename "contributors.json")
(def contributors+user-filename "contributors+user.json")
(def contributors+user+commit-filename "contributors+user+commit.json")
(def data-dir ".data")
(def contributors+user-dir "contributors+user")
(def user+commit-dir "user+commit")
(defn- repo->data-dir-meta
[repo]
(let [base-path (str data-dir "/" repo)]
{:base-dir-path (str data-dir "/" repo)
:contributors+user-dir-path (str base-path "/" contributors+user-dir)
:user+commit-dir-path (str base-path "/" user+commit-dir)}))
(defn- data-dir!
[cli-parameters]
(.mkdirs (io/as-file (:base-dir-path cli-parameters)))
(.mkdirs (io/as-file (:contributors+user-dir-path cli-parameters)))
(.mkdirs (io/as-file (:user+commit-dir-path cli-parameters)))
data-dir)
(defn- contributors!
([repo]
(contributors! repo 1))
([repo page]
(-> (curl/get (str "https://api.github.com/repos/" repo "/contributors")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:query-params {"page" (str page)
"per_page" (str 100)}
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))))
(defn- repo+filename->file
[repo filename]
(io/as-file (str data-dir "/" repo "/" filename)))
(defn- file->json!
[file]
(when (.exists file)
(-> (slurp file)
(json/parse-string true))))
(defn- json->file!
[json file]
(spit file (json/generate-string json))
json)
(defn all-contributors!
[repo]
(let [cf (repo+filename->file repo contributors-filename)
stored-contributors (file->json! cf)]
(if (some? stored-contributors)
stored-contributors
(do
(println (str "Fetching all " repo " contributors"))
(let [all-contributors (loop [page 1
acc []]
(println (str "Fetching page " page))
(let [contributors (contributors! repo page)]
(if (not-empty contributors)
(recur (inc page) (concat acc contributors))
acc)))]
(json->file! all-contributors cf)
(file->json! cf))))))
(defn- user-file
[user-file-path id]
(io/as-file (str user-file-path "/" id)))
(defn user!
[user-file-path contributor]
(let [id (:id contributor)
url (:url contributor)
stored-contributor+user (file->json! (user-file user-file-path id))]
(if (some? stored-contributor+user)
stored-contributor+user
(do
(println (str "Fetching user " (:url contributor)))
(try (let [user (-> (curl/get url {:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))
contributor+user (conj contributor user)]
(spit (user-file user-file-path id) (json/generate-string contributor+user))
(file->json! (user-file user-file-path id)))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor))))))))
(defn- user+commit-file
[user+commit-file-path id]
(io/as-file (str user+commit-file-path "/" id)))
(defn- id->user+commit!
[user+commit-file-path id]
(let [user+commit-file (user+commit-file user+commit-file-path id)]
(when (.exists user+commit-file)
(-> (slurp user+commit-file)
(json/parse-string true)))))
(defn user+commit!
[repo user+commit-dir-path contributor+user]
(let [id (:id contributor+user)
login (:login contributor+user)
stored-user+commit (id->user+commit! user+commit-dir-path id)]
(if (some? stored-user+commit)
stored-user+commit
(do
(println (str "Fetching latest commit of " login))
(try (let [most-recent-commit-date (-> (curl/get (str "https://api.github.com/repos/" repo "/commits")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}
:query-params {"page" "1"
"per_page" "5"
"author" login}})
:body
(json/parse-string true)
(first)
(get-in [:commit :author :date]))
user+commit (conj contributor+user {:most_recent_commit_date most-recent-commit-date})]
(spit (user+commit-file user+commit-dir-path id) (json/generate-string user+commit))
(id->user+commit! user+commit-dir-path id))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor+user))))))))
(defn- entry->csv-row
[map-entry]
(map #(str (get-in map-entry [%])) output-attributes))
(defn ->output-headers
[attrs]
(vec (map name attrs)))
(defn -main [& args]
(let [username (:username user-credentials)
password <PASSWORD> <PASSWORD>)
parsed-opts (parse-opts args cli-options)
cli-args (:options parsed-opts)
cli-parameters (merge (repo->data-dir-meta (:repo cli-args))
cli-args)
repo (:repo cli-parameters)]
(if (and username password cli-args)
(do
(data-dir! cli-parameters)
(let [contributors (all-contributors! repo)
contributors+user-file (repo+filename->file repo contributors+user-filename)
contributors+u+c-file (repo+filename->file repo contributors+user+commit-filename)
contributors+user-json (json->file! (map (partial user! (:contributors+user-dir-path cli-parameters))
contributors) contributors+user-file)
contributors+user+commit-json (json->file!
(map (partial user+commit! repo (:user+commit-dir-path cli-parameters))
contributors+user-json)
contributors+u+c-file)]
(with-open [csv-writer (io/writer (io/as-file
(str data-dir "/" repo "/result.csv")))]
(csv/write-csv csv-writer [(->output-headers output-attributes)])
(doseq [contributor contributors+user+commit-json]
(csv/write-csv csv-writer [(entry->csv-row contributor)])))))
(cond
(not-empty (:errors cli-args)) (println (str/join "\n" (:errors cli-args)))
(empty? (:options cli-args)) (println (:summary cli-args))
:else (println "GH_FETCH_CONTRIBUTORS_USER and GH_FETCH_CONTRIBUTORS_TOKEN env vars are not set.")))))
| true | (ns gh-contributors-cli.main
(:gen-class)
(:require [babashka.curl :as curl]
[cheshire.core :as json]
[clojure.string :as str]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]))
(def user-credentials
{:username (System/getenv "GH_FETCH_CONTRIBUTORS_USER")
:password (System/getenv "GH_FETCH_CONTRIBUTORS_TOKEN")})
(def cli-options
[["-r" "--repo REPO" "Repository name. E.g.: apache/spark"
:validate [#(re-matches #"[\w,\-,\_]+\/[\w,\-,\_]+" %) "Must be a valid owner/repository name"]]
["-h" "--help"]])
(def output-attributes
[:html_url :email :name :most_recent_commit_date
:twitter_username :login :following :updated_at
:bio :contributions :location :blog
:followers :company :created_at])
(def application-gh-json "application/vnd.github.v3+json")
(def contributors-filename "contributors.json")
(def contributors+user-filename "contributors+user.json")
(def contributors+user+commit-filename "contributors+user+commit.json")
(def data-dir ".data")
(def contributors+user-dir "contributors+user")
(def user+commit-dir "user+commit")
(defn- repo->data-dir-meta
[repo]
(let [base-path (str data-dir "/" repo)]
{:base-dir-path (str data-dir "/" repo)
:contributors+user-dir-path (str base-path "/" contributors+user-dir)
:user+commit-dir-path (str base-path "/" user+commit-dir)}))
(defn- data-dir!
[cli-parameters]
(.mkdirs (io/as-file (:base-dir-path cli-parameters)))
(.mkdirs (io/as-file (:contributors+user-dir-path cli-parameters)))
(.mkdirs (io/as-file (:user+commit-dir-path cli-parameters)))
data-dir)
(defn- contributors!
([repo]
(contributors! repo 1))
([repo page]
(-> (curl/get (str "https://api.github.com/repos/" repo "/contributors")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:query-params {"page" (str page)
"per_page" (str 100)}
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))))
(defn- repo+filename->file
[repo filename]
(io/as-file (str data-dir "/" repo "/" filename)))
(defn- file->json!
[file]
(when (.exists file)
(-> (slurp file)
(json/parse-string true))))
(defn- json->file!
[json file]
(spit file (json/generate-string json))
json)
(defn all-contributors!
[repo]
(let [cf (repo+filename->file repo contributors-filename)
stored-contributors (file->json! cf)]
(if (some? stored-contributors)
stored-contributors
(do
(println (str "Fetching all " repo " contributors"))
(let [all-contributors (loop [page 1
acc []]
(println (str "Fetching page " page))
(let [contributors (contributors! repo page)]
(if (not-empty contributors)
(recur (inc page) (concat acc contributors))
acc)))]
(json->file! all-contributors cf)
(file->json! cf))))))
(defn- user-file
[user-file-path id]
(io/as-file (str user-file-path "/" id)))
(defn user!
[user-file-path contributor]
(let [id (:id contributor)
url (:url contributor)
stored-contributor+user (file->json! (user-file user-file-path id))]
(if (some? stored-contributor+user)
stored-contributor+user
(do
(println (str "Fetching user " (:url contributor)))
(try (let [user (-> (curl/get url {:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}})
:body
(json/parse-string true))
contributor+user (conj contributor user)]
(spit (user-file user-file-path id) (json/generate-string contributor+user))
(file->json! (user-file user-file-path id)))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor))))))))
(defn- user+commit-file
[user+commit-file-path id]
(io/as-file (str user+commit-file-path "/" id)))
(defn- id->user+commit!
[user+commit-file-path id]
(let [user+commit-file (user+commit-file user+commit-file-path id)]
(when (.exists user+commit-file)
(-> (slurp user+commit-file)
(json/parse-string true)))))
(defn user+commit!
[repo user+commit-dir-path contributor+user]
(let [id (:id contributor+user)
login (:login contributor+user)
stored-user+commit (id->user+commit! user+commit-dir-path id)]
(if (some? stored-user+commit)
stored-user+commit
(do
(println (str "Fetching latest commit of " login))
(try (let [most-recent-commit-date (-> (curl/get (str "https://api.github.com/repos/" repo "/commits")
{:basic-auth [(:username user-credentials) (:password user-credentials)]
:headers {"Accept" application-gh-json}
:query-params {"page" "1"
"per_page" "5"
"author" login}})
:body
(json/parse-string true)
(first)
(get-in [:commit :author :date]))
user+commit (conj contributor+user {:most_recent_commit_date most-recent-commit-date})]
(spit (user+commit-file user+commit-dir-path id) (json/generate-string user+commit))
(id->user+commit! user+commit-dir-path id))
(catch java.lang.Exception e
(throw (ex-info (.getMessage e) contributor+user))))))))
(defn- entry->csv-row
[map-entry]
(map #(str (get-in map-entry [%])) output-attributes))
(defn ->output-headers
[attrs]
(vec (map name attrs)))
(defn -main [& args]
(let [username (:username user-credentials)
password PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI)
parsed-opts (parse-opts args cli-options)
cli-args (:options parsed-opts)
cli-parameters (merge (repo->data-dir-meta (:repo cli-args))
cli-args)
repo (:repo cli-parameters)]
(if (and username password cli-args)
(do
(data-dir! cli-parameters)
(let [contributors (all-contributors! repo)
contributors+user-file (repo+filename->file repo contributors+user-filename)
contributors+u+c-file (repo+filename->file repo contributors+user+commit-filename)
contributors+user-json (json->file! (map (partial user! (:contributors+user-dir-path cli-parameters))
contributors) contributors+user-file)
contributors+user+commit-json (json->file!
(map (partial user+commit! repo (:user+commit-dir-path cli-parameters))
contributors+user-json)
contributors+u+c-file)]
(with-open [csv-writer (io/writer (io/as-file
(str data-dir "/" repo "/result.csv")))]
(csv/write-csv csv-writer [(->output-headers output-attributes)])
(doseq [contributor contributors+user+commit-json]
(csv/write-csv csv-writer [(entry->csv-row contributor)])))))
(cond
(not-empty (:errors cli-args)) (println (str/join "\n" (:errors cli-args)))
(empty? (:options cli-args)) (println (:summary cli-args))
:else (println "GH_FETCH_CONTRIBUTORS_USER and GH_FETCH_CONTRIBUTORS_TOKEN env vars are not set.")))))
|
[
{
"context": "tOverlayPort 6666)\n (. config setSymmetricKey \"v3JElaRswYgxOt4b\")\n config))\n\n(def subscriptions\n (let [data (",
"end": 602,
"score": 0.9990773797035217,
"start": 586,
"tag": "KEY",
"value": "v3JElaRswYgxOt4b"
}
] | src/com/gossiperl/client/clojure/core.clj | gossiperl/gossiperl-example-clojure | 0 | (ns com.gossiperl.client.clojure.core
(:import [com.gossiperl.client OverlayWorker Supervisor]
[com.gossiperl.client.config OverlayConfiguration]
[com.gossiperl.client.listener GossiperlClientListener]
[java.util ArrayList]))
(def overlay-config
(let [config (OverlayConfiguration.)]
(. config setClientName "clojure-client-test")
(. config setClientPort 54321)
(. config setClientSecret "clojure-client-secret")
(. config setOverlayName "gossiperl_overlay_remote")
(. config setOverlayPort 6666)
(. config setSymmetricKey "v3JElaRswYgxOt4b")
config))
(def subscriptions
(let [data (ArrayList. ["member_in", "digestForwardableTest"])]
data))
(def gossiperl-listener
(proxy [GossiperlClientListener] []
(connected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Connected." (. config getClientName)))))
(disconnected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Disconnected." (. config getClientName)))))
(subscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] SubscribeAck received for events %s." (. config getClientName) events))))
(unsubscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] UnsubscribeAck received for events %s." (. config getClientName) events))))
))
(defn -main
"Starts the Clojure sample client."
[]
(let [supervisor (Supervisor.)]
(let [configuration overlay-config]
(let [overlay-name (. configuration getOverlayName)]
(. supervisor connect configuration gossiperl-listener)
(. Thread sleep 3000)
(. supervisor subscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor unsubscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor disconnect overlay-name)
)))) | 57293 | (ns com.gossiperl.client.clojure.core
(:import [com.gossiperl.client OverlayWorker Supervisor]
[com.gossiperl.client.config OverlayConfiguration]
[com.gossiperl.client.listener GossiperlClientListener]
[java.util ArrayList]))
(def overlay-config
(let [config (OverlayConfiguration.)]
(. config setClientName "clojure-client-test")
(. config setClientPort 54321)
(. config setClientSecret "clojure-client-secret")
(. config setOverlayName "gossiperl_overlay_remote")
(. config setOverlayPort 6666)
(. config setSymmetricKey "<KEY>")
config))
(def subscriptions
(let [data (ArrayList. ["member_in", "digestForwardableTest"])]
data))
(def gossiperl-listener
(proxy [GossiperlClientListener] []
(connected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Connected." (. config getClientName)))))
(disconnected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Disconnected." (. config getClientName)))))
(subscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] SubscribeAck received for events %s." (. config getClientName) events))))
(unsubscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] UnsubscribeAck received for events %s." (. config getClientName) events))))
))
(defn -main
"Starts the Clojure sample client."
[]
(let [supervisor (Supervisor.)]
(let [configuration overlay-config]
(let [overlay-name (. configuration getOverlayName)]
(. supervisor connect configuration gossiperl-listener)
(. Thread sleep 3000)
(. supervisor subscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor unsubscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor disconnect overlay-name)
)))) | true | (ns com.gossiperl.client.clojure.core
(:import [com.gossiperl.client OverlayWorker Supervisor]
[com.gossiperl.client.config OverlayConfiguration]
[com.gossiperl.client.listener GossiperlClientListener]
[java.util ArrayList]))
(def overlay-config
(let [config (OverlayConfiguration.)]
(. config setClientName "clojure-client-test")
(. config setClientPort 54321)
(. config setClientSecret "clojure-client-secret")
(. config setOverlayName "gossiperl_overlay_remote")
(. config setOverlayPort 6666)
(. config setSymmetricKey "PI:KEY:<KEY>END_PI")
config))
(def subscriptions
(let [data (ArrayList. ["member_in", "digestForwardableTest"])]
data))
(def gossiperl-listener
(proxy [GossiperlClientListener] []
(connected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Connected." (. config getClientName)))))
(disconnected [^OverlayWorker worker]
(let [config (. worker getConfiguration)]
(println (format "[%s] Disconnected." (. config getClientName)))))
(subscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] SubscribeAck received for events %s." (. config getClientName) events))))
(unsubscribeAck [^OverlayWorker worker ^ArrayList events]
(let [config (. worker getConfiguration)]
(println (format "[%s] UnsubscribeAck received for events %s." (. config getClientName) events))))
))
(defn -main
"Starts the Clojure sample client."
[]
(let [supervisor (Supervisor.)]
(let [configuration overlay-config]
(let [overlay-name (. configuration getOverlayName)]
(. supervisor connect configuration gossiperl-listener)
(. Thread sleep 3000)
(. supervisor subscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor unsubscribe overlay-name subscriptions)
(. Thread sleep 3000)
(. supervisor disconnect overlay-name)
)))) |
[
{
"context": " using\n clojure.data.avl/subrange.\"\n\n {:author \"Michał Marczyk\"}\n\n (:refer-clojure :exclude [sorted-map sorted-",
"end": 731,
"score": 0.9998568296432495,
"start": 717,
"tag": "NAME",
"value": "Michał Marczyk"
}
] | server/src/server/avl.clj | markrhacker/Discover-Platform | 0 | (ns fabric.avl
"An implementation of persistent sorted maps and sets based on AVL
trees which can be used as drop-in replacements for Clojure's
built-in sorted maps and sets based on red-black trees. Apart from
the standard sorted collection API, the provided map and set types
support the transients API and several additional logarithmic time
operations: rank queries via clojure.core/nth (select element by
rank) and clojure.data.avl/rank-of (discover rank of element),
\"nearest key\" lookups via clojure.data.avl/nearest, splits by key
and index via clojure.data.avl/split-key and
clojure.data.avl/split-at, respectively, and subsets/submaps using
clojure.data.avl/subrange."
{:author "Michał Marczyk"}
(:refer-clojure :exclude [sorted-map sorted-map-by sorted-set sorted-set-by
range split-at])
(:import (clojure.lang RT Util APersistentMap APersistentSet
IPersistentMap IPersistentSet IPersistentStack
Box MapEntry SeqIterator)
(java.util Comparator Collections ArrayList)
(java.util.concurrent.atomic AtomicReference)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn ^:private throw-unsupported []
(throw (UnsupportedOperationException.)))
(defmacro ^:private caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (== h# (int -1))
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key (int h#))
h#))))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
(def ^:private ^:const empty-set-hashcode (.hashCode #{}))
(def ^:private ^:const empty-set-hasheq (hash #{}))
(def ^:private ^:const empty-map-hashcode (.hashCode {}))
(def ^:private ^:const empty-map-hasheq (hash {}))
(defn ^:private hash-imap
[^IPersistentMap m]
(APersistentMap/mapHash m))
(defn ^:private hasheq-imap
[^IPersistentMap m]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll m)
(APersistentMap/mapHasheq m)))
(defn ^:private hash-iset [^IPersistentSet s]
;; a la clojure.lang.APersistentSet
(loop [h (int 0) s (seq s)]
(if s
(let [e (first s)]
(recur (unchecked-add-int h (if (nil? e) 0 (.hashCode ^Object e)))
(next s)))
h)))
(defn ^:private hasheq-iset [^IPersistentSet s]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll s)
(loop [h (int 0) s (seq s)]
(if s
(recur (unchecked-add-int h (Util/hasheq (first s)))
(next s))
h))))
(defn ^:private hash-seq
[s]
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(if (nil? (first s))
(int 0)
(.hashCode ^Object (first s))))
(next s))
h)))
(defn ^:private hasheq-seq
[s]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll s)
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(Util/hasheq (first s)))
(next s))
h))))
(defn ^:private equiv-sequential
"Assumes x is sequential. Returns true if x equals y, otherwise
returns false."
[x y]
(boolean
(when (sequential? y)
(loop [xs (seq x) ys (seq y)]
(cond (nil? xs) (nil? ys)
(nil? ys) false
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))))
(def ^:private never-equiv (Object.))
(defn ^:private equiv-map
"Assumes x is a map. Returns true if y equals x, otherwise returns
false."
[^clojure.lang.IPersistentMap x y]
(if-not (instance? java.util.Map y)
false
(if (and (instance? clojure.lang.IPersistentMap y)
(not (instance? clojure.lang.MapEquivalence y)))
false
(let [m ^java.util.Map y]
(if-not (== (.size ^java.util.Map x) (.size m))
false
(reduce-kv (fn [t k v]
(if-not (.containsKey m k)
(reduced false)
(if-not (Util/equiv v (.get m k))
(reduced false)
t)))
true
x))))))
(gen-interface
:name clojure.data.avl.IAVLNode
:methods
[[getKey [] Object]
[setKey [Object] clojure.data.avl.IAVLNode]
[getVal [] Object]
[setVal [Object] clojure.data.avl.IAVLNode]
[getLeft [] clojure.data.avl.IAVLNode]
[setLeft [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getRight [] clojure.data.avl.IAVLNode]
[setRight [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getHeight [] int]
[setHeight [int] clojure.data.avl.IAVLNode]
[getRank [] int]
[setRank [int] clojure.data.avl.IAVLNode]])
(gen-interface
:name clojure.data.avl.IAVLTree
:methods [[getTree [] clojure.data.avl.IAVLNode]])
(import (clojure.data.avl IAVLNode IAVLTree))
(definterface INavigableTree
(nearest [test k]))
(deftype AVLNode [^AtomicReference edit
^:unsynchronized-mutable key
^:unsynchronized-mutable val
^:unsynchronized-mutable ^IAVLNode left
^:unsynchronized-mutable ^IAVLNode right
^:unsynchronized-mutable ^int height
^:unsynchronized-mutable ^int rank]
IAVLNode
(getKey [this]
key)
(setKey [this k]
(set! key k)
this)
(getVal [this]
val)
(setVal [this v]
(set! val v)
this)
(getLeft [this]
left)
(setLeft [this l]
(set! left l)
this)
(getRight [this]
right)
(setRight [this r]
(set! right r)
this)
(getHeight [this]
height)
(setHeight [this h]
(set! height h)
this)
(getRank [this]
rank)
(setRank [this r]
(set! rank r)
this)
Object
(equals [this that]
(cond
(identical? this that) true
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(.equals key (nth that 0))
(.equals val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(.equals key (first that))
(.equals val (second that)))
:else false))
(hashCode [this]
(-> (int 31)
(unchecked-add-int (Util/hash key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hash val))))
(toString [this]
(pr-str this))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll this)
(-> (int 31)
(unchecked-add-int (Util/hasheq key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hasheq val)))))
clojure.lang.Indexed
(nth [this n]
(case n
0 key
1 val
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVLNode"))))
(nth [this n not-found]
(case n
0 key
1 val
not-found))
clojure.lang.Counted
(count [this]
2)
clojure.lang.IMeta
(meta [this]
nil)
clojure.lang.IObj
(withMeta [this m]
(with-meta [key val] m))
clojure.lang.IPersistentCollection
(cons [this x]
[key val x])
(empty [this]
[])
(equiv [this that]
(cond
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(= key (nth that 0))
(= val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(= key (first that))
(= val (second that)))
:else false))
clojure.lang.IPersistentStack
(peek [this]
val)
(pop [this]
[key])
clojure.lang.IPersistentVector
(assocN [this i x]
(case i
0 [x val]
1 [key x]
(throw
(IndexOutOfBoundsException. "assocN index out of bounds in AVLNode"))))
(length [this]
2)
clojure.lang.Reversible
(rseq [this]
(list val key))
clojure.lang.Associative
(assoc [this k v]
(if (Util/isInteger k)
(.assocN this k v)
(throw (IllegalArgumentException. "key must be integer"))))
(containsKey [this k]
(if (Util/isInteger k)
(case (int k)
0 true
1 true
false)
false))
(entryAt [this k]
(if (Util/isInteger k)
(case (int k)
0 (MapEntry. 0 key)
1 (MapEntry. 1 val)
nil)))
clojure.lang.ILookup
(valAt [this k not-found]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
not-found)
not-found))
(valAt [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
(throw
(IndexOutOfBoundsException.
"invoke index out of bounds in AVLNode")))
(throw (IllegalArgumentException. "key must be integer"))))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(list key val))
clojure.lang.Sequential
clojure.lang.IEditableCollection
(asTransient [this]
(transient [key val]))
clojure.lang.IMapEntry
(key [this]
key)
(val [this]
val)
java.util.Map$Entry
(getValue [this]
val)
(setValue [this x]
(throw-unsupported))
java.io.Serializable
java.lang.Comparable
(compareTo [this that]
(if (identical? this that)
0
(let [^clojure.lang.IPersistentVector v
(cast clojure.lang.IPersistentVector that)
vcnt (.count v)]
(cond
(< 2 vcnt) -1
(> 2 vcnt) 1
:else
(let [comp (Util/compare key (.nth v 0))]
(if (zero? comp)
(Util/compare val (.nth v 1))
comp))))))
java.lang.Iterable
(iterator [this]
(.iterator ^java.lang.Iterable (list key val)))
java.util.RandomAccess
java.util.List
(get [this i]
(.nth this i))
(indexOf [this x]
(condp = x
key 0
val 1
-1))
(lastIndexOf [this x]
(condp = x
val 1
key 0
-1))
(listIterator [this]
(.listIterator this 0))
(listIterator [this i]
(.listIterator (doto (java.util.ArrayList.)
(.add key)
(.add val))
i))
(subList [this a z]
(if (<= 0 a z 2)
(cond
(== a z) []
(and (== a 0) (== z 2)) this
:else (case a
0 [key]
1 [val]))
(throw
(IndexOutOfBoundsException. "subList index out of bounds in AVLNode"))))
java.util.Collection
(contains [this x]
(or (= key x) (= val x)))
(containsAll [this c]
(every? #(.contains this %) c))
(isEmpty [this]
false)
(toArray [this]
(into-array Object this))
(toArray [this arr]
(if (>= (count arr) 2)
(doto arr
(aset 0 key)
(aset 1 val))
(into-array Object this)))
(size [this]
2)
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private ensure-editable
(^IAVLNode [^AtomicReference edit]
(let [owner (.get edit)]
(cond
(identical? owner (Thread/currentThread))
true
(nil? owner)
(throw (IllegalAccessError. "Transient used after persistent! call"))
:else
(throw (IllegalAccessError. "Transient used by non-owner thread")))))
(^IAVLNode [^AtomicReference edit ^AVLNode node]
(if (identical? edit (.-edit node))
node
(AVLNode. edit
(.getKey node) (.getVal node)
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))))
(defn ^:private height ^long [^IAVLNode node]
(if (nil? node)
0
(long (.getHeight node))))
(defn ^:private rotate-left ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(AVLNode. nil
(.getKey r) (.getVal r)
(AVLNode. nil
(.getKey node) (.getVal node)
l
rl
(inc (max lh rlh))
rnk)
rr
(max (+ lh 2)
(+ rlh 2)
(inc rrh))
(inc (+ rnk rnkr)))))
(defn ^:private rotate-left! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
l (.getLeft node)
r (ensure-editable edit (.getRight node))
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(.setLeft r node)
(.setHeight r (max (+ lh 2) (+ rlh 2) (inc rrh)))
(.setRank r (inc (+ rnk rnkr)))
(.setRight node rl)
(.setHeight node (inc (max lh rlh)))
r))
(defn ^:private rotate-right ^IAVLNode [^IAVLNode node]
(let [r (.getRight node)
l (.getLeft node)
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(AVLNode. nil
(.getKey l) (.getVal l)
ll
(AVLNode. nil
(.getKey node) (.getVal node)
lr
r
(inc (max rh lrh))
(dec (- rnk rnkl)))
(max (+ rh 2)
(+ lrh 2)
(inc llh))
rnkl)))
(defn ^:private rotate-right! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
r (.getRight node)
l (ensure-editable edit (.getLeft node))
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(.setRight l node)
(.setHeight l (max (+ rh 2) (+ lrh 2) (inc llh)))
(.setLeft node lr)
(.setHeight node (inc (max rh lrh)))
(.setRank node (dec (- rnk rnkl)))
l))
(defn ^:private lookup ^IAVLNode [^Comparator comp ^IAVLNode node k]
(if (nil? node)
nil
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) node
(neg? c) (recur comp (.getLeft node) k)
:else (recur comp (.getRight node) k)))))
(defn ^:private lookup-nearest
^IAVLNode [^Comparator comp ^IAVLNode node test k]
(let [below? (or (identical? < test) (identical? <= test))
equal? (or (identical? <= test) (identical? >= test))
back? (if below? neg? pos?)
backward (if below?
#(.getLeft ^IAVLNode %)
#(.getRight ^IAVLNode %))
forward (if below?
#(.getRight ^IAVLNode %)
#(.getLeft ^IAVLNode %))]
(loop [prev nil
node node]
(if (nil? node)
prev
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (if equal?
node
(recur prev (backward node)))
(back? c) (recur prev (backward node))
:else (recur node (forward node))))))))
(defn ^:private select [^IAVLNode node ^long rank]
(if (nil? node)
nil
(let [node-rank (.getRank node)]
(cond
(== node-rank rank) node
(< node-rank rank) (recur (.getRight node) (dec (- rank node-rank)))
:else (recur (.getLeft node) rank)))))
(defn ^:private rank ^long [^Comparator comp ^IAVLNode node k]
(if (nil? node)
-1
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (.getRank node)
(neg? c) (recur comp (.getLeft node) k)
:else (let [r (rank comp (.getRight node) k)]
(if (== -1 r)
-1
(inc (+ (.getRank node) r))))))))
(defn ^:private maybe-rebalance ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right r)]
(rotate-left (AVLNode. nil
(.getKey node) (.getVal node)
(.getLeft node)
new-right
(inc (max lh (height new-right)))
(.getRank node))))
(rotate-left node)))
;; left-heavy
(> b 1)
(let [ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left l)]
(rotate-right (AVLNode. nil
(.getKey node) (.getVal node)
new-left
(.getRight node)
(inc (max rh (height new-left)))
(.getRank node))))
(rotate-right node)))
:else
node)))
(defn ^:private maybe-rebalance! ^IAVLNode [edit ^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [node (ensure-editable edit node)
rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right! edit r)]
(.setRight node new-right)
(.setHeight node (inc (max lh (height new-right))))
(rotate-left! edit node))
(rotate-left! edit node)))
;; left-heavy
(> b 1)
(let [node (ensure-editable edit node)
ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left! edit l)]
(.setLeft node new-left)
(.setHeight node (inc (max rh (height new-left))))
(rotate-right! edit node))
(rotate-right! edit node)))
:else
node)))
(defn ^:private insert
^IAVLNode [^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. nil k v nil nil 1 0)
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(AVLNode. nil
k v
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))
(neg? c)
(let [new-child (insert comp (.getLeft node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (.getHeight new-child)
(height (.getRight node))))
(if (.-val found?)
(.getRank node)
(unchecked-inc-int (.getRank node))))))
:else
(let [new-child (insert comp (.getRight node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (.getHeight new-child)
(height (.getLeft node))))
(.getRank node))))))))
(defn ^:private insert!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. edit k v nil nil 1 0)
(let [node (ensure-editable edit node)
nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(.setKey node k)
(.setVal node v)
node)
(neg? c)
(let [new-child (insert! edit comp (.getLeft node) k v found?)]
(.setLeft node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getRight node)))))
(if-not (.-val found?)
(.setRank node (unchecked-inc-int (.getRank node))))
(maybe-rebalance! edit node))
:else
(let [new-child (insert! edit comp (.getRight node) k v found?)]
(.setRight node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))
(defn ^:private get-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(recur r)
node))
(defn ^:private delete-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(let [l (.getLeft node)
new-right (delete-rightmost r)]
(AVLNode. nil
(.getKey node) (.getVal node)
l
new-right
(inc (max (height l) (height new-right)))
(.getRank node)))
(.getLeft node)))
(defn ^:private delete-rightmost! ^IAVLNode [edit ^IAVLNode node]
(if-not (nil? node)
(let [node (ensure-editable edit node)
r ^IAVLNode (.getRight node)]
(cond
(nil? r)
(if-let [l (.getLeft node)]
(ensure-editable edit l))
(nil? (.getRight r))
(do
(.setRight node (.getLeft r))
(.setHeight node
(inc (max (height (.getLeft node))
(height (.getLeft r)))))
node)
:else
(let [new-right (delete-rightmost! edit r)]
(.setRight node new-right)
(.setHeight node
(inc (max (height (.getLeft node))
(height new-right))))
node)))))
(defn ^:private delete
^IAVLNode [^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(if (and l r)
(let [p (get-rightmost l)
l' (delete-rightmost l)]
(AVLNode. nil
(.getKey p) (.getVal p)
l'
r
(inc (max (height l') (height r)))
(unchecked-dec-int (.getRank node))))
(or l r)))
(neg? c)
(let [new-child (delete comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (height new-child)
(height (.getRight node))))
(if (.-val found?)
(unchecked-dec-int (.getRank node))
(.getRank node))))))
:else
(let [new-child (delete comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (height new-child)
(height (.getLeft node))))
(.getRank node)))))))))
(defn ^:private delete!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(cond
(and l r)
(let [node (ensure-editable edit node)
p (get-rightmost l)
l' (delete-rightmost! edit l)]
(.setKey node (.getKey p))
(.setVal node (.getVal p))
(.setLeft node l')
(.setHeight node (inc (max (height l') (height r))))
(.setRank node (unchecked-dec-int (.getRank node)))
node)
l l
r r
:else nil))
(neg? c)
(let [new-child (delete! edit comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(let [node (ensure-editable edit node)]
(.setLeft node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getRight node)))))
(if (.-val found?)
(.setRank node (unchecked-dec-int (.getRank node))))
(maybe-rebalance! edit node))))
:else
(let [new-child (delete! edit comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(let [node (ensure-editable edit node)]
(.setRight node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))))
(defn ^:private join
[^Comparator comp ^long left-count ^IAVLNode left ^IAVLNode right]
(cond
(nil? left) right
(nil? right) left
:else
(let [lh (.getHeight left)
rh (.getHeight right)]
(cond
(== lh rh)
(let [left-min (get-rightmost left)
new-left (delete comp left (.getKey left-min) (Box. false))]
(AVLNode. nil
(.getKey left-min) (.getVal left-min)
new-left
right
(unchecked-inc-int rh)
(unchecked-dec-int left-count)))
(< lh rh)
(letfn [(step [^IAVLNode current ^long lvl]
(cond
(zero? lvl)
(join comp left-count left current)
(nil? (.getLeft current))
(AVLNode. nil
(.getKey current) (.getVal current)
left
(.getRight current)
2
left-count)
:else
(let [new-child (step (.getLeft current) (dec lvl))
current-r (.getRight current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
new-child
current-r
(inc (max (.getHeight ^IAVLNode new-child)
(height current-r)
#_
(if current-r
(.getHeight current-r)
0)))
(+ left-count (.getRank current)))))))]
(step right (- rh lh)))
:else
(letfn [(step [^IAVLNode current ^long cnt ^long lvl]
(cond
(zero? lvl)
(join comp cnt current right)
(nil? (.getRight current))
(AVLNode. nil
(.getKey current) (.getVal current)
(.getLeft current)
right
2
(.getRank current))
:else
(let [new-child (step (.getRight current)
(dec (- cnt (.getRank current)))
(dec lvl))
current-l (.getLeft current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
current-l
new-child
(inc (max (.getHeight ^IAVLNode new-child)
(height current-l)
#_
(if current-l
(.getHeight current-l)
0)))
(.getRank current))))))]
(step left left-count (- lh rh)))))))
(defn ^:private split [^Comparator comp ^IAVLNode node k]
(letfn [(step [^IAVLNode node]
(if (nil? node)
[nil nil nil]
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c)
[(.getLeft node)
(MapEntry. (.getKey node) (.getVal node))
(.getRight node)]
(neg? c)
(let [[l e r] (step (.getLeft node))
r' (insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false))]
[l
e
(cond
e (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e))))
r
r')
r (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r)))))
r
r')
:else (join comp 0 r r'))
#_
(join comp
(- (.getRank node)
(cond
e
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e)))
r
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r))))
:else
(.getRank node)))
r
(insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false)))])
:else
(let [[l e r] (step (.getRight node))]
[(join comp
(unchecked-inc-int (.getRank node))
(insert comp
(.getLeft node)
(.getKey node)
(.getVal node)
(Box. false))
l)
e
r])))))]
(step node)))
(defn ^:private range ^IAVLNode [^Comparator comp ^IAVLNode node low high]
(let [[_ ^MapEntry low-e r] (split comp node low)
[l ^MapEntry high-e _] (split comp r high)]
(cond-> l
low-e (as-> node
(insert comp node
(.key low-e) (.val low-e)
(Box. false)))
high-e (as-> node
(insert comp node
(.key high-e) (.val high-e)
(Box. false))))))
(defn ^:private seq-push [^IAVLNode node stack ascending?]
(loop [node node stack stack]
(if (nil? node)
stack
(recur (if ascending? (.getLeft node) (.getRight node))
(conj stack node)))))
(defn ^:private avl-map-kv-reduce [^IAVLNode node f init]
(let [init (if (nil? (.getLeft node))
init
(avl-map-kv-reduce (.getLeft node) f init))]
(if (reduced? init)
init
(let [init (f init (.getKey node) (.getVal node))]
(if (reduced? init)
init
(if (nil? (.getRight node))
init
(recur (.getRight node) f init)))))))
(deftype AVLMapSeq [^IPersistentMap _meta
^IPersistentStack stack
^boolean ascending?
^int cnt
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
:no-print true
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-seq _hash))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-seq _hasheq))
clojure.lang.Seqable
(seq [this]
this)
clojure.lang.Sequential
clojure.lang.ISeq
(first [this]
(peek stack)
#_
(let [node ^IAVLNode (peek stack)]
(MapEntry. (.getKey node) (.getVal node))))
(more [this]
(let [node ^IAVLNode (first stack)
next-stack (seq-push (if ascending? (.getRight node) (.getLeft node))
(next stack)
ascending?)]
(if (nil? next-stack)
()
(AVLMapSeq. nil next-stack ascending? (unchecked-dec-int cnt) -1 -1))))
(next [this]
(.seq (.more this)))
clojure.lang.Counted
(count [this]
(if (neg? cnt)
(unchecked-inc-int (count (next this)))
cnt))
clojure.lang.IPersistentCollection
(cons [this x]
(cons x this))
(equiv [this that]
(equiv-sequential this that))
(empty [this]
(with-meta () _meta))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMapSeq. meta stack ascending? cnt _hash _hasheq))
java.io.Serializable
java.util.List
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this arr]
(RT/seqToPassedArray (seq this) arr))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? cnt))
(contains [this x]
(or (some #(Util/equiv % x) this) false))
(iterator [this]
(SeqIterator. this))
(subList [this from to]
(.subList (Collections/unmodifiableList (ArrayList. this)) from to))
(indexOf [this x]
(loop [i (int 0) s (seq this)]
(if s
(if (Util/equiv (first s) x)
i
(recur (unchecked-inc-int i) (next s)))
(int -1))))
(lastIndexOf [this x]
(.lastIndexOf (ArrayList. this) x))
(listIterator [this]
(.listIterator (Collections/unmodifiableList (ArrayList. this))))
(listIterator [this i]
(.listIterator (Collections/unmodifiableList (ArrayList. this)) i))
(get [this i]
(RT/nth this i))
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private create-seq [node ascending? cnt]
(AVLMapSeq. nil (seq-push node nil ascending?) ascending? cnt -1 -1))
(declare ->AVLTransientMap)
(deftype AVLMap [^Comparator comp
^IAVLNode tree
^int cnt
^IPersistentMap _meta
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-imap _hash))
(equals [this that]
(APersistentMap/mapEquals this that))
IAVLTree
(getTree [this]
tree)
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest comp tree test k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-imap _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMap. comp tree cnt meta _hash _hasheq))
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.Indexed
(nth [this i]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
not-found))
clojure.lang.IPersistentCollection
(cons [this entry]
(if (vector? entry)
(assoc this (nth entry 0) (nth entry 1))
(reduce conj this entry)))
(empty [this]
(AVLMap. comp nil 0 _meta empty-map-hashcode empty-map-hasheq))
(equiv [this that]
(equiv-map this that))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(if (pos? cnt)
(create-seq tree true cnt)))
clojure.lang.Reversible
(rseq [this]
(if (pos? cnt)
(create-seq tree false cnt)))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.Associative
(assoc [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(AVLMap. comp
new-tree
(if (.-val found?) cnt (unchecked-inc-int cnt))
_meta -1 -1)))
(containsKey [this k]
(not (nil? (.entryAt this k))))
(entryAt [this k]
(if-let [node (lookup comp tree k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.MapEquivalence
clojure.lang.IPersistentMap
(without [this k]
(let [found? (Box. false)
new-tree (delete comp tree k found?)]
(if (.-val found?)
(AVLMap. comp
new-tree
(unchecked-dec-int cnt)
_meta -1 -1)
this)))
(assocEx [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(if (.-val found?)
(throw (ex-info "key already present" {}))
(AVLMap. comp
new-tree
(unchecked-inc-int cnt)
_meta -1 -1))))
clojure.lang.Sorted
(seq [this ascending?]
(if (pos? cnt)
(create-seq tree ascending? cnt)))
(seqFrom [this k ascending?]
(if (pos? cnt)
(loop [stack nil t tree]
(if-not (nil? t)
(let [c (.compare comp k (.getKey t))]
(cond
(zero? c) (AVLMapSeq. nil (conj stack t) ascending? -1 -1 -1)
ascending? (if (neg? c)
(recur (conj stack t) (.getLeft t))
(recur stack (.getRight t)))
:else (if (pos? c)
(recur (conj stack t) (.getRight t))
(recur stack (.getLeft t)))))
(if-not (nil? stack)
(AVLMapSeq. nil stack ascending? -1 -1 -1))))))
(entryKey [this entry]
(key entry))
(comparator [this]
comp)
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientMap
(AtomicReference. (Thread/currentThread)) comp tree cnt))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if (nil? tree)
init
(let [init (avl-map-kv-reduce tree f init)]
(if (reduced? init)
@init
init))))
java.io.Serializable
Iterable
(iterator [this]
(SeqIterator. (seq this)))
java.util.Map
(get [this k]
(.valAt this k))
(clear [this]
(throw-unsupported))
(containsValue [this v]
(.. this values (contains v)))
(entrySet [this]
(set (seq this)))
(put [this k v]
(throw-unsupported))
(putAll [this m]
(throw-unsupported))
(remove [this k]
(throw-unsupported))
(size [this]
cnt)
(values [this]
(vals this)))
(deftype AVLTransientMap [^AtomicReference edit
^Comparator comp
^:unsynchronized-mutable ^IAVLNode tree
^:unsynchronized-mutable ^int cnt]
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.ITransientCollection
(conj [this entry]
(ensure-editable edit)
(if (vector? entry)
(assoc! this (nth entry 0) (nth entry 1))
(reduce conj! this entry)))
(persistent [this]
(ensure-editable edit)
(.set edit nil)
(AVLMap. comp tree cnt nil -1 -1))
clojure.lang.ITransientAssociative
(assoc [this k v]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (insert! edit comp tree k v found?)]
(set! tree new-tree)
(if-not (.-val found?)
(set! cnt (unchecked-inc-int cnt)))
this))
clojure.lang.ITransientMap
(without [this k]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (delete! edit comp tree k found?)]
(when (.-val found?)
(set! tree new-tree)
(set! cnt (unchecked-dec-int cnt)))
this)))
(declare ->AVLTransientSet)
(deftype AVLSet [^IPersistentMap _meta
^AVLMap avl-map
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-iset _hash))
(equals [this that]
(APersistentSet/setEquals this that))
IAVLTree
(getTree [this]
(.getTree avl-map))
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest (.comparator avl-map)
(.getTree avl-map)
test
k)]
(.getKey node)))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-iset _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLSet. meta avl-map _hash _hasheq))
clojure.lang.Counted
(count [this]
(count avl-map))
clojure.lang.Indexed
(nth [this i]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
not-found))
clojure.lang.IPersistentCollection
(cons [this x]
(AVLSet. _meta (assoc avl-map x x) -1 -1))
(empty [this]
(AVLSet. _meta (empty avl-map) empty-set-hashcode empty-set-hasheq))
(equiv [this that]
(and
(set? that)
(== (count this) (count that))
(every? #(contains? this %) that)))
clojure.lang.Seqable
(seq [this]
(keys avl-map))
clojure.lang.Sorted
(seq [this ascending?]
(RT/keys (.seq avl-map ascending?)))
(seqFrom [this k ascending?]
(RT/keys (.seqFrom avl-map k ascending?)))
(entryKey [this entry]
entry)
(comparator [this]
(.comparator avl-map))
clojure.lang.Reversible
(rseq [this]
(map key (rseq avl-map)))
clojure.lang.ILookup
(valAt [this v]
(.valAt this v nil))
(valAt [this v not-found]
(let [n (.entryAt avl-map v)]
(if-not (nil? n)
(.getKey n)
not-found)))
clojure.lang.IPersistentSet
(disjoin [this v]
(AVLSet. _meta (dissoc avl-map v) -1 -1))
(contains [this k]
(contains? avl-map k))
(get [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientSet (.asTransient avl-map)))
java.io.Serializable
java.util.Set
(add [this o] (throw-unsupported))
(remove [this o] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? (count this)))
(iterator [this]
(SeqIterator. (seq this)))
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this a]
(RT/seqToPassedArray (seq this) a)))
(deftype AVLTransientSet
[^:unsynchronized-mutable ^AVLTransientMap transient-avl-map]
clojure.lang.ITransientCollection
(conj [this k]
(set! transient-avl-map (.assoc transient-avl-map k k))
this)
(persistent [this]
(AVLSet. nil (.persistent transient-avl-map) -1 -1))
clojure.lang.ITransientSet
(disjoin [this k]
(set! transient-avl-map (.without transient-avl-map k))
this)
(contains [this k]
(not (identical? this (.valAt transient-avl-map k this))))
(get [this k]
(.valAt transient-avl-map k))
clojure.lang.IFn
(invoke [this k]
(.valAt transient-avl-map k))
(invoke [this k not-found]
(.valAt transient-avl-map k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Counted
(count [this]
(.count transient-avl-map)))
(def ^:private empty-map
(AVLMap. RT/DEFAULT_COMPARATOR nil 0 nil
empty-map-hashcode empty-map-hasheq))
(def ^:private empty-set
(AVLSet. nil empty-map empty-set-hashcode empty-set-hasheq))
(doseq [v [#'->AVLMapSeq
#'->AVLNode
#'->AVLMap
#'->AVLSet
#'->AVLTransientMap
#'->AVLTransientSet]]
(alter-meta! v assoc :private true))
(defn sorted-map
"keyval => key val
Returns a new AVL map with supplied mappings."
{:added "0.0.1"}
[& keyvals]
(loop [in (seq keyvals) out (transient empty-map)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator."
{:added "0.0.1"}
[^Comparator comparator & keyvals]
(loop [in (seq keyvals)
out (AVLTransientMap.
(AtomicReference. (Thread/currentThread)) comparator nil 0)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map-by: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-set
"Returns a new sorted set with supplied keys."
{:added "0.0.1"}
[& keys]
(persistent! (reduce conj! (transient empty-set) keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
{:added "0.0.1"}
[^Comparator comparator & keys]
(persistent!
(reduce conj!
(AVLTransientSet. (transient (sorted-map-by comparator)))
keys)))
(defn rank-of
"Returns the rank of x in coll or -1 if not present."
{:added "0.0.6"}
^long [coll x]
(rank (.comparator ^clojure.lang.Sorted coll) (.getTree ^IAVLTree coll) x))
(defn nearest
"(alpha)
Equivalent to, but more efficient than, (first (subseq* coll test x)),
where subseq* is clojure.core/subseq for test in #{>, >=} and
clojure.core/rsubseq for test in #{<, <=}."
{:added "0.0.12"}
[coll test x]
(.nearest ^INavigableTree coll test x))
(defn split-key
"(alpha)
Returns [left e? right], where left and right are collections of
the same type as coll and containing, respectively, the keys below
and above k in the ordering determined by coll's comparator, while
e? is the entry at key k for maps, the stored copy of the key k for
sets, nil if coll does not contain k."
{:added "0.0.12"}
[k coll]
(let [comp (.comparator ^clojure.lang.Sorted coll)
[left e? right] (split comp (.getTree ^IAVLTree coll) k)
keyfn (if (map? coll) key identity)
wrap (if (map? coll)
(fn wrap-map [tree cnt]
(AVLMap. comp tree cnt nil -1 -1))
(fn wrap-set [tree cnt]
(AVLSet. nil (AVLMap. comp tree cnt nil -1 -1) -1 -1)))]
[(wrap left
(if (or e? right)
(rank-of coll (keyfn (nearest coll >= k)))
(count coll)))
(if (and e? (set? coll))
(.getKey ^MapEntry e?)
e?)
(wrap right
(if right
(- (count coll) (rank-of coll (keyfn (nearest coll > k))))
0))]))
(defn split-at
"(alpha)
Equivalent to, but more efficient than,
[(into (empty coll) (take n coll))
(into (empty coll) (drop n coll))]."
{:added "0.0.12"}
[^long n coll]
(if (>= n (count coll))
[coll (empty coll)]
(let [k (nth coll n)
k (if (map? coll) (key k) k)
[l e r] (split-key k coll)]
[l (conj r e)])))
(defn subrange
"(alpha)
Returns an AVL collection comprising the entries of coll between
start and end (in the sense determined by coll's comparator) in
logarithmic time. Whether the endpoints are themselves included in
the returned collection depends on the provided tests; start-test
must be either > or >=, end-test must be either < or <=.
When passed a single test and limit, subrange infers the other end
of the range from the test: > / >= mean to include items up to the
end of coll, < / <= mean to include items taken from the beginning
of coll.
(subrange >= start <= end) is equivalent to, but more efficient
than, (into (empty coll) (subseq coll >= start <= end)."
{:added "0.0.12"}
([coll test limit]
(cond
(zero? (count coll))
coll
(#{> >=} test)
(let [n (select (.getTree ^IAVLTree coll)
(dec (count coll)))]
(subrange coll
test limit
<= (.getKey ^IAVLNode n)))
:else
(let [n (select (.getTree ^IAVLTree coll) 0)]
(subrange coll
>= (.getKey ^IAVLNode n)
test limit))))
([coll start-test start end-test end]
(if (zero? (count coll))
coll
(let [comp (.comparator ^clojure.lang.Sorted coll)]
(if (pos? (.compare comp start end))
(throw
(IndexOutOfBoundsException. "start greater than end in subrange"))
(let [keyfn (if (map? coll) key identity)
l (nearest coll start-test start)
h (nearest coll end-test end)]
(if (and l h)
(let [tree (range comp (.getTree ^IAVLTree coll)
(keyfn l)
(keyfn h))
cnt (inc (- (rank-of coll (keyfn h))
(rank-of coll (keyfn l))))
m (AVLMap. comp tree cnt nil -1 -1)]
(if (map? coll)
m
(AVLSet. nil m -1 -1)))
(empty coll))))))))
| 28395 | (ns fabric.avl
"An implementation of persistent sorted maps and sets based on AVL
trees which can be used as drop-in replacements for Clojure's
built-in sorted maps and sets based on red-black trees. Apart from
the standard sorted collection API, the provided map and set types
support the transients API and several additional logarithmic time
operations: rank queries via clojure.core/nth (select element by
rank) and clojure.data.avl/rank-of (discover rank of element),
\"nearest key\" lookups via clojure.data.avl/nearest, splits by key
and index via clojure.data.avl/split-key and
clojure.data.avl/split-at, respectively, and subsets/submaps using
clojure.data.avl/subrange."
{:author "<NAME>"}
(:refer-clojure :exclude [sorted-map sorted-map-by sorted-set sorted-set-by
range split-at])
(:import (clojure.lang RT Util APersistentMap APersistentSet
IPersistentMap IPersistentSet IPersistentStack
Box MapEntry SeqIterator)
(java.util Comparator Collections ArrayList)
(java.util.concurrent.atomic AtomicReference)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn ^:private throw-unsupported []
(throw (UnsupportedOperationException.)))
(defmacro ^:private caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (== h# (int -1))
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key (int h#))
h#))))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
(def ^:private ^:const empty-set-hashcode (.hashCode #{}))
(def ^:private ^:const empty-set-hasheq (hash #{}))
(def ^:private ^:const empty-map-hashcode (.hashCode {}))
(def ^:private ^:const empty-map-hasheq (hash {}))
(defn ^:private hash-imap
[^IPersistentMap m]
(APersistentMap/mapHash m))
(defn ^:private hasheq-imap
[^IPersistentMap m]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll m)
(APersistentMap/mapHasheq m)))
(defn ^:private hash-iset [^IPersistentSet s]
;; a la clojure.lang.APersistentSet
(loop [h (int 0) s (seq s)]
(if s
(let [e (first s)]
(recur (unchecked-add-int h (if (nil? e) 0 (.hashCode ^Object e)))
(next s)))
h)))
(defn ^:private hasheq-iset [^IPersistentSet s]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll s)
(loop [h (int 0) s (seq s)]
(if s
(recur (unchecked-add-int h (Util/hasheq (first s)))
(next s))
h))))
(defn ^:private hash-seq
[s]
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(if (nil? (first s))
(int 0)
(.hashCode ^Object (first s))))
(next s))
h)))
(defn ^:private hasheq-seq
[s]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll s)
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(Util/hasheq (first s)))
(next s))
h))))
(defn ^:private equiv-sequential
"Assumes x is sequential. Returns true if x equals y, otherwise
returns false."
[x y]
(boolean
(when (sequential? y)
(loop [xs (seq x) ys (seq y)]
(cond (nil? xs) (nil? ys)
(nil? ys) false
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))))
(def ^:private never-equiv (Object.))
(defn ^:private equiv-map
"Assumes x is a map. Returns true if y equals x, otherwise returns
false."
[^clojure.lang.IPersistentMap x y]
(if-not (instance? java.util.Map y)
false
(if (and (instance? clojure.lang.IPersistentMap y)
(not (instance? clojure.lang.MapEquivalence y)))
false
(let [m ^java.util.Map y]
(if-not (== (.size ^java.util.Map x) (.size m))
false
(reduce-kv (fn [t k v]
(if-not (.containsKey m k)
(reduced false)
(if-not (Util/equiv v (.get m k))
(reduced false)
t)))
true
x))))))
(gen-interface
:name clojure.data.avl.IAVLNode
:methods
[[getKey [] Object]
[setKey [Object] clojure.data.avl.IAVLNode]
[getVal [] Object]
[setVal [Object] clojure.data.avl.IAVLNode]
[getLeft [] clojure.data.avl.IAVLNode]
[setLeft [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getRight [] clojure.data.avl.IAVLNode]
[setRight [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getHeight [] int]
[setHeight [int] clojure.data.avl.IAVLNode]
[getRank [] int]
[setRank [int] clojure.data.avl.IAVLNode]])
(gen-interface
:name clojure.data.avl.IAVLTree
:methods [[getTree [] clojure.data.avl.IAVLNode]])
(import (clojure.data.avl IAVLNode IAVLTree))
(definterface INavigableTree
(nearest [test k]))
(deftype AVLNode [^AtomicReference edit
^:unsynchronized-mutable key
^:unsynchronized-mutable val
^:unsynchronized-mutable ^IAVLNode left
^:unsynchronized-mutable ^IAVLNode right
^:unsynchronized-mutable ^int height
^:unsynchronized-mutable ^int rank]
IAVLNode
(getKey [this]
key)
(setKey [this k]
(set! key k)
this)
(getVal [this]
val)
(setVal [this v]
(set! val v)
this)
(getLeft [this]
left)
(setLeft [this l]
(set! left l)
this)
(getRight [this]
right)
(setRight [this r]
(set! right r)
this)
(getHeight [this]
height)
(setHeight [this h]
(set! height h)
this)
(getRank [this]
rank)
(setRank [this r]
(set! rank r)
this)
Object
(equals [this that]
(cond
(identical? this that) true
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(.equals key (nth that 0))
(.equals val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(.equals key (first that))
(.equals val (second that)))
:else false))
(hashCode [this]
(-> (int 31)
(unchecked-add-int (Util/hash key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hash val))))
(toString [this]
(pr-str this))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll this)
(-> (int 31)
(unchecked-add-int (Util/hasheq key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hasheq val)))))
clojure.lang.Indexed
(nth [this n]
(case n
0 key
1 val
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVLNode"))))
(nth [this n not-found]
(case n
0 key
1 val
not-found))
clojure.lang.Counted
(count [this]
2)
clojure.lang.IMeta
(meta [this]
nil)
clojure.lang.IObj
(withMeta [this m]
(with-meta [key val] m))
clojure.lang.IPersistentCollection
(cons [this x]
[key val x])
(empty [this]
[])
(equiv [this that]
(cond
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(= key (nth that 0))
(= val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(= key (first that))
(= val (second that)))
:else false))
clojure.lang.IPersistentStack
(peek [this]
val)
(pop [this]
[key])
clojure.lang.IPersistentVector
(assocN [this i x]
(case i
0 [x val]
1 [key x]
(throw
(IndexOutOfBoundsException. "assocN index out of bounds in AVLNode"))))
(length [this]
2)
clojure.lang.Reversible
(rseq [this]
(list val key))
clojure.lang.Associative
(assoc [this k v]
(if (Util/isInteger k)
(.assocN this k v)
(throw (IllegalArgumentException. "key must be integer"))))
(containsKey [this k]
(if (Util/isInteger k)
(case (int k)
0 true
1 true
false)
false))
(entryAt [this k]
(if (Util/isInteger k)
(case (int k)
0 (MapEntry. 0 key)
1 (MapEntry. 1 val)
nil)))
clojure.lang.ILookup
(valAt [this k not-found]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
not-found)
not-found))
(valAt [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
(throw
(IndexOutOfBoundsException.
"invoke index out of bounds in AVLNode")))
(throw (IllegalArgumentException. "key must be integer"))))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(list key val))
clojure.lang.Sequential
clojure.lang.IEditableCollection
(asTransient [this]
(transient [key val]))
clojure.lang.IMapEntry
(key [this]
key)
(val [this]
val)
java.util.Map$Entry
(getValue [this]
val)
(setValue [this x]
(throw-unsupported))
java.io.Serializable
java.lang.Comparable
(compareTo [this that]
(if (identical? this that)
0
(let [^clojure.lang.IPersistentVector v
(cast clojure.lang.IPersistentVector that)
vcnt (.count v)]
(cond
(< 2 vcnt) -1
(> 2 vcnt) 1
:else
(let [comp (Util/compare key (.nth v 0))]
(if (zero? comp)
(Util/compare val (.nth v 1))
comp))))))
java.lang.Iterable
(iterator [this]
(.iterator ^java.lang.Iterable (list key val)))
java.util.RandomAccess
java.util.List
(get [this i]
(.nth this i))
(indexOf [this x]
(condp = x
key 0
val 1
-1))
(lastIndexOf [this x]
(condp = x
val 1
key 0
-1))
(listIterator [this]
(.listIterator this 0))
(listIterator [this i]
(.listIterator (doto (java.util.ArrayList.)
(.add key)
(.add val))
i))
(subList [this a z]
(if (<= 0 a z 2)
(cond
(== a z) []
(and (== a 0) (== z 2)) this
:else (case a
0 [key]
1 [val]))
(throw
(IndexOutOfBoundsException. "subList index out of bounds in AVLNode"))))
java.util.Collection
(contains [this x]
(or (= key x) (= val x)))
(containsAll [this c]
(every? #(.contains this %) c))
(isEmpty [this]
false)
(toArray [this]
(into-array Object this))
(toArray [this arr]
(if (>= (count arr) 2)
(doto arr
(aset 0 key)
(aset 1 val))
(into-array Object this)))
(size [this]
2)
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private ensure-editable
(^IAVLNode [^AtomicReference edit]
(let [owner (.get edit)]
(cond
(identical? owner (Thread/currentThread))
true
(nil? owner)
(throw (IllegalAccessError. "Transient used after persistent! call"))
:else
(throw (IllegalAccessError. "Transient used by non-owner thread")))))
(^IAVLNode [^AtomicReference edit ^AVLNode node]
(if (identical? edit (.-edit node))
node
(AVLNode. edit
(.getKey node) (.getVal node)
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))))
(defn ^:private height ^long [^IAVLNode node]
(if (nil? node)
0
(long (.getHeight node))))
(defn ^:private rotate-left ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(AVLNode. nil
(.getKey r) (.getVal r)
(AVLNode. nil
(.getKey node) (.getVal node)
l
rl
(inc (max lh rlh))
rnk)
rr
(max (+ lh 2)
(+ rlh 2)
(inc rrh))
(inc (+ rnk rnkr)))))
(defn ^:private rotate-left! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
l (.getLeft node)
r (ensure-editable edit (.getRight node))
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(.setLeft r node)
(.setHeight r (max (+ lh 2) (+ rlh 2) (inc rrh)))
(.setRank r (inc (+ rnk rnkr)))
(.setRight node rl)
(.setHeight node (inc (max lh rlh)))
r))
(defn ^:private rotate-right ^IAVLNode [^IAVLNode node]
(let [r (.getRight node)
l (.getLeft node)
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(AVLNode. nil
(.getKey l) (.getVal l)
ll
(AVLNode. nil
(.getKey node) (.getVal node)
lr
r
(inc (max rh lrh))
(dec (- rnk rnkl)))
(max (+ rh 2)
(+ lrh 2)
(inc llh))
rnkl)))
(defn ^:private rotate-right! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
r (.getRight node)
l (ensure-editable edit (.getLeft node))
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(.setRight l node)
(.setHeight l (max (+ rh 2) (+ lrh 2) (inc llh)))
(.setLeft node lr)
(.setHeight node (inc (max rh lrh)))
(.setRank node (dec (- rnk rnkl)))
l))
(defn ^:private lookup ^IAVLNode [^Comparator comp ^IAVLNode node k]
(if (nil? node)
nil
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) node
(neg? c) (recur comp (.getLeft node) k)
:else (recur comp (.getRight node) k)))))
(defn ^:private lookup-nearest
^IAVLNode [^Comparator comp ^IAVLNode node test k]
(let [below? (or (identical? < test) (identical? <= test))
equal? (or (identical? <= test) (identical? >= test))
back? (if below? neg? pos?)
backward (if below?
#(.getLeft ^IAVLNode %)
#(.getRight ^IAVLNode %))
forward (if below?
#(.getRight ^IAVLNode %)
#(.getLeft ^IAVLNode %))]
(loop [prev nil
node node]
(if (nil? node)
prev
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (if equal?
node
(recur prev (backward node)))
(back? c) (recur prev (backward node))
:else (recur node (forward node))))))))
(defn ^:private select [^IAVLNode node ^long rank]
(if (nil? node)
nil
(let [node-rank (.getRank node)]
(cond
(== node-rank rank) node
(< node-rank rank) (recur (.getRight node) (dec (- rank node-rank)))
:else (recur (.getLeft node) rank)))))
(defn ^:private rank ^long [^Comparator comp ^IAVLNode node k]
(if (nil? node)
-1
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (.getRank node)
(neg? c) (recur comp (.getLeft node) k)
:else (let [r (rank comp (.getRight node) k)]
(if (== -1 r)
-1
(inc (+ (.getRank node) r))))))))
(defn ^:private maybe-rebalance ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right r)]
(rotate-left (AVLNode. nil
(.getKey node) (.getVal node)
(.getLeft node)
new-right
(inc (max lh (height new-right)))
(.getRank node))))
(rotate-left node)))
;; left-heavy
(> b 1)
(let [ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left l)]
(rotate-right (AVLNode. nil
(.getKey node) (.getVal node)
new-left
(.getRight node)
(inc (max rh (height new-left)))
(.getRank node))))
(rotate-right node)))
:else
node)))
(defn ^:private maybe-rebalance! ^IAVLNode [edit ^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [node (ensure-editable edit node)
rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right! edit r)]
(.setRight node new-right)
(.setHeight node (inc (max lh (height new-right))))
(rotate-left! edit node))
(rotate-left! edit node)))
;; left-heavy
(> b 1)
(let [node (ensure-editable edit node)
ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left! edit l)]
(.setLeft node new-left)
(.setHeight node (inc (max rh (height new-left))))
(rotate-right! edit node))
(rotate-right! edit node)))
:else
node)))
(defn ^:private insert
^IAVLNode [^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. nil k v nil nil 1 0)
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(AVLNode. nil
k v
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))
(neg? c)
(let [new-child (insert comp (.getLeft node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (.getHeight new-child)
(height (.getRight node))))
(if (.-val found?)
(.getRank node)
(unchecked-inc-int (.getRank node))))))
:else
(let [new-child (insert comp (.getRight node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (.getHeight new-child)
(height (.getLeft node))))
(.getRank node))))))))
(defn ^:private insert!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. edit k v nil nil 1 0)
(let [node (ensure-editable edit node)
nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(.setKey node k)
(.setVal node v)
node)
(neg? c)
(let [new-child (insert! edit comp (.getLeft node) k v found?)]
(.setLeft node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getRight node)))))
(if-not (.-val found?)
(.setRank node (unchecked-inc-int (.getRank node))))
(maybe-rebalance! edit node))
:else
(let [new-child (insert! edit comp (.getRight node) k v found?)]
(.setRight node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))
(defn ^:private get-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(recur r)
node))
(defn ^:private delete-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(let [l (.getLeft node)
new-right (delete-rightmost r)]
(AVLNode. nil
(.getKey node) (.getVal node)
l
new-right
(inc (max (height l) (height new-right)))
(.getRank node)))
(.getLeft node)))
(defn ^:private delete-rightmost! ^IAVLNode [edit ^IAVLNode node]
(if-not (nil? node)
(let [node (ensure-editable edit node)
r ^IAVLNode (.getRight node)]
(cond
(nil? r)
(if-let [l (.getLeft node)]
(ensure-editable edit l))
(nil? (.getRight r))
(do
(.setRight node (.getLeft r))
(.setHeight node
(inc (max (height (.getLeft node))
(height (.getLeft r)))))
node)
:else
(let [new-right (delete-rightmost! edit r)]
(.setRight node new-right)
(.setHeight node
(inc (max (height (.getLeft node))
(height new-right))))
node)))))
(defn ^:private delete
^IAVLNode [^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(if (and l r)
(let [p (get-rightmost l)
l' (delete-rightmost l)]
(AVLNode. nil
(.getKey p) (.getVal p)
l'
r
(inc (max (height l') (height r)))
(unchecked-dec-int (.getRank node))))
(or l r)))
(neg? c)
(let [new-child (delete comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (height new-child)
(height (.getRight node))))
(if (.-val found?)
(unchecked-dec-int (.getRank node))
(.getRank node))))))
:else
(let [new-child (delete comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (height new-child)
(height (.getLeft node))))
(.getRank node)))))))))
(defn ^:private delete!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(cond
(and l r)
(let [node (ensure-editable edit node)
p (get-rightmost l)
l' (delete-rightmost! edit l)]
(.setKey node (.getKey p))
(.setVal node (.getVal p))
(.setLeft node l')
(.setHeight node (inc (max (height l') (height r))))
(.setRank node (unchecked-dec-int (.getRank node)))
node)
l l
r r
:else nil))
(neg? c)
(let [new-child (delete! edit comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(let [node (ensure-editable edit node)]
(.setLeft node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getRight node)))))
(if (.-val found?)
(.setRank node (unchecked-dec-int (.getRank node))))
(maybe-rebalance! edit node))))
:else
(let [new-child (delete! edit comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(let [node (ensure-editable edit node)]
(.setRight node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))))
(defn ^:private join
[^Comparator comp ^long left-count ^IAVLNode left ^IAVLNode right]
(cond
(nil? left) right
(nil? right) left
:else
(let [lh (.getHeight left)
rh (.getHeight right)]
(cond
(== lh rh)
(let [left-min (get-rightmost left)
new-left (delete comp left (.getKey left-min) (Box. false))]
(AVLNode. nil
(.getKey left-min) (.getVal left-min)
new-left
right
(unchecked-inc-int rh)
(unchecked-dec-int left-count)))
(< lh rh)
(letfn [(step [^IAVLNode current ^long lvl]
(cond
(zero? lvl)
(join comp left-count left current)
(nil? (.getLeft current))
(AVLNode. nil
(.getKey current) (.getVal current)
left
(.getRight current)
2
left-count)
:else
(let [new-child (step (.getLeft current) (dec lvl))
current-r (.getRight current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
new-child
current-r
(inc (max (.getHeight ^IAVLNode new-child)
(height current-r)
#_
(if current-r
(.getHeight current-r)
0)))
(+ left-count (.getRank current)))))))]
(step right (- rh lh)))
:else
(letfn [(step [^IAVLNode current ^long cnt ^long lvl]
(cond
(zero? lvl)
(join comp cnt current right)
(nil? (.getRight current))
(AVLNode. nil
(.getKey current) (.getVal current)
(.getLeft current)
right
2
(.getRank current))
:else
(let [new-child (step (.getRight current)
(dec (- cnt (.getRank current)))
(dec lvl))
current-l (.getLeft current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
current-l
new-child
(inc (max (.getHeight ^IAVLNode new-child)
(height current-l)
#_
(if current-l
(.getHeight current-l)
0)))
(.getRank current))))))]
(step left left-count (- lh rh)))))))
(defn ^:private split [^Comparator comp ^IAVLNode node k]
(letfn [(step [^IAVLNode node]
(if (nil? node)
[nil nil nil]
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c)
[(.getLeft node)
(MapEntry. (.getKey node) (.getVal node))
(.getRight node)]
(neg? c)
(let [[l e r] (step (.getLeft node))
r' (insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false))]
[l
e
(cond
e (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e))))
r
r')
r (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r)))))
r
r')
:else (join comp 0 r r'))
#_
(join comp
(- (.getRank node)
(cond
e
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e)))
r
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r))))
:else
(.getRank node)))
r
(insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false)))])
:else
(let [[l e r] (step (.getRight node))]
[(join comp
(unchecked-inc-int (.getRank node))
(insert comp
(.getLeft node)
(.getKey node)
(.getVal node)
(Box. false))
l)
e
r])))))]
(step node)))
(defn ^:private range ^IAVLNode [^Comparator comp ^IAVLNode node low high]
(let [[_ ^MapEntry low-e r] (split comp node low)
[l ^MapEntry high-e _] (split comp r high)]
(cond-> l
low-e (as-> node
(insert comp node
(.key low-e) (.val low-e)
(Box. false)))
high-e (as-> node
(insert comp node
(.key high-e) (.val high-e)
(Box. false))))))
(defn ^:private seq-push [^IAVLNode node stack ascending?]
(loop [node node stack stack]
(if (nil? node)
stack
(recur (if ascending? (.getLeft node) (.getRight node))
(conj stack node)))))
(defn ^:private avl-map-kv-reduce [^IAVLNode node f init]
(let [init (if (nil? (.getLeft node))
init
(avl-map-kv-reduce (.getLeft node) f init))]
(if (reduced? init)
init
(let [init (f init (.getKey node) (.getVal node))]
(if (reduced? init)
init
(if (nil? (.getRight node))
init
(recur (.getRight node) f init)))))))
(deftype AVLMapSeq [^IPersistentMap _meta
^IPersistentStack stack
^boolean ascending?
^int cnt
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
:no-print true
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-seq _hash))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-seq _hasheq))
clojure.lang.Seqable
(seq [this]
this)
clojure.lang.Sequential
clojure.lang.ISeq
(first [this]
(peek stack)
#_
(let [node ^IAVLNode (peek stack)]
(MapEntry. (.getKey node) (.getVal node))))
(more [this]
(let [node ^IAVLNode (first stack)
next-stack (seq-push (if ascending? (.getRight node) (.getLeft node))
(next stack)
ascending?)]
(if (nil? next-stack)
()
(AVLMapSeq. nil next-stack ascending? (unchecked-dec-int cnt) -1 -1))))
(next [this]
(.seq (.more this)))
clojure.lang.Counted
(count [this]
(if (neg? cnt)
(unchecked-inc-int (count (next this)))
cnt))
clojure.lang.IPersistentCollection
(cons [this x]
(cons x this))
(equiv [this that]
(equiv-sequential this that))
(empty [this]
(with-meta () _meta))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMapSeq. meta stack ascending? cnt _hash _hasheq))
java.io.Serializable
java.util.List
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this arr]
(RT/seqToPassedArray (seq this) arr))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? cnt))
(contains [this x]
(or (some #(Util/equiv % x) this) false))
(iterator [this]
(SeqIterator. this))
(subList [this from to]
(.subList (Collections/unmodifiableList (ArrayList. this)) from to))
(indexOf [this x]
(loop [i (int 0) s (seq this)]
(if s
(if (Util/equiv (first s) x)
i
(recur (unchecked-inc-int i) (next s)))
(int -1))))
(lastIndexOf [this x]
(.lastIndexOf (ArrayList. this) x))
(listIterator [this]
(.listIterator (Collections/unmodifiableList (ArrayList. this))))
(listIterator [this i]
(.listIterator (Collections/unmodifiableList (ArrayList. this)) i))
(get [this i]
(RT/nth this i))
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private create-seq [node ascending? cnt]
(AVLMapSeq. nil (seq-push node nil ascending?) ascending? cnt -1 -1))
(declare ->AVLTransientMap)
(deftype AVLMap [^Comparator comp
^IAVLNode tree
^int cnt
^IPersistentMap _meta
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-imap _hash))
(equals [this that]
(APersistentMap/mapEquals this that))
IAVLTree
(getTree [this]
tree)
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest comp tree test k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-imap _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMap. comp tree cnt meta _hash _hasheq))
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.Indexed
(nth [this i]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
not-found))
clojure.lang.IPersistentCollection
(cons [this entry]
(if (vector? entry)
(assoc this (nth entry 0) (nth entry 1))
(reduce conj this entry)))
(empty [this]
(AVLMap. comp nil 0 _meta empty-map-hashcode empty-map-hasheq))
(equiv [this that]
(equiv-map this that))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(if (pos? cnt)
(create-seq tree true cnt)))
clojure.lang.Reversible
(rseq [this]
(if (pos? cnt)
(create-seq tree false cnt)))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.Associative
(assoc [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(AVLMap. comp
new-tree
(if (.-val found?) cnt (unchecked-inc-int cnt))
_meta -1 -1)))
(containsKey [this k]
(not (nil? (.entryAt this k))))
(entryAt [this k]
(if-let [node (lookup comp tree k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.MapEquivalence
clojure.lang.IPersistentMap
(without [this k]
(let [found? (Box. false)
new-tree (delete comp tree k found?)]
(if (.-val found?)
(AVLMap. comp
new-tree
(unchecked-dec-int cnt)
_meta -1 -1)
this)))
(assocEx [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(if (.-val found?)
(throw (ex-info "key already present" {}))
(AVLMap. comp
new-tree
(unchecked-inc-int cnt)
_meta -1 -1))))
clojure.lang.Sorted
(seq [this ascending?]
(if (pos? cnt)
(create-seq tree ascending? cnt)))
(seqFrom [this k ascending?]
(if (pos? cnt)
(loop [stack nil t tree]
(if-not (nil? t)
(let [c (.compare comp k (.getKey t))]
(cond
(zero? c) (AVLMapSeq. nil (conj stack t) ascending? -1 -1 -1)
ascending? (if (neg? c)
(recur (conj stack t) (.getLeft t))
(recur stack (.getRight t)))
:else (if (pos? c)
(recur (conj stack t) (.getRight t))
(recur stack (.getLeft t)))))
(if-not (nil? stack)
(AVLMapSeq. nil stack ascending? -1 -1 -1))))))
(entryKey [this entry]
(key entry))
(comparator [this]
comp)
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientMap
(AtomicReference. (Thread/currentThread)) comp tree cnt))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if (nil? tree)
init
(let [init (avl-map-kv-reduce tree f init)]
(if (reduced? init)
@init
init))))
java.io.Serializable
Iterable
(iterator [this]
(SeqIterator. (seq this)))
java.util.Map
(get [this k]
(.valAt this k))
(clear [this]
(throw-unsupported))
(containsValue [this v]
(.. this values (contains v)))
(entrySet [this]
(set (seq this)))
(put [this k v]
(throw-unsupported))
(putAll [this m]
(throw-unsupported))
(remove [this k]
(throw-unsupported))
(size [this]
cnt)
(values [this]
(vals this)))
(deftype AVLTransientMap [^AtomicReference edit
^Comparator comp
^:unsynchronized-mutable ^IAVLNode tree
^:unsynchronized-mutable ^int cnt]
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.ITransientCollection
(conj [this entry]
(ensure-editable edit)
(if (vector? entry)
(assoc! this (nth entry 0) (nth entry 1))
(reduce conj! this entry)))
(persistent [this]
(ensure-editable edit)
(.set edit nil)
(AVLMap. comp tree cnt nil -1 -1))
clojure.lang.ITransientAssociative
(assoc [this k v]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (insert! edit comp tree k v found?)]
(set! tree new-tree)
(if-not (.-val found?)
(set! cnt (unchecked-inc-int cnt)))
this))
clojure.lang.ITransientMap
(without [this k]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (delete! edit comp tree k found?)]
(when (.-val found?)
(set! tree new-tree)
(set! cnt (unchecked-dec-int cnt)))
this)))
(declare ->AVLTransientSet)
(deftype AVLSet [^IPersistentMap _meta
^AVLMap avl-map
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-iset _hash))
(equals [this that]
(APersistentSet/setEquals this that))
IAVLTree
(getTree [this]
(.getTree avl-map))
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest (.comparator avl-map)
(.getTree avl-map)
test
k)]
(.getKey node)))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-iset _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLSet. meta avl-map _hash _hasheq))
clojure.lang.Counted
(count [this]
(count avl-map))
clojure.lang.Indexed
(nth [this i]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
not-found))
clojure.lang.IPersistentCollection
(cons [this x]
(AVLSet. _meta (assoc avl-map x x) -1 -1))
(empty [this]
(AVLSet. _meta (empty avl-map) empty-set-hashcode empty-set-hasheq))
(equiv [this that]
(and
(set? that)
(== (count this) (count that))
(every? #(contains? this %) that)))
clojure.lang.Seqable
(seq [this]
(keys avl-map))
clojure.lang.Sorted
(seq [this ascending?]
(RT/keys (.seq avl-map ascending?)))
(seqFrom [this k ascending?]
(RT/keys (.seqFrom avl-map k ascending?)))
(entryKey [this entry]
entry)
(comparator [this]
(.comparator avl-map))
clojure.lang.Reversible
(rseq [this]
(map key (rseq avl-map)))
clojure.lang.ILookup
(valAt [this v]
(.valAt this v nil))
(valAt [this v not-found]
(let [n (.entryAt avl-map v)]
(if-not (nil? n)
(.getKey n)
not-found)))
clojure.lang.IPersistentSet
(disjoin [this v]
(AVLSet. _meta (dissoc avl-map v) -1 -1))
(contains [this k]
(contains? avl-map k))
(get [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientSet (.asTransient avl-map)))
java.io.Serializable
java.util.Set
(add [this o] (throw-unsupported))
(remove [this o] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? (count this)))
(iterator [this]
(SeqIterator. (seq this)))
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this a]
(RT/seqToPassedArray (seq this) a)))
(deftype AVLTransientSet
[^:unsynchronized-mutable ^AVLTransientMap transient-avl-map]
clojure.lang.ITransientCollection
(conj [this k]
(set! transient-avl-map (.assoc transient-avl-map k k))
this)
(persistent [this]
(AVLSet. nil (.persistent transient-avl-map) -1 -1))
clojure.lang.ITransientSet
(disjoin [this k]
(set! transient-avl-map (.without transient-avl-map k))
this)
(contains [this k]
(not (identical? this (.valAt transient-avl-map k this))))
(get [this k]
(.valAt transient-avl-map k))
clojure.lang.IFn
(invoke [this k]
(.valAt transient-avl-map k))
(invoke [this k not-found]
(.valAt transient-avl-map k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Counted
(count [this]
(.count transient-avl-map)))
(def ^:private empty-map
(AVLMap. RT/DEFAULT_COMPARATOR nil 0 nil
empty-map-hashcode empty-map-hasheq))
(def ^:private empty-set
(AVLSet. nil empty-map empty-set-hashcode empty-set-hasheq))
(doseq [v [#'->AVLMapSeq
#'->AVLNode
#'->AVLMap
#'->AVLSet
#'->AVLTransientMap
#'->AVLTransientSet]]
(alter-meta! v assoc :private true))
(defn sorted-map
"keyval => key val
Returns a new AVL map with supplied mappings."
{:added "0.0.1"}
[& keyvals]
(loop [in (seq keyvals) out (transient empty-map)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator."
{:added "0.0.1"}
[^Comparator comparator & keyvals]
(loop [in (seq keyvals)
out (AVLTransientMap.
(AtomicReference. (Thread/currentThread)) comparator nil 0)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map-by: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-set
"Returns a new sorted set with supplied keys."
{:added "0.0.1"}
[& keys]
(persistent! (reduce conj! (transient empty-set) keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
{:added "0.0.1"}
[^Comparator comparator & keys]
(persistent!
(reduce conj!
(AVLTransientSet. (transient (sorted-map-by comparator)))
keys)))
(defn rank-of
"Returns the rank of x in coll or -1 if not present."
{:added "0.0.6"}
^long [coll x]
(rank (.comparator ^clojure.lang.Sorted coll) (.getTree ^IAVLTree coll) x))
(defn nearest
"(alpha)
Equivalent to, but more efficient than, (first (subseq* coll test x)),
where subseq* is clojure.core/subseq for test in #{>, >=} and
clojure.core/rsubseq for test in #{<, <=}."
{:added "0.0.12"}
[coll test x]
(.nearest ^INavigableTree coll test x))
(defn split-key
"(alpha)
Returns [left e? right], where left and right are collections of
the same type as coll and containing, respectively, the keys below
and above k in the ordering determined by coll's comparator, while
e? is the entry at key k for maps, the stored copy of the key k for
sets, nil if coll does not contain k."
{:added "0.0.12"}
[k coll]
(let [comp (.comparator ^clojure.lang.Sorted coll)
[left e? right] (split comp (.getTree ^IAVLTree coll) k)
keyfn (if (map? coll) key identity)
wrap (if (map? coll)
(fn wrap-map [tree cnt]
(AVLMap. comp tree cnt nil -1 -1))
(fn wrap-set [tree cnt]
(AVLSet. nil (AVLMap. comp tree cnt nil -1 -1) -1 -1)))]
[(wrap left
(if (or e? right)
(rank-of coll (keyfn (nearest coll >= k)))
(count coll)))
(if (and e? (set? coll))
(.getKey ^MapEntry e?)
e?)
(wrap right
(if right
(- (count coll) (rank-of coll (keyfn (nearest coll > k))))
0))]))
(defn split-at
"(alpha)
Equivalent to, but more efficient than,
[(into (empty coll) (take n coll))
(into (empty coll) (drop n coll))]."
{:added "0.0.12"}
[^long n coll]
(if (>= n (count coll))
[coll (empty coll)]
(let [k (nth coll n)
k (if (map? coll) (key k) k)
[l e r] (split-key k coll)]
[l (conj r e)])))
(defn subrange
"(alpha)
Returns an AVL collection comprising the entries of coll between
start and end (in the sense determined by coll's comparator) in
logarithmic time. Whether the endpoints are themselves included in
the returned collection depends on the provided tests; start-test
must be either > or >=, end-test must be either < or <=.
When passed a single test and limit, subrange infers the other end
of the range from the test: > / >= mean to include items up to the
end of coll, < / <= mean to include items taken from the beginning
of coll.
(subrange >= start <= end) is equivalent to, but more efficient
than, (into (empty coll) (subseq coll >= start <= end)."
{:added "0.0.12"}
([coll test limit]
(cond
(zero? (count coll))
coll
(#{> >=} test)
(let [n (select (.getTree ^IAVLTree coll)
(dec (count coll)))]
(subrange coll
test limit
<= (.getKey ^IAVLNode n)))
:else
(let [n (select (.getTree ^IAVLTree coll) 0)]
(subrange coll
>= (.getKey ^IAVLNode n)
test limit))))
([coll start-test start end-test end]
(if (zero? (count coll))
coll
(let [comp (.comparator ^clojure.lang.Sorted coll)]
(if (pos? (.compare comp start end))
(throw
(IndexOutOfBoundsException. "start greater than end in subrange"))
(let [keyfn (if (map? coll) key identity)
l (nearest coll start-test start)
h (nearest coll end-test end)]
(if (and l h)
(let [tree (range comp (.getTree ^IAVLTree coll)
(keyfn l)
(keyfn h))
cnt (inc (- (rank-of coll (keyfn h))
(rank-of coll (keyfn l))))
m (AVLMap. comp tree cnt nil -1 -1)]
(if (map? coll)
m
(AVLSet. nil m -1 -1)))
(empty coll))))))))
| true | (ns fabric.avl
"An implementation of persistent sorted maps and sets based on AVL
trees which can be used as drop-in replacements for Clojure's
built-in sorted maps and sets based on red-black trees. Apart from
the standard sorted collection API, the provided map and set types
support the transients API and several additional logarithmic time
operations: rank queries via clojure.core/nth (select element by
rank) and clojure.data.avl/rank-of (discover rank of element),
\"nearest key\" lookups via clojure.data.avl/nearest, splits by key
and index via clojure.data.avl/split-key and
clojure.data.avl/split-at, respectively, and subsets/submaps using
clojure.data.avl/subrange."
{:author "PI:NAME:<NAME>END_PI"}
(:refer-clojure :exclude [sorted-map sorted-map-by sorted-set sorted-set-by
range split-at])
(:import (clojure.lang RT Util APersistentMap APersistentSet
IPersistentMap IPersistentSet IPersistentStack
Box MapEntry SeqIterator)
(java.util Comparator Collections ArrayList)
(java.util.concurrent.atomic AtomicReference)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn ^:private throw-unsupported []
(throw (UnsupportedOperationException.)))
(defmacro ^:private caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (== h# (int -1))
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key (int h#))
h#))))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
(def ^:private ^:const empty-set-hashcode (.hashCode #{}))
(def ^:private ^:const empty-set-hasheq (hash #{}))
(def ^:private ^:const empty-map-hashcode (.hashCode {}))
(def ^:private ^:const empty-map-hasheq (hash {}))
(defn ^:private hash-imap
[^IPersistentMap m]
(APersistentMap/mapHash m))
(defn ^:private hasheq-imap
[^IPersistentMap m]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll m)
(APersistentMap/mapHasheq m)))
(defn ^:private hash-iset [^IPersistentSet s]
;; a la clojure.lang.APersistentSet
(loop [h (int 0) s (seq s)]
(if s
(let [e (first s)]
(recur (unchecked-add-int h (if (nil? e) 0 (.hashCode ^Object e)))
(next s)))
h)))
(defn ^:private hasheq-iset [^IPersistentSet s]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll s)
(loop [h (int 0) s (seq s)]
(if s
(recur (unchecked-add-int h (Util/hasheq (first s)))
(next s))
h))))
(defn ^:private hash-seq
[s]
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(if (nil? (first s))
(int 0)
(.hashCode ^Object (first s))))
(next s))
h)))
(defn ^:private hasheq-seq
[s]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll s)
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(Util/hasheq (first s)))
(next s))
h))))
(defn ^:private equiv-sequential
"Assumes x is sequential. Returns true if x equals y, otherwise
returns false."
[x y]
(boolean
(when (sequential? y)
(loop [xs (seq x) ys (seq y)]
(cond (nil? xs) (nil? ys)
(nil? ys) false
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))))
(def ^:private never-equiv (Object.))
(defn ^:private equiv-map
"Assumes x is a map. Returns true if y equals x, otherwise returns
false."
[^clojure.lang.IPersistentMap x y]
(if-not (instance? java.util.Map y)
false
(if (and (instance? clojure.lang.IPersistentMap y)
(not (instance? clojure.lang.MapEquivalence y)))
false
(let [m ^java.util.Map y]
(if-not (== (.size ^java.util.Map x) (.size m))
false
(reduce-kv (fn [t k v]
(if-not (.containsKey m k)
(reduced false)
(if-not (Util/equiv v (.get m k))
(reduced false)
t)))
true
x))))))
(gen-interface
:name clojure.data.avl.IAVLNode
:methods
[[getKey [] Object]
[setKey [Object] clojure.data.avl.IAVLNode]
[getVal [] Object]
[setVal [Object] clojure.data.avl.IAVLNode]
[getLeft [] clojure.data.avl.IAVLNode]
[setLeft [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getRight [] clojure.data.avl.IAVLNode]
[setRight [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getHeight [] int]
[setHeight [int] clojure.data.avl.IAVLNode]
[getRank [] int]
[setRank [int] clojure.data.avl.IAVLNode]])
(gen-interface
:name clojure.data.avl.IAVLTree
:methods [[getTree [] clojure.data.avl.IAVLNode]])
(import (clojure.data.avl IAVLNode IAVLTree))
(definterface INavigableTree
(nearest [test k]))
(deftype AVLNode [^AtomicReference edit
^:unsynchronized-mutable key
^:unsynchronized-mutable val
^:unsynchronized-mutable ^IAVLNode left
^:unsynchronized-mutable ^IAVLNode right
^:unsynchronized-mutable ^int height
^:unsynchronized-mutable ^int rank]
IAVLNode
(getKey [this]
key)
(setKey [this k]
(set! key k)
this)
(getVal [this]
val)
(setVal [this v]
(set! val v)
this)
(getLeft [this]
left)
(setLeft [this l]
(set! left l)
this)
(getRight [this]
right)
(setRight [this r]
(set! right r)
this)
(getHeight [this]
height)
(setHeight [this h]
(set! height h)
this)
(getRank [this]
rank)
(setRank [this r]
(set! rank r)
this)
Object
(equals [this that]
(cond
(identical? this that) true
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(.equals key (nth that 0))
(.equals val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(.equals key (first that))
(.equals val (second that)))
:else false))
(hashCode [this]
(-> (int 31)
(unchecked-add-int (Util/hash key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hash val))))
(toString [this]
(pr-str this))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll this)
(-> (int 31)
(unchecked-add-int (Util/hasheq key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hasheq val)))))
clojure.lang.Indexed
(nth [this n]
(case n
0 key
1 val
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVLNode"))))
(nth [this n not-found]
(case n
0 key
1 val
not-found))
clojure.lang.Counted
(count [this]
2)
clojure.lang.IMeta
(meta [this]
nil)
clojure.lang.IObj
(withMeta [this m]
(with-meta [key val] m))
clojure.lang.IPersistentCollection
(cons [this x]
[key val x])
(empty [this]
[])
(equiv [this that]
(cond
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(= key (nth that 0))
(= val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(= key (first that))
(= val (second that)))
:else false))
clojure.lang.IPersistentStack
(peek [this]
val)
(pop [this]
[key])
clojure.lang.IPersistentVector
(assocN [this i x]
(case i
0 [x val]
1 [key x]
(throw
(IndexOutOfBoundsException. "assocN index out of bounds in AVLNode"))))
(length [this]
2)
clojure.lang.Reversible
(rseq [this]
(list val key))
clojure.lang.Associative
(assoc [this k v]
(if (Util/isInteger k)
(.assocN this k v)
(throw (IllegalArgumentException. "key must be integer"))))
(containsKey [this k]
(if (Util/isInteger k)
(case (int k)
0 true
1 true
false)
false))
(entryAt [this k]
(if (Util/isInteger k)
(case (int k)
0 (MapEntry. 0 key)
1 (MapEntry. 1 val)
nil)))
clojure.lang.ILookup
(valAt [this k not-found]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
not-found)
not-found))
(valAt [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
(throw
(IndexOutOfBoundsException.
"invoke index out of bounds in AVLNode")))
(throw (IllegalArgumentException. "key must be integer"))))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(list key val))
clojure.lang.Sequential
clojure.lang.IEditableCollection
(asTransient [this]
(transient [key val]))
clojure.lang.IMapEntry
(key [this]
key)
(val [this]
val)
java.util.Map$Entry
(getValue [this]
val)
(setValue [this x]
(throw-unsupported))
java.io.Serializable
java.lang.Comparable
(compareTo [this that]
(if (identical? this that)
0
(let [^clojure.lang.IPersistentVector v
(cast clojure.lang.IPersistentVector that)
vcnt (.count v)]
(cond
(< 2 vcnt) -1
(> 2 vcnt) 1
:else
(let [comp (Util/compare key (.nth v 0))]
(if (zero? comp)
(Util/compare val (.nth v 1))
comp))))))
java.lang.Iterable
(iterator [this]
(.iterator ^java.lang.Iterable (list key val)))
java.util.RandomAccess
java.util.List
(get [this i]
(.nth this i))
(indexOf [this x]
(condp = x
key 0
val 1
-1))
(lastIndexOf [this x]
(condp = x
val 1
key 0
-1))
(listIterator [this]
(.listIterator this 0))
(listIterator [this i]
(.listIterator (doto (java.util.ArrayList.)
(.add key)
(.add val))
i))
(subList [this a z]
(if (<= 0 a z 2)
(cond
(== a z) []
(and (== a 0) (== z 2)) this
:else (case a
0 [key]
1 [val]))
(throw
(IndexOutOfBoundsException. "subList index out of bounds in AVLNode"))))
java.util.Collection
(contains [this x]
(or (= key x) (= val x)))
(containsAll [this c]
(every? #(.contains this %) c))
(isEmpty [this]
false)
(toArray [this]
(into-array Object this))
(toArray [this arr]
(if (>= (count arr) 2)
(doto arr
(aset 0 key)
(aset 1 val))
(into-array Object this)))
(size [this]
2)
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private ensure-editable
(^IAVLNode [^AtomicReference edit]
(let [owner (.get edit)]
(cond
(identical? owner (Thread/currentThread))
true
(nil? owner)
(throw (IllegalAccessError. "Transient used after persistent! call"))
:else
(throw (IllegalAccessError. "Transient used by non-owner thread")))))
(^IAVLNode [^AtomicReference edit ^AVLNode node]
(if (identical? edit (.-edit node))
node
(AVLNode. edit
(.getKey node) (.getVal node)
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))))
(defn ^:private height ^long [^IAVLNode node]
(if (nil? node)
0
(long (.getHeight node))))
(defn ^:private rotate-left ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(AVLNode. nil
(.getKey r) (.getVal r)
(AVLNode. nil
(.getKey node) (.getVal node)
l
rl
(inc (max lh rlh))
rnk)
rr
(max (+ lh 2)
(+ rlh 2)
(inc rrh))
(inc (+ rnk rnkr)))))
(defn ^:private rotate-left! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
l (.getLeft node)
r (ensure-editable edit (.getRight node))
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(.setLeft r node)
(.setHeight r (max (+ lh 2) (+ rlh 2) (inc rrh)))
(.setRank r (inc (+ rnk rnkr)))
(.setRight node rl)
(.setHeight node (inc (max lh rlh)))
r))
(defn ^:private rotate-right ^IAVLNode [^IAVLNode node]
(let [r (.getRight node)
l (.getLeft node)
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(AVLNode. nil
(.getKey l) (.getVal l)
ll
(AVLNode. nil
(.getKey node) (.getVal node)
lr
r
(inc (max rh lrh))
(dec (- rnk rnkl)))
(max (+ rh 2)
(+ lrh 2)
(inc llh))
rnkl)))
(defn ^:private rotate-right! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
r (.getRight node)
l (ensure-editable edit (.getLeft node))
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(.setRight l node)
(.setHeight l (max (+ rh 2) (+ lrh 2) (inc llh)))
(.setLeft node lr)
(.setHeight node (inc (max rh lrh)))
(.setRank node (dec (- rnk rnkl)))
l))
(defn ^:private lookup ^IAVLNode [^Comparator comp ^IAVLNode node k]
(if (nil? node)
nil
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) node
(neg? c) (recur comp (.getLeft node) k)
:else (recur comp (.getRight node) k)))))
(defn ^:private lookup-nearest
^IAVLNode [^Comparator comp ^IAVLNode node test k]
(let [below? (or (identical? < test) (identical? <= test))
equal? (or (identical? <= test) (identical? >= test))
back? (if below? neg? pos?)
backward (if below?
#(.getLeft ^IAVLNode %)
#(.getRight ^IAVLNode %))
forward (if below?
#(.getRight ^IAVLNode %)
#(.getLeft ^IAVLNode %))]
(loop [prev nil
node node]
(if (nil? node)
prev
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (if equal?
node
(recur prev (backward node)))
(back? c) (recur prev (backward node))
:else (recur node (forward node))))))))
(defn ^:private select [^IAVLNode node ^long rank]
(if (nil? node)
nil
(let [node-rank (.getRank node)]
(cond
(== node-rank rank) node
(< node-rank rank) (recur (.getRight node) (dec (- rank node-rank)))
:else (recur (.getLeft node) rank)))))
(defn ^:private rank ^long [^Comparator comp ^IAVLNode node k]
(if (nil? node)
-1
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (.getRank node)
(neg? c) (recur comp (.getLeft node) k)
:else (let [r (rank comp (.getRight node) k)]
(if (== -1 r)
-1
(inc (+ (.getRank node) r))))))))
(defn ^:private maybe-rebalance ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right r)]
(rotate-left (AVLNode. nil
(.getKey node) (.getVal node)
(.getLeft node)
new-right
(inc (max lh (height new-right)))
(.getRank node))))
(rotate-left node)))
;; left-heavy
(> b 1)
(let [ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left l)]
(rotate-right (AVLNode. nil
(.getKey node) (.getVal node)
new-left
(.getRight node)
(inc (max rh (height new-left)))
(.getRank node))))
(rotate-right node)))
:else
node)))
(defn ^:private maybe-rebalance! ^IAVLNode [edit ^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [node (ensure-editable edit node)
rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right! edit r)]
(.setRight node new-right)
(.setHeight node (inc (max lh (height new-right))))
(rotate-left! edit node))
(rotate-left! edit node)))
;; left-heavy
(> b 1)
(let [node (ensure-editable edit node)
ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left! edit l)]
(.setLeft node new-left)
(.setHeight node (inc (max rh (height new-left))))
(rotate-right! edit node))
(rotate-right! edit node)))
:else
node)))
(defn ^:private insert
^IAVLNode [^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. nil k v nil nil 1 0)
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(AVLNode. nil
k v
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))
(neg? c)
(let [new-child (insert comp (.getLeft node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (.getHeight new-child)
(height (.getRight node))))
(if (.-val found?)
(.getRank node)
(unchecked-inc-int (.getRank node))))))
:else
(let [new-child (insert comp (.getRight node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (.getHeight new-child)
(height (.getLeft node))))
(.getRank node))))))))
(defn ^:private insert!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. edit k v nil nil 1 0)
(let [node (ensure-editable edit node)
nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(.setKey node k)
(.setVal node v)
node)
(neg? c)
(let [new-child (insert! edit comp (.getLeft node) k v found?)]
(.setLeft node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getRight node)))))
(if-not (.-val found?)
(.setRank node (unchecked-inc-int (.getRank node))))
(maybe-rebalance! edit node))
:else
(let [new-child (insert! edit comp (.getRight node) k v found?)]
(.setRight node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))
(defn ^:private get-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(recur r)
node))
(defn ^:private delete-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(let [l (.getLeft node)
new-right (delete-rightmost r)]
(AVLNode. nil
(.getKey node) (.getVal node)
l
new-right
(inc (max (height l) (height new-right)))
(.getRank node)))
(.getLeft node)))
(defn ^:private delete-rightmost! ^IAVLNode [edit ^IAVLNode node]
(if-not (nil? node)
(let [node (ensure-editable edit node)
r ^IAVLNode (.getRight node)]
(cond
(nil? r)
(if-let [l (.getLeft node)]
(ensure-editable edit l))
(nil? (.getRight r))
(do
(.setRight node (.getLeft r))
(.setHeight node
(inc (max (height (.getLeft node))
(height (.getLeft r)))))
node)
:else
(let [new-right (delete-rightmost! edit r)]
(.setRight node new-right)
(.setHeight node
(inc (max (height (.getLeft node))
(height new-right))))
node)))))
(defn ^:private delete
^IAVLNode [^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(if (and l r)
(let [p (get-rightmost l)
l' (delete-rightmost l)]
(AVLNode. nil
(.getKey p) (.getVal p)
l'
r
(inc (max (height l') (height r)))
(unchecked-dec-int (.getRank node))))
(or l r)))
(neg? c)
(let [new-child (delete comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (height new-child)
(height (.getRight node))))
(if (.-val found?)
(unchecked-dec-int (.getRank node))
(.getRank node))))))
:else
(let [new-child (delete comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (height new-child)
(height (.getLeft node))))
(.getRank node)))))))))
(defn ^:private delete!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(cond
(and l r)
(let [node (ensure-editable edit node)
p (get-rightmost l)
l' (delete-rightmost! edit l)]
(.setKey node (.getKey p))
(.setVal node (.getVal p))
(.setLeft node l')
(.setHeight node (inc (max (height l') (height r))))
(.setRank node (unchecked-dec-int (.getRank node)))
node)
l l
r r
:else nil))
(neg? c)
(let [new-child (delete! edit comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(let [node (ensure-editable edit node)]
(.setLeft node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getRight node)))))
(if (.-val found?)
(.setRank node (unchecked-dec-int (.getRank node))))
(maybe-rebalance! edit node))))
:else
(let [new-child (delete! edit comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(let [node (ensure-editable edit node)]
(.setRight node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))))
(defn ^:private join
[^Comparator comp ^long left-count ^IAVLNode left ^IAVLNode right]
(cond
(nil? left) right
(nil? right) left
:else
(let [lh (.getHeight left)
rh (.getHeight right)]
(cond
(== lh rh)
(let [left-min (get-rightmost left)
new-left (delete comp left (.getKey left-min) (Box. false))]
(AVLNode. nil
(.getKey left-min) (.getVal left-min)
new-left
right
(unchecked-inc-int rh)
(unchecked-dec-int left-count)))
(< lh rh)
(letfn [(step [^IAVLNode current ^long lvl]
(cond
(zero? lvl)
(join comp left-count left current)
(nil? (.getLeft current))
(AVLNode. nil
(.getKey current) (.getVal current)
left
(.getRight current)
2
left-count)
:else
(let [new-child (step (.getLeft current) (dec lvl))
current-r (.getRight current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
new-child
current-r
(inc (max (.getHeight ^IAVLNode new-child)
(height current-r)
#_
(if current-r
(.getHeight current-r)
0)))
(+ left-count (.getRank current)))))))]
(step right (- rh lh)))
:else
(letfn [(step [^IAVLNode current ^long cnt ^long lvl]
(cond
(zero? lvl)
(join comp cnt current right)
(nil? (.getRight current))
(AVLNode. nil
(.getKey current) (.getVal current)
(.getLeft current)
right
2
(.getRank current))
:else
(let [new-child (step (.getRight current)
(dec (- cnt (.getRank current)))
(dec lvl))
current-l (.getLeft current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
current-l
new-child
(inc (max (.getHeight ^IAVLNode new-child)
(height current-l)
#_
(if current-l
(.getHeight current-l)
0)))
(.getRank current))))))]
(step left left-count (- lh rh)))))))
(defn ^:private split [^Comparator comp ^IAVLNode node k]
(letfn [(step [^IAVLNode node]
(if (nil? node)
[nil nil nil]
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c)
[(.getLeft node)
(MapEntry. (.getKey node) (.getVal node))
(.getRight node)]
(neg? c)
(let [[l e r] (step (.getLeft node))
r' (insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false))]
[l
e
(cond
e (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e))))
r
r')
r (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r)))))
r
r')
:else (join comp 0 r r'))
#_
(join comp
(- (.getRank node)
(cond
e
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e)))
r
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r))))
:else
(.getRank node)))
r
(insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false)))])
:else
(let [[l e r] (step (.getRight node))]
[(join comp
(unchecked-inc-int (.getRank node))
(insert comp
(.getLeft node)
(.getKey node)
(.getVal node)
(Box. false))
l)
e
r])))))]
(step node)))
(defn ^:private range ^IAVLNode [^Comparator comp ^IAVLNode node low high]
(let [[_ ^MapEntry low-e r] (split comp node low)
[l ^MapEntry high-e _] (split comp r high)]
(cond-> l
low-e (as-> node
(insert comp node
(.key low-e) (.val low-e)
(Box. false)))
high-e (as-> node
(insert comp node
(.key high-e) (.val high-e)
(Box. false))))))
(defn ^:private seq-push [^IAVLNode node stack ascending?]
(loop [node node stack stack]
(if (nil? node)
stack
(recur (if ascending? (.getLeft node) (.getRight node))
(conj stack node)))))
(defn ^:private avl-map-kv-reduce [^IAVLNode node f init]
(let [init (if (nil? (.getLeft node))
init
(avl-map-kv-reduce (.getLeft node) f init))]
(if (reduced? init)
init
(let [init (f init (.getKey node) (.getVal node))]
(if (reduced? init)
init
(if (nil? (.getRight node))
init
(recur (.getRight node) f init)))))))
(deftype AVLMapSeq [^IPersistentMap _meta
^IPersistentStack stack
^boolean ascending?
^int cnt
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
:no-print true
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-seq _hash))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-seq _hasheq))
clojure.lang.Seqable
(seq [this]
this)
clojure.lang.Sequential
clojure.lang.ISeq
(first [this]
(peek stack)
#_
(let [node ^IAVLNode (peek stack)]
(MapEntry. (.getKey node) (.getVal node))))
(more [this]
(let [node ^IAVLNode (first stack)
next-stack (seq-push (if ascending? (.getRight node) (.getLeft node))
(next stack)
ascending?)]
(if (nil? next-stack)
()
(AVLMapSeq. nil next-stack ascending? (unchecked-dec-int cnt) -1 -1))))
(next [this]
(.seq (.more this)))
clojure.lang.Counted
(count [this]
(if (neg? cnt)
(unchecked-inc-int (count (next this)))
cnt))
clojure.lang.IPersistentCollection
(cons [this x]
(cons x this))
(equiv [this that]
(equiv-sequential this that))
(empty [this]
(with-meta () _meta))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMapSeq. meta stack ascending? cnt _hash _hasheq))
java.io.Serializable
java.util.List
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this arr]
(RT/seqToPassedArray (seq this) arr))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? cnt))
(contains [this x]
(or (some #(Util/equiv % x) this) false))
(iterator [this]
(SeqIterator. this))
(subList [this from to]
(.subList (Collections/unmodifiableList (ArrayList. this)) from to))
(indexOf [this x]
(loop [i (int 0) s (seq this)]
(if s
(if (Util/equiv (first s) x)
i
(recur (unchecked-inc-int i) (next s)))
(int -1))))
(lastIndexOf [this x]
(.lastIndexOf (ArrayList. this) x))
(listIterator [this]
(.listIterator (Collections/unmodifiableList (ArrayList. this))))
(listIterator [this i]
(.listIterator (Collections/unmodifiableList (ArrayList. this)) i))
(get [this i]
(RT/nth this i))
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private create-seq [node ascending? cnt]
(AVLMapSeq. nil (seq-push node nil ascending?) ascending? cnt -1 -1))
(declare ->AVLTransientMap)
(deftype AVLMap [^Comparator comp
^IAVLNode tree
^int cnt
^IPersistentMap _meta
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-imap _hash))
(equals [this that]
(APersistentMap/mapEquals this that))
IAVLTree
(getTree [this]
tree)
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest comp tree test k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-imap _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMap. comp tree cnt meta _hash _hasheq))
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.Indexed
(nth [this i]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
not-found))
clojure.lang.IPersistentCollection
(cons [this entry]
(if (vector? entry)
(assoc this (nth entry 0) (nth entry 1))
(reduce conj this entry)))
(empty [this]
(AVLMap. comp nil 0 _meta empty-map-hashcode empty-map-hasheq))
(equiv [this that]
(equiv-map this that))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(if (pos? cnt)
(create-seq tree true cnt)))
clojure.lang.Reversible
(rseq [this]
(if (pos? cnt)
(create-seq tree false cnt)))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.Associative
(assoc [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(AVLMap. comp
new-tree
(if (.-val found?) cnt (unchecked-inc-int cnt))
_meta -1 -1)))
(containsKey [this k]
(not (nil? (.entryAt this k))))
(entryAt [this k]
(if-let [node (lookup comp tree k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.MapEquivalence
clojure.lang.IPersistentMap
(without [this k]
(let [found? (Box. false)
new-tree (delete comp tree k found?)]
(if (.-val found?)
(AVLMap. comp
new-tree
(unchecked-dec-int cnt)
_meta -1 -1)
this)))
(assocEx [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(if (.-val found?)
(throw (ex-info "key already present" {}))
(AVLMap. comp
new-tree
(unchecked-inc-int cnt)
_meta -1 -1))))
clojure.lang.Sorted
(seq [this ascending?]
(if (pos? cnt)
(create-seq tree ascending? cnt)))
(seqFrom [this k ascending?]
(if (pos? cnt)
(loop [stack nil t tree]
(if-not (nil? t)
(let [c (.compare comp k (.getKey t))]
(cond
(zero? c) (AVLMapSeq. nil (conj stack t) ascending? -1 -1 -1)
ascending? (if (neg? c)
(recur (conj stack t) (.getLeft t))
(recur stack (.getRight t)))
:else (if (pos? c)
(recur (conj stack t) (.getRight t))
(recur stack (.getLeft t)))))
(if-not (nil? stack)
(AVLMapSeq. nil stack ascending? -1 -1 -1))))))
(entryKey [this entry]
(key entry))
(comparator [this]
comp)
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientMap
(AtomicReference. (Thread/currentThread)) comp tree cnt))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if (nil? tree)
init
(let [init (avl-map-kv-reduce tree f init)]
(if (reduced? init)
@init
init))))
java.io.Serializable
Iterable
(iterator [this]
(SeqIterator. (seq this)))
java.util.Map
(get [this k]
(.valAt this k))
(clear [this]
(throw-unsupported))
(containsValue [this v]
(.. this values (contains v)))
(entrySet [this]
(set (seq this)))
(put [this k v]
(throw-unsupported))
(putAll [this m]
(throw-unsupported))
(remove [this k]
(throw-unsupported))
(size [this]
cnt)
(values [this]
(vals this)))
(deftype AVLTransientMap [^AtomicReference edit
^Comparator comp
^:unsynchronized-mutable ^IAVLNode tree
^:unsynchronized-mutable ^int cnt]
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.ITransientCollection
(conj [this entry]
(ensure-editable edit)
(if (vector? entry)
(assoc! this (nth entry 0) (nth entry 1))
(reduce conj! this entry)))
(persistent [this]
(ensure-editable edit)
(.set edit nil)
(AVLMap. comp tree cnt nil -1 -1))
clojure.lang.ITransientAssociative
(assoc [this k v]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (insert! edit comp tree k v found?)]
(set! tree new-tree)
(if-not (.-val found?)
(set! cnt (unchecked-inc-int cnt)))
this))
clojure.lang.ITransientMap
(without [this k]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (delete! edit comp tree k found?)]
(when (.-val found?)
(set! tree new-tree)
(set! cnt (unchecked-dec-int cnt)))
this)))
(declare ->AVLTransientSet)
(deftype AVLSet [^IPersistentMap _meta
^AVLMap avl-map
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-iset _hash))
(equals [this that]
(APersistentSet/setEquals this that))
IAVLTree
(getTree [this]
(.getTree avl-map))
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest (.comparator avl-map)
(.getTree avl-map)
test
k)]
(.getKey node)))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-iset _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLSet. meta avl-map _hash _hasheq))
clojure.lang.Counted
(count [this]
(count avl-map))
clojure.lang.Indexed
(nth [this i]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
not-found))
clojure.lang.IPersistentCollection
(cons [this x]
(AVLSet. _meta (assoc avl-map x x) -1 -1))
(empty [this]
(AVLSet. _meta (empty avl-map) empty-set-hashcode empty-set-hasheq))
(equiv [this that]
(and
(set? that)
(== (count this) (count that))
(every? #(contains? this %) that)))
clojure.lang.Seqable
(seq [this]
(keys avl-map))
clojure.lang.Sorted
(seq [this ascending?]
(RT/keys (.seq avl-map ascending?)))
(seqFrom [this k ascending?]
(RT/keys (.seqFrom avl-map k ascending?)))
(entryKey [this entry]
entry)
(comparator [this]
(.comparator avl-map))
clojure.lang.Reversible
(rseq [this]
(map key (rseq avl-map)))
clojure.lang.ILookup
(valAt [this v]
(.valAt this v nil))
(valAt [this v not-found]
(let [n (.entryAt avl-map v)]
(if-not (nil? n)
(.getKey n)
not-found)))
clojure.lang.IPersistentSet
(disjoin [this v]
(AVLSet. _meta (dissoc avl-map v) -1 -1))
(contains [this k]
(contains? avl-map k))
(get [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientSet (.asTransient avl-map)))
java.io.Serializable
java.util.Set
(add [this o] (throw-unsupported))
(remove [this o] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? (count this)))
(iterator [this]
(SeqIterator. (seq this)))
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this a]
(RT/seqToPassedArray (seq this) a)))
(deftype AVLTransientSet
[^:unsynchronized-mutable ^AVLTransientMap transient-avl-map]
clojure.lang.ITransientCollection
(conj [this k]
(set! transient-avl-map (.assoc transient-avl-map k k))
this)
(persistent [this]
(AVLSet. nil (.persistent transient-avl-map) -1 -1))
clojure.lang.ITransientSet
(disjoin [this k]
(set! transient-avl-map (.without transient-avl-map k))
this)
(contains [this k]
(not (identical? this (.valAt transient-avl-map k this))))
(get [this k]
(.valAt transient-avl-map k))
clojure.lang.IFn
(invoke [this k]
(.valAt transient-avl-map k))
(invoke [this k not-found]
(.valAt transient-avl-map k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Counted
(count [this]
(.count transient-avl-map)))
(def ^:private empty-map
(AVLMap. RT/DEFAULT_COMPARATOR nil 0 nil
empty-map-hashcode empty-map-hasheq))
(def ^:private empty-set
(AVLSet. nil empty-map empty-set-hashcode empty-set-hasheq))
(doseq [v [#'->AVLMapSeq
#'->AVLNode
#'->AVLMap
#'->AVLSet
#'->AVLTransientMap
#'->AVLTransientSet]]
(alter-meta! v assoc :private true))
(defn sorted-map
"keyval => key val
Returns a new AVL map with supplied mappings."
{:added "0.0.1"}
[& keyvals]
(loop [in (seq keyvals) out (transient empty-map)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator."
{:added "0.0.1"}
[^Comparator comparator & keyvals]
(loop [in (seq keyvals)
out (AVLTransientMap.
(AtomicReference. (Thread/currentThread)) comparator nil 0)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map-by: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-set
"Returns a new sorted set with supplied keys."
{:added "0.0.1"}
[& keys]
(persistent! (reduce conj! (transient empty-set) keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
{:added "0.0.1"}
[^Comparator comparator & keys]
(persistent!
(reduce conj!
(AVLTransientSet. (transient (sorted-map-by comparator)))
keys)))
(defn rank-of
"Returns the rank of x in coll or -1 if not present."
{:added "0.0.6"}
^long [coll x]
(rank (.comparator ^clojure.lang.Sorted coll) (.getTree ^IAVLTree coll) x))
(defn nearest
"(alpha)
Equivalent to, but more efficient than, (first (subseq* coll test x)),
where subseq* is clojure.core/subseq for test in #{>, >=} and
clojure.core/rsubseq for test in #{<, <=}."
{:added "0.0.12"}
[coll test x]
(.nearest ^INavigableTree coll test x))
(defn split-key
"(alpha)
Returns [left e? right], where left and right are collections of
the same type as coll and containing, respectively, the keys below
and above k in the ordering determined by coll's comparator, while
e? is the entry at key k for maps, the stored copy of the key k for
sets, nil if coll does not contain k."
{:added "0.0.12"}
[k coll]
(let [comp (.comparator ^clojure.lang.Sorted coll)
[left e? right] (split comp (.getTree ^IAVLTree coll) k)
keyfn (if (map? coll) key identity)
wrap (if (map? coll)
(fn wrap-map [tree cnt]
(AVLMap. comp tree cnt nil -1 -1))
(fn wrap-set [tree cnt]
(AVLSet. nil (AVLMap. comp tree cnt nil -1 -1) -1 -1)))]
[(wrap left
(if (or e? right)
(rank-of coll (keyfn (nearest coll >= k)))
(count coll)))
(if (and e? (set? coll))
(.getKey ^MapEntry e?)
e?)
(wrap right
(if right
(- (count coll) (rank-of coll (keyfn (nearest coll > k))))
0))]))
(defn split-at
"(alpha)
Equivalent to, but more efficient than,
[(into (empty coll) (take n coll))
(into (empty coll) (drop n coll))]."
{:added "0.0.12"}
[^long n coll]
(if (>= n (count coll))
[coll (empty coll)]
(let [k (nth coll n)
k (if (map? coll) (key k) k)
[l e r] (split-key k coll)]
[l (conj r e)])))
(defn subrange
"(alpha)
Returns an AVL collection comprising the entries of coll between
start and end (in the sense determined by coll's comparator) in
logarithmic time. Whether the endpoints are themselves included in
the returned collection depends on the provided tests; start-test
must be either > or >=, end-test must be either < or <=.
When passed a single test and limit, subrange infers the other end
of the range from the test: > / >= mean to include items up to the
end of coll, < / <= mean to include items taken from the beginning
of coll.
(subrange >= start <= end) is equivalent to, but more efficient
than, (into (empty coll) (subseq coll >= start <= end)."
{:added "0.0.12"}
([coll test limit]
(cond
(zero? (count coll))
coll
(#{> >=} test)
(let [n (select (.getTree ^IAVLTree coll)
(dec (count coll)))]
(subrange coll
test limit
<= (.getKey ^IAVLNode n)))
:else
(let [n (select (.getTree ^IAVLTree coll) 0)]
(subrange coll
>= (.getKey ^IAVLNode n)
test limit))))
([coll start-test start end-test end]
(if (zero? (count coll))
coll
(let [comp (.comparator ^clojure.lang.Sorted coll)]
(if (pos? (.compare comp start end))
(throw
(IndexOutOfBoundsException. "start greater than end in subrange"))
(let [keyfn (if (map? coll) key identity)
l (nearest coll start-test start)
h (nearest coll end-test end)]
(if (and l h)
(let [tree (range comp (.getTree ^IAVLTree coll)
(keyfn l)
(keyfn h))
cnt (inc (- (rank-of coll (keyfn h))
(rank-of coll (keyfn l))))
m (AVLMap. comp tree cnt nil -1 -1)]
(if (map? coll)
m
(AVLSet. nil m -1 -1)))
(empty coll))))))))
|
[
{
"context": "pi.net\n;; Full project source: https://github.com/samaaron/sonic-pi\n;; License: https://github.com/samaaron/",
"end": 110,
"score": 0.9993710517883301,
"start": 102,
"tag": "USERNAME",
"value": "samaaron"
},
{
"context": "/samaaron/sonic-pi\n;; License: https://github.com/samaaron/sonic-pi/blob/master/LICENSE.md\n;;\n;; Copyright 2",
"end": 159,
"score": 0.9994946122169495,
"start": 151,
"tag": "USERNAME",
"value": "samaaron"
},
{
"context": "ob/master/LICENSE.md\n;;\n;; Copyright 2013, 2014 by Sam Aaron (http://sam.aaron.name).\n;; All rights reserved.\n",
"end": 231,
"score": 0.9998933672904968,
"start": 222,
"tag": "NAME",
"value": "Sam Aaron"
}
] | app/gui/html/cljs/defpi/ws.cljs | jweather/sonic-pi | 1 | ;;--
;; This file is part of Sonic Pi: http://sonic-pi.net
;; Full project source: https://github.com/samaaron/sonic-pi
;; License: https://github.com/samaaron/sonic-pi/blob/master/LICENSE.md
;;
;; Copyright 2013, 2014 by Sam Aaron (http://sam.aaron.name).
;; All rights reserved.
;;
;; Permission is granted for use, copying, modification, distribution,
;; and distribution of modified versions of this work as long as this
;; notice is included.
;;++
(ns defpi.ws
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :as async :refer [>! <! put! chan]]
[clojure.string :as str]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[goog.events :as events]
[cljs.reader :as reader]
[defpi.ringbuffer :as rb]
[defpi.keyboard :as kb]))
(enable-console-print!)
(declare stop-job)
(def ws (atom nil))
(def err-cnt (atom 0))
(def app-state (atom {:messages (rb/mk-ringbuffer 100)
:jobs #{}}))
(defn jobs-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [j-id]
(dom/div #js{:className "animated rotateIn"
:onClick #(stop-job j-id)
:style #js{:float "right"
:height "35px"
:width "35px"
:color "white"
:font-size "15px"
;; :border-width "5px"
;; :border-style "solid"
;; :border-color "#5e5e5e"
:background "deeppink"}} j-id))
(:jobs data)))))
(defn message-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [m]
(dom/div nil (get m "val")
(when (get m "backtrace")
(dom/div nil
(dom/pre nil
(str/join "\n" (get m "backtrace")))))))
(:messages data)))))
(def hostname
(let [hn (.-host (.-location js/window))]
(if (= "" hn)
"localhost"
(re-find #"[^\:]+" hn))))
(defn show-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn show-multi-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn reply-sync
[msg res]
(when-let [id (:sync msg)]
(.send @ws {:cmd "sync"
:val id
:result (cond
(number? res) res
(keyword? res) res
:else (str res))})))
(defmulti handle-message #(get % "type"))
(defmethod handle-message "message"
[msg]
(show-msg msg))
(defmethod handle-message "multimessage"
[msgs]
(show-multi-msg msgs))
(defmethod handle-message "error"
[msg]
(show-msg msg))
(defmethod handle-message "debug_message"
[msg]
(println "debug=> " msg))
(defmethod handle-message "replace-buffer"
[msg]
(.setValue js/editor (get msg "val")))
(defmethod handle-message "job"
[msg]
(cond
(= "start" (get msg "action"))
(swap! app-state update-in [:jobs] conj (get msg "jobid"))
(= "completed" (get msg "action"))
(swap! app-state update-in [:jobs] disj (get msg "jobid" ))
:else
(js/alert (str "Unknown job action: " (:action msg)))
))
(defmethod handle-message js/Object
[m]
(js/console.log "can't handle: " (:type m)))
(defn replace-buffer [buf-id]
(.send @ws (JSON/stringify #js {:cmd "load-buffer"
:id (str buf-id)})))
(defn add-ws-handlers
[]
(set! (.-onopen @ws) (fn []
(om/root message-comp app-state {:target (.getElementById js/document "app-messages")})
(om/root jobs-comp app-state {:target (.getElementById js/document "app-jobs")})
(replace-buffer "main")))
(set! (.-onclose @ws) #(show-msg "Websocket Closed"))
(set! (.-onmessage @ws) (fn [m]
(let [msg (js->clj (JSON/parse (.-data m)))
res (handle-message msg)]
(reply-sync msg res))))
(events/listen js/document (kb/keyword->event-type :keypress)
(fn [e]
(let [code (.-charCode e)]
(cond
(= 18 code)
(.send @ws (JSON/stringify #js{"cmd" "save-and-run-buffer"
"val" (.getValue js/editor)
"buffer_id" "main"}))
(= 19 code)
(.send @ws (JSON/stringify #js{"cmd" "stop-jobs"
"val" (.getValue js/editor)}))))))
)
(defn ^:export sendCode
[]
(.send @ws (JSON/stringify #js {:cmd "save-and-run-buffer"
:val (.getValue js/editor)
:buffer_id "main"})))
(defn ^:export stopCode
[]
(.send @ws (JSON/stringify #js {:cmd "stop-jobs"
:val (.getValue js/editor)})))
(defn ^:export reloadCode
[]
(.send @ws (JSON/stringify #js {:cmd "reload"
:val (.getValue js/editor)})))
(defn stop-job [j-id]
(.send @ws (JSON/stringify #js {:cmd "stop-job"
:val j-id})))
(defn mk-ws []
(reset! ws (js/WebSocket. (str "ws://" hostname ":8001"))))
| 124463 | ;;--
;; This file is part of Sonic Pi: http://sonic-pi.net
;; Full project source: https://github.com/samaaron/sonic-pi
;; License: https://github.com/samaaron/sonic-pi/blob/master/LICENSE.md
;;
;; Copyright 2013, 2014 by <NAME> (http://sam.aaron.name).
;; All rights reserved.
;;
;; Permission is granted for use, copying, modification, distribution,
;; and distribution of modified versions of this work as long as this
;; notice is included.
;;++
(ns defpi.ws
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :as async :refer [>! <! put! chan]]
[clojure.string :as str]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[goog.events :as events]
[cljs.reader :as reader]
[defpi.ringbuffer :as rb]
[defpi.keyboard :as kb]))
(enable-console-print!)
(declare stop-job)
(def ws (atom nil))
(def err-cnt (atom 0))
(def app-state (atom {:messages (rb/mk-ringbuffer 100)
:jobs #{}}))
(defn jobs-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [j-id]
(dom/div #js{:className "animated rotateIn"
:onClick #(stop-job j-id)
:style #js{:float "right"
:height "35px"
:width "35px"
:color "white"
:font-size "15px"
;; :border-width "5px"
;; :border-style "solid"
;; :border-color "#5e5e5e"
:background "deeppink"}} j-id))
(:jobs data)))))
(defn message-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [m]
(dom/div nil (get m "val")
(when (get m "backtrace")
(dom/div nil
(dom/pre nil
(str/join "\n" (get m "backtrace")))))))
(:messages data)))))
(def hostname
(let [hn (.-host (.-location js/window))]
(if (= "" hn)
"localhost"
(re-find #"[^\:]+" hn))))
(defn show-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn show-multi-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn reply-sync
[msg res]
(when-let [id (:sync msg)]
(.send @ws {:cmd "sync"
:val id
:result (cond
(number? res) res
(keyword? res) res
:else (str res))})))
(defmulti handle-message #(get % "type"))
(defmethod handle-message "message"
[msg]
(show-msg msg))
(defmethod handle-message "multimessage"
[msgs]
(show-multi-msg msgs))
(defmethod handle-message "error"
[msg]
(show-msg msg))
(defmethod handle-message "debug_message"
[msg]
(println "debug=> " msg))
(defmethod handle-message "replace-buffer"
[msg]
(.setValue js/editor (get msg "val")))
(defmethod handle-message "job"
[msg]
(cond
(= "start" (get msg "action"))
(swap! app-state update-in [:jobs] conj (get msg "jobid"))
(= "completed" (get msg "action"))
(swap! app-state update-in [:jobs] disj (get msg "jobid" ))
:else
(js/alert (str "Unknown job action: " (:action msg)))
))
(defmethod handle-message js/Object
[m]
(js/console.log "can't handle: " (:type m)))
(defn replace-buffer [buf-id]
(.send @ws (JSON/stringify #js {:cmd "load-buffer"
:id (str buf-id)})))
(defn add-ws-handlers
[]
(set! (.-onopen @ws) (fn []
(om/root message-comp app-state {:target (.getElementById js/document "app-messages")})
(om/root jobs-comp app-state {:target (.getElementById js/document "app-jobs")})
(replace-buffer "main")))
(set! (.-onclose @ws) #(show-msg "Websocket Closed"))
(set! (.-onmessage @ws) (fn [m]
(let [msg (js->clj (JSON/parse (.-data m)))
res (handle-message msg)]
(reply-sync msg res))))
(events/listen js/document (kb/keyword->event-type :keypress)
(fn [e]
(let [code (.-charCode e)]
(cond
(= 18 code)
(.send @ws (JSON/stringify #js{"cmd" "save-and-run-buffer"
"val" (.getValue js/editor)
"buffer_id" "main"}))
(= 19 code)
(.send @ws (JSON/stringify #js{"cmd" "stop-jobs"
"val" (.getValue js/editor)}))))))
)
(defn ^:export sendCode
[]
(.send @ws (JSON/stringify #js {:cmd "save-and-run-buffer"
:val (.getValue js/editor)
:buffer_id "main"})))
(defn ^:export stopCode
[]
(.send @ws (JSON/stringify #js {:cmd "stop-jobs"
:val (.getValue js/editor)})))
(defn ^:export reloadCode
[]
(.send @ws (JSON/stringify #js {:cmd "reload"
:val (.getValue js/editor)})))
(defn stop-job [j-id]
(.send @ws (JSON/stringify #js {:cmd "stop-job"
:val j-id})))
(defn mk-ws []
(reset! ws (js/WebSocket. (str "ws://" hostname ":8001"))))
| true | ;;--
;; This file is part of Sonic Pi: http://sonic-pi.net
;; Full project source: https://github.com/samaaron/sonic-pi
;; License: https://github.com/samaaron/sonic-pi/blob/master/LICENSE.md
;;
;; Copyright 2013, 2014 by PI:NAME:<NAME>END_PI (http://sam.aaron.name).
;; All rights reserved.
;;
;; Permission is granted for use, copying, modification, distribution,
;; and distribution of modified versions of this work as long as this
;; notice is included.
;;++
(ns defpi.ws
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :as async :refer [>! <! put! chan]]
[clojure.string :as str]
[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[goog.events :as events]
[cljs.reader :as reader]
[defpi.ringbuffer :as rb]
[defpi.keyboard :as kb]))
(enable-console-print!)
(declare stop-job)
(def ws (atom nil))
(def err-cnt (atom 0))
(def app-state (atom {:messages (rb/mk-ringbuffer 100)
:jobs #{}}))
(defn jobs-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [j-id]
(dom/div #js{:className "animated rotateIn"
:onClick #(stop-job j-id)
:style #js{:float "right"
:height "35px"
:width "35px"
:color "white"
:font-size "15px"
;; :border-width "5px"
;; :border-style "solid"
;; :border-color "#5e5e5e"
:background "deeppink"}} j-id))
(:jobs data)))))
(defn message-comp [data owner]
(om/component
(apply dom/div nil
(map (fn [m]
(dom/div nil (get m "val")
(when (get m "backtrace")
(dom/div nil
(dom/pre nil
(str/join "\n" (get m "backtrace")))))))
(:messages data)))))
(def hostname
(let [hn (.-host (.-location js/window))]
(if (= "" hn)
"localhost"
(re-find #"[^\:]+" hn))))
(defn show-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn show-multi-msg
[msg]
(swap! app-state update-in [:messages] rb/add msg)
)
(defn reply-sync
[msg res]
(when-let [id (:sync msg)]
(.send @ws {:cmd "sync"
:val id
:result (cond
(number? res) res
(keyword? res) res
:else (str res))})))
(defmulti handle-message #(get % "type"))
(defmethod handle-message "message"
[msg]
(show-msg msg))
(defmethod handle-message "multimessage"
[msgs]
(show-multi-msg msgs))
(defmethod handle-message "error"
[msg]
(show-msg msg))
(defmethod handle-message "debug_message"
[msg]
(println "debug=> " msg))
(defmethod handle-message "replace-buffer"
[msg]
(.setValue js/editor (get msg "val")))
(defmethod handle-message "job"
[msg]
(cond
(= "start" (get msg "action"))
(swap! app-state update-in [:jobs] conj (get msg "jobid"))
(= "completed" (get msg "action"))
(swap! app-state update-in [:jobs] disj (get msg "jobid" ))
:else
(js/alert (str "Unknown job action: " (:action msg)))
))
(defmethod handle-message js/Object
[m]
(js/console.log "can't handle: " (:type m)))
(defn replace-buffer [buf-id]
(.send @ws (JSON/stringify #js {:cmd "load-buffer"
:id (str buf-id)})))
(defn add-ws-handlers
[]
(set! (.-onopen @ws) (fn []
(om/root message-comp app-state {:target (.getElementById js/document "app-messages")})
(om/root jobs-comp app-state {:target (.getElementById js/document "app-jobs")})
(replace-buffer "main")))
(set! (.-onclose @ws) #(show-msg "Websocket Closed"))
(set! (.-onmessage @ws) (fn [m]
(let [msg (js->clj (JSON/parse (.-data m)))
res (handle-message msg)]
(reply-sync msg res))))
(events/listen js/document (kb/keyword->event-type :keypress)
(fn [e]
(let [code (.-charCode e)]
(cond
(= 18 code)
(.send @ws (JSON/stringify #js{"cmd" "save-and-run-buffer"
"val" (.getValue js/editor)
"buffer_id" "main"}))
(= 19 code)
(.send @ws (JSON/stringify #js{"cmd" "stop-jobs"
"val" (.getValue js/editor)}))))))
)
(defn ^:export sendCode
[]
(.send @ws (JSON/stringify #js {:cmd "save-and-run-buffer"
:val (.getValue js/editor)
:buffer_id "main"})))
(defn ^:export stopCode
[]
(.send @ws (JSON/stringify #js {:cmd "stop-jobs"
:val (.getValue js/editor)})))
(defn ^:export reloadCode
[]
(.send @ws (JSON/stringify #js {:cmd "reload"
:val (.getValue js/editor)})))
(defn stop-job [j-id]
(.send @ws (JSON/stringify #js {:cmd "stop-job"
:val j-id})))
(defn mk-ws []
(reset! ws (js/WebSocket. (str "ws://" hostname ":8001"))))
|
[
{
"context": "w (fn [x] (str \"Hello, \" x \"!\"))]\n (is (= (hw \"Dave\") \"Hello, Dave!\"))\n (is (= (hw \"Jenn\") \"Hello,",
"end": 544,
"score": 0.7720151543617249,
"start": 540,
"tag": "NAME",
"value": "Dave"
},
{
"context": " \"Hello, \" x \"!\"))]\n (is (= (hw \"Dave\") \"Hello, Dave!\"))\n (is (= (hw \"Jenn\") \"Hello, Jenn!\"))\n (",
"end": 559,
"score": 0.8465173244476318,
"start": 555,
"tag": "NAME",
"value": "Dave"
}
] | practice/living-clojure/training-plan/src/training_plan/week1/day2.clj | tomjkidd/clojure | 1 | (ns training-plan.week1.day2
(:use clojure.test))
(deftest sequencesRest
(is (= [20 30 40] (rest [10 20 30 40]))))
(deftest introToFunctions
(is (= 8 ((fn add-five [x] (+ x 5)) 3)))
(is (= 8 ((fn [x] (+ x 5)) 3)))
(is (= 8 (#(+ % 5) 3)))
(is (= 8 ((partial + 5) 3))))
(deftest doubleDown
(let [double-fn (fn [x] (* x 2))]
(is (= (double-fn 2) 4))
(is (= (double-fn 3) 6))
(is (= (double-fn 11) 22))
(is (= (double-fn 7) 14))))
(deftest helloWorld
(let [hw (fn [x] (str "Hello, " x "!"))]
(is (= (hw "Dave") "Hello, Dave!"))
(is (= (hw "Jenn") "Hello, Jenn!"))
(is (= (hw "Rhea") "Hello, Rhea!"))))
(deftest sequencesMaps
(is (= '(6 7 8) (map #(+ % 5) '(1 2 3)))))
(deftest sequencesFilter
(is (= '(6 7) (filter #(> % 5) '(3 4 5 6 7)))))
(deftest localBindings
(is (= 7 (let [x 5] (+ 2 x))))
(is (= 7 (let [x 3, y 10] (- y x))))
(is (= 7 (let [x 21] (let [y 3] (/ x y))))))
(deftest letItBe
(is (= 10 (let [x 7 y 3] (+ x y))))
(is (= 4 (let [y 3 z 1] (+ y z))))
(is (= 1 (let [z 1] z))))
| 77417 | (ns training-plan.week1.day2
(:use clojure.test))
(deftest sequencesRest
(is (= [20 30 40] (rest [10 20 30 40]))))
(deftest introToFunctions
(is (= 8 ((fn add-five [x] (+ x 5)) 3)))
(is (= 8 ((fn [x] (+ x 5)) 3)))
(is (= 8 (#(+ % 5) 3)))
(is (= 8 ((partial + 5) 3))))
(deftest doubleDown
(let [double-fn (fn [x] (* x 2))]
(is (= (double-fn 2) 4))
(is (= (double-fn 3) 6))
(is (= (double-fn 11) 22))
(is (= (double-fn 7) 14))))
(deftest helloWorld
(let [hw (fn [x] (str "Hello, " x "!"))]
(is (= (hw "<NAME>") "Hello, <NAME>!"))
(is (= (hw "Jenn") "Hello, Jenn!"))
(is (= (hw "Rhea") "Hello, Rhea!"))))
(deftest sequencesMaps
(is (= '(6 7 8) (map #(+ % 5) '(1 2 3)))))
(deftest sequencesFilter
(is (= '(6 7) (filter #(> % 5) '(3 4 5 6 7)))))
(deftest localBindings
(is (= 7 (let [x 5] (+ 2 x))))
(is (= 7 (let [x 3, y 10] (- y x))))
(is (= 7 (let [x 21] (let [y 3] (/ x y))))))
(deftest letItBe
(is (= 10 (let [x 7 y 3] (+ x y))))
(is (= 4 (let [y 3 z 1] (+ y z))))
(is (= 1 (let [z 1] z))))
| true | (ns training-plan.week1.day2
(:use clojure.test))
(deftest sequencesRest
(is (= [20 30 40] (rest [10 20 30 40]))))
(deftest introToFunctions
(is (= 8 ((fn add-five [x] (+ x 5)) 3)))
(is (= 8 ((fn [x] (+ x 5)) 3)))
(is (= 8 (#(+ % 5) 3)))
(is (= 8 ((partial + 5) 3))))
(deftest doubleDown
(let [double-fn (fn [x] (* x 2))]
(is (= (double-fn 2) 4))
(is (= (double-fn 3) 6))
(is (= (double-fn 11) 22))
(is (= (double-fn 7) 14))))
(deftest helloWorld
(let [hw (fn [x] (str "Hello, " x "!"))]
(is (= (hw "PI:NAME:<NAME>END_PI") "Hello, PI:NAME:<NAME>END_PI!"))
(is (= (hw "Jenn") "Hello, Jenn!"))
(is (= (hw "Rhea") "Hello, Rhea!"))))
(deftest sequencesMaps
(is (= '(6 7 8) (map #(+ % 5) '(1 2 3)))))
(deftest sequencesFilter
(is (= '(6 7) (filter #(> % 5) '(3 4 5 6 7)))))
(deftest localBindings
(is (= 7 (let [x 5] (+ 2 x))))
(is (= 7 (let [x 3, y 10] (- y x))))
(is (= 7 (let [x 21] (let [y 3] (/ x y))))))
(deftest letItBe
(is (= 10 (let [x 7 y 3] (+ x y))))
(is (= 4 (let [y 3 z 1] (+ y z))))
(is (= 1 (let [z 1] z))))
|
[
{
"context": "regions in variants.\n Based on 'vcfentropy' from Erik Garrison's vcflib:\n https://github.com/ekg/vcflib\"\n (:i",
"end": 216,
"score": 0.9909461140632629,
"start": 203,
"tag": "NAME",
"value": "Erik Garrison"
},
{
"context": "rom Erik Garrison's vcflib:\n https://github.com/ekg/vcflib\"\n (:import [org.broadinstitute.sting.gatk",
"end": 252,
"score": 0.9967606067657471,
"start": 249,
"tag": "USERNAME",
"value": "ekg"
},
{
"context": "oFieldAnnotation))\n\n\n;; ## Shannon entropy\n;; From John Lawrence Aspden's information theory posts\n;; https://github.com/",
"end": 650,
"score": 0.9996281862258911,
"start": 630,
"tag": "NAME",
"value": "John Lawrence Aspden"
},
{
"context": "'s information theory posts\n;; https://github.com/johnlawrenceaspden/hobby-code/blob/master/averygentleintroduction-pa",
"end": 718,
"score": 0.99923175573349,
"start": 700,
"tag": "USERNAME",
"value": "johnlawrenceaspden"
}
] | src/bcbio/variation/annotate/entropy.clj | roryk/bcbio.variation | 1 | (ns bcbio.variation.annotate.entropy
"Calculate Shannon entropy for flanking sequence surrounding variants.
Used to identify low-complexity repeat regions in variants.
Based on 'vcfentropy' from Erik Garrison's vcflib:
https://github.com/ekg/vcflib"
(:import [org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation]
[org.broadinstitute.variant.vcf VCFInfoHeaderLine VCFHeaderLineType])
(:gen-class
:name bcbio.variation.annotate.entropy.ShannonEntropy
:extends org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation))
;; ## Shannon entropy
;; From John Lawrence Aspden's information theory posts
;; https://github.com/johnlawrenceaspden/hobby-code/blob/master/averygentleintroduction-part5.clj
(defn bits [n]
"How many bits to represent n alternatives? Fractions allowed! Also know as log2."
(/ (Math/log n) (Math/log 2)))
(defn shannon-entropy [P]
(let [odds (map second P)
total (reduce + odds)
bits-aliased (/ (reduce + (map * odds (map bits odds))) total)]
(- (bits total) bits-aliased)))
(defn seq-entropy
"Calculate entropy of a sequence based on distribution of dimers.
Splits sequence into all dimer 2bp windows, calculates frequency
of each dimer and then feeds distribution to shannon calculation."
[seq]
(->> seq
(partition 2 1)
frequencies
shannon-entropy))
;; ## Helper function
(defn get-flank-seq
"Retrieve sequence surrounding the current variant, with nbp flanking sequence."
[ref-context nbp]
(letfn [(subset-region [x]
(let [want-size (inc (* 2 nbp))
end-subtract (/ (- (count x) want-size) 2)]
(subs x end-subtract (- (count x) end-subtract))))]
(->> ref-context
.getBases
(map char)
(apply str)
subset-region)))
;; ## GATK walker
(def flank-bp 12)
(defn -getKeyNames [_]
["Entropy"])
(defn -getDescriptions [_]
[(VCFInfoHeaderLine. "Entropy" 1 VCFHeaderLineType/Float
(format "Shannon entropy of variant flanking regions, %sbp on both sides"
flank-bp))])
(defn -annotate
"Retrieve flanking region surrounding variant and calculate entropy."
[_ _ _ ref _ _ _]
{"Entropy" (->> (get-flank-seq ref flank-bp)
seq-entropy
(format "%.2f"))})
| 38873 | (ns bcbio.variation.annotate.entropy
"Calculate Shannon entropy for flanking sequence surrounding variants.
Used to identify low-complexity repeat regions in variants.
Based on 'vcfentropy' from <NAME>'s vcflib:
https://github.com/ekg/vcflib"
(:import [org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation]
[org.broadinstitute.variant.vcf VCFInfoHeaderLine VCFHeaderLineType])
(:gen-class
:name bcbio.variation.annotate.entropy.ShannonEntropy
:extends org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation))
;; ## Shannon entropy
;; From <NAME>'s information theory posts
;; https://github.com/johnlawrenceaspden/hobby-code/blob/master/averygentleintroduction-part5.clj
(defn bits [n]
"How many bits to represent n alternatives? Fractions allowed! Also know as log2."
(/ (Math/log n) (Math/log 2)))
(defn shannon-entropy [P]
(let [odds (map second P)
total (reduce + odds)
bits-aliased (/ (reduce + (map * odds (map bits odds))) total)]
(- (bits total) bits-aliased)))
(defn seq-entropy
"Calculate entropy of a sequence based on distribution of dimers.
Splits sequence into all dimer 2bp windows, calculates frequency
of each dimer and then feeds distribution to shannon calculation."
[seq]
(->> seq
(partition 2 1)
frequencies
shannon-entropy))
;; ## Helper function
(defn get-flank-seq
"Retrieve sequence surrounding the current variant, with nbp flanking sequence."
[ref-context nbp]
(letfn [(subset-region [x]
(let [want-size (inc (* 2 nbp))
end-subtract (/ (- (count x) want-size) 2)]
(subs x end-subtract (- (count x) end-subtract))))]
(->> ref-context
.getBases
(map char)
(apply str)
subset-region)))
;; ## GATK walker
(def flank-bp 12)
(defn -getKeyNames [_]
["Entropy"])
(defn -getDescriptions [_]
[(VCFInfoHeaderLine. "Entropy" 1 VCFHeaderLineType/Float
(format "Shannon entropy of variant flanking regions, %sbp on both sides"
flank-bp))])
(defn -annotate
"Retrieve flanking region surrounding variant and calculate entropy."
[_ _ _ ref _ _ _]
{"Entropy" (->> (get-flank-seq ref flank-bp)
seq-entropy
(format "%.2f"))})
| true | (ns bcbio.variation.annotate.entropy
"Calculate Shannon entropy for flanking sequence surrounding variants.
Used to identify low-complexity repeat regions in variants.
Based on 'vcfentropy' from PI:NAME:<NAME>END_PI's vcflib:
https://github.com/ekg/vcflib"
(:import [org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation]
[org.broadinstitute.variant.vcf VCFInfoHeaderLine VCFHeaderLineType])
(:gen-class
:name bcbio.variation.annotate.entropy.ShannonEntropy
:extends org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation))
;; ## Shannon entropy
;; From PI:NAME:<NAME>END_PI's information theory posts
;; https://github.com/johnlawrenceaspden/hobby-code/blob/master/averygentleintroduction-part5.clj
(defn bits [n]
"How many bits to represent n alternatives? Fractions allowed! Also know as log2."
(/ (Math/log n) (Math/log 2)))
(defn shannon-entropy [P]
(let [odds (map second P)
total (reduce + odds)
bits-aliased (/ (reduce + (map * odds (map bits odds))) total)]
(- (bits total) bits-aliased)))
(defn seq-entropy
"Calculate entropy of a sequence based on distribution of dimers.
Splits sequence into all dimer 2bp windows, calculates frequency
of each dimer and then feeds distribution to shannon calculation."
[seq]
(->> seq
(partition 2 1)
frequencies
shannon-entropy))
;; ## Helper function
(defn get-flank-seq
"Retrieve sequence surrounding the current variant, with nbp flanking sequence."
[ref-context nbp]
(letfn [(subset-region [x]
(let [want-size (inc (* 2 nbp))
end-subtract (/ (- (count x) want-size) 2)]
(subs x end-subtract (- (count x) end-subtract))))]
(->> ref-context
.getBases
(map char)
(apply str)
subset-region)))
;; ## GATK walker
(def flank-bp 12)
(defn -getKeyNames [_]
["Entropy"])
(defn -getDescriptions [_]
[(VCFInfoHeaderLine. "Entropy" 1 VCFHeaderLineType/Float
(format "Shannon entropy of variant flanking regions, %sbp on both sides"
flank-bp))])
(defn -annotate
"Retrieve flanking region surrounding variant and calculate entropy."
[_ _ _ ref _ _ _]
{"Entropy" (->> (get-flank-seq ref flank-bp)
seq-entropy
(format "%.2f"))})
|
[
{
"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.9999346733093262,
"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.9997594356536865,
"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.9999339580535889,
"start": 79,
"tag": "EMAIL",
"value": "cb@opscode.com"
}
] | src/omnibus/steps.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.steps
(:use [omnibus.log]
[clojure.contrib.logging :only [log]]
[clojure.contrib.io :only [make-parents file-str]]
[clojure.contrib.str-utils :only [str-join]]
[clojure.java.shell :only [sh with-sh-env with-sh-dir]])
(:require [clojure.contrib.string :as str])
(:gen-class))
(defn run-shell
[step]
(let [combined-env (merge (hash-map) (System/getenv) (step :env))]
(with-sh-env combined-env
(if (step :args)
(apply sh (cons (step :command) (step :args)))
(sh (step :command))))))
(defn- execute-step
"Run a build step"
[step path]
(let [step-info (str-join " " (cons (step :command) (step :args)))]
(log :info (str "Running step: " step-info ))
(with-sh-dir path
(log-sh-result (run-shell step)
(str "Step command succeeded: " step-info)
(str "Step command failed: " step-info)))))
(defn run-steps
"Run the steps for a given piece of software"
[build-root soft]
(log :info (str "Building " (soft :source)))
(dorun (for [step (soft :steps)]
(execute-step step (.getPath (if (= (soft :source) nil)
(file-str build-root)
(if (= (soft :build-subdir) nil)
(file-str build-root "/" (soft :source))
(file-str build-root "/" (soft :source) "/" (soft :build-subdir)))))))))
| 40095 | ;;
;; 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.steps
(:use [omnibus.log]
[clojure.contrib.logging :only [log]]
[clojure.contrib.io :only [make-parents file-str]]
[clojure.contrib.str-utils :only [str-join]]
[clojure.java.shell :only [sh with-sh-env with-sh-dir]])
(:require [clojure.contrib.string :as str])
(:gen-class))
(defn run-shell
[step]
(let [combined-env (merge (hash-map) (System/getenv) (step :env))]
(with-sh-env combined-env
(if (step :args)
(apply sh (cons (step :command) (step :args)))
(sh (step :command))))))
(defn- execute-step
"Run a build step"
[step path]
(let [step-info (str-join " " (cons (step :command) (step :args)))]
(log :info (str "Running step: " step-info ))
(with-sh-dir path
(log-sh-result (run-shell step)
(str "Step command succeeded: " step-info)
(str "Step command failed: " step-info)))))
(defn run-steps
"Run the steps for a given piece of software"
[build-root soft]
(log :info (str "Building " (soft :source)))
(dorun (for [step (soft :steps)]
(execute-step step (.getPath (if (= (soft :source) nil)
(file-str build-root)
(if (= (soft :build-subdir) nil)
(file-str build-root "/" (soft :source))
(file-str build-root "/" (soft :source) "/" (soft :build-subdir)))))))))
| 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.steps
(:use [omnibus.log]
[clojure.contrib.logging :only [log]]
[clojure.contrib.io :only [make-parents file-str]]
[clojure.contrib.str-utils :only [str-join]]
[clojure.java.shell :only [sh with-sh-env with-sh-dir]])
(:require [clojure.contrib.string :as str])
(:gen-class))
(defn run-shell
[step]
(let [combined-env (merge (hash-map) (System/getenv) (step :env))]
(with-sh-env combined-env
(if (step :args)
(apply sh (cons (step :command) (step :args)))
(sh (step :command))))))
(defn- execute-step
"Run a build step"
[step path]
(let [step-info (str-join " " (cons (step :command) (step :args)))]
(log :info (str "Running step: " step-info ))
(with-sh-dir path
(log-sh-result (run-shell step)
(str "Step command succeeded: " step-info)
(str "Step command failed: " step-info)))))
(defn run-steps
"Run the steps for a given piece of software"
[build-root soft]
(log :info (str "Building " (soft :source)))
(dorun (for [step (soft :steps)]
(execute-step step (.getPath (if (= (soft :source) nil)
(file-str build-root)
(if (= (soft :build-subdir) nil)
(file-str build-root "/" (soft :source))
(file-str build-root "/" (soft :source) "/" (soft :build-subdir)))))))))
|
[
{
"context": "rdinality Constraints\n\n; Copyright (c) 2014 - 2018 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 100,
"score": 0.9998745918273926,
"start": 86,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] | src/lwb/prop/cardinality.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Boolean Cardinality Constraints
; Copyright (c) 2014 - 2018 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.prop.cardinality
"Cardinality constraints in propositional logic"
(:require [lwb.prop :refer :all]
[clojure.math.combinatorics :refer (combinations)]
[clojure.spec.alpha :as s]))
;; # Cardinality constraints in propositional logic
;; The functions are returning sequences of clauses of the form `(or literal1 literal2 ...)`
;; expressing cardinality constraints for the given collection of atoms
(s/def ::acoll (s/coll-of atom?))
(defn min-kof
"`(min-kof k acoll)` -> a seq of clauses expressing that
at least k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 1 k (count acoll))]}
(map #(apply list 'or %) (combinations acoll (inc (- (count acoll) k)))))
(s/fdef min-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn max-kof
"`(max-kof k acoll)` -> a seq of clauses expressing that
at most k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 0 k (count acoll))]}
(if (zero? k)
(map #(list 'not %) acoll))
(for [s (combinations acoll (inc k))]
(apply list 'or (map #(list 'not %) s))))
(s/fdef max-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn kof
"`(kof k acoll)` -> a seq of clauses expressing that
exactly k of the symbols in acoll are true."
[k acoll]
(condp = k
0 (max-kof 0 acoll)
(count acoll) (min-kof k acoll)
(concat (min-kof k acoll) (max-kof k acoll))))
(s/fdef kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn oneof
"`(oneof acoll)` -> a seq of clauses expressing that
exactly 1 symbol in acoll is true."
[acoll]
(when (seq acoll) (kof 1 acoll)))
(s/fdef oneof
:args (s/cat :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
| 8076 | ; lwb Logic WorkBench -- Boolean Cardinality Constraints
; Copyright (c) 2014 - 2018 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.prop.cardinality
"Cardinality constraints in propositional logic"
(:require [lwb.prop :refer :all]
[clojure.math.combinatorics :refer (combinations)]
[clojure.spec.alpha :as s]))
;; # Cardinality constraints in propositional logic
;; The functions are returning sequences of clauses of the form `(or literal1 literal2 ...)`
;; expressing cardinality constraints for the given collection of atoms
(s/def ::acoll (s/coll-of atom?))
(defn min-kof
"`(min-kof k acoll)` -> a seq of clauses expressing that
at least k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 1 k (count acoll))]}
(map #(apply list 'or %) (combinations acoll (inc (- (count acoll) k)))))
(s/fdef min-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn max-kof
"`(max-kof k acoll)` -> a seq of clauses expressing that
at most k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 0 k (count acoll))]}
(if (zero? k)
(map #(list 'not %) acoll))
(for [s (combinations acoll (inc k))]
(apply list 'or (map #(list 'not %) s))))
(s/fdef max-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn kof
"`(kof k acoll)` -> a seq of clauses expressing that
exactly k of the symbols in acoll are true."
[k acoll]
(condp = k
0 (max-kof 0 acoll)
(count acoll) (min-kof k acoll)
(concat (min-kof k acoll) (max-kof k acoll))))
(s/fdef kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn oneof
"`(oneof acoll)` -> a seq of clauses expressing that
exactly 1 symbol in acoll is true."
[acoll]
(when (seq acoll) (kof 1 acoll)))
(s/fdef oneof
:args (s/cat :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
| true | ; lwb Logic WorkBench -- Boolean Cardinality Constraints
; Copyright (c) 2014 - 2018 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.prop.cardinality
"Cardinality constraints in propositional logic"
(:require [lwb.prop :refer :all]
[clojure.math.combinatorics :refer (combinations)]
[clojure.spec.alpha :as s]))
;; # Cardinality constraints in propositional logic
;; The functions are returning sequences of clauses of the form `(or literal1 literal2 ...)`
;; expressing cardinality constraints for the given collection of atoms
(s/def ::acoll (s/coll-of atom?))
(defn min-kof
"`(min-kof k acoll)` -> a seq of clauses expressing that
at least k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 1 k (count acoll))]}
(map #(apply list 'or %) (combinations acoll (inc (- (count acoll) k)))))
(s/fdef min-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn max-kof
"`(max-kof k acoll)` -> a seq of clauses expressing that
at most k of the symbols in acoll are true."
[k acoll]
{:pre [(<= 0 k (count acoll))]}
(if (zero? k)
(map #(list 'not %) acoll))
(for [s (combinations acoll (inc k))]
(apply list 'or (map #(list 'not %) s))))
(s/fdef max-kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn kof
"`(kof k acoll)` -> a seq of clauses expressing that
exactly k of the symbols in acoll are true."
[k acoll]
(condp = k
0 (max-kof 0 acoll)
(count acoll) (min-kof k acoll)
(concat (min-kof k acoll) (max-kof k acoll))))
(s/fdef kof
:args (s/cat :k int? :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
(defn oneof
"`(oneof acoll)` -> a seq of clauses expressing that
exactly 1 symbol in acoll is true."
[acoll]
(when (seq acoll) (kof 1 acoll)))
(s/fdef oneof
:args (s/cat :acoll ::acoll)
:ret (s/* :lwb.prop/clause))
|
[
{
"context": "\"\n (prep-tnt-client {:username \"root\"})))\n\n (is (includes? #\"Arg :password = 123[\\s",
"end": 2307,
"score": 0.8863282799720764,
"start": 2303,
"tag": "USERNAME",
"value": "root"
},
{
"context": " \"root\"})))\n\n (is (includes? #\"Arg :password = 123[\\s\\S]+:xtdb\\.tarantool\\/password\"\n ",
"end": 2352,
"score": 0.8779687285423279,
"start": 2351,
"tag": "PASSWORD",
"value": "1"
},
{
"context": "\"\n (prep-tnt-client {:username \"root\"\n :password 1",
"end": 2441,
"score": 0.9116294980049133,
"start": 2437,
"tag": "USERNAME",
"value": "root"
},
{
"context": "t\"\n :password 123})))\n\n (is (includes? #\"Arg :host = 123[\\s\\S]+:",
"end": 2493,
"score": 0.9979454874992371,
"start": 2490,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "\"\n (prep-tnt-client {:username \"root\"\n :password \"",
"end": 2618,
"score": 0.8388744592666626,
"start": 2614,
"tag": "USERNAME",
"value": "root"
},
{
"context": "\"\n :password \"root\"\n :host 1",
"end": 2672,
"score": 0.6134445071220398,
"start": 2668,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "\"\n (prep-tnt-client {:username \"root\"\n :password \"",
"end": 2850,
"score": 0.9425703883171082,
"start": 2846,
"tag": "USERNAME",
"value": "root"
},
{
"context": "\"\n :password \"root\"\n :host \"",
"end": 2904,
"score": 0.9799010157585144,
"start": 2900,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "\"\n :host \"127.0.0.1\"\n :port -",
"end": 2963,
"score": 0.9993590116500854,
"start": 2954,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " (prep-tnt-client {:username \"root\"\n :password ",
"end": 3176,
"score": 0.9064390063285828,
"start": 3172,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"\n :exception-",
"end": 3239,
"score": 0.9806923270225525,
"start": 3235,
"tag": "PASSWORD",
"value": "root"
},
{
"context": " (prep-tnt-client {:username \"root\"\n :password ",
"end": 3469,
"score": 0.9967086911201477,
"start": 3465,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"\n :exception-",
"end": 3535,
"score": 0.9996113181114197,
"start": 3531,
"tag": "PASSWORD",
"value": "root"
},
{
"context": " (prep-tnt-client {:username \"root\"\n :password ",
"end": 3834,
"score": 0.9962615966796875,
"start": 3830,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"\n :exception ",
"end": 3900,
"score": 0.9995771050453186,
"start": 3896,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "specs\"\n (is (nil? (prep-tnt-client {:username \"root\" :password \"root\"})))\n\n (is (nil? (prep-tnt-cl",
"end": 4257,
"score": 0.9946255683898926,
"start": 4253,
"tag": "USERNAME",
"value": "root"
},
{
"context": "il? (prep-tnt-client {:username \"root\" :password \"root\"})))\n\n (is (nil? (prep-tnt-client {:username \"",
"end": 4274,
"score": 0.9996098279953003,
"start": 4270,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "\"})))\n\n (is (nil? (prep-tnt-client {:username \"root\" :password \"root\" :exception-handler (sut/default",
"end": 4328,
"score": 0.9860000014305115,
"start": 4324,
"tag": "USERNAME",
"value": "root"
},
{
"context": "il? (prep-tnt-client {:username \"root\" :password \"root\" :exception-handler (sut/default-exception-handle",
"end": 4345,
"score": 0.9996005296707153,
"start": 4341,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "is (nil? (prep-tnt-client {:username \"root\"\n :password ",
"end": 4462,
"score": 0.9959742426872253,
"start": 4458,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"\n :exception-handl",
"end": 4523,
"score": 0.9995964169502258,
"start": 4519,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "is (nil? (prep-tnt-client {:username \"root\"\n :password ",
"end": 4777,
"score": 0.9958592057228088,
"start": 4773,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"\n :exception-handl",
"end": 4838,
"score": 0.999598503112793,
"start": 4834,
"tag": "PASSWORD",
"value": "root"
},
{
"context": " :username \"root\"\n :passwor",
"end": 5378,
"score": 0.992469847202301,
"start": 5374,
"tag": "USERNAME",
"value": "root"
},
{
"context": " :password \"root\"})]\n (is (instance? RetryingTarantoolTupleCl",
"end": 5435,
"score": 0.9996042251586914,
"start": 5431,
"tag": "PASSWORD",
"value": "root"
},
{
"context": " (let [tnt-client (start-tnt-client {:username \"root\", :password \"root\"})\n box-info (sut/ge",
"end": 5810,
"score": 0.9938855767250061,
"start": 5806,
"tag": "USERNAME",
"value": "root"
},
{
"context": "t (start-tnt-client {:username \"root\", :password \"root\"})\n box-info (sut/get-box-info tnt-cli",
"end": 5828,
"score": 0.9994076490402222,
"start": 5824,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "\n (let [tnt-client (start-tnt-client {:username \"root\", :password \"root\"})\n mapper sut/defau",
"end": 6216,
"score": 0.8659873008728027,
"start": 6212,
"tag": "USERNAME",
"value": "root"
},
{
"context": "t (start-tnt-client {:username \"root\", :password \"root\"})\n mapper sut/default-complex-types-m",
"end": 6234,
"score": 0.9995318651199341,
"start": 6230,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "nt-client\n :username \"root\"\n :password \"root\"}\n\n",
"end": 7309,
"score": 0.9941890239715576,
"start": 7305,
"tag": "USERNAME",
"value": "root"
},
{
"context": " \"root\"\n :password \"root\"}\n\n :xtdb/index-store {:xtdb/module 'xtdb.k",
"end": 7355,
"score": 0.9995362758636475,
"start": 7351,
"tag": "PASSWORD",
"value": "root"
},
{
"context": "(get % :user/name) \"zig\")))\n ;; => ({:user/name \"zig\", :xt/id \"hi2u\"})\n\n )\n",
"end": 8464,
"score": 0.6131690740585327,
"start": 8461,
"tag": "USERNAME",
"value": "zig"
}
] | src/test/clojure/xtdb/tarantool_test.clj | sultanov-team/xtdb-tarantool | 10 | (ns xtdb.tarantool-test
(:require
[clojure.test :refer [deftest testing is]]
[xtdb.api :as xt]
[xtdb.system :as system]
[xtdb.tarantool :as sut]
[xtdb.tx.event :as xte])
(:import
(io.tarantool.driver.core
RetryingTarantoolTupleClient)
(java.util
ArrayList)
(java.util.concurrent
ExecutionException)
(java.util.function
Function
UnaryOperator)))
;;
;; Helper functions
;;
(defn prep-tnt-client
[overrides]
(try
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
:tnt-client)
(catch xtdb.IllegalArgumentException e
(ex-message (ex-cause e)))))
(defn start-tnt-client
[overrides]
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
(system/start-system)
:tnt-client))
(defn includes?
[pattern x]
(try
(boolean (re-find pattern x))
(catch Exception _
false)))
;;
;; Tests
;;
(deftest ^:unit default-exception-handler-test
(testing "should be returned an instance of `java.util.function.Function`"
(is (instance? Function (sut/default-exception-handler)))))
(deftest ^:unit default-request-retry-policy-test
(testing "should be returned an instance of `java.util.function.UnaryOperator`"
(is (instance? UnaryOperator (sut/default-request-retry-policy {:delay 300})))))
(deftest to-inst-test
(testing "should be returned an instance of `java.util.Date`"
(is (= #inst"2021-12-03T01:26:09.506-00:00" (sut/to-inst 1638494769506799)))))
(deftest prepare-fn-args-test
(testing "should be returned an instance of `java.util.ArrayList`"
(doseq [x [nil 1 1/2 "string" \c :keyword ::qualified-keyword 'symbol 'qualified-symbol '(1 2 3) [1 2 3] #{1 2 3} (ArrayList. [1 2 3])]]
(is (instance? ArrayList (sut/prepare-fn-args x))))))
(deftest ^:unit ->tnt-client-specs-test
(testing "should be failed by specs"
(is (includes? #"Arg :username required"
(prep-tnt-client {})))
(is (includes? #"Arg :username = 123[\s\S]+:xtdb\.tarantool\/username"
(prep-tnt-client {:username 123})))
(is (includes? #"Arg :password required"
(prep-tnt-client {:username "root"})))
(is (includes? #"Arg :password = 123[\s\S]+:xtdb\.tarantool\/password"
(prep-tnt-client {:username "root"
:password 123})))
(is (includes? #"Arg :host = 123[\s\S]+:xtdb\.tarantool\/host"
(prep-tnt-client {:username "root"
:password "root"
:host 123})))
(is (includes? #"Arg :port = -123[\s\S]+:xtdb\.tarantool\/port"
(prep-tnt-client {:username "root"
:password "root"
:host "127.0.0.1"
:port -123})))
(is (includes? #"Arg :exception-handler = 123[\s\S]+:xtdb\.tarantool\/exception-handler"
(prep-tnt-client {:username "root"
:password "root"
:exception-handler 123})))
(is (includes? #"Arg :request-retry-policy = 123[\s\S]+:xtdb\.tarantool\/request-retry-policy"
(prep-tnt-client {:username "root"
:password "root"
:exception-handler (sut/default-exception-handler)
:request-retry-policy 123})))
(is (includes? #"Arg :retries = -123[\s\S]+:xtdb\.tarantool\/retries"
(prep-tnt-client {:username "root"
:password "root"
:exception (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries -123}))))
(testing "should be passed by specs"
(is (nil? (prep-tnt-client {:username "root" :password "root"})))
(is (nil? (prep-tnt-client {:username "root" :password "root" :exception-handler (sut/default-exception-handler)})))
(is (nil? (prep-tnt-client {:username "root"
:password "root"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})})))
(is (nil? (prep-tnt-client {:username "root"
:password "root"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries 3})))))
(deftest ^:integration ->tnt-client-test
(testing "should be throw an exception with a bad connection options"
(let [tnt-client (start-tnt-client {:host "localhost"
:port 3302
:username "root"
:password "root"})]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (thrown-with-msg? ExecutionException #"The client is not connected to Tarantool server"
(sut/get-box-info tnt-client sut/default-complex-types-mapper)))))
(testing "should be returned a successful response from the tarantool"
(let [tnt-client (start-tnt-client {:username "root", :password "root"})
box-info (sut/get-box-info tnt-client sut/default-complex-types-mapper)]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (= "0.0.0.0:3301" (get box-info "listen")))
(is (includes? #"2.8.2" (get box-info "version")))
(sut/close tnt-client))))
(deftest ^:integration ->tx-log-test
(let [tnt-client (start-tnt-client {:username "root", :password "root"})
mapper sut/default-complex-types-mapper
tx-log {:tnt-client tnt-client, :mapper mapper}
truncate #(sut/execute tnt-client mapper "xtdb.db.truncate")]
(testing "should be returned the same tx-id"
(truncate)
(is (nil? (sut/latest-submitted-tx tx-log)))
(let [tx @(sut/submit-tx tx-log [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
latest-tx (sut/latest-submitted-tx tx-log)
txs (sut/open-tx-log* tx-log nil)]
(is (every? seq [tx latest-tx txs]))
(is (= #{::xt/tx-id} (->> latest-tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time} (->> tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time ::xte/tx-events} (->> txs (map keys) (flatten) (set))))
(is (= (::xt/tx-id tx) (::xt/tx-id latest-tx) (::xt/tx-id (last txs)))))
(truncate)
(Thread/sleep 5000)
(sut/close tnt-client))))
(comment
(def node
(xt/start-node
{::tnt-client {:xtdb/module `sut/->tnt-client
:username "root"
:password "root"}
:xtdb/index-store {:xtdb/module 'xtdb.kv.index-store/->kv-index-store}
:xtdb/tx-log {:xtdb/module `sut/->tx-log
:tnt-client ::tnt-client}}))
(sut/close node)
(xt/submit-tx node [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
;; => #:xtdb.api{:tx-id 4, :tx-time #inst"2021-12-03T22:00:34.561-00:00"}
(xt/q (xt/db node) '{:find [e]
:where [[e :user/name "zig"]]})
;; => #{["hi2u"]}
(xt/q (xt/db node)
'{:find [(pull ?e [*])]
:where [[?e :xt/id "hi2u"]]})
;; => #{[{:user/name "zig", :xt/id "hi2u"}]}
(def history (xt/entity-history (xt/db node) "hi2u" :desc {:with-docs? true}))
;;=> [#:xtdb.api{:tx-time #inst"2021-12-03T22:00:34.561-00:00",
;; :tx-id 4,
;; :valid-time #inst"2021-12-03T22:00:34.561-00:00",
;; :content-hash #xtdb/id"32f90c7020097d1232d14a9af395fc6aabd02ad7",
;; :doc {:user/name "zig", :xt/id "hi2u"}}]
(->> (map ::xt/doc history)
(filter #(= (get % :user/name) "zig")))
;; => ({:user/name "zig", :xt/id "hi2u"})
)
| 65212 | (ns xtdb.tarantool-test
(:require
[clojure.test :refer [deftest testing is]]
[xtdb.api :as xt]
[xtdb.system :as system]
[xtdb.tarantool :as sut]
[xtdb.tx.event :as xte])
(:import
(io.tarantool.driver.core
RetryingTarantoolTupleClient)
(java.util
ArrayList)
(java.util.concurrent
ExecutionException)
(java.util.function
Function
UnaryOperator)))
;;
;; Helper functions
;;
(defn prep-tnt-client
[overrides]
(try
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
:tnt-client)
(catch xtdb.IllegalArgumentException e
(ex-message (ex-cause e)))))
(defn start-tnt-client
[overrides]
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
(system/start-system)
:tnt-client))
(defn includes?
[pattern x]
(try
(boolean (re-find pattern x))
(catch Exception _
false)))
;;
;; Tests
;;
(deftest ^:unit default-exception-handler-test
(testing "should be returned an instance of `java.util.function.Function`"
(is (instance? Function (sut/default-exception-handler)))))
(deftest ^:unit default-request-retry-policy-test
(testing "should be returned an instance of `java.util.function.UnaryOperator`"
(is (instance? UnaryOperator (sut/default-request-retry-policy {:delay 300})))))
(deftest to-inst-test
(testing "should be returned an instance of `java.util.Date`"
(is (= #inst"2021-12-03T01:26:09.506-00:00" (sut/to-inst 1638494769506799)))))
(deftest prepare-fn-args-test
(testing "should be returned an instance of `java.util.ArrayList`"
(doseq [x [nil 1 1/2 "string" \c :keyword ::qualified-keyword 'symbol 'qualified-symbol '(1 2 3) [1 2 3] #{1 2 3} (ArrayList. [1 2 3])]]
(is (instance? ArrayList (sut/prepare-fn-args x))))))
(deftest ^:unit ->tnt-client-specs-test
(testing "should be failed by specs"
(is (includes? #"Arg :username required"
(prep-tnt-client {})))
(is (includes? #"Arg :username = 123[\s\S]+:xtdb\.tarantool\/username"
(prep-tnt-client {:username 123})))
(is (includes? #"Arg :password required"
(prep-tnt-client {:username "root"})))
(is (includes? #"Arg :password = <PASSWORD>23[\s\S]+:xtdb\.tarantool\/password"
(prep-tnt-client {:username "root"
:password <PASSWORD>})))
(is (includes? #"Arg :host = 123[\s\S]+:xtdb\.tarantool\/host"
(prep-tnt-client {:username "root"
:password "<PASSWORD>"
:host 123})))
(is (includes? #"Arg :port = -123[\s\S]+:xtdb\.tarantool\/port"
(prep-tnt-client {:username "root"
:password "<PASSWORD>"
:host "127.0.0.1"
:port -123})))
(is (includes? #"Arg :exception-handler = 123[\s\S]+:xtdb\.tarantool\/exception-handler"
(prep-tnt-client {:username "root"
:password "<PASSWORD>"
:exception-handler 123})))
(is (includes? #"Arg :request-retry-policy = 123[\s\S]+:xtdb\.tarantool\/request-retry-policy"
(prep-tnt-client {:username "root"
:password "<PASSWORD>"
:exception-handler (sut/default-exception-handler)
:request-retry-policy 123})))
(is (includes? #"Arg :retries = -123[\s\S]+:xtdb\.tarantool\/retries"
(prep-tnt-client {:username "root"
:password "<PASSWORD>"
:exception (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries -123}))))
(testing "should be passed by specs"
(is (nil? (prep-tnt-client {:username "root" :password "<PASSWORD>"})))
(is (nil? (prep-tnt-client {:username "root" :password "<PASSWORD>" :exception-handler (sut/default-exception-handler)})))
(is (nil? (prep-tnt-client {:username "root"
:password "<PASSWORD>"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})})))
(is (nil? (prep-tnt-client {:username "root"
:password "<PASSWORD>"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries 3})))))
(deftest ^:integration ->tnt-client-test
(testing "should be throw an exception with a bad connection options"
(let [tnt-client (start-tnt-client {:host "localhost"
:port 3302
:username "root"
:password "<PASSWORD>"})]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (thrown-with-msg? ExecutionException #"The client is not connected to Tarantool server"
(sut/get-box-info tnt-client sut/default-complex-types-mapper)))))
(testing "should be returned a successful response from the tarantool"
(let [tnt-client (start-tnt-client {:username "root", :password "<PASSWORD>"})
box-info (sut/get-box-info tnt-client sut/default-complex-types-mapper)]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (= "0.0.0.0:3301" (get box-info "listen")))
(is (includes? #"2.8.2" (get box-info "version")))
(sut/close tnt-client))))
(deftest ^:integration ->tx-log-test
(let [tnt-client (start-tnt-client {:username "root", :password "<PASSWORD>"})
mapper sut/default-complex-types-mapper
tx-log {:tnt-client tnt-client, :mapper mapper}
truncate #(sut/execute tnt-client mapper "xtdb.db.truncate")]
(testing "should be returned the same tx-id"
(truncate)
(is (nil? (sut/latest-submitted-tx tx-log)))
(let [tx @(sut/submit-tx tx-log [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
latest-tx (sut/latest-submitted-tx tx-log)
txs (sut/open-tx-log* tx-log nil)]
(is (every? seq [tx latest-tx txs]))
(is (= #{::xt/tx-id} (->> latest-tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time} (->> tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time ::xte/tx-events} (->> txs (map keys) (flatten) (set))))
(is (= (::xt/tx-id tx) (::xt/tx-id latest-tx) (::xt/tx-id (last txs)))))
(truncate)
(Thread/sleep 5000)
(sut/close tnt-client))))
(comment
(def node
(xt/start-node
{::tnt-client {:xtdb/module `sut/->tnt-client
:username "root"
:password "<PASSWORD>"}
:xtdb/index-store {:xtdb/module 'xtdb.kv.index-store/->kv-index-store}
:xtdb/tx-log {:xtdb/module `sut/->tx-log
:tnt-client ::tnt-client}}))
(sut/close node)
(xt/submit-tx node [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
;; => #:xtdb.api{:tx-id 4, :tx-time #inst"2021-12-03T22:00:34.561-00:00"}
(xt/q (xt/db node) '{:find [e]
:where [[e :user/name "zig"]]})
;; => #{["hi2u"]}
(xt/q (xt/db node)
'{:find [(pull ?e [*])]
:where [[?e :xt/id "hi2u"]]})
;; => #{[{:user/name "zig", :xt/id "hi2u"}]}
(def history (xt/entity-history (xt/db node) "hi2u" :desc {:with-docs? true}))
;;=> [#:xtdb.api{:tx-time #inst"2021-12-03T22:00:34.561-00:00",
;; :tx-id 4,
;; :valid-time #inst"2021-12-03T22:00:34.561-00:00",
;; :content-hash #xtdb/id"32f90c7020097d1232d14a9af395fc6aabd02ad7",
;; :doc {:user/name "zig", :xt/id "hi2u"}}]
(->> (map ::xt/doc history)
(filter #(= (get % :user/name) "zig")))
;; => ({:user/name "zig", :xt/id "hi2u"})
)
| true | (ns xtdb.tarantool-test
(:require
[clojure.test :refer [deftest testing is]]
[xtdb.api :as xt]
[xtdb.system :as system]
[xtdb.tarantool :as sut]
[xtdb.tx.event :as xte])
(:import
(io.tarantool.driver.core
RetryingTarantoolTupleClient)
(java.util
ArrayList)
(java.util.concurrent
ExecutionException)
(java.util.function
Function
UnaryOperator)))
;;
;; Helper functions
;;
(defn prep-tnt-client
[overrides]
(try
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
:tnt-client)
(catch xtdb.IllegalArgumentException e
(ex-message (ex-cause e)))))
(defn start-tnt-client
[overrides]
(-> {:tnt-client (merge {:xtdb/module 'xtdb.tarantool/->tnt-client} overrides)}
(system/prep-system)
(system/start-system)
:tnt-client))
(defn includes?
[pattern x]
(try
(boolean (re-find pattern x))
(catch Exception _
false)))
;;
;; Tests
;;
(deftest ^:unit default-exception-handler-test
(testing "should be returned an instance of `java.util.function.Function`"
(is (instance? Function (sut/default-exception-handler)))))
(deftest ^:unit default-request-retry-policy-test
(testing "should be returned an instance of `java.util.function.UnaryOperator`"
(is (instance? UnaryOperator (sut/default-request-retry-policy {:delay 300})))))
(deftest to-inst-test
(testing "should be returned an instance of `java.util.Date`"
(is (= #inst"2021-12-03T01:26:09.506-00:00" (sut/to-inst 1638494769506799)))))
(deftest prepare-fn-args-test
(testing "should be returned an instance of `java.util.ArrayList`"
(doseq [x [nil 1 1/2 "string" \c :keyword ::qualified-keyword 'symbol 'qualified-symbol '(1 2 3) [1 2 3] #{1 2 3} (ArrayList. [1 2 3])]]
(is (instance? ArrayList (sut/prepare-fn-args x))))))
(deftest ^:unit ->tnt-client-specs-test
(testing "should be failed by specs"
(is (includes? #"Arg :username required"
(prep-tnt-client {})))
(is (includes? #"Arg :username = 123[\s\S]+:xtdb\.tarantool\/username"
(prep-tnt-client {:username 123})))
(is (includes? #"Arg :password required"
(prep-tnt-client {:username "root"})))
(is (includes? #"Arg :password = PI:PASSWORD:<PASSWORD>END_PI23[\s\S]+:xtdb\.tarantool\/password"
(prep-tnt-client {:username "root"
:password PI:PASSWORD:<PASSWORD>END_PI})))
(is (includes? #"Arg :host = 123[\s\S]+:xtdb\.tarantool\/host"
(prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:host 123})))
(is (includes? #"Arg :port = -123[\s\S]+:xtdb\.tarantool\/port"
(prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:host "127.0.0.1"
:port -123})))
(is (includes? #"Arg :exception-handler = 123[\s\S]+:xtdb\.tarantool\/exception-handler"
(prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:exception-handler 123})))
(is (includes? #"Arg :request-retry-policy = 123[\s\S]+:xtdb\.tarantool\/request-retry-policy"
(prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:exception-handler (sut/default-exception-handler)
:request-retry-policy 123})))
(is (includes? #"Arg :retries = -123[\s\S]+:xtdb\.tarantool\/retries"
(prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:exception (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries -123}))))
(testing "should be passed by specs"
(is (nil? (prep-tnt-client {:username "root" :password "PI:PASSWORD:<PASSWORD>END_PI"})))
(is (nil? (prep-tnt-client {:username "root" :password "PI:PASSWORD:<PASSWORD>END_PI" :exception-handler (sut/default-exception-handler)})))
(is (nil? (prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})})))
(is (nil? (prep-tnt-client {:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:exception-handler (sut/default-exception-handler)
:request-retry-policy (sut/default-request-retry-policy {:delay 500})
:retries 3})))))
(deftest ^:integration ->tnt-client-test
(testing "should be throw an exception with a bad connection options"
(let [tnt-client (start-tnt-client {:host "localhost"
:port 3302
:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"})]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (thrown-with-msg? ExecutionException #"The client is not connected to Tarantool server"
(sut/get-box-info tnt-client sut/default-complex-types-mapper)))))
(testing "should be returned a successful response from the tarantool"
(let [tnt-client (start-tnt-client {:username "root", :password "PI:PASSWORD:<PASSWORD>END_PI"})
box-info (sut/get-box-info tnt-client sut/default-complex-types-mapper)]
(is (instance? RetryingTarantoolTupleClient tnt-client))
(is (= "0.0.0.0:3301" (get box-info "listen")))
(is (includes? #"2.8.2" (get box-info "version")))
(sut/close tnt-client))))
(deftest ^:integration ->tx-log-test
(let [tnt-client (start-tnt-client {:username "root", :password "PI:PASSWORD:<PASSWORD>END_PI"})
mapper sut/default-complex-types-mapper
tx-log {:tnt-client tnt-client, :mapper mapper}
truncate #(sut/execute tnt-client mapper "xtdb.db.truncate")]
(testing "should be returned the same tx-id"
(truncate)
(is (nil? (sut/latest-submitted-tx tx-log)))
(let [tx @(sut/submit-tx tx-log [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
latest-tx (sut/latest-submitted-tx tx-log)
txs (sut/open-tx-log* tx-log nil)]
(is (every? seq [tx latest-tx txs]))
(is (= #{::xt/tx-id} (->> latest-tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time} (->> tx (keys) (set))))
(is (= #{::xt/tx-id ::xt/tx-time ::xte/tx-events} (->> txs (map keys) (flatten) (set))))
(is (= (::xt/tx-id tx) (::xt/tx-id latest-tx) (::xt/tx-id (last txs)))))
(truncate)
(Thread/sleep 5000)
(sut/close tnt-client))))
(comment
(def node
(xt/start-node
{::tnt-client {:xtdb/module `sut/->tnt-client
:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:xtdb/index-store {:xtdb/module 'xtdb.kv.index-store/->kv-index-store}
:xtdb/tx-log {:xtdb/module `sut/->tx-log
:tnt-client ::tnt-client}}))
(sut/close node)
(xt/submit-tx node [[::xt/put {:xt/id "hi2u", :user/name "zig"}]])
;; => #:xtdb.api{:tx-id 4, :tx-time #inst"2021-12-03T22:00:34.561-00:00"}
(xt/q (xt/db node) '{:find [e]
:where [[e :user/name "zig"]]})
;; => #{["hi2u"]}
(xt/q (xt/db node)
'{:find [(pull ?e [*])]
:where [[?e :xt/id "hi2u"]]})
;; => #{[{:user/name "zig", :xt/id "hi2u"}]}
(def history (xt/entity-history (xt/db node) "hi2u" :desc {:with-docs? true}))
;;=> [#:xtdb.api{:tx-time #inst"2021-12-03T22:00:34.561-00:00",
;; :tx-id 4,
;; :valid-time #inst"2021-12-03T22:00:34.561-00:00",
;; :content-hash #xtdb/id"32f90c7020097d1232d14a9af395fc6aabd02ad7",
;; :doc {:user/name "zig", :xt/id "hi2u"}}]
(->> (map ::xt/doc history)
(filter #(= (get % :user/name) "zig")))
;; => ({:user/name "zig", :xt/id "hi2u"})
)
|
[
{
"context": " :user \"dogpig\"\n :password \"dogpig\"\n :useSSL false}))\n ",
"end": 253,
"score": 0.9992711544036865,
"start": 247,
"tag": "PASSWORD",
"value": "dogpig"
}
] | src/dog_board/server.clj | re-noir/dog-board | 0 | (ns dog-board.server
(:require [noir.server :as server]
[korma.db :refer :all])
(:gen-class))
(defdb dev (mysql {:host "localhost"
:db "dogpigdb"
:user "dogpig"
:password "dogpig"
:useSSL false}))
(server/load-views-ns 'dog-board.views)
(defn -main [& m]
(let [mode (keyword (or (first m) :dev))
port (Integer. (get (System/getenv) "PORT" "9090"))]
(server/start port {:mode mode
:ns 'dog-board})))
| 81652 | (ns dog-board.server
(:require [noir.server :as server]
[korma.db :refer :all])
(:gen-class))
(defdb dev (mysql {:host "localhost"
:db "dogpigdb"
:user "dogpig"
:password "<PASSWORD>"
:useSSL false}))
(server/load-views-ns 'dog-board.views)
(defn -main [& m]
(let [mode (keyword (or (first m) :dev))
port (Integer. (get (System/getenv) "PORT" "9090"))]
(server/start port {:mode mode
:ns 'dog-board})))
| true | (ns dog-board.server
(:require [noir.server :as server]
[korma.db :refer :all])
(:gen-class))
(defdb dev (mysql {:host "localhost"
:db "dogpigdb"
:user "dogpig"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:useSSL false}))
(server/load-views-ns 'dog-board.views)
(defn -main [& m]
(let [mode (keyword (or (first m) :dev))
port (Integer. (get (System/getenv) "PORT" "9090"))]
(server/start port {:mode mode
:ns 'dog-board})))
|
[
{
"context": "er/customerid 4858\n :customer/email \"OVWOIYIDDL@dell.com\"\n :orderline/orderlineid 8\n ",
"end": 6296,
"score": 0.999923825263977,
"start": 6277,
"tag": "EMAIL",
"value": "OVWOIYIDDL@dell.com"
},
{
"context": "er/customerid 4858\n :customer/email \"OVWOIYIDDL@dell.com\"\n :orderline/orderlineid 4\n ",
"end": 6699,
"score": 0.9999252557754517,
"start": 6680,
"tag": "EMAIL",
"value": "OVWOIYIDDL@dell.com"
},
{
"context": "ues (\n 12345,\n 'Foo', 'Bar', 'foobar@example.org', '123 Some Place',\n",
"end": 11519,
"score": 0.6776864528656006,
"start": 11516,
"tag": "NAME",
"value": "Foo"
},
{
"context": " 12345,\n 'Foo', 'Bar', 'foobar@example.org', '123 Some Place',\n 'Thousand O",
"end": 11548,
"score": 0.9999235272407532,
"start": 11530,
"tag": "EMAIL",
"value": "foobar@example.org"
},
{
"context": ".]\n :where [?e :customer/email \"foobar@example.org\"]]\n db')\n ents (->> ids\n ",
"end": 11944,
"score": 0.9999227523803711,
"start": 11926,
"tag": "EMAIL",
"value": "foobar@example.org"
},
{
"context": "stomerid 12345\n :customer/firstname \"Foo\"\n :customer/lastname \"Bar\"\n ",
"end": 12227,
"score": 0.9990184307098389,
"start": 12224,
"tag": "NAME",
"value": "Foo"
},
{
"context": "firstname \"Foo\"\n :customer/lastname \"Bar\"\n :customer/email \"foobar@example.or",
"end": 12266,
"score": 0.9967354536056519,
"start": 12263,
"tag": "NAME",
"value": "Bar"
},
{
"context": "mer/lastname \"Bar\"\n :customer/email \"foobar@example.org\"\n :customer/address-1 \"123 Some Plac",
"end": 12317,
"score": 0.9999222755432129,
"start": 12299,
"tag": "EMAIL",
"value": "foobar@example.org"
},
{
"context": "te-targeting-no-rows-has-no-effect\n (let [actor \"homer simpson\"\n stmt (format \"delete from product where ",
"end": 20488,
"score": 0.8058615922927856,
"start": 20475,
"tag": "USERNAME",
"value": "homer simpson"
}
] | test/sql_datomic/integration_test.clj | kenrestivo-stem/sql-datomic | 26 | (ns sql-datomic.integration-test
(:require [clojure.test :refer :all]
[sql-datomic.datomic :as dat]
sql-datomic.types ;; necessary for reader literals
[sql-datomic.parser :as par]
[sql-datomic.select-command :as sel]
[sql-datomic.insert-command :as ins]
[sql-datomic.update-command :as upd]
[sql-datomic.delete-command :as del]
[sql-datomic.retract-command :as rtr]
[datomic.api :as d]
[clojure.string :as str]
[clojure.set :as set]))
;;;; SETUP and HELPER FUNCTIONS ;;;;
(def ^:dynamic *conn* :not-a-connection)
(def ^:dynamic *db* :not-a-db)
(defn current-db [] (d/db *conn*))
(defn entity->map
([eid] (entity->map *db* eid))
([db eid]
(if-let [e (d/entity db eid)]
(->> e d/touch (into {:db/id (:db/id e)}))
{})))
(defn product-map->comparable [m]
;; cannot compare byte arrays and :db/id changes per db refresh
(dissoc m :db/id :product/blob))
(defn -select-keys [ks m]
(select-keys m ks))
(defn -select-resultset [{:keys [entities attrs]}]
(into #{} (map (partial -select-keys attrs) entities)))
(defn count-entities
([db primary-attr]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr
:where [?e ?attr]]
db
primary-attr)]
(if (nil? n) 0 n)))
([db attr v]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr ?v
:where [?e ?attr ?v]]
db
attr v)]
(if (nil? n) 0 n))))
(defn db-fixture [f]
(let [sys (.start (dat/system {}))]
#_(do (println "=== db set-up") (flush))
(binding [*conn* (->> sys :datomic :connection)]
(binding [*db* (d/db *conn*)]
(f)))
(.stop sys)
#_(do (println "=== db tear-down") (flush))))
(use-fixtures :each db-fixture)
;;;; SELECT statements ;;;;
(deftest product-entity-present
(is (= (product-map->comparable (entity->map *db* [:product/prod-id 8293]))
{:product/url #uri "http://example.com/products/8293"
:product/prod-id 8293
:product/uuid #uuid "57607472-0bd8-4ed3-98d3-586e9e9c9683"
:product/common-prod-id 4804
:product/man-hours 100N
:product/price 13.99M
:product/category :product.category/family
:product/tag :alabama-exorcist-family
:product/actor "NICK MINELLI"
:product/rating #float 2.6
:product/special false
:product/title "ALABAMA EXORCIST"})))
(defn stmt->ir [stmt]
(->> stmt par/parser par/transform))
(deftest select-product-by-prod-id
(let [ir (stmt->ir "select where product.prod-id = 9990")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map product-map->comparable))
[{:product/url #uri "http://example.com/products/9990"
:product/prod-id 9990
:product/uuid #uuid "57607426-cdd4-49fa-aecb-0a2572976db9"
:product/common-prod-id 6584
:product/man-hours 60100200300N
:product/price 25.99M
:product/category :product.category/music
:product/tag :aladdin-world-music
:product/actor "HUMPHREY DENCH"
:product/rating #float 2.0
:product/special false
:product/title "ALADDIN WORLD"}]))))
(deftest select-all-products-by-prod-id
(let [ir (stmt->ir "select where product.prod-id > 0")
prod-ids #{1298 1567
2290 2926
4402 4936
5130
6127 6376 6879
8293
9990}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-prod-id-6k-products
(let [ir (stmt->ir
"select where product.prod-id between 6000 and 6999")
prod-ids #{6127 6376 6879}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-no-products-by-prod-id
(let [ir (stmt->ir
"select where product.prod-id >= 10000")
prod-ids #{}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-order-between-dates
(let [ir (stmt->ir
"select where
order.orderdate between #inst \"2004-01-01\"
and #inst \"2004-01-05\" ")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map (partial -select-keys
[:order/orderid :order/orderdate]))
(into #{}))
#{{:order/orderid 2
:order/orderdate #inst "2004-01-01T08:00:00.000-00:00"}}))))
(deftest select-cols-of-product-by-prod-id
(let [ir (stmt->ir
"select product.prod-id, #attr :product/tag, product.title
where product.prod-id = 9990")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990
:product/tag :aladdin-world-music
:product/title "ALADDIN WORLD"}}))))
(deftest select-join
(let [ir (stmt->ir
"select order.orderid,
order.totalamount,
order.customerid,
customer.email,
orderline.orderlineid,
orderline.prod-id,
product.uuid,
product.category,
orderline.quantity
where order.orderid = orderline.orderid
and order.customerid = customer.customerid
and orderline.prod-id = product.prod-id
and order.orderid in (1, 2, 3)
and orderline.quantity > 2
and product.category <> :product.category/new
")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "OVWOIYIDDL@dell.com"
:orderline/orderlineid 8
:orderline/prod-id 2926
:product/uuid #uuid "576073e7-d671-45ba-af1a-f08a9a355b81"
:product/category :product.category/music
:orderline/quantity 3}
{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "OVWOIYIDDL@dell.com"
:orderline/orderlineid 4
:orderline/prod-id 5130
:product/uuid #uuid "5760740c-4f24-4f3d-8455-f79a1cc57fa9"
:product/category :product.category/action
:orderline/quantity 3}}))))
;; | :product/prod-id | :product/rating | :product/price | :product/category | :product/man-hours | cat | pr | mh | ??
;; |------------------+-----------------+----------------+-------------------------------+--------------------|
;; | 2926 | #float 1.6 | 22.99M | :product.category/music | 40100200300N | t f f t
;; | 5130 | #float 1.8 | 14.99M | :product.category/action | 50100200300N | t t f t
;; | 9990 | #float 2.0 | 25.99M | :product.category/music | 60100200300N | t f f t
;; | 1567 | #float 2.2 | 25.99M | :product.category/new | 70100200300N | f f f f
;; | 6376 | #float 2.4 | 21.99M | :product.category/drama | 80100200300N | f f f f
;; | 8293 | #float 2.6 | 13.99M | :product.category/family | 100N | t t t t
;; | 4402 | #float 2.8 | 11.99M | :product.category/children | 101N | f t t t
;; | 6879 | #float 3.0 | 12.99M | :product.category/action | 102N | t t t t
;; | 2290 | #float 3.2 | 15.99M | :product.category/documentary | 103N | f t t t
(deftest select-and-or-not-oh-my
(let [ir (stmt->ir
"select product.prod-id,
product.category,
product.price,
product.man-hours,
product.rating
where ( product.category in (
:product.category/music,
:product.category/action,
:product.category/family,
:product.category/horror)
or ( (not (product.price between 20.0M and 30.0M))
and (not (product.man-hours > 1000N))))
and product.rating > 1.5f")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 2926
:product/rating #float 1.6
:product/price 22.99M
:product/category :product.category/music
:product/man-hours 40100200300N}
{:product/prod-id 5130
:product/rating #float 1.8
:product/price 14.99M
:product/category :product.category/action
:product/man-hours 50100200300N}
{:product/prod-id 9990
:product/rating #float 2.0
:product/price 25.99M
:product/category :product.category/music
:product/man-hours 60100200300N}
{:product/prod-id 8293
:product/rating #float 2.6
:product/price 13.99M
:product/category :product.category/family
:product/man-hours 100N}
{:product/prod-id 4402
:product/rating #float 2.8
:product/price 11.99M
:product/category :product.category/children
:product/man-hours 101N}
{:product/prod-id 6879
:product/rating #float 3.0
:product/price 12.99M
:product/category :product.category/action
:product/man-hours 102N}
{:product/prod-id 2290
:product/rating #float 3.2
:product/price 15.99M
:product/category :product.category/documentary
:product/man-hours 103N}}))))
(deftest select-by-db-id
(let [db-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6500)]]
*db*)
stmt (str "select product.prod-id where #attr :db/id "
(str/join " " db-ids))
ir (stmt->ir stmt)]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990}
{:product/prod-id 8293}
{:product/prod-id 6879}}))))
;;;; INSERT statements ;;;;
(deftest insert-traditional-form
(let [db *db*
cnt (count-entities db :customer/customerid)
stmt "insert into customer (
customerid,
firstname, lastname, email, address-1,
city, state, zip, country
)
values (
12345,
'Foo', 'Bar', 'foobar@example.org', '123 Some Place',
'Thousand Oaks', 'CA', '91362', 'USA'
)"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :customer/customerid)
ids (d/q '[:find [?e ...]
:where [?e :customer/email "foobar@example.org"]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:customer/customerid 12345
:customer/firstname "Foo"
:customer/lastname "Bar"
:customer/email "foobar@example.org"
:customer/address-1 "123 Some Place"
:customer/city "Thousand Oaks"
:customer/state "CA"
:customer/zip "91362"
:customer/country "USA"}}))))
(deftest insert-short-form
(let [db *db*
cnt (count-entities db :product/prod-id)
stmt "insert into
#attr :product/prod-id = 9999,
#attr :product/actor = 'Naomi Watts',
#attr :product/title = 'The Ring',
product.category = :product.category/horror,
product.rating = 4.5f,
product.man-hours = 9001N,
product.price = 21.99M"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :product/prod-id)
ids (d/q '[:find [?e ...]
:where [?e :product/prod-id 9999]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:product/prod-id 9999
:product/actor "Naomi Watts"
:product/title "The Ring"
:product/category :product.category/horror
:product/rating #float 4.5
:product/man-hours 9001N
:product/price 21.99M}}))))
;;;; UPDATE statements ;;;;
(deftest update-customer-where-customerid
(let [stmt "update customer
set customer.city = 'Springfield'
, customer.state = 'VA'
, customer.zip = '22150'
where customer.customerid = 4858"
db *db*
id (d/q '[:find ?e . :where [?e :customer/customerid 4858]] db)
ent (entity->map db id)
cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
ent' (entity->map db' id)]
(is (= ent'
(assoc ent
:customer/city "Springfield"
:customer/state "VA"
:customer/zip "22150")))
(is (= (count-entities db' :customer/customerid) cnt)
"number of customers remains unchanged")))
(deftest update-products-where-db-id
(let [db *db*
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
e->m (partial entity->map db)
ents (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
stmt "update product
set product.tag = :all-the-things
, product.special = true
, product.price = 1.50M
where db.id "
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
ents' (->> ids (map e->m') (into #{}))]
(is (= ents'
(->> ents
(map (fn [ent]
(assoc ent
:product/tag :all-the-things
:product/special true
:product/price 1.50M)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")
;; assumption: all products originally have special set to false
(when (zero? (count-entities db :product/special true))
(is (= (count ents')
(count-entities db' :product/special true))))))
(deftest update-customer-order-join
(let [stmt "update customer
set #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
(deftest update-product-short-form
(let [stmt "update #attr :product/rating = 3.5f
where #attr :product/prod-id > 6000"
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-product-short-form-by-db-id
(let [stmt "update #attr :product/rating = 3.5f
where #attr :db/id in ("
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(< ?pid 6000)]]
db)
stmt' (str stmt (str/join ", " ids) ")")
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-customer-order-join-short-form
(let [stmt "update #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
;; this works so long as all attrs in the assignment pair list
;; refer to one (and only one) namespace/table.
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
;;;; DELETE statements ;;;;
(deftest delete-targeting-no-rows-has-no-effect
(let [actor "homer simpson"
stmt (format "delete from product where product.actor = '%s'"
actor)
db *db*
product-cnt (count-entities db :product/prod-id)
;; should be empty
ids (d/q '[:find [?e ...]
:in $ ?doh!
:where [?e :product/actor ?doh!]]
db actor)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (empty? ids) "assumption: where clause matched no rows")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (= db db') "the db itself has not changed")))
(deftest delete-product-by-prod-id
(let [prod-id 9990
stmt (format "delete from product where product.prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-all-products-by-prod-id
;; chose products here because they have no component attrs,
;; i.e., they will not trigger a cascading delete.
(let [stmt "delete from product where product.prod-id > 0"
db *db*
query '[:find [?e ...]
:where [?e :product/prod-id]]
ids (d/q query db)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (pos? (count-entities db :product/prod-id))
"assumption: initially, db had products present")
(is (zero? (count-entities db' :product/prod-id))
"the number of products has decreased to zero")
(is (empty? (d/q query db'))
"no products are present in db")))
(deftest delete-products-by-db-id
(let [stmt "delete from product where db.id "
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
query '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 7000)]
[(<= 4000 ?pid)]]
ids (d/q query db)
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
query' '[:find [?e ...] :where [?e :product/prod-id]]
ids' (d/q query' db')
products' (map e->m' ids')]
(is (= (count-entities db' :product/prod-id)
(- product-cnt (count ids)))
"the number of products has decreased appropriately")
(is (empty? (set/intersection
(into #{} ids')
(into #{} ids)))
"targeted :db/ids no longer present in db")
(is (not-any? (fn [{:keys [product/prod-id]}]
(<= 4000 prod-id 7000))
products'))))
(deftest delete-order-cascading-orderlines-by-orderid
(let [stmt "delete from order where order.orderid = 5"
db *db*
e->m (partial entity->map db)
;; an order has many orderlines (as components)
;; an orderline has a product (not component)
;; deleting an order should delete its orderlines but not the products
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
oid (d/q '[:find ?e . :where [?e :order/orderid 5]] db)
order (e->m oid)
olids (d/q '[:find [?e ...] :where [?e :orderline/orderid 5]] db)
orderlines (map e->m olids)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 5]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
products (map e->m pids)
prod-ids (map :product/prod-id products)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (empty? (d/q '[:find ?e :where [?e :order/orderid 5]] db'))
"targeted order is no longer present in db")
(is (empty? (d/q '[:find ?e :where [?e :orderline/orderid 5]] db'))
"targeted order's orderlines are no longer present in db")
(is (not-empty
(d/q '[:find ?e
:in $ [?pid ...]
:where [?e :product/prod-id ?pid]]
db' prod-ids))
"targeted order's orderlines' products are still present in db")
(is (= (count-entities db' :order/orderid)
(dec order-cnt))
"the number of orders has decreased by one")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")))
(deftest delete-product-by-prod-id-short-form
(let [prod-id 1567
stmt (format "delete where #attr :product/prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-orderlines-join-by-orderid
(let [stmt "delete from orderline
where orderline.orderid = order.orderid
and order.orderid = 2
and orderline.quantity = 1"
;; note that we are targeting orderlines for deletion, not order
db *db*
e->m (partial entity->map db)
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
target-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity 1]] db)
target-orderline-ids (->> target-olids
(map e->m)
(map :orderline/orderlineid))
remain-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity ?n]
[(not= ?n 1)]] db)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 2]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
prod-ids (->> pids
(map e->m)
(map :product/prod-id))
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
orderlines' (->> (d/q '[:find [?e ...]
:where [?e :orderline/orderid 2]] db')
(map e->m'))]
(is (= (count-entities db' :order/orderid)
order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count target-olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (not-empty (d/q '[:find ?e :where [?e :order/orderid 2]] db'))
"the associated order is still present")
(is (empty?
(d/q '[:find ?e
:in $ [?olid ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/orderlineid ?olid]]
db' target-orderline-ids))
"targeted orderlines of given order were retracted")
(is (not-any? (fn [{:keys [orderline/quantity]}]
(= 1 quantity))
orderlines')
"none of the quantity orderlines of given order are present")
(is (= (->> (d/q '[:find [?e ...] :where [?e :orderline/orderid 2]] db')
(into #{}))
(->> remain-olids (into #{})))
"all of the non-targeted orderlines are still present")))
;;;; RETRACT statements ;;;;
(deftest retract-product-attr-by-db-id
(let [stmt-fmt "RETRACT product.uuid WHERE db.id = %d"
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
prod-id 8293
id (d/q '[:find ?e .
:in $ ?pid
:where [?e :product/prod-id ?pid]]
db prod-id)
stmt (format stmt-fmt id)
ir (stmt->ir stmt)
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
product' (e->m' id)
attrs' (->> product' keys (into #{}))]
(is (= (get attrs' :product/uuid :nope) :nope)
"the retracted attr is no longer present on target product")
(is (= (count-entities db' :product/uuid)
(dec product-cnt))
"number of products with uuid attr decreased by one")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")))
(deftest retract-product-attrs-for-many-db-ids
(let [stmt "retract #attr :product/actor,
#attr :product/rating,
#attr :product/url
where db.id "
db *db*
e->m (partial entity->map db)
retracted-attrs [:product/actor :product/rating :product/url]
product-cnt (count-entities db :product/prod-id)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
remain-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 6000)]]
db)
remain-products (->> remain-ids (map e->m))
all-attrs (->> remain-products first keys (into #{}))
kept-attrs (set/difference all-attrs (into #{} retracted-attrs))
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m'))
remain-products' (->> remain-ids (map e->m'))]
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")
(is (= (into #{} remain-products')
(into #{} remain-products))
"the non-targeted products remain unchanged")
(is (every? (fn [p]
(let [attrs (->> p keys (into #{}))]
(= kept-attrs attrs)))
products')
"the retracted attrs are no longer present on target products")))
(comment
(defn pp-ent [eid]
(db-fixture
(fn []
(->> (entity->map *db* eid)
clojure.pprint/pprint))))
(pp-ent [:product/prod-id 9990])
)
| 114684 | (ns sql-datomic.integration-test
(:require [clojure.test :refer :all]
[sql-datomic.datomic :as dat]
sql-datomic.types ;; necessary for reader literals
[sql-datomic.parser :as par]
[sql-datomic.select-command :as sel]
[sql-datomic.insert-command :as ins]
[sql-datomic.update-command :as upd]
[sql-datomic.delete-command :as del]
[sql-datomic.retract-command :as rtr]
[datomic.api :as d]
[clojure.string :as str]
[clojure.set :as set]))
;;;; SETUP and HELPER FUNCTIONS ;;;;
(def ^:dynamic *conn* :not-a-connection)
(def ^:dynamic *db* :not-a-db)
(defn current-db [] (d/db *conn*))
(defn entity->map
([eid] (entity->map *db* eid))
([db eid]
(if-let [e (d/entity db eid)]
(->> e d/touch (into {:db/id (:db/id e)}))
{})))
(defn product-map->comparable [m]
;; cannot compare byte arrays and :db/id changes per db refresh
(dissoc m :db/id :product/blob))
(defn -select-keys [ks m]
(select-keys m ks))
(defn -select-resultset [{:keys [entities attrs]}]
(into #{} (map (partial -select-keys attrs) entities)))
(defn count-entities
([db primary-attr]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr
:where [?e ?attr]]
db
primary-attr)]
(if (nil? n) 0 n)))
([db attr v]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr ?v
:where [?e ?attr ?v]]
db
attr v)]
(if (nil? n) 0 n))))
(defn db-fixture [f]
(let [sys (.start (dat/system {}))]
#_(do (println "=== db set-up") (flush))
(binding [*conn* (->> sys :datomic :connection)]
(binding [*db* (d/db *conn*)]
(f)))
(.stop sys)
#_(do (println "=== db tear-down") (flush))))
(use-fixtures :each db-fixture)
;;;; SELECT statements ;;;;
(deftest product-entity-present
(is (= (product-map->comparable (entity->map *db* [:product/prod-id 8293]))
{:product/url #uri "http://example.com/products/8293"
:product/prod-id 8293
:product/uuid #uuid "57607472-0bd8-4ed3-98d3-586e9e9c9683"
:product/common-prod-id 4804
:product/man-hours 100N
:product/price 13.99M
:product/category :product.category/family
:product/tag :alabama-exorcist-family
:product/actor "NICK MINELLI"
:product/rating #float 2.6
:product/special false
:product/title "ALABAMA EXORCIST"})))
(defn stmt->ir [stmt]
(->> stmt par/parser par/transform))
(deftest select-product-by-prod-id
(let [ir (stmt->ir "select where product.prod-id = 9990")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map product-map->comparable))
[{:product/url #uri "http://example.com/products/9990"
:product/prod-id 9990
:product/uuid #uuid "57607426-cdd4-49fa-aecb-0a2572976db9"
:product/common-prod-id 6584
:product/man-hours 60100200300N
:product/price 25.99M
:product/category :product.category/music
:product/tag :aladdin-world-music
:product/actor "HUMPHREY DENCH"
:product/rating #float 2.0
:product/special false
:product/title "ALADDIN WORLD"}]))))
(deftest select-all-products-by-prod-id
(let [ir (stmt->ir "select where product.prod-id > 0")
prod-ids #{1298 1567
2290 2926
4402 4936
5130
6127 6376 6879
8293
9990}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-prod-id-6k-products
(let [ir (stmt->ir
"select where product.prod-id between 6000 and 6999")
prod-ids #{6127 6376 6879}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-no-products-by-prod-id
(let [ir (stmt->ir
"select where product.prod-id >= 10000")
prod-ids #{}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-order-between-dates
(let [ir (stmt->ir
"select where
order.orderdate between #inst \"2004-01-01\"
and #inst \"2004-01-05\" ")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map (partial -select-keys
[:order/orderid :order/orderdate]))
(into #{}))
#{{:order/orderid 2
:order/orderdate #inst "2004-01-01T08:00:00.000-00:00"}}))))
(deftest select-cols-of-product-by-prod-id
(let [ir (stmt->ir
"select product.prod-id, #attr :product/tag, product.title
where product.prod-id = 9990")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990
:product/tag :aladdin-world-music
:product/title "ALADDIN WORLD"}}))))
(deftest select-join
(let [ir (stmt->ir
"select order.orderid,
order.totalamount,
order.customerid,
customer.email,
orderline.orderlineid,
orderline.prod-id,
product.uuid,
product.category,
orderline.quantity
where order.orderid = orderline.orderid
and order.customerid = customer.customerid
and orderline.prod-id = product.prod-id
and order.orderid in (1, 2, 3)
and orderline.quantity > 2
and product.category <> :product.category/new
")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "<EMAIL>"
:orderline/orderlineid 8
:orderline/prod-id 2926
:product/uuid #uuid "576073e7-d671-45ba-af1a-f08a9a355b81"
:product/category :product.category/music
:orderline/quantity 3}
{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "<EMAIL>"
:orderline/orderlineid 4
:orderline/prod-id 5130
:product/uuid #uuid "5760740c-4f24-4f3d-8455-f79a1cc57fa9"
:product/category :product.category/action
:orderline/quantity 3}}))))
;; | :product/prod-id | :product/rating | :product/price | :product/category | :product/man-hours | cat | pr | mh | ??
;; |------------------+-----------------+----------------+-------------------------------+--------------------|
;; | 2926 | #float 1.6 | 22.99M | :product.category/music | 40100200300N | t f f t
;; | 5130 | #float 1.8 | 14.99M | :product.category/action | 50100200300N | t t f t
;; | 9990 | #float 2.0 | 25.99M | :product.category/music | 60100200300N | t f f t
;; | 1567 | #float 2.2 | 25.99M | :product.category/new | 70100200300N | f f f f
;; | 6376 | #float 2.4 | 21.99M | :product.category/drama | 80100200300N | f f f f
;; | 8293 | #float 2.6 | 13.99M | :product.category/family | 100N | t t t t
;; | 4402 | #float 2.8 | 11.99M | :product.category/children | 101N | f t t t
;; | 6879 | #float 3.0 | 12.99M | :product.category/action | 102N | t t t t
;; | 2290 | #float 3.2 | 15.99M | :product.category/documentary | 103N | f t t t
(deftest select-and-or-not-oh-my
(let [ir (stmt->ir
"select product.prod-id,
product.category,
product.price,
product.man-hours,
product.rating
where ( product.category in (
:product.category/music,
:product.category/action,
:product.category/family,
:product.category/horror)
or ( (not (product.price between 20.0M and 30.0M))
and (not (product.man-hours > 1000N))))
and product.rating > 1.5f")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 2926
:product/rating #float 1.6
:product/price 22.99M
:product/category :product.category/music
:product/man-hours 40100200300N}
{:product/prod-id 5130
:product/rating #float 1.8
:product/price 14.99M
:product/category :product.category/action
:product/man-hours 50100200300N}
{:product/prod-id 9990
:product/rating #float 2.0
:product/price 25.99M
:product/category :product.category/music
:product/man-hours 60100200300N}
{:product/prod-id 8293
:product/rating #float 2.6
:product/price 13.99M
:product/category :product.category/family
:product/man-hours 100N}
{:product/prod-id 4402
:product/rating #float 2.8
:product/price 11.99M
:product/category :product.category/children
:product/man-hours 101N}
{:product/prod-id 6879
:product/rating #float 3.0
:product/price 12.99M
:product/category :product.category/action
:product/man-hours 102N}
{:product/prod-id 2290
:product/rating #float 3.2
:product/price 15.99M
:product/category :product.category/documentary
:product/man-hours 103N}}))))
(deftest select-by-db-id
(let [db-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6500)]]
*db*)
stmt (str "select product.prod-id where #attr :db/id "
(str/join " " db-ids))
ir (stmt->ir stmt)]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990}
{:product/prod-id 8293}
{:product/prod-id 6879}}))))
;;;; INSERT statements ;;;;
(deftest insert-traditional-form
(let [db *db*
cnt (count-entities db :customer/customerid)
stmt "insert into customer (
customerid,
firstname, lastname, email, address-1,
city, state, zip, country
)
values (
12345,
'<NAME>', 'Bar', '<EMAIL>', '123 Some Place',
'Thousand Oaks', 'CA', '91362', 'USA'
)"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :customer/customerid)
ids (d/q '[:find [?e ...]
:where [?e :customer/email "<EMAIL>"]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:customer/customerid 12345
:customer/firstname "<NAME>"
:customer/lastname "<NAME>"
:customer/email "<EMAIL>"
:customer/address-1 "123 Some Place"
:customer/city "Thousand Oaks"
:customer/state "CA"
:customer/zip "91362"
:customer/country "USA"}}))))
(deftest insert-short-form
(let [db *db*
cnt (count-entities db :product/prod-id)
stmt "insert into
#attr :product/prod-id = 9999,
#attr :product/actor = 'Naomi Watts',
#attr :product/title = 'The Ring',
product.category = :product.category/horror,
product.rating = 4.5f,
product.man-hours = 9001N,
product.price = 21.99M"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :product/prod-id)
ids (d/q '[:find [?e ...]
:where [?e :product/prod-id 9999]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:product/prod-id 9999
:product/actor "Naomi Watts"
:product/title "The Ring"
:product/category :product.category/horror
:product/rating #float 4.5
:product/man-hours 9001N
:product/price 21.99M}}))))
;;;; UPDATE statements ;;;;
(deftest update-customer-where-customerid
(let [stmt "update customer
set customer.city = 'Springfield'
, customer.state = 'VA'
, customer.zip = '22150'
where customer.customerid = 4858"
db *db*
id (d/q '[:find ?e . :where [?e :customer/customerid 4858]] db)
ent (entity->map db id)
cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
ent' (entity->map db' id)]
(is (= ent'
(assoc ent
:customer/city "Springfield"
:customer/state "VA"
:customer/zip "22150")))
(is (= (count-entities db' :customer/customerid) cnt)
"number of customers remains unchanged")))
(deftest update-products-where-db-id
(let [db *db*
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
e->m (partial entity->map db)
ents (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
stmt "update product
set product.tag = :all-the-things
, product.special = true
, product.price = 1.50M
where db.id "
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
ents' (->> ids (map e->m') (into #{}))]
(is (= ents'
(->> ents
(map (fn [ent]
(assoc ent
:product/tag :all-the-things
:product/special true
:product/price 1.50M)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")
;; assumption: all products originally have special set to false
(when (zero? (count-entities db :product/special true))
(is (= (count ents')
(count-entities db' :product/special true))))))
(deftest update-customer-order-join
(let [stmt "update customer
set #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
(deftest update-product-short-form
(let [stmt "update #attr :product/rating = 3.5f
where #attr :product/prod-id > 6000"
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-product-short-form-by-db-id
(let [stmt "update #attr :product/rating = 3.5f
where #attr :db/id in ("
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(< ?pid 6000)]]
db)
stmt' (str stmt (str/join ", " ids) ")")
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-customer-order-join-short-form
(let [stmt "update #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
;; this works so long as all attrs in the assignment pair list
;; refer to one (and only one) namespace/table.
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
;;;; DELETE statements ;;;;
(deftest delete-targeting-no-rows-has-no-effect
(let [actor "homer simpson"
stmt (format "delete from product where product.actor = '%s'"
actor)
db *db*
product-cnt (count-entities db :product/prod-id)
;; should be empty
ids (d/q '[:find [?e ...]
:in $ ?doh!
:where [?e :product/actor ?doh!]]
db actor)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (empty? ids) "assumption: where clause matched no rows")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (= db db') "the db itself has not changed")))
(deftest delete-product-by-prod-id
(let [prod-id 9990
stmt (format "delete from product where product.prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-all-products-by-prod-id
;; chose products here because they have no component attrs,
;; i.e., they will not trigger a cascading delete.
(let [stmt "delete from product where product.prod-id > 0"
db *db*
query '[:find [?e ...]
:where [?e :product/prod-id]]
ids (d/q query db)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (pos? (count-entities db :product/prod-id))
"assumption: initially, db had products present")
(is (zero? (count-entities db' :product/prod-id))
"the number of products has decreased to zero")
(is (empty? (d/q query db'))
"no products are present in db")))
(deftest delete-products-by-db-id
(let [stmt "delete from product where db.id "
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
query '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 7000)]
[(<= 4000 ?pid)]]
ids (d/q query db)
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
query' '[:find [?e ...] :where [?e :product/prod-id]]
ids' (d/q query' db')
products' (map e->m' ids')]
(is (= (count-entities db' :product/prod-id)
(- product-cnt (count ids)))
"the number of products has decreased appropriately")
(is (empty? (set/intersection
(into #{} ids')
(into #{} ids)))
"targeted :db/ids no longer present in db")
(is (not-any? (fn [{:keys [product/prod-id]}]
(<= 4000 prod-id 7000))
products'))))
(deftest delete-order-cascading-orderlines-by-orderid
(let [stmt "delete from order where order.orderid = 5"
db *db*
e->m (partial entity->map db)
;; an order has many orderlines (as components)
;; an orderline has a product (not component)
;; deleting an order should delete its orderlines but not the products
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
oid (d/q '[:find ?e . :where [?e :order/orderid 5]] db)
order (e->m oid)
olids (d/q '[:find [?e ...] :where [?e :orderline/orderid 5]] db)
orderlines (map e->m olids)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 5]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
products (map e->m pids)
prod-ids (map :product/prod-id products)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (empty? (d/q '[:find ?e :where [?e :order/orderid 5]] db'))
"targeted order is no longer present in db")
(is (empty? (d/q '[:find ?e :where [?e :orderline/orderid 5]] db'))
"targeted order's orderlines are no longer present in db")
(is (not-empty
(d/q '[:find ?e
:in $ [?pid ...]
:where [?e :product/prod-id ?pid]]
db' prod-ids))
"targeted order's orderlines' products are still present in db")
(is (= (count-entities db' :order/orderid)
(dec order-cnt))
"the number of orders has decreased by one")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")))
(deftest delete-product-by-prod-id-short-form
(let [prod-id 1567
stmt (format "delete where #attr :product/prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-orderlines-join-by-orderid
(let [stmt "delete from orderline
where orderline.orderid = order.orderid
and order.orderid = 2
and orderline.quantity = 1"
;; note that we are targeting orderlines for deletion, not order
db *db*
e->m (partial entity->map db)
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
target-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity 1]] db)
target-orderline-ids (->> target-olids
(map e->m)
(map :orderline/orderlineid))
remain-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity ?n]
[(not= ?n 1)]] db)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 2]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
prod-ids (->> pids
(map e->m)
(map :product/prod-id))
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
orderlines' (->> (d/q '[:find [?e ...]
:where [?e :orderline/orderid 2]] db')
(map e->m'))]
(is (= (count-entities db' :order/orderid)
order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count target-olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (not-empty (d/q '[:find ?e :where [?e :order/orderid 2]] db'))
"the associated order is still present")
(is (empty?
(d/q '[:find ?e
:in $ [?olid ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/orderlineid ?olid]]
db' target-orderline-ids))
"targeted orderlines of given order were retracted")
(is (not-any? (fn [{:keys [orderline/quantity]}]
(= 1 quantity))
orderlines')
"none of the quantity orderlines of given order are present")
(is (= (->> (d/q '[:find [?e ...] :where [?e :orderline/orderid 2]] db')
(into #{}))
(->> remain-olids (into #{})))
"all of the non-targeted orderlines are still present")))
;;;; RETRACT statements ;;;;
(deftest retract-product-attr-by-db-id
(let [stmt-fmt "RETRACT product.uuid WHERE db.id = %d"
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
prod-id 8293
id (d/q '[:find ?e .
:in $ ?pid
:where [?e :product/prod-id ?pid]]
db prod-id)
stmt (format stmt-fmt id)
ir (stmt->ir stmt)
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
product' (e->m' id)
attrs' (->> product' keys (into #{}))]
(is (= (get attrs' :product/uuid :nope) :nope)
"the retracted attr is no longer present on target product")
(is (= (count-entities db' :product/uuid)
(dec product-cnt))
"number of products with uuid attr decreased by one")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")))
(deftest retract-product-attrs-for-many-db-ids
(let [stmt "retract #attr :product/actor,
#attr :product/rating,
#attr :product/url
where db.id "
db *db*
e->m (partial entity->map db)
retracted-attrs [:product/actor :product/rating :product/url]
product-cnt (count-entities db :product/prod-id)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
remain-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 6000)]]
db)
remain-products (->> remain-ids (map e->m))
all-attrs (->> remain-products first keys (into #{}))
kept-attrs (set/difference all-attrs (into #{} retracted-attrs))
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m'))
remain-products' (->> remain-ids (map e->m'))]
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")
(is (= (into #{} remain-products')
(into #{} remain-products))
"the non-targeted products remain unchanged")
(is (every? (fn [p]
(let [attrs (->> p keys (into #{}))]
(= kept-attrs attrs)))
products')
"the retracted attrs are no longer present on target products")))
(comment
(defn pp-ent [eid]
(db-fixture
(fn []
(->> (entity->map *db* eid)
clojure.pprint/pprint))))
(pp-ent [:product/prod-id 9990])
)
| true | (ns sql-datomic.integration-test
(:require [clojure.test :refer :all]
[sql-datomic.datomic :as dat]
sql-datomic.types ;; necessary for reader literals
[sql-datomic.parser :as par]
[sql-datomic.select-command :as sel]
[sql-datomic.insert-command :as ins]
[sql-datomic.update-command :as upd]
[sql-datomic.delete-command :as del]
[sql-datomic.retract-command :as rtr]
[datomic.api :as d]
[clojure.string :as str]
[clojure.set :as set]))
;;;; SETUP and HELPER FUNCTIONS ;;;;
(def ^:dynamic *conn* :not-a-connection)
(def ^:dynamic *db* :not-a-db)
(defn current-db [] (d/db *conn*))
(defn entity->map
([eid] (entity->map *db* eid))
([db eid]
(if-let [e (d/entity db eid)]
(->> e d/touch (into {:db/id (:db/id e)}))
{})))
(defn product-map->comparable [m]
;; cannot compare byte arrays and :db/id changes per db refresh
(dissoc m :db/id :product/blob))
(defn -select-keys [ks m]
(select-keys m ks))
(defn -select-resultset [{:keys [entities attrs]}]
(into #{} (map (partial -select-keys attrs) entities)))
(defn count-entities
([db primary-attr]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr
:where [?e ?attr]]
db
primary-attr)]
(if (nil? n) 0 n)))
([db attr v]
(let [n (d/q '[:find (count ?e) .
:in $ ?attr ?v
:where [?e ?attr ?v]]
db
attr v)]
(if (nil? n) 0 n))))
(defn db-fixture [f]
(let [sys (.start (dat/system {}))]
#_(do (println "=== db set-up") (flush))
(binding [*conn* (->> sys :datomic :connection)]
(binding [*db* (d/db *conn*)]
(f)))
(.stop sys)
#_(do (println "=== db tear-down") (flush))))
(use-fixtures :each db-fixture)
;;;; SELECT statements ;;;;
(deftest product-entity-present
(is (= (product-map->comparable (entity->map *db* [:product/prod-id 8293]))
{:product/url #uri "http://example.com/products/8293"
:product/prod-id 8293
:product/uuid #uuid "57607472-0bd8-4ed3-98d3-586e9e9c9683"
:product/common-prod-id 4804
:product/man-hours 100N
:product/price 13.99M
:product/category :product.category/family
:product/tag :alabama-exorcist-family
:product/actor "NICK MINELLI"
:product/rating #float 2.6
:product/special false
:product/title "ALABAMA EXORCIST"})))
(defn stmt->ir [stmt]
(->> stmt par/parser par/transform))
(deftest select-product-by-prod-id
(let [ir (stmt->ir "select where product.prod-id = 9990")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map product-map->comparable))
[{:product/url #uri "http://example.com/products/9990"
:product/prod-id 9990
:product/uuid #uuid "57607426-cdd4-49fa-aecb-0a2572976db9"
:product/common-prod-id 6584
:product/man-hours 60100200300N
:product/price 25.99M
:product/category :product.category/music
:product/tag :aladdin-world-music
:product/actor "HUMPHREY DENCH"
:product/rating #float 2.0
:product/special false
:product/title "ALADDIN WORLD"}]))))
(deftest select-all-products-by-prod-id
(let [ir (stmt->ir "select where product.prod-id > 0")
prod-ids #{1298 1567
2290 2926
4402 4936
5130
6127 6376 6879
8293
9990}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-prod-id-6k-products
(let [ir (stmt->ir
"select where product.prod-id between 6000 and 6999")
prod-ids #{6127 6376 6879}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-no-products-by-prod-id
(let [ir (stmt->ir
"select where product.prod-id >= 10000")
prod-ids #{}]
(is (= (->> (sel/run-select *db* ir)
:entities
(map :product/prod-id)
(into #{}))
prod-ids))))
(deftest select-order-between-dates
(let [ir (stmt->ir
"select where
order.orderdate between #inst \"2004-01-01\"
and #inst \"2004-01-05\" ")]
(is (= (->> (sel/run-select *db* ir)
:entities
(map (partial -select-keys
[:order/orderid :order/orderdate]))
(into #{}))
#{{:order/orderid 2
:order/orderdate #inst "2004-01-01T08:00:00.000-00:00"}}))))
(deftest select-cols-of-product-by-prod-id
(let [ir (stmt->ir
"select product.prod-id, #attr :product/tag, product.title
where product.prod-id = 9990")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990
:product/tag :aladdin-world-music
:product/title "ALADDIN WORLD"}}))))
(deftest select-join
(let [ir (stmt->ir
"select order.orderid,
order.totalamount,
order.customerid,
customer.email,
orderline.orderlineid,
orderline.prod-id,
product.uuid,
product.category,
orderline.quantity
where order.orderid = orderline.orderid
and order.customerid = customer.customerid
and orderline.prod-id = product.prod-id
and order.orderid in (1, 2, 3)
and orderline.quantity > 2
and product.category <> :product.category/new
")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "PI:EMAIL:<EMAIL>END_PI"
:orderline/orderlineid 8
:orderline/prod-id 2926
:product/uuid #uuid "576073e7-d671-45ba-af1a-f08a9a355b81"
:product/category :product.category/music
:orderline/quantity 3}
{:order/orderid 2
:order/totalamount 59.43M
:order/customerid 4858
:customer/email "PI:EMAIL:<EMAIL>END_PI"
:orderline/orderlineid 4
:orderline/prod-id 5130
:product/uuid #uuid "5760740c-4f24-4f3d-8455-f79a1cc57fa9"
:product/category :product.category/action
:orderline/quantity 3}}))))
;; | :product/prod-id | :product/rating | :product/price | :product/category | :product/man-hours | cat | pr | mh | ??
;; |------------------+-----------------+----------------+-------------------------------+--------------------|
;; | 2926 | #float 1.6 | 22.99M | :product.category/music | 40100200300N | t f f t
;; | 5130 | #float 1.8 | 14.99M | :product.category/action | 50100200300N | t t f t
;; | 9990 | #float 2.0 | 25.99M | :product.category/music | 60100200300N | t f f t
;; | 1567 | #float 2.2 | 25.99M | :product.category/new | 70100200300N | f f f f
;; | 6376 | #float 2.4 | 21.99M | :product.category/drama | 80100200300N | f f f f
;; | 8293 | #float 2.6 | 13.99M | :product.category/family | 100N | t t t t
;; | 4402 | #float 2.8 | 11.99M | :product.category/children | 101N | f t t t
;; | 6879 | #float 3.0 | 12.99M | :product.category/action | 102N | t t t t
;; | 2290 | #float 3.2 | 15.99M | :product.category/documentary | 103N | f t t t
(deftest select-and-or-not-oh-my
(let [ir (stmt->ir
"select product.prod-id,
product.category,
product.price,
product.man-hours,
product.rating
where ( product.category in (
:product.category/music,
:product.category/action,
:product.category/family,
:product.category/horror)
or ( (not (product.price between 20.0M and 30.0M))
and (not (product.man-hours > 1000N))))
and product.rating > 1.5f")]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 2926
:product/rating #float 1.6
:product/price 22.99M
:product/category :product.category/music
:product/man-hours 40100200300N}
{:product/prod-id 5130
:product/rating #float 1.8
:product/price 14.99M
:product/category :product.category/action
:product/man-hours 50100200300N}
{:product/prod-id 9990
:product/rating #float 2.0
:product/price 25.99M
:product/category :product.category/music
:product/man-hours 60100200300N}
{:product/prod-id 8293
:product/rating #float 2.6
:product/price 13.99M
:product/category :product.category/family
:product/man-hours 100N}
{:product/prod-id 4402
:product/rating #float 2.8
:product/price 11.99M
:product/category :product.category/children
:product/man-hours 101N}
{:product/prod-id 6879
:product/rating #float 3.0
:product/price 12.99M
:product/category :product.category/action
:product/man-hours 102N}
{:product/prod-id 2290
:product/rating #float 3.2
:product/price 15.99M
:product/category :product.category/documentary
:product/man-hours 103N}}))))
(deftest select-by-db-id
(let [db-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6500)]]
*db*)
stmt (str "select product.prod-id where #attr :db/id "
(str/join " " db-ids))
ir (stmt->ir stmt)]
(is (= (-select-resultset (sel/run-select *db* ir))
#{{:product/prod-id 9990}
{:product/prod-id 8293}
{:product/prod-id 6879}}))))
;;;; INSERT statements ;;;;
(deftest insert-traditional-form
(let [db *db*
cnt (count-entities db :customer/customerid)
stmt "insert into customer (
customerid,
firstname, lastname, email, address-1,
city, state, zip, country
)
values (
12345,
'PI:NAME:<NAME>END_PI', 'Bar', 'PI:EMAIL:<EMAIL>END_PI', '123 Some Place',
'Thousand Oaks', 'CA', '91362', 'USA'
)"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :customer/customerid)
ids (d/q '[:find [?e ...]
:where [?e :customer/email "PI:EMAIL:<EMAIL>END_PI"]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:customer/customerid 12345
:customer/firstname "PI:NAME:<NAME>END_PI"
:customer/lastname "PI:NAME:<NAME>END_PI"
:customer/email "PI:EMAIL:<EMAIL>END_PI"
:customer/address-1 "123 Some Place"
:customer/city "Thousand Oaks"
:customer/state "CA"
:customer/zip "91362"
:customer/country "USA"}}))))
(deftest insert-short-form
(let [db *db*
cnt (count-entities db :product/prod-id)
stmt "insert into
#attr :product/prod-id = 9999,
#attr :product/actor = 'Naomi Watts',
#attr :product/title = 'The Ring',
product.category = :product.category/horror,
product.rating = 4.5f,
product.man-hours = 9001N,
product.price = 21.99M"
ir (stmt->ir stmt)
_got (ins/run-insert *conn* ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
cnt' (count-entities db' :product/prod-id)
ids (d/q '[:find [?e ...]
:where [?e :product/prod-id 9999]]
db')
ents (->> ids
(map e->m')
(map (fn [m] (dissoc m :db/id)))
(into #{}))]
(is (= (inc cnt) cnt'))
(is (= ents
#{{:product/prod-id 9999
:product/actor "Naomi Watts"
:product/title "The Ring"
:product/category :product.category/horror
:product/rating #float 4.5
:product/man-hours 9001N
:product/price 21.99M}}))))
;;;; UPDATE statements ;;;;
(deftest update-customer-where-customerid
(let [stmt "update customer
set customer.city = 'Springfield'
, customer.state = 'VA'
, customer.zip = '22150'
where customer.customerid = 4858"
db *db*
id (d/q '[:find ?e . :where [?e :customer/customerid 4858]] db)
ent (entity->map db id)
cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
ent' (entity->map db' id)]
(is (= ent'
(assoc ent
:customer/city "Springfield"
:customer/state "VA"
:customer/zip "22150")))
(is (= (count-entities db' :customer/customerid) cnt)
"number of customers remains unchanged")))
(deftest update-products-where-db-id
(let [db *db*
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
e->m (partial entity->map db)
ents (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
stmt "update product
set product.tag = :all-the-things
, product.special = true
, product.price = 1.50M
where db.id "
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
ents' (->> ids (map e->m') (into #{}))]
(is (= ents'
(->> ents
(map (fn [ent]
(assoc ent
:product/tag :all-the-things
:product/special true
:product/price 1.50M)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")
;; assumption: all products originally have special set to false
(when (zero? (count-entities db :product/special true))
(is (= (count ents')
(count-entities db' :product/special true))))))
(deftest update-customer-order-join
(let [stmt "update customer
set #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
(deftest update-product-short-form
(let [stmt "update #attr :product/rating = 3.5f
where #attr :product/prod-id > 6000"
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-product-short-form-by-db-id
(let [stmt "update #attr :product/rating = 3.5f
where #attr :db/id in ("
db *db*
e->m (partial entity->map db)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(< ?pid 6000)]]
db)
stmt' (str stmt (str/join ", " ids) ")")
products (->> ids (map e->m) (into #{}))
cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt')
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m') (into #{}))]
(is (= products'
(->> products
(map (fn [p] (assoc p :product/rating #float 3.5)))
(into #{}))))
(is (= (count-entities db' :product/prod-id) cnt)
"the number of products has not changed")))
(deftest update-customer-order-join-short-form
(let [stmt "update #attr :customer/age = 45
, customer.income = 70000M
where customer.customerid = order.customerid
and order.orderid = 5"
;; this works so long as all attrs in the assignment pair list
;; refer to one (and only one) namespace/table.
db *db*
e->m (partial entity->map db)
the-order (e->m [:order/orderid 5])
the-cust (:order/customer the-order)
order-cnt (count-entities db :order/orderid)
cust-cnt (count-entities db :customer/customerid)
ir (stmt->ir stmt)
_got (upd/run-update *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (= (e->m' [:order/orderid 5])
the-order)
"the order was unaffected")
(is (= (e->m' (:db/id the-cust))
(assoc (e->m (:db/id the-cust))
:customer/age 45
:customer/income 70000M)))
(is (= (count-entities db' :order/orderid) order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :customer/customerid) cust-cnt)
"the number of customers has not changed")))
;;;; DELETE statements ;;;;
(deftest delete-targeting-no-rows-has-no-effect
(let [actor "homer simpson"
stmt (format "delete from product where product.actor = '%s'"
actor)
db *db*
product-cnt (count-entities db :product/prod-id)
;; should be empty
ids (d/q '[:find [?e ...]
:in $ ?doh!
:where [?e :product/actor ?doh!]]
db actor)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (empty? ids) "assumption: where clause matched no rows")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (= db db') "the db itself has not changed")))
(deftest delete-product-by-prod-id
(let [prod-id 9990
stmt (format "delete from product where product.prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-all-products-by-prod-id
;; chose products here because they have no component attrs,
;; i.e., they will not trigger a cascading delete.
(let [stmt "delete from product where product.prod-id > 0"
db *db*
query '[:find [?e ...]
:where [?e :product/prod-id]]
ids (d/q query db)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)]
(is (pos? (count-entities db :product/prod-id))
"assumption: initially, db had products present")
(is (zero? (count-entities db' :product/prod-id))
"the number of products has decreased to zero")
(is (empty? (d/q query db'))
"no products are present in db")))
(deftest delete-products-by-db-id
(let [stmt "delete from product where db.id "
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
query '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 7000)]
[(<= 4000 ?pid)]]
ids (d/q query db)
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
query' '[:find [?e ...] :where [?e :product/prod-id]]
ids' (d/q query' db')
products' (map e->m' ids')]
(is (= (count-entities db' :product/prod-id)
(- product-cnt (count ids)))
"the number of products has decreased appropriately")
(is (empty? (set/intersection
(into #{} ids')
(into #{} ids)))
"targeted :db/ids no longer present in db")
(is (not-any? (fn [{:keys [product/prod-id]}]
(<= 4000 prod-id 7000))
products'))))
(deftest delete-order-cascading-orderlines-by-orderid
(let [stmt "delete from order where order.orderid = 5"
db *db*
e->m (partial entity->map db)
;; an order has many orderlines (as components)
;; an orderline has a product (not component)
;; deleting an order should delete its orderlines but not the products
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
oid (d/q '[:find ?e . :where [?e :order/orderid 5]] db)
order (e->m oid)
olids (d/q '[:find [?e ...] :where [?e :orderline/orderid 5]] db)
orderlines (map e->m olids)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 5]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
products (map e->m pids)
prod-ids (map :product/prod-id products)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (empty? (d/q '[:find ?e :where [?e :order/orderid 5]] db'))
"targeted order is no longer present in db")
(is (empty? (d/q '[:find ?e :where [?e :orderline/orderid 5]] db'))
"targeted order's orderlines are no longer present in db")
(is (not-empty
(d/q '[:find ?e
:in $ [?pid ...]
:where [?e :product/prod-id ?pid]]
db' prod-ids))
"targeted order's orderlines' products are still present in db")
(is (= (count-entities db' :order/orderid)
(dec order-cnt))
"the number of orders has decreased by one")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")))
(deftest delete-product-by-prod-id-short-form
(let [prod-id 1567
stmt (format "delete where #attr :product/prod-id = %d"
prod-id)
db *db*
e->m (partial entity->map db)
query '[:find ?e
:in $ ?pid
:where [?e :product/prod-id ?pid]]
product (e->m [:product/prod-id prod-id])
product-cnt (count-entities db :product/prod-id)
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')]
(is (not-empty (d/q query db prod-id))
"assumption: product targeted for deletion was present initially")
(is (= (count-entities db' :product/prod-id)
(dec product-cnt))
"the number of products has decreased by one")
(is (empty? (d/q query db' prod-id))
"product targeted for deletion was retracted")))
(deftest delete-orderlines-join-by-orderid
(let [stmt "delete from orderline
where orderline.orderid = order.orderid
and order.orderid = 2
and orderline.quantity = 1"
;; note that we are targeting orderlines for deletion, not order
db *db*
e->m (partial entity->map db)
order-cnt (count-entities db :order/orderid)
orderline-cnt (count-entities db :orderline/orderlineid)
product-cnt (count-entities db :product/prod-id)
target-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity 1]] db)
target-orderline-ids (->> target-olids
(map e->m)
(map :orderline/orderlineid))
remain-olids (d/q '[:find [?e ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/quantity ?n]
[(not= ?n 1)]] db)
pids (d/q '[:find [?e ...]
:where
[?ol :orderline/orderid 2]
[?ol :orderline/prod-id ?pid]
[?e :product/prod-id ?pid]] db)
prod-ids (->> pids
(map e->m)
(map :product/prod-id))
ir (stmt->ir stmt)
_got (del/run-delete *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
orderlines' (->> (d/q '[:find [?e ...]
:where [?e :orderline/orderid 2]] db')
(map e->m'))]
(is (= (count-entities db' :order/orderid)
order-cnt)
"the number of orders has not changed")
(is (= (count-entities db' :orderline/orderlineid)
(- orderline-cnt (count target-olids)))
"the number of orderlines has decreased appropriately")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"the number of products has not changed")
(is (not-empty (d/q '[:find ?e :where [?e :order/orderid 2]] db'))
"the associated order is still present")
(is (empty?
(d/q '[:find ?e
:in $ [?olid ...]
:where
[?e :orderline/orderid 2]
[?e :orderline/orderlineid ?olid]]
db' target-orderline-ids))
"targeted orderlines of given order were retracted")
(is (not-any? (fn [{:keys [orderline/quantity]}]
(= 1 quantity))
orderlines')
"none of the quantity orderlines of given order are present")
(is (= (->> (d/q '[:find [?e ...] :where [?e :orderline/orderid 2]] db')
(into #{}))
(->> remain-olids (into #{})))
"all of the non-targeted orderlines are still present")))
;;;; RETRACT statements ;;;;
(deftest retract-product-attr-by-db-id
(let [stmt-fmt "RETRACT product.uuid WHERE db.id = %d"
db *db*
e->m (partial entity->map db)
product-cnt (count-entities db :product/prod-id)
prod-id 8293
id (d/q '[:find ?e .
:in $ ?pid
:where [?e :product/prod-id ?pid]]
db prod-id)
stmt (format stmt-fmt id)
ir (stmt->ir stmt)
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
product' (e->m' id)
attrs' (->> product' keys (into #{}))]
(is (= (get attrs' :product/uuid :nope) :nope)
"the retracted attr is no longer present on target product")
(is (= (count-entities db' :product/uuid)
(dec product-cnt))
"number of products with uuid attr decreased by one")
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")))
(deftest retract-product-attrs-for-many-db-ids
(let [stmt "retract #attr :product/actor,
#attr :product/rating,
#attr :product/url
where db.id "
db *db*
e->m (partial entity->map db)
retracted-attrs [:product/actor :product/rating :product/url]
product-cnt (count-entities db :product/prod-id)
ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(> ?pid 6000)]]
db)
remain-ids (d/q '[:find [?e ...]
:where
[?e :product/prod-id ?pid]
[(<= ?pid 6000)]]
db)
remain-products (->> remain-ids (map e->m))
all-attrs (->> remain-products first keys (into #{}))
kept-attrs (set/difference all-attrs (into #{} retracted-attrs))
stmt' (str stmt (str/join " " ids))
ir (stmt->ir stmt')
_got (rtr/run-retract *conn* db ir {:silent true})
db' (d/db *conn*)
e->m' (partial entity->map db')
products' (->> ids (map e->m'))
remain-products' (->> remain-ids (map e->m'))]
(is (= (count-entities db' :product/prod-id)
product-cnt)
"number of products remains unchanged")
(is (= (into #{} remain-products')
(into #{} remain-products))
"the non-targeted products remain unchanged")
(is (every? (fn [p]
(let [attrs (->> p keys (into #{}))]
(= kept-attrs attrs)))
products')
"the retracted attrs are no longer present on target products")))
(comment
(defn pp-ent [eid]
(db-fixture
(fn []
(->> (entity->map *db* eid)
clojure.pprint/pprint))))
(pp-ent [:product/prod-id 9990])
)
|
[
{
"context": ":body (json/write-str {:nickname account :password password})})\n (println \"Login successful. Redirecting",
"end": 2018,
"score": 0.7668209075927734,
"start": 2010,
"tag": "PASSWORD",
"value": "password"
}
] | src/dbas/eauth/service.clj | hhucn/dbas-eauth | 0 | (ns dbas.eauth.service
(:require [clojure.spec.alpha :as s]
[clojure.core.async :as async :refer [<!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[konserve.filestore :refer [new-fs-store]]
[konserve.core :as k]
[clojure.data.json :as json]
[clj-http.client :as client]
[hiccup.page :as hp]))
(def dbas-url (or (System/getenv "DBAS_URL") "https://dbas.cs.uni-duesseldorf.de/api/login"))
(def store (<!! (new-fs-store (or (System/getenv "EAUTH_STORE") "./store"))))
(def users_auth (atom {}))
;; -----------------------------------------------------------------------------
(defn login-page [{{:keys [redirect_uri account_linking_token]} :query-params}]
(ring-resp/response (hp/html5
(hp/include-css "css/bootstrap.min.css")
[:div.container
[:h1 "Login"]
[:form {:action "/auth" :method :POST}
[:div.form-group
[:label "D-BAS Account"]
[:input.form-control {:name "account"}]]
[:div.form-group
[:label "Password"]
[:input.form-control {:name "password" :type :password}]]
[:input {:name "redirect_uri" :value redirect_uri :type :hidden}]
[:input {:name "account_linking_token" :value account_linking_token :type :hidden}]
[:input {:class "btn btn-primary"
:type :submit}]]])))
(defn auth-page [{{:keys [account password redirect_uri]} :form-params}]
(let [uuid (str (java.util.UUID/randomUUID))
redirect (str redirect_uri "&authorization_code=" uuid)]
(try
(client/post dbas-url
{:body (json/write-str {:nickname account :password password})})
(println "Login successful. Redirecting to" redirect)
(swap! users_auth assoc uuid account)
(ring-resp/redirect redirect)
(catch Exception e
(println "Login not successful. Redirecting to" redirect_uri)
(println e)
(ring-resp/redirect redirect_uri)))))
(defn success-page [{{:keys [recipient sender account_linking]} :json-params :as params}]
(when (s/valid? ::success-params (:json-params params))
(let [auth (:authorization_code account_linking)
status (:status account_linking)
nickname (get @users_auth auth)]
(case status
"linked" (do
(<!! (k/assoc-in store [{:service "facebook"
:app_id (:id recipient)
:user_id (:id sender)}]
nickname))
(swap! users_auth dissoc auth)
(println nickname "linked")
(http/json-response {:status :ok :message "User logged in"}))
"unlinked" (do
(<!! (k/dissoc store {:service "facebook" :app_id (:id recipient) :user_id (:id sender)}))
(println "User unlinked")
(http/json-response {:status :ok :message "User logged out"}))))))
(defn resolve-user [{{:keys [service app_id user_id]} :params :as request}]
(if (s/valid? ::resolve-user-params (:params request))
(if-let [nickname (<!! (k/get-in store [{:service service
:app_id app_id
:user_id user_id}]))]
(do (println "Nickname resolved:" nickname)
(http/json-response {:status :ok, :data {:nickname nickname}}))
(do (println "Could not resolve nickname for: " service app_id user_id)
(http/json-response {:status :error, :data "Could not resolve nickname!"})))
(http/json-response {:status :error, :data "You fucked up your parameters! Try: /resolve-user?service=Facebook&app_id=1456&user_id=2378"})))
(comment
(client/get "http://localhost:8080/resolve-user?service=Facebook&app_id=1144092719067446&user_id=1235572976569567"))
(defn add-user [{json :json-params}]
(if (s/valid? ::add-user-params json)
(do (println "Add" (select-keys json [:service :app_id :user_id]) (:nickname json) "to store.")
(k/assoc-in store [(select-keys json [:service :app_id :user_id])] (:nickname json))
(http/json-response {:status :ok}))
(-> (http/json-response {:status :error :data (s/explain-data ::add-user-params json)})
(assoc :status 400))))
;; -----------------------------------------------------------------------------
(s/def ::id string?)
(s/def ::recipient (s/keys :req-un [::id]))
(s/def ::timestamp pos-int?)
(s/def ::sender (s/keys :req-un [::id]))
(s/def ::authorization_code string?)
(s/def ::status string?)
(s/def ::account_linking (s/keys :req-un [::status]
:opt-un [::authorization_code]))
(s/def ::success-params
(s/keys :req-un [::recipient ::timestamp ::sender ::account_linking]))
(s/def ::service string?)
(s/def ::app_id string?)
(s/def ::user_id string?)
(s/def ::resolve-user-params
(s/keys :req-un [::service ::app_id ::user_id]))
(s/def ::add-user-params
(s/keys :req-un [::service ::app_id ::user_id ::nickname]))
;; -----------------------------------------------------------------------------
(def common-interceptors [(body-params/body-params) http/html-body])
(def routes #{["/login" :get (conj common-interceptors `login-page)]
["/auth" :post (conj common-interceptors `auth-page)]
["/success" :post (conj common-interceptors `success-page)]
["/resolve-user" :get (conj common-interceptors `resolve-user)]
["/add-user" :post (conj common-interceptors `add-user)]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port 1236
::http/container-options {:h2c? true
:h2? false
:ssl? false}})
| 29779 | (ns dbas.eauth.service
(:require [clojure.spec.alpha :as s]
[clojure.core.async :as async :refer [<!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[konserve.filestore :refer [new-fs-store]]
[konserve.core :as k]
[clojure.data.json :as json]
[clj-http.client :as client]
[hiccup.page :as hp]))
(def dbas-url (or (System/getenv "DBAS_URL") "https://dbas.cs.uni-duesseldorf.de/api/login"))
(def store (<!! (new-fs-store (or (System/getenv "EAUTH_STORE") "./store"))))
(def users_auth (atom {}))
;; -----------------------------------------------------------------------------
(defn login-page [{{:keys [redirect_uri account_linking_token]} :query-params}]
(ring-resp/response (hp/html5
(hp/include-css "css/bootstrap.min.css")
[:div.container
[:h1 "Login"]
[:form {:action "/auth" :method :POST}
[:div.form-group
[:label "D-BAS Account"]
[:input.form-control {:name "account"}]]
[:div.form-group
[:label "Password"]
[:input.form-control {:name "password" :type :password}]]
[:input {:name "redirect_uri" :value redirect_uri :type :hidden}]
[:input {:name "account_linking_token" :value account_linking_token :type :hidden}]
[:input {:class "btn btn-primary"
:type :submit}]]])))
(defn auth-page [{{:keys [account password redirect_uri]} :form-params}]
(let [uuid (str (java.util.UUID/randomUUID))
redirect (str redirect_uri "&authorization_code=" uuid)]
(try
(client/post dbas-url
{:body (json/write-str {:nickname account :password <PASSWORD>})})
(println "Login successful. Redirecting to" redirect)
(swap! users_auth assoc uuid account)
(ring-resp/redirect redirect)
(catch Exception e
(println "Login not successful. Redirecting to" redirect_uri)
(println e)
(ring-resp/redirect redirect_uri)))))
(defn success-page [{{:keys [recipient sender account_linking]} :json-params :as params}]
(when (s/valid? ::success-params (:json-params params))
(let [auth (:authorization_code account_linking)
status (:status account_linking)
nickname (get @users_auth auth)]
(case status
"linked" (do
(<!! (k/assoc-in store [{:service "facebook"
:app_id (:id recipient)
:user_id (:id sender)}]
nickname))
(swap! users_auth dissoc auth)
(println nickname "linked")
(http/json-response {:status :ok :message "User logged in"}))
"unlinked" (do
(<!! (k/dissoc store {:service "facebook" :app_id (:id recipient) :user_id (:id sender)}))
(println "User unlinked")
(http/json-response {:status :ok :message "User logged out"}))))))
(defn resolve-user [{{:keys [service app_id user_id]} :params :as request}]
(if (s/valid? ::resolve-user-params (:params request))
(if-let [nickname (<!! (k/get-in store [{:service service
:app_id app_id
:user_id user_id}]))]
(do (println "Nickname resolved:" nickname)
(http/json-response {:status :ok, :data {:nickname nickname}}))
(do (println "Could not resolve nickname for: " service app_id user_id)
(http/json-response {:status :error, :data "Could not resolve nickname!"})))
(http/json-response {:status :error, :data "You fucked up your parameters! Try: /resolve-user?service=Facebook&app_id=1456&user_id=2378"})))
(comment
(client/get "http://localhost:8080/resolve-user?service=Facebook&app_id=1144092719067446&user_id=1235572976569567"))
(defn add-user [{json :json-params}]
(if (s/valid? ::add-user-params json)
(do (println "Add" (select-keys json [:service :app_id :user_id]) (:nickname json) "to store.")
(k/assoc-in store [(select-keys json [:service :app_id :user_id])] (:nickname json))
(http/json-response {:status :ok}))
(-> (http/json-response {:status :error :data (s/explain-data ::add-user-params json)})
(assoc :status 400))))
;; -----------------------------------------------------------------------------
(s/def ::id string?)
(s/def ::recipient (s/keys :req-un [::id]))
(s/def ::timestamp pos-int?)
(s/def ::sender (s/keys :req-un [::id]))
(s/def ::authorization_code string?)
(s/def ::status string?)
(s/def ::account_linking (s/keys :req-un [::status]
:opt-un [::authorization_code]))
(s/def ::success-params
(s/keys :req-un [::recipient ::timestamp ::sender ::account_linking]))
(s/def ::service string?)
(s/def ::app_id string?)
(s/def ::user_id string?)
(s/def ::resolve-user-params
(s/keys :req-un [::service ::app_id ::user_id]))
(s/def ::add-user-params
(s/keys :req-un [::service ::app_id ::user_id ::nickname]))
;; -----------------------------------------------------------------------------
(def common-interceptors [(body-params/body-params) http/html-body])
(def routes #{["/login" :get (conj common-interceptors `login-page)]
["/auth" :post (conj common-interceptors `auth-page)]
["/success" :post (conj common-interceptors `success-page)]
["/resolve-user" :get (conj common-interceptors `resolve-user)]
["/add-user" :post (conj common-interceptors `add-user)]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port 1236
::http/container-options {:h2c? true
:h2? false
:ssl? false}})
| true | (ns dbas.eauth.service
(:require [clojure.spec.alpha :as s]
[clojure.core.async :as async :refer [<!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[konserve.filestore :refer [new-fs-store]]
[konserve.core :as k]
[clojure.data.json :as json]
[clj-http.client :as client]
[hiccup.page :as hp]))
(def dbas-url (or (System/getenv "DBAS_URL") "https://dbas.cs.uni-duesseldorf.de/api/login"))
(def store (<!! (new-fs-store (or (System/getenv "EAUTH_STORE") "./store"))))
(def users_auth (atom {}))
;; -----------------------------------------------------------------------------
(defn login-page [{{:keys [redirect_uri account_linking_token]} :query-params}]
(ring-resp/response (hp/html5
(hp/include-css "css/bootstrap.min.css")
[:div.container
[:h1 "Login"]
[:form {:action "/auth" :method :POST}
[:div.form-group
[:label "D-BAS Account"]
[:input.form-control {:name "account"}]]
[:div.form-group
[:label "Password"]
[:input.form-control {:name "password" :type :password}]]
[:input {:name "redirect_uri" :value redirect_uri :type :hidden}]
[:input {:name "account_linking_token" :value account_linking_token :type :hidden}]
[:input {:class "btn btn-primary"
:type :submit}]]])))
(defn auth-page [{{:keys [account password redirect_uri]} :form-params}]
(let [uuid (str (java.util.UUID/randomUUID))
redirect (str redirect_uri "&authorization_code=" uuid)]
(try
(client/post dbas-url
{:body (json/write-str {:nickname account :password PI:PASSWORD:<PASSWORD>END_PI})})
(println "Login successful. Redirecting to" redirect)
(swap! users_auth assoc uuid account)
(ring-resp/redirect redirect)
(catch Exception e
(println "Login not successful. Redirecting to" redirect_uri)
(println e)
(ring-resp/redirect redirect_uri)))))
(defn success-page [{{:keys [recipient sender account_linking]} :json-params :as params}]
(when (s/valid? ::success-params (:json-params params))
(let [auth (:authorization_code account_linking)
status (:status account_linking)
nickname (get @users_auth auth)]
(case status
"linked" (do
(<!! (k/assoc-in store [{:service "facebook"
:app_id (:id recipient)
:user_id (:id sender)}]
nickname))
(swap! users_auth dissoc auth)
(println nickname "linked")
(http/json-response {:status :ok :message "User logged in"}))
"unlinked" (do
(<!! (k/dissoc store {:service "facebook" :app_id (:id recipient) :user_id (:id sender)}))
(println "User unlinked")
(http/json-response {:status :ok :message "User logged out"}))))))
(defn resolve-user [{{:keys [service app_id user_id]} :params :as request}]
(if (s/valid? ::resolve-user-params (:params request))
(if-let [nickname (<!! (k/get-in store [{:service service
:app_id app_id
:user_id user_id}]))]
(do (println "Nickname resolved:" nickname)
(http/json-response {:status :ok, :data {:nickname nickname}}))
(do (println "Could not resolve nickname for: " service app_id user_id)
(http/json-response {:status :error, :data "Could not resolve nickname!"})))
(http/json-response {:status :error, :data "You fucked up your parameters! Try: /resolve-user?service=Facebook&app_id=1456&user_id=2378"})))
(comment
(client/get "http://localhost:8080/resolve-user?service=Facebook&app_id=1144092719067446&user_id=1235572976569567"))
(defn add-user [{json :json-params}]
(if (s/valid? ::add-user-params json)
(do (println "Add" (select-keys json [:service :app_id :user_id]) (:nickname json) "to store.")
(k/assoc-in store [(select-keys json [:service :app_id :user_id])] (:nickname json))
(http/json-response {:status :ok}))
(-> (http/json-response {:status :error :data (s/explain-data ::add-user-params json)})
(assoc :status 400))))
;; -----------------------------------------------------------------------------
(s/def ::id string?)
(s/def ::recipient (s/keys :req-un [::id]))
(s/def ::timestamp pos-int?)
(s/def ::sender (s/keys :req-un [::id]))
(s/def ::authorization_code string?)
(s/def ::status string?)
(s/def ::account_linking (s/keys :req-un [::status]
:opt-un [::authorization_code]))
(s/def ::success-params
(s/keys :req-un [::recipient ::timestamp ::sender ::account_linking]))
(s/def ::service string?)
(s/def ::app_id string?)
(s/def ::user_id string?)
(s/def ::resolve-user-params
(s/keys :req-un [::service ::app_id ::user_id]))
(s/def ::add-user-params
(s/keys :req-un [::service ::app_id ::user_id ::nickname]))
;; -----------------------------------------------------------------------------
(def common-interceptors [(body-params/body-params) http/html-body])
(def routes #{["/login" :get (conj common-interceptors `login-page)]
["/auth" :post (conj common-interceptors `auth-page)]
["/success" :post (conj common-interceptors `success-page)]
["/resolve-user" :get (conj common-interceptors `resolve-user)]
["/add-user" :post (conj common-interceptors `add-user)]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port 1236
::http/container-options {:h2c? true
:h2? false
:ssl? false}})
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-07-27\"\n :doc \"Tests for zana.te",
"end": 105,
"score": 0.9998798966407776,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/test/clojure/zana/test/collections/sets.clj | wahpenayo/zana | 2 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-07-27"
:doc "Tests for zana.test.collections.maps." }
zana.test.collections.sets
(:require [clojure.test :as t]
[zana.api :as z]))
;;------------------------------------------------------------------------------
(t/deftest test-distinct-identity
(t/testing
"distinct identity"
(let [a [1 2 3]
b (vector 1 2 3)
s (z/distinct-identity [a b])]
(t/is (not (identical? a b)))
(t/is (= a b))
(t/is (= 2 (z/count s)))
)))
;;------------------------------------------------------------------------------ | 354 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-07-27"
:doc "Tests for zana.test.collections.maps." }
zana.test.collections.sets
(:require [clojure.test :as t]
[zana.api :as z]))
;;------------------------------------------------------------------------------
(t/deftest test-distinct-identity
(t/testing
"distinct identity"
(let [a [1 2 3]
b (vector 1 2 3)
s (z/distinct-identity [a b])]
(t/is (not (identical? a b)))
(t/is (= a b))
(t/is (= 2 (z/count s)))
)))
;;------------------------------------------------------------------------------ | true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-07-27"
:doc "Tests for zana.test.collections.maps." }
zana.test.collections.sets
(:require [clojure.test :as t]
[zana.api :as z]))
;;------------------------------------------------------------------------------
(t/deftest test-distinct-identity
(t/testing
"distinct identity"
(let [a [1 2 3]
b (vector 1 2 3)
s (z/distinct-identity [a b])]
(t/is (not (identical? a b)))
(t/is (= a b))
(t/is (= 2 (z/count s)))
)))
;;------------------------------------------------------------------------------ |
[
{
"context": "lection-position!`\n (let [data-keys [:dataset_query :description :display :name\n ",
"end": 12343,
"score": 0.7234708666801453,
"start": 12330,
"tag": "KEY",
"value": "dataset_query"
}
] | c#-metabase/src/metabase/api/card.clj | hanakhry/Crime_Admin | 0 | (ns metabase.api.card
"/api/card endpoints."
(:require [cheshire.core :as json]
[clojure.core.async :as a]
[clojure.tools.logging :as log]
[compojure.core :refer [DELETE GET POST PUT]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.api.dataset :as dataset-api]
[metabase.async.util :as async.u]
[metabase.email.messages :as messages]
[metabase.events :as events]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.models.card :as card :refer [Card]]
[metabase.models.card-favorite :refer [CardFavorite]]
[metabase.models.collection :as collection :refer [Collection]]
[metabase.models.database :refer [Database]]
[metabase.models.interface :as mi]
[metabase.models.pulse :as pulse :refer [Pulse]]
[metabase.models.query :as query]
[metabase.models.query.permissions :as query-perms]
[metabase.models.revision.last-edit :as last-edit]
[metabase.models.table :refer [Table]]
[metabase.models.view-log :refer [ViewLog]]
[metabase.public-settings :as public-settings]
[metabase.query-processor :as qp]
[metabase.query-processor.async :as qp.async]
[metabase.query-processor.middleware.constraints :as constraints]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.middleware.results-metadata :as results-metadata]
[metabase.query-processor.pivot :as qp.pivot]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.query-processor.util :as qputil]
[metabase.related :as related]
[metabase.sync.analyze.query-results :as qr]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]])
(:import clojure.core.async.impl.channels.ManyToManyChannel
java.util.UUID
metabase.models.card.CardInstance))
;;; --------------------------------------------------- Hydration ----------------------------------------------------
(defn hydrate-favorites
"Efficiently add `favorite` status for a large collection of `Cards`."
{:batched-hydrate :favorite}
[cards]
(when (seq cards)
(let [favorite-card-ids (db/select-field :card_id CardFavorite
:owner_id api/*current-user-id*
:card_id [:in (map :id cards)])]
(for [card cards]
(assoc card :favorite (contains? favorite-card-ids (:id card)))))))
;;; ----------------------------------------------- Filtered Fetch Fns -----------------------------------------------
(defmulti ^:private cards-for-filter-option*
{:arglists '([filter-option & args])}
(fn [filter-option & _]
(keyword filter-option)))
;; return all Cards. This is the default filter option.
(defmethod cards-for-filter-option* :all
[_]
(db/select Card, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return Cards created by the current user
(defmethod cards-for-filter-option* :mine
[_]
(db/select Card, :creator_id api/*current-user-id*, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return all Cards favorited by the current user.
(defmethod cards-for-filter-option* :fav
[_]
(let [cards (for [{{:keys [archived], :as card} :card} (hydrate (db/select [CardFavorite :card_id]
:owner_id api/*current-user-id*)
:card)
:when (not archived)]
card)]
(sort-by :name cards)))
;; Return all Cards belonging to Database with `database-id`.
(defmethod cards-for-filter-option* :database
[_ database-id]
(db/select Card, :database_id database-id, :archived false, {:order-by [[:%lower.name :asc]]}))
;; Return all Cards belonging to `Table` with `table-id`.
(defmethod cards-for-filter-option* :table
[_ table-id]
(db/select Card, :table_id table-id, :archived false, {:order-by [[:%lower.name :asc]]}))
(s/defn ^:private cards-with-ids :- (s/maybe [CardInstance])
"Return unarchived Cards with `card-ids`.
Make sure cards are returned in the same order as `card-ids`; `[in card-ids]` won't preserve the order."
[card-ids :- [su/IntGreaterThanZero]]
(when (seq card-ids)
(let [card-id->card (u/key-by :id (db/select Card, :id [:in (set card-ids)], :archived false))]
(filter identity (map card-id->card card-ids)))))
;; Return the 10 Cards most recently viewed by the current user, sorted by how recently they were viewed.
(defmethod cards-for-filter-option* :recent
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%max.timestamp :max]]
:model "card"
:user_id api/*current-user-id*
{:group-by [:model_id]
:order-by [[:max :desc]]
:limit 10}))))
;; All Cards, sorted by popularity (the total number of times they are viewed in `ViewLogs`). (yes, this isn't
;; actually filtering anything, but for the sake of simplicitiy it is included amongst the filter options for the time
;; being).
(defmethod cards-for-filter-option* :popular
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%count.* :count]]
:model "card"
{:group-by [:model_id]
:order-by [[:count :desc]]}))))
;; Cards that have been archived.
(defmethod cards-for-filter-option* :archived
[_]
(db/select Card, :archived true, {:order-by [[:%lower.name :asc]]}))
(defn- cards-for-filter-option [filter-option model-id-or-nil]
(-> (apply cards-for-filter-option* (or filter-option :all) (when model-id-or-nil [model-id-or-nil]))
(hydrate :creator :collection :favorite)))
;;; -------------------------------------------- Fetching a Card or Cards --------------------------------------------
(def ^:private CardFilterOption
"Schema for a valid card filter option."
(apply s/enum (map name (keys (methods cards-for-filter-option*)))))
(api/defendpoint GET "/"
"Get all the Cards. Option filter param `f` can be used to change the set of Cards that are returned; default is
`all`, but other options include `mine`, `fav`, `database`, `table`, `recent`, `popular`, and `archived`. See
corresponding implementation functions above for the specific behavior of each filter option. :card_index:"
[f model_id]
{f (s/maybe CardFilterOption)
model_id (s/maybe su/IntGreaterThanZero)}
(let [f (keyword f)]
(when (contains? #{:database :table} f)
(api/checkp (integer? model_id) "model_id" (format "model_id is a required parameter when filter mode is '%s'"
(name f)))
(case f
:database (api/read-check Database model_id)
:table (api/read-check Database (db/select-one-field :db_id Table, :id model_id))))
(let [cards (filter mi/can-read? (cards-for-filter-option f model_id))
last-edit-info (:card (last-edit/fetch-last-edited-info {:card-ids (map :id cards)}))]
(into []
(map (fn [{:keys [id] :as card}]
(if-let [edit-info (get last-edit-info id)]
(assoc card :last-edit-info edit-info)
card)))
cards))))
(api/defendpoint GET "/:id"
"Get `Card` with ID."
[id]
(u/prog1 (-> (Card id)
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
api/read-check
(last-edit/with-last-edit-info :card))
(events/publish-event! :card-read (assoc <> :actor_id api/*current-user-id*))))
;;; -------------------------------------------------- Saving Cards --------------------------------------------------
;; When a new Card is saved, we wouldn't normally have the results metadata for it until the first time its query is
;; ran. As a workaround, we'll calculate this metadata and return it with all query responses, and then let the
;; frontend pass it back to us when saving or updating a Card. As a basic step to make sure the Metadata is valid
;; we'll also pass a simple checksum and have the frontend pass it back to us. See the QP `results-metadata`
;; middleware namespace for more details
(s/defn ^:private result-metadata-async :- ManyToManyChannel
"Get the right results metadata for this `card`, and return them in a channel. We'll check to see whether the
`metadata` passed in seems valid,and, if so, return a channel that returns the value as-is; otherwise, we'll run the
query ourselves to get the right values, and return a channel where you can listen for the results."
[query metadata checksum]
(let [valid-metadata? (and (results-metadata/valid-checksum? metadata checksum)
(s/validate qr/ResultsMetadata metadata))]
(log/info
(cond
valid-metadata? (trs "Card results metadata passed in to API is VALID. Thanks!")
metadata (trs "Card results metadata passed in to API is INVALID. Running query to fetch correct metadata.")
:else (trs "Card results metadata passed in to API is MISSING. Running query to fetch correct metadata.")))
(if valid-metadata?
(a/to-chan [metadata])
(qp.async/result-metadata-for-query-async query))))
(defn check-data-permissions-for-query
"Make sure the Current User has the appropriate *data* permissions to run `query`. We don't want Users saving Cards
with queries they wouldn't be allowed to run!"
[query]
{:pre [(map? query)]}
(when-not (query-perms/can-run-query? query)
(let [required-perms (try
(query-perms/perms-set query :throw-exceptions? true)
(catch Throwable e
e))]
(throw (ex-info (tru "You cannot save this Question because you do not have permissions to run its query.")
{:status-code 403
:query query
:required-perms (if (instance? Throwable required-perms)
:error
required-perms)
:actual-perms @api/*current-user-permissions-set*}
(when (instance? Throwable required-perms)
required-perms))))))
(defn- save-new-card-async!
"Save `card-data` as a new Card on a separate thread. Returns a channel to fetch the response; closing this channel
will cancel the save."
[card-data user]
(async.u/cancelable-thread
(let [card (db/transaction
;; Adding a new card at `collection_position` could cause other cards in this
;; collection to change position, check that and fix it if needed
(api/maybe-reconcile-collection-position! card-data)
(db/insert! Card card-data))]
(events/publish-event! :card-create card)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it
;; currently has with returned one -- See #4283
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user user))))))
(defn- create-card-async!
"Create a new Card asynchronously. Returns a channel for fetching the newly created Card, or an Exception if one was
thrown. Closing this channel before it finishes will cancel the Card creation."
[{:keys [dataset_query result_metadata metadata_checksum], :as card-data}]
;; `zipmap` instead of `select-keys` because we want to get `nil` values for keys that aren't present. Required by
;; `api/maybe-reconcile-collection-position!`
(let [data-keys [:dataset_query :description :display :name
:visualization_settings :collection_id :collection_position]
card-data (assoc (zipmap data-keys (map card-data data-keys))
:creator_id api/*current-user-id*)
result-metadata-chan (result-metadata-async dataset_query result_metadata metadata_checksum)
out-chan (a/promise-chan)]
(a/go
(try
(let [card-data (assoc card-data :result_metadata (a/<! result-metadata-chan))]
(a/close! result-metadata-chan)
;; now do the actual saving on a separate thread so we don't tie up our precious core.async thread. Pipe the
;; result into `out-chan`.
(async.u/promise-pipe (save-new-card-async! card-data @api/*current-user*) out-chan))
(catch Throwable e
(a/put! out-chan e)
(a/close! out-chan))))
;; Return a channel
out-chan))
(api/defendpoint ^:returns-chan POST "/"
"Create a new `Card`."
[:as {{:keys [collection_id collection_position dataset_query description display metadata_checksum name
result_metadata visualization_settings], :as body} :body}]
{name su/NonBlankString
description (s/maybe su/NonBlankString)
display su/NonBlankString
visualization_settings su/Map
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
;; check that we have permissions to run the query that we're trying to save
(check-data-permissions-for-query dataset_query)
;; check that we have permissions for the collection we're trying to save this card to, if applicable
(collection/check-write-perms-for-collection collection_id)
;; Return a channel that can be used to fetch the results asynchronously
(create-card-async! body))
;;; ------------------------------------------------- Updating Cards -------------------------------------------------
(defn- check-allowed-to-modify-query
"If the query is being modified, check that we have data permissions to run the query."
[card-before-updates card-updates]
(let [card-updates (m/update-existing card-updates :dataset_query mbql.normalize/normalize)]
(when (api/column-will-change? :dataset_query card-before-updates card-updates)
(check-data-permissions-for-query (:dataset_query card-updates)))))
(defn- check-allowed-to-change-embedding
"You must be a superuser to change the value of `enable_embedding` or `embedding_params`. Embedding must be
enabled."
[card-before-updates card-updates]
(when (or (api/column-will-change? :enable_embedding card-before-updates card-updates)
(api/column-will-change? :embedding_params card-before-updates card-updates))
(api/check-embedding-enabled)
(api/check-superuser)))
(defn- result-metadata-for-updating-async
"If `card`'s query is being updated, return the value that should be saved for `result_metadata`. This *should* be
passed in to the API; if so, verifiy that it was correct (the checksum is valid); if not, go fetch it. If the query
has not changed, this returns a closed channel (so you will get `nil` when you attempt to fetch the result, and
will know not to update the value in the DB.)
Either way, results are returned asynchronously on a channel."
[card query metadata checksum]
(if (and query
(not= query (:dataset_query card)))
(result-metadata-async query metadata checksum)
(u/prog1 (a/chan)
(a/close! <>))))
(defn- publish-card-update!
"Publish an event appropriate for the update(s) done to this CARD (`:card-update`, or archiving/unarchiving
events)."
[card archived?]
(let [event (cond
;; card was archived
(and archived?
(not (:archived card))) :card-archive
;; card was unarchived
(and (false? archived?)
(:archived card)) :card-unarchive
:else :card-update)]
(events/publish-event! event (assoc card :actor_id api/*current-user-id*))))
(defn- card-archived? [old-card new-card]
(and (not (:archived old-card))
(:archived new-card)))
(defn- line-area-bar? [display]
(contains? #{:line :area :bar} display))
(defn- progress? [display]
(= :progress display))
(defn- allows-rows-alert? [display]
(not (contains? #{:line :bar :area :progress} display)))
(defn- display-change-broke-alert?
"Alerts no longer make sense when the kind of question being alerted on significantly changes. Setting up an alert
when a time series query reaches 10 is no longer valid if the question switches from a line graph to a table. This
function goes through various scenarios that render an alert no longer valid"
[{old-display :display} {new-display :display}]
(when-not (= old-display new-display)
(or
;; Did the alert switch from a table type to a line/bar/area/progress graph type?
(and (allows-rows-alert? old-display)
(or (line-area-bar? new-display)
(progress? new-display)))
;; Switching from a line/bar/area to another type that is not those three invalidates the alert
(and (line-area-bar? old-display)
(not (line-area-bar? new-display)))
;; Switching from a progress graph to anything else invalidates the alert
(and (progress? old-display)
(not (progress? new-display))))))
(defn- goal-missing?
"If we had a goal before, and now it's gone, the alert is no longer valid"
[old-card new-card]
(and
(get-in old-card [:visualization_settings :graph.goal_value])
(not (get-in new-card [:visualization_settings :graph.goal_value]))))
(defn- multiple-breakouts?
"If there are multiple breakouts and a goal, we don't know which breakout to compare to the goal, so it invalidates
the alert"
[{:keys [display] :as new-card}]
(and (or (line-area-bar? display)
(progress? display))
(< 1 (count (get-in new-card [:dataset_query :query :breakout])))))
(defn- delete-alert-and-notify!
"Removes all of the alerts and notifies all of the email recipients of the alerts change via `NOTIFY-FN!`"
[notify-fn! alerts]
(db/delete! Pulse :id [:in (map :id alerts)])
(doseq [{:keys [channels] :as alert} alerts
:let [email-channel (m/find-first #(= :email (:channel_type %)) channels)]]
(doseq [recipient (:recipients email-channel)]
(notify-fn! alert recipient @api/*current-user*))))
(defn delete-alert-and-notify-archived!
"Removes all alerts and will email each recipient letting them know"
[alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-archived-email! alerts))
(defn- delete-alert-and-notify-changed! [alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-changed-email! alerts))
(defn- delete-alerts-if-needed! [old-card {card-id :id :as new-card}]
;; If there are alerts, we need to check to ensure the card change doesn't invalidate the alert
(when-let [alerts (seq (pulse/retrieve-alerts-for-cards card-id))]
(cond
(card-archived? old-card new-card)
(delete-alert-and-notify-archived! alerts)
(or (display-change-broke-alert? old-card new-card)
(goal-missing? old-card new-card)
(multiple-breakouts? new-card))
(delete-alert-and-notify-changed! alerts)
;; The change doesn't invalidate the alert, do nothing
:else
nil)))
(defn- update-card-async!
"Update a Card asynchronously. Returns a `core.async` promise channel that will return updated Card."
[{:keys [id], :as card-before-update} {:keys [archived], :as card-updates}]
;; don't block our precious core.async thread, run the actual DB updates on a separate thread
(async.u/cancelable-thread
;; Setting up a transaction here so that we don't get a partially reconciled/updated card.
(db/transaction
(api/maybe-reconcile-collection-position! card-before-update card-updates)
;; ok, now save the Card
(db/update! Card id
;; `collection_id` and `description` can be `nil` (in order to unset them). Other values should only be
;; modified if they're passed in as non-nil
(u/select-keys-when card-updates
:present #{:collection_id :collection_position :description}
:non-nil #{:dataset_query :display :name :visualization_settings :archived :enable_embedding
:embedding_params :result_metadata})))
;; Fetch the updated Card from the DB
(let [card (Card id)]
(delete-alerts-if-needed! card-before-update card)
(publish-card-update! card archived)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it currently
;; has with returned one -- See #4142
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user @api/*current-user*))))))
(api/defendpoint ^:returns-chan PUT "/:id"
"Update a `Card`."
[id :as {{:keys [dataset_query description display name visualization_settings archived collection_id
collection_position enable_embedding embedding_params result_metadata metadata_checksum]
:as card-updates} :body}]
{name (s/maybe su/NonBlankString)
dataset_query (s/maybe su/Map)
display (s/maybe su/NonBlankString)
description (s/maybe s/Str)
visualization_settings (s/maybe su/Map)
archived (s/maybe s/Bool)
enable_embedding (s/maybe s/Bool)
embedding_params (s/maybe su/EmbeddingParams)
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
(let [card-before-update (api/write-check Card id)]
;; Do various permissions checks
(collection/check-allowed-to-change-collection card-before-update card-updates)
(check-allowed-to-modify-query card-before-update card-updates)
(check-allowed-to-change-embedding card-before-update card-updates)
;; make sure we have the correct `result_metadata`
(let [result-metadata-chan (result-metadata-for-updating-async
card-before-update
dataset_query
result_metadata
metadata_checksum)
out-chan (a/promise-chan)]
;; asynchronously wait for our updated result metadata, then after that call `update-card-async!`, which is done
;; on a non-core.async thread. Pipe the results of that into `out-chan`.
(a/go
(try
(let [card-updates (assoc card-updates :result_metadata (a/<! result-metadata-chan))]
(async.u/promise-pipe (update-card-async! card-before-update card-updates) out-chan))
(finally
(a/close! result-metadata-chan))))
out-chan)))
;;; ------------------------------------------------- Deleting Cards -------------------------------------------------
;; TODO - Pretty sure this endpoint is not actually used any more, since Cards are supposed to get archived (via PUT
;; /api/card/:id) instead of deleted. Should we remove this?
(api/defendpoint DELETE "/:id"
"Delete a Card. (DEPRECATED -- don't delete a Card anymore -- archive it instead.)"
[id]
(log/warn (tru "DELETE /api/card/:id is deprecated. Instead, change its `archived` value via PUT /api/card/:id."))
(let [card (api/write-check Card id)]
(db/delete! Card :id id)
(events/publish-event! :card-delete (assoc card :actor_id api/*current-user-id*)))
api/generic-204-no-content)
;;; --------------------------------------------------- Favoriting ---------------------------------------------------
(api/defendpoint POST "/:card-id/favorite"
"Favorite a Card."
[card-id]
(api/read-check Card card-id)
(db/insert! CardFavorite :card_id card-id, :owner_id api/*current-user-id*))
(api/defendpoint DELETE "/:card-id/favorite"
"Unfavorite a Card."
[card-id]
(api/read-check Card card-id)
(api/let-404 [id (db/select-one-id CardFavorite :card_id card-id, :owner_id api/*current-user-id*)]
(db/delete! CardFavorite, :id id))
api/generic-204-no-content)
;;; -------------------------------------------- Bulk Collections Update ---------------------------------------------
(defn- update-collection-positions!
"For cards that have a position in the previous collection, add them to the end of the new collection, trying to
preseve the order from the original collections. Note it's possible for there to be multiple collections
(and thus duplicate collection positions) merged into this new collection. No special tie breaker logic for when
that's the case, just use the order the DB returned it in"
[new-collection-id-or-nil cards]
;; Sorting by `:collection_position` to ensure lower position cards are appended first
(let [sorted-cards (sort-by :collection_position cards)
max-position-result (db/select-one [Card [:%max.collection_position :max_position]]
:collection_id new-collection-id-or-nil)
;; collection_position for the next card in the collection
starting-position (inc (get max-position-result :max_position 0))]
;; This is using `map` but more like a `doseq` with multiple seqs. Wrapping this in a `doall` as we don't want it
;; to be lazy and we're just going to discard the results
(doall
(map (fn [idx {:keys [collection_id collection_position] :as card}]
;; We are removing this card from `collection_id` so we need to reconcile any
;; `collection_position` entries left behind by this move
(api/reconcile-position-for-collection! collection_id collection_position nil)
;; Now we can update the card with the new collection and a new calculated position
;; that appended to the end
(db/update! Card (u/the-id card)
:collection_position idx
:collection_id new-collection-id-or-nil))
;; These are reversed because of the classic issue when removing an item from array. If we remove an
;; item at index 1, everthing above index 1 will get decremented. By reversing our processing order we
;; can avoid changing the index of cards we haven't yet updated
(reverse (range starting-position (+ (count sorted-cards) starting-position)))
(reverse sorted-cards)))))
(defn- move-cards-to-collection! [new-collection-id-or-nil card-ids]
;; if moving to a collection, make sure we have write perms for it
(when new-collection-id-or-nil
(api/write-check Collection new-collection-id-or-nil))
;; for each affected card...
(when (seq card-ids)
(let [cards (db/select [Card :id :collection_id :collection_position :dataset_query]
{:where [:and [:in :id (set card-ids)]
[:or [:not= :collection_id new-collection-id-or-nil]
(when new-collection-id-or-nil
[:= :collection_id nil])]]})] ; poisioned NULLs = ick
;; ...check that we have write permissions for it...
(doseq [card cards]
(api/write-check card))
;; ...and check that we have write permissions for the old collections if applicable
(doseq [old-collection-id (set (filter identity (map :collection_id cards)))]
(api/write-check Collection old-collection-id))
;; Ensure all of the card updates occur in a transaction. Read commited (the default) really isn't what we want
;; here. We are querying for the max card position for a given collection, then using that to base our position
;; changes if the cards are moving to a different collection. Without repeatable read here, it's possible we'll
;; get duplicates
(db/transaction
;; If any of the cards have a `:collection_position`, we'll need to fixup the old collection now that the cards
;; are gone and update the position in the new collection
(when-let [cards-with-position (seq (filter :collection_position cards))]
(update-collection-positions! new-collection-id-or-nil cards-with-position))
;; ok, everything checks out. Set the new `collection_id` for all the Cards that haven't been updated already
(when-let [cards-without-position (seq (for [card cards
:when (not (:collection_position card))]
(u/the-id card)))]
(db/update-where! Card {:id [:in (set cards-without-position)]}
:collection_id new-collection-id-or-nil))))))
(api/defendpoint POST "/collections"
"Bulk update endpoint for Card Collections. Move a set of `Cards` with CARD_IDS into a `Collection` with
COLLECTION_ID, or remove them from any Collections by passing a `null` COLLECTION_ID."
[:as {{:keys [card_ids collection_id]} :body}]
{card_ids [su/IntGreaterThanZero], collection_id (s/maybe su/IntGreaterThanZero)}
(move-cards-to-collection! collection_id card_ids)
{:status :ok})
;;; ------------------------------------------------ Running a Query -------------------------------------------------
(defn- query-magic-ttl
"Compute a 'magic' cache TTL time (in seconds) for QUERY by multipling its historic average execution times by the
`query-caching-ttl-ratio`. If the TTL is less than a second, this returns `nil` (i.e., the cache should not be
utilized.)"
[query]
(when-let [average-duration (query/average-execution-time-ms (qputil/query-hash query))]
(let [ttl-seconds (Math/round (float (/ (* average-duration (public-settings/query-caching-ttl-ratio))
1000.0)))]
(when-not (zero? ttl-seconds)
(log/info (trs "Question''s average execution duration is {0}; using ''magic'' TTL of {1}"
(u/format-milliseconds average-duration) (u/format-seconds ttl-seconds))
(u/emoji "💾"))
ttl-seconds))))
(defn query-for-card
"Generate a query for a saved Card"
[{query :dataset_query
:as card} parameters constraints middleware]
(let [query (-> query
;; don't want default constraints overridding anything that's already there
(m/dissoc-in [:middleware :add-default-userland-constraints?])
(assoc :constraints constraints
:parameters parameters
:middleware middleware))
ttl (when (public-settings/enable-query-caching)
(or (:cache_ttl card)
(query-magic-ttl query)))]
(assoc query :cache-ttl ttl)))
(defn run-query-for-card-async
"Run the query for Card with `parameters` and `constraints`, and return results in a `StreamingResponse` that should
be returned as the result of an API endpoint fn. Will throw an Exception if preconditions (such as read perms) are
not met before returning the `StreamingResponse`."
[card-id export-format
& {:keys [parameters constraints context dashboard-id middleware qp-runner run ignore_cache]
:or {constraints constraints/default-query-constraints
context :question
qp-runner qp/process-query-and-save-execution!}}]
{:pre [(u/maybe? sequential? parameters)]}
(let [run (or run
;; param `run` can be used to control how the query is ran, e.g. if you need to
;; customize the `context` passed to the QP
(^:once fn* [query info]
(qp.streaming/streaming-response [context export-format (u/slugify (:card-name info))]
(binding [qp.perms/*card-id* card-id]
(qp-runner query info context)))))
card (api/read-check (db/select-one [Card :name :dataset_query :cache_ttl :collection_id] :id card-id))
query (-> (assoc (query-for-card card parameters constraints middleware)
:async? true)
(update :middleware (fn [middleware]
(merge
{:js-int-to-string? true :ignore-cached-results? ignore_cache}
middleware))))
info {:executed-by api/*current-user-id*
:context context
:card-id card-id
:card-name (:name card)
:dashboard-id dashboard-id}]
(api/check-not-archived card)
(run query info)))
(api/defendpoint ^:streaming POST "/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache], :or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async
card-id :api
:parameters parameters,
:ignore_cache ignore_cache
:middleware {:process-viz-settings? false}))
(api/defendpoint ^:streaming POST "/:card-id/query/:export-format"
"Run the query associated with a Card, and return its results as a file in the specified format. Note that this
expects the parameters as serialized JSON in the 'parameters' parameter"
[card-id export-format :as {{:keys [parameters]} :params}]
{parameters (s/maybe su/JSONString)
export-format dataset-api/ExportFormat}
(run-query-for-card-async
card-id export-format
:parameters (json/parse-string parameters keyword)
:constraints nil
:context (dataset-api/export-format->context export-format)
:middleware {:process-viz-settings? true
:skip-results-metadata? true
:ignore-cached-results? true
:format-rows? false
:js-int-to-string? false}))
;;; ----------------------------------------------- Sharing is Caring ------------------------------------------------
(api/defendpoint POST "/:card-id/public_link"
"Generate publicly-accessible links for this Card. Returns UUID to be used in public links. (If this Card has
already been shared, it will return the existing public link rather than creating a new one.) Public sharing must
be enabled."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-not-archived (api/read-check Card card-id))
{:uuid (or (db/select-one-field :public_uuid Card :id card-id)
(u/prog1 (str (UUID/randomUUID))
(db/update! Card card-id
:public_uuid <>
:made_public_by_id api/*current-user-id*)))})
(api/defendpoint DELETE "/:card-id/public_link"
"Delete the publicly-accessible link to this Card."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-exists? Card :id card-id, :public_uuid [:not= nil])
(db/update! Card card-id
:public_uuid nil
:made_public_by_id nil)
{:status 204, :body nil})
(api/defendpoint GET "/public"
"Fetch a list of Cards with public UUIDs. These cards are publicly-accessible *if* public sharing is enabled."
[]
(api/check-superuser)
(api/check-public-sharing-enabled)
(db/select [Card :name :id :public_uuid], :public_uuid [:not= nil], :archived false))
(api/defendpoint GET "/embeddable"
"Fetch a list of Cards where `enable_embedding` is `true`. The cards can be embedded using the embedding endpoints
and a signed JWT."
[]
(api/check-superuser)
(api/check-embedding-enabled)
(db/select [Card :name :id], :enable_embedding true, :archived false))
(api/defendpoint GET "/:id/related"
"Return related entities."
[id]
(-> id Card api/read-check related/related))
(api/defendpoint POST "/related"
"Return related entities for an ad-hoc query."
[:as {query :body}]
(related/related (query/adhoc-query query)))
(api/defendpoint ^:streaming POST "/pivot/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache]
:or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async card-id :api
:parameters parameters,
:qp-runner qp.pivot/run-pivot-query
:ignore_cache ignore_cache))
(api/define-routes)
| 81248 | (ns metabase.api.card
"/api/card endpoints."
(:require [cheshire.core :as json]
[clojure.core.async :as a]
[clojure.tools.logging :as log]
[compojure.core :refer [DELETE GET POST PUT]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.api.dataset :as dataset-api]
[metabase.async.util :as async.u]
[metabase.email.messages :as messages]
[metabase.events :as events]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.models.card :as card :refer [Card]]
[metabase.models.card-favorite :refer [CardFavorite]]
[metabase.models.collection :as collection :refer [Collection]]
[metabase.models.database :refer [Database]]
[metabase.models.interface :as mi]
[metabase.models.pulse :as pulse :refer [Pulse]]
[metabase.models.query :as query]
[metabase.models.query.permissions :as query-perms]
[metabase.models.revision.last-edit :as last-edit]
[metabase.models.table :refer [Table]]
[metabase.models.view-log :refer [ViewLog]]
[metabase.public-settings :as public-settings]
[metabase.query-processor :as qp]
[metabase.query-processor.async :as qp.async]
[metabase.query-processor.middleware.constraints :as constraints]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.middleware.results-metadata :as results-metadata]
[metabase.query-processor.pivot :as qp.pivot]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.query-processor.util :as qputil]
[metabase.related :as related]
[metabase.sync.analyze.query-results :as qr]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]])
(:import clojure.core.async.impl.channels.ManyToManyChannel
java.util.UUID
metabase.models.card.CardInstance))
;;; --------------------------------------------------- Hydration ----------------------------------------------------
(defn hydrate-favorites
"Efficiently add `favorite` status for a large collection of `Cards`."
{:batched-hydrate :favorite}
[cards]
(when (seq cards)
(let [favorite-card-ids (db/select-field :card_id CardFavorite
:owner_id api/*current-user-id*
:card_id [:in (map :id cards)])]
(for [card cards]
(assoc card :favorite (contains? favorite-card-ids (:id card)))))))
;;; ----------------------------------------------- Filtered Fetch Fns -----------------------------------------------
(defmulti ^:private cards-for-filter-option*
{:arglists '([filter-option & args])}
(fn [filter-option & _]
(keyword filter-option)))
;; return all Cards. This is the default filter option.
(defmethod cards-for-filter-option* :all
[_]
(db/select Card, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return Cards created by the current user
(defmethod cards-for-filter-option* :mine
[_]
(db/select Card, :creator_id api/*current-user-id*, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return all Cards favorited by the current user.
(defmethod cards-for-filter-option* :fav
[_]
(let [cards (for [{{:keys [archived], :as card} :card} (hydrate (db/select [CardFavorite :card_id]
:owner_id api/*current-user-id*)
:card)
:when (not archived)]
card)]
(sort-by :name cards)))
;; Return all Cards belonging to Database with `database-id`.
(defmethod cards-for-filter-option* :database
[_ database-id]
(db/select Card, :database_id database-id, :archived false, {:order-by [[:%lower.name :asc]]}))
;; Return all Cards belonging to `Table` with `table-id`.
(defmethod cards-for-filter-option* :table
[_ table-id]
(db/select Card, :table_id table-id, :archived false, {:order-by [[:%lower.name :asc]]}))
(s/defn ^:private cards-with-ids :- (s/maybe [CardInstance])
"Return unarchived Cards with `card-ids`.
Make sure cards are returned in the same order as `card-ids`; `[in card-ids]` won't preserve the order."
[card-ids :- [su/IntGreaterThanZero]]
(when (seq card-ids)
(let [card-id->card (u/key-by :id (db/select Card, :id [:in (set card-ids)], :archived false))]
(filter identity (map card-id->card card-ids)))))
;; Return the 10 Cards most recently viewed by the current user, sorted by how recently they were viewed.
(defmethod cards-for-filter-option* :recent
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%max.timestamp :max]]
:model "card"
:user_id api/*current-user-id*
{:group-by [:model_id]
:order-by [[:max :desc]]
:limit 10}))))
;; All Cards, sorted by popularity (the total number of times they are viewed in `ViewLogs`). (yes, this isn't
;; actually filtering anything, but for the sake of simplicitiy it is included amongst the filter options for the time
;; being).
(defmethod cards-for-filter-option* :popular
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%count.* :count]]
:model "card"
{:group-by [:model_id]
:order-by [[:count :desc]]}))))
;; Cards that have been archived.
(defmethod cards-for-filter-option* :archived
[_]
(db/select Card, :archived true, {:order-by [[:%lower.name :asc]]}))
(defn- cards-for-filter-option [filter-option model-id-or-nil]
(-> (apply cards-for-filter-option* (or filter-option :all) (when model-id-or-nil [model-id-or-nil]))
(hydrate :creator :collection :favorite)))
;;; -------------------------------------------- Fetching a Card or Cards --------------------------------------------
(def ^:private CardFilterOption
"Schema for a valid card filter option."
(apply s/enum (map name (keys (methods cards-for-filter-option*)))))
(api/defendpoint GET "/"
"Get all the Cards. Option filter param `f` can be used to change the set of Cards that are returned; default is
`all`, but other options include `mine`, `fav`, `database`, `table`, `recent`, `popular`, and `archived`. See
corresponding implementation functions above for the specific behavior of each filter option. :card_index:"
[f model_id]
{f (s/maybe CardFilterOption)
model_id (s/maybe su/IntGreaterThanZero)}
(let [f (keyword f)]
(when (contains? #{:database :table} f)
(api/checkp (integer? model_id) "model_id" (format "model_id is a required parameter when filter mode is '%s'"
(name f)))
(case f
:database (api/read-check Database model_id)
:table (api/read-check Database (db/select-one-field :db_id Table, :id model_id))))
(let [cards (filter mi/can-read? (cards-for-filter-option f model_id))
last-edit-info (:card (last-edit/fetch-last-edited-info {:card-ids (map :id cards)}))]
(into []
(map (fn [{:keys [id] :as card}]
(if-let [edit-info (get last-edit-info id)]
(assoc card :last-edit-info edit-info)
card)))
cards))))
(api/defendpoint GET "/:id"
"Get `Card` with ID."
[id]
(u/prog1 (-> (Card id)
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
api/read-check
(last-edit/with-last-edit-info :card))
(events/publish-event! :card-read (assoc <> :actor_id api/*current-user-id*))))
;;; -------------------------------------------------- Saving Cards --------------------------------------------------
;; When a new Card is saved, we wouldn't normally have the results metadata for it until the first time its query is
;; ran. As a workaround, we'll calculate this metadata and return it with all query responses, and then let the
;; frontend pass it back to us when saving or updating a Card. As a basic step to make sure the Metadata is valid
;; we'll also pass a simple checksum and have the frontend pass it back to us. See the QP `results-metadata`
;; middleware namespace for more details
(s/defn ^:private result-metadata-async :- ManyToManyChannel
"Get the right results metadata for this `card`, and return them in a channel. We'll check to see whether the
`metadata` passed in seems valid,and, if so, return a channel that returns the value as-is; otherwise, we'll run the
query ourselves to get the right values, and return a channel where you can listen for the results."
[query metadata checksum]
(let [valid-metadata? (and (results-metadata/valid-checksum? metadata checksum)
(s/validate qr/ResultsMetadata metadata))]
(log/info
(cond
valid-metadata? (trs "Card results metadata passed in to API is VALID. Thanks!")
metadata (trs "Card results metadata passed in to API is INVALID. Running query to fetch correct metadata.")
:else (trs "Card results metadata passed in to API is MISSING. Running query to fetch correct metadata.")))
(if valid-metadata?
(a/to-chan [metadata])
(qp.async/result-metadata-for-query-async query))))
(defn check-data-permissions-for-query
"Make sure the Current User has the appropriate *data* permissions to run `query`. We don't want Users saving Cards
with queries they wouldn't be allowed to run!"
[query]
{:pre [(map? query)]}
(when-not (query-perms/can-run-query? query)
(let [required-perms (try
(query-perms/perms-set query :throw-exceptions? true)
(catch Throwable e
e))]
(throw (ex-info (tru "You cannot save this Question because you do not have permissions to run its query.")
{:status-code 403
:query query
:required-perms (if (instance? Throwable required-perms)
:error
required-perms)
:actual-perms @api/*current-user-permissions-set*}
(when (instance? Throwable required-perms)
required-perms))))))
(defn- save-new-card-async!
"Save `card-data` as a new Card on a separate thread. Returns a channel to fetch the response; closing this channel
will cancel the save."
[card-data user]
(async.u/cancelable-thread
(let [card (db/transaction
;; Adding a new card at `collection_position` could cause other cards in this
;; collection to change position, check that and fix it if needed
(api/maybe-reconcile-collection-position! card-data)
(db/insert! Card card-data))]
(events/publish-event! :card-create card)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it
;; currently has with returned one -- See #4283
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user user))))))
(defn- create-card-async!
"Create a new Card asynchronously. Returns a channel for fetching the newly created Card, or an Exception if one was
thrown. Closing this channel before it finishes will cancel the Card creation."
[{:keys [dataset_query result_metadata metadata_checksum], :as card-data}]
;; `zipmap` instead of `select-keys` because we want to get `nil` values for keys that aren't present. Required by
;; `api/maybe-reconcile-collection-position!`
(let [data-keys [:<KEY> :description :display :name
:visualization_settings :collection_id :collection_position]
card-data (assoc (zipmap data-keys (map card-data data-keys))
:creator_id api/*current-user-id*)
result-metadata-chan (result-metadata-async dataset_query result_metadata metadata_checksum)
out-chan (a/promise-chan)]
(a/go
(try
(let [card-data (assoc card-data :result_metadata (a/<! result-metadata-chan))]
(a/close! result-metadata-chan)
;; now do the actual saving on a separate thread so we don't tie up our precious core.async thread. Pipe the
;; result into `out-chan`.
(async.u/promise-pipe (save-new-card-async! card-data @api/*current-user*) out-chan))
(catch Throwable e
(a/put! out-chan e)
(a/close! out-chan))))
;; Return a channel
out-chan))
(api/defendpoint ^:returns-chan POST "/"
"Create a new `Card`."
[:as {{:keys [collection_id collection_position dataset_query description display metadata_checksum name
result_metadata visualization_settings], :as body} :body}]
{name su/NonBlankString
description (s/maybe su/NonBlankString)
display su/NonBlankString
visualization_settings su/Map
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
;; check that we have permissions to run the query that we're trying to save
(check-data-permissions-for-query dataset_query)
;; check that we have permissions for the collection we're trying to save this card to, if applicable
(collection/check-write-perms-for-collection collection_id)
;; Return a channel that can be used to fetch the results asynchronously
(create-card-async! body))
;;; ------------------------------------------------- Updating Cards -------------------------------------------------
(defn- check-allowed-to-modify-query
"If the query is being modified, check that we have data permissions to run the query."
[card-before-updates card-updates]
(let [card-updates (m/update-existing card-updates :dataset_query mbql.normalize/normalize)]
(when (api/column-will-change? :dataset_query card-before-updates card-updates)
(check-data-permissions-for-query (:dataset_query card-updates)))))
(defn- check-allowed-to-change-embedding
"You must be a superuser to change the value of `enable_embedding` or `embedding_params`. Embedding must be
enabled."
[card-before-updates card-updates]
(when (or (api/column-will-change? :enable_embedding card-before-updates card-updates)
(api/column-will-change? :embedding_params card-before-updates card-updates))
(api/check-embedding-enabled)
(api/check-superuser)))
(defn- result-metadata-for-updating-async
"If `card`'s query is being updated, return the value that should be saved for `result_metadata`. This *should* be
passed in to the API; if so, verifiy that it was correct (the checksum is valid); if not, go fetch it. If the query
has not changed, this returns a closed channel (so you will get `nil` when you attempt to fetch the result, and
will know not to update the value in the DB.)
Either way, results are returned asynchronously on a channel."
[card query metadata checksum]
(if (and query
(not= query (:dataset_query card)))
(result-metadata-async query metadata checksum)
(u/prog1 (a/chan)
(a/close! <>))))
(defn- publish-card-update!
"Publish an event appropriate for the update(s) done to this CARD (`:card-update`, or archiving/unarchiving
events)."
[card archived?]
(let [event (cond
;; card was archived
(and archived?
(not (:archived card))) :card-archive
;; card was unarchived
(and (false? archived?)
(:archived card)) :card-unarchive
:else :card-update)]
(events/publish-event! event (assoc card :actor_id api/*current-user-id*))))
(defn- card-archived? [old-card new-card]
(and (not (:archived old-card))
(:archived new-card)))
(defn- line-area-bar? [display]
(contains? #{:line :area :bar} display))
(defn- progress? [display]
(= :progress display))
(defn- allows-rows-alert? [display]
(not (contains? #{:line :bar :area :progress} display)))
(defn- display-change-broke-alert?
"Alerts no longer make sense when the kind of question being alerted on significantly changes. Setting up an alert
when a time series query reaches 10 is no longer valid if the question switches from a line graph to a table. This
function goes through various scenarios that render an alert no longer valid"
[{old-display :display} {new-display :display}]
(when-not (= old-display new-display)
(or
;; Did the alert switch from a table type to a line/bar/area/progress graph type?
(and (allows-rows-alert? old-display)
(or (line-area-bar? new-display)
(progress? new-display)))
;; Switching from a line/bar/area to another type that is not those three invalidates the alert
(and (line-area-bar? old-display)
(not (line-area-bar? new-display)))
;; Switching from a progress graph to anything else invalidates the alert
(and (progress? old-display)
(not (progress? new-display))))))
(defn- goal-missing?
"If we had a goal before, and now it's gone, the alert is no longer valid"
[old-card new-card]
(and
(get-in old-card [:visualization_settings :graph.goal_value])
(not (get-in new-card [:visualization_settings :graph.goal_value]))))
(defn- multiple-breakouts?
"If there are multiple breakouts and a goal, we don't know which breakout to compare to the goal, so it invalidates
the alert"
[{:keys [display] :as new-card}]
(and (or (line-area-bar? display)
(progress? display))
(< 1 (count (get-in new-card [:dataset_query :query :breakout])))))
(defn- delete-alert-and-notify!
"Removes all of the alerts and notifies all of the email recipients of the alerts change via `NOTIFY-FN!`"
[notify-fn! alerts]
(db/delete! Pulse :id [:in (map :id alerts)])
(doseq [{:keys [channels] :as alert} alerts
:let [email-channel (m/find-first #(= :email (:channel_type %)) channels)]]
(doseq [recipient (:recipients email-channel)]
(notify-fn! alert recipient @api/*current-user*))))
(defn delete-alert-and-notify-archived!
"Removes all alerts and will email each recipient letting them know"
[alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-archived-email! alerts))
(defn- delete-alert-and-notify-changed! [alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-changed-email! alerts))
(defn- delete-alerts-if-needed! [old-card {card-id :id :as new-card}]
;; If there are alerts, we need to check to ensure the card change doesn't invalidate the alert
(when-let [alerts (seq (pulse/retrieve-alerts-for-cards card-id))]
(cond
(card-archived? old-card new-card)
(delete-alert-and-notify-archived! alerts)
(or (display-change-broke-alert? old-card new-card)
(goal-missing? old-card new-card)
(multiple-breakouts? new-card))
(delete-alert-and-notify-changed! alerts)
;; The change doesn't invalidate the alert, do nothing
:else
nil)))
(defn- update-card-async!
"Update a Card asynchronously. Returns a `core.async` promise channel that will return updated Card."
[{:keys [id], :as card-before-update} {:keys [archived], :as card-updates}]
;; don't block our precious core.async thread, run the actual DB updates on a separate thread
(async.u/cancelable-thread
;; Setting up a transaction here so that we don't get a partially reconciled/updated card.
(db/transaction
(api/maybe-reconcile-collection-position! card-before-update card-updates)
;; ok, now save the Card
(db/update! Card id
;; `collection_id` and `description` can be `nil` (in order to unset them). Other values should only be
;; modified if they're passed in as non-nil
(u/select-keys-when card-updates
:present #{:collection_id :collection_position :description}
:non-nil #{:dataset_query :display :name :visualization_settings :archived :enable_embedding
:embedding_params :result_metadata})))
;; Fetch the updated Card from the DB
(let [card (Card id)]
(delete-alerts-if-needed! card-before-update card)
(publish-card-update! card archived)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it currently
;; has with returned one -- See #4142
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user @api/*current-user*))))))
(api/defendpoint ^:returns-chan PUT "/:id"
"Update a `Card`."
[id :as {{:keys [dataset_query description display name visualization_settings archived collection_id
collection_position enable_embedding embedding_params result_metadata metadata_checksum]
:as card-updates} :body}]
{name (s/maybe su/NonBlankString)
dataset_query (s/maybe su/Map)
display (s/maybe su/NonBlankString)
description (s/maybe s/Str)
visualization_settings (s/maybe su/Map)
archived (s/maybe s/Bool)
enable_embedding (s/maybe s/Bool)
embedding_params (s/maybe su/EmbeddingParams)
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
(let [card-before-update (api/write-check Card id)]
;; Do various permissions checks
(collection/check-allowed-to-change-collection card-before-update card-updates)
(check-allowed-to-modify-query card-before-update card-updates)
(check-allowed-to-change-embedding card-before-update card-updates)
;; make sure we have the correct `result_metadata`
(let [result-metadata-chan (result-metadata-for-updating-async
card-before-update
dataset_query
result_metadata
metadata_checksum)
out-chan (a/promise-chan)]
;; asynchronously wait for our updated result metadata, then after that call `update-card-async!`, which is done
;; on a non-core.async thread. Pipe the results of that into `out-chan`.
(a/go
(try
(let [card-updates (assoc card-updates :result_metadata (a/<! result-metadata-chan))]
(async.u/promise-pipe (update-card-async! card-before-update card-updates) out-chan))
(finally
(a/close! result-metadata-chan))))
out-chan)))
;;; ------------------------------------------------- Deleting Cards -------------------------------------------------
;; TODO - Pretty sure this endpoint is not actually used any more, since Cards are supposed to get archived (via PUT
;; /api/card/:id) instead of deleted. Should we remove this?
(api/defendpoint DELETE "/:id"
"Delete a Card. (DEPRECATED -- don't delete a Card anymore -- archive it instead.)"
[id]
(log/warn (tru "DELETE /api/card/:id is deprecated. Instead, change its `archived` value via PUT /api/card/:id."))
(let [card (api/write-check Card id)]
(db/delete! Card :id id)
(events/publish-event! :card-delete (assoc card :actor_id api/*current-user-id*)))
api/generic-204-no-content)
;;; --------------------------------------------------- Favoriting ---------------------------------------------------
(api/defendpoint POST "/:card-id/favorite"
"Favorite a Card."
[card-id]
(api/read-check Card card-id)
(db/insert! CardFavorite :card_id card-id, :owner_id api/*current-user-id*))
(api/defendpoint DELETE "/:card-id/favorite"
"Unfavorite a Card."
[card-id]
(api/read-check Card card-id)
(api/let-404 [id (db/select-one-id CardFavorite :card_id card-id, :owner_id api/*current-user-id*)]
(db/delete! CardFavorite, :id id))
api/generic-204-no-content)
;;; -------------------------------------------- Bulk Collections Update ---------------------------------------------
(defn- update-collection-positions!
"For cards that have a position in the previous collection, add them to the end of the new collection, trying to
preseve the order from the original collections. Note it's possible for there to be multiple collections
(and thus duplicate collection positions) merged into this new collection. No special tie breaker logic for when
that's the case, just use the order the DB returned it in"
[new-collection-id-or-nil cards]
;; Sorting by `:collection_position` to ensure lower position cards are appended first
(let [sorted-cards (sort-by :collection_position cards)
max-position-result (db/select-one [Card [:%max.collection_position :max_position]]
:collection_id new-collection-id-or-nil)
;; collection_position for the next card in the collection
starting-position (inc (get max-position-result :max_position 0))]
;; This is using `map` but more like a `doseq` with multiple seqs. Wrapping this in a `doall` as we don't want it
;; to be lazy and we're just going to discard the results
(doall
(map (fn [idx {:keys [collection_id collection_position] :as card}]
;; We are removing this card from `collection_id` so we need to reconcile any
;; `collection_position` entries left behind by this move
(api/reconcile-position-for-collection! collection_id collection_position nil)
;; Now we can update the card with the new collection and a new calculated position
;; that appended to the end
(db/update! Card (u/the-id card)
:collection_position idx
:collection_id new-collection-id-or-nil))
;; These are reversed because of the classic issue when removing an item from array. If we remove an
;; item at index 1, everthing above index 1 will get decremented. By reversing our processing order we
;; can avoid changing the index of cards we haven't yet updated
(reverse (range starting-position (+ (count sorted-cards) starting-position)))
(reverse sorted-cards)))))
(defn- move-cards-to-collection! [new-collection-id-or-nil card-ids]
;; if moving to a collection, make sure we have write perms for it
(when new-collection-id-or-nil
(api/write-check Collection new-collection-id-or-nil))
;; for each affected card...
(when (seq card-ids)
(let [cards (db/select [Card :id :collection_id :collection_position :dataset_query]
{:where [:and [:in :id (set card-ids)]
[:or [:not= :collection_id new-collection-id-or-nil]
(when new-collection-id-or-nil
[:= :collection_id nil])]]})] ; poisioned NULLs = ick
;; ...check that we have write permissions for it...
(doseq [card cards]
(api/write-check card))
;; ...and check that we have write permissions for the old collections if applicable
(doseq [old-collection-id (set (filter identity (map :collection_id cards)))]
(api/write-check Collection old-collection-id))
;; Ensure all of the card updates occur in a transaction. Read commited (the default) really isn't what we want
;; here. We are querying for the max card position for a given collection, then using that to base our position
;; changes if the cards are moving to a different collection. Without repeatable read here, it's possible we'll
;; get duplicates
(db/transaction
;; If any of the cards have a `:collection_position`, we'll need to fixup the old collection now that the cards
;; are gone and update the position in the new collection
(when-let [cards-with-position (seq (filter :collection_position cards))]
(update-collection-positions! new-collection-id-or-nil cards-with-position))
;; ok, everything checks out. Set the new `collection_id` for all the Cards that haven't been updated already
(when-let [cards-without-position (seq (for [card cards
:when (not (:collection_position card))]
(u/the-id card)))]
(db/update-where! Card {:id [:in (set cards-without-position)]}
:collection_id new-collection-id-or-nil))))))
(api/defendpoint POST "/collections"
"Bulk update endpoint for Card Collections. Move a set of `Cards` with CARD_IDS into a `Collection` with
COLLECTION_ID, or remove them from any Collections by passing a `null` COLLECTION_ID."
[:as {{:keys [card_ids collection_id]} :body}]
{card_ids [su/IntGreaterThanZero], collection_id (s/maybe su/IntGreaterThanZero)}
(move-cards-to-collection! collection_id card_ids)
{:status :ok})
;;; ------------------------------------------------ Running a Query -------------------------------------------------
(defn- query-magic-ttl
"Compute a 'magic' cache TTL time (in seconds) for QUERY by multipling its historic average execution times by the
`query-caching-ttl-ratio`. If the TTL is less than a second, this returns `nil` (i.e., the cache should not be
utilized.)"
[query]
(when-let [average-duration (query/average-execution-time-ms (qputil/query-hash query))]
(let [ttl-seconds (Math/round (float (/ (* average-duration (public-settings/query-caching-ttl-ratio))
1000.0)))]
(when-not (zero? ttl-seconds)
(log/info (trs "Question''s average execution duration is {0}; using ''magic'' TTL of {1}"
(u/format-milliseconds average-duration) (u/format-seconds ttl-seconds))
(u/emoji "💾"))
ttl-seconds))))
(defn query-for-card
"Generate a query for a saved Card"
[{query :dataset_query
:as card} parameters constraints middleware]
(let [query (-> query
;; don't want default constraints overridding anything that's already there
(m/dissoc-in [:middleware :add-default-userland-constraints?])
(assoc :constraints constraints
:parameters parameters
:middleware middleware))
ttl (when (public-settings/enable-query-caching)
(or (:cache_ttl card)
(query-magic-ttl query)))]
(assoc query :cache-ttl ttl)))
(defn run-query-for-card-async
"Run the query for Card with `parameters` and `constraints`, and return results in a `StreamingResponse` that should
be returned as the result of an API endpoint fn. Will throw an Exception if preconditions (such as read perms) are
not met before returning the `StreamingResponse`."
[card-id export-format
& {:keys [parameters constraints context dashboard-id middleware qp-runner run ignore_cache]
:or {constraints constraints/default-query-constraints
context :question
qp-runner qp/process-query-and-save-execution!}}]
{:pre [(u/maybe? sequential? parameters)]}
(let [run (or run
;; param `run` can be used to control how the query is ran, e.g. if you need to
;; customize the `context` passed to the QP
(^:once fn* [query info]
(qp.streaming/streaming-response [context export-format (u/slugify (:card-name info))]
(binding [qp.perms/*card-id* card-id]
(qp-runner query info context)))))
card (api/read-check (db/select-one [Card :name :dataset_query :cache_ttl :collection_id] :id card-id))
query (-> (assoc (query-for-card card parameters constraints middleware)
:async? true)
(update :middleware (fn [middleware]
(merge
{:js-int-to-string? true :ignore-cached-results? ignore_cache}
middleware))))
info {:executed-by api/*current-user-id*
:context context
:card-id card-id
:card-name (:name card)
:dashboard-id dashboard-id}]
(api/check-not-archived card)
(run query info)))
(api/defendpoint ^:streaming POST "/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache], :or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async
card-id :api
:parameters parameters,
:ignore_cache ignore_cache
:middleware {:process-viz-settings? false}))
(api/defendpoint ^:streaming POST "/:card-id/query/:export-format"
"Run the query associated with a Card, and return its results as a file in the specified format. Note that this
expects the parameters as serialized JSON in the 'parameters' parameter"
[card-id export-format :as {{:keys [parameters]} :params}]
{parameters (s/maybe su/JSONString)
export-format dataset-api/ExportFormat}
(run-query-for-card-async
card-id export-format
:parameters (json/parse-string parameters keyword)
:constraints nil
:context (dataset-api/export-format->context export-format)
:middleware {:process-viz-settings? true
:skip-results-metadata? true
:ignore-cached-results? true
:format-rows? false
:js-int-to-string? false}))
;;; ----------------------------------------------- Sharing is Caring ------------------------------------------------
(api/defendpoint POST "/:card-id/public_link"
"Generate publicly-accessible links for this Card. Returns UUID to be used in public links. (If this Card has
already been shared, it will return the existing public link rather than creating a new one.) Public sharing must
be enabled."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-not-archived (api/read-check Card card-id))
{:uuid (or (db/select-one-field :public_uuid Card :id card-id)
(u/prog1 (str (UUID/randomUUID))
(db/update! Card card-id
:public_uuid <>
:made_public_by_id api/*current-user-id*)))})
(api/defendpoint DELETE "/:card-id/public_link"
"Delete the publicly-accessible link to this Card."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-exists? Card :id card-id, :public_uuid [:not= nil])
(db/update! Card card-id
:public_uuid nil
:made_public_by_id nil)
{:status 204, :body nil})
(api/defendpoint GET "/public"
"Fetch a list of Cards with public UUIDs. These cards are publicly-accessible *if* public sharing is enabled."
[]
(api/check-superuser)
(api/check-public-sharing-enabled)
(db/select [Card :name :id :public_uuid], :public_uuid [:not= nil], :archived false))
(api/defendpoint GET "/embeddable"
"Fetch a list of Cards where `enable_embedding` is `true`. The cards can be embedded using the embedding endpoints
and a signed JWT."
[]
(api/check-superuser)
(api/check-embedding-enabled)
(db/select [Card :name :id], :enable_embedding true, :archived false))
(api/defendpoint GET "/:id/related"
"Return related entities."
[id]
(-> id Card api/read-check related/related))
(api/defendpoint POST "/related"
"Return related entities for an ad-hoc query."
[:as {query :body}]
(related/related (query/adhoc-query query)))
(api/defendpoint ^:streaming POST "/pivot/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache]
:or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async card-id :api
:parameters parameters,
:qp-runner qp.pivot/run-pivot-query
:ignore_cache ignore_cache))
(api/define-routes)
| true | (ns metabase.api.card
"/api/card endpoints."
(:require [cheshire.core :as json]
[clojure.core.async :as a]
[clojure.tools.logging :as log]
[compojure.core :refer [DELETE GET POST PUT]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.api.dataset :as dataset-api]
[metabase.async.util :as async.u]
[metabase.email.messages :as messages]
[metabase.events :as events]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.models.card :as card :refer [Card]]
[metabase.models.card-favorite :refer [CardFavorite]]
[metabase.models.collection :as collection :refer [Collection]]
[metabase.models.database :refer [Database]]
[metabase.models.interface :as mi]
[metabase.models.pulse :as pulse :refer [Pulse]]
[metabase.models.query :as query]
[metabase.models.query.permissions :as query-perms]
[metabase.models.revision.last-edit :as last-edit]
[metabase.models.table :refer [Table]]
[metabase.models.view-log :refer [ViewLog]]
[metabase.public-settings :as public-settings]
[metabase.query-processor :as qp]
[metabase.query-processor.async :as qp.async]
[metabase.query-processor.middleware.constraints :as constraints]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.middleware.results-metadata :as results-metadata]
[metabase.query-processor.pivot :as qp.pivot]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.query-processor.util :as qputil]
[metabase.related :as related]
[metabase.sync.analyze.query-results :as qr]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]])
(:import clojure.core.async.impl.channels.ManyToManyChannel
java.util.UUID
metabase.models.card.CardInstance))
;;; --------------------------------------------------- Hydration ----------------------------------------------------
(defn hydrate-favorites
"Efficiently add `favorite` status for a large collection of `Cards`."
{:batched-hydrate :favorite}
[cards]
(when (seq cards)
(let [favorite-card-ids (db/select-field :card_id CardFavorite
:owner_id api/*current-user-id*
:card_id [:in (map :id cards)])]
(for [card cards]
(assoc card :favorite (contains? favorite-card-ids (:id card)))))))
;;; ----------------------------------------------- Filtered Fetch Fns -----------------------------------------------
(defmulti ^:private cards-for-filter-option*
{:arglists '([filter-option & args])}
(fn [filter-option & _]
(keyword filter-option)))
;; return all Cards. This is the default filter option.
(defmethod cards-for-filter-option* :all
[_]
(db/select Card, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return Cards created by the current user
(defmethod cards-for-filter-option* :mine
[_]
(db/select Card, :creator_id api/*current-user-id*, :archived false, {:order-by [[:%lower.name :asc]]}))
;; return all Cards favorited by the current user.
(defmethod cards-for-filter-option* :fav
[_]
(let [cards (for [{{:keys [archived], :as card} :card} (hydrate (db/select [CardFavorite :card_id]
:owner_id api/*current-user-id*)
:card)
:when (not archived)]
card)]
(sort-by :name cards)))
;; Return all Cards belonging to Database with `database-id`.
(defmethod cards-for-filter-option* :database
[_ database-id]
(db/select Card, :database_id database-id, :archived false, {:order-by [[:%lower.name :asc]]}))
;; Return all Cards belonging to `Table` with `table-id`.
(defmethod cards-for-filter-option* :table
[_ table-id]
(db/select Card, :table_id table-id, :archived false, {:order-by [[:%lower.name :asc]]}))
(s/defn ^:private cards-with-ids :- (s/maybe [CardInstance])
"Return unarchived Cards with `card-ids`.
Make sure cards are returned in the same order as `card-ids`; `[in card-ids]` won't preserve the order."
[card-ids :- [su/IntGreaterThanZero]]
(when (seq card-ids)
(let [card-id->card (u/key-by :id (db/select Card, :id [:in (set card-ids)], :archived false))]
(filter identity (map card-id->card card-ids)))))
;; Return the 10 Cards most recently viewed by the current user, sorted by how recently they were viewed.
(defmethod cards-for-filter-option* :recent
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%max.timestamp :max]]
:model "card"
:user_id api/*current-user-id*
{:group-by [:model_id]
:order-by [[:max :desc]]
:limit 10}))))
;; All Cards, sorted by popularity (the total number of times they are viewed in `ViewLogs`). (yes, this isn't
;; actually filtering anything, but for the sake of simplicitiy it is included amongst the filter options for the time
;; being).
(defmethod cards-for-filter-option* :popular
[_]
(cards-with-ids (map :model_id (db/select [ViewLog :model_id [:%count.* :count]]
:model "card"
{:group-by [:model_id]
:order-by [[:count :desc]]}))))
;; Cards that have been archived.
(defmethod cards-for-filter-option* :archived
[_]
(db/select Card, :archived true, {:order-by [[:%lower.name :asc]]}))
(defn- cards-for-filter-option [filter-option model-id-or-nil]
(-> (apply cards-for-filter-option* (or filter-option :all) (when model-id-or-nil [model-id-or-nil]))
(hydrate :creator :collection :favorite)))
;;; -------------------------------------------- Fetching a Card or Cards --------------------------------------------
(def ^:private CardFilterOption
"Schema for a valid card filter option."
(apply s/enum (map name (keys (methods cards-for-filter-option*)))))
(api/defendpoint GET "/"
"Get all the Cards. Option filter param `f` can be used to change the set of Cards that are returned; default is
`all`, but other options include `mine`, `fav`, `database`, `table`, `recent`, `popular`, and `archived`. See
corresponding implementation functions above for the specific behavior of each filter option. :card_index:"
[f model_id]
{f (s/maybe CardFilterOption)
model_id (s/maybe su/IntGreaterThanZero)}
(let [f (keyword f)]
(when (contains? #{:database :table} f)
(api/checkp (integer? model_id) "model_id" (format "model_id is a required parameter when filter mode is '%s'"
(name f)))
(case f
:database (api/read-check Database model_id)
:table (api/read-check Database (db/select-one-field :db_id Table, :id model_id))))
(let [cards (filter mi/can-read? (cards-for-filter-option f model_id))
last-edit-info (:card (last-edit/fetch-last-edited-info {:card-ids (map :id cards)}))]
(into []
(map (fn [{:keys [id] :as card}]
(if-let [edit-info (get last-edit-info id)]
(assoc card :last-edit-info edit-info)
card)))
cards))))
(api/defendpoint GET "/:id"
"Get `Card` with ID."
[id]
(u/prog1 (-> (Card id)
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
api/read-check
(last-edit/with-last-edit-info :card))
(events/publish-event! :card-read (assoc <> :actor_id api/*current-user-id*))))
;;; -------------------------------------------------- Saving Cards --------------------------------------------------
;; When a new Card is saved, we wouldn't normally have the results metadata for it until the first time its query is
;; ran. As a workaround, we'll calculate this metadata and return it with all query responses, and then let the
;; frontend pass it back to us when saving or updating a Card. As a basic step to make sure the Metadata is valid
;; we'll also pass a simple checksum and have the frontend pass it back to us. See the QP `results-metadata`
;; middleware namespace for more details
(s/defn ^:private result-metadata-async :- ManyToManyChannel
"Get the right results metadata for this `card`, and return them in a channel. We'll check to see whether the
`metadata` passed in seems valid,and, if so, return a channel that returns the value as-is; otherwise, we'll run the
query ourselves to get the right values, and return a channel where you can listen for the results."
[query metadata checksum]
(let [valid-metadata? (and (results-metadata/valid-checksum? metadata checksum)
(s/validate qr/ResultsMetadata metadata))]
(log/info
(cond
valid-metadata? (trs "Card results metadata passed in to API is VALID. Thanks!")
metadata (trs "Card results metadata passed in to API is INVALID. Running query to fetch correct metadata.")
:else (trs "Card results metadata passed in to API is MISSING. Running query to fetch correct metadata.")))
(if valid-metadata?
(a/to-chan [metadata])
(qp.async/result-metadata-for-query-async query))))
(defn check-data-permissions-for-query
"Make sure the Current User has the appropriate *data* permissions to run `query`. We don't want Users saving Cards
with queries they wouldn't be allowed to run!"
[query]
{:pre [(map? query)]}
(when-not (query-perms/can-run-query? query)
(let [required-perms (try
(query-perms/perms-set query :throw-exceptions? true)
(catch Throwable e
e))]
(throw (ex-info (tru "You cannot save this Question because you do not have permissions to run its query.")
{:status-code 403
:query query
:required-perms (if (instance? Throwable required-perms)
:error
required-perms)
:actual-perms @api/*current-user-permissions-set*}
(when (instance? Throwable required-perms)
required-perms))))))
(defn- save-new-card-async!
"Save `card-data` as a new Card on a separate thread. Returns a channel to fetch the response; closing this channel
will cancel the save."
[card-data user]
(async.u/cancelable-thread
(let [card (db/transaction
;; Adding a new card at `collection_position` could cause other cards in this
;; collection to change position, check that and fix it if needed
(api/maybe-reconcile-collection-position! card-data)
(db/insert! Card card-data))]
(events/publish-event! :card-create card)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it
;; currently has with returned one -- See #4283
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user user))))))
(defn- create-card-async!
"Create a new Card asynchronously. Returns a channel for fetching the newly created Card, or an Exception if one was
thrown. Closing this channel before it finishes will cancel the Card creation."
[{:keys [dataset_query result_metadata metadata_checksum], :as card-data}]
;; `zipmap` instead of `select-keys` because we want to get `nil` values for keys that aren't present. Required by
;; `api/maybe-reconcile-collection-position!`
(let [data-keys [:PI:KEY:<KEY>END_PI :description :display :name
:visualization_settings :collection_id :collection_position]
card-data (assoc (zipmap data-keys (map card-data data-keys))
:creator_id api/*current-user-id*)
result-metadata-chan (result-metadata-async dataset_query result_metadata metadata_checksum)
out-chan (a/promise-chan)]
(a/go
(try
(let [card-data (assoc card-data :result_metadata (a/<! result-metadata-chan))]
(a/close! result-metadata-chan)
;; now do the actual saving on a separate thread so we don't tie up our precious core.async thread. Pipe the
;; result into `out-chan`.
(async.u/promise-pipe (save-new-card-async! card-data @api/*current-user*) out-chan))
(catch Throwable e
(a/put! out-chan e)
(a/close! out-chan))))
;; Return a channel
out-chan))
(api/defendpoint ^:returns-chan POST "/"
"Create a new `Card`."
[:as {{:keys [collection_id collection_position dataset_query description display metadata_checksum name
result_metadata visualization_settings], :as body} :body}]
{name su/NonBlankString
description (s/maybe su/NonBlankString)
display su/NonBlankString
visualization_settings su/Map
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
;; check that we have permissions to run the query that we're trying to save
(check-data-permissions-for-query dataset_query)
;; check that we have permissions for the collection we're trying to save this card to, if applicable
(collection/check-write-perms-for-collection collection_id)
;; Return a channel that can be used to fetch the results asynchronously
(create-card-async! body))
;;; ------------------------------------------------- Updating Cards -------------------------------------------------
(defn- check-allowed-to-modify-query
"If the query is being modified, check that we have data permissions to run the query."
[card-before-updates card-updates]
(let [card-updates (m/update-existing card-updates :dataset_query mbql.normalize/normalize)]
(when (api/column-will-change? :dataset_query card-before-updates card-updates)
(check-data-permissions-for-query (:dataset_query card-updates)))))
(defn- check-allowed-to-change-embedding
"You must be a superuser to change the value of `enable_embedding` or `embedding_params`. Embedding must be
enabled."
[card-before-updates card-updates]
(when (or (api/column-will-change? :enable_embedding card-before-updates card-updates)
(api/column-will-change? :embedding_params card-before-updates card-updates))
(api/check-embedding-enabled)
(api/check-superuser)))
(defn- result-metadata-for-updating-async
"If `card`'s query is being updated, return the value that should be saved for `result_metadata`. This *should* be
passed in to the API; if so, verifiy that it was correct (the checksum is valid); if not, go fetch it. If the query
has not changed, this returns a closed channel (so you will get `nil` when you attempt to fetch the result, and
will know not to update the value in the DB.)
Either way, results are returned asynchronously on a channel."
[card query metadata checksum]
(if (and query
(not= query (:dataset_query card)))
(result-metadata-async query metadata checksum)
(u/prog1 (a/chan)
(a/close! <>))))
(defn- publish-card-update!
"Publish an event appropriate for the update(s) done to this CARD (`:card-update`, or archiving/unarchiving
events)."
[card archived?]
(let [event (cond
;; card was archived
(and archived?
(not (:archived card))) :card-archive
;; card was unarchived
(and (false? archived?)
(:archived card)) :card-unarchive
:else :card-update)]
(events/publish-event! event (assoc card :actor_id api/*current-user-id*))))
(defn- card-archived? [old-card new-card]
(and (not (:archived old-card))
(:archived new-card)))
(defn- line-area-bar? [display]
(contains? #{:line :area :bar} display))
(defn- progress? [display]
(= :progress display))
(defn- allows-rows-alert? [display]
(not (contains? #{:line :bar :area :progress} display)))
(defn- display-change-broke-alert?
"Alerts no longer make sense when the kind of question being alerted on significantly changes. Setting up an alert
when a time series query reaches 10 is no longer valid if the question switches from a line graph to a table. This
function goes through various scenarios that render an alert no longer valid"
[{old-display :display} {new-display :display}]
(when-not (= old-display new-display)
(or
;; Did the alert switch from a table type to a line/bar/area/progress graph type?
(and (allows-rows-alert? old-display)
(or (line-area-bar? new-display)
(progress? new-display)))
;; Switching from a line/bar/area to another type that is not those three invalidates the alert
(and (line-area-bar? old-display)
(not (line-area-bar? new-display)))
;; Switching from a progress graph to anything else invalidates the alert
(and (progress? old-display)
(not (progress? new-display))))))
(defn- goal-missing?
"If we had a goal before, and now it's gone, the alert is no longer valid"
[old-card new-card]
(and
(get-in old-card [:visualization_settings :graph.goal_value])
(not (get-in new-card [:visualization_settings :graph.goal_value]))))
(defn- multiple-breakouts?
"If there are multiple breakouts and a goal, we don't know which breakout to compare to the goal, so it invalidates
the alert"
[{:keys [display] :as new-card}]
(and (or (line-area-bar? display)
(progress? display))
(< 1 (count (get-in new-card [:dataset_query :query :breakout])))))
(defn- delete-alert-and-notify!
"Removes all of the alerts and notifies all of the email recipients of the alerts change via `NOTIFY-FN!`"
[notify-fn! alerts]
(db/delete! Pulse :id [:in (map :id alerts)])
(doseq [{:keys [channels] :as alert} alerts
:let [email-channel (m/find-first #(= :email (:channel_type %)) channels)]]
(doseq [recipient (:recipients email-channel)]
(notify-fn! alert recipient @api/*current-user*))))
(defn delete-alert-and-notify-archived!
"Removes all alerts and will email each recipient letting them know"
[alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-archived-email! alerts))
(defn- delete-alert-and-notify-changed! [alerts]
(delete-alert-and-notify! messages/send-alert-stopped-because-changed-email! alerts))
(defn- delete-alerts-if-needed! [old-card {card-id :id :as new-card}]
;; If there are alerts, we need to check to ensure the card change doesn't invalidate the alert
(when-let [alerts (seq (pulse/retrieve-alerts-for-cards card-id))]
(cond
(card-archived? old-card new-card)
(delete-alert-and-notify-archived! alerts)
(or (display-change-broke-alert? old-card new-card)
(goal-missing? old-card new-card)
(multiple-breakouts? new-card))
(delete-alert-and-notify-changed! alerts)
;; The change doesn't invalidate the alert, do nothing
:else
nil)))
(defn- update-card-async!
"Update a Card asynchronously. Returns a `core.async` promise channel that will return updated Card."
[{:keys [id], :as card-before-update} {:keys [archived], :as card-updates}]
;; don't block our precious core.async thread, run the actual DB updates on a separate thread
(async.u/cancelable-thread
;; Setting up a transaction here so that we don't get a partially reconciled/updated card.
(db/transaction
(api/maybe-reconcile-collection-position! card-before-update card-updates)
;; ok, now save the Card
(db/update! Card id
;; `collection_id` and `description` can be `nil` (in order to unset them). Other values should only be
;; modified if they're passed in as non-nil
(u/select-keys-when card-updates
:present #{:collection_id :collection_position :description}
:non-nil #{:dataset_query :display :name :visualization_settings :archived :enable_embedding
:embedding_params :result_metadata})))
;; Fetch the updated Card from the DB
(let [card (Card id)]
(delete-alerts-if-needed! card-before-update card)
(publish-card-update! card archived)
;; include same information returned by GET /api/card/:id since frontend replaces the Card it currently
;; has with returned one -- See #4142
(-> card
(hydrate :creator :dashboard_count :can_write :collection :moderation_reviews)
(assoc :last-edit-info (last-edit/edit-information-for-user @api/*current-user*))))))
(api/defendpoint ^:returns-chan PUT "/:id"
"Update a `Card`."
[id :as {{:keys [dataset_query description display name visualization_settings archived collection_id
collection_position enable_embedding embedding_params result_metadata metadata_checksum]
:as card-updates} :body}]
{name (s/maybe su/NonBlankString)
dataset_query (s/maybe su/Map)
display (s/maybe su/NonBlankString)
description (s/maybe s/Str)
visualization_settings (s/maybe su/Map)
archived (s/maybe s/Bool)
enable_embedding (s/maybe s/Bool)
embedding_params (s/maybe su/EmbeddingParams)
collection_id (s/maybe su/IntGreaterThanZero)
collection_position (s/maybe su/IntGreaterThanZero)
result_metadata (s/maybe qr/ResultsMetadata)
metadata_checksum (s/maybe su/NonBlankString)}
(let [card-before-update (api/write-check Card id)]
;; Do various permissions checks
(collection/check-allowed-to-change-collection card-before-update card-updates)
(check-allowed-to-modify-query card-before-update card-updates)
(check-allowed-to-change-embedding card-before-update card-updates)
;; make sure we have the correct `result_metadata`
(let [result-metadata-chan (result-metadata-for-updating-async
card-before-update
dataset_query
result_metadata
metadata_checksum)
out-chan (a/promise-chan)]
;; asynchronously wait for our updated result metadata, then after that call `update-card-async!`, which is done
;; on a non-core.async thread. Pipe the results of that into `out-chan`.
(a/go
(try
(let [card-updates (assoc card-updates :result_metadata (a/<! result-metadata-chan))]
(async.u/promise-pipe (update-card-async! card-before-update card-updates) out-chan))
(finally
(a/close! result-metadata-chan))))
out-chan)))
;;; ------------------------------------------------- Deleting Cards -------------------------------------------------
;; TODO - Pretty sure this endpoint is not actually used any more, since Cards are supposed to get archived (via PUT
;; /api/card/:id) instead of deleted. Should we remove this?
(api/defendpoint DELETE "/:id"
"Delete a Card. (DEPRECATED -- don't delete a Card anymore -- archive it instead.)"
[id]
(log/warn (tru "DELETE /api/card/:id is deprecated. Instead, change its `archived` value via PUT /api/card/:id."))
(let [card (api/write-check Card id)]
(db/delete! Card :id id)
(events/publish-event! :card-delete (assoc card :actor_id api/*current-user-id*)))
api/generic-204-no-content)
;;; --------------------------------------------------- Favoriting ---------------------------------------------------
(api/defendpoint POST "/:card-id/favorite"
"Favorite a Card."
[card-id]
(api/read-check Card card-id)
(db/insert! CardFavorite :card_id card-id, :owner_id api/*current-user-id*))
(api/defendpoint DELETE "/:card-id/favorite"
"Unfavorite a Card."
[card-id]
(api/read-check Card card-id)
(api/let-404 [id (db/select-one-id CardFavorite :card_id card-id, :owner_id api/*current-user-id*)]
(db/delete! CardFavorite, :id id))
api/generic-204-no-content)
;;; -------------------------------------------- Bulk Collections Update ---------------------------------------------
(defn- update-collection-positions!
"For cards that have a position in the previous collection, add them to the end of the new collection, trying to
preseve the order from the original collections. Note it's possible for there to be multiple collections
(and thus duplicate collection positions) merged into this new collection. No special tie breaker logic for when
that's the case, just use the order the DB returned it in"
[new-collection-id-or-nil cards]
;; Sorting by `:collection_position` to ensure lower position cards are appended first
(let [sorted-cards (sort-by :collection_position cards)
max-position-result (db/select-one [Card [:%max.collection_position :max_position]]
:collection_id new-collection-id-or-nil)
;; collection_position for the next card in the collection
starting-position (inc (get max-position-result :max_position 0))]
;; This is using `map` but more like a `doseq` with multiple seqs. Wrapping this in a `doall` as we don't want it
;; to be lazy and we're just going to discard the results
(doall
(map (fn [idx {:keys [collection_id collection_position] :as card}]
;; We are removing this card from `collection_id` so we need to reconcile any
;; `collection_position` entries left behind by this move
(api/reconcile-position-for-collection! collection_id collection_position nil)
;; Now we can update the card with the new collection and a new calculated position
;; that appended to the end
(db/update! Card (u/the-id card)
:collection_position idx
:collection_id new-collection-id-or-nil))
;; These are reversed because of the classic issue when removing an item from array. If we remove an
;; item at index 1, everthing above index 1 will get decremented. By reversing our processing order we
;; can avoid changing the index of cards we haven't yet updated
(reverse (range starting-position (+ (count sorted-cards) starting-position)))
(reverse sorted-cards)))))
(defn- move-cards-to-collection! [new-collection-id-or-nil card-ids]
;; if moving to a collection, make sure we have write perms for it
(when new-collection-id-or-nil
(api/write-check Collection new-collection-id-or-nil))
;; for each affected card...
(when (seq card-ids)
(let [cards (db/select [Card :id :collection_id :collection_position :dataset_query]
{:where [:and [:in :id (set card-ids)]
[:or [:not= :collection_id new-collection-id-or-nil]
(when new-collection-id-or-nil
[:= :collection_id nil])]]})] ; poisioned NULLs = ick
;; ...check that we have write permissions for it...
(doseq [card cards]
(api/write-check card))
;; ...and check that we have write permissions for the old collections if applicable
(doseq [old-collection-id (set (filter identity (map :collection_id cards)))]
(api/write-check Collection old-collection-id))
;; Ensure all of the card updates occur in a transaction. Read commited (the default) really isn't what we want
;; here. We are querying for the max card position for a given collection, then using that to base our position
;; changes if the cards are moving to a different collection. Without repeatable read here, it's possible we'll
;; get duplicates
(db/transaction
;; If any of the cards have a `:collection_position`, we'll need to fixup the old collection now that the cards
;; are gone and update the position in the new collection
(when-let [cards-with-position (seq (filter :collection_position cards))]
(update-collection-positions! new-collection-id-or-nil cards-with-position))
;; ok, everything checks out. Set the new `collection_id` for all the Cards that haven't been updated already
(when-let [cards-without-position (seq (for [card cards
:when (not (:collection_position card))]
(u/the-id card)))]
(db/update-where! Card {:id [:in (set cards-without-position)]}
:collection_id new-collection-id-or-nil))))))
(api/defendpoint POST "/collections"
"Bulk update endpoint for Card Collections. Move a set of `Cards` with CARD_IDS into a `Collection` with
COLLECTION_ID, or remove them from any Collections by passing a `null` COLLECTION_ID."
[:as {{:keys [card_ids collection_id]} :body}]
{card_ids [su/IntGreaterThanZero], collection_id (s/maybe su/IntGreaterThanZero)}
(move-cards-to-collection! collection_id card_ids)
{:status :ok})
;;; ------------------------------------------------ Running a Query -------------------------------------------------
(defn- query-magic-ttl
"Compute a 'magic' cache TTL time (in seconds) for QUERY by multipling its historic average execution times by the
`query-caching-ttl-ratio`. If the TTL is less than a second, this returns `nil` (i.e., the cache should not be
utilized.)"
[query]
(when-let [average-duration (query/average-execution-time-ms (qputil/query-hash query))]
(let [ttl-seconds (Math/round (float (/ (* average-duration (public-settings/query-caching-ttl-ratio))
1000.0)))]
(when-not (zero? ttl-seconds)
(log/info (trs "Question''s average execution duration is {0}; using ''magic'' TTL of {1}"
(u/format-milliseconds average-duration) (u/format-seconds ttl-seconds))
(u/emoji "💾"))
ttl-seconds))))
(defn query-for-card
"Generate a query for a saved Card"
[{query :dataset_query
:as card} parameters constraints middleware]
(let [query (-> query
;; don't want default constraints overridding anything that's already there
(m/dissoc-in [:middleware :add-default-userland-constraints?])
(assoc :constraints constraints
:parameters parameters
:middleware middleware))
ttl (when (public-settings/enable-query-caching)
(or (:cache_ttl card)
(query-magic-ttl query)))]
(assoc query :cache-ttl ttl)))
(defn run-query-for-card-async
"Run the query for Card with `parameters` and `constraints`, and return results in a `StreamingResponse` that should
be returned as the result of an API endpoint fn. Will throw an Exception if preconditions (such as read perms) are
not met before returning the `StreamingResponse`."
[card-id export-format
& {:keys [parameters constraints context dashboard-id middleware qp-runner run ignore_cache]
:or {constraints constraints/default-query-constraints
context :question
qp-runner qp/process-query-and-save-execution!}}]
{:pre [(u/maybe? sequential? parameters)]}
(let [run (or run
;; param `run` can be used to control how the query is ran, e.g. if you need to
;; customize the `context` passed to the QP
(^:once fn* [query info]
(qp.streaming/streaming-response [context export-format (u/slugify (:card-name info))]
(binding [qp.perms/*card-id* card-id]
(qp-runner query info context)))))
card (api/read-check (db/select-one [Card :name :dataset_query :cache_ttl :collection_id] :id card-id))
query (-> (assoc (query-for-card card parameters constraints middleware)
:async? true)
(update :middleware (fn [middleware]
(merge
{:js-int-to-string? true :ignore-cached-results? ignore_cache}
middleware))))
info {:executed-by api/*current-user-id*
:context context
:card-id card-id
:card-name (:name card)
:dashboard-id dashboard-id}]
(api/check-not-archived card)
(run query info)))
(api/defendpoint ^:streaming POST "/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache], :or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async
card-id :api
:parameters parameters,
:ignore_cache ignore_cache
:middleware {:process-viz-settings? false}))
(api/defendpoint ^:streaming POST "/:card-id/query/:export-format"
"Run the query associated with a Card, and return its results as a file in the specified format. Note that this
expects the parameters as serialized JSON in the 'parameters' parameter"
[card-id export-format :as {{:keys [parameters]} :params}]
{parameters (s/maybe su/JSONString)
export-format dataset-api/ExportFormat}
(run-query-for-card-async
card-id export-format
:parameters (json/parse-string parameters keyword)
:constraints nil
:context (dataset-api/export-format->context export-format)
:middleware {:process-viz-settings? true
:skip-results-metadata? true
:ignore-cached-results? true
:format-rows? false
:js-int-to-string? false}))
;;; ----------------------------------------------- Sharing is Caring ------------------------------------------------
(api/defendpoint POST "/:card-id/public_link"
"Generate publicly-accessible links for this Card. Returns UUID to be used in public links. (If this Card has
already been shared, it will return the existing public link rather than creating a new one.) Public sharing must
be enabled."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-not-archived (api/read-check Card card-id))
{:uuid (or (db/select-one-field :public_uuid Card :id card-id)
(u/prog1 (str (UUID/randomUUID))
(db/update! Card card-id
:public_uuid <>
:made_public_by_id api/*current-user-id*)))})
(api/defendpoint DELETE "/:card-id/public_link"
"Delete the publicly-accessible link to this Card."
[card-id]
(api/check-superuser)
(api/check-public-sharing-enabled)
(api/check-exists? Card :id card-id, :public_uuid [:not= nil])
(db/update! Card card-id
:public_uuid nil
:made_public_by_id nil)
{:status 204, :body nil})
(api/defendpoint GET "/public"
"Fetch a list of Cards with public UUIDs. These cards are publicly-accessible *if* public sharing is enabled."
[]
(api/check-superuser)
(api/check-public-sharing-enabled)
(db/select [Card :name :id :public_uuid], :public_uuid [:not= nil], :archived false))
(api/defendpoint GET "/embeddable"
"Fetch a list of Cards where `enable_embedding` is `true`. The cards can be embedded using the embedding endpoints
and a signed JWT."
[]
(api/check-superuser)
(api/check-embedding-enabled)
(db/select [Card :name :id], :enable_embedding true, :archived false))
(api/defendpoint GET "/:id/related"
"Return related entities."
[id]
(-> id Card api/read-check related/related))
(api/defendpoint POST "/related"
"Return related entities for an ad-hoc query."
[:as {query :body}]
(related/related (query/adhoc-query query)))
(api/defendpoint ^:streaming POST "/pivot/:card-id/query"
"Run the query associated with a Card."
[card-id :as {{:keys [parameters ignore_cache]
:or {ignore_cache false}} :body}]
{ignore_cache (s/maybe s/Bool)}
(run-query-for-card-async card-id :api
:parameters parameters,
:qp-runner qp.pivot/run-pivot-query
:ignore_cache ignore_cache))
(api/define-routes)
|
[
{
"context": "; Written by Raju\n; Run using following command\n; clojure lazyEvalu",
"end": 17,
"score": 0.9998179078102112,
"start": 13,
"tag": "NAME",
"value": "Raju"
}
] | Chapter09/lazyEvaluation.clj | PacktPublishing/Learning-Functional-Data-Structures-and-Algorithms | 31 | ; Written by Raju
; Run using following command
; clojure lazyEvaluation.clj
; Lazy Evaluation in Clojure
(def lazyVal (delay 10))
(println lazyVal)
(println (realized? lazyVal))
(println (class lazyVal))
(println (deref lazyVal))
(println lazyVal)
(println (realized? lazyVal))
(println (def lazyVal (delay 10)))
(println (force lazyVal))
(println (def lazyVal (delay 10)))
(println @lazyVal)
(println (def fp (promise)))
(println (realized? fp))
(println (deliver fp (str "MyString")))
(println (realized? fp))
(println fp)
(println (deref fp))
(println (def lazyDate ( delay (new java.util.Date))))
(println lazyDate )
(println (def simpleDate (new java.util.Date)))
(println simpleDate)
(println (count [1,2,3,4,5]))
(println simpleDate)
(println (deref lazyDate))
| 84771 | ; Written by <NAME>
; Run using following command
; clojure lazyEvaluation.clj
; Lazy Evaluation in Clojure
(def lazyVal (delay 10))
(println lazyVal)
(println (realized? lazyVal))
(println (class lazyVal))
(println (deref lazyVal))
(println lazyVal)
(println (realized? lazyVal))
(println (def lazyVal (delay 10)))
(println (force lazyVal))
(println (def lazyVal (delay 10)))
(println @lazyVal)
(println (def fp (promise)))
(println (realized? fp))
(println (deliver fp (str "MyString")))
(println (realized? fp))
(println fp)
(println (deref fp))
(println (def lazyDate ( delay (new java.util.Date))))
(println lazyDate )
(println (def simpleDate (new java.util.Date)))
(println simpleDate)
(println (count [1,2,3,4,5]))
(println simpleDate)
(println (deref lazyDate))
| true | ; Written by PI:NAME:<NAME>END_PI
; Run using following command
; clojure lazyEvaluation.clj
; Lazy Evaluation in Clojure
(def lazyVal (delay 10))
(println lazyVal)
(println (realized? lazyVal))
(println (class lazyVal))
(println (deref lazyVal))
(println lazyVal)
(println (realized? lazyVal))
(println (def lazyVal (delay 10)))
(println (force lazyVal))
(println (def lazyVal (delay 10)))
(println @lazyVal)
(println (def fp (promise)))
(println (realized? fp))
(println (deliver fp (str "MyString")))
(println (realized? fp))
(println fp)
(println (deref fp))
(println (def lazyDate ( delay (new java.util.Date))))
(println lazyDate )
(println (def simpleDate (new java.util.Date)))
(println simpleDate)
(println (count [1,2,3,4,5]))
(println simpleDate)
(println (deref lazyDate))
|
[
{
"context": "lient} username password]\n (let [attrs {:username username, :password password}]\n (-> {:params {:profile ",
"end": 237,
"score": 0.8929257392883301,
"start": 229,
"tag": "USERNAME",
"value": "username"
},
{
"context": "word]\n (let [attrs {:username username, :password password}]\n (-> {:params {:profile attrs}}\n (pos",
"end": 257,
"score": 0.7521048188209534,
"start": 249,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "name password]\n :params {:profile {:password new-password}}}\n (put (url/profile host-url username))\n ",
"end": 769,
"score": 0.734144926071167,
"start": 757,
"tag": "PASSWORD",
"value": "new-password"
},
{
"context": "th reset-token\n :params {:profile {:password new-password}}}\n (put (url/profile host-url user",
"end": 1034,
"score": 0.9115943312644958,
"start": 1031,
"tag": "PASSWORD",
"value": "new"
},
{
"context": "set-token\n :params {:profile {:password new-password}}}\n (put (url/profile host-url username))\n ",
"end": 1043,
"score": 0.8458352088928223,
"start": 1035,
"tag": "PASSWORD",
"value": "password"
}
] | src/zanmi/client/user.cljc | zonotope/zanmi-client | 1 | (ns zanmi.client.user
(:require [zanmi.client.request :refer [delete parse-response post put]]
[zanmi.client.url :as url]))
(defn register [{:keys [host-url] :as client} username password]
(let [attrs {:username username, :password password}]
(-> {:params {:profile attrs}}
(post (url/profile-collection host-url))
(parse-response :auth-token))))
(defn authenticate [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(post (url/auth host-url username))
(parse-response :auth-token)))
(defn update-password [{:keys [host-url] :as client} username password
new-password]
(-> {:basic-auth [username password]
:params {:profile {:password new-password}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn reset-password [{:keys [host-url] :as client} username reset-token
new-password]
(-> {:reset-auth reset-token
:params {:profile {:password new-password}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn unregister [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(delete (url/profile host-url username))
(parse-response :message)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; client ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord UserClient [host-url])
(defn user-client [host-url]
(->UserClient host-url))
| 31943 | (ns zanmi.client.user
(:require [zanmi.client.request :refer [delete parse-response post put]]
[zanmi.client.url :as url]))
(defn register [{:keys [host-url] :as client} username password]
(let [attrs {:username username, :password <PASSWORD>}]
(-> {:params {:profile attrs}}
(post (url/profile-collection host-url))
(parse-response :auth-token))))
(defn authenticate [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(post (url/auth host-url username))
(parse-response :auth-token)))
(defn update-password [{:keys [host-url] :as client} username password
new-password]
(-> {:basic-auth [username password]
:params {:profile {:password <PASSWORD>}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn reset-password [{:keys [host-url] :as client} username reset-token
new-password]
(-> {:reset-auth reset-token
:params {:profile {:password <PASSWORD>-<PASSWORD>}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn unregister [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(delete (url/profile host-url username))
(parse-response :message)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; client ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord UserClient [host-url])
(defn user-client [host-url]
(->UserClient host-url))
| true | (ns zanmi.client.user
(:require [zanmi.client.request :refer [delete parse-response post put]]
[zanmi.client.url :as url]))
(defn register [{:keys [host-url] :as client} username password]
(let [attrs {:username username, :password PI:PASSWORD:<PASSWORD>END_PI}]
(-> {:params {:profile attrs}}
(post (url/profile-collection host-url))
(parse-response :auth-token))))
(defn authenticate [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(post (url/auth host-url username))
(parse-response :auth-token)))
(defn update-password [{:keys [host-url] :as client} username password
new-password]
(-> {:basic-auth [username password]
:params {:profile {:password PI:PASSWORD:<PASSWORD>END_PI}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn reset-password [{:keys [host-url] :as client} username reset-token
new-password]
(-> {:reset-auth reset-token
:params {:profile {:password PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI}}}
(put (url/profile host-url username))
(parse-response :auth-token)))
(defn unregister [{:keys [host-url] :as client} username password]
(-> {:basic-auth [username password]}
(delete (url/profile host-url username))
(parse-response :message)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; client ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord UserClient [host-url])
(defn user-client [host-url]
(->UserClient host-url))
|
[
{
"context": "ps://open.relay-chat.com/signup_user_complete/?id=inclojure\n;; IN/Clojure Slack: https://join.slack.com/t/inc",
"end": 275,
"score": 0.9310464859008789,
"start": 266,
"tag": "USERNAME",
"value": "inclojure"
},
{
"context": "e/?id=inclojure\n;; IN/Clojure Slack: https://join.slack.com/t/inclojure/shared_invite/enQtMjkzNDcyMjk1NDY",
"end": 315,
"score": 0.6092303991317749,
"start": 310,
"tag": "KEY",
"value": "slack"
},
{
"context": "lojure\n;; IN/Clojure Slack: https://join.slack.com/t/inclojure/shared_invite/enQtMjkzNDcyMjk1NDYwLWE4Mz",
"end": 322,
"score": 0.7442471385002136,
"start": 320,
"tag": "KEY",
"value": "t/"
},
{
"context": "\n;; IN/Clojure Slack: https://join.slack.com/t/inclojure/shared_invite/enQtMjkzNDcyMjk1NDYwLWE4MzljNGRlZjc",
"end": 331,
"score": 0.6853419542312622,
"start": 325,
"tag": "USERNAME",
"value": "lojure"
},
{
"context": "/Clojure Slack: https://join.slack.com/t/inclojure/shared_invite/enQtMjkzNDcyMjk1NDYwLWE4MzljNGRlZjcwZTRlYWFkODM3Mzc1NmU0M2Q3NjIxZmQ2NTYyZGU3MGVmZGJlMmFjYzBlNWM2Y2IwMjk0Y2Q\n;; Clojure Subreddit: https://www.reddit.com/r/Cl",
"end": 453,
"score": 0.9949475526809692,
"start": 332,
"tag": "KEY",
"value": "shared_invite/enQtMjkzNDcyMjk1NDYwLWE4MzljNGRlZjcwZTRlYWFkODM3Mzc1NmU0M2Q3NjIxZmQ2NTYyZGU3MGVmZGJlMmFjYzBlNWM2Y2IwMjk0Y2Q"
},
{
"context": "ube.com/watch?v=wASCH_gPnDw -- Inside Clojure with Brian Beckman and Rich Hickey\n;; https://www.infoq.com/presenta",
"end": 736,
"score": 0.9997539520263672,
"start": 723,
"tag": "NAME",
"value": "Brian Beckman"
},
{
"context": "SCH_gPnDw -- Inside Clojure with Brian Beckman and Rich Hickey\n;; https://www.infoq.com/presentations/Value-Valu",
"end": 752,
"score": 0.9993308782577515,
"start": 741,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "esentations/Value-Values -- The Value of Values by Rich Hickey\n;; https://www.infoq.com/presentations/Value-Iden",
"end": 842,
"score": 0.9970684051513672,
"start": 831,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "rsistent Data Structures and Managed References by Rich Hickey\n;; https://www.infoq.com/presentations/Simple-Mad",
"end": 982,
"score": 0.9485797882080078,
"start": 971,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "sentations/Simple-Made-Easy -- Simple Made Easy by Rich Hickey\n\n;; Debugging:\n;;\n;; - \"Inside-out\"/\"Bottom-up\" R",
"end": 1073,
"score": 0.9924302697181702,
"start": 1062,
"tag": "NAME",
"value": "Rich Hickey"
}
] | src/clojure_by_example/ex08_but_before_we_go.clj | RiteekS/clojure-by-example | 0 | (ns clojure-by-example.ex08-but-before-we-go)
;; But before we boldly go, here are some resources to help us on our journey!
;; Communities:
;; Clojurians Slack: http://clojurians.net/
;; IN/Clojure Open Relay: https://open.relay-chat.com/signup_user_complete/?id=inclojure
;; IN/Clojure Slack: https://join.slack.com/t/inclojure/shared_invite/enQtMjkzNDcyMjk1NDYwLWE4MzljNGRlZjcwZTRlYWFkODM3Mzc1NmU0M2Q3NjIxZmQ2NTYyZGU3MGVmZGJlMmFjYzBlNWM2Y2IwMjk0Y2Q
;; Clojure Subreddit: https://www.reddit.com/r/Clojure/
;; Books:
;; https://www.braveclojure.com/ -- free to read online
;; The Joy of Clojure -- http://www.joyofclojure.com/
;; Talks/Philosphy:
;; https://www.youtube.com/watch?v=wASCH_gPnDw -- Inside Clojure with Brian Beckman and Rich Hickey
;; https://www.infoq.com/presentations/Value-Values -- The Value of Values by Rich Hickey
;; https://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey -- Persistent Data Structures and Managed References by Rich Hickey
;; https://www.infoq.com/presentations/Simple-Made-Easy -- Simple Made Easy by Rich Hickey
;; Debugging:
;;
;; - "Inside-out"/"Bottom-up" REPL-driven debugging, particularly how
;; Stu Halloway explains, in "Debugging With the Scientific Method".
;; https://www.youtube.com/watch?v=FihU5JxmnBg
;;
;; - Aphyr's post is neat!
;; - Scroll down to the "Debugging Clojure" section:
;; https://aphyr.com/posts/319-clojure-from-the-ground-up-debugging
;; Handy REPL utils:
;;
;; - clojure.repl/
;; - source, doc, pp, pprint, print-table
;; - see the bottom of the `clojure-by-example.utils.core` ns
;;
;; - *1, *2, *3, *e
;;
;; - A sane REPL workflow (buffer/file-based, rather than inside REPL)
;;
| 47569 | (ns clojure-by-example.ex08-but-before-we-go)
;; But before we boldly go, here are some resources to help us on our journey!
;; Communities:
;; Clojurians Slack: http://clojurians.net/
;; IN/Clojure Open Relay: https://open.relay-chat.com/signup_user_complete/?id=inclojure
;; IN/Clojure Slack: https://join.<KEY>.com/<KEY>inclojure/<KEY>
;; Clojure Subreddit: https://www.reddit.com/r/Clojure/
;; Books:
;; https://www.braveclojure.com/ -- free to read online
;; The Joy of Clojure -- http://www.joyofclojure.com/
;; Talks/Philosphy:
;; https://www.youtube.com/watch?v=wASCH_gPnDw -- Inside Clojure with <NAME> and <NAME>
;; https://www.infoq.com/presentations/Value-Values -- The Value of Values by <NAME>
;; https://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey -- Persistent Data Structures and Managed References by <NAME>
;; https://www.infoq.com/presentations/Simple-Made-Easy -- Simple Made Easy by <NAME>
;; Debugging:
;;
;; - "Inside-out"/"Bottom-up" REPL-driven debugging, particularly how
;; Stu Halloway explains, in "Debugging With the Scientific Method".
;; https://www.youtube.com/watch?v=FihU5JxmnBg
;;
;; - Aphyr's post is neat!
;; - Scroll down to the "Debugging Clojure" section:
;; https://aphyr.com/posts/319-clojure-from-the-ground-up-debugging
;; Handy REPL utils:
;;
;; - clojure.repl/
;; - source, doc, pp, pprint, print-table
;; - see the bottom of the `clojure-by-example.utils.core` ns
;;
;; - *1, *2, *3, *e
;;
;; - A sane REPL workflow (buffer/file-based, rather than inside REPL)
;;
| true | (ns clojure-by-example.ex08-but-before-we-go)
;; But before we boldly go, here are some resources to help us on our journey!
;; Communities:
;; Clojurians Slack: http://clojurians.net/
;; IN/Clojure Open Relay: https://open.relay-chat.com/signup_user_complete/?id=inclojure
;; IN/Clojure Slack: https://join.PI:KEY:<KEY>END_PI.com/PI:KEY:<KEY>END_PIinclojure/PI:KEY:<KEY>END_PI
;; Clojure Subreddit: https://www.reddit.com/r/Clojure/
;; Books:
;; https://www.braveclojure.com/ -- free to read online
;; The Joy of Clojure -- http://www.joyofclojure.com/
;; Talks/Philosphy:
;; https://www.youtube.com/watch?v=wASCH_gPnDw -- Inside Clojure with PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
;; https://www.infoq.com/presentations/Value-Values -- The Value of Values by PI:NAME:<NAME>END_PI
;; https://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey -- Persistent Data Structures and Managed References by PI:NAME:<NAME>END_PI
;; https://www.infoq.com/presentations/Simple-Made-Easy -- Simple Made Easy by PI:NAME:<NAME>END_PI
;; Debugging:
;;
;; - "Inside-out"/"Bottom-up" REPL-driven debugging, particularly how
;; Stu Halloway explains, in "Debugging With the Scientific Method".
;; https://www.youtube.com/watch?v=FihU5JxmnBg
;;
;; - Aphyr's post is neat!
;; - Scroll down to the "Debugging Clojure" section:
;; https://aphyr.com/posts/319-clojure-from-the-ground-up-debugging
;; Handy REPL utils:
;;
;; - clojure.repl/
;; - source, doc, pp, pprint, print-table
;; - see the bottom of the `clojure-by-example.utils.core` ns
;;
;; - *1, *2, *3, *e
;;
;; - A sane REPL workflow (buffer/file-based, rather than inside REPL)
;;
|
[
{
"context": "rkBench -- Natural deduction\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 79,
"score": 0.9998955726623535,
"start": 65,
"tag": "NAME",
"value": "Burkhardt Renz"
},
{
"context": "Examples for proofs from Richard Bornat's book\n\n;; Richard Bornat and Bernard Sufrin developed an app called Jape (",
"end": 429,
"score": 0.9965571165084839,
"start": 415,
"tag": "NAME",
"value": "Richard Bornat"
},
{
"context": " from Richard Bornat's book\n\n;; Richard Bornat and Bernard Sufrin developed an app called Jape (just another proof ",
"end": 448,
"score": 0.9997653365135193,
"start": 434,
"tag": "NAME",
"value": "Bernard Sufrin"
},
{
"context": " in Formal Logic: An Introduction for Programmers\" Richard Bornat\n;; describes formal logic with emphasis on natura",
"end": 695,
"score": 0.973362386226654,
"start": 681,
"tag": "NAME",
"value": "Richard Bornat"
}
] | src/lwb/nd/examples/bornat.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Natural deduction
; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
;; # Examples for proofs from Richard Bornat's book
;; Richard Bornat and Bernard Sufrin developed an app called Jape (just another proof editor) for natural deduction in
;; the propositinal and predicate logic, and further logics too.
;; In his book "Proof and Disproof in Formal Logic: An Introduction for Programmers" Richard Bornat
;; describes formal logic with emphasis on natural deduction and demonstrates the concepts with Jape.
;; The book is highly recommended.
;; In this file we reconstruct the examples concerning classical logic from the book in lwb.
(ns lwb.nd.examples.bornat
(:require [lwb.nd.repl :refer :all]))
(load-logic :pred)
; interactive checking in the repl for nd
; -----------------------------------------------------------------------------------------
; p.56
(proof '[(or E F) (not F)] 'E)
(step-f :or-e 1 4)
(step-f :not-e 2 5)
(step-b :efq 8)
;
; --------------------------------------------------
; 1: (or E F) :premise
; 2: (not F) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | E :repeat [3]
; ------------------------------------------------
; ------------------------------------------------
; 5: | F :assumption
; 6: | contradiction :not-e [2 5]
; 7: | E :efq [6]
; ------------------------------------------------
; 8: E :or-e [1 [3 4] [5 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.60
(proof '[(impl E F) (impl F G)] '(impl E G))
(step-b :impl-i 4)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | F :impl-e [1 3]
; 5: | G :impl-e [2 4]
; ------------------------------------------------
; 6: (impl E G) :impl-i [[3 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.64
(proof '(impl (not F) (not E)) '(impl E F))
(step-b :impl-i 3)
(step-b :raa 4)
(step-f :impl-e 1 3)
(step-f :not-e 4 2)
;
; --------------------------------------------------
; 1: (impl (not F) (not E)) :premise
; ------------------------------------------------
; 2: | E :assumption
; | ----------------------------------------------
; 3: | | (not F) :assumption
; 4: | | (not E) :impl-e [1 3]
; 5: | | contradiction :not-e [4 2]
; | ----------------------------------------------
; 6: | F :raa [[3 5]]
; ------------------------------------------------
; 7: (impl E F) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.69
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-e1 1)
(step-f :and-e2 1)
(step-f :and-e1 3)
(step-f :and-e2 3)
(step-f :and-i 2 4)
(step-f :and-i 6 5)
;
; --------------------------------------------------
; 1: (and E (and F G)) :premise
; 2: E :and-e1 [1]
; 3: (and F G) :and-e2 [1]
; 4: F :and-e1 [3]
; 5: G :and-e2 [3]
; 6: (and E F) :and-i [2 4]
; 7: (and (and E F) G) :and-i [6 5]
; --------------------------------------------------
; is a theorem in lwb
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-assocr 1)
; -----------------------------------------------------------------------------------------
; p.70
(proof '[(impl E F) (impl F G) E] 'G)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; 3: E :premise
; 4: F :impl-e [1 3]
; 5: G :impl-e [2 4]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.70
(proof '(impl E (impl F G)) '(impl (and E F) G))
(step-b :impl-i 3)
(step-f :and-e1 2)
(step-f :impl-e 1 3)
(step-f :and-e2 2)
(step-f :impl-e 4 5)
;
; --------------------------------------------------
; 1: (impl E (impl F G)) :premise
; ------------------------------------------------
; 2: | (and E F) :assumption
; 3: | E :and-e1 [2]
; 4: | (impl F G) :impl-e [1 3]
; 5: | F :and-e2 [2]
; 6: | G :impl-e [4 5]
; ------------------------------------------------
; 7: (impl (and E F) G) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.71
(proof '(impl F G) '(impl (or E F) (or E G)))
(step-b :impl-i 3)
(step-f :or-e 2 4)
(step-b :or-i1 5)
(step-f :impl-e 1 5)
(step-b :or-i2 8)
;
; --------------------------------------------------
; 1: (impl F G) :premise
; ------------------------------------------------
; 2: | (or E F) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E G) :or-i1 [3]
; | ----------------------------------------------
; | ----------------------------------------------
; 5: | | F :assumption
; 6: | | G :impl-e [1 5]
; 7: | | (or E G) :or-i2 [6]
; | ----------------------------------------------
; 8: | (or E G) :or-e [2 [3 4] [5 7]]
; ------------------------------------------------
; 9: (impl (or E F) (or E G)) :impl-i [[2 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.73
(proof '(or E F) '(not (and (not E) (not F))))
(step-b :not-i 3)
(step-f :or-e 1 4)
(step-f :and-e1 2)
(step-f :not-e 4 3)
(step-f :and-e2 2)
(step-f :not-e 7 6)
;
; --------------------------------------------------
; 1: (or E F) :premise
; ------------------------------------------------
; 2: | (and (not E) (not F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (not E) :and-e1 [2]
; 5: | | contradiction :not-e [4 3]
; | ----------------------------------------------
; | ----------------------------------------------
; 6: | | F :assumption
; 7: | | (not F) :and-e2 [2]
; 8: | | contradiction :not-e [7 6]
; | ----------------------------------------------
; 9: | contradiction :or-e [1 [3 5] [6 8]]
; ------------------------------------------------
; 10: (not (and (not E) (not F))) :not-i [[2 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.77
(proof '(not (and (not E) (not F))) '(or E F))
(step-b :raa 3)
(step-b :not-e 4 1)
(step-b :and-i 4)
(step-b :not-i 6)
(step-f :or-i2 5)
(swap '?1 'E)
(step-f :not-e 2 6)
(step-b :not-i 4)
(step-f :or-i1 3)
(swap '?2 'F)
(step-f :not-e 2 4)
; --------------------------------------------------
; 1: (not (and (not E) (not F))) :premise
; ------------------------------------------------
; 2: | (not (or E F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E F) :or-i1 [3]
; 5: | | contradiction :not-e [2 4]
; | ----------------------------------------------
; 6: | (not E) :not-i [[3 5]]
; | ----------------------------------------------
; 7: | | F :assumption
; 8: | | (or E F) :or-i2 [7]
; 9: | | contradiction :not-e [2 8]
; | ----------------------------------------------
; 10: | (not F) :not-i [[7 9]]
; 11: | (and (not E) (not F)) :and-i [6 10]
; 12: | contradiction :not-e [1 11]
; ------------------------------------------------
; 13: (or E F) :raa [[2 12]]
; --------------------------------------------------
; or
(proof '(not (and (not E) (not F))) '(or E F))
(step-f :not-and->or-not 1)
(step-f :or-e 2 4)
(step-f :notnot-e 3)
(step-b :or-i1 6)
(step-f :notnot-e 6)
(step-b :or-i2 9)
; -----------------------------------------------------------------------------------------
; p.79
; since we have already shown the result -- it's part of our theorems
; we can do the following
(proof '(or E (not E)))
(step-f :tnd)
(swap '?1 'E)
;
; --------------------------------------------------
; 1: (or E (not E)) :tnd []
; --------------------------------------------------
; here is the actual proof
(proof '(or E (not E)))
(step-b :raa 2)
(step-b :not-e 3 1)
(step-b :or-i2 3)
(step-b :not-i 3)
(step-b :not-e 4 1)
(step-b :or-i1 4)
;
; --------------------------------------------------
; ------------------------------------------------
; 1: | (not (or E (not E))) :assumption
; | ----------------------------------------------
; 2: | | E :assumption
; 3: | | (or E (not E)) :or-i1 [2]
; 4: | | contradiction :not-e [1 3]
; | ----------------------------------------------
; 5: | (not E) :not-i [[2 4]]
; 6: | (or E (not E)) :or-i2 [5]
; 7: | contradiction :not-e [1 6]
; ------------------------------------------------
; 8: (or E (not E)) :raa [[1 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.80
(proof 'F '(impl E F))
(step-b :impl-i 3)
;
; --------------------------------------------------
; 1: F :premise
; ------------------------------------------------
; 2: | E :assumption
; 3: | F :repeat [1]
; ------------------------------------------------
; 4: (impl E F) :impl-i [[2 3]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.123 a stuck proof
; example for a step-f for the elimination of the implication!!
(proof '(impl E F) '(impl (impl F G) (impl E G)))
(step-f :impl-e 1)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: ...
; 3: E
; 4: F :impl-e [1 3]
; 5: ...
; 6: (impl (impl F G) (impl E G))
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.99
(proof '[(actual :k) Dark (impl Dark (forall [x] (forall [y] (not (Saw x y)))))] '(not (exists [z] (Saw z, :k))))
(step-b :not-i 5)
(step-f :exists-e 4 6)
(swap '?1 :i)
(step-f :impl-e 3 2)
(step-f :forall-e 7 5)
(step-f :forall-e 8 1)
(step-f :not-e 9 6)
; --------------------------------------------------
; 1: (actual :k) :premise
; 2: Dark :premise
; 3: (impl Dark (forall [x] (forall [y] (not (Saw x y))))):premise
; ------------------------------------------------
; 4: | (exists [z] (Saw z :k)) :assumption
; | ----------------------------------------------
; 5: | | (actual :i) :assumption
; 6: | | (Saw :i :k) :assumption
; 7: | | (forall [x] (forall [y] (not (Saw x y)))):impl-e [3 2]
; 8: | | (forall [y] (not (Saw :i y))) :forall-e [7 5]
; 9: | | (not (Saw :i :k)) :forall-e [8 1]
; 10: | | contradiction :not-e [9 6]
; | ----------------------------------------------
; 11: | contradiction :exists-e [4 [5 10]]
; ------------------------------------------------
; 12: (not (exists [z] (Saw z :k))) :not-i [[4 11]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.111
(proof '[(forall [x] (impl (R x) (S x))) (forall [y] (impl (S y) (T y)))] '(forall [z] (impl (R z) (T z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-f :forall-e 1 3)
(step-f :forall-e 2 3)
(step-b :impl-i 7)
(step-f :impl-e 4 6)
(step-f :impl-e 5 7)
; --------------------------------------------------
; 1: (forall [x] (impl (R x) (S x))) :premise
; 2: (forall [y] (impl (S y) (T y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; 4: | (impl (R :i) (S :i)) :forall-e [1 3]
; 5: | (impl (S :i) (T :i)) :forall-e [2 3]
; | ----------------------------------------------
; 6: | | (R :i) :assumption
; 7: | | (S :i) :impl-e [4 6]
; 8: | | (T :i) :impl-e [5 7]
; | ----------------------------------------------
; 9: | (impl (R :i) (T :i)) :impl-i [[6 8]]
; ------------------------------------------------
; 10: (forall [z] (impl (R z) (T z))) :forall-i [[3 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.112
(proof '[(actual :j) (forall [x] (R x))] '(exists [y] (R y)))
(step-f :forall-e 2 1)
(step-b :exists-i 5 1)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (forall [x] (R x)) :premise
; 3: (R :j) :forall-e [2 1]
; 4: (exists [y] (R y)) :exists-i [1 3]
; --------------------------------------------------
; with the additional rule :actual
(proof '(forall [x] (R x)) '(exists [y] (R y)))
(step-f :actual)
(swap '?1 :j)
(step-f :forall-e 1 2)
(step-b :exists-i 5 2)
; -----------------------------------------------------------------------------------------
; p.114
(proof '(forall [x] (Green x)) '(forall [y] (impl (Sheep y) (Green y))))
(step-b :forall-i 3)
(swap '?1 :i)
(step-b :impl-i 4)
(step-f :forall-e 1 2)
; --------------------------------------------------
; 1: (forall [x] (Green x)) :premise
; ------------------------------------------------
; 2: | (actual :i) :assumption
; | ----------------------------------------------
; 3: | | (Sheep :i) :assumption
; 4: | | (Green :i) :forall-e [1 2]
; | ----------------------------------------------
; 5: | (impl (Sheep :i) (Green :i)) :impl-i [[3 4]]
; ------------------------------------------------
; 6: (forall [y] (impl (Sheep y) (Green y))) :forall-i [[2 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.115
(proof '[(forall [x] (not (Green x))) (forall [y] (not (Sheep y)))] '(forall [z] (impl (Sheep z) (Green z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-b :impl-i 5)
(step-f :forall-e 2 3)
(step-f :not-e 5 4)
(step-b :efq 8)
; --------------------------------------------------
; 1: (forall [x] (not (Green x))) :premise
; 2: (forall [y] (not (Sheep y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; | ----------------------------------------------
; 4: | | (Sheep :i) :assumption
; 5: | | (not (Sheep :i)) :forall-e [2 3]
; 6: | | contradiction :not-e [5 4]
; 7: | | (Green :i) :efq [6]
; | ----------------------------------------------
; 8: | (impl (Sheep :i) (Green :i)) :impl-i [[4 7]]
; ------------------------------------------------
; 9: (forall [z] (impl (Sheep z) (Green z))) :forall-i [[3 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.117 Drinker's paradoxon
; That's my proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-f :tnd)
(swap '?1 '(and (Drunk :j) (Drunk :k)))
(step-f :or-e 3 5)
(step-f :and-e1 4)
(step-b :exists-i 7 1)
(step-b :impl-i 7)
(step-f :not-and->or-not 10)
(step-f :or-e 11 13)
(step-b :exists-i 14 1)
(step-b :impl-i 14)
(step-f :not-e 12 13)
(step-b :efq 16)
(step-b :exists-i 20 2)
(step-b :impl-i 20)
(step-f :not-e 18 19)
(step-b :efq 22)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; 3: (or (and (Drunk :j) (Drunk :k)) (not (and (Drunk :j) (Drunk :k)))) :tnd []
; ------------------------------------------------
; 4: | (and (Drunk :j) (Drunk :k)) :assumption
; 5: | (Drunk :j) :and-e1 [4]
; | ----------------------------------------------
; 6: | | (Drunk :j) :assumption
; 7: | | (and (Drunk :j) (Drunk :k)) :repeat [4]
; | ----------------------------------------------
; 8: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[6 7]]
; 9: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 8]
; ------------------------------------------------
; ------------------------------------------------
; 10: | (not (and (Drunk :j) (Drunk :k))) :assumption
; 11: | (or (not (Drunk :j)) (not (Drunk :k))):not-and->or-not [10]
; | ----------------------------------------------
; 12: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 13: | | | (Drunk :j) :assumption
; 14: | | | contradiction :not-e [12 13]
; 15: | | | (and (Drunk :j) (Drunk :k)) :efq [14]
; | | --------------------------------------------
; 16: | | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[13 15]]
; 17: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 16]
; | ----------------------------------------------
; | ----------------------------------------------
; 18: | | (not (Drunk :k)) :assumption
; | | --------------------------------------------
; 19: | | | (Drunk :k) :assumption
; 20: | | | contradiction :not-e [18 19]
; 21: | | | (and (Drunk :j) (Drunk :k)) :efq [20]
; | | --------------------------------------------
; 22: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[19 21]]
; 23: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 22]
; | ----------------------------------------------
; 24: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [11 [12 17] [18 23]]
; ------------------------------------------------
; 25: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [3 [4 9] [10 24]]
; --------------------------------------------------
; That's Bornat's proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-b :raa 4)
(step-b :not-e 5 3)
(step-b :exists-i 5 1)
(step-b :impl-i 5)
(step-b :and-i 6)
(step-b :efq 6)
(step-b :not-e 6 3)
(step-b :exists-i 6 2)
(step-b :impl-i 6)
(step-b :and-i 7)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; ------------------------------------------------
; 3: | (not (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k))))) :assumption
; | ----------------------------------------------
; 4: | | (Drunk :j) :assumption
; | | --------------------------------------------
; 5: | | | (Drunk :k) :assumption
; 6: | | | (and (Drunk :j) (Drunk :k)) :and-i [4 5]
; | | --------------------------------------------
; 7: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[5 6]]
; 8: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 7]
; 9: | | contradiction :not-e [3 8]
; 10: | | (Drunk :k) :efq [9]
; 11: | | (and (Drunk :j) (Drunk :k)) :and-i [4 10]
; | ----------------------------------------------
; 12: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[4 11]]
; 13: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 12]
; 14: | contradiction :not-e [3 13]
; ------------------------------------------------
; 15: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :raa [[3 14]]
; --------------------------------------------------
; That's the proof for the more general theorem
(proof '(exists [x] (impl (Drunk x) (forall [y] (Drunk y)))))
(step-f :tnd)
(swap '?1 '(forall [y] (Drunk y)))
(step-f :or-e 1 3)
(step-f :actual)
(swap '?2 :i)
(step-b :exists-i 5 3)
(step-b :impl-i 5)
(step-f :not-forall->exists-not 8)
(step-f :exists-e 9 11)
(swap '?3 :j)
(step-b :exists-i 13 10)
(step-b :impl-i 13)
(step-f :not-e 11 12)
(step-b :efq 15)
; --------------------------------------------------
; 1: (or (forall [y] (Drunk y)) (not (forall [y] (Drunk y)))) :tnd []
; ------------------------------------------------
; 2: | (forall [y] (Drunk y)) :assumption
; 3: | (actual :i) :actual [] ; that's okay since our universe is not empty
; | ----------------------------------------------
; 4: | | (Drunk :i) :assumption
; 5: | | (forall [y] (Drunk y)) :repeat [2]
; | ----------------------------------------------
; 6: | (impl (Drunk :i) (forall [y] (Drunk y))) :impl-i [[4 5]]
; 7: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [3 6]
; ------------------------------------------------
; ------------------------------------------------
; 8: | (not (forall [y] (Drunk y))) :assumption
; 9: | (exists [y] (not (Drunk y))) :not-forall->exists-not [8]
; | ----------------------------------------------
; 10: | | (actual :j) :assumption
; 11: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 12: | | | (Drunk :j) :assumption
; 13: | | | contradiction :not-e [11 12]
; 14: | | | (forall [y] (Drunk y)) :efq [13]
; | | --------------------------------------------
; 15: | | (impl (Drunk :j) (forall [y] (Drunk y))) :impl-i [[12 14]]
; 16: | | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [10 15]
; | ----------------------------------------------
; 17: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-e [9 [10 16]]
; ------------------------------------------------
; 18: (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :or-e [1 [2 7] [8 17]]
; --------------------------------------------------
| 100971 | ; lwb Logic WorkBench -- Natural deduction
; Copyright (c) 2016 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
;; # Examples for proofs from Richard Bornat's book
;; <NAME> and <NAME> developed an app called Jape (just another proof editor) for natural deduction in
;; the propositinal and predicate logic, and further logics too.
;; In his book "Proof and Disproof in Formal Logic: An Introduction for Programmers" <NAME>
;; describes formal logic with emphasis on natural deduction and demonstrates the concepts with Jape.
;; The book is highly recommended.
;; In this file we reconstruct the examples concerning classical logic from the book in lwb.
(ns lwb.nd.examples.bornat
(:require [lwb.nd.repl :refer :all]))
(load-logic :pred)
; interactive checking in the repl for nd
; -----------------------------------------------------------------------------------------
; p.56
(proof '[(or E F) (not F)] 'E)
(step-f :or-e 1 4)
(step-f :not-e 2 5)
(step-b :efq 8)
;
; --------------------------------------------------
; 1: (or E F) :premise
; 2: (not F) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | E :repeat [3]
; ------------------------------------------------
; ------------------------------------------------
; 5: | F :assumption
; 6: | contradiction :not-e [2 5]
; 7: | E :efq [6]
; ------------------------------------------------
; 8: E :or-e [1 [3 4] [5 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.60
(proof '[(impl E F) (impl F G)] '(impl E G))
(step-b :impl-i 4)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | F :impl-e [1 3]
; 5: | G :impl-e [2 4]
; ------------------------------------------------
; 6: (impl E G) :impl-i [[3 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.64
(proof '(impl (not F) (not E)) '(impl E F))
(step-b :impl-i 3)
(step-b :raa 4)
(step-f :impl-e 1 3)
(step-f :not-e 4 2)
;
; --------------------------------------------------
; 1: (impl (not F) (not E)) :premise
; ------------------------------------------------
; 2: | E :assumption
; | ----------------------------------------------
; 3: | | (not F) :assumption
; 4: | | (not E) :impl-e [1 3]
; 5: | | contradiction :not-e [4 2]
; | ----------------------------------------------
; 6: | F :raa [[3 5]]
; ------------------------------------------------
; 7: (impl E F) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.69
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-e1 1)
(step-f :and-e2 1)
(step-f :and-e1 3)
(step-f :and-e2 3)
(step-f :and-i 2 4)
(step-f :and-i 6 5)
;
; --------------------------------------------------
; 1: (and E (and F G)) :premise
; 2: E :and-e1 [1]
; 3: (and F G) :and-e2 [1]
; 4: F :and-e1 [3]
; 5: G :and-e2 [3]
; 6: (and E F) :and-i [2 4]
; 7: (and (and E F) G) :and-i [6 5]
; --------------------------------------------------
; is a theorem in lwb
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-assocr 1)
; -----------------------------------------------------------------------------------------
; p.70
(proof '[(impl E F) (impl F G) E] 'G)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; 3: E :premise
; 4: F :impl-e [1 3]
; 5: G :impl-e [2 4]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.70
(proof '(impl E (impl F G)) '(impl (and E F) G))
(step-b :impl-i 3)
(step-f :and-e1 2)
(step-f :impl-e 1 3)
(step-f :and-e2 2)
(step-f :impl-e 4 5)
;
; --------------------------------------------------
; 1: (impl E (impl F G)) :premise
; ------------------------------------------------
; 2: | (and E F) :assumption
; 3: | E :and-e1 [2]
; 4: | (impl F G) :impl-e [1 3]
; 5: | F :and-e2 [2]
; 6: | G :impl-e [4 5]
; ------------------------------------------------
; 7: (impl (and E F) G) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.71
(proof '(impl F G) '(impl (or E F) (or E G)))
(step-b :impl-i 3)
(step-f :or-e 2 4)
(step-b :or-i1 5)
(step-f :impl-e 1 5)
(step-b :or-i2 8)
;
; --------------------------------------------------
; 1: (impl F G) :premise
; ------------------------------------------------
; 2: | (or E F) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E G) :or-i1 [3]
; | ----------------------------------------------
; | ----------------------------------------------
; 5: | | F :assumption
; 6: | | G :impl-e [1 5]
; 7: | | (or E G) :or-i2 [6]
; | ----------------------------------------------
; 8: | (or E G) :or-e [2 [3 4] [5 7]]
; ------------------------------------------------
; 9: (impl (or E F) (or E G)) :impl-i [[2 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.73
(proof '(or E F) '(not (and (not E) (not F))))
(step-b :not-i 3)
(step-f :or-e 1 4)
(step-f :and-e1 2)
(step-f :not-e 4 3)
(step-f :and-e2 2)
(step-f :not-e 7 6)
;
; --------------------------------------------------
; 1: (or E F) :premise
; ------------------------------------------------
; 2: | (and (not E) (not F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (not E) :and-e1 [2]
; 5: | | contradiction :not-e [4 3]
; | ----------------------------------------------
; | ----------------------------------------------
; 6: | | F :assumption
; 7: | | (not F) :and-e2 [2]
; 8: | | contradiction :not-e [7 6]
; | ----------------------------------------------
; 9: | contradiction :or-e [1 [3 5] [6 8]]
; ------------------------------------------------
; 10: (not (and (not E) (not F))) :not-i [[2 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.77
(proof '(not (and (not E) (not F))) '(or E F))
(step-b :raa 3)
(step-b :not-e 4 1)
(step-b :and-i 4)
(step-b :not-i 6)
(step-f :or-i2 5)
(swap '?1 'E)
(step-f :not-e 2 6)
(step-b :not-i 4)
(step-f :or-i1 3)
(swap '?2 'F)
(step-f :not-e 2 4)
; --------------------------------------------------
; 1: (not (and (not E) (not F))) :premise
; ------------------------------------------------
; 2: | (not (or E F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E F) :or-i1 [3]
; 5: | | contradiction :not-e [2 4]
; | ----------------------------------------------
; 6: | (not E) :not-i [[3 5]]
; | ----------------------------------------------
; 7: | | F :assumption
; 8: | | (or E F) :or-i2 [7]
; 9: | | contradiction :not-e [2 8]
; | ----------------------------------------------
; 10: | (not F) :not-i [[7 9]]
; 11: | (and (not E) (not F)) :and-i [6 10]
; 12: | contradiction :not-e [1 11]
; ------------------------------------------------
; 13: (or E F) :raa [[2 12]]
; --------------------------------------------------
; or
(proof '(not (and (not E) (not F))) '(or E F))
(step-f :not-and->or-not 1)
(step-f :or-e 2 4)
(step-f :notnot-e 3)
(step-b :or-i1 6)
(step-f :notnot-e 6)
(step-b :or-i2 9)
; -----------------------------------------------------------------------------------------
; p.79
; since we have already shown the result -- it's part of our theorems
; we can do the following
(proof '(or E (not E)))
(step-f :tnd)
(swap '?1 'E)
;
; --------------------------------------------------
; 1: (or E (not E)) :tnd []
; --------------------------------------------------
; here is the actual proof
(proof '(or E (not E)))
(step-b :raa 2)
(step-b :not-e 3 1)
(step-b :or-i2 3)
(step-b :not-i 3)
(step-b :not-e 4 1)
(step-b :or-i1 4)
;
; --------------------------------------------------
; ------------------------------------------------
; 1: | (not (or E (not E))) :assumption
; | ----------------------------------------------
; 2: | | E :assumption
; 3: | | (or E (not E)) :or-i1 [2]
; 4: | | contradiction :not-e [1 3]
; | ----------------------------------------------
; 5: | (not E) :not-i [[2 4]]
; 6: | (or E (not E)) :or-i2 [5]
; 7: | contradiction :not-e [1 6]
; ------------------------------------------------
; 8: (or E (not E)) :raa [[1 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.80
(proof 'F '(impl E F))
(step-b :impl-i 3)
;
; --------------------------------------------------
; 1: F :premise
; ------------------------------------------------
; 2: | E :assumption
; 3: | F :repeat [1]
; ------------------------------------------------
; 4: (impl E F) :impl-i [[2 3]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.123 a stuck proof
; example for a step-f for the elimination of the implication!!
(proof '(impl E F) '(impl (impl F G) (impl E G)))
(step-f :impl-e 1)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: ...
; 3: E
; 4: F :impl-e [1 3]
; 5: ...
; 6: (impl (impl F G) (impl E G))
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.99
(proof '[(actual :k) Dark (impl Dark (forall [x] (forall [y] (not (Saw x y)))))] '(not (exists [z] (Saw z, :k))))
(step-b :not-i 5)
(step-f :exists-e 4 6)
(swap '?1 :i)
(step-f :impl-e 3 2)
(step-f :forall-e 7 5)
(step-f :forall-e 8 1)
(step-f :not-e 9 6)
; --------------------------------------------------
; 1: (actual :k) :premise
; 2: Dark :premise
; 3: (impl Dark (forall [x] (forall [y] (not (Saw x y))))):premise
; ------------------------------------------------
; 4: | (exists [z] (Saw z :k)) :assumption
; | ----------------------------------------------
; 5: | | (actual :i) :assumption
; 6: | | (Saw :i :k) :assumption
; 7: | | (forall [x] (forall [y] (not (Saw x y)))):impl-e [3 2]
; 8: | | (forall [y] (not (Saw :i y))) :forall-e [7 5]
; 9: | | (not (Saw :i :k)) :forall-e [8 1]
; 10: | | contradiction :not-e [9 6]
; | ----------------------------------------------
; 11: | contradiction :exists-e [4 [5 10]]
; ------------------------------------------------
; 12: (not (exists [z] (Saw z :k))) :not-i [[4 11]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.111
(proof '[(forall [x] (impl (R x) (S x))) (forall [y] (impl (S y) (T y)))] '(forall [z] (impl (R z) (T z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-f :forall-e 1 3)
(step-f :forall-e 2 3)
(step-b :impl-i 7)
(step-f :impl-e 4 6)
(step-f :impl-e 5 7)
; --------------------------------------------------
; 1: (forall [x] (impl (R x) (S x))) :premise
; 2: (forall [y] (impl (S y) (T y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; 4: | (impl (R :i) (S :i)) :forall-e [1 3]
; 5: | (impl (S :i) (T :i)) :forall-e [2 3]
; | ----------------------------------------------
; 6: | | (R :i) :assumption
; 7: | | (S :i) :impl-e [4 6]
; 8: | | (T :i) :impl-e [5 7]
; | ----------------------------------------------
; 9: | (impl (R :i) (T :i)) :impl-i [[6 8]]
; ------------------------------------------------
; 10: (forall [z] (impl (R z) (T z))) :forall-i [[3 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.112
(proof '[(actual :j) (forall [x] (R x))] '(exists [y] (R y)))
(step-f :forall-e 2 1)
(step-b :exists-i 5 1)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (forall [x] (R x)) :premise
; 3: (R :j) :forall-e [2 1]
; 4: (exists [y] (R y)) :exists-i [1 3]
; --------------------------------------------------
; with the additional rule :actual
(proof '(forall [x] (R x)) '(exists [y] (R y)))
(step-f :actual)
(swap '?1 :j)
(step-f :forall-e 1 2)
(step-b :exists-i 5 2)
; -----------------------------------------------------------------------------------------
; p.114
(proof '(forall [x] (Green x)) '(forall [y] (impl (Sheep y) (Green y))))
(step-b :forall-i 3)
(swap '?1 :i)
(step-b :impl-i 4)
(step-f :forall-e 1 2)
; --------------------------------------------------
; 1: (forall [x] (Green x)) :premise
; ------------------------------------------------
; 2: | (actual :i) :assumption
; | ----------------------------------------------
; 3: | | (Sheep :i) :assumption
; 4: | | (Green :i) :forall-e [1 2]
; | ----------------------------------------------
; 5: | (impl (Sheep :i) (Green :i)) :impl-i [[3 4]]
; ------------------------------------------------
; 6: (forall [y] (impl (Sheep y) (Green y))) :forall-i [[2 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.115
(proof '[(forall [x] (not (Green x))) (forall [y] (not (Sheep y)))] '(forall [z] (impl (Sheep z) (Green z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-b :impl-i 5)
(step-f :forall-e 2 3)
(step-f :not-e 5 4)
(step-b :efq 8)
; --------------------------------------------------
; 1: (forall [x] (not (Green x))) :premise
; 2: (forall [y] (not (Sheep y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; | ----------------------------------------------
; 4: | | (Sheep :i) :assumption
; 5: | | (not (Sheep :i)) :forall-e [2 3]
; 6: | | contradiction :not-e [5 4]
; 7: | | (Green :i) :efq [6]
; | ----------------------------------------------
; 8: | (impl (Sheep :i) (Green :i)) :impl-i [[4 7]]
; ------------------------------------------------
; 9: (forall [z] (impl (Sheep z) (Green z))) :forall-i [[3 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.117 Drinker's paradoxon
; That's my proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-f :tnd)
(swap '?1 '(and (Drunk :j) (Drunk :k)))
(step-f :or-e 3 5)
(step-f :and-e1 4)
(step-b :exists-i 7 1)
(step-b :impl-i 7)
(step-f :not-and->or-not 10)
(step-f :or-e 11 13)
(step-b :exists-i 14 1)
(step-b :impl-i 14)
(step-f :not-e 12 13)
(step-b :efq 16)
(step-b :exists-i 20 2)
(step-b :impl-i 20)
(step-f :not-e 18 19)
(step-b :efq 22)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; 3: (or (and (Drunk :j) (Drunk :k)) (not (and (Drunk :j) (Drunk :k)))) :tnd []
; ------------------------------------------------
; 4: | (and (Drunk :j) (Drunk :k)) :assumption
; 5: | (Drunk :j) :and-e1 [4]
; | ----------------------------------------------
; 6: | | (Drunk :j) :assumption
; 7: | | (and (Drunk :j) (Drunk :k)) :repeat [4]
; | ----------------------------------------------
; 8: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[6 7]]
; 9: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 8]
; ------------------------------------------------
; ------------------------------------------------
; 10: | (not (and (Drunk :j) (Drunk :k))) :assumption
; 11: | (or (not (Drunk :j)) (not (Drunk :k))):not-and->or-not [10]
; | ----------------------------------------------
; 12: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 13: | | | (Drunk :j) :assumption
; 14: | | | contradiction :not-e [12 13]
; 15: | | | (and (Drunk :j) (Drunk :k)) :efq [14]
; | | --------------------------------------------
; 16: | | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[13 15]]
; 17: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 16]
; | ----------------------------------------------
; | ----------------------------------------------
; 18: | | (not (Drunk :k)) :assumption
; | | --------------------------------------------
; 19: | | | (Drunk :k) :assumption
; 20: | | | contradiction :not-e [18 19]
; 21: | | | (and (Drunk :j) (Drunk :k)) :efq [20]
; | | --------------------------------------------
; 22: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[19 21]]
; 23: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 22]
; | ----------------------------------------------
; 24: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [11 [12 17] [18 23]]
; ------------------------------------------------
; 25: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [3 [4 9] [10 24]]
; --------------------------------------------------
; That's Bornat's proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-b :raa 4)
(step-b :not-e 5 3)
(step-b :exists-i 5 1)
(step-b :impl-i 5)
(step-b :and-i 6)
(step-b :efq 6)
(step-b :not-e 6 3)
(step-b :exists-i 6 2)
(step-b :impl-i 6)
(step-b :and-i 7)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; ------------------------------------------------
; 3: | (not (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k))))) :assumption
; | ----------------------------------------------
; 4: | | (Drunk :j) :assumption
; | | --------------------------------------------
; 5: | | | (Drunk :k) :assumption
; 6: | | | (and (Drunk :j) (Drunk :k)) :and-i [4 5]
; | | --------------------------------------------
; 7: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[5 6]]
; 8: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 7]
; 9: | | contradiction :not-e [3 8]
; 10: | | (Drunk :k) :efq [9]
; 11: | | (and (Drunk :j) (Drunk :k)) :and-i [4 10]
; | ----------------------------------------------
; 12: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[4 11]]
; 13: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 12]
; 14: | contradiction :not-e [3 13]
; ------------------------------------------------
; 15: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :raa [[3 14]]
; --------------------------------------------------
; That's the proof for the more general theorem
(proof '(exists [x] (impl (Drunk x) (forall [y] (Drunk y)))))
(step-f :tnd)
(swap '?1 '(forall [y] (Drunk y)))
(step-f :or-e 1 3)
(step-f :actual)
(swap '?2 :i)
(step-b :exists-i 5 3)
(step-b :impl-i 5)
(step-f :not-forall->exists-not 8)
(step-f :exists-e 9 11)
(swap '?3 :j)
(step-b :exists-i 13 10)
(step-b :impl-i 13)
(step-f :not-e 11 12)
(step-b :efq 15)
; --------------------------------------------------
; 1: (or (forall [y] (Drunk y)) (not (forall [y] (Drunk y)))) :tnd []
; ------------------------------------------------
; 2: | (forall [y] (Drunk y)) :assumption
; 3: | (actual :i) :actual [] ; that's okay since our universe is not empty
; | ----------------------------------------------
; 4: | | (Drunk :i) :assumption
; 5: | | (forall [y] (Drunk y)) :repeat [2]
; | ----------------------------------------------
; 6: | (impl (Drunk :i) (forall [y] (Drunk y))) :impl-i [[4 5]]
; 7: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [3 6]
; ------------------------------------------------
; ------------------------------------------------
; 8: | (not (forall [y] (Drunk y))) :assumption
; 9: | (exists [y] (not (Drunk y))) :not-forall->exists-not [8]
; | ----------------------------------------------
; 10: | | (actual :j) :assumption
; 11: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 12: | | | (Drunk :j) :assumption
; 13: | | | contradiction :not-e [11 12]
; 14: | | | (forall [y] (Drunk y)) :efq [13]
; | | --------------------------------------------
; 15: | | (impl (Drunk :j) (forall [y] (Drunk y))) :impl-i [[12 14]]
; 16: | | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [10 15]
; | ----------------------------------------------
; 17: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-e [9 [10 16]]
; ------------------------------------------------
; 18: (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :or-e [1 [2 7] [8 17]]
; --------------------------------------------------
| true | ; lwb Logic WorkBench -- Natural deduction
; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
;; # Examples for proofs from Richard Bornat's book
;; PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI developed an app called Jape (just another proof editor) for natural deduction in
;; the propositinal and predicate logic, and further logics too.
;; In his book "Proof and Disproof in Formal Logic: An Introduction for Programmers" PI:NAME:<NAME>END_PI
;; describes formal logic with emphasis on natural deduction and demonstrates the concepts with Jape.
;; The book is highly recommended.
;; In this file we reconstruct the examples concerning classical logic from the book in lwb.
(ns lwb.nd.examples.bornat
(:require [lwb.nd.repl :refer :all]))
(load-logic :pred)
; interactive checking in the repl for nd
; -----------------------------------------------------------------------------------------
; p.56
(proof '[(or E F) (not F)] 'E)
(step-f :or-e 1 4)
(step-f :not-e 2 5)
(step-b :efq 8)
;
; --------------------------------------------------
; 1: (or E F) :premise
; 2: (not F) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | E :repeat [3]
; ------------------------------------------------
; ------------------------------------------------
; 5: | F :assumption
; 6: | contradiction :not-e [2 5]
; 7: | E :efq [6]
; ------------------------------------------------
; 8: E :or-e [1 [3 4] [5 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.60
(proof '[(impl E F) (impl F G)] '(impl E G))
(step-b :impl-i 4)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; ------------------------------------------------
; 3: | E :assumption
; 4: | F :impl-e [1 3]
; 5: | G :impl-e [2 4]
; ------------------------------------------------
; 6: (impl E G) :impl-i [[3 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.64
(proof '(impl (not F) (not E)) '(impl E F))
(step-b :impl-i 3)
(step-b :raa 4)
(step-f :impl-e 1 3)
(step-f :not-e 4 2)
;
; --------------------------------------------------
; 1: (impl (not F) (not E)) :premise
; ------------------------------------------------
; 2: | E :assumption
; | ----------------------------------------------
; 3: | | (not F) :assumption
; 4: | | (not E) :impl-e [1 3]
; 5: | | contradiction :not-e [4 2]
; | ----------------------------------------------
; 6: | F :raa [[3 5]]
; ------------------------------------------------
; 7: (impl E F) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.69
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-e1 1)
(step-f :and-e2 1)
(step-f :and-e1 3)
(step-f :and-e2 3)
(step-f :and-i 2 4)
(step-f :and-i 6 5)
;
; --------------------------------------------------
; 1: (and E (and F G)) :premise
; 2: E :and-e1 [1]
; 3: (and F G) :and-e2 [1]
; 4: F :and-e1 [3]
; 5: G :and-e2 [3]
; 6: (and E F) :and-i [2 4]
; 7: (and (and E F) G) :and-i [6 5]
; --------------------------------------------------
; is a theorem in lwb
(proof '(and E (and F G)) '(and (and E F) G))
(step-f :and-assocr 1)
; -----------------------------------------------------------------------------------------
; p.70
(proof '[(impl E F) (impl F G) E] 'G)
(step-f :impl-e 1 3)
(step-f :impl-e 2 4)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: (impl F G) :premise
; 3: E :premise
; 4: F :impl-e [1 3]
; 5: G :impl-e [2 4]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.70
(proof '(impl E (impl F G)) '(impl (and E F) G))
(step-b :impl-i 3)
(step-f :and-e1 2)
(step-f :impl-e 1 3)
(step-f :and-e2 2)
(step-f :impl-e 4 5)
;
; --------------------------------------------------
; 1: (impl E (impl F G)) :premise
; ------------------------------------------------
; 2: | (and E F) :assumption
; 3: | E :and-e1 [2]
; 4: | (impl F G) :impl-e [1 3]
; 5: | F :and-e2 [2]
; 6: | G :impl-e [4 5]
; ------------------------------------------------
; 7: (impl (and E F) G) :impl-i [[2 6]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.71
(proof '(impl F G) '(impl (or E F) (or E G)))
(step-b :impl-i 3)
(step-f :or-e 2 4)
(step-b :or-i1 5)
(step-f :impl-e 1 5)
(step-b :or-i2 8)
;
; --------------------------------------------------
; 1: (impl F G) :premise
; ------------------------------------------------
; 2: | (or E F) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E G) :or-i1 [3]
; | ----------------------------------------------
; | ----------------------------------------------
; 5: | | F :assumption
; 6: | | G :impl-e [1 5]
; 7: | | (or E G) :or-i2 [6]
; | ----------------------------------------------
; 8: | (or E G) :or-e [2 [3 4] [5 7]]
; ------------------------------------------------
; 9: (impl (or E F) (or E G)) :impl-i [[2 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.73
(proof '(or E F) '(not (and (not E) (not F))))
(step-b :not-i 3)
(step-f :or-e 1 4)
(step-f :and-e1 2)
(step-f :not-e 4 3)
(step-f :and-e2 2)
(step-f :not-e 7 6)
;
; --------------------------------------------------
; 1: (or E F) :premise
; ------------------------------------------------
; 2: | (and (not E) (not F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (not E) :and-e1 [2]
; 5: | | contradiction :not-e [4 3]
; | ----------------------------------------------
; | ----------------------------------------------
; 6: | | F :assumption
; 7: | | (not F) :and-e2 [2]
; 8: | | contradiction :not-e [7 6]
; | ----------------------------------------------
; 9: | contradiction :or-e [1 [3 5] [6 8]]
; ------------------------------------------------
; 10: (not (and (not E) (not F))) :not-i [[2 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.77
(proof '(not (and (not E) (not F))) '(or E F))
(step-b :raa 3)
(step-b :not-e 4 1)
(step-b :and-i 4)
(step-b :not-i 6)
(step-f :or-i2 5)
(swap '?1 'E)
(step-f :not-e 2 6)
(step-b :not-i 4)
(step-f :or-i1 3)
(swap '?2 'F)
(step-f :not-e 2 4)
; --------------------------------------------------
; 1: (not (and (not E) (not F))) :premise
; ------------------------------------------------
; 2: | (not (or E F)) :assumption
; | ----------------------------------------------
; 3: | | E :assumption
; 4: | | (or E F) :or-i1 [3]
; 5: | | contradiction :not-e [2 4]
; | ----------------------------------------------
; 6: | (not E) :not-i [[3 5]]
; | ----------------------------------------------
; 7: | | F :assumption
; 8: | | (or E F) :or-i2 [7]
; 9: | | contradiction :not-e [2 8]
; | ----------------------------------------------
; 10: | (not F) :not-i [[7 9]]
; 11: | (and (not E) (not F)) :and-i [6 10]
; 12: | contradiction :not-e [1 11]
; ------------------------------------------------
; 13: (or E F) :raa [[2 12]]
; --------------------------------------------------
; or
(proof '(not (and (not E) (not F))) '(or E F))
(step-f :not-and->or-not 1)
(step-f :or-e 2 4)
(step-f :notnot-e 3)
(step-b :or-i1 6)
(step-f :notnot-e 6)
(step-b :or-i2 9)
; -----------------------------------------------------------------------------------------
; p.79
; since we have already shown the result -- it's part of our theorems
; we can do the following
(proof '(or E (not E)))
(step-f :tnd)
(swap '?1 'E)
;
; --------------------------------------------------
; 1: (or E (not E)) :tnd []
; --------------------------------------------------
; here is the actual proof
(proof '(or E (not E)))
(step-b :raa 2)
(step-b :not-e 3 1)
(step-b :or-i2 3)
(step-b :not-i 3)
(step-b :not-e 4 1)
(step-b :or-i1 4)
;
; --------------------------------------------------
; ------------------------------------------------
; 1: | (not (or E (not E))) :assumption
; | ----------------------------------------------
; 2: | | E :assumption
; 3: | | (or E (not E)) :or-i1 [2]
; 4: | | contradiction :not-e [1 3]
; | ----------------------------------------------
; 5: | (not E) :not-i [[2 4]]
; 6: | (or E (not E)) :or-i2 [5]
; 7: | contradiction :not-e [1 6]
; ------------------------------------------------
; 8: (or E (not E)) :raa [[1 7]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.80
(proof 'F '(impl E F))
(step-b :impl-i 3)
;
; --------------------------------------------------
; 1: F :premise
; ------------------------------------------------
; 2: | E :assumption
; 3: | F :repeat [1]
; ------------------------------------------------
; 4: (impl E F) :impl-i [[2 3]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.123 a stuck proof
; example for a step-f for the elimination of the implication!!
(proof '(impl E F) '(impl (impl F G) (impl E G)))
(step-f :impl-e 1)
;
; --------------------------------------------------
; 1: (impl E F) :premise
; 2: ...
; 3: E
; 4: F :impl-e [1 3]
; 5: ...
; 6: (impl (impl F G) (impl E G))
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.99
(proof '[(actual :k) Dark (impl Dark (forall [x] (forall [y] (not (Saw x y)))))] '(not (exists [z] (Saw z, :k))))
(step-b :not-i 5)
(step-f :exists-e 4 6)
(swap '?1 :i)
(step-f :impl-e 3 2)
(step-f :forall-e 7 5)
(step-f :forall-e 8 1)
(step-f :not-e 9 6)
; --------------------------------------------------
; 1: (actual :k) :premise
; 2: Dark :premise
; 3: (impl Dark (forall [x] (forall [y] (not (Saw x y))))):premise
; ------------------------------------------------
; 4: | (exists [z] (Saw z :k)) :assumption
; | ----------------------------------------------
; 5: | | (actual :i) :assumption
; 6: | | (Saw :i :k) :assumption
; 7: | | (forall [x] (forall [y] (not (Saw x y)))):impl-e [3 2]
; 8: | | (forall [y] (not (Saw :i y))) :forall-e [7 5]
; 9: | | (not (Saw :i :k)) :forall-e [8 1]
; 10: | | contradiction :not-e [9 6]
; | ----------------------------------------------
; 11: | contradiction :exists-e [4 [5 10]]
; ------------------------------------------------
; 12: (not (exists [z] (Saw z :k))) :not-i [[4 11]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.111
(proof '[(forall [x] (impl (R x) (S x))) (forall [y] (impl (S y) (T y)))] '(forall [z] (impl (R z) (T z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-f :forall-e 1 3)
(step-f :forall-e 2 3)
(step-b :impl-i 7)
(step-f :impl-e 4 6)
(step-f :impl-e 5 7)
; --------------------------------------------------
; 1: (forall [x] (impl (R x) (S x))) :premise
; 2: (forall [y] (impl (S y) (T y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; 4: | (impl (R :i) (S :i)) :forall-e [1 3]
; 5: | (impl (S :i) (T :i)) :forall-e [2 3]
; | ----------------------------------------------
; 6: | | (R :i) :assumption
; 7: | | (S :i) :impl-e [4 6]
; 8: | | (T :i) :impl-e [5 7]
; | ----------------------------------------------
; 9: | (impl (R :i) (T :i)) :impl-i [[6 8]]
; ------------------------------------------------
; 10: (forall [z] (impl (R z) (T z))) :forall-i [[3 9]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.112
(proof '[(actual :j) (forall [x] (R x))] '(exists [y] (R y)))
(step-f :forall-e 2 1)
(step-b :exists-i 5 1)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (forall [x] (R x)) :premise
; 3: (R :j) :forall-e [2 1]
; 4: (exists [y] (R y)) :exists-i [1 3]
; --------------------------------------------------
; with the additional rule :actual
(proof '(forall [x] (R x)) '(exists [y] (R y)))
(step-f :actual)
(swap '?1 :j)
(step-f :forall-e 1 2)
(step-b :exists-i 5 2)
; -----------------------------------------------------------------------------------------
; p.114
(proof '(forall [x] (Green x)) '(forall [y] (impl (Sheep y) (Green y))))
(step-b :forall-i 3)
(swap '?1 :i)
(step-b :impl-i 4)
(step-f :forall-e 1 2)
; --------------------------------------------------
; 1: (forall [x] (Green x)) :premise
; ------------------------------------------------
; 2: | (actual :i) :assumption
; | ----------------------------------------------
; 3: | | (Sheep :i) :assumption
; 4: | | (Green :i) :forall-e [1 2]
; | ----------------------------------------------
; 5: | (impl (Sheep :i) (Green :i)) :impl-i [[3 4]]
; ------------------------------------------------
; 6: (forall [y] (impl (Sheep y) (Green y))) :forall-i [[2 5]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.115
(proof '[(forall [x] (not (Green x))) (forall [y] (not (Sheep y)))] '(forall [z] (impl (Sheep z) (Green z))))
(step-b :forall-i 4)
(swap '?1 :i)
(step-b :impl-i 5)
(step-f :forall-e 2 3)
(step-f :not-e 5 4)
(step-b :efq 8)
; --------------------------------------------------
; 1: (forall [x] (not (Green x))) :premise
; 2: (forall [y] (not (Sheep y))) :premise
; ------------------------------------------------
; 3: | (actual :i) :assumption
; | ----------------------------------------------
; 4: | | (Sheep :i) :assumption
; 5: | | (not (Sheep :i)) :forall-e [2 3]
; 6: | | contradiction :not-e [5 4]
; 7: | | (Green :i) :efq [6]
; | ----------------------------------------------
; 8: | (impl (Sheep :i) (Green :i)) :impl-i [[4 7]]
; ------------------------------------------------
; 9: (forall [z] (impl (Sheep z) (Green z))) :forall-i [[3 8]]
; --------------------------------------------------
; -----------------------------------------------------------------------------------------
; p.117 Drinker's paradoxon
; That's my proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-f :tnd)
(swap '?1 '(and (Drunk :j) (Drunk :k)))
(step-f :or-e 3 5)
(step-f :and-e1 4)
(step-b :exists-i 7 1)
(step-b :impl-i 7)
(step-f :not-and->or-not 10)
(step-f :or-e 11 13)
(step-b :exists-i 14 1)
(step-b :impl-i 14)
(step-f :not-e 12 13)
(step-b :efq 16)
(step-b :exists-i 20 2)
(step-b :impl-i 20)
(step-f :not-e 18 19)
(step-b :efq 22)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; 3: (or (and (Drunk :j) (Drunk :k)) (not (and (Drunk :j) (Drunk :k)))) :tnd []
; ------------------------------------------------
; 4: | (and (Drunk :j) (Drunk :k)) :assumption
; 5: | (Drunk :j) :and-e1 [4]
; | ----------------------------------------------
; 6: | | (Drunk :j) :assumption
; 7: | | (and (Drunk :j) (Drunk :k)) :repeat [4]
; | ----------------------------------------------
; 8: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[6 7]]
; 9: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 8]
; ------------------------------------------------
; ------------------------------------------------
; 10: | (not (and (Drunk :j) (Drunk :k))) :assumption
; 11: | (or (not (Drunk :j)) (not (Drunk :k))):not-and->or-not [10]
; | ----------------------------------------------
; 12: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 13: | | | (Drunk :j) :assumption
; 14: | | | contradiction :not-e [12 13]
; 15: | | | (and (Drunk :j) (Drunk :k)) :efq [14]
; | | --------------------------------------------
; 16: | | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[13 15]]
; 17: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 16]
; | ----------------------------------------------
; | ----------------------------------------------
; 18: | | (not (Drunk :k)) :assumption
; | | --------------------------------------------
; 19: | | | (Drunk :k) :assumption
; 20: | | | contradiction :not-e [18 19]
; 21: | | | (and (Drunk :j) (Drunk :k)) :efq [20]
; | | --------------------------------------------
; 22: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[19 21]]
; 23: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 22]
; | ----------------------------------------------
; 24: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [11 [12 17] [18 23]]
; ------------------------------------------------
; 25: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :or-e [3 [4 9] [10 24]]
; --------------------------------------------------
; That's Bornat's proof
(proof '[(actual :j) (actual :k)] '(exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))))
(step-b :raa 4)
(step-b :not-e 5 3)
(step-b :exists-i 5 1)
(step-b :impl-i 5)
(step-b :and-i 6)
(step-b :efq 6)
(step-b :not-e 6 3)
(step-b :exists-i 6 2)
(step-b :impl-i 6)
(step-b :and-i 7)
; --------------------------------------------------
; 1: (actual :j) :premise
; 2: (actual :k) :premise
; ------------------------------------------------
; 3: | (not (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k))))) :assumption
; | ----------------------------------------------
; 4: | | (Drunk :j) :assumption
; | | --------------------------------------------
; 5: | | | (Drunk :k) :assumption
; 6: | | | (and (Drunk :j) (Drunk :k)) :and-i [4 5]
; | | --------------------------------------------
; 7: | | (impl (Drunk :k) (and (Drunk :j) (Drunk :k))) :impl-i [[5 6]]
; 8: | | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [2 7]
; 9: | | contradiction :not-e [3 8]
; 10: | | (Drunk :k) :efq [9]
; 11: | | (and (Drunk :j) (Drunk :k)) :and-i [4 10]
; | ----------------------------------------------
; 12: | (impl (Drunk :j) (and (Drunk :j) (Drunk :k))) :impl-i [[4 11]]
; 13: | (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :exists-i [1 12]
; 14: | contradiction :not-e [3 13]
; ------------------------------------------------
; 15: (exists [x] (impl (Drunk x) (and (Drunk :j) (Drunk :k)))) :raa [[3 14]]
; --------------------------------------------------
; That's the proof for the more general theorem
(proof '(exists [x] (impl (Drunk x) (forall [y] (Drunk y)))))
(step-f :tnd)
(swap '?1 '(forall [y] (Drunk y)))
(step-f :or-e 1 3)
(step-f :actual)
(swap '?2 :i)
(step-b :exists-i 5 3)
(step-b :impl-i 5)
(step-f :not-forall->exists-not 8)
(step-f :exists-e 9 11)
(swap '?3 :j)
(step-b :exists-i 13 10)
(step-b :impl-i 13)
(step-f :not-e 11 12)
(step-b :efq 15)
; --------------------------------------------------
; 1: (or (forall [y] (Drunk y)) (not (forall [y] (Drunk y)))) :tnd []
; ------------------------------------------------
; 2: | (forall [y] (Drunk y)) :assumption
; 3: | (actual :i) :actual [] ; that's okay since our universe is not empty
; | ----------------------------------------------
; 4: | | (Drunk :i) :assumption
; 5: | | (forall [y] (Drunk y)) :repeat [2]
; | ----------------------------------------------
; 6: | (impl (Drunk :i) (forall [y] (Drunk y))) :impl-i [[4 5]]
; 7: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [3 6]
; ------------------------------------------------
; ------------------------------------------------
; 8: | (not (forall [y] (Drunk y))) :assumption
; 9: | (exists [y] (not (Drunk y))) :not-forall->exists-not [8]
; | ----------------------------------------------
; 10: | | (actual :j) :assumption
; 11: | | (not (Drunk :j)) :assumption
; | | --------------------------------------------
; 12: | | | (Drunk :j) :assumption
; 13: | | | contradiction :not-e [11 12]
; 14: | | | (forall [y] (Drunk y)) :efq [13]
; | | --------------------------------------------
; 15: | | (impl (Drunk :j) (forall [y] (Drunk y))) :impl-i [[12 14]]
; 16: | | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-i [10 15]
; | ----------------------------------------------
; 17: | (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :exists-e [9 [10 16]]
; ------------------------------------------------
; 18: (exists [x] (impl (Drunk x) (forall [y] (Drunk y)))) :or-e [1 [2 7] [8 17]]
; --------------------------------------------------
|
[
{
"context": "(atom {:name\n {:first-name \"John\" :last-name \"Smith\"}}))\n\n(defn parent []\n [:div\n",
"end": 1103,
"score": 0.9998766183853149,
"start": 1099,
"tag": "NAME",
"value": "John"
},
{
"context": " {:first-name \"John\" :last-name \"Smith\"}}))\n\n(defn parent []\n [:div\n [:p \"Current sta",
"end": 1122,
"score": 0.9997801780700684,
"start": 1117,
"tag": "NAME",
"value": "Smith"
},
{
"context": "element\")\n\n(def figwheel-link \"https://github.com/bhauman/lein-figwheel\")\n\n(defn main [{:keys [summary]}]\n ",
"end": 2047,
"score": 0.9996944069862366,
"start": 2040,
"tag": "USERNAME",
"value": "bhauman"
}
] | demo/reagentdemo/news/news050.cljs | tomconnors/reagent | 0 | (ns reagentdemo.news.news050
(:require [reagent.core :as r :refer [atom]]
[reagent.interop :refer-macros [.' .!]]
[reagent.debug :refer-macros [dbg println]]
[reagentdemo.syntax :as s :include-macros true]
[sitetools :as tools :refer [link]]
[reagentdemo.common :as common :refer [demo-component]]
[todomvc :as todomvc]))
(def url "news/news050.html")
(def title "News in 0.5.0-alpha")
(def ns-src (s/syntaxed "(ns example
(:require [reagent.core :as r :refer [atom]]))"))
(defn input [prompt val]
[:div
prompt
[:input {:value @val
:on-change #(reset! val (.-target.value %))}]])
(defn name-edit [n]
(let [{:keys [first-name last-name]} @n]
[:div
[:p "I'm editing " first-name " " last-name "."]
[input "First name: " (r/wrap first-name
swap! n assoc :first-name)]
[input "Last name: " (r/wrap last-name
swap! n assoc :last-name)]]))
(defonce person (atom {:name
{:first-name "John" :last-name "Smith"}}))
(defn parent []
[:div
[:p "Current state: " (pr-str @person)]
[name-edit (r/wrap (:name @person)
swap! person assoc :name)]])
(defn integration []
[:div
[:div.foo "Hello " [:strong "world"]]
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/create-element "strong"
#js{}
"world"))
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/as-element [:strong "world"]))
[:div.foo "Hello " (r/create-element "strong"
#js{}
"world")]])
(def cel-link "http://facebook.github.io/react/docs/top-level-api.html#react.createelement")
(def figwheel-link "https://github.com/bhauman/lein-figwheel")
(defn main [{:keys [summary]}]
[:div.reagent-demo
[:h1 [link {:href url} title]]
[:div.demo-text
[:p "Lots of new features (and one breaking change) in Reagent
0.5.0-alpha."]
(if summary
[link {:href url
:class 'news-read-more} "Read more"]
[:div.demo-text
[:h2 "Splitting atoms"]
[:p "Reagent now has a simple way to make reusable components
that edit part of a parents state: "]
[:p " The new " [:code "wrap"] "
function combines two parts – a simple value, and a callback
for when that value should change – into one value, that
happens to look as an atom. "]
[:p "The first argument to " [:code "wrap"] " should be the
value that will be returned by " [:code "@the-result"] "."]
[:p "The second argument should be a function, that will be
passed the new value whenever the result is changed (with
optional extra arguments to " [:code "wrap"] " prepended, as
with " [:code "partial"] ")."]
[:p "Usage can look something like this:"]
[demo-component {:comp parent
:src [:pre ns-src
(s/src-of [:input :name-edit
:person :parent])]}]
[:p "Here, the " [:code "parent"] " component controls the
global state, and delegates editing the name
to " [:code "name-edit"] ". " [:code "name-edit"] " in turn
delegates the actual input of first and last names
to " [:code "input"] "."]
[:p [:b "Note: "] "The result from " [:code "wrap"] " is just a
simple and light-weight value, that happens to look like an
atom – it doesn’t by itself trigger any re-renderings
like " [:code "reagent.core/atom"] " does. That means that it
is probably only useful to pass from one component to another,
and that the callback function in the end must cause a ”real”
atom to change."]
[:h2 "Faster rendering"]
[:p "Reagent used to wrap all ”native” React components in an
extra Reagent component, in order to keep track of how deep in
the component tree each component was (to make sure that
un-necessary re-renderings were avoided)."]
[:p "Now, this extra wrapper-component isn’t needed anymore,
which means quite a bit faster generation of native React
elements. This will be noticeable if you generate html strings,
or if you animate a large number of components."]
[:h2 "Simple React integration"]
[:p "Since Reagent doesn't need those wrappers anymore it is
also now easier to mix native React components with Reagent
ones. There’s a new convenience
function, " [:code "reagent.core/create-element"] ", that
simply calls " [:a {:href
cel-link} [:code "React.createElement"]] ". This,
unsurprisingly, creates React elements, either from the result
of " [:code "React.createClass"] " or html tag names."]
[:p [:code "reagent.core/as-element"] " turns Reagent’s hiccup
forms into React elements, that can be passed to ordinary React
components. The combination of " [:code "create-element"] "
and " [:code "as-element"] " allows mixing and matching of
Reagent and React components."]
[:p "For an example, here are four different ways to achieve
the same thing:"]
[demo-component {:comp integration
:src (s/src-of [:integration])}]
[:h2 "More equality"]
[:p "Reagent used to have a rather complicated way of
determining when a component should be re-rendered in response
to changing arguments. Now the rule is much simpler: a
component will be re-rendered if the old and new arguments are
not equal (i.e. they are compared with a
simple " [:code "="] ")."]
[:p [:strong "Note: "] "This is a breaking change! It means
that you can no longer pass infinite " [:code "seq"] "s to a
component."]
[:h2 "React 0.12"]
[:p "Reagent now comes with, and requires, React 0.12.1. To
mirror the changes in API in React, some Reagent functions have
gotten new names: "]
[:ul
[:li [:code "render-component"] " is now " [:code "render"]]
[:li [:code "render-component-to-string"] " is now " [:code "render-to-string"]]
[:li [:code "as-component"] " is now " [:code "as-element"]]]
[:p "The old names still work, though."]
[:p "There is also a new
function, " [:code "render-to-static-markup"] ", that works
just like render-to-string, except that it doesn’t add
React-specific attributes."]
[:h2 "Easier live-programming"]
[:p "It is now easier than before to integrate Reagent with
e.g. the rather excellent " [:a {:href
figwheel-link} "figwheel"] ", since " [:code "render"] " now
will cause the entire component tree to update (by-passing the
equality checks)."] ])]])
(tools/register-page url (fn [] [main]) title)
| 73860 | (ns reagentdemo.news.news050
(:require [reagent.core :as r :refer [atom]]
[reagent.interop :refer-macros [.' .!]]
[reagent.debug :refer-macros [dbg println]]
[reagentdemo.syntax :as s :include-macros true]
[sitetools :as tools :refer [link]]
[reagentdemo.common :as common :refer [demo-component]]
[todomvc :as todomvc]))
(def url "news/news050.html")
(def title "News in 0.5.0-alpha")
(def ns-src (s/syntaxed "(ns example
(:require [reagent.core :as r :refer [atom]]))"))
(defn input [prompt val]
[:div
prompt
[:input {:value @val
:on-change #(reset! val (.-target.value %))}]])
(defn name-edit [n]
(let [{:keys [first-name last-name]} @n]
[:div
[:p "I'm editing " first-name " " last-name "."]
[input "First name: " (r/wrap first-name
swap! n assoc :first-name)]
[input "Last name: " (r/wrap last-name
swap! n assoc :last-name)]]))
(defonce person (atom {:name
{:first-name "<NAME>" :last-name "<NAME>"}}))
(defn parent []
[:div
[:p "Current state: " (pr-str @person)]
[name-edit (r/wrap (:name @person)
swap! person assoc :name)]])
(defn integration []
[:div
[:div.foo "Hello " [:strong "world"]]
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/create-element "strong"
#js{}
"world"))
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/as-element [:strong "world"]))
[:div.foo "Hello " (r/create-element "strong"
#js{}
"world")]])
(def cel-link "http://facebook.github.io/react/docs/top-level-api.html#react.createelement")
(def figwheel-link "https://github.com/bhauman/lein-figwheel")
(defn main [{:keys [summary]}]
[:div.reagent-demo
[:h1 [link {:href url} title]]
[:div.demo-text
[:p "Lots of new features (and one breaking change) in Reagent
0.5.0-alpha."]
(if summary
[link {:href url
:class 'news-read-more} "Read more"]
[:div.demo-text
[:h2 "Splitting atoms"]
[:p "Reagent now has a simple way to make reusable components
that edit part of a parents state: "]
[:p " The new " [:code "wrap"] "
function combines two parts – a simple value, and a callback
for when that value should change – into one value, that
happens to look as an atom. "]
[:p "The first argument to " [:code "wrap"] " should be the
value that will be returned by " [:code "@the-result"] "."]
[:p "The second argument should be a function, that will be
passed the new value whenever the result is changed (with
optional extra arguments to " [:code "wrap"] " prepended, as
with " [:code "partial"] ")."]
[:p "Usage can look something like this:"]
[demo-component {:comp parent
:src [:pre ns-src
(s/src-of [:input :name-edit
:person :parent])]}]
[:p "Here, the " [:code "parent"] " component controls the
global state, and delegates editing the name
to " [:code "name-edit"] ". " [:code "name-edit"] " in turn
delegates the actual input of first and last names
to " [:code "input"] "."]
[:p [:b "Note: "] "The result from " [:code "wrap"] " is just a
simple and light-weight value, that happens to look like an
atom – it doesn’t by itself trigger any re-renderings
like " [:code "reagent.core/atom"] " does. That means that it
is probably only useful to pass from one component to another,
and that the callback function in the end must cause a ”real”
atom to change."]
[:h2 "Faster rendering"]
[:p "Reagent used to wrap all ”native” React components in an
extra Reagent component, in order to keep track of how deep in
the component tree each component was (to make sure that
un-necessary re-renderings were avoided)."]
[:p "Now, this extra wrapper-component isn’t needed anymore,
which means quite a bit faster generation of native React
elements. This will be noticeable if you generate html strings,
or if you animate a large number of components."]
[:h2 "Simple React integration"]
[:p "Since Reagent doesn't need those wrappers anymore it is
also now easier to mix native React components with Reagent
ones. There’s a new convenience
function, " [:code "reagent.core/create-element"] ", that
simply calls " [:a {:href
cel-link} [:code "React.createElement"]] ". This,
unsurprisingly, creates React elements, either from the result
of " [:code "React.createClass"] " or html tag names."]
[:p [:code "reagent.core/as-element"] " turns Reagent’s hiccup
forms into React elements, that can be passed to ordinary React
components. The combination of " [:code "create-element"] "
and " [:code "as-element"] " allows mixing and matching of
Reagent and React components."]
[:p "For an example, here are four different ways to achieve
the same thing:"]
[demo-component {:comp integration
:src (s/src-of [:integration])}]
[:h2 "More equality"]
[:p "Reagent used to have a rather complicated way of
determining when a component should be re-rendered in response
to changing arguments. Now the rule is much simpler: a
component will be re-rendered if the old and new arguments are
not equal (i.e. they are compared with a
simple " [:code "="] ")."]
[:p [:strong "Note: "] "This is a breaking change! It means
that you can no longer pass infinite " [:code "seq"] "s to a
component."]
[:h2 "React 0.12"]
[:p "Reagent now comes with, and requires, React 0.12.1. To
mirror the changes in API in React, some Reagent functions have
gotten new names: "]
[:ul
[:li [:code "render-component"] " is now " [:code "render"]]
[:li [:code "render-component-to-string"] " is now " [:code "render-to-string"]]
[:li [:code "as-component"] " is now " [:code "as-element"]]]
[:p "The old names still work, though."]
[:p "There is also a new
function, " [:code "render-to-static-markup"] ", that works
just like render-to-string, except that it doesn’t add
React-specific attributes."]
[:h2 "Easier live-programming"]
[:p "It is now easier than before to integrate Reagent with
e.g. the rather excellent " [:a {:href
figwheel-link} "figwheel"] ", since " [:code "render"] " now
will cause the entire component tree to update (by-passing the
equality checks)."] ])]])
(tools/register-page url (fn [] [main]) title)
| true | (ns reagentdemo.news.news050
(:require [reagent.core :as r :refer [atom]]
[reagent.interop :refer-macros [.' .!]]
[reagent.debug :refer-macros [dbg println]]
[reagentdemo.syntax :as s :include-macros true]
[sitetools :as tools :refer [link]]
[reagentdemo.common :as common :refer [demo-component]]
[todomvc :as todomvc]))
(def url "news/news050.html")
(def title "News in 0.5.0-alpha")
(def ns-src (s/syntaxed "(ns example
(:require [reagent.core :as r :refer [atom]]))"))
(defn input [prompt val]
[:div
prompt
[:input {:value @val
:on-change #(reset! val (.-target.value %))}]])
(defn name-edit [n]
(let [{:keys [first-name last-name]} @n]
[:div
[:p "I'm editing " first-name " " last-name "."]
[input "First name: " (r/wrap first-name
swap! n assoc :first-name)]
[input "Last name: " (r/wrap last-name
swap! n assoc :last-name)]]))
(defonce person (atom {:name
{:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}}))
(defn parent []
[:div
[:p "Current state: " (pr-str @person)]
[name-edit (r/wrap (:name @person)
swap! person assoc :name)]])
(defn integration []
[:div
[:div.foo "Hello " [:strong "world"]]
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/create-element "strong"
#js{}
"world"))
(r/create-element "div"
#js{:className "foo"}
"Hello "
(r/as-element [:strong "world"]))
[:div.foo "Hello " (r/create-element "strong"
#js{}
"world")]])
(def cel-link "http://facebook.github.io/react/docs/top-level-api.html#react.createelement")
(def figwheel-link "https://github.com/bhauman/lein-figwheel")
(defn main [{:keys [summary]}]
[:div.reagent-demo
[:h1 [link {:href url} title]]
[:div.demo-text
[:p "Lots of new features (and one breaking change) in Reagent
0.5.0-alpha."]
(if summary
[link {:href url
:class 'news-read-more} "Read more"]
[:div.demo-text
[:h2 "Splitting atoms"]
[:p "Reagent now has a simple way to make reusable components
that edit part of a parents state: "]
[:p " The new " [:code "wrap"] "
function combines two parts – a simple value, and a callback
for when that value should change – into one value, that
happens to look as an atom. "]
[:p "The first argument to " [:code "wrap"] " should be the
value that will be returned by " [:code "@the-result"] "."]
[:p "The second argument should be a function, that will be
passed the new value whenever the result is changed (with
optional extra arguments to " [:code "wrap"] " prepended, as
with " [:code "partial"] ")."]
[:p "Usage can look something like this:"]
[demo-component {:comp parent
:src [:pre ns-src
(s/src-of [:input :name-edit
:person :parent])]}]
[:p "Here, the " [:code "parent"] " component controls the
global state, and delegates editing the name
to " [:code "name-edit"] ". " [:code "name-edit"] " in turn
delegates the actual input of first and last names
to " [:code "input"] "."]
[:p [:b "Note: "] "The result from " [:code "wrap"] " is just a
simple and light-weight value, that happens to look like an
atom – it doesn’t by itself trigger any re-renderings
like " [:code "reagent.core/atom"] " does. That means that it
is probably only useful to pass from one component to another,
and that the callback function in the end must cause a ”real”
atom to change."]
[:h2 "Faster rendering"]
[:p "Reagent used to wrap all ”native” React components in an
extra Reagent component, in order to keep track of how deep in
the component tree each component was (to make sure that
un-necessary re-renderings were avoided)."]
[:p "Now, this extra wrapper-component isn’t needed anymore,
which means quite a bit faster generation of native React
elements. This will be noticeable if you generate html strings,
or if you animate a large number of components."]
[:h2 "Simple React integration"]
[:p "Since Reagent doesn't need those wrappers anymore it is
also now easier to mix native React components with Reagent
ones. There’s a new convenience
function, " [:code "reagent.core/create-element"] ", that
simply calls " [:a {:href
cel-link} [:code "React.createElement"]] ". This,
unsurprisingly, creates React elements, either from the result
of " [:code "React.createClass"] " or html tag names."]
[:p [:code "reagent.core/as-element"] " turns Reagent’s hiccup
forms into React elements, that can be passed to ordinary React
components. The combination of " [:code "create-element"] "
and " [:code "as-element"] " allows mixing and matching of
Reagent and React components."]
[:p "For an example, here are four different ways to achieve
the same thing:"]
[demo-component {:comp integration
:src (s/src-of [:integration])}]
[:h2 "More equality"]
[:p "Reagent used to have a rather complicated way of
determining when a component should be re-rendered in response
to changing arguments. Now the rule is much simpler: a
component will be re-rendered if the old and new arguments are
not equal (i.e. they are compared with a
simple " [:code "="] ")."]
[:p [:strong "Note: "] "This is a breaking change! It means
that you can no longer pass infinite " [:code "seq"] "s to a
component."]
[:h2 "React 0.12"]
[:p "Reagent now comes with, and requires, React 0.12.1. To
mirror the changes in API in React, some Reagent functions have
gotten new names: "]
[:ul
[:li [:code "render-component"] " is now " [:code "render"]]
[:li [:code "render-component-to-string"] " is now " [:code "render-to-string"]]
[:li [:code "as-component"] " is now " [:code "as-element"]]]
[:p "The old names still work, though."]
[:p "There is also a new
function, " [:code "render-to-static-markup"] ", that works
just like render-to-string, except that it doesn’t add
React-specific attributes."]
[:h2 "Easier live-programming"]
[:p "It is now easier than before to integrate Reagent with
e.g. the rather excellent " [:a {:href
figwheel-link} "figwheel"] ", since " [:code "render"] " now
will cause the entire component tree to update (by-passing the
equality checks)."] ])]])
(tools/register-page url (fn [] [main]) title)
|
[
{
"context": "--------------\n;; File simple_op.clj\n;; Written by Chris Frisz\n;; \n;; Created 2 Apr 2012\n;; Last modified 5 No",
"end": 120,
"score": 0.9998462796211243,
"start": 109,
"tag": "NAME",
"value": "Chris Frisz"
}
] | src/ctco/expr/simple_op.clj | cjfrisz/clojure-tco | 64 | ;;----------------------------------------------------------------------
;; File simple_op.clj
;; Written by Chris Frisz
;;
;; Created 2 Apr 2012
;; Last modified 5 Nov 2012
;;
;; Defines the SimpleOpSrs, SimpleOpTriv, and SimpleOpCps record types
;; for representing operations using simple primitives, i.e.
;; arithmetic and relational operators or simple type predicates.
;; SimpleOpSrs and SimpleOpTriv correspond to primitive operations
;; that are "serious" or "trivial" with respect to the Danvy-style CPS
;; algorithm, respectively. The SimpleOpCps record type corresponds to
;; primitive operations which have undergone the CPS transformation.
;;
;; SimpleOpCps implements the following protocols:
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; SimpleOpSrs implements the following protocols:
;;
;; PCpsSrs:
;; Applies the Danvy-style CPS transformation to the
;; primitive operation. Essentially, for each trivial
;; subexpression, it is CPSed and left in place. For each
;; serious subexpression, it is pulled out of the
;; expression, evaluated, and the original application
;; expression is placed inside a continuation with the
;; subexpression replaced with a variable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpTriv implements the following protocols:
;;
;; PCpsTriv:
;; Maps cps-triv over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpCps, SimpleOpSrs, and SimpleOpTriv use the same
;; implementation for the following protocols:
;;
;; PUnparse:
;; Unparses (recursively) the syntax for the expression as
;; `(~op ~@opnd*)
;;
;; PWalkable:
;; Maps the given function over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;----------------------------------------------------------------------
(ns ctco.expr.simple-op
(:require [ctco.protocol :as proto]
[ctco.expr.cont :as cont]
[ctco.util :as util])
(:import [ctco.expr.cont
Cont AppCont]))
(defrecord SimpleOpCps [op opnd*]
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpCps. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpCps. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpCps. %1 %2))))
(defrecord SimpleOpSrs [op opnd*]
proto/PCpsSrs
(cps-srs [this k]
(letfn [(cps [pre-opnd* post-opnd* k]
(if (nil? (seq pre-opnd*))
(let [OP (SimpleOpCps. (:op this) post-opnd*)]
(AppCont. k OP))
(let [fst (first pre-opnd*)
rst (rest pre-opnd*)]
(if (extends? proto/PCpsTriv (type fst))
(recur rst (conj post-opnd* (proto/cps-triv fst)) k)
(let [s (util/new-var "s")]
(proto/cps-srs
fst
(Cont. s (cps rst (conj post-opnd* s) k))))))))]
(cps (:opnd* this) [] k)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpSrs. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpSrs. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpSrs. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpSrs. %1 %2))))
(defrecord SimpleOpTriv [op opnd*]
proto/PCpsTriv
(cps-triv [this]
(proto/walk-expr this proto/cps-triv #(SimpleOpCps. %1 %2)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpTriv. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpTriv. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpTriv. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpTriv. %1 %2))))
(util/extend-multi (SimpleOpCps SimpleOpSrs SimpleOpTriv)
proto/PUnparse
(unparse [this] `(~(:op this) ~@(map proto/unparse (:opnd* this))))
proto/PWalkable
(walk-expr [this f ctor] (ctor (:op this) (mapv f (:opnd* this)))))
| 35218 | ;;----------------------------------------------------------------------
;; File simple_op.clj
;; Written by <NAME>
;;
;; Created 2 Apr 2012
;; Last modified 5 Nov 2012
;;
;; Defines the SimpleOpSrs, SimpleOpTriv, and SimpleOpCps record types
;; for representing operations using simple primitives, i.e.
;; arithmetic and relational operators or simple type predicates.
;; SimpleOpSrs and SimpleOpTriv correspond to primitive operations
;; that are "serious" or "trivial" with respect to the Danvy-style CPS
;; algorithm, respectively. The SimpleOpCps record type corresponds to
;; primitive operations which have undergone the CPS transformation.
;;
;; SimpleOpCps implements the following protocols:
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; SimpleOpSrs implements the following protocols:
;;
;; PCpsSrs:
;; Applies the Danvy-style CPS transformation to the
;; primitive operation. Essentially, for each trivial
;; subexpression, it is CPSed and left in place. For each
;; serious subexpression, it is pulled out of the
;; expression, evaluated, and the original application
;; expression is placed inside a continuation with the
;; subexpression replaced with a variable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpTriv implements the following protocols:
;;
;; PCpsTriv:
;; Maps cps-triv over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpCps, SimpleOpSrs, and SimpleOpTriv use the same
;; implementation for the following protocols:
;;
;; PUnparse:
;; Unparses (recursively) the syntax for the expression as
;; `(~op ~@opnd*)
;;
;; PWalkable:
;; Maps the given function over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;----------------------------------------------------------------------
(ns ctco.expr.simple-op
(:require [ctco.protocol :as proto]
[ctco.expr.cont :as cont]
[ctco.util :as util])
(:import [ctco.expr.cont
Cont AppCont]))
(defrecord SimpleOpCps [op opnd*]
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpCps. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpCps. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpCps. %1 %2))))
(defrecord SimpleOpSrs [op opnd*]
proto/PCpsSrs
(cps-srs [this k]
(letfn [(cps [pre-opnd* post-opnd* k]
(if (nil? (seq pre-opnd*))
(let [OP (SimpleOpCps. (:op this) post-opnd*)]
(AppCont. k OP))
(let [fst (first pre-opnd*)
rst (rest pre-opnd*)]
(if (extends? proto/PCpsTriv (type fst))
(recur rst (conj post-opnd* (proto/cps-triv fst)) k)
(let [s (util/new-var "s")]
(proto/cps-srs
fst
(Cont. s (cps rst (conj post-opnd* s) k))))))))]
(cps (:opnd* this) [] k)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpSrs. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpSrs. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpSrs. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpSrs. %1 %2))))
(defrecord SimpleOpTriv [op opnd*]
proto/PCpsTriv
(cps-triv [this]
(proto/walk-expr this proto/cps-triv #(SimpleOpCps. %1 %2)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpTriv. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpTriv. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpTriv. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpTriv. %1 %2))))
(util/extend-multi (SimpleOpCps SimpleOpSrs SimpleOpTriv)
proto/PUnparse
(unparse [this] `(~(:op this) ~@(map proto/unparse (:opnd* this))))
proto/PWalkable
(walk-expr [this f ctor] (ctor (:op this) (mapv f (:opnd* this)))))
| true | ;;----------------------------------------------------------------------
;; File simple_op.clj
;; Written by PI:NAME:<NAME>END_PI
;;
;; Created 2 Apr 2012
;; Last modified 5 Nov 2012
;;
;; Defines the SimpleOpSrs, SimpleOpTriv, and SimpleOpCps record types
;; for representing operations using simple primitives, i.e.
;; arithmetic and relational operators or simple type predicates.
;; SimpleOpSrs and SimpleOpTriv correspond to primitive operations
;; that are "serious" or "trivial" with respect to the Danvy-style CPS
;; algorithm, respectively. The SimpleOpCps record type corresponds to
;; primitive operations which have undergone the CPS transformation.
;;
;; SimpleOpCps implements the following protocols:
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; SimpleOpSrs implements the following protocols:
;;
;; PCpsSrs:
;; Applies the Danvy-style CPS transformation to the
;; primitive operation. Essentially, for each trivial
;; subexpression, it is CPSed and left in place. For each
;; serious subexpression, it is pulled out of the
;; expression, evaluated, and the original application
;; expression is placed inside a continuation with the
;; subexpression replaced with a variable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpTriv implements the following protocols:
;;
;; PCpsTriv:
;; Maps cps-triv over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PThunkify:
;; Maps thunkify over the operands of the expression. Uses
;; the walk-expr function provided by PWalkable.
;;
;; PUnRecurify:
;; Maps unrecurify over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;
;; SimpleOpCps, SimpleOpSrs, and SimpleOpTriv use the same
;; implementation for the following protocols:
;;
;; PUnparse:
;; Unparses (recursively) the syntax for the expression as
;; `(~op ~@opnd*)
;;
;; PWalkable:
;; Maps the given function over the operands of the
;; expression. Uses the walk-expr function provided by
;; PWalkable.
;;----------------------------------------------------------------------
(ns ctco.expr.simple-op
(:require [ctco.protocol :as proto]
[ctco.expr.cont :as cont]
[ctco.util :as util])
(:import [ctco.expr.cont
Cont AppCont]))
(defrecord SimpleOpCps [op opnd*]
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpCps. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpCps. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpCps. %1 %2))))
(defrecord SimpleOpSrs [op opnd*]
proto/PCpsSrs
(cps-srs [this k]
(letfn [(cps [pre-opnd* post-opnd* k]
(if (nil? (seq pre-opnd*))
(let [OP (SimpleOpCps. (:op this) post-opnd*)]
(AppCont. k OP))
(let [fst (first pre-opnd*)
rst (rest pre-opnd*)]
(if (extends? proto/PCpsTriv (type fst))
(recur rst (conj post-opnd* (proto/cps-triv fst)) k)
(let [s (util/new-var "s")]
(proto/cps-srs
fst
(Cont. s (cps rst (conj post-opnd* s) k))))))))]
(cps (:opnd* this) [] k)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpSrs. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpSrs. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpSrs. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpSrs. %1 %2))))
(defrecord SimpleOpTriv [op opnd*]
proto/PCpsTriv
(cps-triv [this]
(proto/walk-expr this proto/cps-triv #(SimpleOpCps. %1 %2)))
proto/PLoadTrampoline
(load-tramp [this tramp]
(proto/walk-expr this #(proto/load-tramp % tramp) #(SimpleOpTriv. %1 %2)))
proto/PRecurify
(recurify [this name arity tail?]
(proto/walk-expr this #(proto/recurify % nil nil false)
#(SimpleOpTriv. %1 %2)))
proto/PThunkify
(thunkify [this]
(proto/walk-expr this proto/thunkify #(SimpleOpTriv. %1 %2)))
proto/PUnRecurify
(unrecurify [this name]
(proto/walk-expr this #(proto/unrecurify % name) #(SimpleOpTriv. %1 %2))))
(util/extend-multi (SimpleOpCps SimpleOpSrs SimpleOpTriv)
proto/PUnparse
(unparse [this] `(~(:op this) ~@(map proto/unparse (:opnd* this))))
proto/PWalkable
(walk-expr [this f ctor] (ctor (:op this) (mapv f (:opnd* this)))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998099207878113,
"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.9998177886009216,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/test/editor/ui_test.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.ui-test
(:require [clojure.test :refer :all]
[dynamo.graph :as g]
[editor.handler :as handler]
[editor.ui :as ui]
[support.test-support :as test-support])
(:import [javafx.scene Scene]
[javafx.scene.control ComboBox ListView Menu MenuBar MenuItem SelectionMode TreeItem TreeView]
[javafx.scene.layout Pane VBox]))
(defn- make-fake-stage []
(let [root (VBox.)
stage (ui/make-stage)
scene (Scene. root)]
(.setScene stage scene)
stage))
(defn fixture [f]
(with-redefs [handler/state-atom (atom {})
ui/*main-stage* (atom (ui/run-now (make-fake-stage)))]
(f)))
(use-fixtures :each fixture)
(deftest extend-menu-test
(handler/register-menu! ::menubar
[{:label "File"
:children [{:label "New"
:id ::new}]}])
(handler/register-menu! ::save-menu ::new
[{:label "Save"}])
(handler/register-menu! ::quit-menu ::new
[{:label "Quit"}])
(is (= (handler/realize-menu ::menubar) [{:label "File"
:children [{:label "New"
:id ::new}
{:label "Save"}
{:label "Quit"}]}])))
(defrecord TestSelectionProvider [selection]
handler/SelectionProvider
(selection [this] selection)
(succeeding-selection [this] [])
(alt-selection [this] []))
(defn- make-menu-items [scene menu-id command-context]
(g/with-auto-evaluation-context evaluation-context
(#'ui/make-menu-items scene (handler/realize-menu menu-id) [command-context] {} evaluation-context)))
(deftest menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children [{:label "Open"
:id ::open
:command :open}
{:label "Save"
:command :save}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (ui/run-now (Scene. root))
command-context {:name :global :env {:selection []}}]
(let [menu-items (make-menu-items scene ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (instance? Menu (first menu-items)))
(is (= 2 (count (.getItems (first menu-items)))))
(is (instance? MenuItem (first (.getItems (first menu-items)))))))))
(deftest options-menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Add"
:command :add}])
(handler/defhandler :add :global
(run [user-data] user-data)
(active? [user-data] (or (not user-data) (= user-data 1)))
(options [user-data] (when-not user-data [{:label "first"
:command :add
:user-data 1}
{:label "second"
:command :add
:user-data 2}])))
(let [command-context {:name :global :env {}}]
(let [menu-items (make-menu-items nil ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (= 1 (count (.getItems (first menu-items)))))))))
(deftest toolbar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Open"
:command :open
:id ::open}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123)
(state [] false))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124)
(state [] false))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])]
(.setId root "toolbar")
(ui/context! root :global {} selection-provider)
(ui/register-toolbar scene root "#toolbar" ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getChildren root))
c2 (do (ui/refresh scene) (.getChildren root))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(is (= 2 (count (.getChildren root))))))))
(deftest menubar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children
[{:label "Open"
:id ::open
:command :open}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])
menubar (MenuBar.)]
(ui/context! root :global {} selection-provider)
(.add (.getChildren root) menubar)
(.setId menubar "menubar")
(ui/register-menubar scene menubar ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 2 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))))))
(deftest list-view-test
(let [selected-items (atom nil)]
(ui/run-now
(let [root (ui/main-root)
list (doto (ListView.)
(ui/items! [:a :b :c :d]))]
(doto (.getSelectionModel list)
(.setSelectionMode SelectionMode/MULTIPLE))
(ui/observe-list (ui/selection list)
(fn [_ values]
(reset! selected-items values)))
(ui/add-child! root list)
(doto (.getSelectionModel list)
(.selectRange 1 3))))
(is (= [:b :c] @selected-items))))
(deftest observe-selection-test
(testing "TreeView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
tree-item-a (TreeItem. :a)
tree-item-b (TreeItem. :b)
tree-view (doto (TreeView.)
(.setRoot (doto (TreeItem. :root)
(.setExpanded true)
(-> .getChildren
(.addAll [tree-item-a
tree-item-b])))))]
(swap! results assoc :observed-view tree-view)
(ui/add-child! root tree-view)
(ui/observe-selection tree-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(doto (.getSelectionModel tree-view)
(.setSelectionMode SelectionMode/MULTIPLE)
(.select 1)
(.select 2))))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? TreeView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:a :b] selected-items)))))
(testing "ListView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
list-view (doto (ListView.)
(ui/selection-mode! :multiple)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view list-view)
(ui/add-child! root list-view)
(ui/observe-selection list-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! list-view :b)
(ui/select! list-view :c)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ListView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b :c] selected-items)))))
(testing "ComboBox"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
combo-box (doto (ComboBox.)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view combo-box)
(ui/add-child! root combo-box)
(ui/observe-selection combo-box (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! combo-box :b)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ComboBox observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b] selected-items))))))
| 28716 | ;; 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.ui-test
(:require [clojure.test :refer :all]
[dynamo.graph :as g]
[editor.handler :as handler]
[editor.ui :as ui]
[support.test-support :as test-support])
(:import [javafx.scene Scene]
[javafx.scene.control ComboBox ListView Menu MenuBar MenuItem SelectionMode TreeItem TreeView]
[javafx.scene.layout Pane VBox]))
(defn- make-fake-stage []
(let [root (VBox.)
stage (ui/make-stage)
scene (Scene. root)]
(.setScene stage scene)
stage))
(defn fixture [f]
(with-redefs [handler/state-atom (atom {})
ui/*main-stage* (atom (ui/run-now (make-fake-stage)))]
(f)))
(use-fixtures :each fixture)
(deftest extend-menu-test
(handler/register-menu! ::menubar
[{:label "File"
:children [{:label "New"
:id ::new}]}])
(handler/register-menu! ::save-menu ::new
[{:label "Save"}])
(handler/register-menu! ::quit-menu ::new
[{:label "Quit"}])
(is (= (handler/realize-menu ::menubar) [{:label "File"
:children [{:label "New"
:id ::new}
{:label "Save"}
{:label "Quit"}]}])))
(defrecord TestSelectionProvider [selection]
handler/SelectionProvider
(selection [this] selection)
(succeeding-selection [this] [])
(alt-selection [this] []))
(defn- make-menu-items [scene menu-id command-context]
(g/with-auto-evaluation-context evaluation-context
(#'ui/make-menu-items scene (handler/realize-menu menu-id) [command-context] {} evaluation-context)))
(deftest menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children [{:label "Open"
:id ::open
:command :open}
{:label "Save"
:command :save}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (ui/run-now (Scene. root))
command-context {:name :global :env {:selection []}}]
(let [menu-items (make-menu-items scene ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (instance? Menu (first menu-items)))
(is (= 2 (count (.getItems (first menu-items)))))
(is (instance? MenuItem (first (.getItems (first menu-items)))))))))
(deftest options-menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Add"
:command :add}])
(handler/defhandler :add :global
(run [user-data] user-data)
(active? [user-data] (or (not user-data) (= user-data 1)))
(options [user-data] (when-not user-data [{:label "first"
:command :add
:user-data 1}
{:label "second"
:command :add
:user-data 2}])))
(let [command-context {:name :global :env {}}]
(let [menu-items (make-menu-items nil ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (= 1 (count (.getItems (first menu-items)))))))))
(deftest toolbar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Open"
:command :open
:id ::open}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123)
(state [] false))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124)
(state [] false))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])]
(.setId root "toolbar")
(ui/context! root :global {} selection-provider)
(ui/register-toolbar scene root "#toolbar" ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getChildren root))
c2 (do (ui/refresh scene) (.getChildren root))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(is (= 2 (count (.getChildren root))))))))
(deftest menubar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children
[{:label "Open"
:id ::open
:command :open}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])
menubar (MenuBar.)]
(ui/context! root :global {} selection-provider)
(.add (.getChildren root) menubar)
(.setId menubar "menubar")
(ui/register-menubar scene menubar ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 2 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))))))
(deftest list-view-test
(let [selected-items (atom nil)]
(ui/run-now
(let [root (ui/main-root)
list (doto (ListView.)
(ui/items! [:a :b :c :d]))]
(doto (.getSelectionModel list)
(.setSelectionMode SelectionMode/MULTIPLE))
(ui/observe-list (ui/selection list)
(fn [_ values]
(reset! selected-items values)))
(ui/add-child! root list)
(doto (.getSelectionModel list)
(.selectRange 1 3))))
(is (= [:b :c] @selected-items))))
(deftest observe-selection-test
(testing "TreeView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
tree-item-a (TreeItem. :a)
tree-item-b (TreeItem. :b)
tree-view (doto (TreeView.)
(.setRoot (doto (TreeItem. :root)
(.setExpanded true)
(-> .getChildren
(.addAll [tree-item-a
tree-item-b])))))]
(swap! results assoc :observed-view tree-view)
(ui/add-child! root tree-view)
(ui/observe-selection tree-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(doto (.getSelectionModel tree-view)
(.setSelectionMode SelectionMode/MULTIPLE)
(.select 1)
(.select 2))))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? TreeView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:a :b] selected-items)))))
(testing "ListView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
list-view (doto (ListView.)
(ui/selection-mode! :multiple)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view list-view)
(ui/add-child! root list-view)
(ui/observe-selection list-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! list-view :b)
(ui/select! list-view :c)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ListView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b :c] selected-items)))))
(testing "ComboBox"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
combo-box (doto (ComboBox.)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view combo-box)
(ui/add-child! root combo-box)
(ui/observe-selection combo-box (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! combo-box :b)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ComboBox observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b] selected-items))))))
| 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.ui-test
(:require [clojure.test :refer :all]
[dynamo.graph :as g]
[editor.handler :as handler]
[editor.ui :as ui]
[support.test-support :as test-support])
(:import [javafx.scene Scene]
[javafx.scene.control ComboBox ListView Menu MenuBar MenuItem SelectionMode TreeItem TreeView]
[javafx.scene.layout Pane VBox]))
(defn- make-fake-stage []
(let [root (VBox.)
stage (ui/make-stage)
scene (Scene. root)]
(.setScene stage scene)
stage))
(defn fixture [f]
(with-redefs [handler/state-atom (atom {})
ui/*main-stage* (atom (ui/run-now (make-fake-stage)))]
(f)))
(use-fixtures :each fixture)
(deftest extend-menu-test
(handler/register-menu! ::menubar
[{:label "File"
:children [{:label "New"
:id ::new}]}])
(handler/register-menu! ::save-menu ::new
[{:label "Save"}])
(handler/register-menu! ::quit-menu ::new
[{:label "Quit"}])
(is (= (handler/realize-menu ::menubar) [{:label "File"
:children [{:label "New"
:id ::new}
{:label "Save"}
{:label "Quit"}]}])))
(defrecord TestSelectionProvider [selection]
handler/SelectionProvider
(selection [this] selection)
(succeeding-selection [this] [])
(alt-selection [this] []))
(defn- make-menu-items [scene menu-id command-context]
(g/with-auto-evaluation-context evaluation-context
(#'ui/make-menu-items scene (handler/realize-menu menu-id) [command-context] {} evaluation-context)))
(deftest menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children [{:label "Open"
:id ::open
:command :open}
{:label "Save"
:command :save}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (ui/run-now (Scene. root))
command-context {:name :global :env {:selection []}}]
(let [menu-items (make-menu-items scene ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (instance? Menu (first menu-items)))
(is (= 2 (count (.getItems (first menu-items)))))
(is (instance? MenuItem (first (.getItems (first menu-items)))))))))
(deftest options-menu-test
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Add"
:command :add}])
(handler/defhandler :add :global
(run [user-data] user-data)
(active? [user-data] (or (not user-data) (= user-data 1)))
(options [user-data] (when-not user-data [{:label "first"
:command :add
:user-data 1}
{:label "second"
:command :add
:user-data 2}])))
(let [command-context {:name :global :env {}}]
(let [menu-items (make-menu-items nil ::my-menu command-context)]
(is (= 1 (count menu-items)))
(is (= 1 (count (.getItems (first menu-items)))))))))
(deftest toolbar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "Open"
:command :open
:id ::open}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123)
(state [] false))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124)
(state [] false))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])]
(.setId root "toolbar")
(ui/context! root :global {} selection-provider)
(ui/register-toolbar scene root "#toolbar" ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getChildren root))
c2 (do (ui/refresh scene) (.getChildren root))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(is (= 2 (count (.getChildren root))))))))
(deftest menubar-test
(ui/run-now
(test-support/with-clean-system
(handler/register-menu! ::my-menu
[{:label "File"
:children
[{:label "Open"
:id ::open
:command :open}]}])
(handler/defhandler :open :global
(enabled? [selection] true)
(run [selection] 123))
(handler/defhandler :save :global
(enabled? [selection] true)
(run [selection] 124))
(let [root (Pane.)
scene (Scene. root)
selection-provider (TestSelectionProvider. [])
menubar (MenuBar.)]
(ui/context! root :global {} selection-provider)
(.add (.getChildren root) menubar)
(.setId menubar "menubar")
(ui/register-menubar scene menubar ::my-menu)
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 1 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))
(handler/register-menu! ::extra ::open
[{:label "Save"
:command :save}])
(ui/refresh scene)
(let [c1 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))
c2 (do (ui/refresh scene) (.getItems (first (.getMenus menubar))))]
(is (= 2 (count c1) (count c2)))
(is (= (.get c1 0) (.get c2 0))))))))
(deftest list-view-test
(let [selected-items (atom nil)]
(ui/run-now
(let [root (ui/main-root)
list (doto (ListView.)
(ui/items! [:a :b :c :d]))]
(doto (.getSelectionModel list)
(.setSelectionMode SelectionMode/MULTIPLE))
(ui/observe-list (ui/selection list)
(fn [_ values]
(reset! selected-items values)))
(ui/add-child! root list)
(doto (.getSelectionModel list)
(.selectRange 1 3))))
(is (= [:b :c] @selected-items))))
(deftest observe-selection-test
(testing "TreeView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
tree-item-a (TreeItem. :a)
tree-item-b (TreeItem. :b)
tree-view (doto (TreeView.)
(.setRoot (doto (TreeItem. :root)
(.setExpanded true)
(-> .getChildren
(.addAll [tree-item-a
tree-item-b])))))]
(swap! results assoc :observed-view tree-view)
(ui/add-child! root tree-view)
(ui/observe-selection tree-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(doto (.getSelectionModel tree-view)
(.setSelectionMode SelectionMode/MULTIPLE)
(.select 1)
(.select 2))))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? TreeView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:a :b] selected-items)))))
(testing "ListView"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
list-view (doto (ListView.)
(ui/selection-mode! :multiple)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view list-view)
(ui/add-child! root list-view)
(ui/observe-selection list-view (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! list-view :b)
(ui/select! list-view :c)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ListView observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b :c] selected-items)))))
(testing "ComboBox"
(let [results (atom {:observed-view nil :selection-owner nil :selected-items nil})]
(ui/run-now
(let [root (ui/main-root)
combo-box (doto (ComboBox.)
(ui/items! [:a :b :c]))]
(swap! results assoc :observed-view combo-box)
(ui/add-child! root combo-box)
(ui/observe-selection combo-box (fn [selection-owner selected-items]
(swap! results assoc
:selection-owner selection-owner
:selected-items selected-items)))
(ui/select! combo-box :b)))
(let [{:keys [observed-view selection-owner selected-items]} @results]
(is (instance? ComboBox observed-view))
(is (identical? observed-view selection-owner))
(is (= [:b] selected-items))))))
|
[
{
"context": "le value\n(sph/set-value! env \"accounts\" \"user1\" \"John\")\n;;=> \"John\"\n\n;; get the value back\n(sph/get-val",
"end": 725,
"score": 0.9976651668548584,
"start": 721,
"tag": "NAME",
"value": "John"
},
{
"context": "/set-value! env \"accounts\" \"user1\" \"John\")\n;;=> \"John\"\n\n;; get the value back\n(sph/get-value env \"acc",
"end": 738,
"score": 0.9987229704856873,
"start": 734,
"tag": "NAME",
"value": "John"
},
{
"context": "ck\n(sph/get-value env \"accounts\" \"user1\")\n;;=> \"John\"\n\n;; delete a key\n(sph/delete-key! env \"accounts\"",
"end": 814,
"score": 0.9991077184677124,
"start": 810,
"tag": "NAME",
"value": "John"
},
{
"context": "v \"accounts\" \"user1\"\n {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0})\n;;=> {:",
"end": 1059,
"score": 0.9997907280921936,
"start": 1055,
"tag": "NAME",
"value": "John"
},
{
"context": "r1\"\n {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0})\n;;=> {:firstname \"John\"",
"end": 1075,
"score": 0.9985442161560059,
"start": 1072,
"tag": "NAME",
"value": "Doe"
},
{
"context": " \"Doe\" :age 34 :balance 100.0})\n;;=> {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0}\n\n;; get ",
"end": 1124,
"score": 0.9997734427452087,
"start": 1120,
"tag": "NAME",
"value": "John"
},
{
"context": "alance 100.0})\n;;=> {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0}\n\n;; get it back\n(sph/get",
"end": 1140,
"score": 0.9990940093994141,
"start": 1137,
"tag": "NAME",
"value": "Doe"
},
{
"context": "value env \"accounts\" \"user1\")\n;;=> {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0}\n\n(sph/se",
"end": 1245,
"score": 0.9998023509979248,
"start": 1241,
"tag": "NAME",
"value": "John"
},
{
"context": "unts\" \"user1\")\n;;=> {:firstname \"John\" :lastname \"Doe\" :age 34 :balance 100.0}\n\n(sph/set-value! env \"ac",
"end": 1261,
"score": 0.9994399547576904,
"start": 1258,
"tag": "NAME",
"value": "Doe"
},
{
"context": "v \"accounts\" \"user2\"\n {:firstname \"Jane\" :lastname \"Smith\" :age 28 :balance 200.0})\n;;=> ",
"end": 1360,
"score": 0.9997040033340454,
"start": 1356,
"tag": "NAME",
"value": "Jane"
},
{
"context": "r2\"\n {:firstname \"Jane\" :lastname \"Smith\" :age 28 :balance 200.0})\n;;=> :{:firstname \"Jane",
"end": 1378,
"score": 0.9996302723884583,
"start": 1373,
"tag": "NAME",
"value": "Smith"
},
{
"context": "mith\" :age 28 :balance 200.0})\n;;=> :{:firstname \"Jane\" :lastname \"Smith\" :age 28 :balance 200.0}\n\n(sph/",
"end": 1428,
"score": 0.9997073411941528,
"start": 1424,
"tag": "NAME",
"value": "Jane"
},
{
"context": "lance 200.0})\n;;=> :{:firstname \"Jane\" :lastname \"Smith\" :age 28 :balance 200.0}\n\n(sph/set-value! env \"ac",
"end": 1446,
"score": 0.9996770620346069,
"start": 1441,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ance 200.0}\n\n(sph/set-value! env \"accounts\" \"admin1\"\n {:firstname \"Robert\" :lastname \"",
"end": 1511,
"score": 0.7527902722358704,
"start": 1510,
"tag": "USERNAME",
"value": "1"
},
{
"context": " \"accounts\" \"admin1\"\n {:firstname \"Robert\" :lastname \"Green\" :age 32 :grants [:accounts/adm",
"end": 1548,
"score": 0.9997777938842773,
"start": 1542,
"tag": "NAME",
"value": "Robert"
},
{
"context": "\"\n {:firstname \"Robert\" :lastname \"Green\" :age 32 :grants [:accounts/admin]})\n;;=> {:first",
"end": 1566,
"score": 0.9144084453582764,
"start": 1561,
"tag": "NAME",
"value": "Green"
},
{
"context": " 32 :grants [:accounts/admin]})\n;;=> {:firstname \"Robert\" :lastname \"Green\" :age 32 :grants [:accounts/adm",
"end": 1628,
"score": 0.9997847080230713,
"start": 1622,
"tag": "NAME",
"value": "Robert"
},
{
"context": " (sph/range-query cur \"accounts\")))\n;;=> {\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32",
"end": 2338,
"score": 0.6639833450317383,
"start": 2337,
"tag": "USERNAME",
"value": "1"
},
{
"context": "ery cur \"accounts\")))\n;;=> {\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/",
"end": 2359,
"score": 0.9997880458831787,
"start": 2353,
"tag": "NAME",
"value": "Robert"
},
{
"context": "ts [:accounts/admin]},\n;; \"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0},\n;; ",
"end": 2449,
"score": 0.9998045563697815,
"start": 2445,
"tag": "NAME",
"value": "John"
},
{
"context": "n]},\n;; \"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0},\n;; \"user2\" {:first",
"end": 2466,
"score": 0.9983092546463013,
"start": 2463,
"tag": "NAME",
"value": "Doe"
},
{
"context": "e 34, :balance 100.0},\n;; \"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}}\n\n\n",
"end": 2526,
"score": 0.9996809959411621,
"start": 2522,
"tag": "NAME",
"value": "Jane"
},
{
"context": ".0},\n;; \"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}}\n\n\n\n(with-open [cur (s",
"end": 2545,
"score": 0.9994032382965088,
"start": 2540,
"tag": "NAME",
"value": "Smith"
},
{
"context": "counts\" :order :desc)))\n\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]\n;;",
"end": 2709,
"score": 0.9997164011001587,
"start": 2705,
"tag": "NAME",
"value": "Jane"
},
{
"context": "sc)))\n\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]\n;; [\"user1\" {:firstna",
"end": 2728,
"score": 0.9994775056838989,
"start": 2723,
"tag": "NAME",
"value": "Smith"
},
{
"context": "age 28, :balance 200.0}]\n;; [\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; [",
"end": 2786,
"score": 0.9998253583908081,
"start": 2782,
"tag": "NAME",
"value": "John"
},
{
"context": "00.0}]\n;; [\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; [\"admin1\" {:firstn",
"end": 2803,
"score": 0.9993976354598999,
"start": 2800,
"tag": "NAME",
"value": "Doe"
},
{
"context": "ge 34, :balance 100.0}]\n;; [\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/",
"end": 2864,
"score": 0.999740719795227,
"start": 2858,
"tag": "NAME",
"value": "Robert"
},
{
"context": "user1\" :order :asc)))\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; ",
"end": 3094,
"score": 0.999771773815155,
"start": 3090,
"tag": "NAME",
"value": "John"
},
{
"context": ")))\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; [\"user2\" {:firs",
"end": 3111,
"score": 0.9992934465408325,
"start": 3108,
"tag": "NAME",
"value": "Doe"
},
{
"context": " 34, :balance 100.0}]\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]]\n\n",
"end": 3172,
"score": 0.9996967315673828,
"start": 3168,
"tag": "NAME",
"value": "Jane"
},
{
"context": "0}]\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]]\n\n\n(with-open [cur (s",
"end": 3191,
"score": 0.9996023774147034,
"start": 3186,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ser1\" :order :desc)))\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; ",
"end": 3369,
"score": 0.9997921586036682,
"start": 3365,
"tag": "NAME",
"value": "John"
},
{
"context": ")))\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; [\"admin1\" {:fir",
"end": 3386,
"score": 0.9997612833976746,
"start": 3383,
"tag": "NAME",
"value": "Doe"
},
{
"context": "lastname \"Doe\", :age 34, :balance 100.0}]\n;; [\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32",
"end": 3429,
"score": 0.9672356843948364,
"start": 3423,
"tag": "USERNAME",
"value": "admin1"
},
{
"context": "34, :balance 100.0}]\n;; [\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/",
"end": 3450,
"score": 0.9997910261154175,
"start": 3444,
"tag": "NAME",
"value": "Robert"
},
{
"context": "\n;; [\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/admin]}]]\n\n\n(with-o",
"end": 3469,
"score": 0.9973236918449402,
"start": 3464,
"tag": "NAME",
"value": "Green"
},
{
"context": "esc :search-type :index-scan-exclusive)))\n;;=> [[\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32",
"end": 3675,
"score": 0.9586660265922546,
"start": 3669,
"tag": "USERNAME",
"value": "admin1"
},
{
"context": "ex-scan-exclusive)))\n;;=> [[\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/",
"end": 3696,
"score": 0.9997779130935669,
"start": 3690,
"tag": "NAME",
"value": "Robert"
},
{
"context": "\n;;=> [[\"admin1\" {:firstname \"Robert\", :lastname \"Green\", :age 32, :grants [:accounts/admin]}]]\n\n\n;;\n;; p",
"end": 3715,
"score": 0.9982204437255859,
"start": 3710,
"tag": "NAME",
"value": "Green"
},
{
"context": "arch-type :prefix)))\n\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; ",
"end": 3929,
"score": 0.9998390674591064,
"start": 3925,
"tag": "NAME",
"value": "John"
},
{
"context": "))\n\n;;=> [[\"user1\" {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}]\n;; [\"user2\" {:firs",
"end": 3946,
"score": 0.9996057748794556,
"start": 3943,
"tag": "NAME",
"value": "Doe"
},
{
"context": " 34, :balance 100.0}]\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]]\n\n",
"end": 4007,
"score": 0.999683141708374,
"start": 4003,
"tag": "NAME",
"value": "Jane"
},
{
"context": "0}]\n;; [\"user2\" {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}]]\n\n\n(with-open [cur (s",
"end": 4026,
"score": 0.9996616840362549,
"start": 4021,
"tag": "NAME",
"value": "Smith"
},
{
"context": "t-value env \"accounts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}\n\n(sph",
"end": 4817,
"score": 0.9998202323913574,
"start": 4813,
"tag": "NAME",
"value": "John"
},
{
"context": "nts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 100.0}\n\n(sph/with-transaction",
"end": 4834,
"score": 0.999702513217926,
"start": 4831,
"tag": "NAME",
"value": "Doe"
},
{
"context": "date user1 :balance + 150.0))))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 250.0}\n\n(sph",
"end": 5070,
"score": 0.9998335838317871,
"start": 5066,
"tag": "NAME",
"value": "John"
},
{
"context": "e + 150.0))))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 250.0}\n\n(sph/get-value env \"a",
"end": 5087,
"score": 0.9996533393859863,
"start": 5084,
"tag": "NAME",
"value": "Doe"
},
{
"context": "t-value env \"accounts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 250.0}\n\n\n(sp",
"end": 5177,
"score": 0.9998123645782471,
"start": 5173,
"tag": "NAME",
"value": "John"
},
{
"context": "nts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 250.0}\n\n\n(sph/get-value env \"",
"end": 5194,
"score": 0.9996180534362793,
"start": 5191,
"tag": "NAME",
"value": "Doe"
},
{
"context": "t-value env \"accounts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}\n\n(l",
"end": 5285,
"score": 0.9996165037155151,
"start": 5281,
"tag": "NAME",
"value": "Jane"
},
{
"context": "nts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 200.0}\n\n(let [from \"user1\"\n",
"end": 5304,
"score": 0.9995768070220947,
"start": 5299,
"tag": "NAME",
"value": "Smith"
},
{
"context": "e user2 :balance + amount )))))\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 400.0}\n\n(s",
"end": 6093,
"score": 0.9995903968811035,
"start": 6089,
"tag": "NAME",
"value": "Jane"
},
{
"context": " amount )))))\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 400.0}\n\n(sph/get-value env \"a",
"end": 6112,
"score": 0.9996395111083984,
"start": 6107,
"tag": "NAME",
"value": "Smith"
},
{
"context": "t-value env \"accounts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 400.0}\n\n(s",
"end": 6202,
"score": 0.9996157884597778,
"start": 6198,
"tag": "NAME",
"value": "Jane"
},
{
"context": "nts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 400.0}\n\n(sph/get-value env \"a",
"end": 6221,
"score": 0.9996302127838135,
"start": 6216,
"tag": "NAME",
"value": "Smith"
},
{
"context": "t-value env \"accounts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 50.0}\n\n\n;; m",
"end": 6311,
"score": 0.999794065952301,
"start": 6307,
"tag": "NAME",
"value": "John"
},
{
"context": "nts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 50.0}\n\n\n;; multi table transa",
"end": 6328,
"score": 0.999683678150177,
"start": 6325,
"tag": "NAME",
"value": "Doe"
},
{
"context": "t-value env \"accounts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 150.0}\n\n(s",
"end": 7662,
"score": 0.9993472099304199,
"start": 7658,
"tag": "NAME",
"value": "Jane"
},
{
"context": "nts\" \"user2\")\n;;=> {:firstname \"Jane\", :lastname \"Smith\", :age 28, :balance 150.0}\n\n(sph/get-value env \"a",
"end": 7681,
"score": 0.9995279312133789,
"start": 7676,
"tag": "NAME",
"value": "Smith"
},
{
"context": "t-value env \"accounts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 300.0}\n\n\n(sp",
"end": 7771,
"score": 0.9994893670082092,
"start": 7767,
"tag": "NAME",
"value": "John"
},
{
"context": "nts\" \"user1\")\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 300.0}\n\n\n(sph/transact! env\n ",
"end": 7788,
"score": 0.9996806383132935,
"start": 7785,
"tag": "NAME",
"value": "Doe"
},
{
"context": "ate u :votes (fnil inc 0)))))))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 300.0 :votes",
"end": 8041,
"score": 0.9995200634002686,
"start": 8037,
"tag": "NAME",
"value": "John"
},
{
"context": " inc 0)))))))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 34, :balance 300.0 :votes 1}\n\n\n(sph/update",
"end": 8058,
"score": 0.9992531538009644,
"start": 8055,
"tag": "NAME",
"value": "Doe"
},
{
"context": "\" (fn [u] (update u :age inc)))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 35, :balance 300.0 :votes",
"end": 8191,
"score": 0.9997771382331848,
"start": 8187,
"tag": "NAME",
"value": "John"
},
{
"context": "u :age inc)))\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 35, :balance 300.0 :votes 1}\n\n(sph/update-",
"end": 8208,
"score": 0.9997886419296265,
"start": 8205,
"tag": "NAME",
"value": "Doe"
},
{
"context": "ounts\" \"user1\" update :age inc)\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 35, :balance 300.0 :votes",
"end": 8327,
"score": 0.9997199177742004,
"start": 8323,
"tag": "NAME",
"value": "John"
},
{
"context": "ate :age inc)\n;;=> {:firstname \"John\", :lastname \"Doe\", :age 35, :balance 300.0 :votes 1}\n\n;; user10 do",
"end": 8344,
"score": 0.9997966885566711,
"start": 8341,
"tag": "NAME",
"value": "Doe"
}
] | dev/user.clj | BrunoBonacci/clj-sophia | 16 | (ns user
(:require [com.brunobonacci.sophia :as sph]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| G E T / S E T / D E L E T E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def env
(sph/sophia
{;; where to store the files on disk
:sophia.path "/tmp/sophia-test"
;; which logical databases to create
:dbs ["accounts", {:name "transactions"}]}))
;; set a simple value
(sph/set-value! env "accounts" "user1" "John")
;;=> "John"
;; get the value back
(sph/get-value env "accounts" "user1")
;;=> "John"
;; delete a key
(sph/delete-key! env "accounts" "user1")
;;=> nil
;; now the key isn't present
(sph/get-value env "accounts" "user1")
;;=> nil
;; set a complex value
(sph/set-value! env "accounts" "user1"
{:firstname "John" :lastname "Doe" :age 34 :balance 100.0})
;;=> {:firstname "John" :lastname "Doe" :age 34 :balance 100.0}
;; get it back
(sph/get-value env "accounts" "user1")
;;=> {:firstname "John" :lastname "Doe" :age 34 :balance 100.0}
(sph/set-value! env "accounts" "user2"
{:firstname "Jane" :lastname "Smith" :age 28 :balance 200.0})
;;=> :{:firstname "Jane" :lastname "Smith" :age 28 :balance 200.0}
(sph/set-value! env "accounts" "admin1"
{:firstname "Robert" :lastname "Green" :age 32 :grants [:accounts/admin]})
;;=> {:firstname "Robert" :lastname "Green" :age 32 :grants [:accounts/admin]}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| R A N G E - Q U E R Y |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; display all the values in ascending order (by key)
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts")))
(with-open [cur (sph/cursor env)]
(into {}
(sph/range-query cur "accounts")))
;;=> {"admin1" {:firstname "Robert", :lastname "Green", :age 32, :grants [:accounts/admin]},
;; "user1" {:firstname "John", :lastname "Doe", :age 34, :balance 100.0},
;; "user2" {:firstname "Jane", :lastname "Smith", :age 28, :balance 200.0}}
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts" :order :desc)))
;; ["user2" {:firstname "Jane", :lastname "Smith", :age 28, :balance 200.0}]
;; ["user1" {:firstname "John", :lastname "Doe", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "Robert", :lastname "Green", :age 32, :grants [:accounts/admin]}]
;;
;; Seek and scan
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :asc)))
;;=> [["user1" {:firstname "John", :lastname "Doe", :age 34, :balance 100.0}]
;; ["user2" {:firstname "Jane", :lastname "Smith", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc)))
;;=> [["user1" {:firstname "John", :lastname "Doe", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "Robert", :lastname "Green", :age 32, :grants [:accounts/admin]}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc :search-type :index-scan-exclusive)))
;;=> [["admin1" {:firstname "Robert", :lastname "Green", :age 32, :grants [:accounts/admin]}]]
;;
;; prefix
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix)))
;;=> [["user1" {:firstname "John", :lastname "Doe", :age 34, :balance 100.0}]
;; ["user2" {:firstname "Jane", :lastname "Smith", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "foo" :search-type :prefix)))
;;=> []
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix
:order :desc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| T R A N S A C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(sph/get-value env "accounts" "user1")
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 100.0}
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" "user1")]
(sph/set-value! tx "accounts" "user1" (update user1 :balance + 150.0))))
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "Jane", :lastname "Smith", :age 28, :balance 200.0}
(let [from "user1"
to "user2"
amount 200.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
;; if funds are not available abort the transaction
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; these two update are inside a transaction and they will be stored
;; atomically
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
;;=> {:firstname "Jane", :lastname "Smith", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "Jane", :lastname "Smith", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 50.0}
;; multi table transactions
(require '[clj-time.core :as t]
'[clj-time.format :as f])
(defn now-UTC
"Returns the current UTC timestamp in ISO format"
[]
(f/unparse (f/formatters :date-time) (t/now)))
(now-UTC)
;;=> "2018-03-21T22:15:52.512Z"
(let [from "user2"
to "user1"
amount 250.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; add a entry in the `transactions`
(sph/set-value! tx "transactions" (now-UTC)
{:tx-type :transfer :from from :amount amount :to to})
;; now update both user's balance
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
(with-open [cur (sph/cursor env)]
(into [] (sph/range-query cur "transactions")))
;;=> [["2018-03-21T22:26:16.284Z" {:tx-type :transfer, :from "user2", :amount 250.0, :to "user1"}]]
(sph/get-value env "accounts" "user2")
;;=> {:firstname "Jane", :lastname "Smith", :age 28, :balance 150.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 300.0}
(sph/transact! env
(fn [tx]
(let [u (sph/get-value tx "accounts" "user1")]
(when u
(sph/set-value! tx "accounts" "user1"
(update u :votes (fnil inc 0)))))))
;;=> {:firstname "John", :lastname "Doe", :age 34, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" (fn [u] (update u :age inc)))
;;=> {:firstname "John", :lastname "Doe", :age 35, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" update :age inc)
;;=> {:firstname "John", :lastname "Doe", :age 35, :balance 300.0 :votes 1}
;; user10 doesn't exists.
(sph/update-value! env "accounts" "user10" update :age inc)
;;=> nil
;; user10 doesn't exists.
(sph/upsert-value! env "accounts" "user10" update :votes (fnil inc 0))
;;=> {:votes 1}
| 104506 | (ns user
(:require [com.brunobonacci.sophia :as sph]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| G E T / S E T / D E L E T E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def env
(sph/sophia
{;; where to store the files on disk
:sophia.path "/tmp/sophia-test"
;; which logical databases to create
:dbs ["accounts", {:name "transactions"}]}))
;; set a simple value
(sph/set-value! env "accounts" "user1" "<NAME>")
;;=> "<NAME>"
;; get the value back
(sph/get-value env "accounts" "user1")
;;=> "<NAME>"
;; delete a key
(sph/delete-key! env "accounts" "user1")
;;=> nil
;; now the key isn't present
(sph/get-value env "accounts" "user1")
;;=> nil
;; set a complex value
(sph/set-value! env "accounts" "user1"
{:firstname "<NAME>" :lastname "<NAME>" :age 34 :balance 100.0})
;;=> {:firstname "<NAME>" :lastname "<NAME>" :age 34 :balance 100.0}
;; get it back
(sph/get-value env "accounts" "user1")
;;=> {:firstname "<NAME>" :lastname "<NAME>" :age 34 :balance 100.0}
(sph/set-value! env "accounts" "user2"
{:firstname "<NAME>" :lastname "<NAME>" :age 28 :balance 200.0})
;;=> :{:firstname "<NAME>" :lastname "<NAME>" :age 28 :balance 200.0}
(sph/set-value! env "accounts" "admin1"
{:firstname "<NAME>" :lastname "<NAME>" :age 32 :grants [:accounts/admin]})
;;=> {:firstname "<NAME>" :lastname "Green" :age 32 :grants [:accounts/admin]}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| R A N G E - Q U E R Y |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; display all the values in ascending order (by key)
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts")))
(with-open [cur (sph/cursor env)]
(into {}
(sph/range-query cur "accounts")))
;;=> {"admin1" {:firstname "<NAME>", :lastname "Green", :age 32, :grants [:accounts/admin]},
;; "user1" {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0},
;; "user2" {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 200.0}}
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts" :order :desc)))
;; ["user2" {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 200.0}]
;; ["user1" {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "<NAME>", :lastname "Green", :age 32, :grants [:accounts/admin]}]
;;
;; Seek and scan
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :asc)))
;;=> [["user1" {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0}]
;; ["user2" {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc)))
;;=> [["user1" {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "<NAME>", :lastname "<NAME>", :age 32, :grants [:accounts/admin]}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc :search-type :index-scan-exclusive)))
;;=> [["admin1" {:firstname "<NAME>", :lastname "<NAME>", :age 32, :grants [:accounts/admin]}]]
;;
;; prefix
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix)))
;;=> [["user1" {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0}]
;; ["user2" {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "foo" :search-type :prefix)))
;;=> []
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix
:order :desc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| T R A N S A C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(sph/get-value env "accounts" "user1")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 100.0}
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" "user1")]
(sph/set-value! tx "accounts" "user1" (update user1 :balance + 150.0))))
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 200.0}
(let [from "user1"
to "user2"
amount 200.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
;; if funds are not available abort the transaction
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; these two update are inside a transaction and they will be stored
;; atomically
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 50.0}
;; multi table transactions
(require '[clj-time.core :as t]
'[clj-time.format :as f])
(defn now-UTC
"Returns the current UTC timestamp in ISO format"
[]
(f/unparse (f/formatters :date-time) (t/now)))
(now-UTC)
;;=> "2018-03-21T22:15:52.512Z"
(let [from "user2"
to "user1"
amount 250.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; add a entry in the `transactions`
(sph/set-value! tx "transactions" (now-UTC)
{:tx-type :transfer :from from :amount amount :to to})
;; now update both user's balance
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
(with-open [cur (sph/cursor env)]
(into [] (sph/range-query cur "transactions")))
;;=> [["2018-03-21T22:26:16.284Z" {:tx-type :transfer, :from "user2", :amount 250.0, :to "user1"}]]
(sph/get-value env "accounts" "user2")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 28, :balance 150.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 300.0}
(sph/transact! env
(fn [tx]
(let [u (sph/get-value tx "accounts" "user1")]
(when u
(sph/set-value! tx "accounts" "user1"
(update u :votes (fnil inc 0)))))))
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 34, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" (fn [u] (update u :age inc)))
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 35, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" update :age inc)
;;=> {:firstname "<NAME>", :lastname "<NAME>", :age 35, :balance 300.0 :votes 1}
;; user10 doesn't exists.
(sph/update-value! env "accounts" "user10" update :age inc)
;;=> nil
;; user10 doesn't exists.
(sph/upsert-value! env "accounts" "user10" update :votes (fnil inc 0))
;;=> {:votes 1}
| true | (ns user
(:require [com.brunobonacci.sophia :as sph]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| G E T / S E T / D E L E T E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def env
(sph/sophia
{;; where to store the files on disk
:sophia.path "/tmp/sophia-test"
;; which logical databases to create
:dbs ["accounts", {:name "transactions"}]}))
;; set a simple value
(sph/set-value! env "accounts" "user1" "PI:NAME:<NAME>END_PI")
;;=> "PI:NAME:<NAME>END_PI"
;; get the value back
(sph/get-value env "accounts" "user1")
;;=> "PI:NAME:<NAME>END_PI"
;; delete a key
(sph/delete-key! env "accounts" "user1")
;;=> nil
;; now the key isn't present
(sph/get-value env "accounts" "user1")
;;=> nil
;; set a complex value
(sph/set-value! env "accounts" "user1"
{:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 34 :balance 100.0})
;;=> {:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 34 :balance 100.0}
;; get it back
(sph/get-value env "accounts" "user1")
;;=> {:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 34 :balance 100.0}
(sph/set-value! env "accounts" "user2"
{:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 28 :balance 200.0})
;;=> :{:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 28 :balance 200.0}
(sph/set-value! env "accounts" "admin1"
{:firstname "PI:NAME:<NAME>END_PI" :lastname "PI:NAME:<NAME>END_PI" :age 32 :grants [:accounts/admin]})
;;=> {:firstname "PI:NAME:<NAME>END_PI" :lastname "Green" :age 32 :grants [:accounts/admin]}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| R A N G E - Q U E R Y |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; display all the values in ascending order (by key)
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts")))
(with-open [cur (sph/cursor env)]
(into {}
(sph/range-query cur "accounts")))
;;=> {"admin1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "Green", :age 32, :grants [:accounts/admin]},
;; "user1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0},
;; "user2" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 200.0}}
(with-open [cur (sph/cursor env)]
(run! prn
(sph/range-query cur "accounts" :order :desc)))
;; ["user2" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 200.0}]
;; ["user1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "Green", :age 32, :grants [:accounts/admin]}]
;;
;; Seek and scan
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :asc)))
;;=> [["user1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0}]
;; ["user2" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc)))
;;=> [["user1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0}]
;; ["admin1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 32, :grants [:accounts/admin]}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user1" :order :desc :search-type :index-scan-exclusive)))
;;=> [["admin1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 32, :grants [:accounts/admin]}]]
;;
;; prefix
;;
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix)))
;;=> [["user1" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0}]
;; ["user2" {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 200.0}]]
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "foo" :search-type :prefix)))
;;=> []
(with-open [cur (sph/cursor env)]
(into []
(sph/range-query cur "accounts" :key "user" :search-type :prefix
:order :desc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| T R A N S A C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(sph/get-value env "accounts" "user1")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 100.0}
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" "user1")]
(sph/set-value! tx "accounts" "user1" (update user1 :balance + 150.0))))
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 250.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 200.0}
(let [from "user1"
to "user2"
amount 200.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
;; if funds are not available abort the transaction
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; these two update are inside a transaction and they will be stored
;; atomically
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user2")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 400.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 50.0}
;; multi table transactions
(require '[clj-time.core :as t]
'[clj-time.format :as f])
(defn now-UTC
"Returns the current UTC timestamp in ISO format"
[]
(f/unparse (f/formatters :date-time) (t/now)))
(now-UTC)
;;=> "2018-03-21T22:15:52.512Z"
(let [from "user2"
to "user1"
amount 250.0]
;; start transaction
(sph/with-transaction [tx (sph/begin-transaction env)]
(let [user1 (sph/get-value tx "accounts" from)
user2 (sph/get-value tx "accounts" to)]
(when-not (>= (:balance user1) amount)
(throw (ex-info (str "Insufficient funds in available from: " from)
{:from user1 :amount amount :to user2})))
;; add a entry in the `transactions`
(sph/set-value! tx "transactions" (now-UTC)
{:tx-type :transfer :from from :amount amount :to to})
;; now update both user's balance
(sph/set-value! tx "accounts" from (update user1 :balance - amount ))
(sph/set-value! tx "accounts" to (update user2 :balance + amount )))))
(with-open [cur (sph/cursor env)]
(into [] (sph/range-query cur "transactions")))
;;=> [["2018-03-21T22:26:16.284Z" {:tx-type :transfer, :from "user2", :amount 250.0, :to "user1"}]]
(sph/get-value env "accounts" "user2")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 28, :balance 150.0}
(sph/get-value env "accounts" "user1")
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 300.0}
(sph/transact! env
(fn [tx]
(let [u (sph/get-value tx "accounts" "user1")]
(when u
(sph/set-value! tx "accounts" "user1"
(update u :votes (fnil inc 0)))))))
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 34, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" (fn [u] (update u :age inc)))
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 35, :balance 300.0 :votes 1}
(sph/update-value! env "accounts" "user1" update :age inc)
;;=> {:firstname "PI:NAME:<NAME>END_PI", :lastname "PI:NAME:<NAME>END_PI", :age 35, :balance 300.0 :votes 1}
;; user10 doesn't exists.
(sph/update-value! env "accounts" "user10" update :age inc)
;;=> nil
;; user10 doesn't exists.
(sph/upsert-value! env "accounts" "user10" update :votes (fnil inc 0))
;;=> {:votes 1}
|
[
{
"context": "s (= [\"Building Search Applications is authored by Manu Konchady.\"]\n (generate-text {:document-plan-name \"",
"end": 671,
"score": 0.930834174156189,
"start": 658,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": "{\"0\" [\"Building Search Applications is authored by Manu Konchady.\"]\n \"1\" [\"The Business Blockchain is aut",
"end": 867,
"score": 0.9688337445259094,
"start": 854,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"1\" [\"The Business Blockchain is authored by William Mougayar.\"]}\n (generate-text-bulk {:document-plan-",
"end": 942,
"score": 0.9499908089637756,
"start": 926,
"tag": "NAME",
"value": "William Mougayar"
},
{
"context": " :data-rows {\"0\" {\"authors\" \"Manu Konchady\"\n ",
"end": 1090,
"score": 0.9997807741165161,
"start": 1077,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"1\" {\"authors\" \"William Mougayar\"\n ",
"end": 1273,
"score": 0.9998129606246948,
"start": 1257,
"tag": "NAME",
"value": "William Mougayar"
},
{
"context": "s (= [\"Building Search Applications is authored by Manu Konchady.\"]\n (generate-text {:document-plan-nam",
"end": 1508,
"score": 0.6688746809959412,
"start": 1498,
"tag": "NAME",
"value": "Manu Konch"
},
{
"context": "{\"0\" [\"Building Search Applications is authored by Manu Konchady.\"]\n \"1\" [\"The Business Blockchain is aut",
"end": 1708,
"score": 0.969253659248352,
"start": 1695,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"1\" [\"The Business Blockchain is authored by William Mougayar.\"]}\n (generate-text-bulk {:document-plan-",
"end": 1783,
"score": 0.9960034489631653,
"start": 1767,
"tag": "NAME",
"value": "William Mougayar"
},
{
"context": " :data-rows {\"0\" {\"authors\" \"Manu Konchady\"\n ",
"end": 1931,
"score": 0.9997398257255554,
"start": 1918,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"1\" {\"authors\" \"William Mougayar\"\n ",
"end": 2114,
"score": 0.999832272529602,
"start": 2098,
"tag": "NAME",
"value": "William Mougayar"
},
{
"context": "s (= #{\"Building Search Applications is written by Manu Konchady.\"\n \"Building Search Applications wird d",
"end": 2452,
"score": 0.9998656511306763,
"start": 2439,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"Building Search Applications wird durch Manu Konchady geschrieben.\"}\n (set (generate-text {:doc",
"end": 2520,
"score": 0.9677351713180542,
"start": 2507,
"tag": "NAME",
"value": "Manu Konchady"
}
] | api/test/api/end_to_end_test.clj | oytuntez/accelerated-text | 0 | (ns api.end-to-end-test
(:require [api.db-fixtures :as db]
[api.test-utils :refer [generate-text generate-text-bulk load-document-plan load-dictionary]]
[clojure.test :refer [deftest is use-fixtures]]))
(use-fixtures :each db/clean-db)
(deftest ^:integration text-generation-with-default-plan
(is (= [] (generate-text {:document-plan-name "Untitled plan"})))
(is (= {"test" []} (generate-text-bulk {:document-plan-name "Untitled plan"
:data-rows {"test" {}}}))))
(deftest ^:integration text-generation-with-simple-plan
(is (= ["Building Search Applications is authored by Manu Konchady."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.csv"})))
(is (= {"0" ["Building Search Applications is authored by Manu Konchady."]
"1" ["The Business Blockchain is authored by William Mougayar."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "Manu Konchady"
"title" "Building Search Applications"}
"1" {"authors" "William Mougayar"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-simple-plan-using-xlsx
(is (= ["Building Search Applications is authored by Manu Konchady."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.xlsx"})))
(is (= {"0" ["Building Search Applications is authored by Manu Konchady."]
"1" ["The Business Blockchain is authored by William Mougayar."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "Manu Konchady"
"title" "Building Search Applications"}
"1" {"authors" "William Mougayar"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-complex-plan
(load-dictionary "authorship")
(load-document-plan "AuthorshipRGL")
(load-document-plan "AuthorshipAMR")
(is (= #{"Building Search Applications is written by Manu Konchady."
"Building Search Applications wird durch Manu Konchady geschrieben."}
(set (generate-text {:document-plan-name "AuthorshipMultiLang"
:data-file-name "books.csv"
:reader-flags {"Eng" true "Ger" true}})))))
| 113952 | (ns api.end-to-end-test
(:require [api.db-fixtures :as db]
[api.test-utils :refer [generate-text generate-text-bulk load-document-plan load-dictionary]]
[clojure.test :refer [deftest is use-fixtures]]))
(use-fixtures :each db/clean-db)
(deftest ^:integration text-generation-with-default-plan
(is (= [] (generate-text {:document-plan-name "Untitled plan"})))
(is (= {"test" []} (generate-text-bulk {:document-plan-name "Untitled plan"
:data-rows {"test" {}}}))))
(deftest ^:integration text-generation-with-simple-plan
(is (= ["Building Search Applications is authored by <NAME>."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.csv"})))
(is (= {"0" ["Building Search Applications is authored by <NAME>."]
"1" ["The Business Blockchain is authored by <NAME>."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "<NAME>"
"title" "Building Search Applications"}
"1" {"authors" "<NAME>"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-simple-plan-using-xlsx
(is (= ["Building Search Applications is authored by <NAME>ady."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.xlsx"})))
(is (= {"0" ["Building Search Applications is authored by <NAME>."]
"1" ["The Business Blockchain is authored by <NAME>."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "<NAME>"
"title" "Building Search Applications"}
"1" {"authors" "<NAME>"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-complex-plan
(load-dictionary "authorship")
(load-document-plan "AuthorshipRGL")
(load-document-plan "AuthorshipAMR")
(is (= #{"Building Search Applications is written by <NAME>."
"Building Search Applications wird durch <NAME> geschrieben."}
(set (generate-text {:document-plan-name "AuthorshipMultiLang"
:data-file-name "books.csv"
:reader-flags {"Eng" true "Ger" true}})))))
| true | (ns api.end-to-end-test
(:require [api.db-fixtures :as db]
[api.test-utils :refer [generate-text generate-text-bulk load-document-plan load-dictionary]]
[clojure.test :refer [deftest is use-fixtures]]))
(use-fixtures :each db/clean-db)
(deftest ^:integration text-generation-with-default-plan
(is (= [] (generate-text {:document-plan-name "Untitled plan"})))
(is (= {"test" []} (generate-text-bulk {:document-plan-name "Untitled plan"
:data-rows {"test" {}}}))))
(deftest ^:integration text-generation-with-simple-plan
(is (= ["Building Search Applications is authored by PI:NAME:<NAME>END_PI."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.csv"})))
(is (= {"0" ["Building Search Applications is authored by PI:NAME:<NAME>END_PI."]
"1" ["The Business Blockchain is authored by PI:NAME:<NAME>END_PI."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "PI:NAME:<NAME>END_PI"
"title" "Building Search Applications"}
"1" {"authors" "PI:NAME:<NAME>END_PI"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-simple-plan-using-xlsx
(is (= ["Building Search Applications is authored by PI:NAME:<NAME>END_PIady."]
(generate-text {:document-plan-name "Authorship"
:data-file-name "books.xlsx"})))
(is (= {"0" ["Building Search Applications is authored by PI:NAME:<NAME>END_PI."]
"1" ["The Business Blockchain is authored by PI:NAME:<NAME>END_PI."]}
(generate-text-bulk {:document-plan-name "Authorship"
:data-rows {"0" {"authors" "PI:NAME:<NAME>END_PI"
"title" "Building Search Applications"}
"1" {"authors" "PI:NAME:<NAME>END_PI"
"title" "The Business Blockchain"}}}))))
(deftest ^:integration text-generation-with-complex-plan
(load-dictionary "authorship")
(load-document-plan "AuthorshipRGL")
(load-document-plan "AuthorshipAMR")
(is (= #{"Building Search Applications is written by PI:NAME:<NAME>END_PI."
"Building Search Applications wird durch PI:NAME:<NAME>END_PI geschrieben."}
(set (generate-text {:document-plan-name "AuthorshipMultiLang"
:data-file-name "books.csv"
:reader-flags {"Eng" true "Ger" true}})))))
|
[
{
"context": "er-case (str \"file://\" dir))\n fred {:name \"fred\", :age 42}\n fred-ref (dref/persist base",
"end": 2551,
"score": 0.8202880024909973,
"start": 2550,
"tag": "NAME",
"value": "f"
},
{
"context": "r-case (str \"file://\" dir))\n fred {:name \"fred\", :age 42}\n fred-ref (dref/persist base-ur",
"end": 2554,
"score": 0.5061106085777283,
"start": 2551,
"tag": "USERNAME",
"value": "red"
},
{
"context": "/lower-case dir) \"fred.edn\")\n fred {:name \"fred\"}]\n (io/delete-file (.getSchemeSpecificPart (U",
"end": 3228,
"score": 0.9959030747413635,
"start": 3224,
"tag": "NAME",
"value": "fred"
},
{
"context": " \"atomic:mem://tmp/fred.edn\"\n fred {:name \"fred\"}]\n (dref/delete! uri)\n (is (nil? (dref/val",
"end": 3773,
"score": 0.9952552318572998,
"start": 3769,
"tag": "NAME",
"value": "fred"
},
{
"context": " (is (= fred @fred-ref))\n (is (= {:name \"fred\"\n :age 42}\n (swap! fred-",
"end": 4202,
"score": 0.99385005235672,
"start": 4198,
"tag": "NAME",
"value": "fred"
}
] | test/riverford/durable_ref/core_test.clj | riverford/durable-ref | 72 | (ns riverford.durable-ref.core-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.core :as dref]
[clojure.string :as str]
[clojure.java.io :as io])
(:import (java.util UUID)
(java.net URI)))
(deftest test-persist-immediate-deref-equiv
(is (= @(dref/persist "mem://tests" 42)
42))
(is (= (dref/value (dref/persist "mem://tests" {:name "fred"}))
{:name "fred"})))
(deftest test-can-return-uri-of-ref
(is (= (str (dref/uri (dref/reference "mem://tests/foo.edn")))
"mem://tests/foo.edn"))
(is (= (str (dref/uri (dref/reference "volatile:mem://tests/foo.edn")))
"volatile:mem://tests/foo.edn")))
(deftest test-persist-delayed-deref-equiv
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= (dref/value (dref/uri ref))
@ref
uuid))))
(deftest test-overwrite-deref-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/overwrite! ref :bar)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:bar))))
(deftest test-delete-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/delete! ref)
(is (nil? (dref/value ref)))
(dref/delete! ref)
(is (nil? (dref/value ref)))))
(deftest test-persist-idempotency
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= ref
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/reference (dref/uri ref))))))
(deftest test-persist-interning
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (identical? ref (dref/persist "mem://tests" uuid)))
(is (identical? ref (dref/reference (dref/uri ref))))))
(deftest test-value-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
base-uri (str/lower-case (str "file://" dir))
fred {:name "fred", :age 42}
fred-ref (dref/persist base-uri fred)]
(is (instance? riverford.durable_ref.core.DurableValueRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= @fred-ref fred))
(is (= (dref/value fred-ref) fred))
(is (= (dref/uri fred-ref)
(URI. (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))))
(is (= (dref/value (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))
fred))))
(deftest test-volatile-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
uri (str "volatile:file://" (str/lower-case dir) "fred.edn")
fred {:name "fred"}]
(io/delete-file (.getSchemeSpecificPart (URI. uri)) true)
(is (nil? (dref/value uri)))
(is (nil? (dref/overwrite! uri fred)))
(is (= fred (dref/value uri)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableVolatileRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-atomic-ref-tutorial-correct
(let [uri "atomic:mem://tmp/fred.edn"
fred {:name "fred"}]
(dref/delete! uri)
(is (nil? (dref/value uri)))
(is (= 1 (dref/atomic-swap! uri (fnil inc 0))))
(is (= 2 (dref/atomic-swap! uri (fnil inc 0))))
(is (nil? (dref/overwrite! uri fred)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableAtomicRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(is (= {:name "fred"
:age 42}
(swap! fred-ref assoc :age 42)))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-value-ref-mutation-attempt-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))]
(is (thrown? Throwable (dref/overwrite! ref (UUID/randomUUID))))
(is (thrown? Throwable (dref/delete! ref)))))
(deftest test-value-ref-mutated-in-storage-deref-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))
sneaky-ref (dref/reference (str "volatile:" (.getSchemeSpecificPart (dref/uri ref))))]
(dref/overwrite! sneaky-ref (UUID/randomUUID))
(dref/evict! ref)
(is (thrown? Throwable (binding [dref/*verify-hash-identity* true] @ref)))))
(deftest test-ref-eq
(are [x y]
(= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-neq
(are [x y]
(not= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/reference "mem://tests/foo") (dref/->DurableVolatileRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "mem://tests/foo/bar"))))
(deftest test-ref-hash-eq
(are [x y]
(= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-hash-neq
(are [x y]
(not= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")))
(deftest test-edn-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn" {}) "edn" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-edn-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn.zip" {}) "edn.zip" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-concurrent-swaps
(let [uri (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))
futs (doall (repeatedly 10 #(future
(dotimes [x 100]
(Thread/sleep (rand-int 10))
(dref/atomic-swap! uri (fnil inc 0) {})))))]
(run! deref futs)
(is (= 1000 (dref/value uri)))
(dref/delete! uri)))
(deftest test-atom-interface
(let [ref (dref/reference (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn")))]
(is (nil? @ref))
(is (= 42 (reset! ref 42)))
(is (= 42 (swap! ref identity)))
(is (= 45 (swap! ref + 3)))
(is (= 65 (swap! ref + 10 10)))
(is (= 95 (swap! ref + 10 10 10)))
(is (= 135 (swap! ref + 10 10 10 10)))))
(deftest test-atomic-interface
(let [ref (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))]
(is (nil? (dref/value ref)))
(is (nil? (dref/overwrite! ref 42)))
(is (= 42 (dref/atomic-swap! ref identity)))
(is (= 45 (dref/atomic-swap! ref #(+ % 3)))))) | 102231 | (ns riverford.durable-ref.core-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.core :as dref]
[clojure.string :as str]
[clojure.java.io :as io])
(:import (java.util UUID)
(java.net URI)))
(deftest test-persist-immediate-deref-equiv
(is (= @(dref/persist "mem://tests" 42)
42))
(is (= (dref/value (dref/persist "mem://tests" {:name "fred"}))
{:name "fred"})))
(deftest test-can-return-uri-of-ref
(is (= (str (dref/uri (dref/reference "mem://tests/foo.edn")))
"mem://tests/foo.edn"))
(is (= (str (dref/uri (dref/reference "volatile:mem://tests/foo.edn")))
"volatile:mem://tests/foo.edn")))
(deftest test-persist-delayed-deref-equiv
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= (dref/value (dref/uri ref))
@ref
uuid))))
(deftest test-overwrite-deref-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/overwrite! ref :bar)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:bar))))
(deftest test-delete-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/delete! ref)
(is (nil? (dref/value ref)))
(dref/delete! ref)
(is (nil? (dref/value ref)))))
(deftest test-persist-idempotency
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= ref
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/reference (dref/uri ref))))))
(deftest test-persist-interning
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (identical? ref (dref/persist "mem://tests" uuid)))
(is (identical? ref (dref/reference (dref/uri ref))))))
(deftest test-value-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
base-uri (str/lower-case (str "file://" dir))
fred {:name "<NAME>red", :age 42}
fred-ref (dref/persist base-uri fred)]
(is (instance? riverford.durable_ref.core.DurableValueRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= @fred-ref fred))
(is (= (dref/value fred-ref) fred))
(is (= (dref/uri fred-ref)
(URI. (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))))
(is (= (dref/value (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))
fred))))
(deftest test-volatile-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
uri (str "volatile:file://" (str/lower-case dir) "fred.edn")
fred {:name "<NAME>"}]
(io/delete-file (.getSchemeSpecificPart (URI. uri)) true)
(is (nil? (dref/value uri)))
(is (nil? (dref/overwrite! uri fred)))
(is (= fred (dref/value uri)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableVolatileRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-atomic-ref-tutorial-correct
(let [uri "atomic:mem://tmp/fred.edn"
fred {:name "<NAME>"}]
(dref/delete! uri)
(is (nil? (dref/value uri)))
(is (= 1 (dref/atomic-swap! uri (fnil inc 0))))
(is (= 2 (dref/atomic-swap! uri (fnil inc 0))))
(is (nil? (dref/overwrite! uri fred)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableAtomicRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(is (= {:name "<NAME>"
:age 42}
(swap! fred-ref assoc :age 42)))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-value-ref-mutation-attempt-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))]
(is (thrown? Throwable (dref/overwrite! ref (UUID/randomUUID))))
(is (thrown? Throwable (dref/delete! ref)))))
(deftest test-value-ref-mutated-in-storage-deref-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))
sneaky-ref (dref/reference (str "volatile:" (.getSchemeSpecificPart (dref/uri ref))))]
(dref/overwrite! sneaky-ref (UUID/randomUUID))
(dref/evict! ref)
(is (thrown? Throwable (binding [dref/*verify-hash-identity* true] @ref)))))
(deftest test-ref-eq
(are [x y]
(= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-neq
(are [x y]
(not= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/reference "mem://tests/foo") (dref/->DurableVolatileRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "mem://tests/foo/bar"))))
(deftest test-ref-hash-eq
(are [x y]
(= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-hash-neq
(are [x y]
(not= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")))
(deftest test-edn-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn" {}) "edn" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-edn-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn.zip" {}) "edn.zip" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-concurrent-swaps
(let [uri (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))
futs (doall (repeatedly 10 #(future
(dotimes [x 100]
(Thread/sleep (rand-int 10))
(dref/atomic-swap! uri (fnil inc 0) {})))))]
(run! deref futs)
(is (= 1000 (dref/value uri)))
(dref/delete! uri)))
(deftest test-atom-interface
(let [ref (dref/reference (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn")))]
(is (nil? @ref))
(is (= 42 (reset! ref 42)))
(is (= 42 (swap! ref identity)))
(is (= 45 (swap! ref + 3)))
(is (= 65 (swap! ref + 10 10)))
(is (= 95 (swap! ref + 10 10 10)))
(is (= 135 (swap! ref + 10 10 10 10)))))
(deftest test-atomic-interface
(let [ref (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))]
(is (nil? (dref/value ref)))
(is (nil? (dref/overwrite! ref 42)))
(is (= 42 (dref/atomic-swap! ref identity)))
(is (= 45 (dref/atomic-swap! ref #(+ % 3)))))) | true | (ns riverford.durable-ref.core-test
(:require [clojure.test :refer :all]
[riverford.durable-ref.core :as dref]
[clojure.string :as str]
[clojure.java.io :as io])
(:import (java.util UUID)
(java.net URI)))
(deftest test-persist-immediate-deref-equiv
(is (= @(dref/persist "mem://tests" 42)
42))
(is (= (dref/value (dref/persist "mem://tests" {:name "fred"}))
{:name "fred"})))
(deftest test-can-return-uri-of-ref
(is (= (str (dref/uri (dref/reference "mem://tests/foo.edn")))
"mem://tests/foo.edn"))
(is (= (str (dref/uri (dref/reference "volatile:mem://tests/foo.edn")))
"volatile:mem://tests/foo.edn")))
(deftest test-persist-delayed-deref-equiv
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= (dref/value (dref/uri ref))
@ref
uuid))))
(deftest test-overwrite-deref-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/overwrite! ref :bar)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:bar))))
(deftest test-delete-cycle
(let [ref (format "volatile:mem://tests/%s.edn" (UUID/randomUUID))]
(is (nil? (dref/value ref)))
(dref/overwrite! ref :foo)
(is (= (dref/value ref)
(dref/value (URI. ref))
@(dref/reference ref)
@(dref/reference (URI. ref))
:foo))
(dref/delete! ref)
(is (nil? (dref/value ref)))
(dref/delete! ref)
(is (nil? (dref/value ref)))))
(deftest test-persist-idempotency
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (= ref
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/persist "mem://tests" uuid)
(dref/reference (dref/uri ref))))))
(deftest test-persist-interning
(let [uuid (UUID/randomUUID)
ref (dref/persist "mem://tests" uuid)]
(is (identical? ref (dref/persist "mem://tests" uuid)))
(is (identical? ref (dref/reference (dref/uri ref))))))
(deftest test-value-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
base-uri (str/lower-case (str "file://" dir))
fred {:name "PI:NAME:<NAME>END_PIred", :age 42}
fred-ref (dref/persist base-uri fred)]
(is (instance? riverford.durable_ref.core.DurableValueRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= @fred-ref fred))
(is (= (dref/value fred-ref) fred))
(is (= (dref/uri fred-ref)
(URI. (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))))
(is (= (dref/value (str "value:" base-uri "7664124773263ad3bda79e9267e1793915c09e2d.edn"))
fred))))
(deftest test-volatile-ref-tutorial-correct
(let [dir (System/getProperty "java.io.tmpdir")
uri (str "volatile:file://" (str/lower-case dir) "fred.edn")
fred {:name "PI:NAME:<NAME>END_PI"}]
(io/delete-file (.getSchemeSpecificPart (URI. uri)) true)
(is (nil? (dref/value uri)))
(is (nil? (dref/overwrite! uri fred)))
(is (= fred (dref/value uri)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableVolatileRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-atomic-ref-tutorial-correct
(let [uri "atomic:mem://tmp/fred.edn"
fred {:name "PI:NAME:<NAME>END_PI"}]
(dref/delete! uri)
(is (nil? (dref/value uri)))
(is (= 1 (dref/atomic-swap! uri (fnil inc 0))))
(is (= 2 (dref/atomic-swap! uri (fnil inc 0))))
(is (nil? (dref/overwrite! uri fred)))
(let [fred-ref (dref/reference uri)]
(is (instance? riverford.durable_ref.core.DurableAtomicRef fred-ref))
(is (satisfies? dref/IDurableRef fred-ref))
(is (= fred @fred-ref))
(is (= {:name "PI:NAME:<NAME>END_PI"
:age 42}
(swap! fred-ref assoc :age 42)))
(dref/delete! fred-ref)
(is (nil? @fred-ref)))))
(deftest test-value-ref-mutation-attempt-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))]
(is (thrown? Throwable (dref/overwrite! ref (UUID/randomUUID))))
(is (thrown? Throwable (dref/delete! ref)))))
(deftest test-value-ref-mutated-in-storage-deref-throws
(let [ref (dref/persist "mem://tests" (UUID/randomUUID))
sneaky-ref (dref/reference (str "volatile:" (.getSchemeSpecificPart (dref/uri ref))))]
(dref/overwrite! sneaky-ref (UUID/randomUUID))
(dref/evict! ref)
(is (thrown? Throwable (binding [dref/*verify-hash-identity* true] @ref)))))
(deftest test-ref-eq
(are [x y]
(= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-neq
(are [x y]
(not= x y)
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/reference "mem://tests/foo") (dref/->DurableVolatileRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableReadonlyRef (URI. "mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "mem://tests/foo/bar"))))
(deftest test-ref-hash-eq
(are [x y]
(= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo")
(dref/reference "mem://tests/foo") (dref/->DurableReadonlyRef (URI. "mem://tests/foo"))
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" 42)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")
(dref/reference "volatile:mem://tests/foo/bar") (dref/->DurableVolatileRef (URI. "volatile:mem://tests/foo/bar"))
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "atomic:mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/->DurableAtomicRef (URI. "atomic:mem://tests/foo/bar"))))
(deftest test-ref-hash-neq
(are [x y]
(not= (hash x) (hash y))
(dref/reference "mem://tests/foo") (dref/reference "mem://tests/foo2")
(dref/persist "mem://tests/foo" 42) (dref/persist "mem://tests/foo" :fred)
(dref/reference "volatile:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "mem://tests/foo/bar")
(dref/reference "atomic:mem://tests/foo/bar") (dref/reference "volatile:mem://tests/foo/bar")))
(deftest test-edn-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn" {}) "edn" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-edn-zip-serialization-round-trips
(are [x]
(= (dref/deserialize (dref/serialize x "edn.zip" {}) "edn.zip" {}) x)
42
:fred
"ethel"
42M
42N
42.5
2/3
{:foo :bar}
[1 2 3]
(range 99)
#{1, 2, 3}))
(deftest test-concurrent-swaps
(let [uri (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))
futs (doall (repeatedly 10 #(future
(dotimes [x 100]
(Thread/sleep (rand-int 10))
(dref/atomic-swap! uri (fnil inc 0) {})))))]
(run! deref futs)
(is (= 1000 (dref/value uri)))
(dref/delete! uri)))
(deftest test-atom-interface
(let [ref (dref/reference (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn")))]
(is (nil? @ref))
(is (= 42 (reset! ref 42)))
(is (= 42 (swap! ref identity)))
(is (= 45 (swap! ref + 3)))
(is (= 65 (swap! ref + 10 10)))
(is (= 95 (swap! ref + 10 10 10)))
(is (= 135 (swap! ref + 10 10 10 10)))))
(deftest test-atomic-interface
(let [ref (URI. (str "atomic:mem://test/" (UUID/randomUUID) ".edn"))]
(is (nil? (dref/value ref)))
(is (nil? (dref/overwrite! ref 42)))
(is (= 42 (dref/atomic-swap! ref identity)))
(is (= 45 (dref/atomic-swap! ref #(+ % 3)))))) |
[
{
"context": " \"eu-central-1_tk6YrMrPc\"}}\n {:username \"PingFederate_robert.pofuk@rbinternational.com\"}))))\n\n(deftest test2\n (is (= {}\n (cogni",
"end": 567,
"score": 0.9999168515205383,
"start": 522,
"tag": "EMAIL",
"value": "PingFederate_robert.pofuk@rbinternational.com"
},
{
"context": " \"eu-central-1_tk6YrMrPc\"}}\n {:username \"PingFederate_robert.pofuk@rbinternational.com\"}))))\n\n",
"end": 1010,
"score": 0.9999231100082397,
"start": 965,
"tag": "EMAIL",
"value": "PingFederate_robert.pofuk@rbinternational.com"
}
] | test/sdk/aws/repl.clj | raiffeisenbankinternational/edd-core | 4 | (ns sdk.aws.repl
(:require [clojure.test :refer :all]
[sdk.aws.cognito-idp :as cognito-idp]
[lambda.util :as util]))
(deftest test1
(is (= {}
(cognito-idp/admin-get-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "PingFederate_robert.pofuk@rbinternational.com"}))))
(deftest test2
(is (= {}
(cognito-idp/admin-list-groups-for-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "PingFederate_robert.pofuk@rbinternational.com"}))))
| 121794 | (ns sdk.aws.repl
(:require [clojure.test :refer :all]
[sdk.aws.cognito-idp :as cognito-idp]
[lambda.util :as util]))
(deftest test1
(is (= {}
(cognito-idp/admin-get-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "<EMAIL>"}))))
(deftest test2
(is (= {}
(cognito-idp/admin-list-groups-for-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "<EMAIL>"}))))
| true | (ns sdk.aws.repl
(:require [clojure.test :refer :all]
[sdk.aws.cognito-idp :as cognito-idp]
[lambda.util :as util]))
(deftest test1
(is (= {}
(cognito-idp/admin-get-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "PI:EMAIL:<EMAIL>END_PI"}))))
(deftest test2
(is (= {}
(cognito-idp/admin-list-groups-for-user
{:aws {:aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID")
:aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY")
:aws-session-token (util/get-env "AWS_SESSION_TOKEN")}
:auth {:user-pool-id "eu-central-1_tk6YrMrPc"}}
{:username "PI:EMAIL:<EMAIL>END_PI"}))))
|
[
{
"context": " :password :env/CI_DEPLOY_PASSWORD\n :sign-releases fals",
"end": 1422,
"score": 0.6570007801055908,
"start": 1414,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | project.clj | kephale/incisor-cell-segmentation | 0 | (defproject incisor-cell-counter "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:jvm-opts ["-Xmx25g" "-server"]
:main incisor-cell-counter.imaris-cropped-analysis
:dependencies [[org.clojure/clojure "1.8.0"]
[fun.imagej/fun.imagej "0.2.5"]
[mosaic/MosaicSuite "1.0.8_Full"]
[org.flatland/ordered "1.5.6"]
]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["sonatype-snapshots" "https://oss.sonatype.org/content/repositories/snapshots/"]
["snapshots" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]
["releases" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]
])
(require 'cemerick.pomegranate.aether)
(cemerick.pomegranate.aether/register-wagon-factory!
"http" #(org.apache.maven.wagon.providers.http.HttpWagon.))
| 87049 | (defproject incisor-cell-counter "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:jvm-opts ["-Xmx25g" "-server"]
:main incisor-cell-counter.imaris-cropped-analysis
:dependencies [[org.clojure/clojure "1.8.0"]
[fun.imagej/fun.imagej "0.2.5"]
[mosaic/MosaicSuite "1.0.8_Full"]
[org.flatland/ordered "1.5.6"]
]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["sonatype-snapshots" "https://oss.sonatype.org/content/repositories/snapshots/"]
["snapshots" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]
["releases" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_<PASSWORD>
:sign-releases false}]
])
(require 'cemerick.pomegranate.aether)
(cemerick.pomegranate.aether/register-wagon-factory!
"http" #(org.apache.maven.wagon.providers.http.HttpWagon.))
| true | (defproject incisor-cell-counter "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:jvm-opts ["-Xmx25g" "-server"]
:main incisor-cell-counter.imaris-cropped-analysis
:dependencies [[org.clojure/clojure "1.8.0"]
[fun.imagej/fun.imagej "0.2.5"]
[mosaic/MosaicSuite "1.0.8_Full"]
[org.flatland/ordered "1.5.6"]
]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["sonatype-snapshots" "https://oss.sonatype.org/content/repositories/snapshots/"]
["snapshots" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]
["releases" {:url "https://clojars.org/repo"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]
])
(require 'cemerick.pomegranate.aether)
(cemerick.pomegranate.aether/register-wagon-factory!
"http" #(org.apache.maven.wagon.providers.http.HttpWagon.))
|
[
{
"context": "rt \"5432\"\n :user \"tester\"\n :password \"test-password\"})\n\n(deftest data-source-check-fn-times-out-after",
"end": 468,
"score": 0.9993095993995667,
"start": 455,
"tag": "PASSWORD",
"value": "test-password"
}
] | check-fns/data-source/test/integration/salutem/check_fns/data_source/timeout_test.clj | logicblocks/salutem | 13 | (ns salutem.check-fns.data-source.timeout-test
(:require
[clojure.test :refer :all]
[clojure.pprint :as pp]
[next.jdbc :as jdbc]
[salutem.core :as salutem]
[salutem.check-fns.data-source.core :as scfds]
[tick.alpha.api :as time])
(:import
[com.impossibl.postgres.jdbc PGSQLSimpleException]))
(def db-spec
{:dbtype "pgsql"
:dbname "test"
:host "localhost"
:port "5432"
:user "tester"
:password "test-password"})
(deftest data-source-check-fn-times-out-after-5-seconds-by-default
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(10) AS up;"]
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 7500 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
(deftest data-source-check-fn-uses-supplied-timeout-when-specified
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(5) AS up;"]
:query-timeout
(salutem/duration 1 :seconds)
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 3000 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
| 89491 | (ns salutem.check-fns.data-source.timeout-test
(:require
[clojure.test :refer :all]
[clojure.pprint :as pp]
[next.jdbc :as jdbc]
[salutem.core :as salutem]
[salutem.check-fns.data-source.core :as scfds]
[tick.alpha.api :as time])
(:import
[com.impossibl.postgres.jdbc PGSQLSimpleException]))
(def db-spec
{:dbtype "pgsql"
:dbname "test"
:host "localhost"
:port "5432"
:user "tester"
:password "<PASSWORD>"})
(deftest data-source-check-fn-times-out-after-5-seconds-by-default
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(10) AS up;"]
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 7500 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
(deftest data-source-check-fn-uses-supplied-timeout-when-specified
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(5) AS up;"]
:query-timeout
(salutem/duration 1 :seconds)
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 3000 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
| true | (ns salutem.check-fns.data-source.timeout-test
(:require
[clojure.test :refer :all]
[clojure.pprint :as pp]
[next.jdbc :as jdbc]
[salutem.core :as salutem]
[salutem.check-fns.data-source.core :as scfds]
[tick.alpha.api :as time])
(:import
[com.impossibl.postgres.jdbc PGSQLSimpleException]))
(def db-spec
{:dbtype "pgsql"
:dbname "test"
:host "localhost"
:port "5432"
:user "tester"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(deftest data-source-check-fn-times-out-after-5-seconds-by-default
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(10) AS up;"]
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 7500 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
(deftest data-source-check-fn-uses-supplied-timeout-when-specified
(let [data-source (jdbc/get-datasource db-spec)]
(let [check-fn (scfds/data-source-check-fn data-source
{:query-sql-params
["SELECT pg_sleep(5) AS up;"]
:query-timeout
(salutem/duration 1 :seconds)
:failure-reason-fn
(fn [_ ^Exception exception]
(if (and
(isa? (class exception) PGSQLSimpleException)
(= (.getMessage exception)
"canceling statement due to user request"))
:timed-out
:threw-exception))})
context {}
result-promise (promise)
result-cb (partial deliver result-promise)]
(check-fn context result-cb)
(let [result (deref result-promise 3000 nil)]
(is (salutem/unhealthy? result))
(is (= :timed-out (:salutem/reason result)))
(is (not (nil? (:salutem/exception result))))))))
|
[
{
"context": "ge, London, All rights reserved.\n;\n; Contributors: Jony Hudson\n;\n; Released under the MIT license..\n;\n\n(ns darwi",
"end": 134,
"score": 0.9997671246528625,
"start": 123,
"tag": "NAME",
"value": "Jony Hudson"
}
] | data/test/clojure/69b670693d8f48abd97d41ffc5c6fec7985cb53dscoring.clj | harshp8l/deep-learning-lang-detection | 84 | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: Jony Hudson
;
; Released under the MIT license..
;
(ns darwin.evolution.scoring
"Functions in this namespace manage the process of scoring individuals in a population.
The actual score functions themselves are representation dependent and will be found with
the implementations of the representations.")
(defn update-individual-scores
"Update the scores for an individual. The score functions are given as a map of functions:
each function will be applied to the individual's genotype and its result stored on the individual,
under the function's key."
[score-funcs individual]
(merge individual
(into {} (map (fn [s] [(first s) ((second s) (:genotype individual))]) score-funcs))))
(defn update-scores
"Update the scores for each individual in the given list. See above for how the score functions are
specified."
[individuals score-funcs]
(doall (pmap (partial update-individual-scores score-funcs) individuals))) | 25883 | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: <NAME>
;
; Released under the MIT license..
;
(ns darwin.evolution.scoring
"Functions in this namespace manage the process of scoring individuals in a population.
The actual score functions themselves are representation dependent and will be found with
the implementations of the representations.")
(defn update-individual-scores
"Update the scores for an individual. The score functions are given as a map of functions:
each function will be applied to the individual's genotype and its result stored on the individual,
under the function's key."
[score-funcs individual]
(merge individual
(into {} (map (fn [s] [(first s) ((second s) (:genotype individual))]) score-funcs))))
(defn update-scores
"Update the scores for each individual in the given list. See above for how the score functions are
specified."
[individuals score-funcs]
(doall (pmap (partial update-individual-scores score-funcs) individuals))) | true | ;
; This file is part of darwin.
;
; Copyright (C) 2014-, Imperial College, London, All rights reserved.
;
; Contributors: PI:NAME:<NAME>END_PI
;
; Released under the MIT license..
;
(ns darwin.evolution.scoring
"Functions in this namespace manage the process of scoring individuals in a population.
The actual score functions themselves are representation dependent and will be found with
the implementations of the representations.")
(defn update-individual-scores
"Update the scores for an individual. The score functions are given as a map of functions:
each function will be applied to the individual's genotype and its result stored on the individual,
under the function's key."
[score-funcs individual]
(merge individual
(into {} (map (fn [s] [(first s) ((second s) (:genotype individual))]) score-funcs))))
(defn update-scores
"Update the scores for each individual in the given list. See above for how the score functions are
specified."
[individuals score-funcs]
(doall (pmap (partial update-individual-scores score-funcs) individuals))) |
[
{
"context": "pted Clojure code style.\n;; (https://github.com/bbatsov/clojure-style-guide)\n\n\n;; A Simple \"Function\"\n\n;;",
"end": 3585,
"score": 0.99901282787323,
"start": 3578,
"tag": "USERNAME",
"value": "bbatsov"
},
{
"context": "cises:\n\n;; EXERCISE:\n;;\n;; Define another planet `mercury`, using keywords as keys.\n;; - Ensure all key",
"end": 10066,
"score": 0.9029214382171631,
"start": 10063,
"tag": "NAME",
"value": "mer"
},
{
"context": "e the information below.\n;;\n#_(;; FIXME\n pname \"Mercury\" ; has...\n moons 0\n mass 0.0553 ; recall w",
"end": 10267,
"score": 0.9048826098442078,
"start": 10260,
"tag": "NAME",
"value": "Mercury"
},
{
"context": "ases 0.5)\n\n\n\n;; EXERCISE:\n;;\n;; Query the planet `mercury` in 3 ways:\n;; - with nested `get`\n;; - with ",
"end": 10614,
"score": 0.8422611951828003,
"start": 10611,
"tag": "NAME",
"value": "mer"
}
] | src/clojure_by_example/ex01_small_beginnings.clj | RiteekS/clojure-by-example | 0 | (ns clojure-by-example.ex01-small-beginnings)
;; Ex01: LESSON GOAL:
;;
;; - Show a way to model things with pure data, in the form of hash-maps
;; - Show how to query hash-maps
;; - Introduce the idea of a function
;; - Use the above to show how we can "do more with less"
;; Our Earth
;; "pname" "Earth"
;; "mass" 1 ; if Earth mass is 1, Jupiter's mass is 317.8 x Earth
;; "radius" 1 ; if Earth radius is 1, Jupiter's radius is 11.21 x Earth
;; "moons" 1
;; "atmosphere" "nitrogen" 78.08
;; "oxygen" 20.95
;; "CO2" 0.40
;; "water-vapour" 0.10
;; "other-gases" "argon" 0.33
;; "traces" 0.14
;; Looks like a collection of name-value pairs. To some, it will
;; look like JSON.
;;
;; This intuition is correct. We can describe the Earth by its
;; properties, written as name-value pairs or "key"-value pairs.
;; If we put curly braces in the right places, it becomes a
;; Clojure "hash-map":
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}
;; Let's query the Earth.
;; But first, let's create a global reference to our hash-map,
;; for convenience.
;; Let's call it `earth`.
(def earth
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}) ; <- evaluate this
;; To evaluate the above `def`:
;; - Place the cursor just after the closing paren `)`, and
;; - evaluate it using your editor's evaluate feature
;; (in LightTable, hit ctrl+Enter on Win/Linux, and cmd+Enter on Mac)
;; Evaluation will attach (or 'bind') the hash-map to the symbol
;; we have called `earth`.
earth ; evaluate and check the hash-map
;; _Now_ let's query the 'earth' global...
;; Top-level access:
;; Wait!
;;
;; What do you _expect_ 'get' to do, in the expression below?
;;
;; Try to predict, before you evaluate.
(get earth "pname") ; <- place cursor after closing paren and evaluate.
;; EXERCISE:
;;
;; How to get number of moons?
;; - Uncomment, and fix the expression below:
;; (get earth 'FIX)
;; EXERCISE:
;;
;; What does the atmosphere contain?
;; - Type your expression below:
;;
;; ('FIX 'FIX 'FIX)
;; Lesson:
;; - Given a hash-map and a "key", `get` returns the value
;; associated with the key.
;; - A value can be a string, or a number, or even another hash-map.
;; Nested access:
;; EXERCISE:
;;
;; Now, how to find what the other gases are, in the atmosphere?
;; - Hint: Mentally replace FIX with the value of "atmosphere".
;; - Now ask yourself, what expression will return that value?
;; (get 'FIX "other-gases")
;; EXERCISE:
;;
;; Now, try to go even deeper, to find how much argon we have?
;; - Hint: now you have to replace 'FIX with a nested expression
;;
;; (get 'FIX "argon")
;; Lesson:
;; - You can put s-expressions inside s-expressions and evaluate the
;; whole thing as one s-expression.
;; Notes:
;; - You may choose to indent a deeply nested s-expression, for clarity.
;; - For now, indent or don't indent, as per your comfort level.
;; - Later, learn about generally-accepted Clojure code style.
;; (https://github.com/bbatsov/clojure-style-guide)
;; A Simple "Function"
;; Let's make our own function to access any "third" level value...
(defn get-level-3 ; function name
[planet level1-key level2-key level3-key] ; arguments list
;; function "body":
(get (get (get planet level1-key)
level2-key)
level3-key)) ; What does the function's "body" look like?
;; Now we can...
(get-level-3 earth "atmosphere" "other-gases" "argon")
(get-level-3 earth "atmosphere" "other-gases" "traces")
;; Keywords as Keys of Hash-maps
;; Hash-maps so widely-used, and can so conveniently represent things,
;; that Clojure provides a far more convenient way to define hash-maps
;; and query them.
;; Instead of plain old strings as keys, we can use
;; Clojure "keywords" as keys.
"moons" ; a string
:moons ; a keyword
;; Like strings and numbers, keywords directly "represent" themselves.
;; (A keyword is a fundamental data type.)
;; _Unlike_ strings, keywords are designed to do special things.
;; To find out, we must first define an alternative hash-map,
;; - that represents the same data about the Earth,
;; - but with keywords as keys, instead of strings
;; - to let us super-easily query the hash-map, using just keywords
(def earth-alt {:pname "Earth"
:mass 1
:radius 1
:moons 1
:atmosphere {:nitrogen 78.08
:oxygen 20.95
:CO2 0.4
:water-vapour 0.10
:other-gases {:argon 0.33
:traces 0.14}}})
;; Easier top-level access
;; EXERCISE:
;;
;; What will these return?
(:pname earth-alt)
(:mass earth-alt)
;; EXERCISE:
;;
;; How to find the atmosphere? Uncomment,fix, and evaluate:
;; ('FIX earth-alt)
;; EXERCISE:
;;
;; What are the other gases, in the atmosphere?
;; - Hint: Remember, we can nest s-expressions inside s-expressions.
;; - Replace each 'FIX with the appropriate value or s-expression.
;;
;; ('FIX 'FIX)
;; EXERCISE:
;;
;; How much argon is present in the atmosphere?
;; Hint: once again, 'FIX with value(s) or nested s-expression(s).
;; ('FIX 'FIX)
;; Clojure provides `get-in`, because nested access is so common.
;; - `get-in` is the cousin of `get` (and the granddaddy of our
;; get-level-3 function!)
;; Try evaluating each one of these...
(get-in earth-alt [:atmosphere])
(get-in earth-alt [:atmosphere :other-gases])
(get-in earth-alt [:atmosphere :other-gases :argon])
;; '--> imagine this as a "path" to the value
;; By the way, the function we defined earlier, is general enough
;; to work with keywords too!
(get-level-3 earth-alt :atmosphere :other-gases :argon)
;; EXERCISE:
;;
;; We saw `get-in` work for keywords. Does it work for strings too?
;; Uncomment, fix, and evaluate:
;; (get-in earth 'FIX)
;; Did that work? Why or why not?
;; EXERCISE:
;;
;; Use get-in to query other gases from the `earth` hash-map.
;; Type your expression below and evaluate it:
;; EXERCISE:
;;
;; Use get-in to query argon from `earth`'s atmosphere
;; Type your expression below and evaluate it:
;; Lesson:
;; - Given a hash-map and a path "key", `get` returns the value
;; associated with the key.
;; Clojure "Vectors":
;; The square bracketed things we used with `get-in` are in fact a
;; Clojure datastructure. (Other languages may call these "Arrays".)
["atmosphere"] ; is a vector of one string
[:atmosphere :other-gases] ; is a vector of two keywords
;; These are `indexed` collections, i.e. we can query a value in
;; a Vector, if we know what "index" position it occupies in the vector.
;; EXERCISE:
;;
;; What will this return?
(get [:foo :bar :baz] 0)
;; Note: We count position starting at `0`, not `1`, in Clojure
;; EXERCISE:
;;
;; What will this return?
(get-in [:foo [:bar :baz]] [1 1])
;; But we are actually just trying to find the "nth" item,
;; and Clojure gives us...
(nth [:foo :bar :baz] 0)
(nth (nth [:foo [:bar :baz]] 1)
1)
;; Lesson:
;; - `get` and `get-in` are general enough to query Vectors too,
;; using index number.
;; - but we'd rather just look up the `nth` item in Vectors
;; Basic Data Modeling:
;; We rarely use vectors to model objects like the Earth.
;; In Clojure, a hash-map is almost always the best way to model
;; an object that we need to query.
;;
;; But why?
;; What if we model the earth as a vector, instead of a hash-map?
(def earth-as-a-vector
"Docstring: This vector represents Earth this way:
[Name, Radius, Mass, Moons]"
["Earth" 1 1 1])
;; Now, how do we query Earth?
(defn get-earth-name [] ; empty vector means zero arguments
(nth earth-as-a-vector 0))
(get-earth-name) ; call with zero arguments
(defn get-earth-radius []
(nth earth-as-a-vector 1))
(get-earth-radius)
(defn get-earth-moons []
(nth earth-as-a-vector 2)) ; Uh, was it 2 or 3?
(get-earth-moons) ; did this return Mass, or Moons?
(:moons earth-alt) ; compare: how obviously we can query :moons in earth-alt
;; Further, our custom "getter" functions for Earth's properties,
;; are practically useless for other planets we may wish to also define
;; as vectors.
;;
;; Why?
;;
;; Property positions for other planets may differ from earth.
;; And in vector look-up, position matters.
;;
;; Said another way: "Positional semantics do not scale"
;;
;; Consider the function below:
;;
(defn get-planet-prop
"A function with a dangerous, brittle assumption about
planetary properties."
[planet-as-vector prop-position]
(nth planet-as-vector
prop-position))
;; Lesson: Doing More With Less:
;; Clojure programmers rely on the power, and general-purpose
;; flexibility of hash-maps, as well as general-purpose functions,
;; to avoid getting stuck in such situations.
;; While nobody stops us from doing so, using vectors to model an object
;; (like the Earth) is clearly awkward.
;; - We must maintain label/name information about values separately
;; (perhaps in the docstring)
;; - Our custom `get-xyz` functions are also far too "specialized",
;; i.e. we can only sensibly use them to query _only_ the earth.
;; - And it opens us up to a whole host of errors:
;; - we can easily lose track of what value represents what property
;; - what if someone decides to add the number of man-made satellites
;; between mass and moon?
;; Lesson-end Exercises:
;; EXERCISE:
;;
;; Define another planet `mercury`, using keywords as keys.
;; - Ensure all keys are keywords
;; - Ensure braces {} are in the right places, to nest data correctly.
;;
;; Use the information below.
;;
#_(;; FIXME
pname "Mercury" ; has...
moons 0
mass 0.0553 ; recall we assume Earth mass is 1
radius 0.383 ; recall we assume Earth radius is 1
atmosphere ; % of total volume
oxygen 42.0
sodium 29.0
hydrogen 22.0
helium 6.0
potassium 0.5
other-gases 0.5)
;; EXERCISE:
;;
;; Query the planet `mercury` in 3 ways:
;; - with nested `get`
;; - with get-in
;; - with keywords
;; Type your solutions below:
;; EXERCISE:
;;
;; Write a custom function to do a two-level deep query on `mercury`.
;; - It should be able to query earth, and earth-alt as well.
;; - name it `get-level-2`
;;
;; Fix the function below:
#_(defn get-level-2
['FIX ...]
'FIX)
;; Uncomment and evaluate to check you get the correct values
#_(get-level-2 earth "atmosphere" "oxygen")
#_(get-level-2 earth-alt :atmosphere :oxygen)
#_(get-level-2 mercury :atmosphere :oxygen)
;; RECAP:
;;
;; - hash-maps let us conveniently represent objects we wish to
;; model and query
;; - We can query hash-maps variously with keywords, `get`, and `get-in`
;; - If we use keywords as keys in hash-maps, querying is dead-simple
;; - We can define our own functions with `defn`, using this syntax:
;;
;; (defn function-name
;; [arg1 arg2 arg3 ... argN]
;; (body of the function))
;;
;; - Using general-purpose data structures, and writing general-purpose
;; functions lets us do more with less
| 3160 | (ns clojure-by-example.ex01-small-beginnings)
;; Ex01: LESSON GOAL:
;;
;; - Show a way to model things with pure data, in the form of hash-maps
;; - Show how to query hash-maps
;; - Introduce the idea of a function
;; - Use the above to show how we can "do more with less"
;; Our Earth
;; "pname" "Earth"
;; "mass" 1 ; if Earth mass is 1, Jupiter's mass is 317.8 x Earth
;; "radius" 1 ; if Earth radius is 1, Jupiter's radius is 11.21 x Earth
;; "moons" 1
;; "atmosphere" "nitrogen" 78.08
;; "oxygen" 20.95
;; "CO2" 0.40
;; "water-vapour" 0.10
;; "other-gases" "argon" 0.33
;; "traces" 0.14
;; Looks like a collection of name-value pairs. To some, it will
;; look like JSON.
;;
;; This intuition is correct. We can describe the Earth by its
;; properties, written as name-value pairs or "key"-value pairs.
;; If we put curly braces in the right places, it becomes a
;; Clojure "hash-map":
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}
;; Let's query the Earth.
;; But first, let's create a global reference to our hash-map,
;; for convenience.
;; Let's call it `earth`.
(def earth
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}) ; <- evaluate this
;; To evaluate the above `def`:
;; - Place the cursor just after the closing paren `)`, and
;; - evaluate it using your editor's evaluate feature
;; (in LightTable, hit ctrl+Enter on Win/Linux, and cmd+Enter on Mac)
;; Evaluation will attach (or 'bind') the hash-map to the symbol
;; we have called `earth`.
earth ; evaluate and check the hash-map
;; _Now_ let's query the 'earth' global...
;; Top-level access:
;; Wait!
;;
;; What do you _expect_ 'get' to do, in the expression below?
;;
;; Try to predict, before you evaluate.
(get earth "pname") ; <- place cursor after closing paren and evaluate.
;; EXERCISE:
;;
;; How to get number of moons?
;; - Uncomment, and fix the expression below:
;; (get earth 'FIX)
;; EXERCISE:
;;
;; What does the atmosphere contain?
;; - Type your expression below:
;;
;; ('FIX 'FIX 'FIX)
;; Lesson:
;; - Given a hash-map and a "key", `get` returns the value
;; associated with the key.
;; - A value can be a string, or a number, or even another hash-map.
;; Nested access:
;; EXERCISE:
;;
;; Now, how to find what the other gases are, in the atmosphere?
;; - Hint: Mentally replace FIX with the value of "atmosphere".
;; - Now ask yourself, what expression will return that value?
;; (get 'FIX "other-gases")
;; EXERCISE:
;;
;; Now, try to go even deeper, to find how much argon we have?
;; - Hint: now you have to replace 'FIX with a nested expression
;;
;; (get 'FIX "argon")
;; Lesson:
;; - You can put s-expressions inside s-expressions and evaluate the
;; whole thing as one s-expression.
;; Notes:
;; - You may choose to indent a deeply nested s-expression, for clarity.
;; - For now, indent or don't indent, as per your comfort level.
;; - Later, learn about generally-accepted Clojure code style.
;; (https://github.com/bbatsov/clojure-style-guide)
;; A Simple "Function"
;; Let's make our own function to access any "third" level value...
(defn get-level-3 ; function name
[planet level1-key level2-key level3-key] ; arguments list
;; function "body":
(get (get (get planet level1-key)
level2-key)
level3-key)) ; What does the function's "body" look like?
;; Now we can...
(get-level-3 earth "atmosphere" "other-gases" "argon")
(get-level-3 earth "atmosphere" "other-gases" "traces")
;; Keywords as Keys of Hash-maps
;; Hash-maps so widely-used, and can so conveniently represent things,
;; that Clojure provides a far more convenient way to define hash-maps
;; and query them.
;; Instead of plain old strings as keys, we can use
;; Clojure "keywords" as keys.
"moons" ; a string
:moons ; a keyword
;; Like strings and numbers, keywords directly "represent" themselves.
;; (A keyword is a fundamental data type.)
;; _Unlike_ strings, keywords are designed to do special things.
;; To find out, we must first define an alternative hash-map,
;; - that represents the same data about the Earth,
;; - but with keywords as keys, instead of strings
;; - to let us super-easily query the hash-map, using just keywords
(def earth-alt {:pname "Earth"
:mass 1
:radius 1
:moons 1
:atmosphere {:nitrogen 78.08
:oxygen 20.95
:CO2 0.4
:water-vapour 0.10
:other-gases {:argon 0.33
:traces 0.14}}})
;; Easier top-level access
;; EXERCISE:
;;
;; What will these return?
(:pname earth-alt)
(:mass earth-alt)
;; EXERCISE:
;;
;; How to find the atmosphere? Uncomment,fix, and evaluate:
;; ('FIX earth-alt)
;; EXERCISE:
;;
;; What are the other gases, in the atmosphere?
;; - Hint: Remember, we can nest s-expressions inside s-expressions.
;; - Replace each 'FIX with the appropriate value or s-expression.
;;
;; ('FIX 'FIX)
;; EXERCISE:
;;
;; How much argon is present in the atmosphere?
;; Hint: once again, 'FIX with value(s) or nested s-expression(s).
;; ('FIX 'FIX)
;; Clojure provides `get-in`, because nested access is so common.
;; - `get-in` is the cousin of `get` (and the granddaddy of our
;; get-level-3 function!)
;; Try evaluating each one of these...
(get-in earth-alt [:atmosphere])
(get-in earth-alt [:atmosphere :other-gases])
(get-in earth-alt [:atmosphere :other-gases :argon])
;; '--> imagine this as a "path" to the value
;; By the way, the function we defined earlier, is general enough
;; to work with keywords too!
(get-level-3 earth-alt :atmosphere :other-gases :argon)
;; EXERCISE:
;;
;; We saw `get-in` work for keywords. Does it work for strings too?
;; Uncomment, fix, and evaluate:
;; (get-in earth 'FIX)
;; Did that work? Why or why not?
;; EXERCISE:
;;
;; Use get-in to query other gases from the `earth` hash-map.
;; Type your expression below and evaluate it:
;; EXERCISE:
;;
;; Use get-in to query argon from `earth`'s atmosphere
;; Type your expression below and evaluate it:
;; Lesson:
;; - Given a hash-map and a path "key", `get` returns the value
;; associated with the key.
;; Clojure "Vectors":
;; The square bracketed things we used with `get-in` are in fact a
;; Clojure datastructure. (Other languages may call these "Arrays".)
["atmosphere"] ; is a vector of one string
[:atmosphere :other-gases] ; is a vector of two keywords
;; These are `indexed` collections, i.e. we can query a value in
;; a Vector, if we know what "index" position it occupies in the vector.
;; EXERCISE:
;;
;; What will this return?
(get [:foo :bar :baz] 0)
;; Note: We count position starting at `0`, not `1`, in Clojure
;; EXERCISE:
;;
;; What will this return?
(get-in [:foo [:bar :baz]] [1 1])
;; But we are actually just trying to find the "nth" item,
;; and Clojure gives us...
(nth [:foo :bar :baz] 0)
(nth (nth [:foo [:bar :baz]] 1)
1)
;; Lesson:
;; - `get` and `get-in` are general enough to query Vectors too,
;; using index number.
;; - but we'd rather just look up the `nth` item in Vectors
;; Basic Data Modeling:
;; We rarely use vectors to model objects like the Earth.
;; In Clojure, a hash-map is almost always the best way to model
;; an object that we need to query.
;;
;; But why?
;; What if we model the earth as a vector, instead of a hash-map?
(def earth-as-a-vector
"Docstring: This vector represents Earth this way:
[Name, Radius, Mass, Moons]"
["Earth" 1 1 1])
;; Now, how do we query Earth?
(defn get-earth-name [] ; empty vector means zero arguments
(nth earth-as-a-vector 0))
(get-earth-name) ; call with zero arguments
(defn get-earth-radius []
(nth earth-as-a-vector 1))
(get-earth-radius)
(defn get-earth-moons []
(nth earth-as-a-vector 2)) ; Uh, was it 2 or 3?
(get-earth-moons) ; did this return Mass, or Moons?
(:moons earth-alt) ; compare: how obviously we can query :moons in earth-alt
;; Further, our custom "getter" functions for Earth's properties,
;; are practically useless for other planets we may wish to also define
;; as vectors.
;;
;; Why?
;;
;; Property positions for other planets may differ from earth.
;; And in vector look-up, position matters.
;;
;; Said another way: "Positional semantics do not scale"
;;
;; Consider the function below:
;;
(defn get-planet-prop
"A function with a dangerous, brittle assumption about
planetary properties."
[planet-as-vector prop-position]
(nth planet-as-vector
prop-position))
;; Lesson: Doing More With Less:
;; Clojure programmers rely on the power, and general-purpose
;; flexibility of hash-maps, as well as general-purpose functions,
;; to avoid getting stuck in such situations.
;; While nobody stops us from doing so, using vectors to model an object
;; (like the Earth) is clearly awkward.
;; - We must maintain label/name information about values separately
;; (perhaps in the docstring)
;; - Our custom `get-xyz` functions are also far too "specialized",
;; i.e. we can only sensibly use them to query _only_ the earth.
;; - And it opens us up to a whole host of errors:
;; - we can easily lose track of what value represents what property
;; - what if someone decides to add the number of man-made satellites
;; between mass and moon?
;; Lesson-end Exercises:
;; EXERCISE:
;;
;; Define another planet `<NAME>cury`, using keywords as keys.
;; - Ensure all keys are keywords
;; - Ensure braces {} are in the right places, to nest data correctly.
;;
;; Use the information below.
;;
#_(;; FIXME
pname "<NAME>" ; has...
moons 0
mass 0.0553 ; recall we assume Earth mass is 1
radius 0.383 ; recall we assume Earth radius is 1
atmosphere ; % of total volume
oxygen 42.0
sodium 29.0
hydrogen 22.0
helium 6.0
potassium 0.5
other-gases 0.5)
;; EXERCISE:
;;
;; Query the planet `<NAME>cury` in 3 ways:
;; - with nested `get`
;; - with get-in
;; - with keywords
;; Type your solutions below:
;; EXERCISE:
;;
;; Write a custom function to do a two-level deep query on `mercury`.
;; - It should be able to query earth, and earth-alt as well.
;; - name it `get-level-2`
;;
;; Fix the function below:
#_(defn get-level-2
['FIX ...]
'FIX)
;; Uncomment and evaluate to check you get the correct values
#_(get-level-2 earth "atmosphere" "oxygen")
#_(get-level-2 earth-alt :atmosphere :oxygen)
#_(get-level-2 mercury :atmosphere :oxygen)
;; RECAP:
;;
;; - hash-maps let us conveniently represent objects we wish to
;; model and query
;; - We can query hash-maps variously with keywords, `get`, and `get-in`
;; - If we use keywords as keys in hash-maps, querying is dead-simple
;; - We can define our own functions with `defn`, using this syntax:
;;
;; (defn function-name
;; [arg1 arg2 arg3 ... argN]
;; (body of the function))
;;
;; - Using general-purpose data structures, and writing general-purpose
;; functions lets us do more with less
| true | (ns clojure-by-example.ex01-small-beginnings)
;; Ex01: LESSON GOAL:
;;
;; - Show a way to model things with pure data, in the form of hash-maps
;; - Show how to query hash-maps
;; - Introduce the idea of a function
;; - Use the above to show how we can "do more with less"
;; Our Earth
;; "pname" "Earth"
;; "mass" 1 ; if Earth mass is 1, Jupiter's mass is 317.8 x Earth
;; "radius" 1 ; if Earth radius is 1, Jupiter's radius is 11.21 x Earth
;; "moons" 1
;; "atmosphere" "nitrogen" 78.08
;; "oxygen" 20.95
;; "CO2" 0.40
;; "water-vapour" 0.10
;; "other-gases" "argon" 0.33
;; "traces" 0.14
;; Looks like a collection of name-value pairs. To some, it will
;; look like JSON.
;;
;; This intuition is correct. We can describe the Earth by its
;; properties, written as name-value pairs or "key"-value pairs.
;; If we put curly braces in the right places, it becomes a
;; Clojure "hash-map":
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}
;; Let's query the Earth.
;; But first, let's create a global reference to our hash-map,
;; for convenience.
;; Let's call it `earth`.
(def earth
{"pname" "Earth"
"mass" 1
"radius" 1
"moons" 1
"atmosphere" {"nitrogen" 78.08
"oxygen" 20.95
"CO2" 0.40
"water-vapour" 0.10
"other-gases" {"argon" 0.33
"traces" 0.14}}}) ; <- evaluate this
;; To evaluate the above `def`:
;; - Place the cursor just after the closing paren `)`, and
;; - evaluate it using your editor's evaluate feature
;; (in LightTable, hit ctrl+Enter on Win/Linux, and cmd+Enter on Mac)
;; Evaluation will attach (or 'bind') the hash-map to the symbol
;; we have called `earth`.
earth ; evaluate and check the hash-map
;; _Now_ let's query the 'earth' global...
;; Top-level access:
;; Wait!
;;
;; What do you _expect_ 'get' to do, in the expression below?
;;
;; Try to predict, before you evaluate.
(get earth "pname") ; <- place cursor after closing paren and evaluate.
;; EXERCISE:
;;
;; How to get number of moons?
;; - Uncomment, and fix the expression below:
;; (get earth 'FIX)
;; EXERCISE:
;;
;; What does the atmosphere contain?
;; - Type your expression below:
;;
;; ('FIX 'FIX 'FIX)
;; Lesson:
;; - Given a hash-map and a "key", `get` returns the value
;; associated with the key.
;; - A value can be a string, or a number, or even another hash-map.
;; Nested access:
;; EXERCISE:
;;
;; Now, how to find what the other gases are, in the atmosphere?
;; - Hint: Mentally replace FIX with the value of "atmosphere".
;; - Now ask yourself, what expression will return that value?
;; (get 'FIX "other-gases")
;; EXERCISE:
;;
;; Now, try to go even deeper, to find how much argon we have?
;; - Hint: now you have to replace 'FIX with a nested expression
;;
;; (get 'FIX "argon")
;; Lesson:
;; - You can put s-expressions inside s-expressions and evaluate the
;; whole thing as one s-expression.
;; Notes:
;; - You may choose to indent a deeply nested s-expression, for clarity.
;; - For now, indent or don't indent, as per your comfort level.
;; - Later, learn about generally-accepted Clojure code style.
;; (https://github.com/bbatsov/clojure-style-guide)
;; A Simple "Function"
;; Let's make our own function to access any "third" level value...
(defn get-level-3 ; function name
[planet level1-key level2-key level3-key] ; arguments list
;; function "body":
(get (get (get planet level1-key)
level2-key)
level3-key)) ; What does the function's "body" look like?
;; Now we can...
(get-level-3 earth "atmosphere" "other-gases" "argon")
(get-level-3 earth "atmosphere" "other-gases" "traces")
;; Keywords as Keys of Hash-maps
;; Hash-maps so widely-used, and can so conveniently represent things,
;; that Clojure provides a far more convenient way to define hash-maps
;; and query them.
;; Instead of plain old strings as keys, we can use
;; Clojure "keywords" as keys.
"moons" ; a string
:moons ; a keyword
;; Like strings and numbers, keywords directly "represent" themselves.
;; (A keyword is a fundamental data type.)
;; _Unlike_ strings, keywords are designed to do special things.
;; To find out, we must first define an alternative hash-map,
;; - that represents the same data about the Earth,
;; - but with keywords as keys, instead of strings
;; - to let us super-easily query the hash-map, using just keywords
(def earth-alt {:pname "Earth"
:mass 1
:radius 1
:moons 1
:atmosphere {:nitrogen 78.08
:oxygen 20.95
:CO2 0.4
:water-vapour 0.10
:other-gases {:argon 0.33
:traces 0.14}}})
;; Easier top-level access
;; EXERCISE:
;;
;; What will these return?
(:pname earth-alt)
(:mass earth-alt)
;; EXERCISE:
;;
;; How to find the atmosphere? Uncomment,fix, and evaluate:
;; ('FIX earth-alt)
;; EXERCISE:
;;
;; What are the other gases, in the atmosphere?
;; - Hint: Remember, we can nest s-expressions inside s-expressions.
;; - Replace each 'FIX with the appropriate value or s-expression.
;;
;; ('FIX 'FIX)
;; EXERCISE:
;;
;; How much argon is present in the atmosphere?
;; Hint: once again, 'FIX with value(s) or nested s-expression(s).
;; ('FIX 'FIX)
;; Clojure provides `get-in`, because nested access is so common.
;; - `get-in` is the cousin of `get` (and the granddaddy of our
;; get-level-3 function!)
;; Try evaluating each one of these...
(get-in earth-alt [:atmosphere])
(get-in earth-alt [:atmosphere :other-gases])
(get-in earth-alt [:atmosphere :other-gases :argon])
;; '--> imagine this as a "path" to the value
;; By the way, the function we defined earlier, is general enough
;; to work with keywords too!
(get-level-3 earth-alt :atmosphere :other-gases :argon)
;; EXERCISE:
;;
;; We saw `get-in` work for keywords. Does it work for strings too?
;; Uncomment, fix, and evaluate:
;; (get-in earth 'FIX)
;; Did that work? Why or why not?
;; EXERCISE:
;;
;; Use get-in to query other gases from the `earth` hash-map.
;; Type your expression below and evaluate it:
;; EXERCISE:
;;
;; Use get-in to query argon from `earth`'s atmosphere
;; Type your expression below and evaluate it:
;; Lesson:
;; - Given a hash-map and a path "key", `get` returns the value
;; associated with the key.
;; Clojure "Vectors":
;; The square bracketed things we used with `get-in` are in fact a
;; Clojure datastructure. (Other languages may call these "Arrays".)
["atmosphere"] ; is a vector of one string
[:atmosphere :other-gases] ; is a vector of two keywords
;; These are `indexed` collections, i.e. we can query a value in
;; a Vector, if we know what "index" position it occupies in the vector.
;; EXERCISE:
;;
;; What will this return?
(get [:foo :bar :baz] 0)
;; Note: We count position starting at `0`, not `1`, in Clojure
;; EXERCISE:
;;
;; What will this return?
(get-in [:foo [:bar :baz]] [1 1])
;; But we are actually just trying to find the "nth" item,
;; and Clojure gives us...
(nth [:foo :bar :baz] 0)
(nth (nth [:foo [:bar :baz]] 1)
1)
;; Lesson:
;; - `get` and `get-in` are general enough to query Vectors too,
;; using index number.
;; - but we'd rather just look up the `nth` item in Vectors
;; Basic Data Modeling:
;; We rarely use vectors to model objects like the Earth.
;; In Clojure, a hash-map is almost always the best way to model
;; an object that we need to query.
;;
;; But why?
;; What if we model the earth as a vector, instead of a hash-map?
(def earth-as-a-vector
"Docstring: This vector represents Earth this way:
[Name, Radius, Mass, Moons]"
["Earth" 1 1 1])
;; Now, how do we query Earth?
(defn get-earth-name [] ; empty vector means zero arguments
(nth earth-as-a-vector 0))
(get-earth-name) ; call with zero arguments
(defn get-earth-radius []
(nth earth-as-a-vector 1))
(get-earth-radius)
(defn get-earth-moons []
(nth earth-as-a-vector 2)) ; Uh, was it 2 or 3?
(get-earth-moons) ; did this return Mass, or Moons?
(:moons earth-alt) ; compare: how obviously we can query :moons in earth-alt
;; Further, our custom "getter" functions for Earth's properties,
;; are practically useless for other planets we may wish to also define
;; as vectors.
;;
;; Why?
;;
;; Property positions for other planets may differ from earth.
;; And in vector look-up, position matters.
;;
;; Said another way: "Positional semantics do not scale"
;;
;; Consider the function below:
;;
(defn get-planet-prop
"A function with a dangerous, brittle assumption about
planetary properties."
[planet-as-vector prop-position]
(nth planet-as-vector
prop-position))
;; Lesson: Doing More With Less:
;; Clojure programmers rely on the power, and general-purpose
;; flexibility of hash-maps, as well as general-purpose functions,
;; to avoid getting stuck in such situations.
;; While nobody stops us from doing so, using vectors to model an object
;; (like the Earth) is clearly awkward.
;; - We must maintain label/name information about values separately
;; (perhaps in the docstring)
;; - Our custom `get-xyz` functions are also far too "specialized",
;; i.e. we can only sensibly use them to query _only_ the earth.
;; - And it opens us up to a whole host of errors:
;; - we can easily lose track of what value represents what property
;; - what if someone decides to add the number of man-made satellites
;; between mass and moon?
;; Lesson-end Exercises:
;; EXERCISE:
;;
;; Define another planet `PI:NAME:<NAME>END_PIcury`, using keywords as keys.
;; - Ensure all keys are keywords
;; - Ensure braces {} are in the right places, to nest data correctly.
;;
;; Use the information below.
;;
#_(;; FIXME
pname "PI:NAME:<NAME>END_PI" ; has...
moons 0
mass 0.0553 ; recall we assume Earth mass is 1
radius 0.383 ; recall we assume Earth radius is 1
atmosphere ; % of total volume
oxygen 42.0
sodium 29.0
hydrogen 22.0
helium 6.0
potassium 0.5
other-gases 0.5)
;; EXERCISE:
;;
;; Query the planet `PI:NAME:<NAME>END_PIcury` in 3 ways:
;; - with nested `get`
;; - with get-in
;; - with keywords
;; Type your solutions below:
;; EXERCISE:
;;
;; Write a custom function to do a two-level deep query on `mercury`.
;; - It should be able to query earth, and earth-alt as well.
;; - name it `get-level-2`
;;
;; Fix the function below:
#_(defn get-level-2
['FIX ...]
'FIX)
;; Uncomment and evaluate to check you get the correct values
#_(get-level-2 earth "atmosphere" "oxygen")
#_(get-level-2 earth-alt :atmosphere :oxygen)
#_(get-level-2 mercury :atmosphere :oxygen)
;; RECAP:
;;
;; - hash-maps let us conveniently represent objects we wish to
;; model and query
;; - We can query hash-maps variously with keywords, `get`, and `get-in`
;; - If we use keywords as keys in hash-maps, querying is dead-simple
;; - We can define our own functions with `defn`, using this syntax:
;;
;; (defn function-name
;; [arg1 arg2 arg3 ... argN]
;; (body of the function))
;;
;; - Using general-purpose data structures, and writing general-purpose
;; functions lets us do more with less
|
[
{
"context": "\n [:section\n [:a.button.reply {:href \"mailto:support@criipto.com\"}\n [:span \"Reply\"]\n [:div.icon.reply]]]])",
"end": 4718,
"score": 0.9999096989631653,
"start": 4699,
"tag": "EMAIL",
"value": "support@criipto.com"
},
{
"context": " [:<>\n [:div [:a {:href \"mailto:support@criipto.com\"} \"support@criipto.com\"]]\n [:div [:",
"end": 5387,
"score": 0.999908447265625,
"start": 5368,
"tag": "EMAIL",
"value": "support@criipto.com"
},
{
"context": " [:div [:a {:href \"mailto:support@criipto.com\"} \"support@criipto.com\"]]\n [:div [:a {:href \"https://criip",
"end": 5410,
"score": 0.9998964667320251,
"start": 5391,
"tag": "EMAIL",
"value": "support@criipto.com"
}
] | Bank/Cljs-re-frame/src/cljs_re_frame/views.cljs | criipto/samples | 0 | (ns cljs-re-frame.views
(:require [Authentication.authentication :as auth]
[cljs-re-frame.events :as events]
[cljs-re-frame.subs :as subs]
[clojure.string :as str]
[markdown-to-hiccup.core :as markdown]
[re-frame.core :as rf]))
(defn print-date [^js/Date d]
(str (.getDate d) "/"
(.getMonth d) "/"
(.getFullYear d)))
(def nav-items
(->> [{:id :overview
:icon "lamp"
:text "Overview"}
{:id :accounts
:icon "coins"
:text "Accounts"}
{:id :payments-and-transfer
:icon "arrows"
:text "Payments & Transfer"}
{:id :investment
:icon "chart"
:text "Investment"}
{:id :pension-and-insurance
:icon "wineglass"
:text "Pension & Insurance"}
{:id :messages
:icon "envelope"
:text "Messages"}
{:id :profile
:icon "profile"
:text "Profile"}
{:id :developer-support
:icon "code"
:text "Developer Support"}]
(map (juxt :id identity))
(into {})))
(defn create-columns [attributes & columns]
[:div.columns.account attributes
[:<>
(for [{:keys [content attrs]} columns]
[:div.column.is-4 (update attrs :key (fnil identity (random-uuid)))
content])]])
(defn log-in-button []
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))
button-style {:background-color "transparent"
:border-style "none"
:font-size "18px"}
log-in-fn auth/login
log-off-fn #(rf/dispatch [::events/logout])
button (fn [text on-click-fn]
[:a.button {:style button-style
:on-click on-click-fn}
[:span.navbar-item text]
[:div.icon.power-off-white]])]
[:div.buttons
(if (nil? auth-user-info)
[button "Log on" log-in-fn]
[button "Log off" log-off-fn])]))
(defn page-content [& {:keys [title page-type content]}]
[:div.card {:style {:box-shadow "none"
:background-color "white"}}
[:div.card-content
[:article.media
[:div.media-left
[:figure.image {:class (str "is-32x32 icon " (:icon (nav-items page-type)))}]]]
[:div.content
[:h1.title (or title (:text (nav-items page-type)))]
[content]]]])
(defn profile []
(let [auth-error (deref (rf/subscribe [::subs/auth-error]))
auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:page-type :profile
:content (fn []
[:<>
(when auth-user-info
[:<>
(for [[k v] auth-user-info]
(create-columns {:key (str "auth-user-info-" (name k))}
{:content (str/capitalize (name k))} {:content v}))
[:button.button.is-danger {:on-click (fn [_] (rf/dispatch [::events/logout]))}
"Log off"]])
(when auth-error
[:p (str "auth error: " auth-error)])])]))
(defn accounts-view []
(let [accounts (deref (rf/subscribe [::subs/accounts]))]
[:<>
[create-columns {:class "header"}
{:content "Name"}
{:content "Balance"}
{:content "Recent Transactions"}]
(for [{:keys [account-name id balance last-transaction-date]} accounts]
[create-columns {:key id}
{:content account-name}
{:content balance}
{:content (print-date last-transaction-date)}])]))
(defn accounts []
[page-content
:page-type :accounts
:content (fn [] [accounts-view])])
(defn payments-and-transfer []
[page-content
:page-type :payments-and-transfer
:content (fn [] [:div])])
(defn investment []
[page-content
:page-type :investment
:content (fn [] [:div])])
(defn pension-and-insurance []
[page-content
:page-type :pension-and-insurance
:content (fn [] [:div])])
(defn message-view [{:keys [index from title content date read? id unfolded?]}]
[:article.accordion.message-item (when unfolded? {:class "is-active"})
[:div.accordion-header.message-item.toggle
{:class (str "message-item-" index)
:on-click #(rf/dispatch [::events/toggle-message id])}
[:div.message-item.from
(when (not read?)
[:div.icon.dot {:style {:margin-right "12px"}}])
[:span (str from " " date)]]
[:span.message-item.subject title]]
[:div.accordion-body
[:div.accordion-content.message-item
[:div (->> content
markdown/md->hiccup
markdown/component)]]]
[:section
[:a.button.reply {:href "mailto:support@criipto.com"}
[:span "Reply"]
[:div.icon.reply]]]])
(defn messages []
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1)))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))])
(defn developer-support []
[page-content
:page-type :developer-support
:content (fn []
[:<>
[:div [:a {:href "mailto:support@criipto.com"} "support@criipto.com"]]
[:div [:a {:href "https://criipto.slack.com/"} "Slack"]]])])
(def front-page-icons
[{:icon "apartment"
:text "Housing"}
{:icon "car"
:text "Cars"}
{:icon "chart"
:text "Investment"}
{:icon "wineglass"
:text "Pension"}
{:icon "hand-holding-medical"
:text "Insurance"}
{:icon "credit-card"
:text "Cards"}
{:icon "coins"
:text "Loans"}
{:icon "cardboard-box"
:text "More products"}])
(def tiles-content
[{:title "Easy digital signing of sensitive documents"
:text "Criipto provides Criipto Bank’s secure and user-friendly signing solution so you can sign securely - on your computer and on the go."
:icon "signature"}
{:title "Easy login to Criipto Bank"
:text "Criipto Bank is using Criipto's easy and secure login solution. It saves us a lot of money that we can spend on better service for you!'"
:icon "power-off"}
{:title "MitID has arrived - We have you covered"
:text "Don’t worry. We have your back. With Criipto’s easy e-ID login solution we provide MitID and NemID login side-by-side."
:icon "mitid"}])
(defn front-page []
[:div.columns
[:div.column.is-2]
[:div.column.is-8
[:div.tile.is-ancestor.splash-menu
[:div.tile.is-parent
(for [{:keys [text icon]} front-page-icons]
[:div.tile.is-child {:key (str "front-page-" text "-" icon)}
[:div.menu-icon.icon {:class icon}]
[:div.menu-name text]])]]
[:div.tile.is-ancestor
[:div.tile.is-parent
[:div.tile.is-child.box.banner
[:div.banner.overlay]
[:div.banner-content
[:h2.subtitle.banner "BUSINESS TO BUSINESS"]
[:h1.title.banner "“We save 120 dev hours a year with Criipto’s e-ID login”"]]]]]
[:div.tile.is-ancestor
[:div.tile.is-parent
(for [{:keys [title text icon]} tiles-content]
[:div.tile.is-child.box.splash-item {:key (str "front-page-" icon)}
[:div.icon.is-40h.splash-item {:class icon}]
[:h1.title.splash-item title]
[:div.content.splash-item text]])]]]])
(defn overview []
[:<>
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:title (:name auth-user-info)
:page-type :profile
:content (fn []
[:h2.subtitle.is-size-6
(str "Fødselsdag: " (:birthdate auth-user-info))])])
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1))
(take 2))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))]
[page-content
:page-type :accounts
:content (fn [] [accounts-view])]])
(defn pages []
(let [active-page (deref (rf/subscribe [::subs/active-page]))]
(case active-page
:accounts [accounts]
:developer-support [developer-support]
:investment [investment]
:messages [messages]
:overview [overview]
:payments-and-transfer [payments-and-transfer]
:pension-and-insurance [pension-and-insurance]
:profile [profile]
[overview])))
(defn navigation-menu []
(let [active-page (deref (rf/subscribe [::subs/active-page]))
number-of-unread-messages (deref (rf/subscribe [::subs/number-of-unread-messages]))]
[:div.column.is-one-quarter.is-one-fifth-fullhd
[:nav.panel {:style {:box-shadow "none"}}
(for [{:keys [id icon text]} (vals nav-items)]
[:<> {:key (str "nav-menu-item-" id)}
[:div.menu-item.panel-block {:class (when (= id active-page) "is-active")
:on-click #(rf/dispatch [::events/set-active-page id])}
[:span.panel-icon
[:div.icon {:class icon}
(when (and (= id :messages) (< 0 number-of-unread-messages))
[:span.badge {:class "is-danger"}
number-of-unread-messages])]]
[:span text]]
[:br]])]]))
| 16390 | (ns cljs-re-frame.views
(:require [Authentication.authentication :as auth]
[cljs-re-frame.events :as events]
[cljs-re-frame.subs :as subs]
[clojure.string :as str]
[markdown-to-hiccup.core :as markdown]
[re-frame.core :as rf]))
(defn print-date [^js/Date d]
(str (.getDate d) "/"
(.getMonth d) "/"
(.getFullYear d)))
(def nav-items
(->> [{:id :overview
:icon "lamp"
:text "Overview"}
{:id :accounts
:icon "coins"
:text "Accounts"}
{:id :payments-and-transfer
:icon "arrows"
:text "Payments & Transfer"}
{:id :investment
:icon "chart"
:text "Investment"}
{:id :pension-and-insurance
:icon "wineglass"
:text "Pension & Insurance"}
{:id :messages
:icon "envelope"
:text "Messages"}
{:id :profile
:icon "profile"
:text "Profile"}
{:id :developer-support
:icon "code"
:text "Developer Support"}]
(map (juxt :id identity))
(into {})))
(defn create-columns [attributes & columns]
[:div.columns.account attributes
[:<>
(for [{:keys [content attrs]} columns]
[:div.column.is-4 (update attrs :key (fnil identity (random-uuid)))
content])]])
(defn log-in-button []
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))
button-style {:background-color "transparent"
:border-style "none"
:font-size "18px"}
log-in-fn auth/login
log-off-fn #(rf/dispatch [::events/logout])
button (fn [text on-click-fn]
[:a.button {:style button-style
:on-click on-click-fn}
[:span.navbar-item text]
[:div.icon.power-off-white]])]
[:div.buttons
(if (nil? auth-user-info)
[button "Log on" log-in-fn]
[button "Log off" log-off-fn])]))
(defn page-content [& {:keys [title page-type content]}]
[:div.card {:style {:box-shadow "none"
:background-color "white"}}
[:div.card-content
[:article.media
[:div.media-left
[:figure.image {:class (str "is-32x32 icon " (:icon (nav-items page-type)))}]]]
[:div.content
[:h1.title (or title (:text (nav-items page-type)))]
[content]]]])
(defn profile []
(let [auth-error (deref (rf/subscribe [::subs/auth-error]))
auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:page-type :profile
:content (fn []
[:<>
(when auth-user-info
[:<>
(for [[k v] auth-user-info]
(create-columns {:key (str "auth-user-info-" (name k))}
{:content (str/capitalize (name k))} {:content v}))
[:button.button.is-danger {:on-click (fn [_] (rf/dispatch [::events/logout]))}
"Log off"]])
(when auth-error
[:p (str "auth error: " auth-error)])])]))
(defn accounts-view []
(let [accounts (deref (rf/subscribe [::subs/accounts]))]
[:<>
[create-columns {:class "header"}
{:content "Name"}
{:content "Balance"}
{:content "Recent Transactions"}]
(for [{:keys [account-name id balance last-transaction-date]} accounts]
[create-columns {:key id}
{:content account-name}
{:content balance}
{:content (print-date last-transaction-date)}])]))
(defn accounts []
[page-content
:page-type :accounts
:content (fn [] [accounts-view])])
(defn payments-and-transfer []
[page-content
:page-type :payments-and-transfer
:content (fn [] [:div])])
(defn investment []
[page-content
:page-type :investment
:content (fn [] [:div])])
(defn pension-and-insurance []
[page-content
:page-type :pension-and-insurance
:content (fn [] [:div])])
(defn message-view [{:keys [index from title content date read? id unfolded?]}]
[:article.accordion.message-item (when unfolded? {:class "is-active"})
[:div.accordion-header.message-item.toggle
{:class (str "message-item-" index)
:on-click #(rf/dispatch [::events/toggle-message id])}
[:div.message-item.from
(when (not read?)
[:div.icon.dot {:style {:margin-right "12px"}}])
[:span (str from " " date)]]
[:span.message-item.subject title]]
[:div.accordion-body
[:div.accordion-content.message-item
[:div (->> content
markdown/md->hiccup
markdown/component)]]]
[:section
[:a.button.reply {:href "mailto:<EMAIL>"}
[:span "Reply"]
[:div.icon.reply]]]])
(defn messages []
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1)))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))])
(defn developer-support []
[page-content
:page-type :developer-support
:content (fn []
[:<>
[:div [:a {:href "mailto:<EMAIL>"} "<EMAIL>"]]
[:div [:a {:href "https://criipto.slack.com/"} "Slack"]]])])
(def front-page-icons
[{:icon "apartment"
:text "Housing"}
{:icon "car"
:text "Cars"}
{:icon "chart"
:text "Investment"}
{:icon "wineglass"
:text "Pension"}
{:icon "hand-holding-medical"
:text "Insurance"}
{:icon "credit-card"
:text "Cards"}
{:icon "coins"
:text "Loans"}
{:icon "cardboard-box"
:text "More products"}])
(def tiles-content
[{:title "Easy digital signing of sensitive documents"
:text "Criipto provides Criipto Bank’s secure and user-friendly signing solution so you can sign securely - on your computer and on the go."
:icon "signature"}
{:title "Easy login to Criipto Bank"
:text "Criipto Bank is using Criipto's easy and secure login solution. It saves us a lot of money that we can spend on better service for you!'"
:icon "power-off"}
{:title "MitID has arrived - We have you covered"
:text "Don’t worry. We have your back. With Criipto’s easy e-ID login solution we provide MitID and NemID login side-by-side."
:icon "mitid"}])
(defn front-page []
[:div.columns
[:div.column.is-2]
[:div.column.is-8
[:div.tile.is-ancestor.splash-menu
[:div.tile.is-parent
(for [{:keys [text icon]} front-page-icons]
[:div.tile.is-child {:key (str "front-page-" text "-" icon)}
[:div.menu-icon.icon {:class icon}]
[:div.menu-name text]])]]
[:div.tile.is-ancestor
[:div.tile.is-parent
[:div.tile.is-child.box.banner
[:div.banner.overlay]
[:div.banner-content
[:h2.subtitle.banner "BUSINESS TO BUSINESS"]
[:h1.title.banner "“We save 120 dev hours a year with Criipto’s e-ID login”"]]]]]
[:div.tile.is-ancestor
[:div.tile.is-parent
(for [{:keys [title text icon]} tiles-content]
[:div.tile.is-child.box.splash-item {:key (str "front-page-" icon)}
[:div.icon.is-40h.splash-item {:class icon}]
[:h1.title.splash-item title]
[:div.content.splash-item text]])]]]])
(defn overview []
[:<>
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:title (:name auth-user-info)
:page-type :profile
:content (fn []
[:h2.subtitle.is-size-6
(str "Fødselsdag: " (:birthdate auth-user-info))])])
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1))
(take 2))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))]
[page-content
:page-type :accounts
:content (fn [] [accounts-view])]])
(defn pages []
(let [active-page (deref (rf/subscribe [::subs/active-page]))]
(case active-page
:accounts [accounts]
:developer-support [developer-support]
:investment [investment]
:messages [messages]
:overview [overview]
:payments-and-transfer [payments-and-transfer]
:pension-and-insurance [pension-and-insurance]
:profile [profile]
[overview])))
(defn navigation-menu []
(let [active-page (deref (rf/subscribe [::subs/active-page]))
number-of-unread-messages (deref (rf/subscribe [::subs/number-of-unread-messages]))]
[:div.column.is-one-quarter.is-one-fifth-fullhd
[:nav.panel {:style {:box-shadow "none"}}
(for [{:keys [id icon text]} (vals nav-items)]
[:<> {:key (str "nav-menu-item-" id)}
[:div.menu-item.panel-block {:class (when (= id active-page) "is-active")
:on-click #(rf/dispatch [::events/set-active-page id])}
[:span.panel-icon
[:div.icon {:class icon}
(when (and (= id :messages) (< 0 number-of-unread-messages))
[:span.badge {:class "is-danger"}
number-of-unread-messages])]]
[:span text]]
[:br]])]]))
| true | (ns cljs-re-frame.views
(:require [Authentication.authentication :as auth]
[cljs-re-frame.events :as events]
[cljs-re-frame.subs :as subs]
[clojure.string :as str]
[markdown-to-hiccup.core :as markdown]
[re-frame.core :as rf]))
(defn print-date [^js/Date d]
(str (.getDate d) "/"
(.getMonth d) "/"
(.getFullYear d)))
(def nav-items
(->> [{:id :overview
:icon "lamp"
:text "Overview"}
{:id :accounts
:icon "coins"
:text "Accounts"}
{:id :payments-and-transfer
:icon "arrows"
:text "Payments & Transfer"}
{:id :investment
:icon "chart"
:text "Investment"}
{:id :pension-and-insurance
:icon "wineglass"
:text "Pension & Insurance"}
{:id :messages
:icon "envelope"
:text "Messages"}
{:id :profile
:icon "profile"
:text "Profile"}
{:id :developer-support
:icon "code"
:text "Developer Support"}]
(map (juxt :id identity))
(into {})))
(defn create-columns [attributes & columns]
[:div.columns.account attributes
[:<>
(for [{:keys [content attrs]} columns]
[:div.column.is-4 (update attrs :key (fnil identity (random-uuid)))
content])]])
(defn log-in-button []
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))
button-style {:background-color "transparent"
:border-style "none"
:font-size "18px"}
log-in-fn auth/login
log-off-fn #(rf/dispatch [::events/logout])
button (fn [text on-click-fn]
[:a.button {:style button-style
:on-click on-click-fn}
[:span.navbar-item text]
[:div.icon.power-off-white]])]
[:div.buttons
(if (nil? auth-user-info)
[button "Log on" log-in-fn]
[button "Log off" log-off-fn])]))
(defn page-content [& {:keys [title page-type content]}]
[:div.card {:style {:box-shadow "none"
:background-color "white"}}
[:div.card-content
[:article.media
[:div.media-left
[:figure.image {:class (str "is-32x32 icon " (:icon (nav-items page-type)))}]]]
[:div.content
[:h1.title (or title (:text (nav-items page-type)))]
[content]]]])
(defn profile []
(let [auth-error (deref (rf/subscribe [::subs/auth-error]))
auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:page-type :profile
:content (fn []
[:<>
(when auth-user-info
[:<>
(for [[k v] auth-user-info]
(create-columns {:key (str "auth-user-info-" (name k))}
{:content (str/capitalize (name k))} {:content v}))
[:button.button.is-danger {:on-click (fn [_] (rf/dispatch [::events/logout]))}
"Log off"]])
(when auth-error
[:p (str "auth error: " auth-error)])])]))
(defn accounts-view []
(let [accounts (deref (rf/subscribe [::subs/accounts]))]
[:<>
[create-columns {:class "header"}
{:content "Name"}
{:content "Balance"}
{:content "Recent Transactions"}]
(for [{:keys [account-name id balance last-transaction-date]} accounts]
[create-columns {:key id}
{:content account-name}
{:content balance}
{:content (print-date last-transaction-date)}])]))
(defn accounts []
[page-content
:page-type :accounts
:content (fn [] [accounts-view])])
(defn payments-and-transfer []
[page-content
:page-type :payments-and-transfer
:content (fn [] [:div])])
(defn investment []
[page-content
:page-type :investment
:content (fn [] [:div])])
(defn pension-and-insurance []
[page-content
:page-type :pension-and-insurance
:content (fn [] [:div])])
(defn message-view [{:keys [index from title content date read? id unfolded?]}]
[:article.accordion.message-item (when unfolded? {:class "is-active"})
[:div.accordion-header.message-item.toggle
{:class (str "message-item-" index)
:on-click #(rf/dispatch [::events/toggle-message id])}
[:div.message-item.from
(when (not read?)
[:div.icon.dot {:style {:margin-right "12px"}}])
[:span (str from " " date)]]
[:span.message-item.subject title]]
[:div.accordion-body
[:div.accordion-content.message-item
[:div (->> content
markdown/md->hiccup
markdown/component)]]]
[:section
[:a.button.reply {:href "mailto:PI:EMAIL:<EMAIL>END_PI"}
[:span "Reply"]
[:div.icon.reply]]]])
(defn messages []
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1)))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))])
(defn developer-support []
[page-content
:page-type :developer-support
:content (fn []
[:<>
[:div [:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} "PI:EMAIL:<EMAIL>END_PI"]]
[:div [:a {:href "https://criipto.slack.com/"} "Slack"]]])])
(def front-page-icons
[{:icon "apartment"
:text "Housing"}
{:icon "car"
:text "Cars"}
{:icon "chart"
:text "Investment"}
{:icon "wineglass"
:text "Pension"}
{:icon "hand-holding-medical"
:text "Insurance"}
{:icon "credit-card"
:text "Cards"}
{:icon "coins"
:text "Loans"}
{:icon "cardboard-box"
:text "More products"}])
(def tiles-content
[{:title "Easy digital signing of sensitive documents"
:text "Criipto provides Criipto Bank’s secure and user-friendly signing solution so you can sign securely - on your computer and on the go."
:icon "signature"}
{:title "Easy login to Criipto Bank"
:text "Criipto Bank is using Criipto's easy and secure login solution. It saves us a lot of money that we can spend on better service for you!'"
:icon "power-off"}
{:title "MitID has arrived - We have you covered"
:text "Don’t worry. We have your back. With Criipto’s easy e-ID login solution we provide MitID and NemID login side-by-side."
:icon "mitid"}])
(defn front-page []
[:div.columns
[:div.column.is-2]
[:div.column.is-8
[:div.tile.is-ancestor.splash-menu
[:div.tile.is-parent
(for [{:keys [text icon]} front-page-icons]
[:div.tile.is-child {:key (str "front-page-" text "-" icon)}
[:div.menu-icon.icon {:class icon}]
[:div.menu-name text]])]]
[:div.tile.is-ancestor
[:div.tile.is-parent
[:div.tile.is-child.box.banner
[:div.banner.overlay]
[:div.banner-content
[:h2.subtitle.banner "BUSINESS TO BUSINESS"]
[:h1.title.banner "“We save 120 dev hours a year with Criipto’s e-ID login”"]]]]]
[:div.tile.is-ancestor
[:div.tile.is-parent
(for [{:keys [title text icon]} tiles-content]
[:div.tile.is-child.box.splash-item {:key (str "front-page-" icon)}
[:div.icon.is-40h.splash-item {:class icon}]
[:h1.title.splash-item title]
[:div.content.splash-item text]])]]]])
(defn overview []
[:<>
(let [auth-user-info (deref (rf/subscribe [::subs/auth-user]))]
[page-content
:title (:name auth-user-info)
:page-type :profile
:content (fn []
[:h2.subtitle.is-size-6
(str "Fødselsdag: " (:birthdate auth-user-info))])])
[page-content
:page-type :messages
:content (fn []
(let [messages (->> (deref (rf/subscribe [::subs/messages]))
vals
(sort-by :date #(compare %2 %1))
(take 2))]
[:section.accordions
(for [[index {:keys [id] :as message}] (map-indexed vector messages)]
[:<> {:key (str "message-" id)}
[message-view (assoc message :index index)]])]))]
[page-content
:page-type :accounts
:content (fn [] [accounts-view])]])
(defn pages []
(let [active-page (deref (rf/subscribe [::subs/active-page]))]
(case active-page
:accounts [accounts]
:developer-support [developer-support]
:investment [investment]
:messages [messages]
:overview [overview]
:payments-and-transfer [payments-and-transfer]
:pension-and-insurance [pension-and-insurance]
:profile [profile]
[overview])))
(defn navigation-menu []
(let [active-page (deref (rf/subscribe [::subs/active-page]))
number-of-unread-messages (deref (rf/subscribe [::subs/number-of-unread-messages]))]
[:div.column.is-one-quarter.is-one-fifth-fullhd
[:nav.panel {:style {:box-shadow "none"}}
(for [{:keys [id icon text]} (vals nav-items)]
[:<> {:key (str "nav-menu-item-" id)}
[:div.menu-item.panel-block {:class (when (= id active-page) "is-active")
:on-click #(rf/dispatch [::events/set-active-page id])}
[:span.panel-icon
[:div.icon {:class icon}
(when (and (= id :messages) (< 0 number-of-unread-messages))
[:span.badge {:class "is-danger"}
number-of-unread-messages])]]
[:span text]]
[:br]])]]))
|
[
{
"context": "(ns com.mrmccue.macros\n ^{:author \"Ethan McCue\"\n :email \"emccue@live.com\"\n :doc \"A collect",
"end": 47,
"score": 0.9998791813850403,
"start": 36,
"tag": "NAME",
"value": "Ethan McCue"
},
{
"context": "ccue.macros\n ^{:author \"Ethan McCue\"\n :email \"emccue@live.com\"\n :doc \"A collection of useful macros to exten",
"end": 76,
"score": 0.9999327659606934,
"start": 61,
"tag": "EMAIL",
"value": "emccue@live.com"
}
] | Clojure/macros.clj | PushpneetSingh/Hello-world | 1,428 | (ns com.mrmccue.macros
^{:author "Ethan McCue"
:email "emccue@live.com"
:doc "A collection of useful macros to extend base clojure"}
(:require [clojure.core.strint :refer [<<]]
[clojure.java.io :as io]))
(defmacro oops [msg]
(when (not (string? msg))
(oops "Argument to 'oops' must be a string literal"))
`(throw (IllegalArgumentException. ^String (<< ~msg))))
;; ----------------------------------------------------------------------------
(defmacro m
"Expands out a series of variables to a map where
the name of the variable is the key under which the variable
goes
Ex. (m a b c) => {:a a, :b b, :c c}
(m) => {}"
[& vars]
(doseq [name vars]
(when (not (symbol? name))
(oops "Every element passed to the 'm' macro must be a symbol.
Element ~{name} is not a symbol")))
(into {}
(for [name vars]
[(keyword name) name])))
;; ----------------------------------------------------------------------------
(declare
^{:doc "Dummy variable to resolve the | symbol in cursive"}
|)
;; ----------------------------------------------------------------------------
(defmacro m+
"Like m, but will allow for custom rebinding of some symbols
Ex. (m+ a b c) => {:a a, :b b, :c c}
(m+) => {}
(m+ a b | :cat c) => {:a a, :b b, :cat c}
(m+ a b | c d :f some-var) => {:a a, :b b, c d, :f some-var}"
[& vars]
(let [number-of-dividers (count (filter #(= % '|) vars))]
(when (not (or (= number-of-dividers 0)
(= number-of-dividers 1)))
(oops "There should only be either 1 or 0 of the divider symbol '|
passed to the 'm+' macro. Found ~{number-of-dividers} occurrences")))
(let [[symbols map-bindings-plus-divider] (split-with #(not= % '|) vars)
map-bindings (rest map-bindings-plus-divider)]
(doseq [name symbols]
(when (not (symbol? name))
(oops "Every element passed to the 'm+' macro before
a divider must be a symbol.
Element ~{name} is not a symbol")))
(when (not (even? (count map-bindings)))
(oops "Uneven number of map bindings passed to the 'm+' macro"))
(merge (into {}
(for [name symbols]
[(keyword name) name]))
(apply hash-map map-bindings))))
| 60963 | (ns com.mrmccue.macros
^{:author "<NAME>"
:email "<EMAIL>"
:doc "A collection of useful macros to extend base clojure"}
(:require [clojure.core.strint :refer [<<]]
[clojure.java.io :as io]))
(defmacro oops [msg]
(when (not (string? msg))
(oops "Argument to 'oops' must be a string literal"))
`(throw (IllegalArgumentException. ^String (<< ~msg))))
;; ----------------------------------------------------------------------------
(defmacro m
"Expands out a series of variables to a map where
the name of the variable is the key under which the variable
goes
Ex. (m a b c) => {:a a, :b b, :c c}
(m) => {}"
[& vars]
(doseq [name vars]
(when (not (symbol? name))
(oops "Every element passed to the 'm' macro must be a symbol.
Element ~{name} is not a symbol")))
(into {}
(for [name vars]
[(keyword name) name])))
;; ----------------------------------------------------------------------------
(declare
^{:doc "Dummy variable to resolve the | symbol in cursive"}
|)
;; ----------------------------------------------------------------------------
(defmacro m+
"Like m, but will allow for custom rebinding of some symbols
Ex. (m+ a b c) => {:a a, :b b, :c c}
(m+) => {}
(m+ a b | :cat c) => {:a a, :b b, :cat c}
(m+ a b | c d :f some-var) => {:a a, :b b, c d, :f some-var}"
[& vars]
(let [number-of-dividers (count (filter #(= % '|) vars))]
(when (not (or (= number-of-dividers 0)
(= number-of-dividers 1)))
(oops "There should only be either 1 or 0 of the divider symbol '|
passed to the 'm+' macro. Found ~{number-of-dividers} occurrences")))
(let [[symbols map-bindings-plus-divider] (split-with #(not= % '|) vars)
map-bindings (rest map-bindings-plus-divider)]
(doseq [name symbols]
(when (not (symbol? name))
(oops "Every element passed to the 'm+' macro before
a divider must be a symbol.
Element ~{name} is not a symbol")))
(when (not (even? (count map-bindings)))
(oops "Uneven number of map bindings passed to the 'm+' macro"))
(merge (into {}
(for [name symbols]
[(keyword name) name]))
(apply hash-map map-bindings))))
| true | (ns com.mrmccue.macros
^{:author "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:doc "A collection of useful macros to extend base clojure"}
(:require [clojure.core.strint :refer [<<]]
[clojure.java.io :as io]))
(defmacro oops [msg]
(when (not (string? msg))
(oops "Argument to 'oops' must be a string literal"))
`(throw (IllegalArgumentException. ^String (<< ~msg))))
;; ----------------------------------------------------------------------------
(defmacro m
"Expands out a series of variables to a map where
the name of the variable is the key under which the variable
goes
Ex. (m a b c) => {:a a, :b b, :c c}
(m) => {}"
[& vars]
(doseq [name vars]
(when (not (symbol? name))
(oops "Every element passed to the 'm' macro must be a symbol.
Element ~{name} is not a symbol")))
(into {}
(for [name vars]
[(keyword name) name])))
;; ----------------------------------------------------------------------------
(declare
^{:doc "Dummy variable to resolve the | symbol in cursive"}
|)
;; ----------------------------------------------------------------------------
(defmacro m+
"Like m, but will allow for custom rebinding of some symbols
Ex. (m+ a b c) => {:a a, :b b, :c c}
(m+) => {}
(m+ a b | :cat c) => {:a a, :b b, :cat c}
(m+ a b | c d :f some-var) => {:a a, :b b, c d, :f some-var}"
[& vars]
(let [number-of-dividers (count (filter #(= % '|) vars))]
(when (not (or (= number-of-dividers 0)
(= number-of-dividers 1)))
(oops "There should only be either 1 or 0 of the divider symbol '|
passed to the 'm+' macro. Found ~{number-of-dividers} occurrences")))
(let [[symbols map-bindings-plus-divider] (split-with #(not= % '|) vars)
map-bindings (rest map-bindings-plus-divider)]
(doseq [name symbols]
(when (not (symbol? name))
(oops "Every element passed to the 'm+' macro before
a divider must be a symbol.
Element ~{name} is not a symbol")))
(when (not (even? (count map-bindings)))
(oops "Uneven number of map bindings passed to the 'm+' macro"))
(merge (into {}
(for [name symbols]
[(keyword name) name]))
(apply hash-map map-bindings))))
|
[
{
"context": " could look like\n this:\n\n ```\n (def my-token \\\"FOOBAR123\\\")\n ```\n\n Each function takes this token as its",
"end": 312,
"score": 0.9824076294898987,
"start": 303,
"tag": "PASSWORD",
"value": "FOOBAR123"
}
] | src/hcloud/core.clj | olieidel/hcloud | 13 | (ns hcloud.core
"Hetzner Cloud API functions.
## Auth Token
All calls to the Hetzner API must be authenticated. For that, you
need an Authentication Token which you can generate online in your
Hetzner Cloud Account. The token is a string and could look like
this:
```
(def my-token \"FOOBAR123\")
```
Each function takes this token as its first argument. An example
call to `get-prices` would look like this:
```
(get-prices my-token)
```
## IDs
Furthermore, some functions take an `id` as an argument. The `id` is
a string and refers to the resource which the API call is referring
to (e.g., a server). An example call to `get-server` would look like
this:
```
(get-server my-token \"SERVER-ID-123\")
```
## Query Parameters
Some functions take query string parameters. These are appended to
the API url, i.e. in the url
`https://api.hetzner.cloud/v1/servers?name=cx11`, there is the query
parameter `name` with the value of `cx11`.
In our functions, these query string parameters can be set in the
`query-m` map. For example, the API call above is equivalent to this
function call:
```
(get-servers my-token {:name \"cx11\"})
```
Pagination is also handled via the query parameters (and therefore
the `query-m` map). Say we want to retrieve page 2 of our servers:
```
(get-servers my-token {:page 2})
```
### An important note on kebab-case
Note that these are converted from kebab-cased keywords to
snake-cased strings. So if the Hetzner API would be expecting a
query parameter called \"foo_bar\", we would set it by providing
`{:foo-bar \"some-value\"}` in our map. Dashes are converted to
underscores.
This is also true for the replies from the Hetzner API, this time
the other way round: The keys are snake-cased strings and will be
converted to kebab-cased keywords. So if the reply json has a key
\"time_series\", you'll find it in a Clojure map under the value
`:time-series`.
## Body Parameters
Some functions take (json) body parameters. In our functions, these
can be set in the `body-m` map. Let's say we want to create a server
with the name \"HAL\", this is how we would do it:
```
(create-server my-token {:name \"HAL\"})
```
Note that keywords will be converted from kebab-case to snake-case
again, so if you would also want to set the `start_after_create`
value, you would do this:
```
(create-server my-token {:name \"HAL\"
:start-after-create true})
```
## Metadata of public functions
Public functions in this namespace have two keys in their metadata:
`:api-category` and `:order`. These are used to auto-generate docs
in the README (check `dev/readme.clj`). The idea is to have the
documentation of the functions in the same order as in the [Hetzner
docs](https://docs.hetzner.cloud). Therefore `:api-category` refers
to the endpoint (and the title of the section in the docs) and
`:order` is the position at which it appears in the docs.
If you didn't understand any of this, don't worry. As long as you
understand the README, you're fine!"
(:require [camel-snake-kebab.core :as csk]
[camel-snake-kebab.extras :as csk.extras]
[cheshire.core :as cheshire]
[clj-http.client :as http]
[clojure.string :as str]))
;; -- Key Transformations ------------------------------------------------------
(defn- kebab-case-keys [m]
(csk.extras/transform-keys csk/->kebab-case-keyword m))
(defn- snake-case-keys [m]
(csk.extras/transform-keys csk/->snake_case_keyword m))
(defn- map->json-str [m]
(cheshire/generate-string (snake-case-keys m)))
(defn- json-str->map [s]
(kebab-case-keys (cheshire/parse-string s)))
;; -- General Stuff ------------------------------------------------------------
(def ^:private ^:const hetzner-api-url
"The Hetzner API Url."
"https://api.hetzner.cloud/v1")
(defn- api-url [& paths]
(str/join (interpose "/" (cons hetzner-api-url paths))))
(defn- http-opts
[{:keys [token body-m query-m]}]
(cond-> {:accept :json
:as :json
:content-type :json
;; this will add an "Authorization" header with the string
;; "Bearer TOKEN"
:oauth-token token}
(not (empty? body-m)) (assoc :body (map->json-str body-m))
(not (empty? query-m)) (assoc :query-params query-m)))
;; -- Exception Handling -------------------------------------------------------
(defn- handle-exception
"Handle exceptions which are usually raised by clj-http.
The `:body` of the response is parsed (the API returns a JSON
string), keys are converted to kebab-cased keywords. Also, the
`:http-status` of the request is `assoc`ed to the map.
Example error data, note that the `:error` key is provided by the
API response. As the API response body is merged as-is into the map,
in theory other keys besides `:error` could be there:
```clojure
{:error
{:message \"invalid input in field 'server_type'\",
:code \"invalid_input\",
:details
{:fields
[{:name \"server_type\",
:messages [\"Missing data for required field.\"]}]}},
:http-status 422}
```"
[exception]
(let [exception-data (ex-data exception)]
(merge (json-str->map (:body exception-data))
{:http-status (:status exception-data)})))
;; -- Request ------------------------------------------------------------------
(defn- request
"Do a HTTP request with `http-fn` (most likely `clj-http`), convert
the keys of the body to kebab-case, catch exceptions."
[http-fn & args]
(try
(let [result (apply http-fn args)]
(kebab-case-keys (:body result)))
(catch Exception e
(handle-exception e))))
;; -- Actions ------------------------------------------------------------------
(defn ^{:api-category :actions
:order 0}
get-actions
"List all Actions
https://docs.hetzner.cloud/#actions-list-all-actions
Returns all action objects. You can select specific actions only and
sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-actions token {}))
([token query-m]
(request http/get (api-url "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :actions
:order 1}
get-action
"Get one Action
https://docs.hetzner.cloud/#actions-get-one-action
Returns a specific action object.
Parameters:
* `id` (string): ID of the action"
[token id]
(request http/get (api-url "actions" id) (http-opts {:token token})))
;; -- Servers ------------------------------------------------------------------
(defn ^{:api-category :servers
:order 0}
get-servers
"Get all Servers
https://docs.hetzner.cloud/#servers-get-all-servers
Returns all existing server objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter servers by their
name. The response will only contain the server matching the
specified name."
([token] (get-servers token {}))
([token query-m]
(request http/get (api-url "servers")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :servers
:order 1}
get-server
"Get a Server
https://docs.hetzner.cloud/#servers-get-a-server
Returns a specific server object. The server must exist inside the
project.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/get (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 2}
create-server
"Create a Server
https://docs.hetzner.cloud/#servers-create-a-server
Creates a new server. Returns preliminary information about the
server as well as an action that covers progress of creation.
Required body parameters (`body-m`):
* `:name` (string): Name of the server to create (must be unique
per project and a valid hostname as per RFC 1123)
* `:server_type` (string): ID or name of the server type this
server should be created with
* `:image` (string): ID or name of the image the server is created
from
Optional body parameters (`body-m`):
* `:start-after-create` (boolean): Start Server right after
creation. Defaults to true.
* `:ssh-keys` (vector): SSH key IDs or names which should be
injected into the server at creation time
* `:user-data` (string): Cloud-Init user data to use during server
creation. This field is limited to 32KiB.
* `:location` (string): ID or name of location to create server in.
* `:datacenter` (string): ID or name of datacenter to create server
in."
[token body-m]
(request http/post (api-url "servers")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 3}
change-server-name
"Change Name of a Server
https://docs.hetzner.cloud/#servers-change-name-of-a-server
Changes the name of a server.
Please note that server names must be unique per project and valid
hostnames as per RFC 1123 (i.e. may only contain letters, digits,
periods, and dashes).
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:name` (string): New name to set. Note: I have no idea why this
is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "servers" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 4}
delete-server
"Delete a Server
https://docs.hetzner.cloud/#servers-delete-a-server
Deletes a server. This immediately removes the server from your
account, and it is no longer accessible.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/delete (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 5}
get-server-metrics
"Get Metrics for a Server
https://docs.hetzner.cloud/#servers-get-metrics-for-a-server
Get Metrics for specified server.
You must specify the type of metric to get: cpu, disk or
network. You can also specify more than one type by comma
separation, e.g. cpu,disk.
Parameters:
* `id` (string): ID of the server
Required query parameters (`query-m`):
* `:type` (string): Type of metrics to get (cpu, disk, network)
* `:start` (string): Start of period to get Metrics for (in
ISO-8601 format)
* `:end` (string): End of period to get Metrics for (in ISO-8601
format)
Optional query parameters (`query-m`):
* `:step` (number): Resolution of results in seconds "
[token id query-m]
(request http/get (api-url "servers" id "metrics")
(http-opts {:token token :query-m query-m})))
;; -- Server Actions -----------------------------------------------------------
(defn ^{:api-category :server-actions
:order 0}
get-server-actions
"Get all Actions for a Server
https://docs.hetzner.cloud/#server-actions-get-all-actions-for-a-server
Returns all action objects for a server.
Parameters:
* `id` (string): ID of the server
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-server-actions token {}))
([token id query-m]
(request http/get (api-url "servers" id "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-actions
:order 1}
get-server-action
"Get a specific Action for a Server
https://docs.hetzner.cloud/#server-actions-get-a-specific-action-for-a-server
Returns a specific action object for a Server.
Parameters:
* `id` (string): ID of the server
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "servers" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 2}
power-on-server
"Power on a Server
https://docs.hetzner.cloud/#server-actions-power-on-a-server
Starts a server by turning its power on.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweron")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 3}
soft-reboot-server
"Soft-reboot a Server
https://docs.hetzner.cloud/#server-actions-soft-reboot-a-server
Reboots a server gracefully by sending an ACPI request. The server
operating system must support ACPI and react to the request,
otherwise the server will not reboot.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reboot")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 4}
reset-server
"Reset a Server
https://docs.hetzner.cloud/#server-actions-reset-a-server
Cuts power to a server and starts it again. This forcefully stops it
without giving the server operating system time to gracefully
stop. This may lead to data loss, it’s equivalent to pulling the
power cord and plugging it in again. Reset should only be used when
reboot does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 5}
shutdown-server
"Shutdown a Server
https://docs.hetzner.cloud/#server-actions-shutdown-a-server
Shuts down a server gracefully by sending an ACPI shutdown
request. The server operating system must support ACPI and react to
the request, otherwise the server will not shut down.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "shutdown")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 6}
power-off-server
"Power off a Server
https://docs.hetzner.cloud/#server-actions-power-off-a-server
Cuts power to the server. This forcefully stops it without giving
the server operating system time to gracefully stop. May lead to
data loss, equivalent to pulling the power cord. Power off should
only be used when shutdown does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweroff")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 7}
reset-server-root-password
"Reset root Password of a Server
https://docs.hetzner.cloud/#server-actions-reset-root-password-of-a-server
Resets the root password. Only works for Linux systems that are
running the qemu guest agent. Server must be powered on (state on)
in order for this operation to succeed.
This will generate a new password for this server and return it.
If this does not succeed you can use the rescue system to netboot
the server and manually change your server password by hand.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset_password")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 8}
enable-server-rescue-mode
"Enable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-enable-rescue-mode-for-a-server
Enable the Hetzner Rescue System for this server. The next time a
Server with enabled rescue mode boots it will start a special
minimal Linux distribution designed for repair and reinstall.
In case a server cannot boot on its own you can use this to access a
server’s disks.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Enabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:type` (string): Type of rescue system to boot (default:
linux64) Choices: linux64, linux32, freebsd64
* `:ssh-keys` (vector): Array of SSH key IDs which should be
injected into the rescue system. Only available for types: linux64
and linux32."
([token] (enable-server-rescue-mode token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_rescue")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 9}
disable-server-rescue-mode
"Disable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-disable-rescue-mode-for-a-server
Disables the Hetzner Rescue System for a server. This makes a server
start from its disks on next reboot.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Disabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_rescue")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 10}
create-server-image
"Create Image from a Server
https://docs.hetzner.cloud/#server-actions-create-image-from-a-server
Creates an image (snapshot) from a server by copying the contents of
its disks. This creates a snapshot of the current state of the disk
and copies it into an image. If the server is currently running you
must make sure that its disk content is consistent. Otherwise, the
created image may not be readable.
To make sure disk content is consistent, we recommend to shut down
the server prior to creating an image.
You can either create a backup image that is bound to the server and
therefore will be deleted when the server is deleted, or you can
create an snapshot image which is completely independent of the
server it was created from and will survive server deletion. Backup
images are only available when the backup option is enabled for the
Server. Snapshot images are billed on a per GB basis.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:description` (string): Description of the image. If you do not
set this we auto-generate one for you.
* `:type` (string): Type of image to create (default: snapshot)
Choices: snapshot, backup"
([token] (create-server-image token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "create_image")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 11}
rebuild-server-from-image
"Rebuild a Server from an Image
https://docs.hetzner.cloud/#server-actions-rebuild-a-server-from-an-image
Rebuilds a server overwriting its disk with the content of an image,
thereby destroying all data on the target server
The image can either be one you have created earlier (backup or
snapshot image) or it can be a completely fresh system image
provided by us. You can get a list of all available images with GET
/images.
Your server will automatically be powered off before the rebuild
command executes.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:image` (string): ID or name of image to rebuilt from."
[token id body-m]
(request http/post (api-url "servers" id "actions" "rebuild")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 12}
change-server-type
"Change the Type of a Server
https://docs.hetzner.cloud/#server-actions-change-the-type-of-a-server
Changes the type (Cores, RAM and disk sizes) of a server.
Server must be powered off for this command to succeed.
This copies the content of its disk, and starts it again.
You can only migrate to server types with the same storage_type and
equal or bigger disks. Shrinking disks is not possible as it might
destroy data.
If the disk gets upgraded, the server type can not be downgraded any
more. If you plan to downgrade the server type, set upgrade_disk to
false.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:server-type` (string): ID or name of server type the server
should migrate to
Optional body parameters (`body-m`):
* `:upgrade-disk` (boolean): If false, do not upgrade the
disk. This allows downgrading the server type later."
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_type")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 13}
enable-server-backup
"Enable and Configure Backups for a Server
https://docs.hetzner.cloud/#server-actions-enable-and-configure-backups-for-a-server
Enables and configures the automatic daily backup option for the
server. Enabling automatic backups will increase the price of the
server by 20%. In return, you will get seven slots where images of
type backup can be stored.
Backups are automatically created daily.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:backup-window` (string): Time window (UTC) in which the backup
will run. Choices: 22-02, 02-06, 06-10, 10-14, 14-18, 18-22"
([token] (enable-server-backup token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_backup")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 14}
disable-server-backup
"Disable Backups for a Server
https://docs.hetzner.cloud/#server-actions-disable-backups-for-a-server
Disables the automatic backup option and deletes all existing
Backups for a Server. No more additional charges for backups will be
made.
Caution: This immediately removes all existing backups for the
server!
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_backup")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 15}
attach-iso-to-server
"Attach an ISO to a Server
https://docs.hetzner.cloud/#server-actions-attach-an-iso-to-a-server
Attaches an ISO to a server. The Server will immediately see it as a
new disk. An already attached ISO will automatically be detached
before the new ISO is attached.
Servers with attached ISOs have a modified boot order: They will try
to boot from the ISO first before falling back to hard disk.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:iso` (string): ID or name of ISO to attach to the server as
listed in GET /isos"
[token id body-m]
(request http/post (api-url "servers" id "actions" "attach_iso")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 16}
detach-iso-from-server
"Detach an ISO from a Server
https://docs.hetzner.cloud/#server-actions-detach-an-iso-from-a-server
Detaches an ISO from a server. In case no ISO image is attached to
the server, the status of the returned action is immediately set to
success.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "detach_iso")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 17}
change-server-reverse-dns-entry
"Change reverse DNS entry for this server
https://docs.hetzner.cloud/#server-actions-change-reverse-dns-entry-for-this-server
Changes the hostname that will appear when getting the hostname
belonging to the primary IPs (ipv4 and ipv6) of this server.
Floating IPs assigned to the server are not affected by this.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:ip` (string): Primary IP address for which the reverse DNS
entry should be set.
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR
entry. Will reset to original value if null"
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 18}
change-server-protection
"Change protection for a Server
https://docs.hetzner.cloud/#server-actions-change-protection-for-a-server
Changes the protection configuration of the server.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the server from being
deleted (currently delete and rebuild attribute needs to have the
same value)
* `:rebuild` (boolean): If true, prevents the server from being
rebuilt` (currently delete and rebuild attribute needs to have the
same value)"
([token] (change-server-protection token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 19}
request-server-console
"Request Console for a Server
https://docs.hetzner.cloud/#server-actions-request-console-for-a-server
Requests credentials for remote access via vnc over websocket to
keyboard, monitor, and mouse for a server. The provided url is valid
for 1 minute, after this period a new url needs to be created to
connect to the server. How long the connection is open after the
initial connect is not subject to this timeout.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "request_console")
(http-opts {:token token})))
;; -- Floating IPs -------------------------------------------------------------
(defn ^{:api-category :floating-ips
:order 0}
get-floating-ips
"Get all Floating IPs
https://docs.hetzner.cloud/#floating-ips-get-all-floating-ips
Returns all floating ip objects."
([token] (get-floating-ips token {}))
([token query-m]
(request http/get (api-url "floating_ips")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :floating-ips
:order 1}
get-floating-ip
"Get a specific Floating IP
https://docs.hetzner.cloud/#floating-ips-get-a-specific-floating-ip
Returns a specific floating ip object.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/get (api-url "floating_ips" id) (http-opts {:token token})))
(defn ^{:api-category :floating-ips
:order 1}
create-floating-ip
"Create a Floating IP
https://docs.hetzner.cloud/#floating-ips-create-a-floating-ip
Creates a new Floating IP assigned to a server. If you want to
create a Floating IP that is not bound to a server, you need to
provide the home_location key instead of server. This can be either
the ID or the name of the location this IP shall be created in. Note
that a Floating IP can be assigned to a server in any location later
on. For optimal routing it is advised to use the Floating IP in the
same Location it was created in.
Required body parameters (`body-m`):
* `:type` (string): Floating IP type Choices: ipv4, ipv6
Optional body parameters (`body-m`):
* `:server` (number): Server to assign the Floating IP to
* `:home-location` (string): Home location (routing is optimized
for that location). Only optional if server argument is passed.
* `:description` (string)"
[token body-m]
(request http/post (api-url "floating_ips")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 2}
change-floating-ip-description
"Change description of a Floating IP
https://docs.hetzner.cloud/#floating-ips-change-description-of-a-floating-ip
Changes the description of a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:description` (string): New Description to set. Note: I have no
idea why this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "floating_ips" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 3}
delete-floating-ip
"Delete a Floating IP
https://docs.hetzner.cloud/#floating-ips-delete-a-floating-ip
Deletes a Floating IP. If it is currently assigned to a server it
will automatically get unassigned.
Parameters:
* `id`: ID of the Floating IP"
[token id]
(request http/delete (api-url "floating_ips" id) (http-opts {:token token})))
;; -- Floating IP Actions ------------------------------------------------------
(defn ^{:api-category :floating-ip-actions
:order 0}
get-floating-ip-actions
"Get all Actions for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-all-actions-for-a-floating-ip
Returns all action objects for a Floating IP. You can sort the
results by using the sort URI parameter.
Parameters:
* `id` (string): ID of the Floating IP
Required query parameters (`query_m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "floating_ips" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :floating-ip-actions
:order 1}
get-floating-ip-action
"Get an Action for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-an-action-for-a-floating-ip
Returns a specific action object for a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "floating_ips" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions} assign-floating-ip-to-server
"Assign a Floating IP to a Server
https://docs.hetzner.cloud/#floating-ip-actions-assign-a-floating-ip-to-a-server
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:server` (number): ID of the server the Floating IP shall be
assigned to"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "assign")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 2}
unassign-floating-ip
"Unassign a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-unassign-a-floating-ip
Unassigns a Floating IP, resulting in it being unreachable. You may
assign it to a server again at a later time.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/post (api-url "floating_ips" id "actions" "unassign")
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions
:order 3}
change-floating-ip-reverse-dns-entry
"Change reverse DNS entry for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-change-reverse-dns-entry-for-a-floating-ip
Changes the hostname that will appear when getting the hostname
belonging to this Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:ip` (string): IP address for which to set the reverse DNS entry
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR entry,
will reset to original default value if null"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 4}
change-floating-ip-protection
"Change protection
https://docs.hetzner.cloud/#floating-ip-actions-change-protection
Changes the protection configuration of the Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the Floating IP from being
deleted. Note: I have no idea why this is optional in the official
Hetzner API docs."
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_protection")
(http-opts {:token token :body-m body-m})))
;; -- SSH Keys -----------------------------------------------------------------
(defn ^{:api-category :ssh-keys
:order 0}
get-ssh-keys
"Get all SSH keys
https://docs.hetzner.cloud/#ssh-keys-get-all-ssh-keys
Returns all SSH key objects.
Optional query parameters (`query_m`):
* `:name` (string): Can be used to filter SSH keys by their
name. The response will only contain the SSH key matching the
specified name.
* `:fingerprint` (string): Can be used to filter SSH keys by their
fingerprint. The response will only contain the SSH key matching the
specified fingerprint."
([token] (get-ssh-keys token {}))
([token query-m]
(request http/get (api-url "ssh_keys")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :ssh-keys
:order 1}
get-ssh-key
"Get an SSH key
https://docs.hetzner.cloud/#ssh-keys-get-an-ssh-key
Returns a specific SSH key object.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/get (api-url "ssh_keys" id) (http-opts {:token token})))
(defn ^{:api-category :ssh-keys
:order 2}
create-ssh-key
"Create an SSH key
https://docs.hetzner.cloud/#ssh-keys-create-an-ssh-key
Creates a new SSH key with the given name and public_key. Once an
SSH key is created, it can be used in other calls such as creating
servers.
Required body parameters (`body-m`):
* `:name` (string): Note: Seems to be missing in API docs.
* `:public-key` (string): Note: Seems to be missing in API docs."
[token body-m]
(request http/post (api-url "ssh_keys")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 3}
change-ssh-key-name
"Change the name of an SSH key.
https://docs.hetzner.cloud/#ssh-keys-change-the-name-of-an-ssh-key
Parameters:
* `id` (string): ID of the SSH key
Optional body parameters (`body-m`):
* `:name` (string): New name Name to set. Note: I have no idea why
this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "ssh_keys" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 4}
delete-ssh-key
"Delete an SSH key
https://docs.hetzner.cloud/#ssh-keys-delete-an-ssh-key
Deletes an SSH key. It cannot be used anymore.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/delete (api-url "ssh_keys" id) (http-opts {:token token})))
;; -- Server Types -------------------------------------------------------------
(defn ^{:api-category :server-types
:order 0}
get-server-types
"Get all Server Types
https://docs.hetzner.cloud/#server-types-get-all-server-types
Gets all server type objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter server types by their
name. The response will only contain the server type matching the
specified name."
([token] (get-server-types {}))
([token query-m]
(request http/get (api-url "server_types")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-types
:order 1}
get-server-type
"Get a Server Type
https://docs.hetzner.cloud/#server-types-get-a-server-type
Gets a specific server type object.
Parameters:
* `id` (string): ID of server type"
[token id]
(request http/get (api-url "server_types" id) (http-opts {:token token})))
;; -- Locations ----------------------------------------------------------------
(defn ^{:api-category :locations
:order 0}
get-locations
"Get all Locations
https://docs.hetzner.cloud/#locations-get-all-locations
Returns all location objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter locations by their
name. The response will only contain the location matching the
specified name."
([token] (get-locations token {}))
([token query-m]
(request http/get (api-url "locations")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :locations
:order 1}
get-location
"Get a Location
https://docs.hetzner.cloud/#locations-get-a-location
Returns a specific location object.
Parameters:
* `id` (string): ID of location"
[token id]
(request http/get (api-url "locations" id) (http-opts {:token token})))
;; -- Datacenters --------------------------------------------------------------
(defn ^{:api-category :datacenters
:order 0}
get-datacenters
"Get all Datacenters
https://docs.hetzner.cloud/#datacenters-get-all-datacenters
Returns all datacenter objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter datacenters by their
name. The response will only contain the datacenter matching the
specified name. When the name does not match the datacenter name
format, an invalid_input error is returned."
([token] (get-datacenters token {}))
([token query-m]
(request http/get (api-url "datacenters")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :datacenters
:order 1}
get-datacenter
"Get a Datacenter
https://docs.hetzner.cloud/#datacenters-get-a-datacenter
Returns a specific datacenter object.
Parameters:
* `id` (string): ID of datacenter"
[token id]
(request http/get (api-url "datacenters" id) (http-opts {:token token})))
;; -- Images -------------------------------------------------------------------
(defn ^{:api-category :images
:order 0}
get-images
"Get all Images
https://docs.hetzner.cloud/#images-get-all-images
Returns all image objects. You can select specific image types only
and sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc name name:asc name:desc created
created:asc created:desc
* `:type` (vector of strings): Can be used multiple times.
Choices: system snapshot backup
* `:bound-to` (string): Can be used multiple times. Server Id
linked to the image. Only available for images of type backup
* `:name` (string): Can be used to filter images by their name. The
response will only contain the image matching the specified name."
([token] (get-images token {}))
([token query-m]
(request http/get (api-url "images")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :images
:order 1}
get-image
"Get an Image
https://docs.hetzner.cloud/#images-get-an-image
Returns a specific image object.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/get (api-url "images" id) (http-opts {:token token})))
(defn ^{:api-category :images
:order 2}
update-image
"Update an Image
https://docs.hetzner.cloud/#images-update-an-image
Updates the Image. You may change the description or convert a
Backup image to a Snapshot Image. Only images of type snapshot and
backup can be updated.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:description` (string): New description of Image
* `:type` (string): Destination image type to convert to
Choices: snapshot"
([token] (update-image token {}))
([token id body-m]
(request http/put (api-url "images" id)
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :images
:order 3}
delete-image
"Delete an Image
https://docs.hetzner.cloud/#images-delete-an-image
Deletes an Image. Only images of type snapshot and backup can be deleted.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/delete (api-url "images" id) (http-opts {:token token})))
;; -- Image Actions ------------------------------------------------------------
(defn ^{:api-category :image-actions
:order 0}
get-image-actions
"Get all Actions for an Image
https://docs.hetzner.cloud/#image-actions-get-all-actions-for-an-image
Returns all action objects for an image. You can sort the results by
using the sort URI parameter.
Parameters:
* `id` (string): ID of the Image
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "images" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :image-actions
:order 1}
get-image-action
"Get an Action for an Image
https://docs.hetzner.cloud/#image-actions-get-an-action-for-an-image
Returns a specific action object for an image.
Parameters:
* `id` (string): ID of the image
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "images" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :image-actions
:order 2}
change-image-protection
"Change protection for an Image
https://docs.hetzner.cloud/#image-actions-change-protection-for-an-image
Changes the protection configuration of the image. Can only be used
on snapshots.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the snapshot from being deleted"
([token] (change-image-protection token {}))
([token id body-m]
(request http/post (api-url "images" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
;; -- ISOs ---------------------------------------------------------------------
(defn ^{:api-category :isos
:order 0}
get-isos
"Get all ISOs
https://docs.hetzner.cloud/#isos-get-all-isos
Returns all available iso objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter isos by their name. The
response will only contain the iso matching the specified name."
([token] (get-isos token {}))
([token query-m]
(request http/get (api-url "isos") (http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :isos
:order 1}
get-iso
"Get an ISO
https://docs.hetzner.cloud/#isos-get-an-iso
Returns a specific iso object.
Parameters:
* `id` (string): ID of the ISO"
[token id]
(request http/get (api-url "isos" id) (http-opts {:token token})))
;; -- Pricing ------------------------------------------------------------------
(defn ^{:api-category :pricing
:order 0}
get-prices
"Get all prices
https://docs.hetzner.cloud/#pricing-get-all-prices
Returns prices for all resources available on the platform. VAT and
currency of the project owner are used for calculations.
Both net and gross prices are included in the response."
[token]
(request http/get (api-url "pricing") (http-opts {:token token})))
| 87965 | (ns hcloud.core
"Hetzner Cloud API functions.
## Auth Token
All calls to the Hetzner API must be authenticated. For that, you
need an Authentication Token which you can generate online in your
Hetzner Cloud Account. The token is a string and could look like
this:
```
(def my-token \"<PASSWORD>\")
```
Each function takes this token as its first argument. An example
call to `get-prices` would look like this:
```
(get-prices my-token)
```
## IDs
Furthermore, some functions take an `id` as an argument. The `id` is
a string and refers to the resource which the API call is referring
to (e.g., a server). An example call to `get-server` would look like
this:
```
(get-server my-token \"SERVER-ID-123\")
```
## Query Parameters
Some functions take query string parameters. These are appended to
the API url, i.e. in the url
`https://api.hetzner.cloud/v1/servers?name=cx11`, there is the query
parameter `name` with the value of `cx11`.
In our functions, these query string parameters can be set in the
`query-m` map. For example, the API call above is equivalent to this
function call:
```
(get-servers my-token {:name \"cx11\"})
```
Pagination is also handled via the query parameters (and therefore
the `query-m` map). Say we want to retrieve page 2 of our servers:
```
(get-servers my-token {:page 2})
```
### An important note on kebab-case
Note that these are converted from kebab-cased keywords to
snake-cased strings. So if the Hetzner API would be expecting a
query parameter called \"foo_bar\", we would set it by providing
`{:foo-bar \"some-value\"}` in our map. Dashes are converted to
underscores.
This is also true for the replies from the Hetzner API, this time
the other way round: The keys are snake-cased strings and will be
converted to kebab-cased keywords. So if the reply json has a key
\"time_series\", you'll find it in a Clojure map under the value
`:time-series`.
## Body Parameters
Some functions take (json) body parameters. In our functions, these
can be set in the `body-m` map. Let's say we want to create a server
with the name \"HAL\", this is how we would do it:
```
(create-server my-token {:name \"HAL\"})
```
Note that keywords will be converted from kebab-case to snake-case
again, so if you would also want to set the `start_after_create`
value, you would do this:
```
(create-server my-token {:name \"HAL\"
:start-after-create true})
```
## Metadata of public functions
Public functions in this namespace have two keys in their metadata:
`:api-category` and `:order`. These are used to auto-generate docs
in the README (check `dev/readme.clj`). The idea is to have the
documentation of the functions in the same order as in the [Hetzner
docs](https://docs.hetzner.cloud). Therefore `:api-category` refers
to the endpoint (and the title of the section in the docs) and
`:order` is the position at which it appears in the docs.
If you didn't understand any of this, don't worry. As long as you
understand the README, you're fine!"
(:require [camel-snake-kebab.core :as csk]
[camel-snake-kebab.extras :as csk.extras]
[cheshire.core :as cheshire]
[clj-http.client :as http]
[clojure.string :as str]))
;; -- Key Transformations ------------------------------------------------------
(defn- kebab-case-keys [m]
(csk.extras/transform-keys csk/->kebab-case-keyword m))
(defn- snake-case-keys [m]
(csk.extras/transform-keys csk/->snake_case_keyword m))
(defn- map->json-str [m]
(cheshire/generate-string (snake-case-keys m)))
(defn- json-str->map [s]
(kebab-case-keys (cheshire/parse-string s)))
;; -- General Stuff ------------------------------------------------------------
(def ^:private ^:const hetzner-api-url
"The Hetzner API Url."
"https://api.hetzner.cloud/v1")
(defn- api-url [& paths]
(str/join (interpose "/" (cons hetzner-api-url paths))))
(defn- http-opts
[{:keys [token body-m query-m]}]
(cond-> {:accept :json
:as :json
:content-type :json
;; this will add an "Authorization" header with the string
;; "Bearer TOKEN"
:oauth-token token}
(not (empty? body-m)) (assoc :body (map->json-str body-m))
(not (empty? query-m)) (assoc :query-params query-m)))
;; -- Exception Handling -------------------------------------------------------
(defn- handle-exception
"Handle exceptions which are usually raised by clj-http.
The `:body` of the response is parsed (the API returns a JSON
string), keys are converted to kebab-cased keywords. Also, the
`:http-status` of the request is `assoc`ed to the map.
Example error data, note that the `:error` key is provided by the
API response. As the API response body is merged as-is into the map,
in theory other keys besides `:error` could be there:
```clojure
{:error
{:message \"invalid input in field 'server_type'\",
:code \"invalid_input\",
:details
{:fields
[{:name \"server_type\",
:messages [\"Missing data for required field.\"]}]}},
:http-status 422}
```"
[exception]
(let [exception-data (ex-data exception)]
(merge (json-str->map (:body exception-data))
{:http-status (:status exception-data)})))
;; -- Request ------------------------------------------------------------------
(defn- request
"Do a HTTP request with `http-fn` (most likely `clj-http`), convert
the keys of the body to kebab-case, catch exceptions."
[http-fn & args]
(try
(let [result (apply http-fn args)]
(kebab-case-keys (:body result)))
(catch Exception e
(handle-exception e))))
;; -- Actions ------------------------------------------------------------------
(defn ^{:api-category :actions
:order 0}
get-actions
"List all Actions
https://docs.hetzner.cloud/#actions-list-all-actions
Returns all action objects. You can select specific actions only and
sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-actions token {}))
([token query-m]
(request http/get (api-url "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :actions
:order 1}
get-action
"Get one Action
https://docs.hetzner.cloud/#actions-get-one-action
Returns a specific action object.
Parameters:
* `id` (string): ID of the action"
[token id]
(request http/get (api-url "actions" id) (http-opts {:token token})))
;; -- Servers ------------------------------------------------------------------
(defn ^{:api-category :servers
:order 0}
get-servers
"Get all Servers
https://docs.hetzner.cloud/#servers-get-all-servers
Returns all existing server objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter servers by their
name. The response will only contain the server matching the
specified name."
([token] (get-servers token {}))
([token query-m]
(request http/get (api-url "servers")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :servers
:order 1}
get-server
"Get a Server
https://docs.hetzner.cloud/#servers-get-a-server
Returns a specific server object. The server must exist inside the
project.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/get (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 2}
create-server
"Create a Server
https://docs.hetzner.cloud/#servers-create-a-server
Creates a new server. Returns preliminary information about the
server as well as an action that covers progress of creation.
Required body parameters (`body-m`):
* `:name` (string): Name of the server to create (must be unique
per project and a valid hostname as per RFC 1123)
* `:server_type` (string): ID or name of the server type this
server should be created with
* `:image` (string): ID or name of the image the server is created
from
Optional body parameters (`body-m`):
* `:start-after-create` (boolean): Start Server right after
creation. Defaults to true.
* `:ssh-keys` (vector): SSH key IDs or names which should be
injected into the server at creation time
* `:user-data` (string): Cloud-Init user data to use during server
creation. This field is limited to 32KiB.
* `:location` (string): ID or name of location to create server in.
* `:datacenter` (string): ID or name of datacenter to create server
in."
[token body-m]
(request http/post (api-url "servers")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 3}
change-server-name
"Change Name of a Server
https://docs.hetzner.cloud/#servers-change-name-of-a-server
Changes the name of a server.
Please note that server names must be unique per project and valid
hostnames as per RFC 1123 (i.e. may only contain letters, digits,
periods, and dashes).
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:name` (string): New name to set. Note: I have no idea why this
is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "servers" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 4}
delete-server
"Delete a Server
https://docs.hetzner.cloud/#servers-delete-a-server
Deletes a server. This immediately removes the server from your
account, and it is no longer accessible.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/delete (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 5}
get-server-metrics
"Get Metrics for a Server
https://docs.hetzner.cloud/#servers-get-metrics-for-a-server
Get Metrics for specified server.
You must specify the type of metric to get: cpu, disk or
network. You can also specify more than one type by comma
separation, e.g. cpu,disk.
Parameters:
* `id` (string): ID of the server
Required query parameters (`query-m`):
* `:type` (string): Type of metrics to get (cpu, disk, network)
* `:start` (string): Start of period to get Metrics for (in
ISO-8601 format)
* `:end` (string): End of period to get Metrics for (in ISO-8601
format)
Optional query parameters (`query-m`):
* `:step` (number): Resolution of results in seconds "
[token id query-m]
(request http/get (api-url "servers" id "metrics")
(http-opts {:token token :query-m query-m})))
;; -- Server Actions -----------------------------------------------------------
(defn ^{:api-category :server-actions
:order 0}
get-server-actions
"Get all Actions for a Server
https://docs.hetzner.cloud/#server-actions-get-all-actions-for-a-server
Returns all action objects for a server.
Parameters:
* `id` (string): ID of the server
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-server-actions token {}))
([token id query-m]
(request http/get (api-url "servers" id "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-actions
:order 1}
get-server-action
"Get a specific Action for a Server
https://docs.hetzner.cloud/#server-actions-get-a-specific-action-for-a-server
Returns a specific action object for a Server.
Parameters:
* `id` (string): ID of the server
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "servers" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 2}
power-on-server
"Power on a Server
https://docs.hetzner.cloud/#server-actions-power-on-a-server
Starts a server by turning its power on.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweron")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 3}
soft-reboot-server
"Soft-reboot a Server
https://docs.hetzner.cloud/#server-actions-soft-reboot-a-server
Reboots a server gracefully by sending an ACPI request. The server
operating system must support ACPI and react to the request,
otherwise the server will not reboot.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reboot")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 4}
reset-server
"Reset a Server
https://docs.hetzner.cloud/#server-actions-reset-a-server
Cuts power to a server and starts it again. This forcefully stops it
without giving the server operating system time to gracefully
stop. This may lead to data loss, it’s equivalent to pulling the
power cord and plugging it in again. Reset should only be used when
reboot does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 5}
shutdown-server
"Shutdown a Server
https://docs.hetzner.cloud/#server-actions-shutdown-a-server
Shuts down a server gracefully by sending an ACPI shutdown
request. The server operating system must support ACPI and react to
the request, otherwise the server will not shut down.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "shutdown")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 6}
power-off-server
"Power off a Server
https://docs.hetzner.cloud/#server-actions-power-off-a-server
Cuts power to the server. This forcefully stops it without giving
the server operating system time to gracefully stop. May lead to
data loss, equivalent to pulling the power cord. Power off should
only be used when shutdown does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweroff")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 7}
reset-server-root-password
"Reset root Password of a Server
https://docs.hetzner.cloud/#server-actions-reset-root-password-of-a-server
Resets the root password. Only works for Linux systems that are
running the qemu guest agent. Server must be powered on (state on)
in order for this operation to succeed.
This will generate a new password for this server and return it.
If this does not succeed you can use the rescue system to netboot
the server and manually change your server password by hand.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset_password")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 8}
enable-server-rescue-mode
"Enable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-enable-rescue-mode-for-a-server
Enable the Hetzner Rescue System for this server. The next time a
Server with enabled rescue mode boots it will start a special
minimal Linux distribution designed for repair and reinstall.
In case a server cannot boot on its own you can use this to access a
server’s disks.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Enabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:type` (string): Type of rescue system to boot (default:
linux64) Choices: linux64, linux32, freebsd64
* `:ssh-keys` (vector): Array of SSH key IDs which should be
injected into the rescue system. Only available for types: linux64
and linux32."
([token] (enable-server-rescue-mode token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_rescue")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 9}
disable-server-rescue-mode
"Disable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-disable-rescue-mode-for-a-server
Disables the Hetzner Rescue System for a server. This makes a server
start from its disks on next reboot.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Disabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_rescue")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 10}
create-server-image
"Create Image from a Server
https://docs.hetzner.cloud/#server-actions-create-image-from-a-server
Creates an image (snapshot) from a server by copying the contents of
its disks. This creates a snapshot of the current state of the disk
and copies it into an image. If the server is currently running you
must make sure that its disk content is consistent. Otherwise, the
created image may not be readable.
To make sure disk content is consistent, we recommend to shut down
the server prior to creating an image.
You can either create a backup image that is bound to the server and
therefore will be deleted when the server is deleted, or you can
create an snapshot image which is completely independent of the
server it was created from and will survive server deletion. Backup
images are only available when the backup option is enabled for the
Server. Snapshot images are billed on a per GB basis.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:description` (string): Description of the image. If you do not
set this we auto-generate one for you.
* `:type` (string): Type of image to create (default: snapshot)
Choices: snapshot, backup"
([token] (create-server-image token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "create_image")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 11}
rebuild-server-from-image
"Rebuild a Server from an Image
https://docs.hetzner.cloud/#server-actions-rebuild-a-server-from-an-image
Rebuilds a server overwriting its disk with the content of an image,
thereby destroying all data on the target server
The image can either be one you have created earlier (backup or
snapshot image) or it can be a completely fresh system image
provided by us. You can get a list of all available images with GET
/images.
Your server will automatically be powered off before the rebuild
command executes.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:image` (string): ID or name of image to rebuilt from."
[token id body-m]
(request http/post (api-url "servers" id "actions" "rebuild")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 12}
change-server-type
"Change the Type of a Server
https://docs.hetzner.cloud/#server-actions-change-the-type-of-a-server
Changes the type (Cores, RAM and disk sizes) of a server.
Server must be powered off for this command to succeed.
This copies the content of its disk, and starts it again.
You can only migrate to server types with the same storage_type and
equal or bigger disks. Shrinking disks is not possible as it might
destroy data.
If the disk gets upgraded, the server type can not be downgraded any
more. If you plan to downgrade the server type, set upgrade_disk to
false.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:server-type` (string): ID or name of server type the server
should migrate to
Optional body parameters (`body-m`):
* `:upgrade-disk` (boolean): If false, do not upgrade the
disk. This allows downgrading the server type later."
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_type")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 13}
enable-server-backup
"Enable and Configure Backups for a Server
https://docs.hetzner.cloud/#server-actions-enable-and-configure-backups-for-a-server
Enables and configures the automatic daily backup option for the
server. Enabling automatic backups will increase the price of the
server by 20%. In return, you will get seven slots where images of
type backup can be stored.
Backups are automatically created daily.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:backup-window` (string): Time window (UTC) in which the backup
will run. Choices: 22-02, 02-06, 06-10, 10-14, 14-18, 18-22"
([token] (enable-server-backup token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_backup")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 14}
disable-server-backup
"Disable Backups for a Server
https://docs.hetzner.cloud/#server-actions-disable-backups-for-a-server
Disables the automatic backup option and deletes all existing
Backups for a Server. No more additional charges for backups will be
made.
Caution: This immediately removes all existing backups for the
server!
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_backup")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 15}
attach-iso-to-server
"Attach an ISO to a Server
https://docs.hetzner.cloud/#server-actions-attach-an-iso-to-a-server
Attaches an ISO to a server. The Server will immediately see it as a
new disk. An already attached ISO will automatically be detached
before the new ISO is attached.
Servers with attached ISOs have a modified boot order: They will try
to boot from the ISO first before falling back to hard disk.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:iso` (string): ID or name of ISO to attach to the server as
listed in GET /isos"
[token id body-m]
(request http/post (api-url "servers" id "actions" "attach_iso")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 16}
detach-iso-from-server
"Detach an ISO from a Server
https://docs.hetzner.cloud/#server-actions-detach-an-iso-from-a-server
Detaches an ISO from a server. In case no ISO image is attached to
the server, the status of the returned action is immediately set to
success.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "detach_iso")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 17}
change-server-reverse-dns-entry
"Change reverse DNS entry for this server
https://docs.hetzner.cloud/#server-actions-change-reverse-dns-entry-for-this-server
Changes the hostname that will appear when getting the hostname
belonging to the primary IPs (ipv4 and ipv6) of this server.
Floating IPs assigned to the server are not affected by this.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:ip` (string): Primary IP address for which the reverse DNS
entry should be set.
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR
entry. Will reset to original value if null"
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 18}
change-server-protection
"Change protection for a Server
https://docs.hetzner.cloud/#server-actions-change-protection-for-a-server
Changes the protection configuration of the server.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the server from being
deleted (currently delete and rebuild attribute needs to have the
same value)
* `:rebuild` (boolean): If true, prevents the server from being
rebuilt` (currently delete and rebuild attribute needs to have the
same value)"
([token] (change-server-protection token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 19}
request-server-console
"Request Console for a Server
https://docs.hetzner.cloud/#server-actions-request-console-for-a-server
Requests credentials for remote access via vnc over websocket to
keyboard, monitor, and mouse for a server. The provided url is valid
for 1 minute, after this period a new url needs to be created to
connect to the server. How long the connection is open after the
initial connect is not subject to this timeout.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "request_console")
(http-opts {:token token})))
;; -- Floating IPs -------------------------------------------------------------
(defn ^{:api-category :floating-ips
:order 0}
get-floating-ips
"Get all Floating IPs
https://docs.hetzner.cloud/#floating-ips-get-all-floating-ips
Returns all floating ip objects."
([token] (get-floating-ips token {}))
([token query-m]
(request http/get (api-url "floating_ips")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :floating-ips
:order 1}
get-floating-ip
"Get a specific Floating IP
https://docs.hetzner.cloud/#floating-ips-get-a-specific-floating-ip
Returns a specific floating ip object.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/get (api-url "floating_ips" id) (http-opts {:token token})))
(defn ^{:api-category :floating-ips
:order 1}
create-floating-ip
"Create a Floating IP
https://docs.hetzner.cloud/#floating-ips-create-a-floating-ip
Creates a new Floating IP assigned to a server. If you want to
create a Floating IP that is not bound to a server, you need to
provide the home_location key instead of server. This can be either
the ID or the name of the location this IP shall be created in. Note
that a Floating IP can be assigned to a server in any location later
on. For optimal routing it is advised to use the Floating IP in the
same Location it was created in.
Required body parameters (`body-m`):
* `:type` (string): Floating IP type Choices: ipv4, ipv6
Optional body parameters (`body-m`):
* `:server` (number): Server to assign the Floating IP to
* `:home-location` (string): Home location (routing is optimized
for that location). Only optional if server argument is passed.
* `:description` (string)"
[token body-m]
(request http/post (api-url "floating_ips")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 2}
change-floating-ip-description
"Change description of a Floating IP
https://docs.hetzner.cloud/#floating-ips-change-description-of-a-floating-ip
Changes the description of a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:description` (string): New Description to set. Note: I have no
idea why this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "floating_ips" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 3}
delete-floating-ip
"Delete a Floating IP
https://docs.hetzner.cloud/#floating-ips-delete-a-floating-ip
Deletes a Floating IP. If it is currently assigned to a server it
will automatically get unassigned.
Parameters:
* `id`: ID of the Floating IP"
[token id]
(request http/delete (api-url "floating_ips" id) (http-opts {:token token})))
;; -- Floating IP Actions ------------------------------------------------------
(defn ^{:api-category :floating-ip-actions
:order 0}
get-floating-ip-actions
"Get all Actions for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-all-actions-for-a-floating-ip
Returns all action objects for a Floating IP. You can sort the
results by using the sort URI parameter.
Parameters:
* `id` (string): ID of the Floating IP
Required query parameters (`query_m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "floating_ips" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :floating-ip-actions
:order 1}
get-floating-ip-action
"Get an Action for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-an-action-for-a-floating-ip
Returns a specific action object for a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "floating_ips" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions} assign-floating-ip-to-server
"Assign a Floating IP to a Server
https://docs.hetzner.cloud/#floating-ip-actions-assign-a-floating-ip-to-a-server
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:server` (number): ID of the server the Floating IP shall be
assigned to"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "assign")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 2}
unassign-floating-ip
"Unassign a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-unassign-a-floating-ip
Unassigns a Floating IP, resulting in it being unreachable. You may
assign it to a server again at a later time.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/post (api-url "floating_ips" id "actions" "unassign")
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions
:order 3}
change-floating-ip-reverse-dns-entry
"Change reverse DNS entry for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-change-reverse-dns-entry-for-a-floating-ip
Changes the hostname that will appear when getting the hostname
belonging to this Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:ip` (string): IP address for which to set the reverse DNS entry
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR entry,
will reset to original default value if null"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 4}
change-floating-ip-protection
"Change protection
https://docs.hetzner.cloud/#floating-ip-actions-change-protection
Changes the protection configuration of the Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the Floating IP from being
deleted. Note: I have no idea why this is optional in the official
Hetzner API docs."
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_protection")
(http-opts {:token token :body-m body-m})))
;; -- SSH Keys -----------------------------------------------------------------
(defn ^{:api-category :ssh-keys
:order 0}
get-ssh-keys
"Get all SSH keys
https://docs.hetzner.cloud/#ssh-keys-get-all-ssh-keys
Returns all SSH key objects.
Optional query parameters (`query_m`):
* `:name` (string): Can be used to filter SSH keys by their
name. The response will only contain the SSH key matching the
specified name.
* `:fingerprint` (string): Can be used to filter SSH keys by their
fingerprint. The response will only contain the SSH key matching the
specified fingerprint."
([token] (get-ssh-keys token {}))
([token query-m]
(request http/get (api-url "ssh_keys")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :ssh-keys
:order 1}
get-ssh-key
"Get an SSH key
https://docs.hetzner.cloud/#ssh-keys-get-an-ssh-key
Returns a specific SSH key object.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/get (api-url "ssh_keys" id) (http-opts {:token token})))
(defn ^{:api-category :ssh-keys
:order 2}
create-ssh-key
"Create an SSH key
https://docs.hetzner.cloud/#ssh-keys-create-an-ssh-key
Creates a new SSH key with the given name and public_key. Once an
SSH key is created, it can be used in other calls such as creating
servers.
Required body parameters (`body-m`):
* `:name` (string): Note: Seems to be missing in API docs.
* `:public-key` (string): Note: Seems to be missing in API docs."
[token body-m]
(request http/post (api-url "ssh_keys")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 3}
change-ssh-key-name
"Change the name of an SSH key.
https://docs.hetzner.cloud/#ssh-keys-change-the-name-of-an-ssh-key
Parameters:
* `id` (string): ID of the SSH key
Optional body parameters (`body-m`):
* `:name` (string): New name Name to set. Note: I have no idea why
this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "ssh_keys" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 4}
delete-ssh-key
"Delete an SSH key
https://docs.hetzner.cloud/#ssh-keys-delete-an-ssh-key
Deletes an SSH key. It cannot be used anymore.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/delete (api-url "ssh_keys" id) (http-opts {:token token})))
;; -- Server Types -------------------------------------------------------------
(defn ^{:api-category :server-types
:order 0}
get-server-types
"Get all Server Types
https://docs.hetzner.cloud/#server-types-get-all-server-types
Gets all server type objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter server types by their
name. The response will only contain the server type matching the
specified name."
([token] (get-server-types {}))
([token query-m]
(request http/get (api-url "server_types")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-types
:order 1}
get-server-type
"Get a Server Type
https://docs.hetzner.cloud/#server-types-get-a-server-type
Gets a specific server type object.
Parameters:
* `id` (string): ID of server type"
[token id]
(request http/get (api-url "server_types" id) (http-opts {:token token})))
;; -- Locations ----------------------------------------------------------------
(defn ^{:api-category :locations
:order 0}
get-locations
"Get all Locations
https://docs.hetzner.cloud/#locations-get-all-locations
Returns all location objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter locations by their
name. The response will only contain the location matching the
specified name."
([token] (get-locations token {}))
([token query-m]
(request http/get (api-url "locations")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :locations
:order 1}
get-location
"Get a Location
https://docs.hetzner.cloud/#locations-get-a-location
Returns a specific location object.
Parameters:
* `id` (string): ID of location"
[token id]
(request http/get (api-url "locations" id) (http-opts {:token token})))
;; -- Datacenters --------------------------------------------------------------
(defn ^{:api-category :datacenters
:order 0}
get-datacenters
"Get all Datacenters
https://docs.hetzner.cloud/#datacenters-get-all-datacenters
Returns all datacenter objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter datacenters by their
name. The response will only contain the datacenter matching the
specified name. When the name does not match the datacenter name
format, an invalid_input error is returned."
([token] (get-datacenters token {}))
([token query-m]
(request http/get (api-url "datacenters")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :datacenters
:order 1}
get-datacenter
"Get a Datacenter
https://docs.hetzner.cloud/#datacenters-get-a-datacenter
Returns a specific datacenter object.
Parameters:
* `id` (string): ID of datacenter"
[token id]
(request http/get (api-url "datacenters" id) (http-opts {:token token})))
;; -- Images -------------------------------------------------------------------
(defn ^{:api-category :images
:order 0}
get-images
"Get all Images
https://docs.hetzner.cloud/#images-get-all-images
Returns all image objects. You can select specific image types only
and sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc name name:asc name:desc created
created:asc created:desc
* `:type` (vector of strings): Can be used multiple times.
Choices: system snapshot backup
* `:bound-to` (string): Can be used multiple times. Server Id
linked to the image. Only available for images of type backup
* `:name` (string): Can be used to filter images by their name. The
response will only contain the image matching the specified name."
([token] (get-images token {}))
([token query-m]
(request http/get (api-url "images")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :images
:order 1}
get-image
"Get an Image
https://docs.hetzner.cloud/#images-get-an-image
Returns a specific image object.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/get (api-url "images" id) (http-opts {:token token})))
(defn ^{:api-category :images
:order 2}
update-image
"Update an Image
https://docs.hetzner.cloud/#images-update-an-image
Updates the Image. You may change the description or convert a
Backup image to a Snapshot Image. Only images of type snapshot and
backup can be updated.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:description` (string): New description of Image
* `:type` (string): Destination image type to convert to
Choices: snapshot"
([token] (update-image token {}))
([token id body-m]
(request http/put (api-url "images" id)
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :images
:order 3}
delete-image
"Delete an Image
https://docs.hetzner.cloud/#images-delete-an-image
Deletes an Image. Only images of type snapshot and backup can be deleted.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/delete (api-url "images" id) (http-opts {:token token})))
;; -- Image Actions ------------------------------------------------------------
(defn ^{:api-category :image-actions
:order 0}
get-image-actions
"Get all Actions for an Image
https://docs.hetzner.cloud/#image-actions-get-all-actions-for-an-image
Returns all action objects for an image. You can sort the results by
using the sort URI parameter.
Parameters:
* `id` (string): ID of the Image
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "images" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :image-actions
:order 1}
get-image-action
"Get an Action for an Image
https://docs.hetzner.cloud/#image-actions-get-an-action-for-an-image
Returns a specific action object for an image.
Parameters:
* `id` (string): ID of the image
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "images" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :image-actions
:order 2}
change-image-protection
"Change protection for an Image
https://docs.hetzner.cloud/#image-actions-change-protection-for-an-image
Changes the protection configuration of the image. Can only be used
on snapshots.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the snapshot from being deleted"
([token] (change-image-protection token {}))
([token id body-m]
(request http/post (api-url "images" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
;; -- ISOs ---------------------------------------------------------------------
(defn ^{:api-category :isos
:order 0}
get-isos
"Get all ISOs
https://docs.hetzner.cloud/#isos-get-all-isos
Returns all available iso objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter isos by their name. The
response will only contain the iso matching the specified name."
([token] (get-isos token {}))
([token query-m]
(request http/get (api-url "isos") (http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :isos
:order 1}
get-iso
"Get an ISO
https://docs.hetzner.cloud/#isos-get-an-iso
Returns a specific iso object.
Parameters:
* `id` (string): ID of the ISO"
[token id]
(request http/get (api-url "isos" id) (http-opts {:token token})))
;; -- Pricing ------------------------------------------------------------------
(defn ^{:api-category :pricing
:order 0}
get-prices
"Get all prices
https://docs.hetzner.cloud/#pricing-get-all-prices
Returns prices for all resources available on the platform. VAT and
currency of the project owner are used for calculations.
Both net and gross prices are included in the response."
[token]
(request http/get (api-url "pricing") (http-opts {:token token})))
| true | (ns hcloud.core
"Hetzner Cloud API functions.
## Auth Token
All calls to the Hetzner API must be authenticated. For that, you
need an Authentication Token which you can generate online in your
Hetzner Cloud Account. The token is a string and could look like
this:
```
(def my-token \"PI:PASSWORD:<PASSWORD>END_PI\")
```
Each function takes this token as its first argument. An example
call to `get-prices` would look like this:
```
(get-prices my-token)
```
## IDs
Furthermore, some functions take an `id` as an argument. The `id` is
a string and refers to the resource which the API call is referring
to (e.g., a server). An example call to `get-server` would look like
this:
```
(get-server my-token \"SERVER-ID-123\")
```
## Query Parameters
Some functions take query string parameters. These are appended to
the API url, i.e. in the url
`https://api.hetzner.cloud/v1/servers?name=cx11`, there is the query
parameter `name` with the value of `cx11`.
In our functions, these query string parameters can be set in the
`query-m` map. For example, the API call above is equivalent to this
function call:
```
(get-servers my-token {:name \"cx11\"})
```
Pagination is also handled via the query parameters (and therefore
the `query-m` map). Say we want to retrieve page 2 of our servers:
```
(get-servers my-token {:page 2})
```
### An important note on kebab-case
Note that these are converted from kebab-cased keywords to
snake-cased strings. So if the Hetzner API would be expecting a
query parameter called \"foo_bar\", we would set it by providing
`{:foo-bar \"some-value\"}` in our map. Dashes are converted to
underscores.
This is also true for the replies from the Hetzner API, this time
the other way round: The keys are snake-cased strings and will be
converted to kebab-cased keywords. So if the reply json has a key
\"time_series\", you'll find it in a Clojure map under the value
`:time-series`.
## Body Parameters
Some functions take (json) body parameters. In our functions, these
can be set in the `body-m` map. Let's say we want to create a server
with the name \"HAL\", this is how we would do it:
```
(create-server my-token {:name \"HAL\"})
```
Note that keywords will be converted from kebab-case to snake-case
again, so if you would also want to set the `start_after_create`
value, you would do this:
```
(create-server my-token {:name \"HAL\"
:start-after-create true})
```
## Metadata of public functions
Public functions in this namespace have two keys in their metadata:
`:api-category` and `:order`. These are used to auto-generate docs
in the README (check `dev/readme.clj`). The idea is to have the
documentation of the functions in the same order as in the [Hetzner
docs](https://docs.hetzner.cloud). Therefore `:api-category` refers
to the endpoint (and the title of the section in the docs) and
`:order` is the position at which it appears in the docs.
If you didn't understand any of this, don't worry. As long as you
understand the README, you're fine!"
(:require [camel-snake-kebab.core :as csk]
[camel-snake-kebab.extras :as csk.extras]
[cheshire.core :as cheshire]
[clj-http.client :as http]
[clojure.string :as str]))
;; -- Key Transformations ------------------------------------------------------
(defn- kebab-case-keys [m]
(csk.extras/transform-keys csk/->kebab-case-keyword m))
(defn- snake-case-keys [m]
(csk.extras/transform-keys csk/->snake_case_keyword m))
(defn- map->json-str [m]
(cheshire/generate-string (snake-case-keys m)))
(defn- json-str->map [s]
(kebab-case-keys (cheshire/parse-string s)))
;; -- General Stuff ------------------------------------------------------------
(def ^:private ^:const hetzner-api-url
"The Hetzner API Url."
"https://api.hetzner.cloud/v1")
(defn- api-url [& paths]
(str/join (interpose "/" (cons hetzner-api-url paths))))
(defn- http-opts
[{:keys [token body-m query-m]}]
(cond-> {:accept :json
:as :json
:content-type :json
;; this will add an "Authorization" header with the string
;; "Bearer TOKEN"
:oauth-token token}
(not (empty? body-m)) (assoc :body (map->json-str body-m))
(not (empty? query-m)) (assoc :query-params query-m)))
;; -- Exception Handling -------------------------------------------------------
(defn- handle-exception
"Handle exceptions which are usually raised by clj-http.
The `:body` of the response is parsed (the API returns a JSON
string), keys are converted to kebab-cased keywords. Also, the
`:http-status` of the request is `assoc`ed to the map.
Example error data, note that the `:error` key is provided by the
API response. As the API response body is merged as-is into the map,
in theory other keys besides `:error` could be there:
```clojure
{:error
{:message \"invalid input in field 'server_type'\",
:code \"invalid_input\",
:details
{:fields
[{:name \"server_type\",
:messages [\"Missing data for required field.\"]}]}},
:http-status 422}
```"
[exception]
(let [exception-data (ex-data exception)]
(merge (json-str->map (:body exception-data))
{:http-status (:status exception-data)})))
;; -- Request ------------------------------------------------------------------
(defn- request
"Do a HTTP request with `http-fn` (most likely `clj-http`), convert
the keys of the body to kebab-case, catch exceptions."
[http-fn & args]
(try
(let [result (apply http-fn args)]
(kebab-case-keys (:body result)))
(catch Exception e
(handle-exception e))))
;; -- Actions ------------------------------------------------------------------
(defn ^{:api-category :actions
:order 0}
get-actions
"List all Actions
https://docs.hetzner.cloud/#actions-list-all-actions
Returns all action objects. You can select specific actions only and
sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-actions token {}))
([token query-m]
(request http/get (api-url "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :actions
:order 1}
get-action
"Get one Action
https://docs.hetzner.cloud/#actions-get-one-action
Returns a specific action object.
Parameters:
* `id` (string): ID of the action"
[token id]
(request http/get (api-url "actions" id) (http-opts {:token token})))
;; -- Servers ------------------------------------------------------------------
(defn ^{:api-category :servers
:order 0}
get-servers
"Get all Servers
https://docs.hetzner.cloud/#servers-get-all-servers
Returns all existing server objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter servers by their
name. The response will only contain the server matching the
specified name."
([token] (get-servers token {}))
([token query-m]
(request http/get (api-url "servers")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :servers
:order 1}
get-server
"Get a Server
https://docs.hetzner.cloud/#servers-get-a-server
Returns a specific server object. The server must exist inside the
project.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/get (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 2}
create-server
"Create a Server
https://docs.hetzner.cloud/#servers-create-a-server
Creates a new server. Returns preliminary information about the
server as well as an action that covers progress of creation.
Required body parameters (`body-m`):
* `:name` (string): Name of the server to create (must be unique
per project and a valid hostname as per RFC 1123)
* `:server_type` (string): ID or name of the server type this
server should be created with
* `:image` (string): ID or name of the image the server is created
from
Optional body parameters (`body-m`):
* `:start-after-create` (boolean): Start Server right after
creation. Defaults to true.
* `:ssh-keys` (vector): SSH key IDs or names which should be
injected into the server at creation time
* `:user-data` (string): Cloud-Init user data to use during server
creation. This field is limited to 32KiB.
* `:location` (string): ID or name of location to create server in.
* `:datacenter` (string): ID or name of datacenter to create server
in."
[token body-m]
(request http/post (api-url "servers")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 3}
change-server-name
"Change Name of a Server
https://docs.hetzner.cloud/#servers-change-name-of-a-server
Changes the name of a server.
Please note that server names must be unique per project and valid
hostnames as per RFC 1123 (i.e. may only contain letters, digits,
periods, and dashes).
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:name` (string): New name to set. Note: I have no idea why this
is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "servers" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :servers
:order 4}
delete-server
"Delete a Server
https://docs.hetzner.cloud/#servers-delete-a-server
Deletes a server. This immediately removes the server from your
account, and it is no longer accessible.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/delete (api-url "servers" id) (http-opts {:token token})))
(defn ^{:api-category :servers
:order 5}
get-server-metrics
"Get Metrics for a Server
https://docs.hetzner.cloud/#servers-get-metrics-for-a-server
Get Metrics for specified server.
You must specify the type of metric to get: cpu, disk or
network. You can also specify more than one type by comma
separation, e.g. cpu,disk.
Parameters:
* `id` (string): ID of the server
Required query parameters (`query-m`):
* `:type` (string): Type of metrics to get (cpu, disk, network)
* `:start` (string): Start of period to get Metrics for (in
ISO-8601 format)
* `:end` (string): End of period to get Metrics for (in ISO-8601
format)
Optional query parameters (`query-m`):
* `:step` (number): Resolution of results in seconds "
[token id query-m]
(request http/get (api-url "servers" id "metrics")
(http-opts {:token token :query-m query-m})))
;; -- Server Actions -----------------------------------------------------------
(defn ^{:api-category :server-actions
:order 0}
get-server-actions
"Get all Actions for a Server
https://docs.hetzner.cloud/#server-actions-get-all-actions-for-a-server
Returns all action objects for a server.
Parameters:
* `id` (string): ID of the server
Optional query parameters (`query-m`):
* `:status` (vector of strings): Can be used multiple
times. Response will have only actions with specified statuses.
Choices: running success error
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
([token] (get-server-actions token {}))
([token id query-m]
(request http/get (api-url "servers" id "actions")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-actions
:order 1}
get-server-action
"Get a specific Action for a Server
https://docs.hetzner.cloud/#server-actions-get-a-specific-action-for-a-server
Returns a specific action object for a Server.
Parameters:
* `id` (string): ID of the server
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "servers" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 2}
power-on-server
"Power on a Server
https://docs.hetzner.cloud/#server-actions-power-on-a-server
Starts a server by turning its power on.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweron")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 3}
soft-reboot-server
"Soft-reboot a Server
https://docs.hetzner.cloud/#server-actions-soft-reboot-a-server
Reboots a server gracefully by sending an ACPI request. The server
operating system must support ACPI and react to the request,
otherwise the server will not reboot.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reboot")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 4}
reset-server
"Reset a Server
https://docs.hetzner.cloud/#server-actions-reset-a-server
Cuts power to a server and starts it again. This forcefully stops it
without giving the server operating system time to gracefully
stop. This may lead to data loss, it’s equivalent to pulling the
power cord and plugging it in again. Reset should only be used when
reboot does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 5}
shutdown-server
"Shutdown a Server
https://docs.hetzner.cloud/#server-actions-shutdown-a-server
Shuts down a server gracefully by sending an ACPI shutdown
request. The server operating system must support ACPI and react to
the request, otherwise the server will not shut down.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "shutdown")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 6}
power-off-server
"Power off a Server
https://docs.hetzner.cloud/#server-actions-power-off-a-server
Cuts power to the server. This forcefully stops it without giving
the server operating system time to gracefully stop. May lead to
data loss, equivalent to pulling the power cord. Power off should
only be used when shutdown does not work.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "poweroff")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 7}
reset-server-root-password
"Reset root Password of a Server
https://docs.hetzner.cloud/#server-actions-reset-root-password-of-a-server
Resets the root password. Only works for Linux systems that are
running the qemu guest agent. Server must be powered on (state on)
in order for this operation to succeed.
This will generate a new password for this server and return it.
If this does not succeed you can use the rescue system to netboot
the server and manually change your server password by hand.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "reset_password")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 8}
enable-server-rescue-mode
"Enable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-enable-rescue-mode-for-a-server
Enable the Hetzner Rescue System for this server. The next time a
Server with enabled rescue mode boots it will start a special
minimal Linux distribution designed for repair and reinstall.
In case a server cannot boot on its own you can use this to access a
server’s disks.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Enabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:type` (string): Type of rescue system to boot (default:
linux64) Choices: linux64, linux32, freebsd64
* `:ssh-keys` (vector): Array of SSH key IDs which should be
injected into the rescue system. Only available for types: linux64
and linux32."
([token] (enable-server-rescue-mode token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_rescue")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 9}
disable-server-rescue-mode
"Disable Rescue Mode for a Server
https://docs.hetzner.cloud/#server-actions-disable-rescue-mode-for-a-server
Disables the Hetzner Rescue System for a server. This makes a server
start from its disks on next reboot.
Rescue Mode is automatically disabled when you first boot into it or
if you do not use it for 60 minutes.
Disabling rescue mode will not reboot your server — you will have to
do this yourself.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_rescue")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 10}
create-server-image
"Create Image from a Server
https://docs.hetzner.cloud/#server-actions-create-image-from-a-server
Creates an image (snapshot) from a server by copying the contents of
its disks. This creates a snapshot of the current state of the disk
and copies it into an image. If the server is currently running you
must make sure that its disk content is consistent. Otherwise, the
created image may not be readable.
To make sure disk content is consistent, we recommend to shut down
the server prior to creating an image.
You can either create a backup image that is bound to the server and
therefore will be deleted when the server is deleted, or you can
create an snapshot image which is completely independent of the
server it was created from and will survive server deletion. Backup
images are only available when the backup option is enabled for the
Server. Snapshot images are billed on a per GB basis.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:description` (string): Description of the image. If you do not
set this we auto-generate one for you.
* `:type` (string): Type of image to create (default: snapshot)
Choices: snapshot, backup"
([token] (create-server-image token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "create_image")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 11}
rebuild-server-from-image
"Rebuild a Server from an Image
https://docs.hetzner.cloud/#server-actions-rebuild-a-server-from-an-image
Rebuilds a server overwriting its disk with the content of an image,
thereby destroying all data on the target server
The image can either be one you have created earlier (backup or
snapshot image) or it can be a completely fresh system image
provided by us. You can get a list of all available images with GET
/images.
Your server will automatically be powered off before the rebuild
command executes.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:image` (string): ID or name of image to rebuilt from."
[token id body-m]
(request http/post (api-url "servers" id "actions" "rebuild")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 12}
change-server-type
"Change the Type of a Server
https://docs.hetzner.cloud/#server-actions-change-the-type-of-a-server
Changes the type (Cores, RAM and disk sizes) of a server.
Server must be powered off for this command to succeed.
This copies the content of its disk, and starts it again.
You can only migrate to server types with the same storage_type and
equal or bigger disks. Shrinking disks is not possible as it might
destroy data.
If the disk gets upgraded, the server type can not be downgraded any
more. If you plan to downgrade the server type, set upgrade_disk to
false.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:server-type` (string): ID or name of server type the server
should migrate to
Optional body parameters (`body-m`):
* `:upgrade-disk` (boolean): If false, do not upgrade the
disk. This allows downgrading the server type later."
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_type")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 13}
enable-server-backup
"Enable and Configure Backups for a Server
https://docs.hetzner.cloud/#server-actions-enable-and-configure-backups-for-a-server
Enables and configures the automatic daily backup option for the
server. Enabling automatic backups will increase the price of the
server by 20%. In return, you will get seven slots where images of
type backup can be stored.
Backups are automatically created daily.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:backup-window` (string): Time window (UTC) in which the backup
will run. Choices: 22-02, 02-06, 06-10, 10-14, 14-18, 18-22"
([token] (enable-server-backup token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "enable_backup")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 14}
disable-server-backup
"Disable Backups for a Server
https://docs.hetzner.cloud/#server-actions-disable-backups-for-a-server
Disables the automatic backup option and deletes all existing
Backups for a Server. No more additional charges for backups will be
made.
Caution: This immediately removes all existing backups for the
server!
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "disable_backup")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 15}
attach-iso-to-server
"Attach an ISO to a Server
https://docs.hetzner.cloud/#server-actions-attach-an-iso-to-a-server
Attaches an ISO to a server. The Server will immediately see it as a
new disk. An already attached ISO will automatically be detached
before the new ISO is attached.
Servers with attached ISOs have a modified boot order: They will try
to boot from the ISO first before falling back to hard disk.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:iso` (string): ID or name of ISO to attach to the server as
listed in GET /isos"
[token id body-m]
(request http/post (api-url "servers" id "actions" "attach_iso")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 16}
detach-iso-from-server
"Detach an ISO from a Server
https://docs.hetzner.cloud/#server-actions-detach-an-iso-from-a-server
Detaches an ISO from a server. In case no ISO image is attached to
the server, the status of the returned action is immediately set to
success.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "detach_iso")
(http-opts {:token token})))
(defn ^{:api-category :server-actions
:order 17}
change-server-reverse-dns-entry
"Change reverse DNS entry for this server
https://docs.hetzner.cloud/#server-actions-change-reverse-dns-entry-for-this-server
Changes the hostname that will appear when getting the hostname
belonging to the primary IPs (ipv4 and ipv6) of this server.
Floating IPs assigned to the server are not affected by this.
Parameters:
* `id` (string): ID of the server
Required body parameters (`body-m`):
* `:ip` (string): Primary IP address for which the reverse DNS
entry should be set.
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR
entry. Will reset to original value if null"
[token id body-m]
(request http/post (api-url "servers" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :server-actions
:order 18}
change-server-protection
"Change protection for a Server
https://docs.hetzner.cloud/#server-actions-change-protection-for-a-server
Changes the protection configuration of the server.
Parameters:
* `id` (string): ID of the server
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the server from being
deleted (currently delete and rebuild attribute needs to have the
same value)
* `:rebuild` (boolean): If true, prevents the server from being
rebuilt` (currently delete and rebuild attribute needs to have the
same value)"
([token] (change-server-protection token {}))
([token id body-m]
(request http/post (api-url "servers" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :server-actions
:order 19}
request-server-console
"Request Console for a Server
https://docs.hetzner.cloud/#server-actions-request-console-for-a-server
Requests credentials for remote access via vnc over websocket to
keyboard, monitor, and mouse for a server. The provided url is valid
for 1 minute, after this period a new url needs to be created to
connect to the server. How long the connection is open after the
initial connect is not subject to this timeout.
Parameters:
* `id` (string): ID of the server"
[token id]
(request http/post (api-url "servers" id "actions" "request_console")
(http-opts {:token token})))
;; -- Floating IPs -------------------------------------------------------------
(defn ^{:api-category :floating-ips
:order 0}
get-floating-ips
"Get all Floating IPs
https://docs.hetzner.cloud/#floating-ips-get-all-floating-ips
Returns all floating ip objects."
([token] (get-floating-ips token {}))
([token query-m]
(request http/get (api-url "floating_ips")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :floating-ips
:order 1}
get-floating-ip
"Get a specific Floating IP
https://docs.hetzner.cloud/#floating-ips-get-a-specific-floating-ip
Returns a specific floating ip object.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/get (api-url "floating_ips" id) (http-opts {:token token})))
(defn ^{:api-category :floating-ips
:order 1}
create-floating-ip
"Create a Floating IP
https://docs.hetzner.cloud/#floating-ips-create-a-floating-ip
Creates a new Floating IP assigned to a server. If you want to
create a Floating IP that is not bound to a server, you need to
provide the home_location key instead of server. This can be either
the ID or the name of the location this IP shall be created in. Note
that a Floating IP can be assigned to a server in any location later
on. For optimal routing it is advised to use the Floating IP in the
same Location it was created in.
Required body parameters (`body-m`):
* `:type` (string): Floating IP type Choices: ipv4, ipv6
Optional body parameters (`body-m`):
* `:server` (number): Server to assign the Floating IP to
* `:home-location` (string): Home location (routing is optimized
for that location). Only optional if server argument is passed.
* `:description` (string)"
[token body-m]
(request http/post (api-url "floating_ips")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 2}
change-floating-ip-description
"Change description of a Floating IP
https://docs.hetzner.cloud/#floating-ips-change-description-of-a-floating-ip
Changes the description of a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:description` (string): New Description to set. Note: I have no
idea why this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "floating_ips" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ips
:order 3}
delete-floating-ip
"Delete a Floating IP
https://docs.hetzner.cloud/#floating-ips-delete-a-floating-ip
Deletes a Floating IP. If it is currently assigned to a server it
will automatically get unassigned.
Parameters:
* `id`: ID of the Floating IP"
[token id]
(request http/delete (api-url "floating_ips" id) (http-opts {:token token})))
;; -- Floating IP Actions ------------------------------------------------------
(defn ^{:api-category :floating-ip-actions
:order 0}
get-floating-ip-actions
"Get all Actions for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-all-actions-for-a-floating-ip
Returns all action objects for a Floating IP. You can sort the
results by using the sort URI parameter.
Parameters:
* `id` (string): ID of the Floating IP
Required query parameters (`query_m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "floating_ips" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :floating-ip-actions
:order 1}
get-floating-ip-action
"Get an Action for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-get-an-action-for-a-floating-ip
Returns a specific action object for a Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "floating_ips" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions} assign-floating-ip-to-server
"Assign a Floating IP to a Server
https://docs.hetzner.cloud/#floating-ip-actions-assign-a-floating-ip-to-a-server
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:server` (number): ID of the server the Floating IP shall be
assigned to"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "assign")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 2}
unassign-floating-ip
"Unassign a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-unassign-a-floating-ip
Unassigns a Floating IP, resulting in it being unreachable. You may
assign it to a server again at a later time.
Parameters:
* `id` (string): ID of the Floating IP"
[token id]
(request http/post (api-url "floating_ips" id "actions" "unassign")
(http-opts {:token token})))
(defn ^{:api-category :floating-ip-actions
:order 3}
change-floating-ip-reverse-dns-entry
"Change reverse DNS entry for a Floating IP
https://docs.hetzner.cloud/#floating-ip-actions-change-reverse-dns-entry-for-a-floating-ip
Changes the hostname that will appear when getting the hostname
belonging to this Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Required body parameters (`body-m`):
* `:ip` (string): IP address for which to set the reverse DNS entry
* `:dns-ptr` (string): Hostname to set as a reverse DNS PTR entry,
will reset to original default value if null"
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_dns_ptr")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :floating-ip-actions
:order 4}
change-floating-ip-protection
"Change protection
https://docs.hetzner.cloud/#floating-ip-actions-change-protection
Changes the protection configuration of the Floating IP.
Parameters:
* `id` (string): ID of the Floating IP
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the Floating IP from being
deleted. Note: I have no idea why this is optional in the official
Hetzner API docs."
[token id body-m]
(request http/post (api-url "floating_ips" id "actions" "change_protection")
(http-opts {:token token :body-m body-m})))
;; -- SSH Keys -----------------------------------------------------------------
(defn ^{:api-category :ssh-keys
:order 0}
get-ssh-keys
"Get all SSH keys
https://docs.hetzner.cloud/#ssh-keys-get-all-ssh-keys
Returns all SSH key objects.
Optional query parameters (`query_m`):
* `:name` (string): Can be used to filter SSH keys by their
name. The response will only contain the SSH key matching the
specified name.
* `:fingerprint` (string): Can be used to filter SSH keys by their
fingerprint. The response will only contain the SSH key matching the
specified fingerprint."
([token] (get-ssh-keys token {}))
([token query-m]
(request http/get (api-url "ssh_keys")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :ssh-keys
:order 1}
get-ssh-key
"Get an SSH key
https://docs.hetzner.cloud/#ssh-keys-get-an-ssh-key
Returns a specific SSH key object.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/get (api-url "ssh_keys" id) (http-opts {:token token})))
(defn ^{:api-category :ssh-keys
:order 2}
create-ssh-key
"Create an SSH key
https://docs.hetzner.cloud/#ssh-keys-create-an-ssh-key
Creates a new SSH key with the given name and public_key. Once an
SSH key is created, it can be used in other calls such as creating
servers.
Required body parameters (`body-m`):
* `:name` (string): Note: Seems to be missing in API docs.
* `:public-key` (string): Note: Seems to be missing in API docs."
[token body-m]
(request http/post (api-url "ssh_keys")
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 3}
change-ssh-key-name
"Change the name of an SSH key.
https://docs.hetzner.cloud/#ssh-keys-change-the-name-of-an-ssh-key
Parameters:
* `id` (string): ID of the SSH key
Optional body parameters (`body-m`):
* `:name` (string): New name Name to set. Note: I have no idea why
this is optional in the official Hetzner API docs."
[token id body-m]
(request http/put (api-url "ssh_keys" id)
(http-opts {:token token :body-m body-m})))
(defn ^{:api-category :ssh-keys
:order 4}
delete-ssh-key
"Delete an SSH key
https://docs.hetzner.cloud/#ssh-keys-delete-an-ssh-key
Deletes an SSH key. It cannot be used anymore.
Parameters:
* `id` (string): ID of the SSH key"
[token id]
(request http/delete (api-url "ssh_keys" id) (http-opts {:token token})))
;; -- Server Types -------------------------------------------------------------
(defn ^{:api-category :server-types
:order 0}
get-server-types
"Get all Server Types
https://docs.hetzner.cloud/#server-types-get-all-server-types
Gets all server type objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter server types by their
name. The response will only contain the server type matching the
specified name."
([token] (get-server-types {}))
([token query-m]
(request http/get (api-url "server_types")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :server-types
:order 1}
get-server-type
"Get a Server Type
https://docs.hetzner.cloud/#server-types-get-a-server-type
Gets a specific server type object.
Parameters:
* `id` (string): ID of server type"
[token id]
(request http/get (api-url "server_types" id) (http-opts {:token token})))
;; -- Locations ----------------------------------------------------------------
(defn ^{:api-category :locations
:order 0}
get-locations
"Get all Locations
https://docs.hetzner.cloud/#locations-get-all-locations
Returns all location objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter locations by their
name. The response will only contain the location matching the
specified name."
([token] (get-locations token {}))
([token query-m]
(request http/get (api-url "locations")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :locations
:order 1}
get-location
"Get a Location
https://docs.hetzner.cloud/#locations-get-a-location
Returns a specific location object.
Parameters:
* `id` (string): ID of location"
[token id]
(request http/get (api-url "locations" id) (http-opts {:token token})))
;; -- Datacenters --------------------------------------------------------------
(defn ^{:api-category :datacenters
:order 0}
get-datacenters
"Get all Datacenters
https://docs.hetzner.cloud/#datacenters-get-all-datacenters
Returns all datacenter objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter datacenters by their
name. The response will only contain the datacenter matching the
specified name. When the name does not match the datacenter name
format, an invalid_input error is returned."
([token] (get-datacenters token {}))
([token query-m]
(request http/get (api-url "datacenters")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :datacenters
:order 1}
get-datacenter
"Get a Datacenter
https://docs.hetzner.cloud/#datacenters-get-a-datacenter
Returns a specific datacenter object.
Parameters:
* `id` (string): ID of datacenter"
[token id]
(request http/get (api-url "datacenters" id) (http-opts {:token token})))
;; -- Images -------------------------------------------------------------------
(defn ^{:api-category :images
:order 0}
get-images
"Get all Images
https://docs.hetzner.cloud/#images-get-all-images
Returns all image objects. You can select specific image types only
and sort the results by using URI parameters.
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc name name:asc name:desc created
created:asc created:desc
* `:type` (vector of strings): Can be used multiple times.
Choices: system snapshot backup
* `:bound-to` (string): Can be used multiple times. Server Id
linked to the image. Only available for images of type backup
* `:name` (string): Can be used to filter images by their name. The
response will only contain the image matching the specified name."
([token] (get-images token {}))
([token query-m]
(request http/get (api-url "images")
(http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :images
:order 1}
get-image
"Get an Image
https://docs.hetzner.cloud/#images-get-an-image
Returns a specific image object.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/get (api-url "images" id) (http-opts {:token token})))
(defn ^{:api-category :images
:order 2}
update-image
"Update an Image
https://docs.hetzner.cloud/#images-update-an-image
Updates the Image. You may change the description or convert a
Backup image to a Snapshot Image. Only images of type snapshot and
backup can be updated.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:description` (string): New description of Image
* `:type` (string): Destination image type to convert to
Choices: snapshot"
([token] (update-image token {}))
([token id body-m]
(request http/put (api-url "images" id)
(http-opts {:token token :body-m body-m}))))
(defn ^{:api-category :images
:order 3}
delete-image
"Delete an Image
https://docs.hetzner.cloud/#images-delete-an-image
Deletes an Image. Only images of type snapshot and backup can be deleted.
Parameters:
* `id` (string): ID of the image"
[token id]
(request http/delete (api-url "images" id) (http-opts {:token token})))
;; -- Image Actions ------------------------------------------------------------
(defn ^{:api-category :image-actions
:order 0}
get-image-actions
"Get all Actions for an Image
https://docs.hetzner.cloud/#image-actions-get-all-actions-for-an-image
Returns all action objects for an image. You can sort the results by
using the sort URI parameter.
Parameters:
* `id` (string): ID of the Image
Optional query parameters (`query-m`):
* `:sort` (vector of strings): Can be used multiple times.
Choices: id id:asc id:desc command command:asc command:desc status
status:asc status:desc progress progress:asc progress:desc started
started:asc started:desc finished finished:asc finished:desc"
[token id query-m]
(request http/get (api-url "images" id "actions")
(http-opts {:token token :query-m query-m})))
(defn ^{:api-category :image-actions
:order 1}
get-image-action
"Get an Action for an Image
https://docs.hetzner.cloud/#image-actions-get-an-action-for-an-image
Returns a specific action object for an image.
Parameters:
* `id` (string): ID of the image
* `action-id` (string): ID of the action"
[token id action-id]
(request http/get (api-url "images" id "actions" action-id)
(http-opts {:token token})))
(defn ^{:api-category :image-actions
:order 2}
change-image-protection
"Change protection for an Image
https://docs.hetzner.cloud/#image-actions-change-protection-for-an-image
Changes the protection configuration of the image. Can only be used
on snapshots.
Parameters:
* `id` (string): ID of the image
Optional body parameters (`body-m`):
* `:delete` (boolean): If true, prevents the snapshot from being deleted"
([token] (change-image-protection token {}))
([token id body-m]
(request http/post (api-url "images" id "actions" "change_protection")
(http-opts {:token token :body-m body-m}))))
;; -- ISOs ---------------------------------------------------------------------
(defn ^{:api-category :isos
:order 0}
get-isos
"Get all ISOs
https://docs.hetzner.cloud/#isos-get-all-isos
Returns all available iso objects.
Optional query parameters (`query-m`):
* `:name` (string): Can be used to filter isos by their name. The
response will only contain the iso matching the specified name."
([token] (get-isos token {}))
([token query-m]
(request http/get (api-url "isos") (http-opts {:token token :query-m query-m}))))
(defn ^{:api-category :isos
:order 1}
get-iso
"Get an ISO
https://docs.hetzner.cloud/#isos-get-an-iso
Returns a specific iso object.
Parameters:
* `id` (string): ID of the ISO"
[token id]
(request http/get (api-url "isos" id) (http-opts {:token token})))
;; -- Pricing ------------------------------------------------------------------
(defn ^{:api-category :pricing
:order 0}
get-prices
"Get all prices
https://docs.hetzner.cloud/#pricing-get-all-prices
Returns prices for all resources available on the platform. VAT and
currency of the project owner are used for calculations.
Both net and gross prices are included in the response."
[token]
(request http/get (api-url "pricing") (http-opts {:token token})))
|
[
{
"context": "-fx\n :register\n (fn [_ [_ {:keys [email password pass-confirm] :as user}]]\n {:http {:method P",
"end": 1686,
"score": 0.6820852756500244,
"start": 1682,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": " :password password\n :pass-confir",
"end": 1909,
"score": 0.9949331879615784,
"start": 1901,
"tag": "PASSWORD",
"value": "password"
}
] | src/soul_talk/handler/auth.cljs | neromous/Re_Frame_template_of_FamiliyCost | 2 | (ns soul-talk.handler.auth
(:require [soul-talk.db :as db]
[re-frame.core :refer [reg-event-fx reg-event-db dispatch inject-cofx]]
[ajax.core :refer [POST GET DELETE PUT]]
[soul-talk.local-storage :refer [login-user-key auth-token-key]]
[soul-talk.db :refer [api-uri]]))
;; 运行 login
(reg-event-fx
:run-login-events
(fn [{{events :login-events :as db} :db} _]
{:dispatch-n events
:db db}))
;; 添加login
(reg-event-db
:add-login-event
(fn [db [_ event]]
(update db :login-events conj event)))
(reg-event-db
:handle-login-error
(fn [db {:keys [error]}]
(assoc db :error error)))
;; 处理login ok
(reg-event-fx
:handle-login-ok
(fn [{:keys [db]} [_ {:keys [user token]}]]
{:db (assoc db :user user :auth-token token)
:dispatch-n (list
[:set-breadcrumb ["Home" "Post" "List"]]
[:run-login-events]
[:set-active-page :admin]
[:navigate-to "/#/admin"])
:set-user! user
:set-auth-token! token}))
;; login
(reg-event-fx
:login
(fn [_ [_ {:keys [email password] :as user}]]
{:http {:method POST
:url (str api-uri "/login")
:ajax-map {:params {:email email
:password password}}
:success-event [:handle-login-ok]}}))
;; 处理register ok
(reg-event-fx
:handle-register
(fn [{:keys [db]} [_ {:keys [user]}]]
{:dispatch-n (list
[:set-active-page :admin])
:db (assoc db :user user)}))
;; register
(reg-event-fx
:register
(fn [_ [_ {:keys [email password pass-confirm] :as user}]]
{:http {:method POST
:url (str api-uri "/register")
:ajax-map {:params {:email email
:password password
:pass-confirm pass-confirm}}
:success-event [:handle-register]}}))
(reg-event-fx
:handle-logout
(fn [_ _]
{:dispatch-n (list
[:set-active-page :login])
:set-user! nil
:set-auth-token! nil
:db db/default-db}))
(reg-event-fx
:logout
(fn [_ _]
{:http {:method POST
:url (str api-uri "/logout")
:ignore-response-body true
:success-event [:handle-logout]
:error-event [:handle-logout]}}))
| 2593 | (ns soul-talk.handler.auth
(:require [soul-talk.db :as db]
[re-frame.core :refer [reg-event-fx reg-event-db dispatch inject-cofx]]
[ajax.core :refer [POST GET DELETE PUT]]
[soul-talk.local-storage :refer [login-user-key auth-token-key]]
[soul-talk.db :refer [api-uri]]))
;; 运行 login
(reg-event-fx
:run-login-events
(fn [{{events :login-events :as db} :db} _]
{:dispatch-n events
:db db}))
;; 添加login
(reg-event-db
:add-login-event
(fn [db [_ event]]
(update db :login-events conj event)))
(reg-event-db
:handle-login-error
(fn [db {:keys [error]}]
(assoc db :error error)))
;; 处理login ok
(reg-event-fx
:handle-login-ok
(fn [{:keys [db]} [_ {:keys [user token]}]]
{:db (assoc db :user user :auth-token token)
:dispatch-n (list
[:set-breadcrumb ["Home" "Post" "List"]]
[:run-login-events]
[:set-active-page :admin]
[:navigate-to "/#/admin"])
:set-user! user
:set-auth-token! token}))
;; login
(reg-event-fx
:login
(fn [_ [_ {:keys [email password] :as user}]]
{:http {:method POST
:url (str api-uri "/login")
:ajax-map {:params {:email email
:password password}}
:success-event [:handle-login-ok]}}))
;; 处理register ok
(reg-event-fx
:handle-register
(fn [{:keys [db]} [_ {:keys [user]}]]
{:dispatch-n (list
[:set-active-page :admin])
:db (assoc db :user user)}))
;; register
(reg-event-fx
:register
(fn [_ [_ {:keys [email password <PASSWORD>-confirm] :as user}]]
{:http {:method POST
:url (str api-uri "/register")
:ajax-map {:params {:email email
:password <PASSWORD>
:pass-confirm pass-confirm}}
:success-event [:handle-register]}}))
(reg-event-fx
:handle-logout
(fn [_ _]
{:dispatch-n (list
[:set-active-page :login])
:set-user! nil
:set-auth-token! nil
:db db/default-db}))
(reg-event-fx
:logout
(fn [_ _]
{:http {:method POST
:url (str api-uri "/logout")
:ignore-response-body true
:success-event [:handle-logout]
:error-event [:handle-logout]}}))
| true | (ns soul-talk.handler.auth
(:require [soul-talk.db :as db]
[re-frame.core :refer [reg-event-fx reg-event-db dispatch inject-cofx]]
[ajax.core :refer [POST GET DELETE PUT]]
[soul-talk.local-storage :refer [login-user-key auth-token-key]]
[soul-talk.db :refer [api-uri]]))
;; 运行 login
(reg-event-fx
:run-login-events
(fn [{{events :login-events :as db} :db} _]
{:dispatch-n events
:db db}))
;; 添加login
(reg-event-db
:add-login-event
(fn [db [_ event]]
(update db :login-events conj event)))
(reg-event-db
:handle-login-error
(fn [db {:keys [error]}]
(assoc db :error error)))
;; 处理login ok
(reg-event-fx
:handle-login-ok
(fn [{:keys [db]} [_ {:keys [user token]}]]
{:db (assoc db :user user :auth-token token)
:dispatch-n (list
[:set-breadcrumb ["Home" "Post" "List"]]
[:run-login-events]
[:set-active-page :admin]
[:navigate-to "/#/admin"])
:set-user! user
:set-auth-token! token}))
;; login
(reg-event-fx
:login
(fn [_ [_ {:keys [email password] :as user}]]
{:http {:method POST
:url (str api-uri "/login")
:ajax-map {:params {:email email
:password password}}
:success-event [:handle-login-ok]}}))
;; 处理register ok
(reg-event-fx
:handle-register
(fn [{:keys [db]} [_ {:keys [user]}]]
{:dispatch-n (list
[:set-active-page :admin])
:db (assoc db :user user)}))
;; register
(reg-event-fx
:register
(fn [_ [_ {:keys [email password PI:PASSWORD:<PASSWORD>END_PI-confirm] :as user}]]
{:http {:method POST
:url (str api-uri "/register")
:ajax-map {:params {:email email
:password PI:PASSWORD:<PASSWORD>END_PI
:pass-confirm pass-confirm}}
:success-event [:handle-register]}}))
(reg-event-fx
:handle-logout
(fn [_ _]
{:dispatch-n (list
[:set-active-page :login])
:set-user! nil
:set-auth-token! nil
:db db/default-db}))
(reg-event-fx
:logout
(fn [_ _]
{:http {:method POST
:url (str api-uri "/logout")
:ignore-response-body true
:success-event [:handle-logout]
:error-event [:handle-logout]}}))
|
[
{
"context": " :firstname \"Fred\"\n :surna",
"end": 1801,
"score": 0.9997456073760986,
"start": 1797,
"tag": "NAME",
"value": "Fred"
},
{
"context": " :surname \"Smith\"}]])\n (with-open [db (c/open-db node)]\n (",
"end": 1860,
"score": 0.9995831251144409,
"start": 1855,
"tag": "NAME",
"value": "Smith"
},
{
"context": " :where [[(text-search :firstname \"Fre*\" {:lucene-store-k :eav}) [[?e]]]\n ",
"end": 2005,
"score": 0.9352949261665344,
"start": 2002,
"tag": "NAME",
"value": "Fre"
},
{
"context": "lucene-text-search \"firstname:%s AND surname:%s\" \"Fred\" \"Smith\" {:lucene-store-k :multi}) [[?e]]]]})))))",
"end": 2131,
"score": 0.9997049570083618,
"start": 2127,
"tag": "NAME",
"value": "Fred"
},
{
"context": "text-search \"firstname:%s AND surname:%s\" \"Fred\" \"Smith\" {:lucene-store-k :multi}) [[?e]]]]}))))))\n\n(t/de",
"end": 2139,
"score": 0.9995334148406982,
"start": 2134,
"tag": "NAME",
"value": "Smith"
},
{
"context": "nnector use-case, derived from https://github.com/odpi/egeria-connector-crux/\n\n(def ^:const field-crux-v",
"end": 4703,
"score": 0.9904757142066956,
"start": 4699,
"tag": "USERNAME",
"value": "odpi"
}
] | crux-lucene/test/crux/lucene/extension_test.clj | joelittlejohn/crux | 0 | (ns crux.lucene.extension-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.codec :as cc]
[crux.system :as sys]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.lucene :as l])
(:import org.apache.lucene.analysis.Analyzer
org.apache.lucene.queries.function.FunctionScoreQuery
[org.apache.lucene.analysis.core KeywordAnalyzer KeywordTokenizerFactory LowerCaseFilterFactory]
[org.apache.lucene.analysis.standard StandardTokenizerFactory]
org.apache.lucene.analysis.custom.CustomAnalyzer
org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper
[org.apache.lucene.document Document Field$Store StringField TextField]
[org.apache.lucene.index IndexWriter Term]
org.apache.lucene.queryparser.classic.QueryParser
[org.apache.lucene.search BooleanClause$Occur BooleanQuery$Builder TermQuery Query DoubleValuesSource]))
(require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols
(t/use-fixtures :each (fix/with-opts {::l/lucene-store {}}) fix/with-node)
(t/deftest test-multiple-lucene-stores
(with-open [node (c/start-node {:eav {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene/->indexer}
:multi {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene.multi-field/->indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan
:firstname "Fred"
:surname "Smith"}]])
(with-open [db (c/open-db node)]
(t/is (seq (c/q db '{:find [?e]
:where [[(text-search :firstname "Fre*" {:lucene-store-k :eav}) [[?e]]]
[(lucene-text-search "firstname:%s AND surname:%s" "Fred" "Smith" {:lucene-store-k :multi}) [[?e]]]]}))))))
(t/deftest test-userspace-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {:default-field (name :description)})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e :description 'v]]}
v s)))
(take 5))))))))
(t/deftest test-userspace-wildcard-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n) :foo (str "Entitybar" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n) :foo (str "Entitybaz" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n) :foo (str "Entityqaz" n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[a v s]]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e (keyword a) 'v]]}
(keyword a) v s)))
(take 5))))))))
;;; Egeria Connector use-case, derived from https://github.com/odpi/egeria-connector-crux/
(def ^:const field-crux-val-exact "_crux_val_exact")
(defn ^String keyword->kcs [k]
(subs (str k "-exact") 1))
(defrecord CustomEavIndexer [index-store]
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a ^String v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized (case-insensitive) (dynamic field)
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Custom - the actual term, to be used for exact matches (case-sensitive) (dynamic field)
(.add (StringField. (keyword->kcs a), v, Field$Store/YES))
;; Used for wildcard searches (case-insensitive)
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Custom - used for wildcard searches (case-sensitive)
(.add (StringField. field-crux-val-exact, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->custom-eav-indexer
{::sys/deps {:index-store :crux/index-store}}
[{:keys [index-store]}]
(CustomEavIndexer. index-store))
(defn ^Analyzer ->custom-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String KeywordTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(defn ^Analyzer ->per-field-analyzer
"global analyzer to cover indexing and _nearly_ all queries (it can't help with overriding dynamic fields)"
[_]
(PerFieldAnalyzerWrapper. (->custom-analyzer nil) {field-crux-val-exact (KeywordAnalyzer.)}))
(defn build-custom-query [analyzer field-string v]
(let [qp (doto (QueryParser. field-string analyzer) (.setAllowLeadingWildcard true))
b (doto (BooleanQuery$Builder.)
(.add (.parse qp v) BooleanClause$Occur/MUST))]
(.build b)))
(defn custom-text-search
([node db attr query]
(custom-text-search node db attr query {}))
([node db attr query opts]
(with-open [s (l/search node query)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e attr 'v]]}
v s)))
(into [])))))
(defn custom-wildcard-text-search
([node db query]
(custom-wildcard-text-search node db query {}))
([node db query opts]
(with-open [s (l/search node
query
opts)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[a v s]]
(let [a (keyword a)]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e a 'v]]}
a v s))))
(into [])))))
(t/deftest test-custom-index-and-analyzer
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->per-field-analyzer
:indexer 'crux.lucene.extension-test/->custom-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id 0, :description "Some Entity"}]
[:crux.tx/put {:crux.db/id 1, :description "Another entity"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 2.0]
[1 "Another entity" 1.0]]
(let [a :description]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "so* *En*")))))
;; case-sensitive text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 1.0]]
(let [a :description]
;; as per the docstring above, using KeywordAnalyzer here because PerFieldAnalyzerWrapper only helps with hardcoded fields
(custom-text-search node db a (build-custom-query (KeywordAnalyzer.) (keyword->kcs a) "*En*")))))
;; wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 2.0]
[1 :description "Another entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) l/field-crux-val "*So* *En*"))))
;; case-sensitive wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) field-crux-val-exact "*En*")))))))
;;; how-to example
(defrecord ExampleEavIndexer []
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:when (contains? #{:product/title :product/description} a) ;; example - don't index all attributes
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Used for wildcard searches
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->example-eav-indexer [_]
(ExampleEavIndexer.))
(defn ^Analyzer ->example-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String StandardTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(t/deftest test-example-use-case
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->example-analyzer
:indexer 'crux.lucene.extension-test/->example-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id "SKU-32934"
:product/title "Brown Summer Hat"
:product/description "This large and comfortable woven hat will keep you cool in the summer"}]
[:crux.tx/put {:crux.db/id "SKU-93921"
:product/title "Yellow Raincoat"
:product/description "Light and bright - a yellow raincoat to keep you dry all year round"}]
[:crux.tx/put {:crux.db/id "SKU-13892"
:product/title "Large Umbrella"
:product/description "Don't let rain get in the way of your day!"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [["SKU-32934" "Brown Summer Hat" 1.0]]
(let [a :product/title]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "*hat*")))))
;; wildcard-text-search + leading wildcard + boosted :product/title
(t/is (= [["SKU-93921" :product/title "Yellow Raincoat" 10.0]
["SKU-13892"
:product/description
"Don't let rain get in the way of your day!"
1.0]
["SKU-93921"
:product/description
"Light and bright - a yellow raincoat to keep you dry all year round"
1.0]]
(->> (custom-wildcard-text-search node
db
(FunctionScoreQuery/boostByQuery
(build-custom-query (->per-field-analyzer nil)
l/field-crux-val
"*rain*")
(build-custom-query (->per-field-analyzer nil)
l/field-crux-attr
(-> :product/title
l/keyword->k
QueryParser/escape))
10.0))
(sort-by (juxt (comp - last) first))))))))
| 73233 | (ns crux.lucene.extension-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.codec :as cc]
[crux.system :as sys]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.lucene :as l])
(:import org.apache.lucene.analysis.Analyzer
org.apache.lucene.queries.function.FunctionScoreQuery
[org.apache.lucene.analysis.core KeywordAnalyzer KeywordTokenizerFactory LowerCaseFilterFactory]
[org.apache.lucene.analysis.standard StandardTokenizerFactory]
org.apache.lucene.analysis.custom.CustomAnalyzer
org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper
[org.apache.lucene.document Document Field$Store StringField TextField]
[org.apache.lucene.index IndexWriter Term]
org.apache.lucene.queryparser.classic.QueryParser
[org.apache.lucene.search BooleanClause$Occur BooleanQuery$Builder TermQuery Query DoubleValuesSource]))
(require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols
(t/use-fixtures :each (fix/with-opts {::l/lucene-store {}}) fix/with-node)
(t/deftest test-multiple-lucene-stores
(with-open [node (c/start-node {:eav {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene/->indexer}
:multi {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene.multi-field/->indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan
:firstname "<NAME>"
:surname "<NAME>"}]])
(with-open [db (c/open-db node)]
(t/is (seq (c/q db '{:find [?e]
:where [[(text-search :firstname "<NAME>*" {:lucene-store-k :eav}) [[?e]]]
[(lucene-text-search "firstname:%s AND surname:%s" "<NAME>" "<NAME>" {:lucene-store-k :multi}) [[?e]]]]}))))))
(t/deftest test-userspace-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {:default-field (name :description)})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e :description 'v]]}
v s)))
(take 5))))))))
(t/deftest test-userspace-wildcard-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n) :foo (str "Entitybar" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n) :foo (str "Entitybaz" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n) :foo (str "Entityqaz" n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[a v s]]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e (keyword a) 'v]]}
(keyword a) v s)))
(take 5))))))))
;;; Egeria Connector use-case, derived from https://github.com/odpi/egeria-connector-crux/
(def ^:const field-crux-val-exact "_crux_val_exact")
(defn ^String keyword->kcs [k]
(subs (str k "-exact") 1))
(defrecord CustomEavIndexer [index-store]
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a ^String v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized (case-insensitive) (dynamic field)
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Custom - the actual term, to be used for exact matches (case-sensitive) (dynamic field)
(.add (StringField. (keyword->kcs a), v, Field$Store/YES))
;; Used for wildcard searches (case-insensitive)
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Custom - used for wildcard searches (case-sensitive)
(.add (StringField. field-crux-val-exact, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->custom-eav-indexer
{::sys/deps {:index-store :crux/index-store}}
[{:keys [index-store]}]
(CustomEavIndexer. index-store))
(defn ^Analyzer ->custom-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String KeywordTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(defn ^Analyzer ->per-field-analyzer
"global analyzer to cover indexing and _nearly_ all queries (it can't help with overriding dynamic fields)"
[_]
(PerFieldAnalyzerWrapper. (->custom-analyzer nil) {field-crux-val-exact (KeywordAnalyzer.)}))
(defn build-custom-query [analyzer field-string v]
(let [qp (doto (QueryParser. field-string analyzer) (.setAllowLeadingWildcard true))
b (doto (BooleanQuery$Builder.)
(.add (.parse qp v) BooleanClause$Occur/MUST))]
(.build b)))
(defn custom-text-search
([node db attr query]
(custom-text-search node db attr query {}))
([node db attr query opts]
(with-open [s (l/search node query)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e attr 'v]]}
v s)))
(into [])))))
(defn custom-wildcard-text-search
([node db query]
(custom-wildcard-text-search node db query {}))
([node db query opts]
(with-open [s (l/search node
query
opts)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[a v s]]
(let [a (keyword a)]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e a 'v]]}
a v s))))
(into [])))))
(t/deftest test-custom-index-and-analyzer
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->per-field-analyzer
:indexer 'crux.lucene.extension-test/->custom-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id 0, :description "Some Entity"}]
[:crux.tx/put {:crux.db/id 1, :description "Another entity"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 2.0]
[1 "Another entity" 1.0]]
(let [a :description]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "so* *En*")))))
;; case-sensitive text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 1.0]]
(let [a :description]
;; as per the docstring above, using KeywordAnalyzer here because PerFieldAnalyzerWrapper only helps with hardcoded fields
(custom-text-search node db a (build-custom-query (KeywordAnalyzer.) (keyword->kcs a) "*En*")))))
;; wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 2.0]
[1 :description "Another entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) l/field-crux-val "*So* *En*"))))
;; case-sensitive wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) field-crux-val-exact "*En*")))))))
;;; how-to example
(defrecord ExampleEavIndexer []
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:when (contains? #{:product/title :product/description} a) ;; example - don't index all attributes
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Used for wildcard searches
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->example-eav-indexer [_]
(ExampleEavIndexer.))
(defn ^Analyzer ->example-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String StandardTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(t/deftest test-example-use-case
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->example-analyzer
:indexer 'crux.lucene.extension-test/->example-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id "SKU-32934"
:product/title "Brown Summer Hat"
:product/description "This large and comfortable woven hat will keep you cool in the summer"}]
[:crux.tx/put {:crux.db/id "SKU-93921"
:product/title "Yellow Raincoat"
:product/description "Light and bright - a yellow raincoat to keep you dry all year round"}]
[:crux.tx/put {:crux.db/id "SKU-13892"
:product/title "Large Umbrella"
:product/description "Don't let rain get in the way of your day!"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [["SKU-32934" "Brown Summer Hat" 1.0]]
(let [a :product/title]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "*hat*")))))
;; wildcard-text-search + leading wildcard + boosted :product/title
(t/is (= [["SKU-93921" :product/title "Yellow Raincoat" 10.0]
["SKU-13892"
:product/description
"Don't let rain get in the way of your day!"
1.0]
["SKU-93921"
:product/description
"Light and bright - a yellow raincoat to keep you dry all year round"
1.0]]
(->> (custom-wildcard-text-search node
db
(FunctionScoreQuery/boostByQuery
(build-custom-query (->per-field-analyzer nil)
l/field-crux-val
"*rain*")
(build-custom-query (->per-field-analyzer nil)
l/field-crux-attr
(-> :product/title
l/keyword->k
QueryParser/escape))
10.0))
(sort-by (juxt (comp - last) first))))))))
| true | (ns crux.lucene.extension-test
(:require [clojure.test :as t]
[crux.api :as c]
[crux.codec :as cc]
[crux.system :as sys]
[crux.fixtures :as fix :refer [*api* submit+await-tx]]
[crux.lucene :as l])
(:import org.apache.lucene.analysis.Analyzer
org.apache.lucene.queries.function.FunctionScoreQuery
[org.apache.lucene.analysis.core KeywordAnalyzer KeywordTokenizerFactory LowerCaseFilterFactory]
[org.apache.lucene.analysis.standard StandardTokenizerFactory]
org.apache.lucene.analysis.custom.CustomAnalyzer
org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper
[org.apache.lucene.document Document Field$Store StringField TextField]
[org.apache.lucene.index IndexWriter Term]
org.apache.lucene.queryparser.classic.QueryParser
[org.apache.lucene.search BooleanClause$Occur BooleanQuery$Builder TermQuery Query DoubleValuesSource]))
(require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols
(t/use-fixtures :each (fix/with-opts {::l/lucene-store {}}) fix/with-node)
(t/deftest test-multiple-lucene-stores
(with-open [node (c/start-node {:eav {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene/->indexer}
:multi {:crux/module 'crux.lucene/->lucene-store
:analyzer 'crux.lucene/->analyzer
:indexer 'crux.lucene.multi-field/->indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan
:firstname "PI:NAME:<NAME>END_PI"
:surname "PI:NAME:<NAME>END_PI"}]])
(with-open [db (c/open-db node)]
(t/is (seq (c/q db '{:find [?e]
:where [[(text-search :firstname "PI:NAME:<NAME>END_PI*" {:lucene-store-k :eav}) [[?e]]]
[(lucene-text-search "firstname:%s AND surname:%s" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" {:lucene-store-k :multi}) [[?e]]]]}))))))
(t/deftest test-userspace-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {:default-field (name :description)})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e :description 'v]]}
v s)))
(take 5))))))))
(t/deftest test-userspace-wildcard-text-search-limit
(submit+await-tx (for [n (range 10)] [:crux.tx/put {:crux.db/id n, :description (str "Entity " n) :foo (str "Entitybar" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id n, :description (str "Entity v2 " n) :foo (str "Entitybaz" n)}]))
(submit+await-tx (for [n (range 4)] [:crux.tx/put {:crux.db/id (+ n 4), :description (str "Entity v2 " n) :foo (str "Entityqaz" n)}]))
(with-open [db (c/open-db *api*)]
(with-open [s (l/search *api* "Entity*" {})]
(t/is (= 5 (count (->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(distinct) ;; rely on the later resolve step to find all the entities sharing a given AV
(mapcat (fn resolve-atemporal-av [[a v s]]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e (keyword a) 'v]]}
(keyword a) v s)))
(take 5))))))))
;;; Egeria Connector use-case, derived from https://github.com/odpi/egeria-connector-crux/
(def ^:const field-crux-val-exact "_crux_val_exact")
(defn ^String keyword->kcs [k]
(subs (str k "-exact") 1))
(defrecord CustomEavIndexer [index-store]
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a ^String v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized (case-insensitive) (dynamic field)
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Custom - the actual term, to be used for exact matches (case-sensitive) (dynamic field)
(.add (StringField. (keyword->kcs a), v, Field$Store/YES))
;; Used for wildcard searches (case-insensitive)
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Custom - used for wildcard searches (case-sensitive)
(.add (StringField. field-crux-val-exact, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->custom-eav-indexer
{::sys/deps {:index-store :crux/index-store}}
[{:keys [index-store]}]
(CustomEavIndexer. index-store))
(defn ^Analyzer ->custom-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String KeywordTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(defn ^Analyzer ->per-field-analyzer
"global analyzer to cover indexing and _nearly_ all queries (it can't help with overriding dynamic fields)"
[_]
(PerFieldAnalyzerWrapper. (->custom-analyzer nil) {field-crux-val-exact (KeywordAnalyzer.)}))
(defn build-custom-query [analyzer field-string v]
(let [qp (doto (QueryParser. field-string analyzer) (.setAllowLeadingWildcard true))
b (doto (BooleanQuery$Builder.)
(.add (.parse qp v) BooleanClause$Occur/MUST))]
(.build b)))
(defn custom-text-search
([node db attr query]
(custom-text-search node db attr query {}))
([node db attr query opts]
(with-open [s (l/search node query)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[v s]]
(c/q db {:find '[e v s]
:in '[v s]
:where [['e attr 'v]]}
v s)))
(into [])))))
(defn custom-wildcard-text-search
([node db query]
(custom-wildcard-text-search node db query {}))
([node db query opts]
(with-open [s (l/search node
query
opts)]
(->> (iterator-seq s)
(map (fn doc->rel [[^Document doc score]]
[(.get ^Document doc l/field-crux-attr) (.get ^Document doc l/field-crux-val) score]))
(mapcat (fn resolve-atemporal-av [[a v s]]
(let [a (keyword a)]
(c/q db {:find '[e a v s]
:in '[a v s]
:where [['e a 'v]]}
a v s))))
(into [])))))
(t/deftest test-custom-index-and-analyzer
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->per-field-analyzer
:indexer 'crux.lucene.extension-test/->custom-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id 0, :description "Some Entity"}]
[:crux.tx/put {:crux.db/id 1, :description "Another entity"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 2.0]
[1 "Another entity" 1.0]]
(let [a :description]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "so* *En*")))))
;; case-sensitive text-search + leading-wildcard
(t/is (= [[0 "Some Entity" 1.0]]
(let [a :description]
;; as per the docstring above, using KeywordAnalyzer here because PerFieldAnalyzerWrapper only helps with hardcoded fields
(custom-text-search node db a (build-custom-query (KeywordAnalyzer.) (keyword->kcs a) "*En*")))))
;; wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 2.0]
[1 :description "Another entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) l/field-crux-val "*So* *En*"))))
;; case-sensitive wildcard-text-search + leading wildcard
(t/is (= [[0 :description "Some Entity" 1.0]]
(custom-wildcard-text-search node db (build-custom-query (->per-field-analyzer nil) field-crux-val-exact "*En*")))))))
;;; how-to example
(defrecord ExampleEavIndexer []
l/LuceneIndexer
(index! [_ index-writer docs]
(doseq [{e :crux.db/id, :as crux-doc} (vals docs)
[a v] (->> (dissoc crux-doc :crux.db/id)
(mapcat (fn [[a v]]
(for [v (cc/vectorize-value v)
:when (string? v)]
[a v]))))
:when (contains? #{:product/title :product/description} a) ;; example - don't index all attributes
:let [id-str (l/->hash-str (l/->DocumentId e a v))
doc (doto (Document.)
;; To search for triples by e-a-v for deduping
(.add (StringField. l/field-crux-id, id-str, Field$Store/NO))
;; The actual term, which will be tokenized
(.add (TextField. (l/keyword->k a), v, Field$Store/YES))
;; Used for wildcard searches
(.add (TextField. l/field-crux-val, v, Field$Store/YES))
;; Used for eviction
(.add (StringField. l/field-crux-eid, (l/->hash-str e), Field$Store/NO))
;; Used for wildcard searches
(.add (StringField. l/field-crux-attr, (l/keyword->k a), Field$Store/YES)))]]
(.updateDocument ^IndexWriter index-writer (Term. l/field-crux-id id-str) doc)))
(evict! [_ index-writer eids]
(let [qs (for [eid eids]
(TermQuery. (Term. l/field-crux-eid (l/->hash-str eid))))]
(.deleteDocuments ^IndexWriter index-writer ^"[Lorg.apache.lucene.search.Query;" (into-array Query qs)))))
(defn ->example-eav-indexer [_]
(ExampleEavIndexer.))
(defn ^Analyzer ->example-analyzer
"case-insensitive analyzer"
[_]
(.build (doto (CustomAnalyzer/builder)
(.withTokenizer ^String StandardTokenizerFactory/NAME ^"[Ljava.lang.String;" (into-array String []))
(.addTokenFilter ^String LowerCaseFilterFactory/NAME ^"[Ljava.lang.String;" (into-array String [])))))
(t/deftest test-example-use-case
(with-open [node (c/start-node {:crux.lucene/lucene-store {:analyzer 'crux.lucene.extension-test/->example-analyzer
:indexer 'crux.lucene.extension-test/->example-eav-indexer}})]
(submit+await-tx node [[:crux.tx/put {:crux.db/id "SKU-32934"
:product/title "Brown Summer Hat"
:product/description "This large and comfortable woven hat will keep you cool in the summer"}]
[:crux.tx/put {:crux.db/id "SKU-93921"
:product/title "Yellow Raincoat"
:product/description "Light and bright - a yellow raincoat to keep you dry all year round"}]
[:crux.tx/put {:crux.db/id "SKU-13892"
:product/title "Large Umbrella"
:product/description "Don't let rain get in the way of your day!"}]])
(let [db (c/db node)]
;; text-search + leading-wildcard
(t/is (= [["SKU-32934" "Brown Summer Hat" 1.0]]
(let [a :product/title]
(custom-text-search node db a (build-custom-query (->per-field-analyzer nil) (l/keyword->k a) "*hat*")))))
;; wildcard-text-search + leading wildcard + boosted :product/title
(t/is (= [["SKU-93921" :product/title "Yellow Raincoat" 10.0]
["SKU-13892"
:product/description
"Don't let rain get in the way of your day!"
1.0]
["SKU-93921"
:product/description
"Light and bright - a yellow raincoat to keep you dry all year round"
1.0]]
(->> (custom-wildcard-text-search node
db
(FunctionScoreQuery/boostByQuery
(build-custom-query (->per-field-analyzer nil)
l/field-crux-val
"*rain*")
(build-custom-query (->per-field-analyzer nil)
l/field-crux-attr
(-> :product/title
l/keyword->k
QueryParser/escape))
10.0))
(sort-by (juxt (comp - last) first))))))))
|
[
{
"context": "scm {:name \"git\"\n :url \"https://github.com/lk-geimfari/secrets.clj\"}\n :url \"https://github.com/lk-geimf",
"end": 206,
"score": 0.9989228844642639,
"start": 195,
"tag": "USERNAME",
"value": "lk-geimfari"
},
{
"context": "geimfari/secrets.clj\"}\n :url \"https://github.com/lk-geimfari/secrets.clj\"\n :license {:name \"MIT License\"}\n :",
"end": 259,
"score": 0.9995258450508118,
"start": 248,
"tag": "USERNAME",
"value": "lk-geimfari"
},
{
"context": "me\n :password :env/clojars_password\n :sign-release",
"end": 657,
"score": 0.9986223578453064,
"start": 637,
"tag": "PASSWORD",
"value": "env/clojars_password"
}
] | project.clj | lk-geimfari/secrets.clj | 66 | (defproject likid_geimfari/secrets "1.0.0"
:description "A Clojure library designed to generate secure random numbers for managing secrets"
:scm {:name "git"
:url "https://github.com/lk-geimfari/secrets.clj"}
:url "https://github.com/lk-geimfari/secrets.clj"
:license {:name "MIT License"}
:plugins [[lein-cljfmt "0.6.8"] [lein-cloverage "1.1.2"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[commons-codec "1.6"]]
:deploy-repositories [["clojars" {:url "https://repo.clojars.org"
:username :env/clojars_username
:password :env/clojars_password
:sign-releases false}]]
:repl-options {:init-ns secrets.core})
| 74002 | (defproject likid_geimfari/secrets "1.0.0"
:description "A Clojure library designed to generate secure random numbers for managing secrets"
:scm {:name "git"
:url "https://github.com/lk-geimfari/secrets.clj"}
:url "https://github.com/lk-geimfari/secrets.clj"
:license {:name "MIT License"}
:plugins [[lein-cljfmt "0.6.8"] [lein-cloverage "1.1.2"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[commons-codec "1.6"]]
:deploy-repositories [["clojars" {:url "https://repo.clojars.org"
:username :env/clojars_username
:password :<PASSWORD>
:sign-releases false}]]
:repl-options {:init-ns secrets.core})
| true | (defproject likid_geimfari/secrets "1.0.0"
:description "A Clojure library designed to generate secure random numbers for managing secrets"
:scm {:name "git"
:url "https://github.com/lk-geimfari/secrets.clj"}
:url "https://github.com/lk-geimfari/secrets.clj"
:license {:name "MIT License"}
:plugins [[lein-cljfmt "0.6.8"] [lein-cloverage "1.1.2"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[commons-codec "1.6"]]
:deploy-repositories [["clojars" {:url "https://repo.clojars.org"
:username :env/clojars_username
:password :PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]]
:repl-options {:init-ns secrets.core})
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2020, Kenneth Leung. All rights reserved.\n\n(ns czlab.shimoji.afx.cryp",
"end": 597,
"score": 0.9998629689216614,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | attic/afx/crypt.cljs | llnek/czlabio | 0 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2020, Kenneth Leung. All rights reserved.
(ns czlab.shimoji.afx.crypt
(:require [clojure.string :as cs]
[czlab.shimoji.afx.core
:as c :refer [n# nzero? abs* estr? nestr? zero??]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private VISCHS (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*"
"fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))
(def ^:private VISCHS-LEN (n# VISCHS))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- calc-delta
"Find the offset."
[shift]
(mod (abs* shift) VISCHS-LEN))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- charat
"Get the char at the index."
([pos]
(charat pos VISCHS))
([pos string_]
(.charAt string_ pos)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- getch
"Index for this char."
[ch]
(loop [pos 0]
(if (>= pos VISCHS-LEN)
-1
(if (= ch (charat pos)) pos (recur (+ 1 pos))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotr
"Rotate right."
[delta cpos]
(let [pos (+ cpos delta)]
(charat (if (>= pos VISCHS-LEN) (- pos VISCHS-LEN) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotl
"Rotate left."
[delta cpos]
(let [pos (- cpos delta)]
(charat (if (< pos 0) (+ VISCHS-LEN pos) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encrypt
"Encrypt source by shifts."
[src shift]
{:pre [(string? src)]}
(if (zero?? shift)
src
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotr delta cpos)
(rotl delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c src
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn decrypt
"Decrypt text by shifts."
[cipherText shift]
{:pre [(string? cipherText)]}
(if (zero?? shift)
cipherText
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotl delta cpos)
(rotr delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c cipherText
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 18060 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2020, <NAME>. All rights reserved.
(ns czlab.shimoji.afx.crypt
(:require [clojure.string :as cs]
[czlab.shimoji.afx.core
:as c :refer [n# nzero? abs* estr? nestr? zero??]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private VISCHS (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*"
"fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))
(def ^:private VISCHS-LEN (n# VISCHS))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- calc-delta
"Find the offset."
[shift]
(mod (abs* shift) VISCHS-LEN))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- charat
"Get the char at the index."
([pos]
(charat pos VISCHS))
([pos string_]
(.charAt string_ pos)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- getch
"Index for this char."
[ch]
(loop [pos 0]
(if (>= pos VISCHS-LEN)
-1
(if (= ch (charat pos)) pos (recur (+ 1 pos))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotr
"Rotate right."
[delta cpos]
(let [pos (+ cpos delta)]
(charat (if (>= pos VISCHS-LEN) (- pos VISCHS-LEN) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotl
"Rotate left."
[delta cpos]
(let [pos (- cpos delta)]
(charat (if (< pos 0) (+ VISCHS-LEN pos) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encrypt
"Encrypt source by shifts."
[src shift]
{:pre [(string? src)]}
(if (zero?? shift)
src
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotr delta cpos)
(rotl delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c src
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn decrypt
"Decrypt text by shifts."
[cipherText shift]
{:pre [(string? cipherText)]}
(if (zero?? shift)
cipherText
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotl delta cpos)
(rotr delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c cipherText
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2020, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.shimoji.afx.crypt
(:require [clojure.string :as cs]
[czlab.shimoji.afx.core
:as c :refer [n# nzero? abs* estr? nestr? zero??]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private VISCHS (str " @N/\\Ri2}aP`(xeT4F3mt;8~%r0v:L5$+Z{'V)\"CKIc>z.*"
"fJEwSU7juYg<klO&1?[h9=n,yoQGsW]BMHpXb6A|D#q^_d!-"))
(def ^:private VISCHS-LEN (n# VISCHS))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- calc-delta
"Find the offset."
[shift]
(mod (abs* shift) VISCHS-LEN))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- charat
"Get the char at the index."
([pos]
(charat pos VISCHS))
([pos string_]
(.charAt string_ pos)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- getch
"Index for this char."
[ch]
(loop [pos 0]
(if (>= pos VISCHS-LEN)
-1
(if (= ch (charat pos)) pos (recur (+ 1 pos))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotr
"Rotate right."
[delta cpos]
(let [pos (+ cpos delta)]
(charat (if (>= pos VISCHS-LEN) (- pos VISCHS-LEN) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- rotl
"Rotate left."
[delta cpos]
(let [pos (- cpos delta)]
(charat (if (< pos 0) (+ VISCHS-LEN pos) pos))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encrypt
"Encrypt source by shifts."
[src shift]
{:pre [(string? src)]}
(if (zero?? shift)
src
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotr delta cpos)
(rotl delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c src
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn decrypt
"Decrypt text by shifts."
[cipherText shift]
{:pre [(string? cipherText)]}
(if (zero?? shift)
cipherText
(let [f' (fn [shift delta cpos] (if (neg? shift)
(rotl delta cpos)
(rotr delta cpos)))
out #js []
d (calc-delta shift)]
(doseq [c cipherText
:let [p (getch c)]]
(.push out (if (< p 0) c (f' shift d p)))) (cs/join "" out))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.