_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
3d80714e6b29b68c9bac9dc3839146f9187161b58a00c95e58c8faa73acbf769
sellout/haskerwaul
Left.hs
# language TypeApplications # module Haskerwaul.Law.Quotient.Left where import Data.Constraint ((\\)) import Data.Proxy (Proxy(..)) import Haskerwaul.Bifunctor import Haskerwaul.Category.Monoidal.Cartesian import Haskerwaul.Isomorphism import Haskerwaul.Law import Haskerwaul.Object import Haskerwaul.Relation.Equality -- | @x = (x / y) y@ lq1Law :: forall c a. (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Prod c a a `c` a -> Law c EqualityRelation (Prod c a a) a lq1Law op' leftQuotient' = Law exr (op' . first p leftQuotient' . to assoc . second p (diagonal @_ @c)) \\ inT @(Ob c) @(Prod c) @a @a where p = Proxy :: Proxy c -- | @x = (x y) / y@ lq2Law :: forall c a. (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Prod c a a `c` a -> Law c EqualityRelation (Prod c a a) a lq2Law op' leftQuotient' = Law exr (leftQuotient' . first p op' . to assoc . second p (diagonal @_ @c)) \\ inT @(Ob c) @(Prod c) @a @a where p = Proxy :: Proxy c
null
https://raw.githubusercontent.com/sellout/haskerwaul/bb197cacf348c0f189d218f35bf8bbb220d3e402/src/Haskerwaul/Law/Quotient/Left.hs
haskell
| @x = (x / y) y@ | @x = (x y) / y@
# language TypeApplications # module Haskerwaul.Law.Quotient.Left where import Data.Constraint ((\\)) import Data.Proxy (Proxy(..)) import Haskerwaul.Bifunctor import Haskerwaul.Category.Monoidal.Cartesian import Haskerwaul.Isomorphism import Haskerwaul.Law import Haskerwaul.Object import Haskerwaul.Relation.Equality lq1Law :: forall c a. (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Prod c a a `c` a -> Law c EqualityRelation (Prod c a a) a lq1Law op' leftQuotient' = Law exr (op' . first p leftQuotient' . to assoc . second p (diagonal @_ @c)) \\ inT @(Ob c) @(Prod c) @a @a where p = Proxy :: Proxy c lq2Law :: forall c a. (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Prod c a a `c` a -> Law c EqualityRelation (Prod c a a) a lq2Law op' leftQuotient' = Law exr (leftQuotient' . first p op' . to assoc . second p (diagonal @_ @c)) \\ inT @(Ob c) @(Prod c) @a @a where p = Proxy :: Proxy c
bc13e25ca34e2eb0bae2c407828ab66fc19506dedc54df4f23a134349b6a2f35
johnmn3/cljs-thread
root.cljs
(ns cljs-thread.root (:require [cljs-thread.env :as e] [cljs-thread.state :as s] [cljs-thread.spawn :refer [spawn]] [cljs-thread.on-when :refer [on-when]] [cljs-thread.future :as f] [cljs-thread.injest :as i] [cljs-thread.util :as u] [cljs-thread.repl :as repl])) (defn after-db [config] (spawn {:id :core} (s/update-conf! config) (on-when (contains? @s/peers :db) (reset! s/ready? true))) (repl/start-repl config)) (defn ^:export init-root! [& [config-map]] (assert (e/in-root?)) (when config-map (swap! s/conf merge config-map)) (let [config @s/conf] (on-when (contains? @s/peers :sw) (f/start-futures config) (i/start-injests config) (if (u/in-safari?) (do (spawn {:id :db :no-globals? true}) (after-db config)) (spawn {:id :db :no-globals? true} (after-db config))))))
null
https://raw.githubusercontent.com/johnmn3/cljs-thread/e98edc26ae71d1e17cea96a1f0e978df41b34d3f/src/cljs_thread/root.cljs
clojure
(ns cljs-thread.root (:require [cljs-thread.env :as e] [cljs-thread.state :as s] [cljs-thread.spawn :refer [spawn]] [cljs-thread.on-when :refer [on-when]] [cljs-thread.future :as f] [cljs-thread.injest :as i] [cljs-thread.util :as u] [cljs-thread.repl :as repl])) (defn after-db [config] (spawn {:id :core} (s/update-conf! config) (on-when (contains? @s/peers :db) (reset! s/ready? true))) (repl/start-repl config)) (defn ^:export init-root! [& [config-map]] (assert (e/in-root?)) (when config-map (swap! s/conf merge config-map)) (let [config @s/conf] (on-when (contains? @s/peers :sw) (f/start-futures config) (i/start-injests config) (if (u/in-safari?) (do (spawn {:id :db :no-globals? true}) (after-db config)) (spawn {:id :db :no-globals? true} (after-db config))))))
9b114d495b7d3419d049e48aa7a305be1a5204b07747c21dc9936b975e27bbeb
schemeorg-community/index.scheme.org
rnrs.lists.6.scm
(((name . "find") (signature lambda ((procedure? pred) (list? list)) *) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The find procedure applies proc to the elements of list in order. If proc returns a true value for an element, find immediately returns that element. If proc returns #f for all elements of the list, find returns #f. Proc is always called in the same dynamic environment as find itself.")) ((name . "for-all") (signature lambda ((procedure? pred) (list? list1) (list? list2) ...) *) (subsigs (pred (lambda (obj1 obj2 ...) *))) (tags pure) (desc . "The lists should all have the same length, and proc should accept n arguments and return a single value. Proc should not mutate the list arguments. For natural numbers i = 0, 1, ..., the for-all procedure successively applies proc to arguments xi1 ... xin, where xij is the ith element of listj, until #f is returned. If proc returns true values for all but the last element of list1, for-all performs a tail call of proc on the kth elements, where k is the length of list1. If proc returns #f on any set of elements, for-all returns #f after the first such application of proc. If the lists are all empty, for-all returns #t.")) ((name . "exists") (signature lambda ((procedure? pred) (list? list1) (list? list2) ...) *) (subsigs (pred (lambda (obj1 obj2 ...) *))) (tags pure) (desc . " The lists should all have the same length, and proc should accept n arguments and return a single value. Proc should not mutate the list arguments. For natural numbers i = 0, 1, ..., the exists procedure applies proc successively to arguments xi1 ... xin, where xij is the ith element of listj, until a true value is returned. If proc returns #f for all but the last elements of the lists, exists performs a tail call of proc on the kth elements, where k is the length of list1. If proc returns a true value on any set of elements, exists returns that value after the first such application of proc. If the lists are all empty, exists returns #f.")) ((name . "filter") (signature lambda ((procedure? pred) (list? list)) list?) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The filter procedure applies proc to each element of list and returns a list of the elements of list for which proc returned a true value. The elements of the result list are in the same order as they appear in the input list. Proc is always called in the same dynamic environment as filter. If multiple returns occur from filter, the return values returned by earlier returns are not mutated.")) ((name . "partition") (signature lambda ((procedure? pred) (list? list)) (values list? list?)) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The partition procedure also applies proc to each element of list, but returns two values, the first one a list of the elements of list for which proc returned a true value, and the second a list of the elements of list for which proc returned #f. The elements of the result lists are in the same order as they appear in the input list. Proc is always called in the same dynamic environment as partition itself. If multiple returns occur from partitions, the return values returned by earlier returns are not mutated.")) ((name . "fold-left") (signature lambda ((procedure? kons) knil (list? list1) (list? list2) ...) *) (subsigs (kons (lambda (obj1 obj2 ... fold-state) *))) (tags pure) (desc . "The lists should all have the same length. Combine must be a procedure. It should accept one more argument than there are lists and return a single value. It should not mutate the list arguments. The fold-left procedure iterates the combine procedure over an accumulator value and the elements of the lists from left to right, starting with an accumulator value of nil. More specifically, fold-left returns nil if the lists are empty. If they are not empty, combine is first applied to nil and the respective first elements of the lists in order. The result becomes the new accumulator value, and combine is applied to the new accumulator value and the respective next elements of the list. This step is repeated until the end of the list is reached; then the accumulator value is returned. Combine is always called in the same dynamic environment as fold-left itself.")) ((name . "fold-right") (signature lambda ((procedure? kons) knil (list? list1) (list? list2) ...) *) (subsigs (kons (lambda (obj1 obj2 ... fold-state) *))) (tags pure) (desc . "The lists should all have the same length. Combine must be a procedure. It should accept one more argument than there are lists and return a single value. Combine should not mutate the list arguments. The fold-right procedure iterates the combine procedure over the elements of the lists from right to left and an accumulator value, starting with an accumulator value of nil. More specifically, fold-right returns nil if the lists are empty. If they are not empty, combine is first applied to the respective last elements of the lists in order and nil. The result becomes the new accumulator value, and combine is applied to the respective previous elements of the lists and the new accumulator value. This step is repeated until the beginning of the list is reached; then the accumulator value is returned. Proc is always called in the same dynamic environment as fold-right itself.")) ((name . "remp") (signature lambda ((procedure? pred) (list? list)) list?) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "The remp procedure applies proc to each element of list and returns a list of the elements of list for which proc returned #f.")) ((name . "remove") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remove procedure return a list of the elements that are not obj as according to equal?.")) ((name . "remv") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remv procedure return a list of the elements that are not obj as according to eqv?.")) ((name . "remq") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remq procedure return a list of the elements that are not obj as according to eq?.")) ((name . "memp") (signature lambda ((procedure? pred) (list? list)) (or #f list?)) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memp procedure applies proc to the cars of the sublists of list until it finds one for which proc returns a true value. Proc is always called in the same dynamic environment as memp itself. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned.")) ((name . "member") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The member procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The member procedure uses equal? to compare obj with the elements of list.")) ((name . "memq") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memq procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The memq procedure uses eq? to compare obj with the elements of list.")) ((name . "memv") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memv procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The memv procedure uses eqv? to compare obj with the elements of list.")) ((name . "assp") (signature lambda ((procedure? pred) (list? alist)) (or pair? #f)) (subsigs (pred (lambda (obj) *)) (alist (alist key value))) (tags pure) (desc . "Alist (for \"association list\") should be a list of pairs. Proc should accept one argument and return a single value. Proc should not mutate alist. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assp procedure successively applies proc to the car fields of alist and looks for a pair for which it returns a true value. Proc is always called in the same dynamic environment as assp itself.")) ((name . "assoc") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assoc procedure uses equal? to compare obj with the car fields of the pairs in alist.")) ((name . "assq") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assq procedure uses eq? to compare obj with the car fields of the pairs in alist.")) ((name . "assv") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assv procedure uses eqv? to compare obj with the car fields of the pairs in alist.")) ((name . "cons*") (signature lambda (elt1 elt2 ...) *) (tags pure) (desc . "If called with at least two arguments, cons* returns a freshly allocated chain of pairs whose cars are obj1, ..., objn, and whose last cdr is obj. If called with only one argument, cons* returns that argument.")))
null
https://raw.githubusercontent.com/schemeorg-community/index.scheme.org/118c698f56913a6a3c89e7dcc95b960a0b553f08/types/rnrs.lists.6.scm
scheme
(((name . "find") (signature lambda ((procedure? pred) (list? list)) *) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The find procedure applies proc to the elements of list in order. If proc returns a true value for an element, find immediately returns that element. If proc returns #f for all elements of the list, find returns #f. Proc is always called in the same dynamic environment as find itself.")) ((name . "for-all") (signature lambda ((procedure? pred) (list? list1) (list? list2) ...) *) (subsigs (pred (lambda (obj1 obj2 ...) *))) (tags pure) (desc . "The lists should all have the same length, and proc should accept n arguments and return a single value. Proc should not mutate the list arguments. For natural numbers i = 0, 1, ..., the for-all procedure successively applies proc to arguments xi1 ... xin, where xij is the ith element of listj, until #f is returned. If proc returns true values for all but the last element of list1, for-all performs a tail call of proc on the kth elements, where k is the length of list1. If proc returns #f on any set of elements, for-all returns #f after the first such application of proc. If the lists are all empty, for-all returns #t.")) ((name . "exists") (signature lambda ((procedure? pred) (list? list1) (list? list2) ...) *) (subsigs (pred (lambda (obj1 obj2 ...) *))) (tags pure) (desc . " The lists should all have the same length, and proc should accept n arguments and return a single value. Proc should not mutate the list arguments. For natural numbers i = 0, 1, ..., the exists procedure applies proc successively to arguments xi1 ... xin, where xij is the ith element of listj, until a true value is returned. If proc returns #f for all but the last elements of the lists, exists performs a tail call of proc on the kth elements, where k is the length of list1. If proc returns a true value on any set of elements, exists returns that value after the first such application of proc. If the lists are all empty, exists returns #f.")) ((name . "filter") (signature lambda ((procedure? pred) (list? list)) list?) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The filter procedure applies proc to each element of list and returns a list of the elements of list for which proc returned a true value. The elements of the result list are in the same order as they appear in the input list. Proc is always called in the same dynamic environment as filter. If multiple returns occur from filter, the return values returned by earlier returns are not mutated.")) ((name . "partition") (signature lambda ((procedure? pred) (list? list)) (values list? list?)) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. The partition procedure also applies proc to each element of list, but returns two values, the first one a list of the elements of list for which proc returned a true value, and the second a list of the elements of list for which proc returned #f. The elements of the result lists are in the same order as they appear in the input list. Proc is always called in the same dynamic environment as partition itself. If multiple returns occur from partitions, the return values returned by earlier returns are not mutated.")) ((name . "fold-left") (signature lambda ((procedure? kons) knil (list? list1) (list? list2) ...) *) (subsigs (kons (lambda (obj1 obj2 ... fold-state) *))) (tags pure) (desc . "The lists should all have the same length. Combine must be a procedure. It should accept one more argument than there are lists and return a single value. It should not mutate the list arguments. The fold-left procedure iterates the combine procedure over an accumulator value and the elements of the lists from left to right, starting with an accumulator value of nil. More specifically, fold-left returns nil if the lists are empty. If they are not empty, combine is first applied to nil and the respective first elements of the lists in order. The result becomes the new accumulator value, and combine is applied to the new accumulator value and the respective next elements of the list. This step is repeated until the end of the list is reached; then the accumulator value is returned. Combine is always called in the same dynamic environment as fold-left itself.")) ((name . "fold-right") (signature lambda ((procedure? kons) knil (list? list1) (list? list2) ...) *) (subsigs (kons (lambda (obj1 obj2 ... fold-state) *))) (tags pure) (desc . "The lists should all have the same length. Combine must be a procedure. It should accept one more argument than there are lists and return a single value. Combine should not mutate the list arguments. The fold-right procedure iterates the combine procedure over the elements of the lists from right to left and an accumulator value, starting with an accumulator value of nil. More specifically, fold-right returns nil if the lists are empty. If they are not empty, combine is first applied to the respective last elements of the lists in order and nil. The result becomes the new accumulator value, and combine is applied to the respective previous elements of the lists and the new accumulator value. This step is repeated until the beginning of the list is reached; then the accumulator value is returned. Proc is always called in the same dynamic environment as fold-right itself.")) ((name . "remp") (signature lambda ((procedure? pred) (list? list)) list?) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "The remp procedure applies proc to each element of list and returns a list of the elements of list for which proc returned #f.")) ((name . "remove") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remove procedure return a list of the elements that are not obj as according to equal?.")) ((name . "remv") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remv procedure return a list of the elements that are not obj as according to eqv?.")) ((name . "remq") (signature lambda (obj (list? list)) list?) (tags pure) (desc . "The remq procedure return a list of the elements that are not obj as according to eq?.")) ((name . "memp") (signature lambda ((procedure? pred) (list? list)) (or #f list?)) (subsigs (pred (lambda (obj) *))) (tags pure) (desc . "Proc should accept one argument and return a single value. Proc should not mutate list. Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memp procedure applies proc to the cars of the sublists of list until it finds one for which proc returns a true value. Proc is always called in the same dynamic environment as memp itself. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned.")) ((name . "member") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The member procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The member procedure uses equal? to compare obj with the elements of list.")) ((name . "memq") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memq procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The memq procedure uses eq? to compare obj with the elements of list.")) ((name . "memv") (signature lambda (obj (list? list)) (or #f list?)) (tags pure) (desc . "Returns the first sublist of list whose car satisfies a given condition, where the sublists of lists are the lists returned by (list-tail list k) for k less than the length of list. The memv procedure looks for the first occurrence of obj. If list does not contain an element satisfying the condition, then #f (not the empty list) is returned. The memv procedure uses eqv? to compare obj with the elements of list.")) ((name . "assp") (signature lambda ((procedure? pred) (list? alist)) (or pair? #f)) (subsigs (pred (lambda (obj) *)) (alist (alist key value))) (tags pure) (desc . "Alist (for \"association list\") should be a list of pairs. Proc should accept one argument and return a single value. Proc should not mutate alist. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assp procedure successively applies proc to the car fields of alist and looks for a pair for which it returns a true value. Proc is always called in the same dynamic environment as assp itself.")) ((name . "assoc") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assoc procedure uses equal? to compare obj with the car fields of the pairs in alist.")) ((name . "assq") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assq procedure uses eq? to compare obj with the car fields of the pairs in alist.")) ((name . "assv") (signature lambda (obj (list? alist)) (or pair? #f)) (subsigs (alist (alist key value))) (tags pure) (desc . " Alist (for \"association list\") should be a list of pairs. The procedure finds the first pair in alist whose car field satisfies a given condition, and returns that pair without traversing alist further. If no pair in alist satisfies the condition, then #f is returned. The assoc procedure looks for a pair that has obj as its car. The assv procedure uses eqv? to compare obj with the car fields of the pairs in alist.")) ((name . "cons*") (signature lambda (elt1 elt2 ...) *) (tags pure) (desc . "If called with at least two arguments, cons* returns a freshly allocated chain of pairs whose cars are obj1, ..., objn, and whose last cdr is obj. If called with only one argument, cons* returns that argument.")))
a46e21133e99147143c61901ace5eb6f7be77fdea54d602046606fcc63972ee4
samply/blaze
measure.clj
(ns blaze.fhir.operation.evaluate-measure.measure (:require [blaze.anomaly :as ba :refer [if-ok when-ok]] [blaze.coll.core :as coll] [blaze.cql-translator :as cql-translator] [blaze.db.api :as d] [blaze.elm.compiler.library :as library] [blaze.fhir.operation.evaluate-measure.measure.population :as population] [blaze.fhir.operation.evaluate-measure.measure.stratifier :as stratifier] [blaze.fhir.operation.evaluate-measure.measure.util :as u] [blaze.fhir.spec :as fhir-spec] [blaze.fhir.spec.type :as type] [blaze.handler.fhir.util :as fhir-util] [blaze.luid :as luid] [clojure.string :as str] [java-time.api :as time] [prometheus.alpha :as prom] [taoensso.timbre :as log]) (:import [java.nio.charset StandardCharsets] [java.time Clock OffsetDateTime] [java.util Base64])) (set! *warn-on-reflection* true) (prom/defhistogram compile-duration-seconds "$evaluate-measure compiling latencies in seconds." {:namespace "fhir" :subsystem "evaluate_measure"} (take 12 (iterate #(* 2 %) 0.001))) (prom/defhistogram evaluate-duration-seconds "$evaluate-measure evaluating latencies in seconds." {:namespace "fhir" :subsystem "evaluate_measure"} (take 22 (iterate #(* 1.4 %) 0.1)) "subject_type") ;; ---- Compilation ----------------------------------------------------------- (defn- extract-cql-code "Extracts the CQL code from the first attachment of `library`. Returns an anomaly on errors." {:arglists '([library])} [{:keys [id content]}] (if-let [{:keys [contentType data]} (first content)] (if (= "text/cql" (type/value contentType)) (let [data (type/value data)] (if data (String. ^bytes (.decode (Base64/getDecoder) ^String data) StandardCharsets/UTF_8) (ba/incorrect (format "Missing embedded data of first attachment in library with id `%s`." id) :fhir/issue "value" :fhir.issue/expression "Library.content[0].data"))) (ba/incorrect (format "Non `text/cql` content type of `%s` of first attachment in library with id `%s`." contentType id) :fhir/issue "value" :fhir.issue/expression "Library.content[0].contentType")) (ba/incorrect (format "Missing content in library with id `%s`." id) :fhir/issue "value" :fhir.issue/expression "Library.content"))) (defn- translate [cql-code] (-> (cql-translator/translate cql-code) (ba/exceptionally #(assoc % :fhir/issue "value" :fhir.issue/expression "Measure.library")))) (defn- compile-library* "Compiles the CQL code from the first attachment in the `library` resource using `node`. Returns an anomaly on errors." [node library] (when-ok [cql-code (extract-cql-code library) library (translate cql-code)] (library/compile-library node library {}))) (defn- compile-library "Compiles the CQL code from the first attachment in the `library` resource using `node`. Returns an anomaly on errors." {:arglists '([node library])} [node {:keys [id] :as library}] (log/debug (format "Start compiling Library with ID `%s`..." id)) (let [timer (prom/timer compile-duration-seconds)] (try (compile-library* node library) (finally (let [duration (prom/observe-duration! timer)] (log/debug (format "Compiled Library with ID `%s` in %.0f ms." id (* duration 1e3)))))))) (defn- first-library-by-url [db url] (coll/first (d/type-query db "Library" [["url" url]]))) (defn- non-deleted-library-handle [db id] (when-let [handle (d/resource-handle db "Library" id)] (when-not (= (:op handle) :delete) handle))) (defn- find-library-handle [db library-ref] (if-let [handle (first-library-by-url db library-ref)] handle (non-deleted-library-handle db (peek (str/split library-ref #"/"))))) (defn- find-library [db library-ref] (when-let [handle (find-library-handle db library-ref)] @(d/pull db handle))) (defn- compile-primary-library "Compiles the CQL code from the first library resource which is referenced from `measure`. The `db` is used to load the library resource and `node` is used for compilation. Returns an anomaly on errors." [db measure] (if-let [library-ref (-> measure :library first type/value)] (if-let [library (find-library db library-ref)] (compile-library (d/node db) library) (ba/incorrect (format "The Library resource with canonical URI `%s` was not found." library-ref) :fhir/issue "value" :fhir.issue/expression "Measure.library")) (ba/unsupported "Missing primary library. Currently only CQL expressions together with one primary library are supported." :fhir/issue "not-supported" :fhir.issue/expression "Measure.library" :measure measure))) ;; ---- Evaluation ------------------------------------------------------------ (defn- evaluate-populations [{:keys [luids] :as context} populations] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx population]] (->> (population/evaluate (assoc context :luids luids) idx population) (u/merge-result ret)))) {:result [] :handles [] :luids luids :tx-ops []} populations)) (defn- evaluate-stratifiers [{:keys [luids] :as context} evaluated-populations stratifiers] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx stratifier]] (->> (stratifier/evaluate (assoc context :luids luids :stratifier-idx idx) evaluated-populations stratifier) (u/merge-result ret)))) {:result [] :luids luids :tx-ops []} stratifiers)) (defn- population-basis [{:keys [extension]}] (some (fn [{:keys [url value]}] (when (= "-populationBasis" url) (let [basis (type/value value)] (cond-> basis (= "boolean" basis) keyword)))) extension)) (defn- evaluate-group {:arglists '([context group])} [context {:keys [code population stratifier] :as group}] (when-ok [context (assoc context :population-basis (population-basis group)) {:keys [luids] :as evaluated-populations} (evaluate-populations context population) evaluated-stratifiers (evaluate-stratifiers (assoc context :luids luids) evaluated-populations stratifier)] {:result (cond-> {:fhir/type :fhir.MeasureReport/group} code (assoc :code code) (seq (:result evaluated-populations)) (assoc :population (:result evaluated-populations)) (seq (:result evaluated-stratifiers)) (assoc :stratifier (:result evaluated-stratifiers))) :tx-ops (into (:tx-ops evaluated-populations) (:tx-ops evaluated-stratifiers))})) (defn- evaluate-groups* [{:keys [luids] :as context} groups] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx group]] (->> (evaluate-group (assoc context :luids luids :group-idx idx) group) (u/merge-result ret)))) {:result [] :luids luids :tx-ops []} groups)) (defn- evaluate-groups-msg [id subject-type duration] (format "Evaluated Measure with ID `%s` and subject type `%s` in %.0f ms." id subject-type (* duration 1e3))) (defn- evaluate-groups [{:keys [subject-type] :as context} {:keys [id] groups :group}] (log/debug (format "Start evaluating Measure with ID `%s`..." id)) (let [timer (prom/timer evaluate-duration-seconds subject-type)] (when-ok [groups (evaluate-groups* context groups)] (let [duration (prom/observe-duration! timer)] (log/debug (evaluate-groups-msg id subject-type duration)) [groups duration])))) (defn- canonical [context {:keys [id url version]}] (if-let [url (type/value url)] (cond-> url version (str "|" version)) (fhir-util/instance-url context "Measure" id))) (defn- get-first-code [codings system] (some #(when (= system (-> % :system type/value)) (-> % :code type/value)) codings)) (defn- subject-type [{{codings :coding} :subject}] (or (get-first-code codings "-types") "Patient")) (defn- eval-duration [duration] (type/extension {:url "-duration" :value (type/map->Quantity {:code #fhir/code"s" :system #fhir/uri"" :unit #fhir/string"s" :value (bigdec duration)})})) (defn- local-ref [handle] (str (name (fhir-spec/fhir-type handle)) "/" (:id handle))) (defn- measure-report [{:keys [now report-type subject-handle] :as context} measure {[start end] :period} [{:keys [result]} duration]] (cond-> {:fhir/type :fhir/MeasureReport :extension [(eval-duration duration)] :status #fhir/code"complete" :type (case report-type "population" #fhir/code"summary" "subject-list" #fhir/code"subject-list" "subject" #fhir/code"individual") :measure (type/canonical (canonical context measure)) :date now :period (type/map->Period {:start (type/dateTime (str start)) :end (type/dateTime (str end))})} subject-handle (assoc :subject (type/map->Reference {:reference (local-ref subject-handle)})) (seq result) (assoc :group result))) (defn- now [clock] (OffsetDateTime/now ^Clock clock)) (defn- successive-luids [{:keys [clock rng-fn]}] (luid/successive-luids clock (rng-fn))) (defn- missing-subject-msg [type id] (format "Subject with type `%s` and id `%s` was not found." type id)) (defn- subject-handle* [db type id] (if-let [{:keys [op] :as handle} (d/resource-handle db type id)] (if (identical? :delete op) (ba/incorrect (missing-subject-msg type id)) handle) (ba/incorrect (missing-subject-msg type id)))) (defn- type-mismatch-msg [measure-subject-type eval-subject-type] (format "Type mismatch between evaluation subject `%s` and Measure subject `%s`." eval-subject-type measure-subject-type)) (defn- subject-handle [db subject-type subject-ref] (if (vector? subject-ref) (if (= subject-type (first subject-ref)) (subject-handle* db subject-type (second subject-ref)) (ba/incorrect (type-mismatch-msg subject-type (first subject-ref)))) (subject-handle* db subject-type subject-ref))) (defn- enhance-context [{:keys [clock db timeout] :as context :or {timeout (time/hours 1)}} measure {:keys [report-type subject-ref]}] (let [subject-type (subject-type measure) now (now clock) timeout-instant (time/instant (time/plus now timeout))] (when-ok [{:keys [expression-defs function-defs parameter-default-values]} (compile-primary-library db measure) subject-handle (some->> subject-ref (subject-handle db subject-type))] (cond-> (assoc context :db db :now now :timeout-eclipsed? #(not (.isBefore (.instant ^Clock clock) timeout-instant)) :timeout timeout :expression-defs expression-defs :function-defs function-defs :parameters parameter-default-values :subject-type subject-type :report-type report-type :luids (successive-luids context)) subject-handle (assoc :subject-handle subject-handle))))) (defn evaluate-measure "Evaluates `measure` inside `period` in `db` with evaluation time of `now`. Returns an already completed MeasureReport under :resource which isn't persisted and optional :tx-ops or an anomaly in case of errors." {:arglists '([context measure params])} [context {:keys [id] :as measure} params] (if-ok [context (enhance-context context measure params) [{:keys [tx-ops]} :as result] (evaluate-groups context measure)] (cond-> {:resource (measure-report context measure params result)} (seq tx-ops) (assoc :tx-ops tx-ops)) #(assoc % :measure-id id)))
null
https://raw.githubusercontent.com/samply/blaze/5a2b8d59a7a66f9e53d4550fdd2b10f4d0b4337d/modules/operation-measure-evaluate-measure/src/blaze/fhir/operation/evaluate_measure/measure.clj
clojure
---- Compilation ----------------------------------------------------------- ---- Evaluation ------------------------------------------------------------
(ns blaze.fhir.operation.evaluate-measure.measure (:require [blaze.anomaly :as ba :refer [if-ok when-ok]] [blaze.coll.core :as coll] [blaze.cql-translator :as cql-translator] [blaze.db.api :as d] [blaze.elm.compiler.library :as library] [blaze.fhir.operation.evaluate-measure.measure.population :as population] [blaze.fhir.operation.evaluate-measure.measure.stratifier :as stratifier] [blaze.fhir.operation.evaluate-measure.measure.util :as u] [blaze.fhir.spec :as fhir-spec] [blaze.fhir.spec.type :as type] [blaze.handler.fhir.util :as fhir-util] [blaze.luid :as luid] [clojure.string :as str] [java-time.api :as time] [prometheus.alpha :as prom] [taoensso.timbre :as log]) (:import [java.nio.charset StandardCharsets] [java.time Clock OffsetDateTime] [java.util Base64])) (set! *warn-on-reflection* true) (prom/defhistogram compile-duration-seconds "$evaluate-measure compiling latencies in seconds." {:namespace "fhir" :subsystem "evaluate_measure"} (take 12 (iterate #(* 2 %) 0.001))) (prom/defhistogram evaluate-duration-seconds "$evaluate-measure evaluating latencies in seconds." {:namespace "fhir" :subsystem "evaluate_measure"} (take 22 (iterate #(* 1.4 %) 0.1)) "subject_type") (defn- extract-cql-code "Extracts the CQL code from the first attachment of `library`. Returns an anomaly on errors." {:arglists '([library])} [{:keys [id content]}] (if-let [{:keys [contentType data]} (first content)] (if (= "text/cql" (type/value contentType)) (let [data (type/value data)] (if data (String. ^bytes (.decode (Base64/getDecoder) ^String data) StandardCharsets/UTF_8) (ba/incorrect (format "Missing embedded data of first attachment in library with id `%s`." id) :fhir/issue "value" :fhir.issue/expression "Library.content[0].data"))) (ba/incorrect (format "Non `text/cql` content type of `%s` of first attachment in library with id `%s`." contentType id) :fhir/issue "value" :fhir.issue/expression "Library.content[0].contentType")) (ba/incorrect (format "Missing content in library with id `%s`." id) :fhir/issue "value" :fhir.issue/expression "Library.content"))) (defn- translate [cql-code] (-> (cql-translator/translate cql-code) (ba/exceptionally #(assoc % :fhir/issue "value" :fhir.issue/expression "Measure.library")))) (defn- compile-library* "Compiles the CQL code from the first attachment in the `library` resource using `node`. Returns an anomaly on errors." [node library] (when-ok [cql-code (extract-cql-code library) library (translate cql-code)] (library/compile-library node library {}))) (defn- compile-library "Compiles the CQL code from the first attachment in the `library` resource using `node`. Returns an anomaly on errors." {:arglists '([node library])} [node {:keys [id] :as library}] (log/debug (format "Start compiling Library with ID `%s`..." id)) (let [timer (prom/timer compile-duration-seconds)] (try (compile-library* node library) (finally (let [duration (prom/observe-duration! timer)] (log/debug (format "Compiled Library with ID `%s` in %.0f ms." id (* duration 1e3)))))))) (defn- first-library-by-url [db url] (coll/first (d/type-query db "Library" [["url" url]]))) (defn- non-deleted-library-handle [db id] (when-let [handle (d/resource-handle db "Library" id)] (when-not (= (:op handle) :delete) handle))) (defn- find-library-handle [db library-ref] (if-let [handle (first-library-by-url db library-ref)] handle (non-deleted-library-handle db (peek (str/split library-ref #"/"))))) (defn- find-library [db library-ref] (when-let [handle (find-library-handle db library-ref)] @(d/pull db handle))) (defn- compile-primary-library "Compiles the CQL code from the first library resource which is referenced from `measure`. The `db` is used to load the library resource and `node` is used for compilation. Returns an anomaly on errors." [db measure] (if-let [library-ref (-> measure :library first type/value)] (if-let [library (find-library db library-ref)] (compile-library (d/node db) library) (ba/incorrect (format "The Library resource with canonical URI `%s` was not found." library-ref) :fhir/issue "value" :fhir.issue/expression "Measure.library")) (ba/unsupported "Missing primary library. Currently only CQL expressions together with one primary library are supported." :fhir/issue "not-supported" :fhir.issue/expression "Measure.library" :measure measure))) (defn- evaluate-populations [{:keys [luids] :as context} populations] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx population]] (->> (population/evaluate (assoc context :luids luids) idx population) (u/merge-result ret)))) {:result [] :handles [] :luids luids :tx-ops []} populations)) (defn- evaluate-stratifiers [{:keys [luids] :as context} evaluated-populations stratifiers] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx stratifier]] (->> (stratifier/evaluate (assoc context :luids luids :stratifier-idx idx) evaluated-populations stratifier) (u/merge-result ret)))) {:result [] :luids luids :tx-ops []} stratifiers)) (defn- population-basis [{:keys [extension]}] (some (fn [{:keys [url value]}] (when (= "-populationBasis" url) (let [basis (type/value value)] (cond-> basis (= "boolean" basis) keyword)))) extension)) (defn- evaluate-group {:arglists '([context group])} [context {:keys [code population stratifier] :as group}] (when-ok [context (assoc context :population-basis (population-basis group)) {:keys [luids] :as evaluated-populations} (evaluate-populations context population) evaluated-stratifiers (evaluate-stratifiers (assoc context :luids luids) evaluated-populations stratifier)] {:result (cond-> {:fhir/type :fhir.MeasureReport/group} code (assoc :code code) (seq (:result evaluated-populations)) (assoc :population (:result evaluated-populations)) (seq (:result evaluated-stratifiers)) (assoc :stratifier (:result evaluated-stratifiers))) :tx-ops (into (:tx-ops evaluated-populations) (:tx-ops evaluated-stratifiers))})) (defn- evaluate-groups* [{:keys [luids] :as context} groups] (transduce (map-indexed vector) (completing (fn [{:keys [luids] :as ret} [idx group]] (->> (evaluate-group (assoc context :luids luids :group-idx idx) group) (u/merge-result ret)))) {:result [] :luids luids :tx-ops []} groups)) (defn- evaluate-groups-msg [id subject-type duration] (format "Evaluated Measure with ID `%s` and subject type `%s` in %.0f ms." id subject-type (* duration 1e3))) (defn- evaluate-groups [{:keys [subject-type] :as context} {:keys [id] groups :group}] (log/debug (format "Start evaluating Measure with ID `%s`..." id)) (let [timer (prom/timer evaluate-duration-seconds subject-type)] (when-ok [groups (evaluate-groups* context groups)] (let [duration (prom/observe-duration! timer)] (log/debug (evaluate-groups-msg id subject-type duration)) [groups duration])))) (defn- canonical [context {:keys [id url version]}] (if-let [url (type/value url)] (cond-> url version (str "|" version)) (fhir-util/instance-url context "Measure" id))) (defn- get-first-code [codings system] (some #(when (= system (-> % :system type/value)) (-> % :code type/value)) codings)) (defn- subject-type [{{codings :coding} :subject}] (or (get-first-code codings "-types") "Patient")) (defn- eval-duration [duration] (type/extension {:url "-duration" :value (type/map->Quantity {:code #fhir/code"s" :system #fhir/uri"" :unit #fhir/string"s" :value (bigdec duration)})})) (defn- local-ref [handle] (str (name (fhir-spec/fhir-type handle)) "/" (:id handle))) (defn- measure-report [{:keys [now report-type subject-handle] :as context} measure {[start end] :period} [{:keys [result]} duration]] (cond-> {:fhir/type :fhir/MeasureReport :extension [(eval-duration duration)] :status #fhir/code"complete" :type (case report-type "population" #fhir/code"summary" "subject-list" #fhir/code"subject-list" "subject" #fhir/code"individual") :measure (type/canonical (canonical context measure)) :date now :period (type/map->Period {:start (type/dateTime (str start)) :end (type/dateTime (str end))})} subject-handle (assoc :subject (type/map->Reference {:reference (local-ref subject-handle)})) (seq result) (assoc :group result))) (defn- now [clock] (OffsetDateTime/now ^Clock clock)) (defn- successive-luids [{:keys [clock rng-fn]}] (luid/successive-luids clock (rng-fn))) (defn- missing-subject-msg [type id] (format "Subject with type `%s` and id `%s` was not found." type id)) (defn- subject-handle* [db type id] (if-let [{:keys [op] :as handle} (d/resource-handle db type id)] (if (identical? :delete op) (ba/incorrect (missing-subject-msg type id)) handle) (ba/incorrect (missing-subject-msg type id)))) (defn- type-mismatch-msg [measure-subject-type eval-subject-type] (format "Type mismatch between evaluation subject `%s` and Measure subject `%s`." eval-subject-type measure-subject-type)) (defn- subject-handle [db subject-type subject-ref] (if (vector? subject-ref) (if (= subject-type (first subject-ref)) (subject-handle* db subject-type (second subject-ref)) (ba/incorrect (type-mismatch-msg subject-type (first subject-ref)))) (subject-handle* db subject-type subject-ref))) (defn- enhance-context [{:keys [clock db timeout] :as context :or {timeout (time/hours 1)}} measure {:keys [report-type subject-ref]}] (let [subject-type (subject-type measure) now (now clock) timeout-instant (time/instant (time/plus now timeout))] (when-ok [{:keys [expression-defs function-defs parameter-default-values]} (compile-primary-library db measure) subject-handle (some->> subject-ref (subject-handle db subject-type))] (cond-> (assoc context :db db :now now :timeout-eclipsed? #(not (.isBefore (.instant ^Clock clock) timeout-instant)) :timeout timeout :expression-defs expression-defs :function-defs function-defs :parameters parameter-default-values :subject-type subject-type :report-type report-type :luids (successive-luids context)) subject-handle (assoc :subject-handle subject-handle))))) (defn evaluate-measure "Evaluates `measure` inside `period` in `db` with evaluation time of `now`. Returns an already completed MeasureReport under :resource which isn't persisted and optional :tx-ops or an anomaly in case of errors." {:arglists '([context measure params])} [context {:keys [id] :as measure} params] (if-ok [context (enhance-context context measure params) [{:keys [tx-ops]} :as result] (evaluate-groups context measure)] (cond-> {:resource (measure-report context measure params result)} (seq tx-ops) (assoc :tx-ops tx-ops)) #(assoc % :measure-id id)))
518842c449e0dfde30d302308e3ab700cc41549f1b0c9c326903e95745efa5a4
xvw/preface
writer.mli
(** Functors that generate a suite for a [Writer]. *) module Suite (Req_m : Model.COVARIANT_1) (M : Preface_specs.MONAD with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_functor (Req_m : Model.COVARIANT_1) (M : Preface_specs.FUNCTOR with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_invariant (Req_m : Model.COVARIANT_1) (M : Preface_specs.FUNCTOR with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_applicative (Req_m : Model.COVARIANT_1) (M : Preface_specs.APPLICATIVE with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_alternative (Req_m : Model.COVARIANT_1) (M : Preface_specs.ALTERNATIVE with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_monad_plus (Req_m : Model.COVARIANT_1) (M : Preface_specs.MONAD_PLUS with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE
null
https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/lib/preface_qcheck/writer.mli
ocaml
* Functors that generate a suite for a [Writer].
module Suite (Req_m : Model.COVARIANT_1) (M : Preface_specs.MONAD with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_functor (Req_m : Model.COVARIANT_1) (M : Preface_specs.FUNCTOR with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_invariant (Req_m : Model.COVARIANT_1) (M : Preface_specs.FUNCTOR with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_applicative (Req_m : Model.COVARIANT_1) (M : Preface_specs.APPLICATIVE with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_alternative (Req_m : Model.COVARIANT_1) (M : Preface_specs.ALTERNATIVE with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) : Model.SUITE module Suite_monad_plus (Req_m : Model.COVARIANT_1) (M : Preface_specs.MONAD_PLUS with type 'a t = 'a Req_m.t) (Req_t : Model.T0) (Tape : Preface_specs.MONOID with type t = Req_t.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE
70b5c080cbf370c0661b32ec1632b88c74016e872053d7cb93e03faa00975a17
nakagami/efirebirdsql
efirebirdsql_socket.erl
The MIT License ( MIT ) Copyright ( c ) 2016 - 2021 Hajime Nakagami< > -module(efirebirdsql_socket). -export([send/2, recv/2, recv_align/2, recv_null_bitmap/2]). -include("efirebirdsql.hrl"). send(Conn, Data) when Conn#conn.write_state =:= undefined -> gen_tcp:send(Conn#conn.sock, Data); send(Conn, Message) -> Encrypted = crypto:crypto_update(Conn#conn.write_state, Message), gen_tcp:send(Conn#conn.sock, Encrypted). recv(_Conn, Len) when Len =:= 0 -> {ok, []}; recv(Conn, Len) when Conn#conn.read_state =:= undefined -> gen_tcp:recv(Conn#conn.sock, Len); recv(Conn, Len) -> {T, Encrypted} = gen_tcp:recv(Conn#conn.sock, Len), Message = crypto:crypto_update(Conn#conn.read_state, Encrypted), {T, Message}. recv_align(Conn, Len) -> {T, V} = recv(Conn, Len), if Len rem 4 =/= 0 -> recv(Conn, 4 - (Len rem 4)); true -> nil end, {T, V}. recv_null_bitmap(_Conn, BitLen) when BitLen =:= 0 -> <<>>; recv_null_bitmap(Conn, BitLen) -> Div8 = BitLen div 8, Len = if BitLen rem 8 =:= 0 -> Div8; BitLen rem 8 =/= 0 -> Div8 + 1 end, {ok, Buf} = recv_align(Conn, Len), <<Bitmap:Len/little-unit:8>> = Buf, Bitmap.
null
https://raw.githubusercontent.com/nakagami/efirebirdsql/d28ff4024211cda37f92667bccbaa7af50d2faf0/src/efirebirdsql_socket.erl
erlang
The MIT License ( MIT ) Copyright ( c ) 2016 - 2021 Hajime Nakagami< > -module(efirebirdsql_socket). -export([send/2, recv/2, recv_align/2, recv_null_bitmap/2]). -include("efirebirdsql.hrl"). send(Conn, Data) when Conn#conn.write_state =:= undefined -> gen_tcp:send(Conn#conn.sock, Data); send(Conn, Message) -> Encrypted = crypto:crypto_update(Conn#conn.write_state, Message), gen_tcp:send(Conn#conn.sock, Encrypted). recv(_Conn, Len) when Len =:= 0 -> {ok, []}; recv(Conn, Len) when Conn#conn.read_state =:= undefined -> gen_tcp:recv(Conn#conn.sock, Len); recv(Conn, Len) -> {T, Encrypted} = gen_tcp:recv(Conn#conn.sock, Len), Message = crypto:crypto_update(Conn#conn.read_state, Encrypted), {T, Message}. recv_align(Conn, Len) -> {T, V} = recv(Conn, Len), if Len rem 4 =/= 0 -> recv(Conn, 4 - (Len rem 4)); true -> nil end, {T, V}. recv_null_bitmap(_Conn, BitLen) when BitLen =:= 0 -> <<>>; recv_null_bitmap(Conn, BitLen) -> Div8 = BitLen div 8, Len = if BitLen rem 8 =:= 0 -> Div8; BitLen rem 8 =/= 0 -> Div8 + 1 end, {ok, Buf} = recv_align(Conn, Len), <<Bitmap:Len/little-unit:8>> = Buf, Bitmap.
60a2abf8cedf4169391c7e633a12b99d252e3fd03363f72ad1fc70607c702270
AccelerateHS/accelerate
Unique.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Array.Accelerate.Array.Unique Copyright : [ 2016 .. 2020 ] The Accelerate Team -- License : BSD3 -- Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC extensions ) -- module Data.Array.Accelerate.Array.Unique where import Data.Array.Accelerate.Lifetime import Control.Applicative import Control.Concurrent.Unique import Control.DeepSeq import Data.Word import Foreign.ForeignPtr import Foreign.ForeignPtr.Unsafe import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import Language.Haskell.TH.Extra import System.IO.Unsafe import Prelude -- | A uniquely identifiable array. -- -- For the purposes of memory management, we use arrays as keys in a table. For -- this reason we need a way to uniquely identify each array we create. We do -- this by attaching a unique identifier to each array. -- -- Note: [Unique array strictness] -- -- The actual array data is in many cases unnecessary. For discrete memory -- backends such as for GPUs, we require the unique identifier to track the data -- in the remote memory space, but the data will in most cases never be copied -- back to the host. Thus, the array payload field is only lazily allocated, and -- we should be careful not to make this field overly strict. -- data UniqueArray e = UniqueArray { uniqueArrayId :: {-# UNPACK #-} !Unique , uniqueArrayData :: {-# UNPACK #-} !(Lifetime (ForeignPtr e)) } instance NFData (UniqueArray e) where rnf = rnfUniqueArray | Create a new UniqueArray -- # INLINE newUniqueArray # newUniqueArray :: ForeignPtr e -> IO (UniqueArray e) newUniqueArray fp = UniqueArray <$> newUnique <*> newLifetime fp -- | Access the pointer backing the unique array. -- -- The array data is kept alive at least during the whole action, even if it is -- not directly used inside. Note that it is not safe to return the pointer from -- the action and use it after the action completes. All uses of the pointer -- should be inside the bracketed function. -- # INLINE withUniqueArrayPtr # withUniqueArrayPtr :: UniqueArray a -> (Ptr a -> IO b) -> IO b withUniqueArrayPtr ua go = withLifetime (uniqueArrayData ua) $ \fp -> withForeignPtr fp go -- | Returns the element of an immutable array at the specified index. This -- does no bounds checking. -- # INLINE unsafeIndexArray # unsafeIndexArray :: Storable e => UniqueArray e -> Int -> e unsafeIndexArray !ua !i = unsafePerformIO $! unsafeReadArray ua i -- | Read an element from a mutable array at the given index. This does no -- bounds checking. -- # INLINE unsafeReadArray # unsafeReadArray :: Storable e => UniqueArray e -> Int -> IO e unsafeReadArray !ua !i = withUniqueArrayPtr ua $ \ptr -> peekElemOff ptr i -- | Write an element into a mutable array at the given index. This does no -- bounds checking. -- # INLINE unsafeWriteArray # unsafeWriteArray :: Storable e => UniqueArray e -> Int -> e -> IO () unsafeWriteArray !ua !i !e = withUniqueArrayPtr ua $ \ptr -> pokeElemOff ptr i e -- | Extract the pointer backing the unique array. -- -- This is potentially unsafe, as if the argument is the last occurrence of this -- unique array then the finalisers will be run, potentially invalidating the -- plain pointer just obtained. -- -- See also: 'unsafeGetValue', 'unsafeForeignPtrToPtr'. -- # INLINE unsafeUniqueArrayPtr # unsafeUniqueArrayPtr :: UniqueArray a -> Ptr a unsafeUniqueArrayPtr = unsafeForeignPtrToPtr . unsafeGetValue . uniqueArrayData -- | Ensure that the unique array is alive at the given place in a sequence of IO actions . Note that this does not force the actual array payload . -- -- See: [Unique array strictness] -- # INLINE touchUniqueArray # touchUniqueArray :: UniqueArray a -> IO () touchUniqueArray = touchLifetime . uniqueArrayData rnfUniqueArray :: UniqueArray a -> () rnfUniqueArray (UniqueArray _ ad) = unsafeGetValue ad `seq` () -- TODO: Make sure that the data is correctly aligned... -- liftUniqueArray :: forall a. Storable a => Int -> UniqueArray a -> CodeQ (UniqueArray a) liftUniqueArray sz ua = unsafeCodeCoerce $ do bytes <- runIO $ peekArray (sizeOf (undefined::a) * sz) (castPtr (unsafeUniqueArrayPtr ua) :: Ptr Word8) [| unsafePerformIO $ do fp <- newForeignPtr_ (Ptr $(litE (StringPrimL bytes))) ua' <- newUniqueArray (castForeignPtr fp) return ua' |]
null
https://raw.githubusercontent.com/AccelerateHS/accelerate/7c769b761d0b2a91f318096b9dd3fced94616961/src/Data/Array/Accelerate/Array/Unique.hs
haskell
# LANGUAGE BangPatterns # # OPTIONS_HADDOCK hide # | Module : Data.Array.Accelerate.Array.Unique License : BSD3 Stability : experimental | A uniquely identifiable array. For the purposes of memory management, we use arrays as keys in a table. For this reason we need a way to uniquely identify each array we create. We do this by attaching a unique identifier to each array. Note: [Unique array strictness] The actual array data is in many cases unnecessary. For discrete memory backends such as for GPUs, we require the unique identifier to track the data in the remote memory space, but the data will in most cases never be copied back to the host. Thus, the array payload field is only lazily allocated, and we should be careful not to make this field overly strict. # UNPACK # # UNPACK # | Access the pointer backing the unique array. The array data is kept alive at least during the whole action, even if it is not directly used inside. Note that it is not safe to return the pointer from the action and use it after the action completes. All uses of the pointer should be inside the bracketed function. | Returns the element of an immutable array at the specified index. This does no bounds checking. | Read an element from a mutable array at the given index. This does no bounds checking. | Write an element into a mutable array at the given index. This does no bounds checking. | Extract the pointer backing the unique array. This is potentially unsafe, as if the argument is the last occurrence of this unique array then the finalisers will be run, potentially invalidating the plain pointer just obtained. See also: 'unsafeGetValue', 'unsafeForeignPtrToPtr'. | Ensure that the unique array is alive at the given place in a sequence of See: [Unique array strictness] TODO: Make sure that the data is correctly aligned...
# LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # Copyright : [ 2016 .. 2020 ] The Accelerate Team Maintainer : < > Portability : non - portable ( GHC extensions ) module Data.Array.Accelerate.Array.Unique where import Data.Array.Accelerate.Lifetime import Control.Applicative import Control.Concurrent.Unique import Control.DeepSeq import Data.Word import Foreign.ForeignPtr import Foreign.ForeignPtr.Unsafe import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import Language.Haskell.TH.Extra import System.IO.Unsafe import Prelude data UniqueArray e = UniqueArray } instance NFData (UniqueArray e) where rnf = rnfUniqueArray | Create a new UniqueArray # INLINE newUniqueArray # newUniqueArray :: ForeignPtr e -> IO (UniqueArray e) newUniqueArray fp = UniqueArray <$> newUnique <*> newLifetime fp # INLINE withUniqueArrayPtr # withUniqueArrayPtr :: UniqueArray a -> (Ptr a -> IO b) -> IO b withUniqueArrayPtr ua go = withLifetime (uniqueArrayData ua) $ \fp -> withForeignPtr fp go # INLINE unsafeIndexArray # unsafeIndexArray :: Storable e => UniqueArray e -> Int -> e unsafeIndexArray !ua !i = unsafePerformIO $! unsafeReadArray ua i # INLINE unsafeReadArray # unsafeReadArray :: Storable e => UniqueArray e -> Int -> IO e unsafeReadArray !ua !i = withUniqueArrayPtr ua $ \ptr -> peekElemOff ptr i # INLINE unsafeWriteArray # unsafeWriteArray :: Storable e => UniqueArray e -> Int -> e -> IO () unsafeWriteArray !ua !i !e = withUniqueArrayPtr ua $ \ptr -> pokeElemOff ptr i e # INLINE unsafeUniqueArrayPtr # unsafeUniqueArrayPtr :: UniqueArray a -> Ptr a unsafeUniqueArrayPtr = unsafeForeignPtrToPtr . unsafeGetValue . uniqueArrayData IO actions . Note that this does not force the actual array payload . # INLINE touchUniqueArray # touchUniqueArray :: UniqueArray a -> IO () touchUniqueArray = touchLifetime . uniqueArrayData rnfUniqueArray :: UniqueArray a -> () rnfUniqueArray (UniqueArray _ ad) = unsafeGetValue ad `seq` () liftUniqueArray :: forall a. Storable a => Int -> UniqueArray a -> CodeQ (UniqueArray a) liftUniqueArray sz ua = unsafeCodeCoerce $ do bytes <- runIO $ peekArray (sizeOf (undefined::a) * sz) (castPtr (unsafeUniqueArrayPtr ua) :: Ptr Word8) [| unsafePerformIO $ do fp <- newForeignPtr_ (Ptr $(litE (StringPrimL bytes))) ua' <- newUniqueArray (castForeignPtr fp) return ua' |]
1b427f2fc05371bfec3fb5a0f2128ceb3562e7f2b6358d3c687ef34bcc7c107b
mukul-rathi/bolt
update_identifier_capabilities.mli
open Ast.Ast_types open Desugaring.Desugared_ast (** Update identifiers that match the given names, filtering by [capability list -> capability -> bool] - a function that given a list of all the capabilities, decides whether a capability should be in the identifier. *) val update_matching_identifier_caps_block_expr : Var_name.t list -> (capability list -> capability -> bool) -> block_expr -> block_expr
null
https://raw.githubusercontent.com/mukul-rathi/bolt/1faf19d698852fdb6af2ee005a5f036ee1c76503/src/frontend/data_race_checker/update_identifier_capabilities.mli
ocaml
* Update identifiers that match the given names, filtering by [capability list -> capability -> bool] - a function that given a list of all the capabilities, decides whether a capability should be in the identifier.
open Ast.Ast_types open Desugaring.Desugared_ast val update_matching_identifier_caps_block_expr : Var_name.t list -> (capability list -> capability -> bool) -> block_expr -> block_expr
9cbd9c6c39edd9789031498f116461ff9ce828a6172940460b57ed226e6f7ecd
danehuang/augurv2
Main.hs
import Data.Either import Control.Monad.Except import AstUtil.Fresh import AstUtil.Pretty import qualified Core.ParseCore import Low.ParseLowPP import Low.LowSyn import Core.CoreSyn import Core.DensSyn import Core.LintCore -- import Low.LowpPrimSyn import Low.RnLow import Low . import qualified Core.RnCore import Compile.Compile import Compile.CompData import Rv.ParseRv import Rv.LowerRv type TestM = ExceptT String IO testCompile :: String -> Maybe String -> [Int] -> Target -> IO () testCompile model Nothing rtSizes target = do fModel <- readFile model case (Rv.ParseRv.runParseModel fModel) of Right model -> do v <- runComp (compile model Nothing rtSizes target) case v of Left errMsg -> putStrLn $ "ERROR: " ++ errMsg Right (pyModParam, pyTys, inferHdr, inferCode) -> putStrLn $ pprShow inferCode testCompile model (Just infer) rtSizes target = do fModel <- readFile model fInfer <- readFile infer case (Rv.ParseRv.runParseModel fModel, Rv.ParseRv.runParseKer fInfer) of (Right model, Right infer) -> do v <- runComp (compile model (Just infer) rtSizes target) case v of Left errMsg -> putStrLn $ "ERROR: " ++ errMsg Right (pyModParam, pyTys, inferHdr, inferCode) -> putStrLn $ pprShow inferCode (Left errMsg, _) -> putStrLn $ "Error parsing model: " ++ errMsg (_, Left errMsg) -> putStrLn $ "Error parsing inference: " ++ errMsg main :: IO () main = do let target = GPU BlkStrat -- target = CPU -- [ K, N, lam, x ] testCompile " test / hlr.rv " ( Just " test / hlr1.infer " ) [ 10 , 1000 , 1 , -1 ] target testCompile " test / hlr.rv " ( Just " test / hlr2.infer " ) [ 10 , 1000 , 1 , -1 , -1 , -1 , 10 , 1000 ] target -- testCompile "test/dethlr.rv" Nothing -- testCompile "test/dethlr.rv" (Just "test/hlr1.infer") target -- testCompile "test/dethlr.rv" (Just "test/hlr2.infer") target -- testCompile "test/mvgmm.rv" Nothing -- testCompile "test/mvgmm.rv" (Just "test/mvgmm1.infer") [] target -- testCompile "test/mvgmm.rv" (Just "test/mvgmm2.infer") [] target -- testCompile "test/mvgmm.rv" (Just "test/mvgmm3.infer") [] target testCompile " test / mvgmm.rv " ( Just " test / " ) [ ] target -- testCompile "test/mvgmm.rv" (Just "test/mvgmm5.infer") [] target -- testCompile "test/mvgmm.rv" (Just "test/mvgmm6.infer") [] target -- testCompile "test/hmvgmm.rv" (Just "test/hmvgmm1.infer") [] target testCompile " test / hmvgmm.rv " ( Just " test / " ) target -- testCompile "test/hmvgmm.rv" (Just "test/hmvgmm3.infer") target K = 3 , D = 4 , N = -1 , sizeof(alpha ) = 3 , sizeof(beta ) = 20 testCompile "test/lda.rv" (Just "test/lda1.infer") [3, 4, -1, 3, 20] target
null
https://raw.githubusercontent.com/danehuang/augurv2/480459bcc2eff898370a4e1b4f92b08ea3ab3f7b/compiler/augur/cmd/Main.hs
haskell
import Low.LowpPrimSyn target = CPU [ K, N, lam, x ] testCompile "test/dethlr.rv" Nothing testCompile "test/dethlr.rv" (Just "test/hlr1.infer") target testCompile "test/dethlr.rv" (Just "test/hlr2.infer") target testCompile "test/mvgmm.rv" Nothing testCompile "test/mvgmm.rv" (Just "test/mvgmm1.infer") [] target testCompile "test/mvgmm.rv" (Just "test/mvgmm2.infer") [] target testCompile "test/mvgmm.rv" (Just "test/mvgmm3.infer") [] target testCompile "test/mvgmm.rv" (Just "test/mvgmm5.infer") [] target testCompile "test/mvgmm.rv" (Just "test/mvgmm6.infer") [] target testCompile "test/hmvgmm.rv" (Just "test/hmvgmm1.infer") [] target testCompile "test/hmvgmm.rv" (Just "test/hmvgmm3.infer") target
import Data.Either import Control.Monad.Except import AstUtil.Fresh import AstUtil.Pretty import qualified Core.ParseCore import Low.ParseLowPP import Low.LowSyn import Core.CoreSyn import Core.DensSyn import Core.LintCore import Low.RnLow import Low . import qualified Core.RnCore import Compile.Compile import Compile.CompData import Rv.ParseRv import Rv.LowerRv type TestM = ExceptT String IO testCompile :: String -> Maybe String -> [Int] -> Target -> IO () testCompile model Nothing rtSizes target = do fModel <- readFile model case (Rv.ParseRv.runParseModel fModel) of Right model -> do v <- runComp (compile model Nothing rtSizes target) case v of Left errMsg -> putStrLn $ "ERROR: " ++ errMsg Right (pyModParam, pyTys, inferHdr, inferCode) -> putStrLn $ pprShow inferCode testCompile model (Just infer) rtSizes target = do fModel <- readFile model fInfer <- readFile infer case (Rv.ParseRv.runParseModel fModel, Rv.ParseRv.runParseKer fInfer) of (Right model, Right infer) -> do v <- runComp (compile model (Just infer) rtSizes target) case v of Left errMsg -> putStrLn $ "ERROR: " ++ errMsg Right (pyModParam, pyTys, inferHdr, inferCode) -> putStrLn $ pprShow inferCode (Left errMsg, _) -> putStrLn $ "Error parsing model: " ++ errMsg (_, Left errMsg) -> putStrLn $ "Error parsing inference: " ++ errMsg main :: IO () main = do let target = GPU BlkStrat testCompile " test / hlr.rv " ( Just " test / hlr1.infer " ) [ 10 , 1000 , 1 , -1 ] target testCompile " test / hlr.rv " ( Just " test / hlr2.infer " ) [ 10 , 1000 , 1 , -1 , -1 , -1 , 10 , 1000 ] target testCompile " test / mvgmm.rv " ( Just " test / " ) [ ] target testCompile " test / hmvgmm.rv " ( Just " test / " ) target K = 3 , D = 4 , N = -1 , sizeof(alpha ) = 3 , sizeof(beta ) = 20 testCompile "test/lda.rv" (Just "test/lda1.infer") [3, 4, -1, 3, 20] target
da293a919a1b7ec319cd8e10b2ca5a3394a0fd47b19b3cdf405587fb1cc0efd2
goldfirere/units
PreciousMetals.hs
# LANGUAGE TemplateHaskell , TypeFamilies , TypeOperators # ----------------------------------------------------------------------------- -- | -- Module : Data.Metrology.Units.PreciousMetals Copyright : ( C ) 2013 -- License : BSD-style (see LICENSE) Maintainer : ( ) -- Stability : experimental -- Portability : non-portable -- -- Units used in the measure of precious metals. ----------------------------------------------------------------------------- module Data.Units.PreciousMetals where import Data.Metrology import Data.Metrology.TH import Data.Units.SI import Data.Units.SI.Prefixes import qualified Data.Units.US.Avoirdupois as Avdp import qualified Data.Units.US.Troy as Troy declareDerivedUnit "Carat" [t| Milli :@ Gram |] 200 (Just "carat") declareDerivedUnit "Point" [t| Carat |] 0.01 (Just "point") declareDerivedUnit "AssayTon" [t| (Milli :@ Gram) :* (Avdp.Ton :/ Troy.Ounce) |] 1 (Just "AT")
null
https://raw.githubusercontent.com/goldfirere/units/4941c3b4325783ad3c5b6486231f395279d8511e/units-defs/Data/Units/PreciousMetals.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Metrology.Units.PreciousMetals License : BSD-style (see LICENSE) Stability : experimental Portability : non-portable Units used in the measure of precious metals. ---------------------------------------------------------------------------
# LANGUAGE TemplateHaskell , TypeFamilies , TypeOperators # Copyright : ( C ) 2013 Maintainer : ( ) module Data.Units.PreciousMetals where import Data.Metrology import Data.Metrology.TH import Data.Units.SI import Data.Units.SI.Prefixes import qualified Data.Units.US.Avoirdupois as Avdp import qualified Data.Units.US.Troy as Troy declareDerivedUnit "Carat" [t| Milli :@ Gram |] 200 (Just "carat") declareDerivedUnit "Point" [t| Carat |] 0.01 (Just "point") declareDerivedUnit "AssayTon" [t| (Milli :@ Gram) :* (Avdp.Ton :/ Troy.Ounce) |] 1 (Just "AT")
6a07447ef00f3eb120957ed801af3c972aa52ce79a53ac59be7ceb6326a69efd
spawnfest/eep49ers
openssl_ECC_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2018 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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. %% %% %CopyrightEnd% %% %% -module(openssl_ECC_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). %% Common test -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). %% Test cases -export([mix_sign/1]). %%-------------------------------------------------------------------- %% Common Test interface functions ----------------------------------- %%-------------------------------------------------------------------- all() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{group, 'tlsv1.2'}, {group, 'dtlsv1.2'}]; false -> [{group, 'tlsv1.2'}] end. groups() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{'tlsv1.2', [], [mix_sign]}, {'dtlsv1.2', [], [mix_sign]}]; false -> [{'tlsv1.2', [], [mix_sign]}] end. init_per_suite(Config0) -> end_per_suite(Config0), try crypto:start() of ok -> ssl_test_lib:clean_start(), case ssl_test_lib:sufficient_crypto_support(cipher_ec) of true -> Config0; false -> {skip, "Openssl does not support ECC"} end catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> application:stop(ssl), application:stop(crypto), ssl_test_lib:kill_openssl(). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group_openssl(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(skip, Config) -> Config; init_per_testcase(TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), Version = proplists:get_value(tls_version, Config), ct:log("Ciphers: ~p~n ", [ssl:cipher_suites(default, Version)]), end_per_testcase(TestCase, Config), ssl:start(), ct:timetrap({seconds, 30}), Config. end_per_testcase(_TestCase, Config) -> application:stop(ssl), Config. %%-------------------------------------------------------------------- %% Test Cases -------------------------------------------------------- %%-------------------------------------------------------------------- mix_sign(Config) -> {COpts0, SOpts0} = ssl_test_lib:make_mix_cert(Config), COpts = ssl_test_lib:ssl_options(COpts0, Config), SOpts = ssl_test_lib:ssl_options(SOpts0, Config), ECDHE_ECDSA = ssl:filter_cipher_suites(ssl:cipher_suites(default, 'tlsv1.2'), [{key_exchange, fun(ecdhe_ecdsa) -> true; (_) -> false end}]), ssl_test_lib:basic_test(COpts, [{ciphers, ECDHE_ECDSA} | SOpts], [{client_type, erlang}, {server_type, openssl} | Config]). %%-------------------------------------------------------------------- Internal functions ------------------------------------------------ %%--------------------------------------------------------------------
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/test/openssl_ECC_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. %CopyrightEnd% Common test Test cases -------------------------------------------------------------------- Common Test interface functions ----------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Test Cases -------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2018 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(openssl_ECC_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("public_key/include/public_key.hrl"). -export([all/0, groups/0, init_per_suite/1, init_per_group/2, init_per_testcase/2, end_per_suite/1, end_per_group/2, end_per_testcase/2 ]). -export([mix_sign/1]). all() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{group, 'tlsv1.2'}, {group, 'dtlsv1.2'}]; false -> [{group, 'tlsv1.2'}] end. groups() -> case ssl_test_lib:openssl_sane_dtls() of true -> [{'tlsv1.2', [], [mix_sign]}, {'dtlsv1.2', [], [mix_sign]}]; false -> [{'tlsv1.2', [], [mix_sign]}] end. init_per_suite(Config0) -> end_per_suite(Config0), try crypto:start() of ok -> ssl_test_lib:clean_start(), case ssl_test_lib:sufficient_crypto_support(cipher_ec) of true -> Config0; false -> {skip, "Openssl does not support ECC"} end catch _:_ -> {skip, "Crypto did not start"} end. end_per_suite(_Config) -> application:stop(ssl), application:stop(crypto), ssl_test_lib:kill_openssl(). init_per_group(GroupName, Config) -> ssl_test_lib:init_per_group_openssl(GroupName, Config). end_per_group(GroupName, Config) -> ssl_test_lib:end_per_group(GroupName, Config). init_per_testcase(skip, Config) -> Config; init_per_testcase(TestCase, Config) -> ssl_test_lib:ct_log_supported_protocol_versions(Config), Version = proplists:get_value(tls_version, Config), ct:log("Ciphers: ~p~n ", [ssl:cipher_suites(default, Version)]), end_per_testcase(TestCase, Config), ssl:start(), ct:timetrap({seconds, 30}), Config. end_per_testcase(_TestCase, Config) -> application:stop(ssl), Config. mix_sign(Config) -> {COpts0, SOpts0} = ssl_test_lib:make_mix_cert(Config), COpts = ssl_test_lib:ssl_options(COpts0, Config), SOpts = ssl_test_lib:ssl_options(SOpts0, Config), ECDHE_ECDSA = ssl:filter_cipher_suites(ssl:cipher_suites(default, 'tlsv1.2'), [{key_exchange, fun(ecdhe_ecdsa) -> true; (_) -> false end}]), ssl_test_lib:basic_test(COpts, [{ciphers, ECDHE_ECDSA} | SOpts], [{client_type, erlang}, {server_type, openssl} | Config]). Internal functions ------------------------------------------------
dc143f831ad483f440cc178a75b63957b10267afee6b5eddf3472c15b9fb67f2
ocaml/opam
opamCliMain.ml
(**************************************************************************) (* *) Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Cmdliner open OpamStateTypes open OpamTypesBase open OpamStd.Op exception InvalidCLI of OpamCLIVersion.Sourced.t (* [InvalidFlagContent (flag_name, Some (invalid_value, expected_value))] *) exception InvalidFlagContent of string * (string * string) option [ InvalidNewFlag ( requested_cli , flag_name , flag_valid_since ) ] exception InvalidNewFlag of OpamCLIVersion.Sourced.t * string * OpamCLIVersion.t let raise_invalid_cli : (OpamCLIVersion.Sourced.t, string option) result -> 'a = function | Ok ocli -> raise (InvalidCLI ocli) | Error None -> raise (InvalidFlagContent ("cli", None)) | Error (Some invalid) -> raise (InvalidFlagContent ("cli", Some (invalid, "major.minor"))) let raise_invalid_confirm_level invalid = let invalid = OpamStd.Option.map (fun i -> i, "one of " ^ (OpamArg.confirm_enum |> List.map (fun (_,s,_) -> Printf.sprintf "`%s'" s) |> OpamStd.Format.pretty_list ~last:"or")) invalid in raise (InvalidFlagContent ("confirm-level", invalid)) Filter and parse " --cli = v " or " --cli v " options let rec filter_cli_arg cli acc args = match args with | [] | "--" :: _ -> (cli, List.rev_append acc args) | "--cl" :: args -> filter_cli_arg cli acc ("--cli"::args) | ["--cli"] | "--cli" :: "--" :: _ -> raise_invalid_cli (Error None) | "--cli" :: arg :: args -> let version = match OpamCLIVersion.of_string_opt arg with | Some cli -> let ocli = cli, `Command_line in if OpamCLIVersion.is_supported cli then ocli else raise_invalid_cli (Ok ocli) | None -> raise_invalid_cli (Error (Some arg)) in filter_cli_arg (Some version) acc args | arg :: args -> match OpamStd.String.cut_at arg '=' with | Some ("--cl", value) | Some ("--cli", value) -> filter_cli_arg cli acc ("--cli"::value::args) | _ -> filter_cli_arg cli (arg::acc) args let is_confirm_level = OpamStd.String.is_prefix_of ~from:4 ~full:"--confirm-level" Pre - process argv processing the --yes , --confirm - level , and --cli . Returns Some cli , if --cli was encountered , a boolean indicating if --yes/-y and the list of arguments to continue with processing . Some cli, if --cli was encountered, a boolean indicating if --yes/-y and the list of arguments to continue with processing. *) let rec preprocess_argv cli yes_args confirm args = let yes = yes_args <> [] in match args with | [] -> (cli, yes, confirm, yes_args) | "--" :: _ -> (cli, yes, confirm, yes_args @ args) Note that because this is evaluated before a sub - command , all the prefixes of are assumed to valid at all times . prefixes of --yes are assumed to valid at all times. *) | ("-y" | "--y" | "--ye" | "--yes") as yes_opt :: args -> preprocess_argv cli [yes_opt] confirm args | ([c] | c :: "--" :: _) when is_confirm_level c -> raise_invalid_confirm_level None | confirm_level :: cl_arg :: args when is_confirm_level confirm_level -> let answer = match OpamStd.List.find_opt (fun (_,n,_) -> n = cl_arg) OpamArg.confirm_enum with | Some (_, _, a) -> a | None -> raise_invalid_confirm_level (Some cl_arg) in preprocess_argv cli yes_args (Some answer) args | "--cl" :: args -> preprocess_argv cli yes_args confirm ("--cli"::args) | ["--cli"] | "--cli" :: "--" :: _ -> raise_invalid_cli (Error None) | "--cli" :: arg :: args -> let version = match OpamCLIVersion.of_string_opt arg with | Some cli -> let ocli = cli, `Command_line in if OpamCLIVersion.is_supported cli then ocli else raise_invalid_cli (Ok ocli) | _ -> raise_invalid_cli (Error (Some arg)) in preprocess_argv (Some version) yes_args confirm args | arg :: rest -> match OpamStd.String.cut_at arg '=' with | Some ("--cl", value) | Some ("--cli", value) -> preprocess_argv cli yes_args confirm ("--cli"::value::rest) | Some (pre, value) when is_confirm_level pre -> preprocess_argv cli yes_args confirm ("--confirm-level"::value::rest) | _ -> if OpamCommands.is_builtin_command arg then let (cli, rest) = filter_cli_arg cli [] rest in (cli, yes, confirm, arg :: (yes_args @ rest)) else (cli, yes, confirm, args) (* Handle git-like plugins *) let check_and_run_external_commands () = Pre - process the and --cli options let (cli, yes, confirm_level, argv) = match Array.to_list Sys.argv with | prog::args -> let (ocli, yes, confirm, args) = preprocess_argv None [] None args in let ocli = match ocli with | Some ((cli, _) as ocli) -> if OpamCLIVersion.(cli < (2, 1)) then begin let cli = OpamCLIVersion.to_string cli in OpamConsole.warning "%s cannot be understood by opam %s; set %s to %s instead." (OpamConsole.colorise `bold ("--cli=" ^ cli)) cli (OpamConsole.colorise `bold "OPAMCLI") (OpamConsole.colorise `bold cli) end; ocli | None -> match OpamCLIVersion.Sourced.env (OpamClientConfig.E.cli ()) with | Some ((cli, _) as ocli) -> if OpamCLIVersion.is_supported cli then let () = if OpamCLIVersion.(cli >= (2, 1)) then let flag = "--cli=" ^ OpamCLIVersion.(to_string cli) in OpamConsole.warning "OPAMCLI should only ever be set to %s - use '%s' instead." (OpamConsole.colorise `bold "2.0") (OpamConsole.colorise `bold flag) in ocli else raise_invalid_cli (Ok ocli) | None -> OpamCLIVersion.Sourced.current in let confirm = (* hardcoded cli validation *) match confirm with | Some _ when OpamCLIVersion.(fst ocli < (2,1)) -> raise (InvalidNewFlag (ocli, "confirm-level", OpamCLIVersion.of_string "2.1")) | _ -> confirm in (ocli, yes, confirm, prog::args) | args -> (OpamCLIVersion.Sourced.current, false, None, args) in match argv with | [] | [_] -> (cli, argv) | _ :: name :: args -> if String.length name > 0 && name.[0] = '-' || OpamCommands.is_builtin_command name then (cli, argv) else (* No such command, check if there is a matching plugin *) let command = OpamPath.plugin_prefix ^ name in OpamArg.init_opam_env_variabes cli; (* `--no` is not taken into account, only `--yes/--confirm-lzvel` are preprocessed *) let yes = if yes then Some (Some true) else None in OpamCoreConfig.init ?yes ?confirm_level (); OpamFormatConfig.init (); let root_dir = OpamStateConfig.opamroot () in let has_init, root_upgraded = match OpamStateConfig.load_defaults ~lock_kind:`Lock_read root_dir with | None -> (false, false) | Some config -> let root_upgraded = let cmp = OpamVersion.compare OpamFile.Config.root_version (OpamFile.Config.opam_root_version config) in if cmp < 0 then OpamConsole.error_and_exit `Configuration_error "%s reports a newer opam version, aborting." (OpamFilename.Dir.to_string root_dir) else cmp = 0 in (true, root_upgraded) in let plugins_bin = OpamPath.plugins_bin root_dir in let plugin_symlink_present = OpamFilename.is_symlink (OpamPath.plugin_bin root_dir (OpamPackage.Name.of_string name)) in let env = if has_init then let updates = ["PATH", OpamParserTypes.PlusEq, OpamFilename.Dir.to_string plugins_bin, None] in OpamStateConfig.init ~root_dir (); match OpamStateConfig.get_switch_opt () with | None -> env_array (OpamEnv.get_pure ~updates ()) | Some sw -> env_array (OpamEnv.full_with_path ~force_path:false ~updates root_dir sw) else Unix.environment () in match OpamSystem.resolve_command ~env command with | Some command when plugin_symlink_present && root_upgraded -> let argv = Array.of_list (command :: args) in raise (OpamStd.Sys.Exec (command, argv, env)) | None when not has_init -> (cli, argv) | cmd -> (* Look for a corresponding package *) match OpamStateConfig.get_switch_opt () with | None -> (cli, argv) | Some sw -> OpamGlobalState.with_ `Lock_none @@ fun gt -> OpamSwitchState.with_ `Lock_none gt ~switch:sw @@ fun st -> let prefixed_name = OpamPath.plugin_prefix ^ name in let candidates = OpamPackage.packages_of_names st.packages (OpamPackage.Name.Set.of_list @@ (OpamStd.List.filter_map (fun s -> try Some (OpamPackage.Name.of_string s) with Failure _ -> None) [ prefixed_name; name ])) in let plugins = OpamPackage.Set.filter (fun nv -> OpamFile.OPAM.has_flag Pkgflag_Plugin (OpamSwitchState.opam st nv)) candidates in let plugins = (* NOTE: Delay the availablity check as late as possible for performance reasons *) (* See *) if OpamPackage.Set.is_empty plugins then plugins else OpamPackage.Set.inter plugins (Lazy.force st.available_packages) in let installed = OpamPackage.Set.inter plugins st.installed in if OpamPackage.Set.is_empty candidates then (cli, argv) else if not OpamPackage.Set.(is_empty installed) && cmd = None then (OpamConsole.error "Plugin %s is already installed, but no %s command was found.\n\ Try upgrading, and report to the package maintainer if \ the problem persists." (OpamPackage.to_string (OpamPackage.Set.choose installed)) command; exit (OpamStd.Sys.get_exit_code `Package_operation_error)) else if OpamPackage.Set.is_empty plugins then (OpamConsole.error "%s is not a known command or plugin (package %s does \ not have the 'plugin' flag set)." name (OpamPackage.to_string (OpamPackage.Set.max_elt candidates)); exit (OpamStd.Sys.get_exit_code `Bad_arguments)) else if (if cmd = None then OpamConsole.confirm "Opam plugin \"%s\" is not installed. \ Install it on the current switch?" else OpamConsole.confirm "Opam plugin \"%s\" may require upgrading/reinstalling. \ Reinstall the plugin on the current switch?") name then let nv = try (* If the command was resolved, attempt to find the package to reinstall. *) if cmd = None then raise Not_found else OpamPackage.package_of_name installed (OpamPackage.Name.of_string prefixed_name) with Not_found -> try OpamPackage.max_version plugins (OpamPackage.Name.of_string prefixed_name) with Not_found -> OpamPackage.max_version plugins (OpamPackage.Name.of_string name) in OpamRepositoryConfig.init (); OpamSolverConfig.init (); OpamClientConfig.init (); OpamSwitchState.with_ `Lock_write gt (fun st -> OpamSwitchState.drop @@ ( if cmd = None then OpamClient.install st [OpamSolution.eq_atom_of_package nv] else if root_upgraded then OpamClient.reinstall st [OpamSolution.eq_atom_of_package nv] else OpamClient.upgrade st ~all:false [OpamSolution.eq_atom_of_package nv]) ); match OpamSystem.resolve_command ~env command with | None -> OpamConsole.error_and_exit `Package_operation_error "Plugin %s was installed, but no %s command was found.\n\ This is probably an error in the plugin package." (OpamPackage.to_string nv) command | Some command -> OpamConsole.header_msg "Carrying on to \"%s\"" (String.concat " " (Array.to_list Sys.argv)); OpamConsole.msg "\n"; let argv = Array.of_list (command :: args) in raise (OpamStd.Sys.Exec (command, argv, env)) else (cli, argv) let display_cli_error msg = Format.eprintf "@[<v>opam: @[%a@]@,@[Usage: @[opam COMMAND ...@]@]@,\ Try `opam --help' for more information.@]@." Format.pp_print_text msg let display_cli_error fmt = Format.ksprintf display_cli_error fmt let flush_all_noerror () = (try flush stderr with _ -> ()); (try flush stdout with _ -> ()) let rec main_catch_all f = try f () with | OpamStd.Sys.Exit 0 -> () | OpamStd.Sys.Exec (cmd,args,env) -> OpamStd.Sys.exec_at_exit (); if Sys.win32 then OpamProcess.create_process_env cmd args env Unix.stdin Unix.stdout Unix.stderr |> Unix.waitpid [] |> function | _, Unix.WEXITED n -> exit n | _, (Unix.WSIGNALED n | Unix.WSTOPPED n) -> exit (128 - n) This is not how you should handle ` WSTOPPED ` ; but it does n't happen on Windows anyway . Windows anyway. *) else Unix.execvpe cmd args env | OpamFormatUpgrade.Upgrade_done (conf, reinit) -> main_catch_all @@ fun () -> OpamConsole.header_msg "Rerunning init and update"; (match reinit with | Some reinit -> reinit conf; OpamConsole.msg "Update done.\n"; exit (OpamStd.Sys.get_exit_code `Success) | None -> OpamClient.reinit ~interactive:true ~update_config:false ~bypass_checks:true conf (OpamStd.Sys.guess_shell_compat ()); OpamConsole.msg "Update done, please now retry your command.\n"; exit (OpamStd.Sys.get_exit_code `Aborted)) | e -> OpamStd.Exn.register_backtrace e; (try Sys.set_signal Sys.sigpipe Sys.Signal_default with Invalid_argument _ -> ()); flush_all_noerror (); if (OpamConsole.verbose ()) then OpamConsole.errmsg "'%s' failed.\n" (String.concat " " (Array.to_list Sys.argv)); let exit_code = match e with | OpamStd.Sys.Exit i -> if (OpamConsole.debug ()) && i <> 0 then OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); i | OpamSystem.Internal_error _ -> OpamConsole.errmsg "%s\n" (Printexc.to_string e); OpamStd.Sys.get_exit_code `Internal_error | OpamSystem.Process_error result -> OpamConsole.errmsg "%s Command %S failed:\n%s\n" (OpamConsole.colorise `red "[ERROR]") (try OpamStd.List.assoc String.equal "command" result.OpamProcess.r_info with Not_found -> "") (Printexc.to_string e); OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error | Sys.Break | OpamParallel.Errors (_, (_, Sys.Break)::_, _) -> OpamStd.Sys.get_exit_code `User_interrupt | Sys_error e when e = "Broken pipe" -> workaround warning 52 , this is a fallback ( we already handle the signal ) and there is no way around at the moment signal) and there is no way around at the moment *) 141 | InvalidCLI (cli, source) -> (* Unsupported CLI version *) let suffix = if source = `Env then " Please fix the value of the OPAMCLI environment variable, \ or use the '--cli <major>.<minor>' flag" else "" in OpamConsole.error "opam command-line version %s is not supported.%s" (OpamCLIVersion.to_string cli) suffix; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidFlagContent (flag, None) -> (* No argument given to flag *) display_cli_error "option `--%s' needs an argument" flag; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidFlagContent (flag, Some (invalid, expected)) -> (* Wrong argument kind given to flag *) display_cli_error "option `--%s': invalid value `%s', expected %s" flag invalid expected; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidNewFlag ((req_cli, _), flag, flag_cli) -> (* Requested cli is older than flag introduction *) display_cli_error "--%s was added in version %s of the opam CLI, \ but version %s has been requested, which is older." flag (OpamCLIVersion.to_string flag_cli) (OpamCLIVersion.to_string req_cli); OpamStd.Sys.get_exit_code `Bad_arguments | Failure msg -> OpamConsole.errmsg "Fatal error: %s\n" msg; OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error | _ -> OpamConsole.errmsg "Fatal error:\n%s\n" (Printexc.to_string e); OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error in exit exit_code let run () = OpamStd.Option.iter OpamVersion.set_git OpamGitVersion.version; OpamSystem.init (); OpamArg.preinit_opam_env_variables (); main_catch_all @@ fun () -> let cli, argv = check_and_run_external_commands () in let (default, commands), argv1 = match argv with | prog :: command :: argv when OpamCommands.is_admin_subcommand command -> OpamAdminCommand.get_cmdliner_parser cli, prog::argv | _ -> OpamCommands.get_cmdliner_parser cli, argv in let argv = Array.of_list argv1 in (* TODO: Get rid of this whenever is available *) let to_new_cmdliner_api (term, info) = Cmd.v info term in let default, default_info = default in let commands = List.map to_new_cmdliner_api commands in match Cmd.eval_value ~catch:false ~argv (Cmd.group ~default default_info commands) with | Error _ -> exit (OpamStd.Sys.get_exit_code `Bad_arguments) | Ok _ -> exit (OpamStd.Sys.get_exit_code `Success) let json_out () = match OpamClientConfig.(!r.json_out) with | None -> () | Some s -> let file_name () = match OpamStd.String.cut_at s '%' with | None -> OpamFilename.of_string s | Some (pfx, sfx) -> let rec getname i = let f = OpamFilename.of_string (Printf.sprintf "%s%d%s" pfx i sfx) in if OpamFilename.exists f then getname (i+1) else f in getname 1 in try let f = OpamFilename.open_out (file_name ()) in OpamJson.flush f; close_out f with e -> OpamConsole.warning "Couldn't write json log: %s" (Printexc.to_string e) let main () = OpamStd.Sys.at_exit (fun () -> flush_all_noerror (); if OpamClientConfig.(!r.print_stats) then ( OpamFile.Stats.print (); OpamSystem.print_stats (); ); json_out () ); run ()
null
https://raw.githubusercontent.com/ocaml/opam/c53b1a83d73d05e0abd361f9bc8361dcd121b6e8/src/client/opamCliMain.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ [InvalidFlagContent (flag_name, Some (invalid_value, expected_value))] Handle git-like plugins hardcoded cli validation No such command, check if there is a matching plugin `--no` is not taken into account, only `--yes/--confirm-lzvel` are preprocessed Look for a corresponding package NOTE: Delay the availablity check as late as possible for performance reasons See If the command was resolved, attempt to find the package to reinstall. Unsupported CLI version No argument given to flag Wrong argument kind given to flag Requested cli is older than flag introduction TODO: Get rid of this whenever is available
Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special open Cmdliner open OpamStateTypes open OpamTypesBase open OpamStd.Op exception InvalidCLI of OpamCLIVersion.Sourced.t exception InvalidFlagContent of string * (string * string) option [ InvalidNewFlag ( requested_cli , flag_name , flag_valid_since ) ] exception InvalidNewFlag of OpamCLIVersion.Sourced.t * string * OpamCLIVersion.t let raise_invalid_cli : (OpamCLIVersion.Sourced.t, string option) result -> 'a = function | Ok ocli -> raise (InvalidCLI ocli) | Error None -> raise (InvalidFlagContent ("cli", None)) | Error (Some invalid) -> raise (InvalidFlagContent ("cli", Some (invalid, "major.minor"))) let raise_invalid_confirm_level invalid = let invalid = OpamStd.Option.map (fun i -> i, "one of " ^ (OpamArg.confirm_enum |> List.map (fun (_,s,_) -> Printf.sprintf "`%s'" s) |> OpamStd.Format.pretty_list ~last:"or")) invalid in raise (InvalidFlagContent ("confirm-level", invalid)) Filter and parse " --cli = v " or " --cli v " options let rec filter_cli_arg cli acc args = match args with | [] | "--" :: _ -> (cli, List.rev_append acc args) | "--cl" :: args -> filter_cli_arg cli acc ("--cli"::args) | ["--cli"] | "--cli" :: "--" :: _ -> raise_invalid_cli (Error None) | "--cli" :: arg :: args -> let version = match OpamCLIVersion.of_string_opt arg with | Some cli -> let ocli = cli, `Command_line in if OpamCLIVersion.is_supported cli then ocli else raise_invalid_cli (Ok ocli) | None -> raise_invalid_cli (Error (Some arg)) in filter_cli_arg (Some version) acc args | arg :: args -> match OpamStd.String.cut_at arg '=' with | Some ("--cl", value) | Some ("--cli", value) -> filter_cli_arg cli acc ("--cli"::value::args) | _ -> filter_cli_arg cli (arg::acc) args let is_confirm_level = OpamStd.String.is_prefix_of ~from:4 ~full:"--confirm-level" Pre - process argv processing the --yes , --confirm - level , and --cli . Returns Some cli , if --cli was encountered , a boolean indicating if --yes/-y and the list of arguments to continue with processing . Some cli, if --cli was encountered, a boolean indicating if --yes/-y and the list of arguments to continue with processing. *) let rec preprocess_argv cli yes_args confirm args = let yes = yes_args <> [] in match args with | [] -> (cli, yes, confirm, yes_args) | "--" :: _ -> (cli, yes, confirm, yes_args @ args) Note that because this is evaluated before a sub - command , all the prefixes of are assumed to valid at all times . prefixes of --yes are assumed to valid at all times. *) | ("-y" | "--y" | "--ye" | "--yes") as yes_opt :: args -> preprocess_argv cli [yes_opt] confirm args | ([c] | c :: "--" :: _) when is_confirm_level c -> raise_invalid_confirm_level None | confirm_level :: cl_arg :: args when is_confirm_level confirm_level -> let answer = match OpamStd.List.find_opt (fun (_,n,_) -> n = cl_arg) OpamArg.confirm_enum with | Some (_, _, a) -> a | None -> raise_invalid_confirm_level (Some cl_arg) in preprocess_argv cli yes_args (Some answer) args | "--cl" :: args -> preprocess_argv cli yes_args confirm ("--cli"::args) | ["--cli"] | "--cli" :: "--" :: _ -> raise_invalid_cli (Error None) | "--cli" :: arg :: args -> let version = match OpamCLIVersion.of_string_opt arg with | Some cli -> let ocli = cli, `Command_line in if OpamCLIVersion.is_supported cli then ocli else raise_invalid_cli (Ok ocli) | _ -> raise_invalid_cli (Error (Some arg)) in preprocess_argv (Some version) yes_args confirm args | arg :: rest -> match OpamStd.String.cut_at arg '=' with | Some ("--cl", value) | Some ("--cli", value) -> preprocess_argv cli yes_args confirm ("--cli"::value::rest) | Some (pre, value) when is_confirm_level pre -> preprocess_argv cli yes_args confirm ("--confirm-level"::value::rest) | _ -> if OpamCommands.is_builtin_command arg then let (cli, rest) = filter_cli_arg cli [] rest in (cli, yes, confirm, arg :: (yes_args @ rest)) else (cli, yes, confirm, args) let check_and_run_external_commands () = Pre - process the and --cli options let (cli, yes, confirm_level, argv) = match Array.to_list Sys.argv with | prog::args -> let (ocli, yes, confirm, args) = preprocess_argv None [] None args in let ocli = match ocli with | Some ((cli, _) as ocli) -> if OpamCLIVersion.(cli < (2, 1)) then begin let cli = OpamCLIVersion.to_string cli in OpamConsole.warning "%s cannot be understood by opam %s; set %s to %s instead." (OpamConsole.colorise `bold ("--cli=" ^ cli)) cli (OpamConsole.colorise `bold "OPAMCLI") (OpamConsole.colorise `bold cli) end; ocli | None -> match OpamCLIVersion.Sourced.env (OpamClientConfig.E.cli ()) with | Some ((cli, _) as ocli) -> if OpamCLIVersion.is_supported cli then let () = if OpamCLIVersion.(cli >= (2, 1)) then let flag = "--cli=" ^ OpamCLIVersion.(to_string cli) in OpamConsole.warning "OPAMCLI should only ever be set to %s - use '%s' instead." (OpamConsole.colorise `bold "2.0") (OpamConsole.colorise `bold flag) in ocli else raise_invalid_cli (Ok ocli) | None -> OpamCLIVersion.Sourced.current in let confirm = match confirm with | Some _ when OpamCLIVersion.(fst ocli < (2,1)) -> raise (InvalidNewFlag (ocli, "confirm-level", OpamCLIVersion.of_string "2.1")) | _ -> confirm in (ocli, yes, confirm, prog::args) | args -> (OpamCLIVersion.Sourced.current, false, None, args) in match argv with | [] | [_] -> (cli, argv) | _ :: name :: args -> if String.length name > 0 && name.[0] = '-' || OpamCommands.is_builtin_command name then (cli, argv) else let command = OpamPath.plugin_prefix ^ name in OpamArg.init_opam_env_variabes cli; let yes = if yes then Some (Some true) else None in OpamCoreConfig.init ?yes ?confirm_level (); OpamFormatConfig.init (); let root_dir = OpamStateConfig.opamroot () in let has_init, root_upgraded = match OpamStateConfig.load_defaults ~lock_kind:`Lock_read root_dir with | None -> (false, false) | Some config -> let root_upgraded = let cmp = OpamVersion.compare OpamFile.Config.root_version (OpamFile.Config.opam_root_version config) in if cmp < 0 then OpamConsole.error_and_exit `Configuration_error "%s reports a newer opam version, aborting." (OpamFilename.Dir.to_string root_dir) else cmp = 0 in (true, root_upgraded) in let plugins_bin = OpamPath.plugins_bin root_dir in let plugin_symlink_present = OpamFilename.is_symlink (OpamPath.plugin_bin root_dir (OpamPackage.Name.of_string name)) in let env = if has_init then let updates = ["PATH", OpamParserTypes.PlusEq, OpamFilename.Dir.to_string plugins_bin, None] in OpamStateConfig.init ~root_dir (); match OpamStateConfig.get_switch_opt () with | None -> env_array (OpamEnv.get_pure ~updates ()) | Some sw -> env_array (OpamEnv.full_with_path ~force_path:false ~updates root_dir sw) else Unix.environment () in match OpamSystem.resolve_command ~env command with | Some command when plugin_symlink_present && root_upgraded -> let argv = Array.of_list (command :: args) in raise (OpamStd.Sys.Exec (command, argv, env)) | None when not has_init -> (cli, argv) | cmd -> match OpamStateConfig.get_switch_opt () with | None -> (cli, argv) | Some sw -> OpamGlobalState.with_ `Lock_none @@ fun gt -> OpamSwitchState.with_ `Lock_none gt ~switch:sw @@ fun st -> let prefixed_name = OpamPath.plugin_prefix ^ name in let candidates = OpamPackage.packages_of_names st.packages (OpamPackage.Name.Set.of_list @@ (OpamStd.List.filter_map (fun s -> try Some (OpamPackage.Name.of_string s) with Failure _ -> None) [ prefixed_name; name ])) in let plugins = OpamPackage.Set.filter (fun nv -> OpamFile.OPAM.has_flag Pkgflag_Plugin (OpamSwitchState.opam st nv)) candidates in let plugins = if OpamPackage.Set.is_empty plugins then plugins else OpamPackage.Set.inter plugins (Lazy.force st.available_packages) in let installed = OpamPackage.Set.inter plugins st.installed in if OpamPackage.Set.is_empty candidates then (cli, argv) else if not OpamPackage.Set.(is_empty installed) && cmd = None then (OpamConsole.error "Plugin %s is already installed, but no %s command was found.\n\ Try upgrading, and report to the package maintainer if \ the problem persists." (OpamPackage.to_string (OpamPackage.Set.choose installed)) command; exit (OpamStd.Sys.get_exit_code `Package_operation_error)) else if OpamPackage.Set.is_empty plugins then (OpamConsole.error "%s is not a known command or plugin (package %s does \ not have the 'plugin' flag set)." name (OpamPackage.to_string (OpamPackage.Set.max_elt candidates)); exit (OpamStd.Sys.get_exit_code `Bad_arguments)) else if (if cmd = None then OpamConsole.confirm "Opam plugin \"%s\" is not installed. \ Install it on the current switch?" else OpamConsole.confirm "Opam plugin \"%s\" may require upgrading/reinstalling. \ Reinstall the plugin on the current switch?") name then let nv = try if cmd = None then raise Not_found else OpamPackage.package_of_name installed (OpamPackage.Name.of_string prefixed_name) with Not_found -> try OpamPackage.max_version plugins (OpamPackage.Name.of_string prefixed_name) with Not_found -> OpamPackage.max_version plugins (OpamPackage.Name.of_string name) in OpamRepositoryConfig.init (); OpamSolverConfig.init (); OpamClientConfig.init (); OpamSwitchState.with_ `Lock_write gt (fun st -> OpamSwitchState.drop @@ ( if cmd = None then OpamClient.install st [OpamSolution.eq_atom_of_package nv] else if root_upgraded then OpamClient.reinstall st [OpamSolution.eq_atom_of_package nv] else OpamClient.upgrade st ~all:false [OpamSolution.eq_atom_of_package nv]) ); match OpamSystem.resolve_command ~env command with | None -> OpamConsole.error_and_exit `Package_operation_error "Plugin %s was installed, but no %s command was found.\n\ This is probably an error in the plugin package." (OpamPackage.to_string nv) command | Some command -> OpamConsole.header_msg "Carrying on to \"%s\"" (String.concat " " (Array.to_list Sys.argv)); OpamConsole.msg "\n"; let argv = Array.of_list (command :: args) in raise (OpamStd.Sys.Exec (command, argv, env)) else (cli, argv) let display_cli_error msg = Format.eprintf "@[<v>opam: @[%a@]@,@[Usage: @[opam COMMAND ...@]@]@,\ Try `opam --help' for more information.@]@." Format.pp_print_text msg let display_cli_error fmt = Format.ksprintf display_cli_error fmt let flush_all_noerror () = (try flush stderr with _ -> ()); (try flush stdout with _ -> ()) let rec main_catch_all f = try f () with | OpamStd.Sys.Exit 0 -> () | OpamStd.Sys.Exec (cmd,args,env) -> OpamStd.Sys.exec_at_exit (); if Sys.win32 then OpamProcess.create_process_env cmd args env Unix.stdin Unix.stdout Unix.stderr |> Unix.waitpid [] |> function | _, Unix.WEXITED n -> exit n | _, (Unix.WSIGNALED n | Unix.WSTOPPED n) -> exit (128 - n) This is not how you should handle ` WSTOPPED ` ; but it does n't happen on Windows anyway . Windows anyway. *) else Unix.execvpe cmd args env | OpamFormatUpgrade.Upgrade_done (conf, reinit) -> main_catch_all @@ fun () -> OpamConsole.header_msg "Rerunning init and update"; (match reinit with | Some reinit -> reinit conf; OpamConsole.msg "Update done.\n"; exit (OpamStd.Sys.get_exit_code `Success) | None -> OpamClient.reinit ~interactive:true ~update_config:false ~bypass_checks:true conf (OpamStd.Sys.guess_shell_compat ()); OpamConsole.msg "Update done, please now retry your command.\n"; exit (OpamStd.Sys.get_exit_code `Aborted)) | e -> OpamStd.Exn.register_backtrace e; (try Sys.set_signal Sys.sigpipe Sys.Signal_default with Invalid_argument _ -> ()); flush_all_noerror (); if (OpamConsole.verbose ()) then OpamConsole.errmsg "'%s' failed.\n" (String.concat " " (Array.to_list Sys.argv)); let exit_code = match e with | OpamStd.Sys.Exit i -> if (OpamConsole.debug ()) && i <> 0 then OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); i | OpamSystem.Internal_error _ -> OpamConsole.errmsg "%s\n" (Printexc.to_string e); OpamStd.Sys.get_exit_code `Internal_error | OpamSystem.Process_error result -> OpamConsole.errmsg "%s Command %S failed:\n%s\n" (OpamConsole.colorise `red "[ERROR]") (try OpamStd.List.assoc String.equal "command" result.OpamProcess.r_info with Not_found -> "") (Printexc.to_string e); OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error | Sys.Break | OpamParallel.Errors (_, (_, Sys.Break)::_, _) -> OpamStd.Sys.get_exit_code `User_interrupt | Sys_error e when e = "Broken pipe" -> workaround warning 52 , this is a fallback ( we already handle the signal ) and there is no way around at the moment signal) and there is no way around at the moment *) 141 | InvalidCLI (cli, source) -> let suffix = if source = `Env then " Please fix the value of the OPAMCLI environment variable, \ or use the '--cli <major>.<minor>' flag" else "" in OpamConsole.error "opam command-line version %s is not supported.%s" (OpamCLIVersion.to_string cli) suffix; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidFlagContent (flag, None) -> display_cli_error "option `--%s' needs an argument" flag; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidFlagContent (flag, Some (invalid, expected)) -> display_cli_error "option `--%s': invalid value `%s', expected %s" flag invalid expected; OpamStd.Sys.get_exit_code `Bad_arguments | InvalidNewFlag ((req_cli, _), flag, flag_cli) -> display_cli_error "--%s was added in version %s of the opam CLI, \ but version %s has been requested, which is older." flag (OpamCLIVersion.to_string flag_cli) (OpamCLIVersion.to_string req_cli); OpamStd.Sys.get_exit_code `Bad_arguments | Failure msg -> OpamConsole.errmsg "Fatal error: %s\n" msg; OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error | _ -> OpamConsole.errmsg "Fatal error:\n%s\n" (Printexc.to_string e); OpamConsole.errmsg "%s" (OpamStd.Exn.pretty_backtrace e); OpamStd.Sys.get_exit_code `Internal_error in exit exit_code let run () = OpamStd.Option.iter OpamVersion.set_git OpamGitVersion.version; OpamSystem.init (); OpamArg.preinit_opam_env_variables (); main_catch_all @@ fun () -> let cli, argv = check_and_run_external_commands () in let (default, commands), argv1 = match argv with | prog :: command :: argv when OpamCommands.is_admin_subcommand command -> OpamAdminCommand.get_cmdliner_parser cli, prog::argv | _ -> OpamCommands.get_cmdliner_parser cli, argv in let argv = Array.of_list argv1 in let to_new_cmdliner_api (term, info) = Cmd.v info term in let default, default_info = default in let commands = List.map to_new_cmdliner_api commands in match Cmd.eval_value ~catch:false ~argv (Cmd.group ~default default_info commands) with | Error _ -> exit (OpamStd.Sys.get_exit_code `Bad_arguments) | Ok _ -> exit (OpamStd.Sys.get_exit_code `Success) let json_out () = match OpamClientConfig.(!r.json_out) with | None -> () | Some s -> let file_name () = match OpamStd.String.cut_at s '%' with | None -> OpamFilename.of_string s | Some (pfx, sfx) -> let rec getname i = let f = OpamFilename.of_string (Printf.sprintf "%s%d%s" pfx i sfx) in if OpamFilename.exists f then getname (i+1) else f in getname 1 in try let f = OpamFilename.open_out (file_name ()) in OpamJson.flush f; close_out f with e -> OpamConsole.warning "Couldn't write json log: %s" (Printexc.to_string e) let main () = OpamStd.Sys.at_exit (fun () -> flush_all_noerror (); if OpamClientConfig.(!r.print_stats) then ( OpamFile.Stats.print (); OpamSystem.print_stats (); ); json_out () ); run ()
7f3273986dfffe94ad54250895cb935130f2306d5c714da88e02129aa57dafa5
ocaml-multicore/parafuzz
fma.ml
(* TEST *) (* modified glibc's fma() tests *) let error l x y z r c = Printf.fprintf stdout "%s FAIL!\tfma (%h, %h, %h) returned %h instead of %h.\n" l x y z c (List.hd r) let success l = Printf.fprintf stdout "%s OK!\n" l let fma_test l x y z r = let c = Float.fma x y z in if List.exists (fun i -> i = c) r then success l else error l x y z r c (* test case description: (string * float * float * float * float list) | | | | | id | | | IEEE compliant result in head, | | | or, accepted fma emulation approximation | | | results in tail (if any) | | | x y z -> operands as in fma x y z *) let _ = let cases = [ ("001", 0x1p+0, 0x2p+0, 0x3p+0, [0x5p+0]); ("002", 0x1.4p+0, 0xcp-4, 0x1p-4, [0x1p+0]); ("003", 0x0p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("004", 0x0p+0, 0x0p+0, ~-.0x0p+0, [0x0p+0]); ("005", 0x0p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("006", 0x0p+0, ~-.0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("007", ~-.0x0p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("008", ~-.0x0p+0, 0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("009", ~-.0x0p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("010", ~-.0x0p+0, ~-.0x0p+0, ~-.0x0p+0, [0x0p+0]); ("011", 0x1p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("012", 0x1p+0, 0x0p+0, ~-.0x0p+0, [0x0p+0]); ("013", 0x1p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("014", 0x1p+0, ~-.0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("015", ~-.0x1p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("016", ~-.0x1p+0, 0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("017", ~-.0x1p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("018", ~-.0x1p+0, ~-.0x0p+0, ~-.0x0p+0, [0x0p+0]); ("019", 0x0p+0, 0x1p+0, 0x0p+0, [0x0p+0]); ("020", 0x0p+0, 0x1p+0, ~-.0x0p+0, [0x0p+0]); ("021", 0x0p+0, ~-.0x1p+0, 0x0p+0, [0x0p+0]); ("022", 0x0p+0, ~-.0x1p+0, ~-.0x0p+0, [~-.0x0p+0]); ("023", ~-.0x0p+0, 0x1p+0, 0x0p+0, [0x0p+0]); ("024", ~-.0x0p+0, 0x1p+0, ~-.0x0p+0, [~-.0x0p+0]); ("025", ~-.0x0p+0, ~-.0x1p+0, 0x0p+0, [0x0p+0]); ("026", ~-.0x0p+0, ~-.0x1p+0, ~-.0x0p+0, [0x0p+0]); ("027", 0x1p+0, 0x1p+0, ~-.0x1p+0, [0x0p+0]); ("028", 0x1p+0, ~-.0x1p+0, 0x1p+0, [0x0p+0]); ("029", ~-.0x1p+0, 0x1p+0, 0x1p+0, [0x0p+0]); ("030", ~-.0x1p+0, ~-.0x1p+0, ~-.0x1p+0, [0x0p+0]); ("031", 0x0p+0, 0x0p+0, 0x1p+0, [0x1p+0]); ("032", 0x0p+0, 0x0p+0, 0x2p+0, [0x2p+0]); ("033", 0x0p+0, 0x0p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("034", 0x0p+0, 0x0p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("035", 0x0p+0, 0x1p+0, 0x1p+0, [0x1p+0]); ("036", 0x1p+0, 0x0p+0, 0x1p+0, [0x1p+0]); ("037", 0x0p+0, 0x1p+0, 0x2p+0, [0x2p+0]); ("038", 0x1p+0, 0x0p+0, 0x2p+0, [0x2p+0]); ("039", 0x0p+0, 0x1p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("040", 0x0p+0, 0x1p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("041", 0x1p+0, 0x0p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("042", 0x1p+0, 0x0p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("043", 0x4p-128, 0x4p-128, 0x0p+0, [0x1p-252]); ("044", 0x4p-128, 0x4p-1024, 0x0p+0, [0x0p+0]); ("045", 0x4p-128, 0x8p-972, 0x0p+0, [0x0p+0]); ("046", 0x4p-1024, 0x4p-128, 0x0p+0, [0x0p+0]); ("047", 0x4p-1024, 0x4p-1024, 0x0p+0, [0x0p+0]); ("048", 0x4p-1024, 0x8p-972, 0x0p+0, [0x0p+0]); ("049", 0x8p-972, 0x4p-128, 0x0p+0, [0x0p+0]); ("050", 0x8p-972, 0x4p-1024, 0x0p+0, [0x0p+0]); ("051", 0x8p-972, 0x8p-972, 0x0p+0, [0x0p+0]); ("052", 0x4p-128, 0x4p-128, ~-.0x0p+0, [0x1p-252]); ("053", 0x4p-128, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("054", 0x4p-128, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("055", 0x4p-1024, 0x4p-128, ~-.0x0p+0, [0x0p+0]); ("056", 0x4p-1024, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("057", 0x4p-1024, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("058", 0x8p-972, 0x4p-128, ~-.0x0p+0, [0x0p+0]); ("059", 0x8p-972, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("060", 0x8p-972, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("061", 0x4p-128, ~-.0x4p-128, 0x0p+0, [~-.0x1p-252]); ("062", 0x4p-128, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("063", 0x4p-128, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("064", 0x4p-1024, ~-.0x4p-128, 0x0p+0, [~-.0x0p+0]); ("065", 0x4p-1024, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("066", 0x4p-1024, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("067", 0x8p-972, ~-.0x4p-128, 0x0p+0, [~-.0x0p+0]); ("068", 0x8p-972, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("069", 0x8p-972, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("070", 0x4p-128, ~-.0x4p-128, ~-.0x0p+0, [~-.0x1p-252]); ("071", 0x4p-128, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("072", 0x4p-128, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("073", 0x4p-1024, ~-.0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("074", 0x4p-1024, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("075", 0x4p-1024, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("076", 0x8p-972, ~-.0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("077", 0x8p-972, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("078", 0x8p-972, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("079", ~-.0x4p-128, 0x4p-128, 0x0p+0, [~-.0x1p-252]); ("080", ~-.0x4p-128, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("081", ~-.0x4p-128, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("082", ~-.0x4p-1024, 0x4p-128, 0x0p+0, [~-.0x0p+0]); ("083", ~-.0x4p-1024, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("084", ~-.0x4p-1024, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("085", ~-.0x8p-972, 0x4p-128, 0x0p+0, [~-.0x0p+0]); ("086", ~-.0x8p-972, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("087", ~-.0x8p-972, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("088", ~-.0x4p-128, 0x4p-128, ~-.0x0p+0, [~-.0x1p-252]); ("089", ~-.0x4p-128, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("090", ~-.0x4p-128, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("091", ~-.0x4p-1024, 0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("092", ~-.0x4p-1024, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("093", ~-.0x4p-1024, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("094", ~-.0x8p-972, 0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("095", ~-.0x8p-972, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("096", ~-.0x8p-972, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("097", ~-.0x4p-128, ~-.0x4p-128, 0x0p+0, [0x1p-252]); ("098", ~-.0x4p-128, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("099", ~-.0x4p-128, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("100", ~-.0x4p-1024, ~-.0x4p-128, 0x0p+0, [0x0p+0]); ("101", ~-.0x4p-1024, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("102", ~-.0x4p-1024, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("103", ~-.0x8p-972, ~-.0x4p-128, 0x0p+0, [0x0p+0]); ("104", ~-.0x8p-972, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("105", ~-.0x8p-972, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("106", ~-.0x4p-128, ~-.0x4p-128, ~-.0x0p+0, [0x1p-252]); ("107", ~-.0x4p-128, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("108", ~-.0x4p-128, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("109", ~-.0x4p-1024, ~-.0x4p-128, ~-.0x0p+0, [0x0p+0]); ("110", ~-.0x4p-1024, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("111", ~-.0x4p-1024, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("112", ~-.0x8p-972, ~-.0x4p-128, ~-.0x0p+0, [0x0p+0]); ("113", ~-.0x8p-972, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("114", ~-.0x8p-972, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("115", 0xf.fffffp+124, 0xf.fffffp+124, 0x4p-128, [0xf.ffffe000001p+252]); ("116", 0xf.fffffp+124, 0xf.fffffp+124, 0x4p-1024, [0xf.ffffe000001p+252]); ("117", 0xf.fffffp+124, 0xf.fffffp+124, 0x8p-972, [0xf.ffffe000001p+252]); ("118", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("119", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("120", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("121", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-128, [infinity]); ("122", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-1024, [infinity]); ("123", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x8p-972, [infinity]); ("124", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("125", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("126", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("127", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-128, [0xf.ffffe000001p+252]); ("128", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-1024, [0xf.ffffe000001p+252]); ("129", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x8p-972, [0xf.ffffe000001p+252]); ("130", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("131", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("132", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("133", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-128, [infinity]); ("134", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-1024, [infinity]); ("135", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x8p-972, [infinity]); ("136", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("137", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("138", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("139", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-128, [~-.0xf.ffffe000001p+252]); ("140", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-1024, [~-.0xf.ffffe000001p+252]); ("141", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x8p-972, [~-.0xf.ffffe000001p+252]); ("142", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("143", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("144", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("145", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-128, [~-.infinity]); ("146", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-1024, [~-.infinity]); ("147", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x8p-972, [~-.infinity]); ("148", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("149", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("150", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("151", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-128, [~-.0xf.ffffe000001p+252]); ("152", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-1024, [~-.0xf.ffffe000001p+252]); ("153", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x8p-972, [~-.0xf.ffffe000001p+252]); ("154", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("155", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("156", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("157", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-128, [~-.infinity]); ("158", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-1024, [~-.infinity]); ("159", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x8p-972, [~-.infinity]); ("160", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("161", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("162", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("163", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x4p-128, [~-.0xf.ffffe000001p+252]); ("164", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x4p-1024, [~-.0xf.ffffe000001p+252]); ("165", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x8p-972, [~-.0xf.ffffe000001p+252]); ("166", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("167", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("168", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("169", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-128, [~-.infinity]); ("170", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-1024, [~-.infinity]); ("171", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x8p-972, [~-.infinity]); ("172", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("173", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("174", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("175", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-128, [~-.0xf.ffffe000001p+252]); ("176", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-1024, [~-.0xf.ffffe000001p+252]); ("177", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x8p-972, [~-.0xf.ffffe000001p+252]); ("178", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("179", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("180", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("181", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-128, [~-.infinity]); ("182", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-1024, [~-.infinity]); ("183", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x8p-972, [~-.infinity]); ("184", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("185", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("186", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("187", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-128, [0xf.ffffe000001p+252]); ("188", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-1024, [0xf.ffffe000001p+252]); ("189", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x8p-972, [0xf.ffffe000001p+252]); ("190", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("191", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("192", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("193", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-128, [infinity]); ("194", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-1024, [infinity]); ("195", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x8p-972, [infinity]); ("196", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("197", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("198", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("199", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-128, [0xf.ffffe000001p+252]); ("200", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-1024, [0xf.ffffe000001p+252]); ("201", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x8p-972, [0xf.ffffe000001p+252]); ("202", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("203", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("204", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("205", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-128, [infinity]); ("206", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-1024, [infinity]); ("207", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x8p-972, [infinity]); ("208", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("209", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("210", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("211", 0x2.fffp+12, 0x1.000002p+0, 0x1.ffffp-24, [0x2.fff006p+12]); ("212", 0x1.fffp+0, 0x1.00001p+0, ~-.0x1.fffp+0, [0x1.fffp-20]); ("213", 0xc.d5e6fp+124, 0x2.6af378p-128, ~-.0x1.f08948p+0, [0xd.da108p-28]); ("214", 0x1.9abcdep+100, 0x2.6af378p-128, ~-.0x3.e1129p-28, [0x1.bb421p-52]); ("215", 0xf.fffffp+124, 0x1.001p+0, ~-.0xf.fffffp+124, [0xf.fffffp+112]); ("216", ~-.0xf.fffffp+124, 0x1.fffffep+0, 0xf.fffffp+124, [~-.0xf.ffffd000002p+124]); ("217", 0xf.fffffp+124, 0x2p+0, ~-.0xf.fffffp+124, [0xf.fffffp+124]); ("218", 0x5p-128, 0x8.00002p-4, 0x1p-128, [0x3.80000ap-128]); ("219", ~-.0x5p-128, 0x8.00002p-4, ~-.0x1p-128, [~-.0x3.80000ap-128]); ("220", 0x7.ffffep-128, 0x8.00001p-4, 0x8p-152, [0x3.ffffffffffep-128]); ("221", ~-.0x7.ffffep-128, 0x8.00001p-4, ~-.0x8p-152, [~-.0x3.ffffffffffep-128]); ("222", 0x8p-152, 0x8p-4, 0x3.fffff8p-128, [0x3.fffffcp-128]); ("223", ~-.0x8p-152, 0x8p-4, ~-.0x3.fffff8p-128, [~-.0x3.fffffcp-128]); ("224", 0x8p-152, 0x8.8p-4, 0x3.fffff8p-128, [0x3.fffffc4p-128]); ("225", ~-.0x8p-152, 0x8.8p-4, ~-.0x3.fffff8p-128, [~-.0x3.fffffc4p-128]); ("226", 0x8p-152, 0x8p-152, 0x8p+124, [0x8p+124]); ("227", 0x8p-152, ~-.0x8p-152, 0x8p+124, [0x8p+124]); ("228", 0x8p-152, 0x8p-152, ~-.0x8p+124, [~-.0x8p+124]); ("229", 0x8p-152, ~-.0x8p-152, ~-.0x8p+124, [~-.0x8p+124]); ("230", 0x8p-152, 0x8p-152, 0x4p-128, [0x4p-128]); ("231", 0x8p-152, ~-.0x8p-152, 0x4p-128, [0x4p-128]); ("232", 0x8p-152, 0x8p-152, ~-.0x4p-128, [~-.0x4p-128]); ("233", 0x8p-152, ~-.0x8p-152, ~-.0x4p-128, [~-.0x4p-128]); ("234", 0x8p-152, 0x8p-152, 0x3.fffff8p-128, [0x3.fffff8p-128]); ("235", 0x8p-152, ~-.0x8p-152, 0x3.fffff8p-128, [0x3.fffff8p-128]); ("236", 0x8p-152, 0x8p-152, ~-.0x3.fffff8p-128, [~-.0x3.fffff8p-128]); ("237", 0x8p-152, ~-.0x8p-152, ~-.0x3.fffff8p-128, [~-.0x3.fffff8p-128]); ("238", 0x8p-152, 0x8p-152, 0x8p-152, [0x8p-152]); ("239", 0x8p-152, ~-.0x8p-152, 0x8p-152, [0x8p-152]); ("240", 0x8p-152, 0x8p-152, ~-.0x8p-152, [~-.0x8p-152]); ("241", 0x8p-152, ~-.0x8p-152, ~-.0x8p-152, [~-.0x8p-152]); ("242", 0xf.ffp-4, 0xf.ffp-4, ~-.0xf.fep-4, [0x1p-24]); ("243", 0xf.ffp-4, ~-.0xf.ffp-4, 0xf.fep-4, [~-.0x1p-24]); ("244", ~-.0xf.ffp-4, 0xf.ffp-4, 0xf.fep-4, [~-.0x1p-24]); ("245", ~-.0xf.ffp-4, ~-.0xf.ffp-4, ~-.0xf.fep-4, [0x1p-24]); ("246", 0x4.000008p-128, 0x4.000008p-28, 0x8p+124, [0x8p+124]); ("247", 0x4.000008p-128, ~-.0x4.000008p-28, 0x8p+124, [0x8p+124]); ("248", 0x4.000008p-128, 0x4.000008p-28, ~-.0x8p+124, [~-.0x8p+124]); ("249", 0x4.000008p-128, ~-.0x4.000008p-28, ~-.0x8p+124, [~-.0x8p+124]); ("250", 0x4.000008p-128, 0x4.000008p-28, 0x8p+100, [0x8p+100]); ("251", 0x4.000008p-128, ~-.0x4.000008p-28, 0x8p+100, [0x8p+100]); ("252", 0x4.000008p-128, 0x4.000008p-28, ~-.0x8p+100, [~-.0x8p+100]); ("253", 0x4.000008p-128, ~-.0x4.000008p-28, ~-.0x8p+100, [~-.0x8p+100]); ("254", 0x2.fep+12, 0x1.0000000000001p+0, 0x1.ffep-48, [0x2.fe00000000002p+12; 0x1.7f00000000002p+13]); ("255", 0x1.fffp+0, 0x1.0000000000001p+0, ~-.0x1.fffp+0, [0x1.fffp-52; 0x1p-51]); ("256", 0x1.0000002p+0, 0xf.fffffep-4, 0x1p-300, [0x1p+0]); ("257", 0x1.0000002p+0, 0xf.fffffep-4, ~-.0x1p-300, [0xf.ffffffffffff8p-4; 0x1p+0]); ("258", 0xe.f56df7797f768p+1020, 0x3.7ab6fbbcbfbb4p-1024, ~-.0x3.40bf1803497f6p+0, [0x8.4c4b43de4ed2p-56; 0x1.095f287bc9da4p-53; 0x1.098p-53]); ("259", 0x1.deadbeef2feedp+900, 0x3.7ab6fbbcbfbb4p-1024, ~-.0x6.817e300692fecp-124, [0x1.0989687bc9da4p-176; 0x1.095f287bc9da4p-176; 0x1.098p-176]); ("260", 0xf.ffffffffffff8p+1020, 0x1.001p+0, ~-.0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1008; 0x1p+1012]); ("261", ~-.0xf.ffffffffffff8p+1020, 0x1.fffffffffffffp+0, 0xf.ffffffffffff8p+1020, [~-.0xf.fffffffffffe8p+1020]); ("262", 0xf.ffffffffffff8p+1020, 0x2p+0, ~-.0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("263", 0x5.a827999fcef3p-540, 0x5.a827999fcef3p-540, 0x0p+0, [0x0p+0]); ("264", 0x3.bd5b7dde5fddap-496, 0x3.bd5b7dde5fddap-496, ~-.0xd.fc352bc352bap-992, [0x1.0989687cp-1044; 0x0.000004277ca1fp-1022; 0x0.00000428p-1022]); ("265", 0x3.bd5b7dde5fddap-504, 0x3.bd5b7dde5fddap-504, ~-.0xd.fc352bc352bap-1008, [0x1.0988p-1060; 0x0.0000000004278p-1022; 0x0.000000000428p-1022]); ("266", 0x8p-540, 0x4p-540, 0x4p-1076, [0x8p-1076]); ("267", 0x1.7fffff8p-968, 0x4p-108, 0x4p-1048, [0x4.0000004p-1048; 0x0.0000010000002p-1022]); ("268", 0x2.8000008p-968, 0x4p-108, 0x4p-1048, [0x4.000000cp-1048; 0x0.0000010000002p-1022]); ("269", 0x2.8p-968, ~-.0x4p-108, ~-.0x4p-1048, [~-.0x4.0000008p-1048]); ("270", ~-.0x2.33956cdae7c2ep-960, 0x3.8e211518bfea2p-108, ~-.0x2.02c2b59766d9p-1024, [~-.0x2.02c2b59767564p-1024]); ("271", ~-.0x3.a5d5dadd1d3a6p-980, ~-.0x2.9c0cd8c5593bap-64, ~-.0x2.49179ac00d15p-1024, [~-.0x2.491702717ed74p-1024]); ("272", 0x2.2a7aca1773e0cp-908, 0x9.6809186a42038p-128, ~-.0x2.c9e356b3f0fp-1024, [~-.0x2.c89d5c48eefa4p-1024; ~-.0x0.b22757123bbe8p-1022]); ("273", ~-.0x3.ffffffffffffep-712, 0x3.ffffffffffffep-276, 0x3.fffffc0000ffep-984, [0x2.fffffc0000ffep-984; 0x1.7ffffe00008p-983]); ("274", 0x5p-1024, 0x8.000000000001p-4, 0x1p-1024, [0x3.8000000000004p-1024]); ("275", ~-.0x5p-1024, 0x8.000000000001p-4, ~-.0x1p-1024, [~-.0x3.8000000000004p-1024]); ("276", 0x7.ffffffffffffp-1024, 0x8.0000000000008p-4, 0x4p-1076, [0x4p-1024]); ("277", ~-.0x7.ffffffffffffp-1024, 0x8.0000000000008p-4, ~-.0x4p-1076, [~-.0x4p-1024]); ("278", 0x4p-1076, 0x8p-4, 0x3.ffffffffffffcp-1024, [0x4p-1024]); ("279", ~-.0x4p-1076, 0x8p-4, ~-.0x3.ffffffffffffcp-1024, [~-.0x4p-1024]); ("280", 0x4p-1076, 0x8.8p-4, 0x3.ffffffffffffcp-1024, [0x4p-1024]); ("281", ~-.0x4p-1076, 0x8.8p-4, ~-.0x3.ffffffffffffcp-1024, [~-.0x4p-1024]); ("282", 0x4p-1076, 0x4p-1076, 0x8p+1020, [0x8p+1020]); ("283", 0x4p-1076, ~-.0x4p-1076, 0x8p+1020, [0x8p+1020]); ("284", 0x4p-1076, 0x4p-1076, ~-.0x8p+1020, [~-.0x8p+1020]); ("285", 0x4p-1076, ~-.0x4p-1076, ~-.0x8p+1020, [~-.0x8p+1020]); ("286", 0x4p-1076, 0x4p-1076, 0x4p-1024, [0x4p-1024]); ("287", 0x4p-1076, ~-.0x4p-1076, 0x4p-1024, [0x4p-1024]); ("288", 0x4p-1076, 0x4p-1076, ~-.0x4p-1024, [~-.0x4p-1024]); ("289", 0x4p-1076, ~-.0x4p-1076, ~-.0x4p-1024, [~-.0x4p-1024]); ("290", 0x4p-1076, 0x4p-1076, 0x3.ffffffffffffcp-1024, [0x3.ffffffffffffcp-1024]); ("291", 0x4p-1076, ~-.0x4p-1076, 0x3.ffffffffffffcp-1024, [0x3.ffffffffffffcp-1024]); ("292", 0x4p-1076, 0x4p-1076, ~-.0x3.ffffffffffffcp-1024, [~-.0x3.ffffffffffffcp-1024]); ("293", 0x4p-1076, ~-.0x4p-1076, ~-.0x3.ffffffffffffcp-1024, [~-.0x3.ffffffffffffcp-1024]); ("294", 0x4p-1076, 0x4p-1076, 0x4p-1076, [0x4p-1076]); ("295", 0x4p-1076, ~-.0x4p-1076, 0x4p-1076, [0x4p-1076]); ("296", 0x4p-1076, 0x4p-1076, ~-.0x4p-1076, [~-.0x4p-1076]); ("297", 0x4p-1076, ~-.0x4p-1076, ~-.0x4p-1076, [~-.0x4p-1076]); ("298", 0xf.ffffffffffff8p-4, 0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffffp-4, [0x4p-108; 0x0p+0]); ("299", 0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffff8p-4, 0xf.ffffffffffffp-4, [~-.0x4p-108; 0x0p+0]); ("300", ~-.0xf.ffffffffffff8p-4, 0xf.ffffffffffff8p-4, 0xf.ffffffffffffp-4, [~-.0x4p-108; 0x0p+0]); ("301", ~-.0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffffp-4, [0x4p-108; 0x0p+0]); ("302", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, 0x8p+1020, [0x8p+1020]); ("303", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, 0x8p+1020, [0x8p+1020]); ("304", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, ~-.0x8p+1020, [~-.0x8p+1020]); ("305", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, ~-.0x8p+1020, [~-.0x8p+1020]); ("306", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, 0x4p+968, [0x4p+968]); ("307", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, 0x4p+968, [0x4p+968]); ("308", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, ~-.0x4p+968, [~-.0x4p+968]); ("309", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, ~-.0x4p+968, [~-.0x4p+968]); ("310", 0x7.fffff8p-128, 0x3.fffffcp+24, 0xf.fffffp+124, [0xf.fffffp+124]); ("311", 0x7.fffff8p-128, ~-.0x3.fffffcp+24, 0xf.fffffp+124, [0xf.fffffp+124]); ("312", 0x7.fffff8p-128, 0x3.fffffcp+24, ~-.0xf.fffffp+124, [~-.0xf.fffffp+124]); ("313", 0x7.fffff8p-128, ~-.0x3.fffffcp+24, ~-.0xf.fffffp+124, [~-.0xf.fffffp+124]); ("314", 0x7.ffffffffffffcp-1024, 0x7.ffffffffffffcp+52, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("315", 0x7.ffffffffffffcp-1024, ~-.0x7.ffffffffffffcp+52, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("316", 0x7.ffffffffffffcp-1024, 0x7.ffffffffffffcp+52, ~-.0xf.ffffffffffff8p+1020, [~-.0xf.ffffffffffff8p+1020]); ("317", 0x7.ffffffffffffcp-1024, ~-.0x7.ffffffffffffcp+52, ~-.0xf.ffffffffffff8p+1020, [~-.0xf.ffffffffffff8p+1020]) ] in let rec do_cases c = match c with (l, x, y, z, r)::t -> fma_test l x y z r; do_cases t | [] -> () in do_cases cases
null
https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/testsuite/tests/fma/fma.ml
ocaml
TEST modified glibc's fma() tests test case description: (string * float * float * float * float list) | | | | | id | | | IEEE compliant result in head, | | | or, accepted fma emulation approximation | | | results in tail (if any) | | | x y z -> operands as in fma x y z
let error l x y z r c = Printf.fprintf stdout "%s FAIL!\tfma (%h, %h, %h) returned %h instead of %h.\n" l x y z c (List.hd r) let success l = Printf.fprintf stdout "%s OK!\n" l let fma_test l x y z r = let c = Float.fma x y z in if List.exists (fun i -> i = c) r then success l else error l x y z r c let _ = let cases = [ ("001", 0x1p+0, 0x2p+0, 0x3p+0, [0x5p+0]); ("002", 0x1.4p+0, 0xcp-4, 0x1p-4, [0x1p+0]); ("003", 0x0p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("004", 0x0p+0, 0x0p+0, ~-.0x0p+0, [0x0p+0]); ("005", 0x0p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("006", 0x0p+0, ~-.0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("007", ~-.0x0p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("008", ~-.0x0p+0, 0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("009", ~-.0x0p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("010", ~-.0x0p+0, ~-.0x0p+0, ~-.0x0p+0, [0x0p+0]); ("011", 0x1p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("012", 0x1p+0, 0x0p+0, ~-.0x0p+0, [0x0p+0]); ("013", 0x1p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("014", 0x1p+0, ~-.0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("015", ~-.0x1p+0, 0x0p+0, 0x0p+0, [0x0p+0]); ("016", ~-.0x1p+0, 0x0p+0, ~-.0x0p+0, [~-.0x0p+0]); ("017", ~-.0x1p+0, ~-.0x0p+0, 0x0p+0, [0x0p+0]); ("018", ~-.0x1p+0, ~-.0x0p+0, ~-.0x0p+0, [0x0p+0]); ("019", 0x0p+0, 0x1p+0, 0x0p+0, [0x0p+0]); ("020", 0x0p+0, 0x1p+0, ~-.0x0p+0, [0x0p+0]); ("021", 0x0p+0, ~-.0x1p+0, 0x0p+0, [0x0p+0]); ("022", 0x0p+0, ~-.0x1p+0, ~-.0x0p+0, [~-.0x0p+0]); ("023", ~-.0x0p+0, 0x1p+0, 0x0p+0, [0x0p+0]); ("024", ~-.0x0p+0, 0x1p+0, ~-.0x0p+0, [~-.0x0p+0]); ("025", ~-.0x0p+0, ~-.0x1p+0, 0x0p+0, [0x0p+0]); ("026", ~-.0x0p+0, ~-.0x1p+0, ~-.0x0p+0, [0x0p+0]); ("027", 0x1p+0, 0x1p+0, ~-.0x1p+0, [0x0p+0]); ("028", 0x1p+0, ~-.0x1p+0, 0x1p+0, [0x0p+0]); ("029", ~-.0x1p+0, 0x1p+0, 0x1p+0, [0x0p+0]); ("030", ~-.0x1p+0, ~-.0x1p+0, ~-.0x1p+0, [0x0p+0]); ("031", 0x0p+0, 0x0p+0, 0x1p+0, [0x1p+0]); ("032", 0x0p+0, 0x0p+0, 0x2p+0, [0x2p+0]); ("033", 0x0p+0, 0x0p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("034", 0x0p+0, 0x0p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("035", 0x0p+0, 0x1p+0, 0x1p+0, [0x1p+0]); ("036", 0x1p+0, 0x0p+0, 0x1p+0, [0x1p+0]); ("037", 0x0p+0, 0x1p+0, 0x2p+0, [0x2p+0]); ("038", 0x1p+0, 0x0p+0, 0x2p+0, [0x2p+0]); ("039", 0x0p+0, 0x1p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("040", 0x0p+0, 0x1p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("041", 0x1p+0, 0x0p+0, 0xf.fffffp+124, [0xf.fffffp+124]); ("042", 0x1p+0, 0x0p+0, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("043", 0x4p-128, 0x4p-128, 0x0p+0, [0x1p-252]); ("044", 0x4p-128, 0x4p-1024, 0x0p+0, [0x0p+0]); ("045", 0x4p-128, 0x8p-972, 0x0p+0, [0x0p+0]); ("046", 0x4p-1024, 0x4p-128, 0x0p+0, [0x0p+0]); ("047", 0x4p-1024, 0x4p-1024, 0x0p+0, [0x0p+0]); ("048", 0x4p-1024, 0x8p-972, 0x0p+0, [0x0p+0]); ("049", 0x8p-972, 0x4p-128, 0x0p+0, [0x0p+0]); ("050", 0x8p-972, 0x4p-1024, 0x0p+0, [0x0p+0]); ("051", 0x8p-972, 0x8p-972, 0x0p+0, [0x0p+0]); ("052", 0x4p-128, 0x4p-128, ~-.0x0p+0, [0x1p-252]); ("053", 0x4p-128, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("054", 0x4p-128, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("055", 0x4p-1024, 0x4p-128, ~-.0x0p+0, [0x0p+0]); ("056", 0x4p-1024, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("057", 0x4p-1024, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("058", 0x8p-972, 0x4p-128, ~-.0x0p+0, [0x0p+0]); ("059", 0x8p-972, 0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("060", 0x8p-972, 0x8p-972, ~-.0x0p+0, [0x0p+0]); ("061", 0x4p-128, ~-.0x4p-128, 0x0p+0, [~-.0x1p-252]); ("062", 0x4p-128, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("063", 0x4p-128, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("064", 0x4p-1024, ~-.0x4p-128, 0x0p+0, [~-.0x0p+0]); ("065", 0x4p-1024, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("066", 0x4p-1024, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("067", 0x8p-972, ~-.0x4p-128, 0x0p+0, [~-.0x0p+0]); ("068", 0x8p-972, ~-.0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("069", 0x8p-972, ~-.0x8p-972, 0x0p+0, [~-.0x0p+0]); ("070", 0x4p-128, ~-.0x4p-128, ~-.0x0p+0, [~-.0x1p-252]); ("071", 0x4p-128, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("072", 0x4p-128, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("073", 0x4p-1024, ~-.0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("074", 0x4p-1024, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("075", 0x4p-1024, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("076", 0x8p-972, ~-.0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("077", 0x8p-972, ~-.0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("078", 0x8p-972, ~-.0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("079", ~-.0x4p-128, 0x4p-128, 0x0p+0, [~-.0x1p-252]); ("080", ~-.0x4p-128, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("081", ~-.0x4p-128, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("082", ~-.0x4p-1024, 0x4p-128, 0x0p+0, [~-.0x0p+0]); ("083", ~-.0x4p-1024, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("084", ~-.0x4p-1024, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("085", ~-.0x8p-972, 0x4p-128, 0x0p+0, [~-.0x0p+0]); ("086", ~-.0x8p-972, 0x4p-1024, 0x0p+0, [~-.0x0p+0]); ("087", ~-.0x8p-972, 0x8p-972, 0x0p+0, [~-.0x0p+0]); ("088", ~-.0x4p-128, 0x4p-128, ~-.0x0p+0, [~-.0x1p-252]); ("089", ~-.0x4p-128, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("090", ~-.0x4p-128, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("091", ~-.0x4p-1024, 0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("092", ~-.0x4p-1024, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("093", ~-.0x4p-1024, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("094", ~-.0x8p-972, 0x4p-128, ~-.0x0p+0, [~-.0x0p+0]); ("095", ~-.0x8p-972, 0x4p-1024, ~-.0x0p+0, [~-.0x0p+0]); ("096", ~-.0x8p-972, 0x8p-972, ~-.0x0p+0, [~-.0x0p+0]); ("097", ~-.0x4p-128, ~-.0x4p-128, 0x0p+0, [0x1p-252]); ("098", ~-.0x4p-128, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("099", ~-.0x4p-128, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("100", ~-.0x4p-1024, ~-.0x4p-128, 0x0p+0, [0x0p+0]); ("101", ~-.0x4p-1024, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("102", ~-.0x4p-1024, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("103", ~-.0x8p-972, ~-.0x4p-128, 0x0p+0, [0x0p+0]); ("104", ~-.0x8p-972, ~-.0x4p-1024, 0x0p+0, [0x0p+0]); ("105", ~-.0x8p-972, ~-.0x8p-972, 0x0p+0, [0x0p+0]); ("106", ~-.0x4p-128, ~-.0x4p-128, ~-.0x0p+0, [0x1p-252]); ("107", ~-.0x4p-128, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("108", ~-.0x4p-128, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("109", ~-.0x4p-1024, ~-.0x4p-128, ~-.0x0p+0, [0x0p+0]); ("110", ~-.0x4p-1024, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("111", ~-.0x4p-1024, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("112", ~-.0x8p-972, ~-.0x4p-128, ~-.0x0p+0, [0x0p+0]); ("113", ~-.0x8p-972, ~-.0x4p-1024, ~-.0x0p+0, [0x0p+0]); ("114", ~-.0x8p-972, ~-.0x8p-972, ~-.0x0p+0, [0x0p+0]); ("115", 0xf.fffffp+124, 0xf.fffffp+124, 0x4p-128, [0xf.ffffe000001p+252]); ("116", 0xf.fffffp+124, 0xf.fffffp+124, 0x4p-1024, [0xf.ffffe000001p+252]); ("117", 0xf.fffffp+124, 0xf.fffffp+124, 0x8p-972, [0xf.ffffe000001p+252]); ("118", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("119", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("120", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("121", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-128, [infinity]); ("122", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-1024, [infinity]); ("123", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x8p-972, [infinity]); ("124", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("125", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("126", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("127", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-128, [0xf.ffffe000001p+252]); ("128", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-1024, [0xf.ffffe000001p+252]); ("129", 0xf.fffffp+124, 0xf.fffffp+124, ~-.0x8p-972, [0xf.ffffe000001p+252]); ("130", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("131", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("132", 0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("133", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-128, [infinity]); ("134", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-1024, [infinity]); ("135", 0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x8p-972, [infinity]); ("136", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("137", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("138", 0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("139", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-128, [~-.0xf.ffffe000001p+252]); ("140", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-1024, [~-.0xf.ffffe000001p+252]); ("141", 0xf.fffffp+124, ~-.0xf.fffffp+124, 0x8p-972, [~-.0xf.ffffe000001p+252]); ("142", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("143", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("144", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("145", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-128, [~-.infinity]); ("146", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-1024, [~-.infinity]); ("147", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x8p-972, [~-.infinity]); ("148", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("149", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("150", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("151", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-128, [~-.0xf.ffffe000001p+252]); ("152", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-1024, [~-.0xf.ffffe000001p+252]); ("153", 0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x8p-972, [~-.0xf.ffffe000001p+252]); ("154", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("155", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("156", 0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("157", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-128, [~-.infinity]); ("158", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-1024, [~-.infinity]); ("159", 0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x8p-972, [~-.infinity]); ("160", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("161", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("162", 0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("163", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x4p-128, [~-.0xf.ffffe000001p+252]); ("164", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x4p-1024, [~-.0xf.ffffe000001p+252]); ("165", ~-.0xf.fffffp+124, 0xf.fffffp+124, 0x8p-972, [~-.0xf.ffffe000001p+252]); ("166", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("167", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("168", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("169", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-128, [~-.infinity]); ("170", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x4p-1024, [~-.infinity]); ("171", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, 0x8p-972, [~-.infinity]); ("172", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-128, [~-.infinity]); ("173", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x4p-1024, [~-.infinity]); ("174", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, 0x8p-972, [~-.infinity]); ("175", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-128, [~-.0xf.ffffe000001p+252]); ("176", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x4p-1024, [~-.0xf.ffffe000001p+252]); ("177", ~-.0xf.fffffp+124, 0xf.fffffp+124, ~-.0x8p-972, [~-.0xf.ffffe000001p+252]); ("178", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("179", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("180", ~-.0xf.fffffp+124, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("181", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-128, [~-.infinity]); ("182", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x4p-1024, [~-.infinity]); ("183", ~-.0xf.ffffffffffff8p+1020, 0xf.fffffp+124, ~-.0x8p-972, [~-.infinity]); ("184", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-128, [~-.infinity]); ("185", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [~-.infinity]); ("186", ~-.0xf.ffffffffffff8p+1020, 0xf.ffffffffffff8p+1020, ~-.0x8p-972, [~-.infinity]); ("187", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-128, [0xf.ffffe000001p+252]); ("188", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x4p-1024, [0xf.ffffe000001p+252]); ("189", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, 0x8p-972, [0xf.ffffe000001p+252]); ("190", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("191", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("192", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("193", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-128, [infinity]); ("194", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x4p-1024, [infinity]); ("195", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, 0x8p-972, [infinity]); ("196", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-128, [infinity]); ("197", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x4p-1024, [infinity]); ("198", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, 0x8p-972, [infinity]); ("199", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-128, [0xf.ffffe000001p+252]); ("200", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x4p-1024, [0xf.ffffe000001p+252]); ("201", ~-.0xf.fffffp+124, ~-.0xf.fffffp+124, ~-.0x8p-972, [0xf.ffffe000001p+252]); ("202", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("203", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("204", ~-.0xf.fffffp+124, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("205", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-128, [infinity]); ("206", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x4p-1024, [infinity]); ("207", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.fffffp+124, ~-.0x8p-972, [infinity]); ("208", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-128, [infinity]); ("209", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x4p-1024, [infinity]); ("210", ~-.0xf.ffffffffffff8p+1020, ~-.0xf.ffffffffffff8p+1020, ~-.0x8p-972, [infinity]); ("211", 0x2.fffp+12, 0x1.000002p+0, 0x1.ffffp-24, [0x2.fff006p+12]); ("212", 0x1.fffp+0, 0x1.00001p+0, ~-.0x1.fffp+0, [0x1.fffp-20]); ("213", 0xc.d5e6fp+124, 0x2.6af378p-128, ~-.0x1.f08948p+0, [0xd.da108p-28]); ("214", 0x1.9abcdep+100, 0x2.6af378p-128, ~-.0x3.e1129p-28, [0x1.bb421p-52]); ("215", 0xf.fffffp+124, 0x1.001p+0, ~-.0xf.fffffp+124, [0xf.fffffp+112]); ("216", ~-.0xf.fffffp+124, 0x1.fffffep+0, 0xf.fffffp+124, [~-.0xf.ffffd000002p+124]); ("217", 0xf.fffffp+124, 0x2p+0, ~-.0xf.fffffp+124, [0xf.fffffp+124]); ("218", 0x5p-128, 0x8.00002p-4, 0x1p-128, [0x3.80000ap-128]); ("219", ~-.0x5p-128, 0x8.00002p-4, ~-.0x1p-128, [~-.0x3.80000ap-128]); ("220", 0x7.ffffep-128, 0x8.00001p-4, 0x8p-152, [0x3.ffffffffffep-128]); ("221", ~-.0x7.ffffep-128, 0x8.00001p-4, ~-.0x8p-152, [~-.0x3.ffffffffffep-128]); ("222", 0x8p-152, 0x8p-4, 0x3.fffff8p-128, [0x3.fffffcp-128]); ("223", ~-.0x8p-152, 0x8p-4, ~-.0x3.fffff8p-128, [~-.0x3.fffffcp-128]); ("224", 0x8p-152, 0x8.8p-4, 0x3.fffff8p-128, [0x3.fffffc4p-128]); ("225", ~-.0x8p-152, 0x8.8p-4, ~-.0x3.fffff8p-128, [~-.0x3.fffffc4p-128]); ("226", 0x8p-152, 0x8p-152, 0x8p+124, [0x8p+124]); ("227", 0x8p-152, ~-.0x8p-152, 0x8p+124, [0x8p+124]); ("228", 0x8p-152, 0x8p-152, ~-.0x8p+124, [~-.0x8p+124]); ("229", 0x8p-152, ~-.0x8p-152, ~-.0x8p+124, [~-.0x8p+124]); ("230", 0x8p-152, 0x8p-152, 0x4p-128, [0x4p-128]); ("231", 0x8p-152, ~-.0x8p-152, 0x4p-128, [0x4p-128]); ("232", 0x8p-152, 0x8p-152, ~-.0x4p-128, [~-.0x4p-128]); ("233", 0x8p-152, ~-.0x8p-152, ~-.0x4p-128, [~-.0x4p-128]); ("234", 0x8p-152, 0x8p-152, 0x3.fffff8p-128, [0x3.fffff8p-128]); ("235", 0x8p-152, ~-.0x8p-152, 0x3.fffff8p-128, [0x3.fffff8p-128]); ("236", 0x8p-152, 0x8p-152, ~-.0x3.fffff8p-128, [~-.0x3.fffff8p-128]); ("237", 0x8p-152, ~-.0x8p-152, ~-.0x3.fffff8p-128, [~-.0x3.fffff8p-128]); ("238", 0x8p-152, 0x8p-152, 0x8p-152, [0x8p-152]); ("239", 0x8p-152, ~-.0x8p-152, 0x8p-152, [0x8p-152]); ("240", 0x8p-152, 0x8p-152, ~-.0x8p-152, [~-.0x8p-152]); ("241", 0x8p-152, ~-.0x8p-152, ~-.0x8p-152, [~-.0x8p-152]); ("242", 0xf.ffp-4, 0xf.ffp-4, ~-.0xf.fep-4, [0x1p-24]); ("243", 0xf.ffp-4, ~-.0xf.ffp-4, 0xf.fep-4, [~-.0x1p-24]); ("244", ~-.0xf.ffp-4, 0xf.ffp-4, 0xf.fep-4, [~-.0x1p-24]); ("245", ~-.0xf.ffp-4, ~-.0xf.ffp-4, ~-.0xf.fep-4, [0x1p-24]); ("246", 0x4.000008p-128, 0x4.000008p-28, 0x8p+124, [0x8p+124]); ("247", 0x4.000008p-128, ~-.0x4.000008p-28, 0x8p+124, [0x8p+124]); ("248", 0x4.000008p-128, 0x4.000008p-28, ~-.0x8p+124, [~-.0x8p+124]); ("249", 0x4.000008p-128, ~-.0x4.000008p-28, ~-.0x8p+124, [~-.0x8p+124]); ("250", 0x4.000008p-128, 0x4.000008p-28, 0x8p+100, [0x8p+100]); ("251", 0x4.000008p-128, ~-.0x4.000008p-28, 0x8p+100, [0x8p+100]); ("252", 0x4.000008p-128, 0x4.000008p-28, ~-.0x8p+100, [~-.0x8p+100]); ("253", 0x4.000008p-128, ~-.0x4.000008p-28, ~-.0x8p+100, [~-.0x8p+100]); ("254", 0x2.fep+12, 0x1.0000000000001p+0, 0x1.ffep-48, [0x2.fe00000000002p+12; 0x1.7f00000000002p+13]); ("255", 0x1.fffp+0, 0x1.0000000000001p+0, ~-.0x1.fffp+0, [0x1.fffp-52; 0x1p-51]); ("256", 0x1.0000002p+0, 0xf.fffffep-4, 0x1p-300, [0x1p+0]); ("257", 0x1.0000002p+0, 0xf.fffffep-4, ~-.0x1p-300, [0xf.ffffffffffff8p-4; 0x1p+0]); ("258", 0xe.f56df7797f768p+1020, 0x3.7ab6fbbcbfbb4p-1024, ~-.0x3.40bf1803497f6p+0, [0x8.4c4b43de4ed2p-56; 0x1.095f287bc9da4p-53; 0x1.098p-53]); ("259", 0x1.deadbeef2feedp+900, 0x3.7ab6fbbcbfbb4p-1024, ~-.0x6.817e300692fecp-124, [0x1.0989687bc9da4p-176; 0x1.095f287bc9da4p-176; 0x1.098p-176]); ("260", 0xf.ffffffffffff8p+1020, 0x1.001p+0, ~-.0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1008; 0x1p+1012]); ("261", ~-.0xf.ffffffffffff8p+1020, 0x1.fffffffffffffp+0, 0xf.ffffffffffff8p+1020, [~-.0xf.fffffffffffe8p+1020]); ("262", 0xf.ffffffffffff8p+1020, 0x2p+0, ~-.0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("263", 0x5.a827999fcef3p-540, 0x5.a827999fcef3p-540, 0x0p+0, [0x0p+0]); ("264", 0x3.bd5b7dde5fddap-496, 0x3.bd5b7dde5fddap-496, ~-.0xd.fc352bc352bap-992, [0x1.0989687cp-1044; 0x0.000004277ca1fp-1022; 0x0.00000428p-1022]); ("265", 0x3.bd5b7dde5fddap-504, 0x3.bd5b7dde5fddap-504, ~-.0xd.fc352bc352bap-1008, [0x1.0988p-1060; 0x0.0000000004278p-1022; 0x0.000000000428p-1022]); ("266", 0x8p-540, 0x4p-540, 0x4p-1076, [0x8p-1076]); ("267", 0x1.7fffff8p-968, 0x4p-108, 0x4p-1048, [0x4.0000004p-1048; 0x0.0000010000002p-1022]); ("268", 0x2.8000008p-968, 0x4p-108, 0x4p-1048, [0x4.000000cp-1048; 0x0.0000010000002p-1022]); ("269", 0x2.8p-968, ~-.0x4p-108, ~-.0x4p-1048, [~-.0x4.0000008p-1048]); ("270", ~-.0x2.33956cdae7c2ep-960, 0x3.8e211518bfea2p-108, ~-.0x2.02c2b59766d9p-1024, [~-.0x2.02c2b59767564p-1024]); ("271", ~-.0x3.a5d5dadd1d3a6p-980, ~-.0x2.9c0cd8c5593bap-64, ~-.0x2.49179ac00d15p-1024, [~-.0x2.491702717ed74p-1024]); ("272", 0x2.2a7aca1773e0cp-908, 0x9.6809186a42038p-128, ~-.0x2.c9e356b3f0fp-1024, [~-.0x2.c89d5c48eefa4p-1024; ~-.0x0.b22757123bbe8p-1022]); ("273", ~-.0x3.ffffffffffffep-712, 0x3.ffffffffffffep-276, 0x3.fffffc0000ffep-984, [0x2.fffffc0000ffep-984; 0x1.7ffffe00008p-983]); ("274", 0x5p-1024, 0x8.000000000001p-4, 0x1p-1024, [0x3.8000000000004p-1024]); ("275", ~-.0x5p-1024, 0x8.000000000001p-4, ~-.0x1p-1024, [~-.0x3.8000000000004p-1024]); ("276", 0x7.ffffffffffffp-1024, 0x8.0000000000008p-4, 0x4p-1076, [0x4p-1024]); ("277", ~-.0x7.ffffffffffffp-1024, 0x8.0000000000008p-4, ~-.0x4p-1076, [~-.0x4p-1024]); ("278", 0x4p-1076, 0x8p-4, 0x3.ffffffffffffcp-1024, [0x4p-1024]); ("279", ~-.0x4p-1076, 0x8p-4, ~-.0x3.ffffffffffffcp-1024, [~-.0x4p-1024]); ("280", 0x4p-1076, 0x8.8p-4, 0x3.ffffffffffffcp-1024, [0x4p-1024]); ("281", ~-.0x4p-1076, 0x8.8p-4, ~-.0x3.ffffffffffffcp-1024, [~-.0x4p-1024]); ("282", 0x4p-1076, 0x4p-1076, 0x8p+1020, [0x8p+1020]); ("283", 0x4p-1076, ~-.0x4p-1076, 0x8p+1020, [0x8p+1020]); ("284", 0x4p-1076, 0x4p-1076, ~-.0x8p+1020, [~-.0x8p+1020]); ("285", 0x4p-1076, ~-.0x4p-1076, ~-.0x8p+1020, [~-.0x8p+1020]); ("286", 0x4p-1076, 0x4p-1076, 0x4p-1024, [0x4p-1024]); ("287", 0x4p-1076, ~-.0x4p-1076, 0x4p-1024, [0x4p-1024]); ("288", 0x4p-1076, 0x4p-1076, ~-.0x4p-1024, [~-.0x4p-1024]); ("289", 0x4p-1076, ~-.0x4p-1076, ~-.0x4p-1024, [~-.0x4p-1024]); ("290", 0x4p-1076, 0x4p-1076, 0x3.ffffffffffffcp-1024, [0x3.ffffffffffffcp-1024]); ("291", 0x4p-1076, ~-.0x4p-1076, 0x3.ffffffffffffcp-1024, [0x3.ffffffffffffcp-1024]); ("292", 0x4p-1076, 0x4p-1076, ~-.0x3.ffffffffffffcp-1024, [~-.0x3.ffffffffffffcp-1024]); ("293", 0x4p-1076, ~-.0x4p-1076, ~-.0x3.ffffffffffffcp-1024, [~-.0x3.ffffffffffffcp-1024]); ("294", 0x4p-1076, 0x4p-1076, 0x4p-1076, [0x4p-1076]); ("295", 0x4p-1076, ~-.0x4p-1076, 0x4p-1076, [0x4p-1076]); ("296", 0x4p-1076, 0x4p-1076, ~-.0x4p-1076, [~-.0x4p-1076]); ("297", 0x4p-1076, ~-.0x4p-1076, ~-.0x4p-1076, [~-.0x4p-1076]); ("298", 0xf.ffffffffffff8p-4, 0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffffp-4, [0x4p-108; 0x0p+0]); ("299", 0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffff8p-4, 0xf.ffffffffffffp-4, [~-.0x4p-108; 0x0p+0]); ("300", ~-.0xf.ffffffffffff8p-4, 0xf.ffffffffffff8p-4, 0xf.ffffffffffffp-4, [~-.0x4p-108; 0x0p+0]); ("301", ~-.0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffff8p-4, ~-.0xf.ffffffffffffp-4, [0x4p-108; 0x0p+0]); ("302", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, 0x8p+1020, [0x8p+1020]); ("303", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, 0x8p+1020, [0x8p+1020]); ("304", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, ~-.0x8p+1020, [~-.0x8p+1020]); ("305", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, ~-.0x8p+1020, [~-.0x8p+1020]); ("306", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, 0x4p+968, [0x4p+968]); ("307", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, 0x4p+968, [0x4p+968]); ("308", 0x4.0000000000004p-1024, 0x2.0000000000002p-56, ~-.0x4p+968, [~-.0x4p+968]); ("309", 0x4.0000000000004p-1024, ~-.0x2.0000000000002p-56, ~-.0x4p+968, [~-.0x4p+968]); ("310", 0x7.fffff8p-128, 0x3.fffffcp+24, 0xf.fffffp+124, [0xf.fffffp+124]); ("311", 0x7.fffff8p-128, ~-.0x3.fffffcp+24, 0xf.fffffp+124, [0xf.fffffp+124]); ("312", 0x7.fffff8p-128, 0x3.fffffcp+24, ~-.0xf.fffffp+124, [~-.0xf.fffffp+124]); ("313", 0x7.fffff8p-128, ~-.0x3.fffffcp+24, ~-.0xf.fffffp+124, [~-.0xf.fffffp+124]); ("314", 0x7.ffffffffffffcp-1024, 0x7.ffffffffffffcp+52, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("315", 0x7.ffffffffffffcp-1024, ~-.0x7.ffffffffffffcp+52, 0xf.ffffffffffff8p+1020, [0xf.ffffffffffff8p+1020]); ("316", 0x7.ffffffffffffcp-1024, 0x7.ffffffffffffcp+52, ~-.0xf.ffffffffffff8p+1020, [~-.0xf.ffffffffffff8p+1020]); ("317", 0x7.ffffffffffffcp-1024, ~-.0x7.ffffffffffffcp+52, ~-.0xf.ffffffffffff8p+1020, [~-.0xf.ffffffffffff8p+1020]) ] in let rec do_cases c = match c with (l, x, y, z, r)::t -> fma_test l x y z r; do_cases t | [] -> () in do_cases cases
ec231949c4b29a4feadcf237263878f4f76ca3f77893e4a480f5ba177d695859
DomainDrivenArchitecture/dda-pallet
versioned_plan_test.clj
Licensed to the Apache Software Foundation ( ASF ) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file to you under the Apache License , Version 2.0 ( the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; -2.0 ; ; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.core.infra.versioned-plan-test (:require [clojure.test :refer :all] [schema.core :as s] [dda.pallet.core.infra.versioned-plan :as sut])) (deftest install-marker (testing "path of install-marker" (is (= "/var/lib/pallet/state/mycrate" (sut/install-marker-path {:facility :mycrate})))))
null
https://raw.githubusercontent.com/DomainDrivenArchitecture/dda-pallet/aa251ac1c678a46ef9183d9fb2d447c4f77a99d3/test/src/dda/pallet/core/infra/versioned_plan_test.clj
clojure
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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.
Licensed to the Apache Software Foundation ( ASF ) under one to you under the Apache License , Version 2.0 ( the distributed under the License is distributed on an " AS IS " BASIS , (ns dda.pallet.core.infra.versioned-plan-test (:require [clojure.test :refer :all] [schema.core :as s] [dda.pallet.core.infra.versioned-plan :as sut])) (deftest install-marker (testing "path of install-marker" (is (= "/var/lib/pallet/state/mycrate" (sut/install-marker-path {:facility :mycrate})))))
7672415b575ff9512b0054fbd4ae24c6f34e0b7ba21614c88ad75a13ab11ef54
yjqww6/racket-x64asm
helper.rkt
#lang typed/racket/base (require racket/match (for-syntax racket/base syntax/parse syntax/id-table)) (provide define-struct-match) (begin-for-syntax (define-syntax-class kid (pattern id:id #:attr kw (datum->syntax #f (string->keyword (symbol->string (syntax-e #'id))))))) (define-syntax (define-struct-match stx) (syntax-parse stx [(_ name:id s:id field:kid ...) #'(define-match-expander name (λ (stx) (syntax-parse stx [(_ (~alt (~optional (~seq field.kw field) #:defaults ([field #'_])) ...) (... ...)) #'(s field ...)] )))]))
null
https://raw.githubusercontent.com/yjqww6/racket-x64asm/73c2b8edc7e96a6248a7ee25fd7a6ae7065ee966/x64asm-lib/x64asm/private/helper.rkt
racket
#lang typed/racket/base (require racket/match (for-syntax racket/base syntax/parse syntax/id-table)) (provide define-struct-match) (begin-for-syntax (define-syntax-class kid (pattern id:id #:attr kw (datum->syntax #f (string->keyword (symbol->string (syntax-e #'id))))))) (define-syntax (define-struct-match stx) (syntax-parse stx [(_ name:id s:id field:kid ...) #'(define-match-expander name (λ (stx) (syntax-parse stx [(_ (~alt (~optional (~seq field.kw field) #:defaults ([field #'_])) ...) (... ...)) #'(s field ...)] )))]))
991bcf37d4a0103fa500579251cbcb81d30738ee5b3c78fdf256316c2f19fabe
elastic/eui-cljs
format_text.cljs
(ns eui.services.format-text (:require ["@elastic/eui/lib/services/format/format_text.js" :as eui])) (def formatText eui/formatText)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/services/format_text.cljs
clojure
(ns eui.services.format-text (:require ["@elastic/eui/lib/services/format/format_text.js" :as eui])) (def formatText eui/formatText)
9ee14cab3bdde62f450d0e386f47aff2cf8baa59ac23341577630d112d0b6924
janestreet/hardcaml_circuits
pipelined_adder.ml
open Base open Hardcaml open Signal Creates an architecture that looks like { v | reg | reg | + | | reg | + | reg | | + | reg | reg | v } Each adder is of size [ part_width+1 ] and sums 3 operands ( the third being a carry in bit ) . The adders are registered in the above diagram . The architecture requires a lot of registers for pipelining . Not providing clear should help to pack the register pipelines into SRLs . {v | reg | reg | + | | reg | + | reg | | + | reg | reg | v} Each adder is of size [part_width+1] and sums 3 operands (the third being a carry in bit). The adders are registered in the above diagram. The architecture requires a lot of registers for pipelining. Not providing clear should help to pack the register pipelines into SRLs. *) let create ~part_width ~clock ?clear ?(c_in = gnd) a b = assert (width a = width b); assert (width c_in = 1); let a = split_lsb ~exact:false ~part_width a in let b = split_lsb ~exact:false ~part_width b in let reg = reg (Reg_spec.create ~clock ?clear ()) ~enable:vdd in let regs = List.map ~f:reg in let rec f prev a b carry = match a, b with | [], [] -> prev | a :: at, b :: bt -> (* assuming that the synthesizer will perform the carry addition for 'free' *) let c = reg (ue a +: ue b +: uresize carry (width a + 1)) in f (lsbs c :: regs prev) (regs at) (regs bt) (msb c) | _ -> raise_s [%message "pipelined adder arguments are not the same width"] in f [] a b c_in |> concat_msb ;; module Short_latency = struct type 'a sum = { c_out : 'a ; sum : 'a } [@@deriving sexp_of] type 'a sums = { sum0 : 'a sum ; sum1 : 'a sum } [@@deriving sexp_of] let partial_sums (type a) (module Comb : Comb.S with type t = a) ~part_width (a : a) (b : a) = let open Comb in let build_sums a b = let sum0 = Uop.(a +: b) in let sum1 = Uop.(a +: b) +:. 1 in let sum x = { c_out = msb x; sum = lsbs x } in { sum0 = sum sum0; sum1 = sum sum1 } in let a = split_lsb ~exact:false ~part_width a in let b = split_lsb ~exact:false ~part_width b in List.map2_exn a b ~f:build_sums ;; (* This is the core of the architecture. It takes the carry outs for [a+b] and [a+b+1] for each sub-part of the adder, and exposes the internal carry out as part of the sum. See the paper for more details. *) let carry_ahead (type a) (module Comb : Comb.S with type t = a) partial_sums = let open Comb in let s0 = List.map partial_sums ~f:(fun sums -> gnd @: sums.sum0.c_out) |> concat_lsb in let s1 = List.map partial_sums ~f:(fun sums -> vdd @: sums.sum1.c_out) |> concat_lsb in let cac_sum = s0 +: s1 in List.mapi partial_sums ~f:(fun i partial_sum -> if i = 0 then ~:(partial_sum.sum0.c_out) else bit cac_sum ((i * 2) + 1)) ;; let final_sums (type a) (module Comb : Comb.S with type t = a) (partial_sums : a sums list) (cac : a list) (c_in : a) = let open Comb in let rec f partial_sums cac c_in = match partial_sums, cac with | [], [] -> [] | p :: pt, c :: ct -> (p.sum0.sum +: uresize c_in (width p.sum0.sum)) :: f pt ct ~:c | _ -> assert false in f partial_sums cac c_in ;; let comb (type a) (module Comb : Comb.S with type t = a) ~part_width (a : a) (b : a) = let partial_sums = partial_sums (module Comb) ~part_width a b in let cac = carry_ahead (module Comb) partial_sums in final_sums (module Comb) partial_sums cac Comb.gnd |> Comb.concat_lsb ;; let partial_sum_reg spec sum = let reg = reg spec ~enable:vdd in { sum0 = { c_out = reg sum.sum0.c_out; sum = reg sum.sum0.sum } ; sum1 = { c_out = reg sum.sum1.c_out; sum = reg sum.sum1.sum } } ;; let create ~part_width ~clock ?clear a b = let spec = Reg_spec.create ~clock ?clear () in let partial_sums = partial_sums (module Signal) ~part_width a b in let partial_sums = List.map partial_sums ~f:(partial_sum_reg spec) in let cac = carry_ahead (module Signal) partial_sums in let cac = List.map cac ~f:(reg spec ~enable:vdd) in let partial_sums = List.map partial_sums ~f:(partial_sum_reg spec) in final_sums (module Signal) partial_sums cac Signal.gnd |> Signal.concat_lsb ;; end
null
https://raw.githubusercontent.com/janestreet/hardcaml_circuits/a2c2d1ea3e6957c3cda4767d519e94c20f1172b2/src/pipelined_adder.ml
ocaml
assuming that the synthesizer will perform the carry addition for 'free' This is the core of the architecture. It takes the carry outs for [a+b] and [a+b+1] for each sub-part of the adder, and exposes the internal carry out as part of the sum. See the paper for more details.
open Base open Hardcaml open Signal Creates an architecture that looks like { v | reg | reg | + | | reg | + | reg | | + | reg | reg | v } Each adder is of size [ part_width+1 ] and sums 3 operands ( the third being a carry in bit ) . The adders are registered in the above diagram . The architecture requires a lot of registers for pipelining . Not providing clear should help to pack the register pipelines into SRLs . {v | reg | reg | + | | reg | + | reg | | + | reg | reg | v} Each adder is of size [part_width+1] and sums 3 operands (the third being a carry in bit). The adders are registered in the above diagram. The architecture requires a lot of registers for pipelining. Not providing clear should help to pack the register pipelines into SRLs. *) let create ~part_width ~clock ?clear ?(c_in = gnd) a b = assert (width a = width b); assert (width c_in = 1); let a = split_lsb ~exact:false ~part_width a in let b = split_lsb ~exact:false ~part_width b in let reg = reg (Reg_spec.create ~clock ?clear ()) ~enable:vdd in let regs = List.map ~f:reg in let rec f prev a b carry = match a, b with | [], [] -> prev | a :: at, b :: bt -> let c = reg (ue a +: ue b +: uresize carry (width a + 1)) in f (lsbs c :: regs prev) (regs at) (regs bt) (msb c) | _ -> raise_s [%message "pipelined adder arguments are not the same width"] in f [] a b c_in |> concat_msb ;; module Short_latency = struct type 'a sum = { c_out : 'a ; sum : 'a } [@@deriving sexp_of] type 'a sums = { sum0 : 'a sum ; sum1 : 'a sum } [@@deriving sexp_of] let partial_sums (type a) (module Comb : Comb.S with type t = a) ~part_width (a : a) (b : a) = let open Comb in let build_sums a b = let sum0 = Uop.(a +: b) in let sum1 = Uop.(a +: b) +:. 1 in let sum x = { c_out = msb x; sum = lsbs x } in { sum0 = sum sum0; sum1 = sum sum1 } in let a = split_lsb ~exact:false ~part_width a in let b = split_lsb ~exact:false ~part_width b in List.map2_exn a b ~f:build_sums ;; let carry_ahead (type a) (module Comb : Comb.S with type t = a) partial_sums = let open Comb in let s0 = List.map partial_sums ~f:(fun sums -> gnd @: sums.sum0.c_out) |> concat_lsb in let s1 = List.map partial_sums ~f:(fun sums -> vdd @: sums.sum1.c_out) |> concat_lsb in let cac_sum = s0 +: s1 in List.mapi partial_sums ~f:(fun i partial_sum -> if i = 0 then ~:(partial_sum.sum0.c_out) else bit cac_sum ((i * 2) + 1)) ;; let final_sums (type a) (module Comb : Comb.S with type t = a) (partial_sums : a sums list) (cac : a list) (c_in : a) = let open Comb in let rec f partial_sums cac c_in = match partial_sums, cac with | [], [] -> [] | p :: pt, c :: ct -> (p.sum0.sum +: uresize c_in (width p.sum0.sum)) :: f pt ct ~:c | _ -> assert false in f partial_sums cac c_in ;; let comb (type a) (module Comb : Comb.S with type t = a) ~part_width (a : a) (b : a) = let partial_sums = partial_sums (module Comb) ~part_width a b in let cac = carry_ahead (module Comb) partial_sums in final_sums (module Comb) partial_sums cac Comb.gnd |> Comb.concat_lsb ;; let partial_sum_reg spec sum = let reg = reg spec ~enable:vdd in { sum0 = { c_out = reg sum.sum0.c_out; sum = reg sum.sum0.sum } ; sum1 = { c_out = reg sum.sum1.c_out; sum = reg sum.sum1.sum } } ;; let create ~part_width ~clock ?clear a b = let spec = Reg_spec.create ~clock ?clear () in let partial_sums = partial_sums (module Signal) ~part_width a b in let partial_sums = List.map partial_sums ~f:(partial_sum_reg spec) in let cac = carry_ahead (module Signal) partial_sums in let cac = List.map cac ~f:(reg spec ~enable:vdd) in let partial_sums = List.map partial_sums ~f:(partial_sum_reg spec) in final_sums (module Signal) partial_sums cac Signal.gnd |> Signal.concat_lsb ;; end
9068e9ab87d344f1b3cd64c578eafd1dbc1f3d9d99b0bd2ceaf3964906bfd836
conjure-cp/conjure
TranslateParameter.hs
module Conjure.UI.TranslateParameter ( translateParameter ) where -- conjure import Conjure.Prelude import Conjure.Bug import Conjure.UserError import Conjure.Language.Definition import Conjure.Language.Domain import Conjure.Language.Constant import Conjure.Language.Type import Conjure.Language.Pretty import Conjure.Language.Instantiate import Conjure.Process.Enums ( removeEnumsFromParam ) import Conjure.Process.FiniteGivens ( finiteGivensParam ) import Conjure.Process.Enumerate ( EnumerateDomain ) import Conjure.Process.ValidateConstantForDomain ( validateConstantForDomain ) import Conjure.Representations ( downC ) translateParameter :: MonadFailDoc m => MonadLog m => NameGen m => EnumerateDomain m => MonadIO m => (?typeCheckerMode :: TypeCheckerMode) => Prepare input files for the Glasgow graph solver Model -> -- eprime model Model -> -- essence param m Model -- eprime param translateParameter graphSolver eprimeModel0 essenceParam0 = do logDebug $ "[eprimeModel 0]" <+-> pretty essenceParam0 logDebug $ "[essenceParam 0]" <+-> pretty essenceParam0 (eprimeModel, essenceParam1) <- removeEnumsFromParam eprimeModel0 essenceParam0 logDebug $ "[eprimeModel 1]" <+-> pretty eprimeModel logDebug $ "[essenceParam 1]" <+-> pretty essenceParam1 let eprimeLettingsForEnums = [ (nm, fromInt (genericLength vals)) | nm1 <- eprimeModel |> mInfo |> miEnumGivens , Declaration (LettingDomainDefnEnum nm2 vals) <- essenceParam0 |> mStatements , nm1 == nm2 , let nm = nm1 `mappend` "_EnumSize" ] (essenceParam, generatedLettingNames) <- finiteGivensParam eprimeModel essenceParam1 eprimeLettingsForEnums logDebug $ "[essenceParam 2]" <+-> pretty essenceParam let essenceLettings = extractLettings essenceParam let essenceGivenNames = eprimeModel |> mInfo |> miGivens let essenceGivens = eprimeModel |> mInfo |> miRepresentations |> filter (\ (n,_) -> n `elem` essenceGivenNames ) logDebug $ "[essenceLettings ]" <+-> vcat [ pretty n <> ":" <+> pretty x | (n,x) <- essenceLettings ] logDebug $ "[essenceGivenNames]" <+-> vcat (map pretty essenceGivenNames) logDebug $ "[essenceGivens ]" <+-> vcat [ pretty n <> ":" <+> pretty x | (n,x) <- essenceGivens ] -- some sanity checks here -- TODO: check if for every given there is a letting (there can be more) -- TODO: check if the same letting has multiple values for it let missingLettings = (essenceGivenNames ++ generatedLettingNames) \\ map fst essenceLettings unless (null missingLettings) $ userErr1 $ "Missing values for parameters:" <++> prettyList id "," missingLettings let extraLettings = map fst essenceLettings \\ (essenceGivenNames ++ generatedLettingNames) unless (null extraLettings) $ userErr1 $ "Too many letting statements in the parameter file:" <++> prettyList id "," extraLettings let allLettings = (eprimeModel |> mInfo |> miLettings) ++ essenceLettings ++ map (second Constant) eprimeLettingsForEnums essenceLettings' <- forM essenceLettings $ \ (name, val) -> do constant <- instantiateExpression allLettings val return (name, constant) logDebug $ "[essenceLettings' ]" <+> vcat [ pretty n <> ":" <+-> pretty x | (n,x) <- essenceLettings' ] essenceGivens' <- forM essenceGivens $ \ (name, dom) -> do constant <- instantiateDomain allLettings dom return (name, constant) logDebug $ "[essenceGivens' ]" <+> vcat [ pretty n <> ":" <+-> pretty x | (n,x) <- essenceGivens' ] essenceGivensAndLettings <- sequence [ case lookup n essenceLettings' of Nothing -> if n `elem` map fst eprimeLettingsForEnums then return Nothing else userErr1 $ vcat [ "No value for parameter:" <+> pretty n , "With domain:" <+> pretty d ] Just v -> if emptyCollection v then do (c, cTyMaybe) <- case v of TypedConstant c cTy | elem TypeAny (universe cTy) -- we may be able to do better! -> return (c, Just cTy) | otherwise -> return (v, Nothing) -- already sufficiently typed _ -> return (v, Just TypeAny) -- empty collection, unknown type case cTyMaybe of Nothing -> return $ Just (n, d, v) Just cTy1 -> do -- calculate the type of the domain, unify with the type we already have cTy2 <- typeOfDomain d let cTy = mostDefined [cTy1, cTy2] if elem TypeAny (universe cTy) then userErr1 $ vcat [ "Cannot fully determine the type of parameter" <+> pretty n , "Domain:" <+> pretty d , "Value :" <+> pretty v ] else return $ Just (n, d, TypedConstant c cTy) else return $ Just (n, d, v) | (n, d) <- essenceGivens' ++ [ (n, DomainInt TagInt []) | n <- generatedLettingNames ] ] logDebug $ "[essenceGivensAndLettings ]" <+> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | Just (n,d,c) <- essenceGivensAndLettings ] let f (Reference nm Nothing) = case [ val | (nm2, val) <- eprimeLettingsForEnums, nm == nm2 ] of [] -> bug ("translateParameter: No value for" <+> pretty nm) [val] -> Constant val _ -> bug ("translateParameter: Multiple values for" <+> pretty nm) f p = p let essenceGivensAndLettings' :: [(Name, Domain HasRepresentation Constant, Constant)] essenceGivensAndLettings' = transformBi f (catMaybes essenceGivensAndLettings) logDebug $ "[essenceGivensAndLettings']" <+-> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | (n,d,c) <- essenceGivensAndLettings' ] errs <- execWriterT $ forM_ essenceGivensAndLettings' $ \ (nm, dom, val) -> do mres <- runExceptT $ validateConstantForDomain nm val dom case mres of Left err -> tell [err] Right () -> return () unless (null errs) (userErr errs) let decorateWithType p@(_, _, TypedConstant{}) = return p decorateWithType (name, domain, constant) | emptyCollection constant = do ty <- typeOfDomain domain return (name, domain, TypedConstant constant ty) decorateWithType p = return p when graphSolver $ do forM_ essenceGivensAndLettings' $ \ (n,d,c) -> do let pairs = case d of DomainFunction _ _ (DomainTuple [DomainInt{}, DomainInt{}]) _ -> case c of (viewConstantFunction -> Just rows) -> [ case row of (ConstantAbstract (AbsLitTuple [a, b]), _) -> [a,b] _ -> [] | row <- rows ] _ -> [] DomainRelation _ _ ([DomainInt{}, DomainInt{}, _]) -> case c of (viewConstantRelation -> Just rows) -> [ case row of [a, b, _] -> [a,b] _ -> [] | row <- rows ] _ -> [] _ -> [] let csvLines = [ pretty a <> "," <> pretty b | [a,b] <- sortNub pairs ] unless (null pairs) $ liftIO $ writeFile ("given-" ++ show (pretty n) ++ ".csv") (render 100000 (vcat csvLines)) let essenceFindNames = eprimeModel |> mInfo |> miFinds let essenceFinds = eprimeModel |> mInfo |> miRepresentations |> filter (\ (n,_) -> n `elem` essenceFindNames ) forM_ essenceFinds $ \ (n, d) -> do case d of DomainFunction _ _ (DomainInt _ [RangeBounded a b]) _ -> do a' <- instantiateExpression allLettings a b' <- instantiateExpression allLettings b case (a', b') of (ConstantInt _ a'', ConstantInt _ b'') -> do let csvLines = [ pretty i <> "," <> name | i <- [a''..b''] , let name = pretty n <> "_Function1D_" <> pretty (padLeft 5 '0' (show i)) ] unless (null csvLines) $ liftIO $ writeFile ("find-" ++ show (pretty n) ++ ".csv") (render 100000 (vcat csvLines)) _ -> userErr1 $ "Unsupported domain for --graph-solver:" <+> pretty d _ -> return () eprimeLettings :: [(Name, Domain HasRepresentation Constant, Constant)] <- failToUserError $ concatMapM downC essenceGivensAndLettings' >>= mapM decorateWithType logDebug $ "[eprimeLettings ]" <+> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | (n,d,c) <- eprimeLettings ] return $ languageEprime def { mStatements = transformBi (\ _ -> TagInt) $ [ Declaration (Letting n (Constant x)) | (n, _, x) <- eprimeLettings ] ++ [ Declaration (Letting n (Constant x)) | (n, x) <- eprimeLettingsForEnums ] }
null
https://raw.githubusercontent.com/conjure-cp/conjure/dd5a27df138af2ccbbb970274c2b8f22ac6b26a0/src/Conjure/UI/TranslateParameter.hs
haskell
conjure eprime model essence param eprime param some sanity checks here TODO: check if for every given there is a letting (there can be more) TODO: check if the same letting has multiple values for it we may be able to do better! already sufficiently typed empty collection, unknown type calculate the type of the domain, unify with the type we already have
module Conjure.UI.TranslateParameter ( translateParameter ) where import Conjure.Prelude import Conjure.Bug import Conjure.UserError import Conjure.Language.Definition import Conjure.Language.Domain import Conjure.Language.Constant import Conjure.Language.Type import Conjure.Language.Pretty import Conjure.Language.Instantiate import Conjure.Process.Enums ( removeEnumsFromParam ) import Conjure.Process.FiniteGivens ( finiteGivensParam ) import Conjure.Process.Enumerate ( EnumerateDomain ) import Conjure.Process.ValidateConstantForDomain ( validateConstantForDomain ) import Conjure.Representations ( downC ) translateParameter :: MonadFailDoc m => MonadLog m => NameGen m => EnumerateDomain m => MonadIO m => (?typeCheckerMode :: TypeCheckerMode) => Prepare input files for the Glasgow graph solver translateParameter graphSolver eprimeModel0 essenceParam0 = do logDebug $ "[eprimeModel 0]" <+-> pretty essenceParam0 logDebug $ "[essenceParam 0]" <+-> pretty essenceParam0 (eprimeModel, essenceParam1) <- removeEnumsFromParam eprimeModel0 essenceParam0 logDebug $ "[eprimeModel 1]" <+-> pretty eprimeModel logDebug $ "[essenceParam 1]" <+-> pretty essenceParam1 let eprimeLettingsForEnums = [ (nm, fromInt (genericLength vals)) | nm1 <- eprimeModel |> mInfo |> miEnumGivens , Declaration (LettingDomainDefnEnum nm2 vals) <- essenceParam0 |> mStatements , nm1 == nm2 , let nm = nm1 `mappend` "_EnumSize" ] (essenceParam, generatedLettingNames) <- finiteGivensParam eprimeModel essenceParam1 eprimeLettingsForEnums logDebug $ "[essenceParam 2]" <+-> pretty essenceParam let essenceLettings = extractLettings essenceParam let essenceGivenNames = eprimeModel |> mInfo |> miGivens let essenceGivens = eprimeModel |> mInfo |> miRepresentations |> filter (\ (n,_) -> n `elem` essenceGivenNames ) logDebug $ "[essenceLettings ]" <+-> vcat [ pretty n <> ":" <+> pretty x | (n,x) <- essenceLettings ] logDebug $ "[essenceGivenNames]" <+-> vcat (map pretty essenceGivenNames) logDebug $ "[essenceGivens ]" <+-> vcat [ pretty n <> ":" <+> pretty x | (n,x) <- essenceGivens ] let missingLettings = (essenceGivenNames ++ generatedLettingNames) \\ map fst essenceLettings unless (null missingLettings) $ userErr1 $ "Missing values for parameters:" <++> prettyList id "," missingLettings let extraLettings = map fst essenceLettings \\ (essenceGivenNames ++ generatedLettingNames) unless (null extraLettings) $ userErr1 $ "Too many letting statements in the parameter file:" <++> prettyList id "," extraLettings let allLettings = (eprimeModel |> mInfo |> miLettings) ++ essenceLettings ++ map (second Constant) eprimeLettingsForEnums essenceLettings' <- forM essenceLettings $ \ (name, val) -> do constant <- instantiateExpression allLettings val return (name, constant) logDebug $ "[essenceLettings' ]" <+> vcat [ pretty n <> ":" <+-> pretty x | (n,x) <- essenceLettings' ] essenceGivens' <- forM essenceGivens $ \ (name, dom) -> do constant <- instantiateDomain allLettings dom return (name, constant) logDebug $ "[essenceGivens' ]" <+> vcat [ pretty n <> ":" <+-> pretty x | (n,x) <- essenceGivens' ] essenceGivensAndLettings <- sequence [ case lookup n essenceLettings' of Nothing -> if n `elem` map fst eprimeLettingsForEnums then return Nothing else userErr1 $ vcat [ "No value for parameter:" <+> pretty n , "With domain:" <+> pretty d ] Just v -> if emptyCollection v then do (c, cTyMaybe) <- case v of TypedConstant c cTy -> return (c, Just cTy) | otherwise case cTyMaybe of Nothing -> return $ Just (n, d, v) Just cTy1 -> do cTy2 <- typeOfDomain d let cTy = mostDefined [cTy1, cTy2] if elem TypeAny (universe cTy) then userErr1 $ vcat [ "Cannot fully determine the type of parameter" <+> pretty n , "Domain:" <+> pretty d , "Value :" <+> pretty v ] else return $ Just (n, d, TypedConstant c cTy) else return $ Just (n, d, v) | (n, d) <- essenceGivens' ++ [ (n, DomainInt TagInt []) | n <- generatedLettingNames ] ] logDebug $ "[essenceGivensAndLettings ]" <+> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | Just (n,d,c) <- essenceGivensAndLettings ] let f (Reference nm Nothing) = case [ val | (nm2, val) <- eprimeLettingsForEnums, nm == nm2 ] of [] -> bug ("translateParameter: No value for" <+> pretty nm) [val] -> Constant val _ -> bug ("translateParameter: Multiple values for" <+> pretty nm) f p = p let essenceGivensAndLettings' :: [(Name, Domain HasRepresentation Constant, Constant)] essenceGivensAndLettings' = transformBi f (catMaybes essenceGivensAndLettings) logDebug $ "[essenceGivensAndLettings']" <+-> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | (n,d,c) <- essenceGivensAndLettings' ] errs <- execWriterT $ forM_ essenceGivensAndLettings' $ \ (nm, dom, val) -> do mres <- runExceptT $ validateConstantForDomain nm val dom case mres of Left err -> tell [err] Right () -> return () unless (null errs) (userErr errs) let decorateWithType p@(_, _, TypedConstant{}) = return p decorateWithType (name, domain, constant) | emptyCollection constant = do ty <- typeOfDomain domain return (name, domain, TypedConstant constant ty) decorateWithType p = return p when graphSolver $ do forM_ essenceGivensAndLettings' $ \ (n,d,c) -> do let pairs = case d of DomainFunction _ _ (DomainTuple [DomainInt{}, DomainInt{}]) _ -> case c of (viewConstantFunction -> Just rows) -> [ case row of (ConstantAbstract (AbsLitTuple [a, b]), _) -> [a,b] _ -> [] | row <- rows ] _ -> [] DomainRelation _ _ ([DomainInt{}, DomainInt{}, _]) -> case c of (viewConstantRelation -> Just rows) -> [ case row of [a, b, _] -> [a,b] _ -> [] | row <- rows ] _ -> [] _ -> [] let csvLines = [ pretty a <> "," <> pretty b | [a,b] <- sortNub pairs ] unless (null pairs) $ liftIO $ writeFile ("given-" ++ show (pretty n) ++ ".csv") (render 100000 (vcat csvLines)) let essenceFindNames = eprimeModel |> mInfo |> miFinds let essenceFinds = eprimeModel |> mInfo |> miRepresentations |> filter (\ (n,_) -> n `elem` essenceFindNames ) forM_ essenceFinds $ \ (n, d) -> do case d of DomainFunction _ _ (DomainInt _ [RangeBounded a b]) _ -> do a' <- instantiateExpression allLettings a b' <- instantiateExpression allLettings b case (a', b') of (ConstantInt _ a'', ConstantInt _ b'') -> do let csvLines = [ pretty i <> "," <> name | i <- [a''..b''] , let name = pretty n <> "_Function1D_" <> pretty (padLeft 5 '0' (show i)) ] unless (null csvLines) $ liftIO $ writeFile ("find-" ++ show (pretty n) ++ ".csv") (render 100000 (vcat csvLines)) _ -> userErr1 $ "Unsupported domain for --graph-solver:" <+> pretty d _ -> return () eprimeLettings :: [(Name, Domain HasRepresentation Constant, Constant)] <- failToUserError $ concatMapM downC essenceGivensAndLettings' >>= mapM decorateWithType logDebug $ "[eprimeLettings ]" <+> vcat [ vcat [ "name :" <+> pretty n , "domain :" <+> pretty d , "constant:" <+-> pretty c ] | (n,d,c) <- eprimeLettings ] return $ languageEprime def { mStatements = transformBi (\ _ -> TagInt) $ [ Declaration (Letting n (Constant x)) | (n, _, x) <- eprimeLettings ] ++ [ Declaration (Letting n (Constant x)) | (n, x) <- eprimeLettingsForEnums ] }
e79cafd322a290206627962734c7f6d591dd22e57d526a34f2e58ae5445ce0f4
Zulu-Inuoe/jzon
jzon-parsing.lisp
(defpackage #:com.inuoe.jzon-parsing (:use #:cl) (:local-nicknames (#:jzon #:com.inuoe.jzon)) (:import-from #:alexandria #:eswitch #:read-stream-content-into-string) (:import-from #:cl-json) (:import-from #:jonathan) (:import-from #:json-streams) (:import-from #:jsown) (:import-from #:shasht) (:import-from #:yason) (:export #:main)) (in-package #:com.inuoe.jzon-parsing) (defun parser-fn (name) (eswitch (name :test #'string-equal) ("cl-json" #'cl-json:decode-json-from-source) ("jzon" #'jzon:parse) ("jonathan" (lambda (s) (jonathan:parse (read-stream-content-into-string s)))) ("jsown" (lambda (s) (jsown:parse (read-stream-content-into-string s)))) ("json-streams" #'json-streams:json-parse) ("shasht" #'shasht:read-json) ("yason" #'yason:parse))) (defun main (&rest argv) (prog ((file (second argv)) (parser-name (or (third argv) "jzon"))) (unless file (format *error-output* "Missing input file.~%") (return 2)) (when (string= file "--help") (format t "usage: jzon-parsing test-file [parser-name] ") (return 0)) (let ((parser (parser-fn parser-name))) (with-open-file (stream file :direction :input :if-does-not-exist nil :external-format :utf8) (unless stream (format *error-output* "Error opening '~A'" file) (return 2)) (return (if (ignore-errors (funcall parser stream) t) 0 1))))))
null
https://raw.githubusercontent.com/Zulu-Inuoe/jzon/c69fa5c08dee2c4fb2c5f4a39d581943a2c4cdd8/JSONTestSuite/jzon-parsing.lisp
lisp
(defpackage #:com.inuoe.jzon-parsing (:use #:cl) (:local-nicknames (#:jzon #:com.inuoe.jzon)) (:import-from #:alexandria #:eswitch #:read-stream-content-into-string) (:import-from #:cl-json) (:import-from #:jonathan) (:import-from #:json-streams) (:import-from #:jsown) (:import-from #:shasht) (:import-from #:yason) (:export #:main)) (in-package #:com.inuoe.jzon-parsing) (defun parser-fn (name) (eswitch (name :test #'string-equal) ("cl-json" #'cl-json:decode-json-from-source) ("jzon" #'jzon:parse) ("jonathan" (lambda (s) (jonathan:parse (read-stream-content-into-string s)))) ("jsown" (lambda (s) (jsown:parse (read-stream-content-into-string s)))) ("json-streams" #'json-streams:json-parse) ("shasht" #'shasht:read-json) ("yason" #'yason:parse))) (defun main (&rest argv) (prog ((file (second argv)) (parser-name (or (third argv) "jzon"))) (unless file (format *error-output* "Missing input file.~%") (return 2)) (when (string= file "--help") (format t "usage: jzon-parsing test-file [parser-name] ") (return 0)) (let ((parser (parser-fn parser-name))) (with-open-file (stream file :direction :input :if-does-not-exist nil :external-format :utf8) (unless stream (format *error-output* "Error opening '~A'" file) (return 2)) (return (if (ignore-errors (funcall parser stream) t) 0 1))))))
fc9a1049baece32293dbb965a0a0226ad1ac5414d4f2742d302a6456e4fb4b04
atolab/zenoh
zenoh_api.ml
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0 , or the Apache License , Version 2.0 * which is available at -2.0 . * * SPDX - License - Identifier : EPL-2.0 OR Apache-2.0 * * Contributors : * team , < > * Copyright (c) 2017, 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0, or the Apache License, Version 2.0 * which is available at -2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 * * Contributors: * ADLINK zenoh team, <> *) open Apero open Lwt.Infix open Zenoh_types type zid = string type feid = string type beid = string type stid = string type sid = string type subid = Zenoh_net.sub type listener_t = (Path.t * change) list -> unit Lwt.t type eval_callback_t = Path.t -> properties -> Value.t Lwt.t type transcoding_fallback = Fail | Drop | Keep module EvalMap = Map.Make (Path) module RegisteredPath = struct type t = { path : Path.t ; pub : Zenoh_net.pub } let put ?quorum value t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: PUT (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_put t.pub value let update ?quorum value t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: UPDATE (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_update t.pub value let remove ?quorum t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: REMOVE (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_remove t.pub end module Workspace = struct type t = { path: Path.t ; zns : Zenoh_net.t ; evals: Zenoh_net.eval EvalMap.t Guard.t } let absolute_path path t = if Path.is_relative path then Path.add_prefix ~prefix:t.path path else path let absolute_selector selector t = if Selector.is_relative selector then Selector.add_prefix ~prefix:t.path selector else selector let register_path path t = let path = absolute_path path t in let%lwt pub = Zenoh_net.publish t.zns (Path.to_string path) in let (r:RegisteredPath.t) = { path; pub } in Lwt.return r let get ?quorum ?encoding ?fallback selector t = ignore quorum; ignore encoding; ignore fallback; let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: GET on %s" (Selector.to_string selector)); Zenoh_netutils.query_values t.zns selector let sget ?quorum ?encoding ?fallback selector t = ignore quorum; ignore encoding; ignore fallback; let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: GET on %s" (Selector.to_string selector)); Zenoh_netutils.squery_values t.zns selector let put ?quorum path value t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: PUT on %s : %s" (Path.to_string path) (Value.to_string value)); Zenoh_netutils.write_put t.zns path value let update ?quorum path value t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: UPDATE on %s" (Path.to_string path)); Zenoh_netutils.write_update t.zns path value let remove ?quorum path t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: REMOVE on %s" (Path.to_string path)); Zenoh_netutils.write_remove t.zns path let subscribe ?listener selector t = let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: SUB on %s" (Selector.to_string selector)); let listener = match listener with | Some l -> Some (fun path changes -> List.map (fun change -> (path, change)) changes |> l) | None -> None in Zenoh_netutils.subscribe t.zns ?listener selector let unsubscribe subid t = Logs.debug (fun m -> m "[Zapi]: UNSUB"); Zenoh_netutils.unsubscribe t.zns subid let register_eval path (eval_callback:eval_callback_t) t = let path = absolute_path path t in let zpath = Path.to_string path in Logs.debug (fun m -> m "[Zapi]: REG_EVAL %s" zpath); let on_query resname predicate = Logs.debug (fun m -> m "[Zapi]: Handling remote Zenoh query on eval '%s' for '%s?%s'" zpath resname predicate); let s = Selector.of_string ((Path.to_string path)^"?"^predicate) in let props = Option.map (Selector.properties s) Properties.of_string in eval_callback path (Option.get_or_default props Properties.empty) >|= fun value -> let encoding = Some(Zenoh_netutils.encoding_to_flag value) in let data_info = { Ztypes.empty_data_info with encoding; ts=None } in let buf = Zenoh_netutils.encode_value value in [(zpath, buf, data_info)] in Guard.guarded t.evals @@ fun evals -> let%lwt () = match EvalMap.find_opt path evals with | Some eval -> Zenoh_net.unevaluate t.zns eval | None -> Lwt.return_unit in let%lwt eval = Zenoh_net.evaluate t.zns zpath on_query in Guard.return () (EvalMap.add path eval evals) let unregister_eval path t = let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: UNREG_EVAL %s" (Path.to_string path)); Guard.guarded t.evals @@ fun evals -> let%lwt () = match EvalMap.find_opt path evals with | Some eval -> Zenoh_net.unevaluate t.zns eval | None -> Lwt.return_unit in Guard.return () (EvalMap.remove path evals) end module Admin = struct type t = { admin : Workspace.t ; zid : zid } let properties_of_value v = match v with | Value.PropertiesValue p -> p | _ -> Properties.singleton "value" (Value.to_string v) let add_backend ?zid beid props t = let zid = match zid with | Some id -> id | None -> t.zid in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.put ~quorum:1 (Path.of_string path) (Value.PropertiesValue props) t.admin let get_backends ?zid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*" zid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= List.map (fun (p, v) -> let beid = Astring.with_range ~first:(String.length sel-1) (Path.to_string p) in let prop = properties_of_value v in (beid, prop)) let get_backend ?zid beid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (_,v) -> properties_of_value v)) let remove_backend ?zid beid t = let zid = match zid with | Some id -> id | None -> t.zid in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.remove ~quorum:1 (Path.of_string path) t.admin let add_storage ?zid stid ?backend props t = let zid = match zid with | Some id -> id | None -> t.zid in let beid = Option.get_or_default backend "auto" in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s/storage/%s" zid beid stid in Workspace.put ~quorum:1 (Path.of_string path) (Value.PropertiesValue props) t.admin let get_storages ?zid ?backend t = let zid = match zid with | Some id -> id | None -> t.zid in let beid = Option.get_or_default backend "*" in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s/storage/*" zid beid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= List.map (fun (p, v) -> let path = Path.to_string p in let last_slash_idx = Astring.find ~rev:true (fun c -> c = '/') path |> Option.get in let stoid = Astring.with_range ~first:(last_slash_idx+1) path in let prop = properties_of_value v in (stoid, prop)) let get_storage ?zid stid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*/storage/%s" zid stid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (_,v) -> properties_of_value v)) let remove_storage ?zid stid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*/storage/%s" zid stid in let path = Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (p,_) -> p)) in match%lwt path with | Some p -> Workspace.remove ~quorum:1 p t.admin | None -> Lwt.return_unit end module Infix = struct let (~//) = Path.of_string let (~/*) = Selector.of_string let (~$) s = Value.of_string s Value.STRING |> Result.get end type t = { zns : Zenoh_net.t ; zid : string ; properties : properties } let login endpoint properties = let%lwt zns = Zenoh_net.zopen endpoint in let zinfo = Zenoh_net.info zns in match Properties.get "peer_pid" zinfo with | Some zid -> Lwt.return { zns; zid=zid; properties; } | None -> raise @@ Zenoh_common_errors.YException (`InternalError (`Msg ("Connected zenohd doesn't provide the property 'peer_pid'"))) let logout t = ignore t; (* TODO: explicit close session... unsubscribe? unstore? *) Lwt.return_unit let get_id t = t.zid let workspace path t : Workspace.t Lwt.t = TODO in sync with : register path as a resource and use resource_id + relative_path in workspace let w : Workspace.t = { path ; zns = t.zns ; evals = Guard.create @@ EvalMap.empty } in Lwt.return w let admin t : Admin.t Lwt.t = let%lwt w = workspace (Path.of_string "/@/") t in let a : Admin.t = { admin=w; zid=t.zid } in Lwt.return a
null
https://raw.githubusercontent.com/atolab/zenoh/32e311aae6be93c001fd725b4d918b2fb4e9713d/src/zenoh-ocaml/zenoh_api.ml
ocaml
TODO: explicit close session... unsubscribe? unstore?
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0 , or the Apache License , Version 2.0 * which is available at -2.0 . * * SPDX - License - Identifier : EPL-2.0 OR Apache-2.0 * * Contributors : * team , < > * Copyright (c) 2017, 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0, or the Apache License, Version 2.0 * which is available at -2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 * * Contributors: * ADLINK zenoh team, <> *) open Apero open Lwt.Infix open Zenoh_types type zid = string type feid = string type beid = string type stid = string type sid = string type subid = Zenoh_net.sub type listener_t = (Path.t * change) list -> unit Lwt.t type eval_callback_t = Path.t -> properties -> Value.t Lwt.t type transcoding_fallback = Fail | Drop | Keep module EvalMap = Map.Make (Path) module RegisteredPath = struct type t = { path : Path.t ; pub : Zenoh_net.pub } let put ?quorum value t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: PUT (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_put t.pub value let update ?quorum value t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: UPDATE (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_update t.pub value let remove ?quorum t = ignore quorum; Logs.debug (fun m -> m "[Zapi]: REMOVE (stream) on %s" (Path.to_string t.path)); Zenoh_netutils.stream_remove t.pub end module Workspace = struct type t = { path: Path.t ; zns : Zenoh_net.t ; evals: Zenoh_net.eval EvalMap.t Guard.t } let absolute_path path t = if Path.is_relative path then Path.add_prefix ~prefix:t.path path else path let absolute_selector selector t = if Selector.is_relative selector then Selector.add_prefix ~prefix:t.path selector else selector let register_path path t = let path = absolute_path path t in let%lwt pub = Zenoh_net.publish t.zns (Path.to_string path) in let (r:RegisteredPath.t) = { path; pub } in Lwt.return r let get ?quorum ?encoding ?fallback selector t = ignore quorum; ignore encoding; ignore fallback; let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: GET on %s" (Selector.to_string selector)); Zenoh_netutils.query_values t.zns selector let sget ?quorum ?encoding ?fallback selector t = ignore quorum; ignore encoding; ignore fallback; let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: GET on %s" (Selector.to_string selector)); Zenoh_netutils.squery_values t.zns selector let put ?quorum path value t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: PUT on %s : %s" (Path.to_string path) (Value.to_string value)); Zenoh_netutils.write_put t.zns path value let update ?quorum path value t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: UPDATE on %s" (Path.to_string path)); Zenoh_netutils.write_update t.zns path value let remove ?quorum path t = ignore quorum; let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: REMOVE on %s" (Path.to_string path)); Zenoh_netutils.write_remove t.zns path let subscribe ?listener selector t = let selector = absolute_selector selector t in Logs.debug (fun m -> m "[Zapi]: SUB on %s" (Selector.to_string selector)); let listener = match listener with | Some l -> Some (fun path changes -> List.map (fun change -> (path, change)) changes |> l) | None -> None in Zenoh_netutils.subscribe t.zns ?listener selector let unsubscribe subid t = Logs.debug (fun m -> m "[Zapi]: UNSUB"); Zenoh_netutils.unsubscribe t.zns subid let register_eval path (eval_callback:eval_callback_t) t = let path = absolute_path path t in let zpath = Path.to_string path in Logs.debug (fun m -> m "[Zapi]: REG_EVAL %s" zpath); let on_query resname predicate = Logs.debug (fun m -> m "[Zapi]: Handling remote Zenoh query on eval '%s' for '%s?%s'" zpath resname predicate); let s = Selector.of_string ((Path.to_string path)^"?"^predicate) in let props = Option.map (Selector.properties s) Properties.of_string in eval_callback path (Option.get_or_default props Properties.empty) >|= fun value -> let encoding = Some(Zenoh_netutils.encoding_to_flag value) in let data_info = { Ztypes.empty_data_info with encoding; ts=None } in let buf = Zenoh_netutils.encode_value value in [(zpath, buf, data_info)] in Guard.guarded t.evals @@ fun evals -> let%lwt () = match EvalMap.find_opt path evals with | Some eval -> Zenoh_net.unevaluate t.zns eval | None -> Lwt.return_unit in let%lwt eval = Zenoh_net.evaluate t.zns zpath on_query in Guard.return () (EvalMap.add path eval evals) let unregister_eval path t = let path = absolute_path path t in Logs.debug (fun m -> m "[Zapi]: UNREG_EVAL %s" (Path.to_string path)); Guard.guarded t.evals @@ fun evals -> let%lwt () = match EvalMap.find_opt path evals with | Some eval -> Zenoh_net.unevaluate t.zns eval | None -> Lwt.return_unit in Guard.return () (EvalMap.remove path evals) end module Admin = struct type t = { admin : Workspace.t ; zid : zid } let properties_of_value v = match v with | Value.PropertiesValue p -> p | _ -> Properties.singleton "value" (Value.to_string v) let add_backend ?zid beid props t = let zid = match zid with | Some id -> id | None -> t.zid in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.put ~quorum:1 (Path.of_string path) (Value.PropertiesValue props) t.admin let get_backends ?zid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*" zid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= List.map (fun (p, v) -> let beid = Astring.with_range ~first:(String.length sel-1) (Path.to_string p) in let prop = properties_of_value v in (beid, prop)) let get_backend ?zid beid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (_,v) -> properties_of_value v)) let remove_backend ?zid beid t = let zid = match zid with | Some id -> id | None -> t.zid in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s" zid beid in Workspace.remove ~quorum:1 (Path.of_string path) t.admin let add_storage ?zid stid ?backend props t = let zid = match zid with | Some id -> id | None -> t.zid in let beid = Option.get_or_default backend "auto" in let path = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s/storage/%s" zid beid stid in Workspace.put ~quorum:1 (Path.of_string path) (Value.PropertiesValue props) t.admin let get_storages ?zid ?backend t = let zid = match zid with | Some id -> id | None -> t.zid in let beid = Option.get_or_default backend "*" in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/%s/storage/*" zid beid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= List.map (fun (p, v) -> let path = Path.to_string p in let last_slash_idx = Astring.find ~rev:true (fun c -> c = '/') path |> Option.get in let stoid = Astring.with_range ~first:(last_slash_idx+1) path in let prop = properties_of_value v in (stoid, prop)) let get_storage ?zid stid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*/storage/%s" zid stid in Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (_,v) -> properties_of_value v)) let remove_storage ?zid stid t = let zid = match zid with | Some id -> id | None -> t.zid in let sel = Printf.sprintf "/@/router/%s/plugin/storages/backend/*/storage/%s" zid stid in let path = Workspace.get ~quorum:1 (Selector.of_string sel) t.admin >|= (fun l -> Option.map (List.nth_opt l 0) (fun (p,_) -> p)) in match%lwt path with | Some p -> Workspace.remove ~quorum:1 p t.admin | None -> Lwt.return_unit end module Infix = struct let (~//) = Path.of_string let (~/*) = Selector.of_string let (~$) s = Value.of_string s Value.STRING |> Result.get end type t = { zns : Zenoh_net.t ; zid : string ; properties : properties } let login endpoint properties = let%lwt zns = Zenoh_net.zopen endpoint in let zinfo = Zenoh_net.info zns in match Properties.get "peer_pid" zinfo with | Some zid -> Lwt.return { zns; zid=zid; properties; } | None -> raise @@ Zenoh_common_errors.YException (`InternalError (`Msg ("Connected zenohd doesn't provide the property 'peer_pid'"))) let logout t = ignore t; Lwt.return_unit let get_id t = t.zid let workspace path t : Workspace.t Lwt.t = TODO in sync with : register path as a resource and use resource_id + relative_path in workspace let w : Workspace.t = { path ; zns = t.zns ; evals = Guard.create @@ EvalMap.empty } in Lwt.return w let admin t : Admin.t Lwt.t = let%lwt w = workspace (Path.of_string "/@/") t in let a : Admin.t = { admin=w; zid=t.zid } in Lwt.return a
b0640b5548d2335ded02c4de7d4925caa30b5f5b4a0a62fa31194f3d7283590e
gedge-platform/gedge-platform
Elixir.RabbitMQ.CLI.Ctl.Commands.DeleteShovelCommand.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% -module('Elixir.RabbitMQ.CLI.Ctl.Commands.DeleteShovelCommand'). -include("rabbit_shovel.hrl"). -behaviour('Elixir.RabbitMQ.CLI.CommandBehaviour'). -ignore_xref([ {'Elixir.RabbitMQ.CLI.DefaultOutput', output, 1}, {'Elixir.RabbitMQ.CLI.Core.Helpers', cli_acting_user, 0} ]). -export([ usage/0, usage_additional/0, usage_doc_guides/0, validate/2, merge_defaults/2, banner/2, run/2, switches/0, aliases/0, output/2, help_section/0, description/0 ]). %%---------------------------------------------------------------------------- %% Callbacks %%---------------------------------------------------------------------------- usage() -> <<"delete_shovel [--vhost <vhost>] <name>">>. usage_additional() -> [ {<<"<name>">>, <<"Shovel to delete">>} ]. usage_doc_guides() -> [?SHOVEL_GUIDE_URL]. description() -> <<"Deletes a Shovel">>. help_section() -> {plugin, shovel}. validate([], _Opts) -> {validation_failure, not_enough_args}; validate([_, _ | _], _Opts) -> {validation_failure, too_many_args}; validate([_], _Opts) -> ok. merge_defaults(A, Opts) -> {A, maps:merge(#{vhost => <<"/">>}, Opts)}. banner([Name], #{vhost := VHost}) -> erlang:list_to_binary(io_lib:format("Deleting shovel ~s in vhost ~s", [Name, VHost])). run([Name], #{node := Node, vhost := VHost}) -> ActingUser = 'Elixir.RabbitMQ.CLI.Core.Helpers':cli_acting_user(), case rabbit_misc:rpc_call(Node, rabbit_shovel_util, delete_shovel, [VHost, Name, ActingUser]) of {badrpc, _} = Error -> Error; {error, not_found} -> ErrMsg = rabbit_misc:format("Shovel with the given name was not found " "on the target node '~s' and / or virtual host '~s'", [Node, VHost]), {error, rabbit_data_coercion:to_binary(ErrMsg)}; ok -> ok end. switches() -> []. aliases() -> []. output(E, _Opts) -> 'Elixir.RabbitMQ.CLI.DefaultOutput':output(E).
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_shovel/src/Elixir.RabbitMQ.CLI.Ctl.Commands.DeleteShovelCommand.erl
erlang
---------------------------------------------------------------------------- Callbacks ----------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . -module('Elixir.RabbitMQ.CLI.Ctl.Commands.DeleteShovelCommand'). -include("rabbit_shovel.hrl"). -behaviour('Elixir.RabbitMQ.CLI.CommandBehaviour'). -ignore_xref([ {'Elixir.RabbitMQ.CLI.DefaultOutput', output, 1}, {'Elixir.RabbitMQ.CLI.Core.Helpers', cli_acting_user, 0} ]). -export([ usage/0, usage_additional/0, usage_doc_guides/0, validate/2, merge_defaults/2, banner/2, run/2, switches/0, aliases/0, output/2, help_section/0, description/0 ]). usage() -> <<"delete_shovel [--vhost <vhost>] <name>">>. usage_additional() -> [ {<<"<name>">>, <<"Shovel to delete">>} ]. usage_doc_guides() -> [?SHOVEL_GUIDE_URL]. description() -> <<"Deletes a Shovel">>. help_section() -> {plugin, shovel}. validate([], _Opts) -> {validation_failure, not_enough_args}; validate([_, _ | _], _Opts) -> {validation_failure, too_many_args}; validate([_], _Opts) -> ok. merge_defaults(A, Opts) -> {A, maps:merge(#{vhost => <<"/">>}, Opts)}. banner([Name], #{vhost := VHost}) -> erlang:list_to_binary(io_lib:format("Deleting shovel ~s in vhost ~s", [Name, VHost])). run([Name], #{node := Node, vhost := VHost}) -> ActingUser = 'Elixir.RabbitMQ.CLI.Core.Helpers':cli_acting_user(), case rabbit_misc:rpc_call(Node, rabbit_shovel_util, delete_shovel, [VHost, Name, ActingUser]) of {badrpc, _} = Error -> Error; {error, not_found} -> ErrMsg = rabbit_misc:format("Shovel with the given name was not found " "on the target node '~s' and / or virtual host '~s'", [Node, VHost]), {error, rabbit_data_coercion:to_binary(ErrMsg)}; ok -> ok end. switches() -> []. aliases() -> []. output(E, _Opts) -> 'Elixir.RabbitMQ.CLI.DefaultOutput':output(E).
2fdbc30df9816389a8c38044b2293e84605ee192734e1fb02bcd71f61464e4d3
folivetti/ITEA
Eval.hs
# LANGUAGE FlexibleContexts # | Module : IT.Eval Description : Evaluation function for IT expressions . Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definition of functions pertaining to the conversion and evaluation of an IT - expression . TODO : move interval evaluation to IT.Eval . Interval Module : IT.Eval Description : Evaluation function for IT expressions. Copyright : (c) Fabricio Olivetti de Franca, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definition of functions pertaining to the conversion and evaluation of an IT-expression. TODO: move interval evaluation to IT.Eval.Interval -} {-# OPTIONS_GHC -Wno-unused-matches #-} module IT.Eval where import qualified Data.Vector as V import qualified Numeric.LinearAlgebra as LA import qualified Data.IntMap.Strict as M import Numeric.Interval hiding (null) import qualified Numeric.Interval as I import Data.Bifunctor import IT import IT.Algorithms -- | log(x+1) log1p :: Floating a => a -> a log1p x = log (x+1) -- * Evaluation of the Transformation functions -- It supports any type that is an instance of Floating. -- | Evaluate the transformation function 'f' in a data point 'x'. transform :: Floating a => Transformation -> a -> a transform Id = id transform Sin = sin transform Cos = cos transform Tan = tan transform Tanh = tanh transform Sqrt = sqrt transform SqrtAbs = sqrt.abs transform Exp = exp transform Log = log transform Log1p = log1p -- | Evaluate the derivative of a transformation function. derivative :: Floating a => Transformation -> a -> a derivative Id = const 1 derivative Sin = cos derivative Cos = negate.sin derivative Tan = recip . (**2.0) . cos derivative Tanh = (1-) . (**2.0) . tanh derivative Sqrt = recip . (2*) . sqrt derivative SqrtAbs = \x -> x / (2* abs x**1.5) derivative Exp = exp derivative Log = recip derivative Log1p = recip . (+1) | Evaluate the second derivative of the transformation function . sndDerivative :: Floating a => Transformation -> a -> a sndDerivative Id = const 0 sndDerivative Sin = negate.sin sndDerivative Cos = negate.cos sndDerivative Tan = \x -> 2 * tan x * cos x ** (-2.0) sndDerivative Tanh = \x -> (-2) * tanh x * (1 - tanh x ** 2.0) sndDerivative Sqrt = negate . recip . (*4) . sqrt . (**3.0) assuming dirac(x ) = 0 sndDerivative Exp = exp sndDerivative Log = \x -> -(1/x**2) sndDerivative Log1p = negate . recip . (**2.0) . (+1) -- | Evaluates the interaction 'ks' in the dataset 'xss' -- -- It folds the map of exponents with the key, retrieve the corresponding column, calculates x_i^k_i and multiplies to the accumulator . -- It return a column vector. polynomial :: Dataset Double -> Interaction -> Column Double polynomial xss ks | V.length xss == 0 = LA.fromList [] | otherwise = M.foldrWithKey monoProduct 1 ks where monoProduct ix k ps = ps * (xss V.! ix) ^^ k -- | Evaluates the interval of the interaction w.r.t. the domains of the variables. -- -- In this case it is faster to fold through the list of domains and checking whether we -- have a nonzero strength. polynomialInterval :: [Interval Double] -> Interaction -> Interval Double polynomialInterval domains ks = foldr monoProduct (singleton 1) $ zip [0..] domains where monoProduct (ix, x) img | ix `M.member` ks = img * x ^^ get ix | otherwise = img get ix = fromIntegral (ks M.! ix) -- | Evaluates a term by applying the transformation function to -- the result of the interaction. evalTerm :: Dataset Double -> Term -> Column Double evalTerm xss (Term t ks) = transform t (polynomial xss ks) -- | Evaluates the term on the interval domains. evalTermInterval :: [Interval Double] -> Term -> Interval Double evalTermInterval domains (Term t ks) | inter == empty = empty | otherwise = protected (transform t) inter where inter = polynomialInterval domains ks -- | The partial derivative of a term w.r.t. the variable ix is: -- -- If ix exists in the interaction, the derivative is: -- derivative t (polynomial xss ks) * (polynomial xss ks') ks ' is the same as ks but with the strength of ix decremented by one Otherwise it is equal to 0 -- -- Given the expression: w1 t1(p1(x)) + w2 t2(p2(x)) -- The derivative is: w1 t1'(p1(x))p1'(x) + w2 t2'(p2(x))p2'(x) evalTermDiff :: Int -> Dataset Double -> Term -> Column Double evalTermDiff ix xss (Term t ks) | M.member ix ks = ki * it * p' | otherwise = LA.fromList $ replicate n 0 where ki = fromIntegral $ ks M.! ix p = polynomial xss ks p' = polynomial xss (M.update dec ix ks) t' = derivative t it = LA.cmap t' p n = LA.size (xss V.! 0) dec 1 = Nothing dec k = Just (k-1) | The second partial derivative of a term w.r.t . the variables ix and iy is : -- given ) as the interaction function , ) the transformation function , f'(x)|i the first derivative of a function given i and f''(x ) the second derivative . -- If iy exists in ) and ix exists in p'(x)|iy , the derivative is : -- -- kx*ky*t''(x)*p'(x)|ix * p'(x)|iy + kxy*t'(x)p''(x) -- -- where kx, ky are the original exponents of variables ix and iy, and kxy is ky * kx ' , with kx ' the exponent of ix on p'(x)|iy -- evalTermSndDiff :: Int -> Int -> Dataset Double -> Term -> Column Double evalTermSndDiff ix iy xss (Term t ks) | M.member ix ks' && M.member iy ks = ki*kj*tp''*px'*py' + kij*tp'*pxy' | otherwise = LA.fromList $ replicate n 0 where ks' = M.update dec iy ks ki = fromIntegral $ ks M.! ix kj = fromIntegral $ ks M.! iy kij = kj * fromIntegral (ks' M.! ix) p = polynomial xss ks px' = polynomial xss (M.update dec ix ks) py' = polynomial xss (M.update dec iy ks) pxy' = polynomial xss (M.update dec ix ks') t' = derivative t t'' = sndDerivative t tp' = LA.cmap t' p tp'' = LA.cmap t'' p n = LA.size (xss V.! 0) dec 1 = Nothing dec k = Just (k-1) -- | Same as 'evalTermDiff' but optimized for intervals. evalTermDiffInterval :: Int -> [Interval Double] -> Term -> Interval Double evalTermDiffInterval ix domains (Term t ks) | M.member ix ks = ki * it * p' | otherwise = singleton 0 where ki = singleton . fromIntegral $ ks M.! ix p = polynomialInterval domains ks p' = polynomialInterval domains (M.update dec ix ks) t' = protected (derivative t) it = t' p dec 1 = Nothing dec k = Just (k-1) -- | Same as 'evalTermSndDiff' but optimized for intervals evalTermSndDiffInterval :: Int -> Int -> [Interval Double] -> Term -> Interval Double evalTermSndDiffInterval ix iy domains (Term t ks) | M.member ix ks' && M.member iy ks = ki*kj*tp''*px'*py' + kij*tp'*pxy' | otherwise = singleton 0 where ks' = M.update dec iy ks ki = singleton . fromIntegral $ ks M.! ix kj = singleton . fromIntegral $ ks M.! iy kij = kj * singleton (fromIntegral (ks' M.! ix)) p = polynomialInterval domains ks px' = polynomialInterval domains (M.update dec ix ks) py' = polynomialInterval domains (M.update dec iy ks) pxy' = polynomialInterval domains (M.update dec ix $ M.update dec iy ks) t' = protected (derivative t) t'' = protected (sndDerivative t) tp' = t' p tp'' = t'' p dec 1 = Nothing dec k = Just (k-1) -- | evaluates an expression by evaluating the terms into a list -- applying the weight and summing the results. evalGeneric :: (Dataset Double -> Term -> Column Double) -> Dataset Double -> Expr -> [Double] -> Column Double evalGeneric f xss terms ws = b + sum weightedTerms where weightedTerms = zipWith multWeight ws (map (f xss') terms) multWeight w = LA.cmap (w*) b = V.head xss xss' = V.tail xss -- | Evaluating an expression is simply applying 'evalTerm' evalExpr :: Dataset Double -> Expr -> [Double] -> Column Double evalExpr = evalGeneric evalTerm -- | Evaluating the derivative is applying 'evalTermDiff' in the expression evalDiff :: Int -> Dataset Double -> Expr -> [Double] -> Column Double evalDiff ix = evalGeneric (evalTermDiff ix) | Evaluating the second derivative is applying ' evalTermSndDiff ' in the expression evalSndDiff :: Int -> Int -> Dataset Double -> Expr -> [Double] -> Column Double evalSndDiff ix iy = evalGeneric (evalTermSndDiff ix iy) -- | Returns the estimate of the image of the funcion with Interval Arithmetic -- -- this requires a different implementation from `evalGeneric` evalImageGeneric :: ([Interval Double] -> Term -> Interval Double) -> [Interval Double]-> Expr -> [Double] -> Interval Double evalImageGeneric f domains terms ws = sum weightedTerms where weightedTerms = zipWith (*) (map singleton ws) (map (f domains) terms) evalImage :: [Interval Double] -> Expr -> [Double] -> Interval Double evalImage = evalImageGeneric evalTermInterval evalDiffImage :: Int -> [Interval Double] -> Expr -> [Double] -> Interval Double evalDiffImage ix = evalImageGeneric (evalTermDiffInterval ix) evalSndDiffImage :: Int -> Int -> [Interval Double] -> Expr -> [Double] -> Interval Double evalSndDiffImage ix iy = evalImageGeneric (evalTermSndDiffInterval ix iy) | A value is invalid if it 's wether NaN or Infinite isInvalid :: Double -> Bool isInvalid x = isNaN x || isInfinite x || abs x >= 1e150 -- | a set of points is valid if none of its values are invalid and the maximum abosolute value is below 1e150 ( to avoid overflow ) isValid :: [Double] -> Bool isValid = all (\x -> not (isNaN x) && not (isInfinite x) && abs x < 1e150) -- not (any isInvalid xs) -- | evaluate an expression to a set of samples -- ( 1 LA.||| ) adds a bias dimension exprToMatrix :: Dataset Double -> Expr -> LA.Matrix Double exprToMatrix xss = LA.fromColumns . (V.head xss :) . map (evalTerm (V.tail xss)) -- | Clean the expression by removing the invalid terms -- TODO: move to IT.Regression cleanExpr :: Dataset Double -> [Interval Double] -> Expr -> (Expr, LA.Matrix Double) cleanExpr xss domains = second (LA.fromColumns . (b:)) . foldr p ([], []) where xss' = V.tail xss b = V.head xss p t (ts, cols) = if isInvalidInterval (evalTermInterval domains t) then (ts, cols) else (t:ts, evalTerm xss' t : cols) p ' t ( ts , cols ) = let col = evalTerm xss ' t in if VV.all ( not.isInvalid ) col then ( t : ts , col : cols ) else ( ts , cols ) p' t (ts, cols) = let col = evalTerm xss' t in if VV.all (not.isInvalid) col then (t:ts, col:cols) else (ts, cols) -} isInvalidInterval :: Interval Double -> Bool isInvalidInterval ys = I.null ys || isInfinite ys1 || isInfinite ys2 || ys2 < ys1 || abs ys1 >= 1e150 || abs ys2 >= 1e150 || isNaN ys1 || isNaN ys2 || width ys < 1e-10 where ys1 = inf ys ys2 = sup ys | Checks if the fitness of a solution is not nor NaN. notInfNan :: Solution -> Bool notInfNan s = not (isInfinite f || isNaN f) where f = head $ _fit s | definition of an interval evaluated to NaN nanInterval :: RealFloat a => Interval a nanInterval = singleton (0/0) -- | Check if any bound of the interval is infinity hasInf :: RealFloat a => Interval a -> Bool hasInf x = any isInfinite [inf x, sup x] -- | Creates a protected function to avoid throwing exceptions protected :: RealFloat a => (Interval a -> Interval a) -> Interval a -> Interval a protected f x | I.null y = y | hasInf x = nanInterval | sup y < inf y = sup y ... inf y | otherwise = y where y = f x
null
https://raw.githubusercontent.com/folivetti/ITEA/04497e282f7b20f3c0f465bf3b2b933fe291f859/src/IT/Eval.hs
haskell
# OPTIONS_GHC -Wno-unused-matches # | log(x+1) * Evaluation of the Transformation functions It supports any type that is an instance of Floating. | Evaluate the transformation function 'f' in a data point 'x'. | Evaluate the derivative of a transformation function. | Evaluates the interaction 'ks' in the dataset 'xss' It folds the map of exponents with the key, retrieve the corresponding column, It return a column vector. | Evaluates the interval of the interaction w.r.t. the domains of the variables. In this case it is faster to fold through the list of domains and checking whether we have a nonzero strength. | Evaluates a term by applying the transformation function to the result of the interaction. | Evaluates the term on the interval domains. | The partial derivative of a term w.r.t. the variable ix is: If ix exists in the interaction, the derivative is: derivative t (polynomial xss ks) * (polynomial xss ks') Given the expression: w1 t1(p1(x)) + w2 t2(p2(x)) The derivative is: w1 t1'(p1(x))p1'(x) + w2 t2'(p2(x))p2'(x) kx*ky*t''(x)*p'(x)|ix * p'(x)|iy + kxy*t'(x)p''(x) where kx, ky are the original exponents of variables ix and iy, | Same as 'evalTermDiff' but optimized for intervals. | Same as 'evalTermSndDiff' but optimized for intervals | evaluates an expression by evaluating the terms into a list applying the weight and summing the results. | Evaluating an expression is simply applying 'evalTerm' | Evaluating the derivative is applying 'evalTermDiff' in the expression | Returns the estimate of the image of the funcion with Interval Arithmetic this requires a different implementation from `evalGeneric` | a set of points is valid if none of its values are invalid and not (any isInvalid xs) | evaluate an expression to a set of samples | Clean the expression by removing the invalid terms TODO: move to IT.Regression | Check if any bound of the interval is infinity | Creates a protected function to avoid throwing exceptions
# LANGUAGE FlexibleContexts # | Module : IT.Eval Description : Evaluation function for IT expressions . Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definition of functions pertaining to the conversion and evaluation of an IT - expression . TODO : move interval evaluation to IT.Eval . Interval Module : IT.Eval Description : Evaluation function for IT expressions. Copyright : (c) Fabricio Olivetti de Franca, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definition of functions pertaining to the conversion and evaluation of an IT-expression. TODO: move interval evaluation to IT.Eval.Interval -} module IT.Eval where import qualified Data.Vector as V import qualified Numeric.LinearAlgebra as LA import qualified Data.IntMap.Strict as M import Numeric.Interval hiding (null) import qualified Numeric.Interval as I import Data.Bifunctor import IT import IT.Algorithms log1p :: Floating a => a -> a log1p x = log (x+1) transform :: Floating a => Transformation -> a -> a transform Id = id transform Sin = sin transform Cos = cos transform Tan = tan transform Tanh = tanh transform Sqrt = sqrt transform SqrtAbs = sqrt.abs transform Exp = exp transform Log = log transform Log1p = log1p derivative :: Floating a => Transformation -> a -> a derivative Id = const 1 derivative Sin = cos derivative Cos = negate.sin derivative Tan = recip . (**2.0) . cos derivative Tanh = (1-) . (**2.0) . tanh derivative Sqrt = recip . (2*) . sqrt derivative SqrtAbs = \x -> x / (2* abs x**1.5) derivative Exp = exp derivative Log = recip derivative Log1p = recip . (+1) | Evaluate the second derivative of the transformation function . sndDerivative :: Floating a => Transformation -> a -> a sndDerivative Id = const 0 sndDerivative Sin = negate.sin sndDerivative Cos = negate.cos sndDerivative Tan = \x -> 2 * tan x * cos x ** (-2.0) sndDerivative Tanh = \x -> (-2) * tanh x * (1 - tanh x ** 2.0) sndDerivative Sqrt = negate . recip . (*4) . sqrt . (**3.0) assuming dirac(x ) = 0 sndDerivative Exp = exp sndDerivative Log = \x -> -(1/x**2) sndDerivative Log1p = negate . recip . (**2.0) . (+1) calculates x_i^k_i and multiplies to the accumulator . polynomial :: Dataset Double -> Interaction -> Column Double polynomial xss ks | V.length xss == 0 = LA.fromList [] | otherwise = M.foldrWithKey monoProduct 1 ks where monoProduct ix k ps = ps * (xss V.! ix) ^^ k polynomialInterval :: [Interval Double] -> Interaction -> Interval Double polynomialInterval domains ks = foldr monoProduct (singleton 1) $ zip [0..] domains where monoProduct (ix, x) img | ix `M.member` ks = img * x ^^ get ix | otherwise = img get ix = fromIntegral (ks M.! ix) evalTerm :: Dataset Double -> Term -> Column Double evalTerm xss (Term t ks) = transform t (polynomial xss ks) evalTermInterval :: [Interval Double] -> Term -> Interval Double evalTermInterval domains (Term t ks) | inter == empty = empty | otherwise = protected (transform t) inter where inter = polynomialInterval domains ks ks ' is the same as ks but with the strength of ix decremented by one Otherwise it is equal to 0 evalTermDiff :: Int -> Dataset Double -> Term -> Column Double evalTermDiff ix xss (Term t ks) | M.member ix ks = ki * it * p' | otherwise = LA.fromList $ replicate n 0 where ki = fromIntegral $ ks M.! ix p = polynomial xss ks p' = polynomial xss (M.update dec ix ks) t' = derivative t it = LA.cmap t' p n = LA.size (xss V.! 0) dec 1 = Nothing dec k = Just (k-1) | The second partial derivative of a term w.r.t . the variables ix and iy is : given ) as the interaction function , ) the transformation function , f'(x)|i the first derivative of a function given i and f''(x ) the second derivative . If iy exists in ) and ix exists in p'(x)|iy , the derivative is : and kxy is ky * kx ' , with kx ' the exponent of ix on p'(x)|iy evalTermSndDiff :: Int -> Int -> Dataset Double -> Term -> Column Double evalTermSndDiff ix iy xss (Term t ks) | M.member ix ks' && M.member iy ks = ki*kj*tp''*px'*py' + kij*tp'*pxy' | otherwise = LA.fromList $ replicate n 0 where ks' = M.update dec iy ks ki = fromIntegral $ ks M.! ix kj = fromIntegral $ ks M.! iy kij = kj * fromIntegral (ks' M.! ix) p = polynomial xss ks px' = polynomial xss (M.update dec ix ks) py' = polynomial xss (M.update dec iy ks) pxy' = polynomial xss (M.update dec ix ks') t' = derivative t t'' = sndDerivative t tp' = LA.cmap t' p tp'' = LA.cmap t'' p n = LA.size (xss V.! 0) dec 1 = Nothing dec k = Just (k-1) evalTermDiffInterval :: Int -> [Interval Double] -> Term -> Interval Double evalTermDiffInterval ix domains (Term t ks) | M.member ix ks = ki * it * p' | otherwise = singleton 0 where ki = singleton . fromIntegral $ ks M.! ix p = polynomialInterval domains ks p' = polynomialInterval domains (M.update dec ix ks) t' = protected (derivative t) it = t' p dec 1 = Nothing dec k = Just (k-1) evalTermSndDiffInterval :: Int -> Int -> [Interval Double] -> Term -> Interval Double evalTermSndDiffInterval ix iy domains (Term t ks) | M.member ix ks' && M.member iy ks = ki*kj*tp''*px'*py' + kij*tp'*pxy' | otherwise = singleton 0 where ks' = M.update dec iy ks ki = singleton . fromIntegral $ ks M.! ix kj = singleton . fromIntegral $ ks M.! iy kij = kj * singleton (fromIntegral (ks' M.! ix)) p = polynomialInterval domains ks px' = polynomialInterval domains (M.update dec ix ks) py' = polynomialInterval domains (M.update dec iy ks) pxy' = polynomialInterval domains (M.update dec ix $ M.update dec iy ks) t' = protected (derivative t) t'' = protected (sndDerivative t) tp' = t' p tp'' = t'' p dec 1 = Nothing dec k = Just (k-1) evalGeneric :: (Dataset Double -> Term -> Column Double) -> Dataset Double -> Expr -> [Double] -> Column Double evalGeneric f xss terms ws = b + sum weightedTerms where weightedTerms = zipWith multWeight ws (map (f xss') terms) multWeight w = LA.cmap (w*) b = V.head xss xss' = V.tail xss evalExpr :: Dataset Double -> Expr -> [Double] -> Column Double evalExpr = evalGeneric evalTerm evalDiff :: Int -> Dataset Double -> Expr -> [Double] -> Column Double evalDiff ix = evalGeneric (evalTermDiff ix) | Evaluating the second derivative is applying ' evalTermSndDiff ' in the expression evalSndDiff :: Int -> Int -> Dataset Double -> Expr -> [Double] -> Column Double evalSndDiff ix iy = evalGeneric (evalTermSndDiff ix iy) evalImageGeneric :: ([Interval Double] -> Term -> Interval Double) -> [Interval Double]-> Expr -> [Double] -> Interval Double evalImageGeneric f domains terms ws = sum weightedTerms where weightedTerms = zipWith (*) (map singleton ws) (map (f domains) terms) evalImage :: [Interval Double] -> Expr -> [Double] -> Interval Double evalImage = evalImageGeneric evalTermInterval evalDiffImage :: Int -> [Interval Double] -> Expr -> [Double] -> Interval Double evalDiffImage ix = evalImageGeneric (evalTermDiffInterval ix) evalSndDiffImage :: Int -> Int -> [Interval Double] -> Expr -> [Double] -> Interval Double evalSndDiffImage ix iy = evalImageGeneric (evalTermSndDiffInterval ix iy) | A value is invalid if it 's wether NaN or Infinite isInvalid :: Double -> Bool isInvalid x = isNaN x || isInfinite x || abs x >= 1e150 the maximum abosolute value is below 1e150 ( to avoid overflow ) isValid :: [Double] -> Bool isValid = all (\x -> not (isNaN x) && not (isInfinite x) && abs x < 1e150) ( 1 LA.||| ) adds a bias dimension exprToMatrix :: Dataset Double -> Expr -> LA.Matrix Double exprToMatrix xss = LA.fromColumns . (V.head xss :) . map (evalTerm (V.tail xss)) cleanExpr :: Dataset Double -> [Interval Double] -> Expr -> (Expr, LA.Matrix Double) cleanExpr xss domains = second (LA.fromColumns . (b:)) . foldr p ([], []) where xss' = V.tail xss b = V.head xss p t (ts, cols) = if isInvalidInterval (evalTermInterval domains t) then (ts, cols) else (t:ts, evalTerm xss' t : cols) p ' t ( ts , cols ) = let col = evalTerm xss ' t in if VV.all ( not.isInvalid ) col then ( t : ts , col : cols ) else ( ts , cols ) p' t (ts, cols) = let col = evalTerm xss' t in if VV.all (not.isInvalid) col then (t:ts, col:cols) else (ts, cols) -} isInvalidInterval :: Interval Double -> Bool isInvalidInterval ys = I.null ys || isInfinite ys1 || isInfinite ys2 || ys2 < ys1 || abs ys1 >= 1e150 || abs ys2 >= 1e150 || isNaN ys1 || isNaN ys2 || width ys < 1e-10 where ys1 = inf ys ys2 = sup ys | Checks if the fitness of a solution is not nor NaN. notInfNan :: Solution -> Bool notInfNan s = not (isInfinite f || isNaN f) where f = head $ _fit s | definition of an interval evaluated to NaN nanInterval :: RealFloat a => Interval a nanInterval = singleton (0/0) hasInf :: RealFloat a => Interval a -> Bool hasInf x = any isInfinite [inf x, sup x] protected :: RealFloat a => (Interval a -> Interval a) -> Interval a -> Interval a protected f x | I.null y = y | hasInf x = nanInterval | sup y < inf y = sup y ... inf y | otherwise = y where y = f x
4e5cc17ad7688352c35bdaae6f7a8c6d6e7eed0c4ddcc9b5cdfb1736eccca222
abridgewater/nq-clim
event-queue-protocol.lisp
;;; nq - clim / event / event - queue - protocol ;;; The parts of CLIM II 8.1.1 that deal with event queues proper . ;;; (cl:defpackage :nq-clim/event/event-queue-protocol (:use :cl) (:export "SHEET-EVENT-QUEUE" "DISPATCH-EVENT" "QUEUE-EVENT" "HANDLE-EVENT" "EVENT-READ" "EVENT-READ-NO-HANG" "EVENT-PEEK" "EVENT-UNREAD" "EVENT-LISTEN")) (cl:in-package :nq-clim/event/event-queue-protocol) ;; Technically a sheet function, not an event-queue function, but it IS described in CLIM II 8.1.1 , and we do n't have a better place to ;; put it at the moment. (defgeneric sheet-event-queue (sheet)) (defgeneric dispatch-event (client event)) (defgeneric queue-event (client event)) (defgeneric handle-event (client event)) (defgeneric event-read (client)) (defgeneric event-read-no-hang (client)) (defgeneric event-peek (client &optional event-type)) (defgeneric event-unread (client event)) (defgeneric event-listen (client)) EOF
null
https://raw.githubusercontent.com/abridgewater/nq-clim/11d339fd0ac77b6d624fc5537b170294a191a3de/event/event-queue-protocol.lisp
lisp
Technically a sheet function, not an event-queue function, but it put it at the moment.
nq - clim / event / event - queue - protocol The parts of CLIM II 8.1.1 that deal with event queues proper . (cl:defpackage :nq-clim/event/event-queue-protocol (:use :cl) (:export "SHEET-EVENT-QUEUE" "DISPATCH-EVENT" "QUEUE-EVENT" "HANDLE-EVENT" "EVENT-READ" "EVENT-READ-NO-HANG" "EVENT-PEEK" "EVENT-UNREAD" "EVENT-LISTEN")) (cl:in-package :nq-clim/event/event-queue-protocol) IS described in CLIM II 8.1.1 , and we do n't have a better place to (defgeneric sheet-event-queue (sheet)) (defgeneric dispatch-event (client event)) (defgeneric queue-event (client event)) (defgeneric handle-event (client event)) (defgeneric event-read (client)) (defgeneric event-read-no-hang (client)) (defgeneric event-peek (client &optional event-type)) (defgeneric event-unread (client event)) (defgeneric event-listen (client)) EOF
c23c7893d4ed4ab067b3f69c9bd912ae3bad7bf1ac1154527950c26334f38dad
clojure/test.check
check.cljc
Copyright ( c ) , , and contributors . ; All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.test.check (:require [clojure.test.check.generators :as gen] [clojure.test.check.random :as random] [clojure.test.check.results :as results] [clojure.test.check.rose-tree :as rose] [clojure.test.check.impl :refer [get-current-time-millis]])) (declare shrink-loop failure) (defn- make-rng [seed] (if seed [seed (random/make-random seed)] (let [non-nil-seed (get-current-time-millis)] [non-nil-seed (random/make-random non-nil-seed)]))) (defn- complete [property num-trials seed start-time reporter-fn] (let [time-elapsed-ms (- (get-current-time-millis) start-time)] (reporter-fn {:type :complete :property property :result true :pass? true :num-tests num-trials :time-elapsed-ms time-elapsed-ms :seed seed}) {:result true :pass? true :num-tests num-trials :time-elapsed-ms time-elapsed-ms :seed seed})) (defn ^:private legacy-result "Returns a value for the legacy :result key, which has the peculiar property of conflating returned exceptions with thrown exceptions." [result] (if (satisfies? results/Result result) (let [d (results/result-data result)] (if-let [[_ e] (find d :clojure.test.check.properties/error)] #?(:clj e :cljs (if (instance? js/Error e) e (ex-info "Non-Error object thrown in test" {} e))) (results/pass? result))) result)) (defn quick-check "Tests `property` `num-tests` times. Takes several optional keys: `:seed` Can be used to re-run previous tests, as the seed used is returned after a test is run. `:max-size`. can be used to control the 'size' of generated values. The size will start at 0, and grow up to max-size, as the number of tests increases. Generators will use the size parameter to bound their growth. This prevents, for example, generating a five-thousand element vector on the very first test. `:reporter-fn` A callback function that will be called at various points in the test run, with a map like: ;; called after a passing trial {:type :trial :args [...] :num-tests <number of tests run so far> :num-tests-total <total number of tests to be run> :seed 42 :pass? true :property #<...> :result true :result-data {...}} called after the first failing trial {:type :failure :fail [...failing args...] :failing-size 13 :num-tests <tests ran before failure found> :pass? false :property #<...> :result false/exception :result-data {...} :seed 42} It will also be called on :complete, :shrink-step and :shrunk. Many of the keys also appear in the quick-check return value, and are documented below. If the test passes, the return value will be something like: {:num-tests 100, :pass? true, :result true, :seed 1561826505982, :time-elapsed-ms 24} If the test fails, the return value will be something like: {:fail [0], :failed-after-ms 0, :failing-size 0, :num-tests 1, :pass? false, :result false, :result-data nil, :seed 1561826506080, :shrunk {:depth 0, :pass? false, :result false, :result-data nil, :smallest [0], :time-shrinking-ms 0, :total-nodes-visited 0}} The meaning of the individual entries is: :num-tests The total number of trials that was were run, not including shrinking (if applicable) :pass? A boolean indicating whether the test passed or failed :result A legacy entry that is similar to :pass? :seed The seed used for the entire test run; can be used to reproduce a test run by passing it as the :seed option to quick-check :time-elapsed-ms The total time, in milliseconds, of a successful test run :fail The generated values for the first failure; note that this is always a vector, since prop/for-all can have multiple clauses :failed-after-ms The total time, in milliseconds, spent finding the first failing trial :failing-size The value of the size parameter used to generate the first failure :result-data The result data, if any, of the first failing trial (to take advantage of this a property must return an object satisfying the clojure.test.check.results/Result protocol) :shrunk A map of data about the shrinking process; nested keys that appear at the top level have the same meaning; other keys are documented next :shrunk / :depth The depth in the shrink tree that the smallest failing instance was found; this is essentially the idea of how many times the original failure was successfully shrunk :smallest The smallest values found in the shrinking process that still fail the test; this is a vector of the same type as :fail :time-shrinking-ms The total time, in milliseconds, spent shrinking :total-nodes-visited The total number of steps in the shrinking process Examples: (def p (for-all [a gen/nat] (> (* a a) a))) (quick-check 100 p) (quick-check 200 p :seed 42 :max-size 50 :reporter-fn (fn [m] (when (= :failure (:type m)) (println \"Uh oh...\"))))" [num-tests property & {:keys [seed max-size reporter-fn] :or {max-size 200, reporter-fn (constantly nil)}}] (let [[created-seed rng] (make-rng seed) size-seq (gen/make-size-range-seq max-size) start-time (get-current-time-millis)] (loop [so-far 0 size-seq size-seq rstate rng] (if (== so-far num-tests) (complete property num-tests created-seed start-time reporter-fn) (let [[size & rest-size-seq] size-seq [r1 r2] (random/split rstate) result-map-rose (gen/call-gen property r1 size) result-map (rose/root result-map-rose) result (:result result-map) args (:args result-map) so-far (inc so-far)] (if (results/pass? result) (do (reporter-fn {:type :trial :args args :num-tests so-far :num-tests-total num-tests :pass? true :property property :result result :result-data (results/result-data result) :seed seed}) (recur so-far rest-size-seq r2)) (failure property result-map-rose so-far size created-seed start-time reporter-fn))))))) (defn- smallest-shrink [total-nodes-visited depth smallest start-time] (let [{:keys [result]} smallest] {:total-nodes-visited total-nodes-visited :depth depth :pass? false :result (legacy-result result) :result-data (results/result-data result) :time-shrinking-ms (- (get-current-time-millis) start-time) :smallest (:args smallest)})) (defn- shrink-loop "Shrinking a value produces a sequence of smaller values of the same type. Each of these values can then be shrunk. Think of this as a tree. We do a modified depth-first search of the tree: Do a non-exhaustive search for a deeper (than the root) failing example. Additional rules added to depth-first search: * If a node passes the property, you may continue searching at this depth, but not backtrack * If a node fails the property, search its children The value returned is the left-most failing example at the depth where a passing example was found. Calls reporter-fn on every shrink step." [rose-tree reporter-fn] (let [start-time (get-current-time-millis) shrinks-this-depth (rose/children rose-tree)] (loop [nodes shrinks-this-depth current-smallest (rose/root rose-tree) total-nodes-visited 0 depth 0] (if (empty? nodes) (smallest-shrink total-nodes-visited depth current-smallest start-time) (let [;; can't destructure here because that could force evaluation of ( second nodes ) head (first nodes) tail (rest nodes) result (:result (rose/root head)) args (:args (rose/root head)) pass? (results/pass? result) reporter-fn-arg {:type :shrink-step :shrinking {:args args :depth depth :pass? (boolean pass?) :result result :result-data (results/result-data result) :smallest (:args current-smallest) :total-nodes-visited total-nodes-visited}}] (if pass? ;; this node passed the test, so now try testing its right-siblings (do (reporter-fn reporter-fn-arg) (recur tail current-smallest (inc total-nodes-visited) depth)) ;; this node failed the test, so check if it has children, ;; if so, traverse down them. If not, save this as the best example ;; seen now and then look at the right-siblings ;; children (let [new-smallest (rose/root head)] (reporter-fn (assoc-in reporter-fn-arg [:shrinking :smallest] (:args new-smallest))) (if-let [children (seq (rose/children head))] (recur children new-smallest (inc total-nodes-visited) (inc depth)) (recur tail new-smallest (inc total-nodes-visited) depth))))))))) (defn- failure [property failing-rose-tree trial-number size seed start-time reporter-fn] (let [failed-after-ms (- (get-current-time-millis) start-time) root (rose/root failing-rose-tree) result (:result root) failure-data {:fail (:args root) :failing-size size :num-tests trial-number :pass? false :property property :result (legacy-result result) :result-data (results/result-data result) :failed-after-ms failed-after-ms :seed seed}] (reporter-fn (assoc failure-data :type :failure)) (let [shrunk (shrink-loop failing-rose-tree #(reporter-fn (merge failure-data %)))] (reporter-fn (assoc failure-data :type :shrunk :shrunk shrunk)) (-> failure-data (dissoc :property) (assoc :shrunk shrunk)))))
null
https://raw.githubusercontent.com/clojure/test.check/c05034f911fa140913958b79aa51017d3f2f4426/src/main/clojure/clojure/test/check.cljc
clojure
All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-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. called after a passing trial can be used to reproduce note that this is nested keys that other keys are this is essentially the idea of how many times the this is a vector of the same type as :fail can't destructure here because that could force this node passed the test, so now try testing its right-siblings this node failed the test, so check if it has children, if so, traverse down them. If not, save this as the best example seen now and then look at the right-siblings children
Copyright ( c ) , , and contributors . (ns clojure.test.check (:require [clojure.test.check.generators :as gen] [clojure.test.check.random :as random] [clojure.test.check.results :as results] [clojure.test.check.rose-tree :as rose] [clojure.test.check.impl :refer [get-current-time-millis]])) (declare shrink-loop failure) (defn- make-rng [seed] (if seed [seed (random/make-random seed)] (let [non-nil-seed (get-current-time-millis)] [non-nil-seed (random/make-random non-nil-seed)]))) (defn- complete [property num-trials seed start-time reporter-fn] (let [time-elapsed-ms (- (get-current-time-millis) start-time)] (reporter-fn {:type :complete :property property :result true :pass? true :num-tests num-trials :time-elapsed-ms time-elapsed-ms :seed seed}) {:result true :pass? true :num-tests num-trials :time-elapsed-ms time-elapsed-ms :seed seed})) (defn ^:private legacy-result "Returns a value for the legacy :result key, which has the peculiar property of conflating returned exceptions with thrown exceptions." [result] (if (satisfies? results/Result result) (let [d (results/result-data result)] (if-let [[_ e] (find d :clojure.test.check.properties/error)] #?(:clj e :cljs (if (instance? js/Error e) e (ex-info "Non-Error object thrown in test" {} e))) (results/pass? result))) result)) (defn quick-check "Tests `property` `num-tests` times. Takes several optional keys: `:seed` Can be used to re-run previous tests, as the seed used is returned after a test is run. `:max-size`. can be used to control the 'size' of generated values. The size will start at 0, and grow up to max-size, as the number of tests increases. Generators will use the size parameter to bound their growth. This prevents, for example, generating a five-thousand element vector on the very first test. `:reporter-fn` A callback function that will be called at various points in the test run, with a map like: {:type :trial :args [...] :num-tests <number of tests run so far> :num-tests-total <total number of tests to be run> :seed 42 :pass? true :property #<...> :result true :result-data {...}} called after the first failing trial {:type :failure :fail [...failing args...] :failing-size 13 :num-tests <tests ran before failure found> :pass? false :property #<...> :result false/exception :result-data {...} :seed 42} It will also be called on :complete, :shrink-step and :shrunk. Many of the keys also appear in the quick-check return value, and are documented below. If the test passes, the return value will be something like: {:num-tests 100, :pass? true, :result true, :seed 1561826505982, :time-elapsed-ms 24} If the test fails, the return value will be something like: {:fail [0], :failed-after-ms 0, :failing-size 0, :num-tests 1, :pass? false, :result false, :result-data nil, :seed 1561826506080, :shrunk {:depth 0, :pass? false, :result false, :result-data nil, :smallest [0], :time-shrinking-ms 0, :total-nodes-visited 0}} The meaning of the individual entries is: :num-tests The total number of trials that was were run, not including shrinking (if applicable) :pass? A boolean indicating whether the test passed or failed :result A legacy entry that is similar to :pass? :seed a test run by passing it as the :seed option to quick-check :time-elapsed-ms The total time, in milliseconds, of a successful test run :fail always a vector, since prop/for-all can have multiple clauses :failed-after-ms The total time, in milliseconds, spent finding the first failing trial :failing-size The value of the size parameter used to generate the first failure :result-data The result data, if any, of the first failing trial (to take advantage of this a property must return an object satisfying the clojure.test.check.results/Result protocol) :shrunk documented next :shrunk / :depth The depth in the shrink tree that the smallest failing instance original failure was successfully shrunk :smallest The smallest values found in the shrinking process that still :time-shrinking-ms The total time, in milliseconds, spent shrinking :total-nodes-visited The total number of steps in the shrinking process Examples: (def p (for-all [a gen/nat] (> (* a a) a))) (quick-check 100 p) (quick-check 200 p :seed 42 :max-size 50 :reporter-fn (fn [m] (when (= :failure (:type m)) (println \"Uh oh...\"))))" [num-tests property & {:keys [seed max-size reporter-fn] :or {max-size 200, reporter-fn (constantly nil)}}] (let [[created-seed rng] (make-rng seed) size-seq (gen/make-size-range-seq max-size) start-time (get-current-time-millis)] (loop [so-far 0 size-seq size-seq rstate rng] (if (== so-far num-tests) (complete property num-tests created-seed start-time reporter-fn) (let [[size & rest-size-seq] size-seq [r1 r2] (random/split rstate) result-map-rose (gen/call-gen property r1 size) result-map (rose/root result-map-rose) result (:result result-map) args (:args result-map) so-far (inc so-far)] (if (results/pass? result) (do (reporter-fn {:type :trial :args args :num-tests so-far :num-tests-total num-tests :pass? true :property property :result result :result-data (results/result-data result) :seed seed}) (recur so-far rest-size-seq r2)) (failure property result-map-rose so-far size created-seed start-time reporter-fn))))))) (defn- smallest-shrink [total-nodes-visited depth smallest start-time] (let [{:keys [result]} smallest] {:total-nodes-visited total-nodes-visited :depth depth :pass? false :result (legacy-result result) :result-data (results/result-data result) :time-shrinking-ms (- (get-current-time-millis) start-time) :smallest (:args smallest)})) (defn- shrink-loop "Shrinking a value produces a sequence of smaller values of the same type. Each of these values can then be shrunk. Think of this as a tree. We do a modified depth-first search of the tree: Do a non-exhaustive search for a deeper (than the root) failing example. Additional rules added to depth-first search: * If a node passes the property, you may continue searching at this depth, but not backtrack * If a node fails the property, search its children The value returned is the left-most failing example at the depth where a passing example was found. Calls reporter-fn on every shrink step." [rose-tree reporter-fn] (let [start-time (get-current-time-millis) shrinks-this-depth (rose/children rose-tree)] (loop [nodes shrinks-this-depth current-smallest (rose/root rose-tree) total-nodes-visited 0 depth 0] (if (empty? nodes) (smallest-shrink total-nodes-visited depth current-smallest start-time) evaluation of ( second nodes ) head (first nodes) tail (rest nodes) result (:result (rose/root head)) args (:args (rose/root head)) pass? (results/pass? result) reporter-fn-arg {:type :shrink-step :shrinking {:args args :depth depth :pass? (boolean pass?) :result result :result-data (results/result-data result) :smallest (:args current-smallest) :total-nodes-visited total-nodes-visited}}] (if pass? (do (reporter-fn reporter-fn-arg) (recur tail current-smallest (inc total-nodes-visited) depth)) (let [new-smallest (rose/root head)] (reporter-fn (assoc-in reporter-fn-arg [:shrinking :smallest] (:args new-smallest))) (if-let [children (seq (rose/children head))] (recur children new-smallest (inc total-nodes-visited) (inc depth)) (recur tail new-smallest (inc total-nodes-visited) depth))))))))) (defn- failure [property failing-rose-tree trial-number size seed start-time reporter-fn] (let [failed-after-ms (- (get-current-time-millis) start-time) root (rose/root failing-rose-tree) result (:result root) failure-data {:fail (:args root) :failing-size size :num-tests trial-number :pass? false :property property :result (legacy-result result) :result-data (results/result-data result) :failed-after-ms failed-after-ms :seed seed}] (reporter-fn (assoc failure-data :type :failure)) (let [shrunk (shrink-loop failing-rose-tree #(reporter-fn (merge failure-data %)))] (reporter-fn (assoc failure-data :type :shrunk :shrunk shrunk)) (-> failure-data (dissoc :property) (assoc :shrunk shrunk)))))
9c3233ff4de3ab403e972827744df9819087f39711e5fcd860cc843a30ccbaa8
CryptoKami/cryptokami-core
Toss.hs
-- | Binary instances for Toss types. module Pos.Binary.Ssc.Toss ( ) where import Pos.Binary.Class (Cons (..), Field (..), deriveSimpleBi, deriveSimpleBiCxt) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Ssc (CommitmentsMap, OpeningsMap, SharesMap, VssCertificatesMap) import Pos.Ssc.Toss.Types (SscTag (..), TossModifier (..)) import Pos.Util.Util (cborError) deriveSimpleBi ''SscTag [ Cons 'CommitmentMsg [], Cons 'OpeningMsg [], Cons 'SharesMsg [], Cons 'VssCertificateMsg []] deriveSimpleBiCxt [t|HasConfiguration|] ''TossModifier [ Cons 'TossModifier [ Field [| _tmCommitments :: CommitmentsMap |], Field [| _tmOpenings :: OpeningsMap |], Field [| _tmShares :: SharesMap |], Field [| _tmCertificates :: VssCertificatesMap |] ]]
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/ssc/Pos/Binary/Ssc/Toss.hs
haskell
| Binary instances for Toss types.
module Pos.Binary.Ssc.Toss ( ) where import Pos.Binary.Class (Cons (..), Field (..), deriveSimpleBi, deriveSimpleBiCxt) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Ssc (CommitmentsMap, OpeningsMap, SharesMap, VssCertificatesMap) import Pos.Ssc.Toss.Types (SscTag (..), TossModifier (..)) import Pos.Util.Util (cborError) deriveSimpleBi ''SscTag [ Cons 'CommitmentMsg [], Cons 'OpeningMsg [], Cons 'SharesMsg [], Cons 'VssCertificateMsg []] deriveSimpleBiCxt [t|HasConfiguration|] ''TossModifier [ Cons 'TossModifier [ Field [| _tmCommitments :: CommitmentsMap |], Field [| _tmOpenings :: OpeningsMap |], Field [| _tmShares :: SharesMap |], Field [| _tmCertificates :: VssCertificatesMap |] ]]
53853e57d266cc43c0cf4f30a72f7ab2534b5669f6e7ca447e8a01eef8b27add
orthecreedence/blackbird
util.lisp
(defpackage :blackbird-test (:use :cl :fiveam :cl-async-base :cl-async-util :blackbird) (:shadow blackbird:*debug-on-error*) (:export #:run-tests)) (in-package :blackbird-test) (defmacro async-let ((&rest bindings) &body body) "Wrap an async op inside of a let/start-event-loop block to mimick a blocking action. Bindings must be set from withing the block via setf." `(let ,bindings (as:start-event-loop (lambda () ,@body) :catch-app-errors t) (values ,@(loop for (binding . nil) in bindings collect binding)))) (defun concat (&rest args) "Shortens string concatenation because I'm lazy and really who the hell wants to type out (concatenate 'string ...) seriously, I mispell concatentate like 90% of the time I type it out." (apply #'concatenate (append '(string) args))) (defun id (val) "Returns val. Yes, yes. I know that the identity function exists, but seriously I'm not going to waste precious time out of my life typing identity when I can just type id. The idea is the same, and everybody KNOWS what I'm trying to express. Oh one more thing: the only reason I NEED identi...err, id is because Eos can't use its `is` macro around another macro. So I need a function to wrap it. Lame. BUT such is life." val) ;; define the test suite (def-suite blackbird-test :description "blackbird test suite")
null
https://raw.githubusercontent.com/orthecreedence/blackbird/d361f81c1411dec07f6c2dcb11c78f7aea9aaca8/test/util.lisp
lisp
define the test suite
(defpackage :blackbird-test (:use :cl :fiveam :cl-async-base :cl-async-util :blackbird) (:shadow blackbird:*debug-on-error*) (:export #:run-tests)) (in-package :blackbird-test) (defmacro async-let ((&rest bindings) &body body) "Wrap an async op inside of a let/start-event-loop block to mimick a blocking action. Bindings must be set from withing the block via setf." `(let ,bindings (as:start-event-loop (lambda () ,@body) :catch-app-errors t) (values ,@(loop for (binding . nil) in bindings collect binding)))) (defun concat (&rest args) "Shortens string concatenation because I'm lazy and really who the hell wants to type out (concatenate 'string ...) seriously, I mispell concatentate like 90% of the time I type it out." (apply #'concatenate (append '(string) args))) (defun id (val) "Returns val. Yes, yes. I know that the identity function exists, but seriously I'm not going to waste precious time out of my life typing identity when I can just type id. The idea is the same, and everybody KNOWS what I'm trying to express. Oh one more thing: the only reason I NEED identi...err, id is because Eos can't use its `is` macro around another macro. So I need a function to wrap it. Lame. BUT such is life." val) (def-suite blackbird-test :description "blackbird test suite")
26d6a9d80e4c073dd96df2abdeb1314026b45bde7b8b69a27cdc792edda7df20
thephoeron/let-over-lambda
let-over-lambda.lisp
(in-package cl-user) (defpackage let-over-lambda-test (:use cl let-over-lambda prove) (:import-from named-readtables in-readtable)) (in-package let-over-lambda-test) (in-readtable lol-syntax) ;; NOTE: To run this test file, execute `(asdf:test-system :let-over-lambda)' in your Lisp. (plan 8) (defun! fn! () `(let ((,g!test 123)) ,g!test)) (defmacro fn-macro () (fn!)) (deftest defun!-test (is-expand (fn-macro) (LET (($TEST 123)) $TEST))) (defparameter flatten-list `(D (E (F ,'(G))))) (deftest flatten-test (is (flatten '((A . B) (C D (E) (F (G))))) '(A B C D E F G) "FLATTEN function works as expected.") (is (flatten `(A B C ,flatten-list)) '(A B C D E F G) "FLATTEN on quasiquotes works as expected.")) (defparameter heredoc-string #>END I can put anything here: ", , "# and ># are no problem. The only thing that will terminate the reading of this string is...END) (deftest heredoc-read-macro-test (is heredoc-string "I can put anything here: \", , \"# and ># are no problem. The only thing that will terminate the reading of this string is..." "SHARP-GREATER-THEN read macro works as expected.")) (deftest pilfered-perl-regex-syntax-test (is-expand '#~m|\w+tp://| '(lambda ($str) (cl-ppcre:scan-to-strings "\\w+tp://" $str)) "#~m expands correctly.") (is-expand '#~s/abc/def/ '(lambda ($str) (cl-ppcre:regex-replace-all "abc" $str "def")) "#~s expands correctly.") (is-values (#~m/abc/ "123abc") '("abc" #()) "#~m runs correctly." :test #'equalp) (is (#~s/abc/def/ "Testing abc testing abc") "Testing def testing def" "#~s runs correctly.")) (deftest read-anaphor-sharp-backquote-test (is '#`((,a1)) '(lambda (a1) `((,a1))) "SHARP-BACKQUOTE expands correctly." :test #'equalp) (is-expand #.(#3`(((,@a2)) ,a3 (,a1 ,a1)) (gensym) '(a b c) 'hello) (((a b c)) hello ($g $g)) "SHARP-BACKQUOTE runs correctly, respecting order, gensyms, nesting, numarg, etc.")) (deftest sharp-f-test (is '#f '(declare (optimize (speed 3) (safety 0))) "Default numarg SHARP-F expands correctly.") (is '#0f '(declare (optimize (speed 0) (safety 3))) "Numarg = 3 SHARP-F expands correctly.") (is '(#1f #2f) '((declare (optimize (speed 1) (safety 2))) (declare (optimize (speed 2) (safety 1)))) "SHARP-F correctly expands into rarely used compiler options.")) (deftest |test-#""#-read-macro| (is #"Contains " and \."# "Contains \" and \\." "SHARP-QUOTE read macro works as expected.")) (deftest if-match-test (is (if-match (#~m_a(b)c_ "abc") $1) "b" "IF-MATCH correctly returns the single capture.") (is-error (if-match (#~m_a(b)c_ "abc") $2) 'simple-error "IF-MATCH throws an error when $2 is unbound.") (is (if-match (#~m_a(b)c_ "def") $1 :else) :else "When IF-MATCH test is false it goes to the else body.") (is (if-match (#~m_a(b)c_ "abc") (if-match (#~m_(d)(e)f_ "def") (list $1 $2) :no-second-match) $1) '("d" "e") "IF-MATCH works with nested IF-MATCHs.") (is (if-match (#~m_a(b)c_ "abc") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $1) :no-second-match "IF-MATCH works with nested IF-MATCHs.") (is-error (if-match (#~m_a(b)c_ "ab c") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $1) 'simple-error "IF-MATCH throws an error, even when nested.") (is-error (if-match (#~m_a(b)c_ "ab c") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $2) 'simple-error "IF-MATCH throws an error, even when nested.")) (run-test-all)
null
https://raw.githubusercontent.com/thephoeron/let-over-lambda/481b2e3ab4646186451dfdd2062113203287d520/t/let-over-lambda.lisp
lisp
NOTE: To run this test file, execute `(asdf:test-system :let-over-lambda)' in your Lisp.
(in-package cl-user) (defpackage let-over-lambda-test (:use cl let-over-lambda prove) (:import-from named-readtables in-readtable)) (in-package let-over-lambda-test) (in-readtable lol-syntax) (plan 8) (defun! fn! () `(let ((,g!test 123)) ,g!test)) (defmacro fn-macro () (fn!)) (deftest defun!-test (is-expand (fn-macro) (LET (($TEST 123)) $TEST))) (defparameter flatten-list `(D (E (F ,'(G))))) (deftest flatten-test (is (flatten '((A . B) (C D (E) (F (G))))) '(A B C D E F G) "FLATTEN function works as expected.") (is (flatten `(A B C ,flatten-list)) '(A B C D E F G) "FLATTEN on quasiquotes works as expected.")) (defparameter heredoc-string #>END I can put anything here: ", , "# and ># are no problem. The only thing that will terminate the reading of this string is...END) (deftest heredoc-read-macro-test (is heredoc-string "I can put anything here: \", , \"# and ># are no problem. The only thing that will terminate the reading of this string is..." "SHARP-GREATER-THEN read macro works as expected.")) (deftest pilfered-perl-regex-syntax-test (is-expand '#~m|\w+tp://| '(lambda ($str) (cl-ppcre:scan-to-strings "\\w+tp://" $str)) "#~m expands correctly.") (is-expand '#~s/abc/def/ '(lambda ($str) (cl-ppcre:regex-replace-all "abc" $str "def")) "#~s expands correctly.") (is-values (#~m/abc/ "123abc") '("abc" #()) "#~m runs correctly." :test #'equalp) (is (#~s/abc/def/ "Testing abc testing abc") "Testing def testing def" "#~s runs correctly.")) (deftest read-anaphor-sharp-backquote-test (is '#`((,a1)) '(lambda (a1) `((,a1))) "SHARP-BACKQUOTE expands correctly." :test #'equalp) (is-expand #.(#3`(((,@a2)) ,a3 (,a1 ,a1)) (gensym) '(a b c) 'hello) (((a b c)) hello ($g $g)) "SHARP-BACKQUOTE runs correctly, respecting order, gensyms, nesting, numarg, etc.")) (deftest sharp-f-test (is '#f '(declare (optimize (speed 3) (safety 0))) "Default numarg SHARP-F expands correctly.") (is '#0f '(declare (optimize (speed 0) (safety 3))) "Numarg = 3 SHARP-F expands correctly.") (is '(#1f #2f) '((declare (optimize (speed 1) (safety 2))) (declare (optimize (speed 2) (safety 1)))) "SHARP-F correctly expands into rarely used compiler options.")) (deftest |test-#""#-read-macro| (is #"Contains " and \."# "Contains \" and \\." "SHARP-QUOTE read macro works as expected.")) (deftest if-match-test (is (if-match (#~m_a(b)c_ "abc") $1) "b" "IF-MATCH correctly returns the single capture.") (is-error (if-match (#~m_a(b)c_ "abc") $2) 'simple-error "IF-MATCH throws an error when $2 is unbound.") (is (if-match (#~m_a(b)c_ "def") $1 :else) :else "When IF-MATCH test is false it goes to the else body.") (is (if-match (#~m_a(b)c_ "abc") (if-match (#~m_(d)(e)f_ "def") (list $1 $2) :no-second-match) $1) '("d" "e") "IF-MATCH works with nested IF-MATCHs.") (is (if-match (#~m_a(b)c_ "abc") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $1) :no-second-match "IF-MATCH works with nested IF-MATCHs.") (is-error (if-match (#~m_a(b)c_ "ab c") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $1) 'simple-error "IF-MATCH throws an error, even when nested.") (is-error (if-match (#~m_a(b)c_ "ab c") (if-match (#~m_(d)(e)f_ "d ef") (list $1 $2) :no-second-match) $2) 'simple-error "IF-MATCH throws an error, even when nested.")) (run-test-all)
9fa014ccb6922c8b4cc76764135344fc5e14a42175668d77c79e0e82e305dbef
louispan/data-diverse
CaseFunc.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # module Data.Diverse.CaseFunc where import Data.Diverse.Case import Data.Diverse.Reiterate import Data.Diverse.TypeLevel import Data.Kind -- | This handler stores a polymorphic function that returns a different type. -- -- @ let y = ' Data.Diverse.Which.pick ' ( 5 : : Int ) : : ' Data . Diverse . Which . Which ' ' [ Int , Bool ] ' Data.Diverse.Which.switch ' y ( ' CaseFunc ' \@'Data . . ' ( show . typeRep . ( pure \@Proxy ) ) ) \`shouldBe ` " Int " -- @ -- -- @ let x = ( 5 : : Int ) ' Data . Diverse . Many .. / ' False ' Data . Diverse . Many .. / ' \'X ' ' Data . Diverse . Many .. / ' Just \'O ' ' Data . Diverse . Many .. / ' ( 6 : : Int ) ' Data . Diverse . Many .. / ' Just \'A ' ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nul ' ' Data.Diverse.AFoldable.afoldr ' ( :) [ ] ( ' Data . Diverse . Many.forMany ' ( ' CaseFunc ' \@'Data . . ' ( show . typeRep . ( pure @Proxy ) ) ) x ) \`shouldBe ` [ \"Int " , \"Bool " , \"Char " , \"Maybe " , \"Int " , \"Maybe " ] -- @ newtype CaseFunc (k :: Type -> Constraint) r (xs :: [Type]) = CaseFunc (forall x. k x => x -> r) This was made possible by Syrak -- / type instance CaseResult (CaseFunc k r) x = r instance Reiterate (CaseFunc k r) xs where reiterate (CaseFunc f) = CaseFunc f instance k x => Case (CaseFunc k r) (x ': xs) where case' (CaseFunc f) = f -- | This handler stores a polymorphic function that doesn't change the type. -- -- @ let x = ( 5 : : Int ) ' Data . Diverse . Many .. / ' ( 6 : : Int8 ) ' Data . Diverse . Many .. / ' ( 7 : : Int16 ) ' Data . Diverse . Many .. / ' ( 8 : : ) ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nil ' y = ( 15 : : Int ) ' Data . Diverse . Many .. / ' ( 16 : : Int8 ) ' Data . Diverse . Many .. / ' ( 17 : : Int16 ) ' Data . Diverse . Many .. / ' ( 18 : : ) ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nil ' ' Data.Diverse.AFunctor.afmap ' ( ' CaseFunc '' \@'Num ' ( +10 ) ) x \`shouldBe ` y -- @ newtype CaseFunc' (k :: Type -> Constraint) (xs :: [Type]) = CaseFunc' (forall x. k x => x -> x) type instance CaseResult (CaseFunc' k) x = x instance Reiterate (CaseFunc' k) xs where reiterate (CaseFunc' f) = CaseFunc' f instance k x => Case (CaseFunc' k) (x ': xs) where case' (CaseFunc' f) = f -- | This handler stores a polymorphic function that work on higher kinds, eg 'Functor' -- You may want to use @C0 for @k@ newtype CaseFunc1 (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) r (xs :: [Type]) = CaseFunc1 (forall f x. (k (f x), k1 f, k0 x) => f x -> f r) type instance CaseResult (CaseFunc1 k k1 k0 r) (f x) = f r instance Reiterate (CaseFunc1 k k1 k0 r) xs where reiterate (CaseFunc1 f) = CaseFunc1 f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1 k k1 k0 r) (f x ': xs) where case' (CaseFunc1 f) = f newtype CaseFunc1_ (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) r x (xs :: [Type]) = CaseFunc1_ (forall f. (k (f x), k1 f, k0 x) => f x -> f r) type instance CaseResult (CaseFunc1_ k k1 k0 r x) (f x) = f r instance Reiterate (CaseFunc1_ k k1 k0 r x) xs where reiterate (CaseFunc1_ f) = CaseFunc1_ f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1_ k k1 k0 r x) (f x ': xs) where case' (CaseFunc1_ f) = f -- | A varation of 'CaseFunc1' that doesn't change the return type newtype CaseFunc1' (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) (xs :: [Type]) = CaseFunc1' (forall f x. (k (f x), k1 f, k0 x) => f x -> f x) type instance CaseResult (CaseFunc1' k k1 k0) (f x) = f x instance Reiterate (CaseFunc1' k k1 k0) xs where reiterate (CaseFunc1' f) = CaseFunc1' f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1' k k1 k0) (f x ': xs) where case' (CaseFunc1' f) = f
null
https://raw.githubusercontent.com/louispan/data-diverse/4033c90c44dab5824f76d64b7128bb6dea2b5dc7/src/Data/Diverse/CaseFunc.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes # | This handler stores a polymorphic function that returns a different type. @ @ @ @ / | This handler stores a polymorphic function that doesn't change the type. @ @ | This handler stores a polymorphic function that work on higher kinds, eg 'Functor' You may want to use @C0 for @k@ | A varation of 'CaseFunc1' that doesn't change the return type
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # module Data.Diverse.CaseFunc where import Data.Diverse.Case import Data.Diverse.Reiterate import Data.Diverse.TypeLevel import Data.Kind let y = ' Data.Diverse.Which.pick ' ( 5 : : Int ) : : ' Data . Diverse . Which . Which ' ' [ Int , Bool ] ' Data.Diverse.Which.switch ' y ( ' CaseFunc ' \@'Data . . ' ( show . typeRep . ( pure \@Proxy ) ) ) \`shouldBe ` " Int " let x = ( 5 : : Int ) ' Data . Diverse . Many .. / ' False ' Data . Diverse . Many .. / ' \'X ' ' Data . Diverse . Many .. / ' Just \'O ' ' Data . Diverse . Many .. / ' ( 6 : : Int ) ' Data . Diverse . Many .. / ' Just \'A ' ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nul ' ' Data.Diverse.AFoldable.afoldr ' ( :) [ ] ( ' Data . Diverse . Many.forMany ' ( ' CaseFunc ' \@'Data . . ' ( show . typeRep . ( pure @Proxy ) ) ) x ) \`shouldBe ` [ \"Int " , \"Bool " , \"Char " , \"Maybe " , \"Int " , \"Maybe " ] newtype CaseFunc (k :: Type -> Constraint) r (xs :: [Type]) = CaseFunc (forall x. k x => x -> r) This was made possible by Syrak type instance CaseResult (CaseFunc k r) x = r instance Reiterate (CaseFunc k r) xs where reiterate (CaseFunc f) = CaseFunc f instance k x => Case (CaseFunc k r) (x ': xs) where case' (CaseFunc f) = f let x = ( 5 : : Int ) ' Data . Diverse . Many .. / ' ( 6 : : Int8 ) ' Data . Diverse . Many .. / ' ( 7 : : Int16 ) ' Data . Diverse . Many .. / ' ( 8 : : ) ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nil ' y = ( 15 : : Int ) ' Data . Diverse . Many .. / ' ( 16 : : Int8 ) ' Data . Diverse . Many .. / ' ( 17 : : Int16 ) ' Data . Diverse . Many .. / ' ( 18 : : ) ' Data . Diverse . Many .. / ' ' Data.Diverse.Many.nil ' ' Data.Diverse.AFunctor.afmap ' ( ' CaseFunc '' \@'Num ' ( +10 ) ) x \`shouldBe ` y newtype CaseFunc' (k :: Type -> Constraint) (xs :: [Type]) = CaseFunc' (forall x. k x => x -> x) type instance CaseResult (CaseFunc' k) x = x instance Reiterate (CaseFunc' k) xs where reiterate (CaseFunc' f) = CaseFunc' f instance k x => Case (CaseFunc' k) (x ': xs) where case' (CaseFunc' f) = f newtype CaseFunc1 (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) r (xs :: [Type]) = CaseFunc1 (forall f x. (k (f x), k1 f, k0 x) => f x -> f r) type instance CaseResult (CaseFunc1 k k1 k0 r) (f x) = f r instance Reiterate (CaseFunc1 k k1 k0 r) xs where reiterate (CaseFunc1 f) = CaseFunc1 f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1 k k1 k0 r) (f x ': xs) where case' (CaseFunc1 f) = f newtype CaseFunc1_ (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) r x (xs :: [Type]) = CaseFunc1_ (forall f. (k (f x), k1 f, k0 x) => f x -> f r) type instance CaseResult (CaseFunc1_ k k1 k0 r x) (f x) = f r instance Reiterate (CaseFunc1_ k k1 k0 r x) xs where reiterate (CaseFunc1_ f) = CaseFunc1_ f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1_ k k1 k0 r x) (f x ': xs) where case' (CaseFunc1_ f) = f newtype CaseFunc1' (k :: Type -> Constraint) (k1 :: (Type -> Type) -> Constraint) (k0 :: Type -> Constraint) (xs :: [Type]) = CaseFunc1' (forall f x. (k (f x), k1 f, k0 x) => f x -> f x) type instance CaseResult (CaseFunc1' k k1 k0) (f x) = f x instance Reiterate (CaseFunc1' k k1 k0) xs where reiterate (CaseFunc1' f) = CaseFunc1' f instance (k (f x), k1 f, k0 x) => Case (CaseFunc1' k k1 k0) (f x ': xs) where case' (CaseFunc1' f) = f
24645d1ae5c70447a6481d0a4f4bc972b52eac324586719802c55fe2482853ab
samrocketman/home
phillips-film-grain.scm
; ; The GIMP -- an image manipulation program Copyright ( C ) 1995 and ; Film Grain script for GIMP 2.4 Copyright ( C ) 2007 < > ; ; Tags: photo, grain, noise, film ; ; Author statement: ; Based on the tutorial at ; This script adds that gritty, art-house/street-photography/high-ISO ; grainy film look, especially in monochromatic photos. ; ; -------------------------------------------------------------------- Distributed by Gimp FX Foundry project ; -------------------------------------------------------------------- ; - Changelog - ; Changelog: Version 1.3 ( 5th August 2007 ) ; - Added GPL3 licence ; - Menu location at the top of the script ; - Removed the "script-fu-menu-register" section ; Version 1.2 - Made the script compatible with GIMP 2.3 ; ; -------------------------------------------------------------------- ; ; 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, you can view the GNU General Public License version 3 at the web site -3.0.html Alternatively you can write to the Free Software Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (script-fu-film-grain theImage theLayer grainSize blurAmount maskToggle midPoint) (define (mask-spline yPoint) (let* ((a (cons-array 6 'byte))) (set-pt a 0 0 0) (set-pt a 1 127 yPoint) (set-pt a 2 255 0) a)) (define (set-pt a index x y) (prog1 (aset a (* index 2) x) (aset a (+ (* index 2) 1) y))) Start an undo group so the process can be undone with one undo (gimp-image-undo-group-start theImage) (let* ( (imageWidth 0) (imageHeight 0) (myForeground 0) (myBackground 0) (newLayer 0) (mask 0) ) (set! imageWidth (car (gimp-image-width theImage))) (set! imageHeight (car (gimp-image-height theImage))) ;Read the current colours (set! myForeground (car (gimp-context-get-foreground))) (set! myBackground (car (gimp-context-get-background))) ;Select none (gimp-selection-none theImage) ;Set the foreground colour (gimp-context-set-foreground '(128 128 128)) ;Add a new layer (set! newLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Film Noise" 100 5))) (gimp-image-add-layer theImage newLayer 0) Fill the layer with BG colour (gimp-edit-fill newLayer 0) Open the scatter HSV (plug-in-scatter-hsv 1 theImage newLayer 2 3 10 grainSize) ;Apply the blur with the supplied blur amount (plug-in-gauss 1 theImage newLayer blurAmount blurAmount 0) (if (= maskToggle TRUE) (begin ;Add a layer mask (set! mask (car (gimp-layer-create-mask newLayer 0))) (gimp-layer-add-mask newLayer mask) ;Copy the layer into the clipboard (gimp-edit-copy theLayer) ;Paste it into the layer mask (gimp-floating-sel-anchor (car (gimp-edit-paste mask TRUE))) ;Alter the curves of the mask (gimp-curves-spline mask 0 6 (mask-spline midPoint)) ) ()) ;Finish the undo group for the process (gimp-image-undo-group-end theImage) Set the FG and BG colours back to what they were (gimp-context-set-foreground myForeground) (gimp-context-set-background myBackground) ;Ensure the updated image is displayed now (gimp-displays-flush) ) ) (script-fu-register "script-fu-film-grain" _"<Image>/FX-Foundry/Photo/Effects/Film Grain..." "Performs a tone mapping operation with a specified blur on the open image" "Harry Phillips" "Harry Phillips" "May. 05 2007" "*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-ADJUSTMENT _"Grain size" '(50 10 500 5 5 1 0) SF-ADJUSTMENT _"Blur amount" '(1 1 5 0.1 1 1 0) SF-TOGGLE _"Add a layer mask" FALSE SF-ADJUSTMENT _"Midpoint adjustment" '(127 0 255 1 1 1 0) )
null
https://raw.githubusercontent.com/samrocketman/home/63a8668a71dc594ea9ed76ec56bf8ca43b2a86ca/dotfiles/.gimp/scripts/phillips-film-grain.scm
scheme
The GIMP -- an image manipulation program Tags: photo, grain, noise, film Author statement: This script adds that gritty, art-house/street-photography/high-ISO grainy film look, especially in monochromatic photos. -------------------------------------------------------------------- -------------------------------------------------------------------- - Changelog - Changelog: - Added GPL3 licence - Menu location at the top of the script - Removed the "script-fu-menu-register" section -------------------------------------------------------------------- This program is free software; you can redistribute it and/or modify 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. along with this program; if not, you can view the GNU General Public Read the current colours Select none Set the foreground colour Add a new layer Apply the blur with the supplied blur amount Add a layer mask Copy the layer into the clipboard Paste it into the layer mask Alter the curves of the mask Finish the undo group for the process Ensure the updated image is displayed now
Copyright ( C ) 1995 and Film Grain script for GIMP 2.4 Copyright ( C ) 2007 < > Based on the tutorial at Distributed by Gimp FX Foundry project Version 1.3 ( 5th August 2007 ) Version 1.2 - Made the script compatible with GIMP 2.3 it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License License version 3 at the web site -3.0.html Alternatively you can write to the Free Software Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . (define (script-fu-film-grain theImage theLayer grainSize blurAmount maskToggle midPoint) (define (mask-spline yPoint) (let* ((a (cons-array 6 'byte))) (set-pt a 0 0 0) (set-pt a 1 127 yPoint) (set-pt a 2 255 0) a)) (define (set-pt a index x y) (prog1 (aset a (* index 2) x) (aset a (+ (* index 2) 1) y))) Start an undo group so the process can be undone with one undo (gimp-image-undo-group-start theImage) (let* ( (imageWidth 0) (imageHeight 0) (myForeground 0) (myBackground 0) (newLayer 0) (mask 0) ) (set! imageWidth (car (gimp-image-width theImage))) (set! imageHeight (car (gimp-image-height theImage))) (set! myForeground (car (gimp-context-get-foreground))) (set! myBackground (car (gimp-context-get-background))) (gimp-selection-none theImage) (gimp-context-set-foreground '(128 128 128)) (set! newLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Film Noise" 100 5))) (gimp-image-add-layer theImage newLayer 0) Fill the layer with BG colour (gimp-edit-fill newLayer 0) Open the scatter HSV (plug-in-scatter-hsv 1 theImage newLayer 2 3 10 grainSize) (plug-in-gauss 1 theImage newLayer blurAmount blurAmount 0) (if (= maskToggle TRUE) (begin (set! mask (car (gimp-layer-create-mask newLayer 0))) (gimp-layer-add-mask newLayer mask) (gimp-edit-copy theLayer) (gimp-floating-sel-anchor (car (gimp-edit-paste mask TRUE))) (gimp-curves-spline mask 0 6 (mask-spline midPoint)) ) ()) (gimp-image-undo-group-end theImage) Set the FG and BG colours back to what they were (gimp-context-set-foreground myForeground) (gimp-context-set-background myBackground) (gimp-displays-flush) ) ) (script-fu-register "script-fu-film-grain" _"<Image>/FX-Foundry/Photo/Effects/Film Grain..." "Performs a tone mapping operation with a specified blur on the open image" "Harry Phillips" "Harry Phillips" "May. 05 2007" "*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-ADJUSTMENT _"Grain size" '(50 10 500 5 5 1 0) SF-ADJUSTMENT _"Blur amount" '(1 1 5 0.1 1 1 0) SF-TOGGLE _"Add a layer mask" FALSE SF-ADJUSTMENT _"Midpoint adjustment" '(127 0 255 1 1 1 0) )
a185059c934b9c6e79f294ce6a1b55e98fdd4f4b9c4c2c47be2d7f57d6f91c01
WhatsApp/erlt
erltc.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2017 . All Rights Reserved . Copyright ( c ) Facebook , Inc. and its affiliates . %% 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 %% %% -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. %% %% %CopyrightEnd% -module(erltc). NOTE : what you see below is based on copy - pasted erlang / lib / stdlib-3.7 / src / erl_compile.erl ( R21 ) -include_lib("kernel/include/file.hrl"). -include("erlt_common.hrl"). -export([ % escript entry point main/1, % programmatic entrypoint. Distinct from compile:file because takes stringy args instead of structured api/1, % rebar3 plugin entrypoint init/1 ]). Macro to avoid misspellings . -define(STDERR, standard_error). NOTE : this record definition was copy - pasted from erlang / lib / stdlib-3.7 / include / erl_compile.hrl ( R21 ) -record(options, { includes = [] :: [file:filename()], % Include paths (list of % absolute directory names). outdir = "." :: file:filename(), % Directory for result % (absolute path). % Type of output file. output_type = undefined :: atom(), defines = [] :: [atom() | {atom(), _}], Preprocessor defines . Each % element is an atom % (the name to define), or % a {Name, Value} tuple. warning = 1 :: non_neg_integer(), % Warning level (0 - no warnings , 1 - standard level , 2 , 3 , ... - more warnings ) . % Verbose (true/false). verbose = false :: boolean(), % Optimize options. optimize = 999, Compiler specific options . specific = [] :: [_], outfile = "" :: file:filename(), % Name of output file (internal % use in erl_compile.erl). cwd :: file:filename(), % Current working directory % for erlc. skip_type_checking = false % Temporary hack, not public api. --skip - type - checking used in Sterlang tests that compare its internal parser to the erltc parser . }). %% Converts generic compiler options to specific options. %% NOTE : this piece was copy - pasted from erlang / lib / compiler-7.3 / src / compile.erl ( R21 ) -import(lists, [ member/2, reverse/1, reverse/2, keyfind/3, last/1, map/2, flatmap/2, foreach/2, foldr/3, any/2 ]). make_erl_options(Opts) -> #options{ includes = Includes, defines = Defines, outdir = Outdir, warning = Warning, verbose = Verbose, specific = Specific, output_type = OutputType, cwd = Cwd, skip_type_checking = SkipTypeChecking } = Opts, Options = [skip_type_checking || SkipTypeChecking] ++ [verbose || Verbose] ++ [report_warnings || Warning =/= 0] ++ map( fun ({Name, Value}) -> {d, Name, Value}; (Name) -> {d, Name} end, Defines ) ++ case OutputType of undefined -> []; jam -> [jam]; beam -> [beam]; native -> [native] end, Options ++ [ report_errors, {cwd, Cwd}, {outdir, Outdir} | [{i, Dir} || Dir <- Includes] ] ++ Specific. % Escript entry point main(Args) -> case api(Args) of ok -> my_halt(0); error -> my_halt(1); {error, Msg} -> io:format(standard_error, "Error: ~p~n", [Msg]), my_halt(2) end. % rebar3 entry point init(RebarState) -> rebar_prv_erlt:init(RebarState). handle_path_args([]) -> []; handle_path_args(["-pa", Path | T]) -> code:add_patha(Path), handle_path_args(T); handle_path_args(["-pz", Path | T]) -> code:add_pathz(Path), handle_path_args(T); handle_path_args([H | T]) -> [H | handle_path_args(T)]. -type cmd_line_arg() :: atom() | string(). -spec my_halt(_) -> no_return(). my_halt(Reason) -> erlang:halt(Reason). %% Run the the compiler in a separate process, trapping EXITs. api(Args0) -> % handle -pa, -pz and remove them from the original args % % NOTE, TODO: for now, only handling well-formed args, if things happen to % be misplaced things won't be handled correctly, e.g. -o -pa ... Args = handle_path_args(Args0), process_flag(trap_exit, true), Pid = spawn_link(compiler_runner(Args)), receive {'EXIT', Pid, {compiler_result, Result}} -> Result; {'EXIT', Pid, {compiler_error, Error}} -> io:put_chars(?STDERR, Error), io:nl(?STDERR), error; {'EXIT', Pid, Reason} -> io:format(?STDERR, "Runtime error: ~tp~n", [Reason]), error end. -spec compiler_runner([cmd_line_arg()]) -> fun(() -> no_return()). compiler_runner(List) -> fun() -> %% We don't want the current directory in the code path. %% Remove it. Path = [D || D <- code:get_path(), D =/= "."], true = code:set_path(Path), exit({compiler_result, compile1(List)}) end. Parses the first part of the option list %% and decides whether to go into "build" (multi-file) mode compile1(Args0) -> {ok, Cwd} = file:get_cwd(), {BuildArgs, Args} = lists:partition(fun(Arg) -> Arg =:= "--build" end, Args0), ShouldBuildMultipleFiles = BuildArgs =/= [], case ShouldBuildMultipleFiles of true -> erlt_build:main(Args); false -> compile1(Args, #options{outdir = Cwd, cwd = Cwd}) end. %% Parses all options. compile1(["--" | Files], Opts) -> compile2(Files, Opts); compile1(["-" ++ Option | T], Opts) -> parse_generic_option(Option, T, Opts); compile1(["+" ++ Option | Rest], Opts) -> Term = make_term(Option), Specific = Opts#options.specific, compile1(Rest, Opts#options{specific = [Term | Specific]}); compile1(Files, Opts) -> compile2(Files, Opts). parse_generic_option("b" ++ Opt, T0, Opts) -> {OutputType, T} = get_option("b", Opt, T0), compile1(T, Opts#options{output_type = list_to_atom(OutputType)}); parse_generic_option("D" ++ Opt, T0, #options{defines = Defs} = Opts) -> {Val0, T} = get_option("D", Opt, T0), {Key0, Val1} = split_at_equals(Val0, []), Key = list_to_atom(Key0), case Val1 of [] -> compile1(T, Opts#options{defines = [Key | Defs]}); Val2 -> Val = make_term(Val2), compile1(T, Opts#options{defines = [{Key, Val} | Defs]}) end; parse_generic_option("help", _, _Opts) -> usage(); parse_generic_option("I" ++ Opt, T0, #options{cwd = Cwd} = Opts) -> {Dir, T} = get_option("I", Opt, T0), AbsDir = filename:absname(Dir, Cwd), compile1(T, Opts#options{includes = [AbsDir | Opts#options.includes]}); parse_generic_option("M" ++ Opt, T0, #options{specific = Spec} = Opts) -> case parse_dep_option(Opt, T0) of error -> error; {SpecOpts, T} -> compile1(T, Opts#options{specific = SpecOpts ++ Spec}) end; parse_generic_option("o" ++ Opt, T0, #options{cwd = Cwd} = Opts) -> {Dir, T} = get_option("o", Opt, T0), AbsName = filename:absname(Dir, Cwd), case file_or_directory(AbsName) of file -> compile1(T, Opts#options{outfile = AbsName}); directory -> compile1(T, Opts#options{outdir = AbsName}) end; parse_generic_option("O" ++ Opt, T, Opts) -> case Opt of "" -> compile1(T, Opts#options{optimize = 1}); _ -> Term = make_term(Opt), compile1(T, Opts#options{optimize = Term}) end; parse_generic_option("v", T, Opts) -> compile1(T, Opts#options{verbose = true}); parse_generic_option("W" ++ Warn, T, #options{specific = Spec} = Opts) -> case Warn of "all" -> compile1(T, Opts#options{warning = 999}); "error" -> compile1(T, Opts#options{specific = [warnings_as_errors | Spec]}); "" -> compile1(T, Opts#options{warning = 1}); _ -> try list_to_integer(Warn) of Level -> compile1(T, Opts#options{warning = Level}) catch error:badarg -> usage() end end; parse_generic_option("B", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['B' | Spec]}); parse_generic_option("A", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['A' | Spec]}); parse_generic_option("E", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['E' | Spec]}); parse_generic_option("P", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['P' | Spec]}); parse_generic_option("S", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['S' | Spec]}); parse_generic_option("-build-phase", T0, #options{specific = Spec} = Opts) -> {PhaseString, T} = get_option("build-phase", "", T0), Phase = case PhaseString of "scan" -> scan; "compile" -> compile; _ -> exit( {compiler_error, "Invalid --build-phase '" ++ PhaseString ++ "'; must be 'scan' or 'compile'"} ) end, PhaseOpt = {build_phase, Phase}, compile1(T, Opts#options{specific = [PhaseOpt | Spec]}); parse_generic_option("-build-dir", T0, #options{specific = Spec} = Opts) -> {BuildDir, T} = get_option("-build-dir", "", T0), BuildDirOpt = {build_dir, BuildDir}, compile1(T, Opts#options{specific = [BuildDirOpt | Spec]}); parse_generic_option("-skip-type-checking", T, Opts) -> compile1(T, Opts#options{skip_type_checking = true}); parse_generic_option(Option, _T, _Opts) -> io:format(?STDERR, "Unknown option: -~ts\n", [Option]), usage(). parse_dep_option("", T) -> {[makedep, {makedep_output, standard_io}], T}; parse_dep_option("D", T) -> {[makedep], T}; parse_dep_option("2", T) -> {[makedep, makedep2], T}; parse_dep_option("MD", T) -> {[makedep_side_effect], T}; parse_dep_option("F" ++ Opt, T0) -> {File, T} = get_option("MF", Opt, T0), {[makedep, {makedep_output, File}], T}; parse_dep_option("G", T) -> {[makedep_add_missing], T}; parse_dep_option("P", T) -> {[makedep_phony], T}; parse_dep_option("Q" ++ Opt, T0) -> {Target, T} = get_option("MT", Opt, T0), {[makedep_quote_target, {makedep_target, Target}], T}; parse_dep_option("T" ++ Opt, T0) -> {Target, T} = get_option("MT", Opt, T0), {[{makedep_target, Target}], T}; parse_dep_option(Opt, _T) -> io:format(?STDERR, "Unknown option: -M~ts\n", [Opt]), usage(). usage() -> H = [ {"-b type", "type of output file (e.g. beam)"}, {"-d", "turn on debugging of erlc itself"}, {"-Dname", "define name"}, {"-Dname=value", "define name to have value"}, {"-help", "shows this help text"}, {"-I path", "where to search for include files"}, {"-M", "generate a rule for make(1) describing the dependencies"}, {"-M2", "similar to -M, but also includes dependencies on .beam files from behaviors and parse transforms"}, {"-MF file", "write the dependencies to 'file'"}, {"-MT target", "change the target of the rule emitted by dependency " "generation"}, {"-MQ target", "same as -MT but quote characters special to make(1)"}, {"-MG", "consider missing headers as generated files and add them to " "the dependencies"}, {"-MP", "add a phony target for each dependency"}, {"-MD", "same as -M -MT file (with default 'file')"}, {"-MMD", "generate dependencies as a side-effect"}, {"-o name", "name output directory or file"}, {"-pa path", "add path to the front of Erlang's code path"}, {"-pz path", "add path to the end of Erlang's code path"}, NOTE : this option is a no - op , because erltc is escript ; on the other hand , -smp is enabled by default these days , so it is a no - op in any % case {"-smp", "compile using SMP emulator"}, {"-v", "verbose compiler output"}, {"-Werror", "make all warnings into errors"}, {"-W0", "disable warnings"}, {"-Wnumber", "set warning level to number"}, {"-Wall", "enable all warnings"}, {"-W", "enable warnings (default; same as -W1)"}, {"-E", "generate listing of expanded code (Erlang compiler)"}, {"-S", "generate assembly listing (Erlang compiler)"}, {"-P", "generate listing of preprocessed code (Erlang compiler)"}, {"+term", "pass the Erlang term unchanged to the compiler"} ], io:put_chars(?STDERR, [ "Usage: erlc [Options] file.ext ...\n", "Options:\n", [io_lib:format("~-14s ~s\n", [K, D]) || {K, D} <- H] ]), error. get_option(_Name, [], [[C | _] = Option | T]) when C =/= $- -> {Option, T}; get_option(_Name, [_ | _] = Option, T) -> {Option, T}; get_option(Name, _, _) -> exit({compiler_error, "No value given to -" ++ Name ++ " option"}). split_at_equals([$= | T], Acc) -> {lists:reverse(Acc), T}; split_at_equals([H | T], Acc) -> split_at_equals(T, [H | Acc]); split_at_equals([], Acc) -> {lists:reverse(Acc), []}. compile2(Files, #options{cwd = Cwd, includes = Incl} = Opts0) -> Opts = Opts0#options{includes = lists:reverse(Incl)}, case Files of [] -> % XXX: I don't think this is a good idea to allow no input files, % but keeping this consistent with erlc behavior for now ok; [File] -> compile3(File, Cwd, Opts); _ -> TODO , XXX : the reason we do not support compiling multiple .erl files in erltc , is because , as a first step , we need to know the % order in which these files should be compiled. This is already % true for behaviors. And this is going to be increasingly important in Erlang v2 as we start adding more features that rely % on compile order between different modules. % % While it is possible to perform compile order scan along with % compiling multiple .erl files, the compiler won't be able to % cache this information for subsequent runs. It feels that it is % better to separate compile order scan and compilation steps and % have them orchestrated by the build system, which can also % implement caching for compile order information. io:put_chars( ?STDERR, "erltc expects only one input file, " "but more than one input files were given.\n" ), error end. compile3(File, Cwd, Options) -> % NOTE: using same transformation of the filename as the original % erl_compile.erl code Root = filename:rootname(File), InFile = filename:absname(Root, Cwd), invoke the Erlang compiler on .erl , use the original erlc code path for % any other file case filename:extension(File) of ?SOURCE_FILE_EXTENSION -> CompileOptions = make_erl_options(Options), case catch erlt_compile:compile(InFile, CompileOptions) of ok -> ok; error -> error; {'EXIT', Reason} -> io:format(?STDERR, "erlt compiler failed:\n~p~n", [Reason]), error; Other -> io:format(?STDERR, "erlt compiler returned:\n~p~n", [Other]), error end; _ -> % TODO: call erlc compiler for non- .erl files % % it would be great if we could simply call % erl_compile:compile_cmdline() at this point, but unfortunately % escript args conventions are incompatible with code : ( ) used by erl_compile . % One thing we could do to make this compatible throughout is , instead of escript , use a shell script or modified erlc.c to call % erltc io:put_chars(?STDERR, "erltc does not support compiling non .erlt files\n"), error end. %% Guesses if a give name refers to a file or a directory. file_or_directory(Name) -> case file:read_file_info(Name) of {ok, #file_info{type = regular}} -> file; {ok, _} -> directory; {error, _} -> case filename:extension(Name) of [] -> directory; _Other -> file end end. Makes an Erlang term given a string . %% Uses Erlang parser/compiler instead of erlt to avoid syntax conflicts make_term(Str) -> case erl_scan:string(Str) of {ok, Tokens, _} -> case erl_parse:parse_term(Tokens ++ [{dot, erl_anno:new(1)}]) of {ok, Term} -> Term; {error, {_, _, Reason}} -> io:format(?STDERR, "~ts: ~ts~n", [Reason, Str]), throw(error) end; {error, {_, _, Reason}, _} -> io:format(?STDERR, "~ts: ~ts~n", [Reason, Str]), throw(error) end.
null
https://raw.githubusercontent.com/WhatsApp/erlt/616a4adc628ca8754112e659701e57f1cd7fecd1/erltc/src/erltc.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. %CopyrightEnd% escript entry point programmatic entrypoint. Distinct from compile:file because takes stringy args instead of structured rebar3 plugin entrypoint Include paths (list of absolute directory names). Directory for result (absolute path). Type of output file. element is an atom (the name to define), or a {Name, Value} tuple. Warning level (0 - no Verbose (true/false). Optimize options. Name of output file (internal use in erl_compile.erl). Current working directory for erlc. Temporary hack, not public api. Converts generic compiler options to specific options. Escript entry point rebar3 entry point Run the the compiler in a separate process, trapping EXITs. handle -pa, -pz and remove them from the original args NOTE, TODO: for now, only handling well-formed args, if things happen to be misplaced things won't be handled correctly, e.g. -o -pa ... We don't want the current directory in the code path. Remove it. and decides whether to go into "build" (multi-file) mode Parses all options. case XXX: I don't think this is a good idea to allow no input files, but keeping this consistent with erlc behavior for now order in which these files should be compiled. This is already true for behaviors. And this is going to be increasingly on compile order between different modules. While it is possible to perform compile order scan along with compiling multiple .erl files, the compiler won't be able to cache this information for subsequent runs. It feels that it is better to separate compile order scan and compilation steps and have them orchestrated by the build system, which can also implement caching for compile order information. NOTE: using same transformation of the filename as the original erl_compile.erl code any other file TODO: call erlc compiler for non- .erl files it would be great if we could simply call erl_compile:compile_cmdline() at this point, but unfortunately escript args conventions are incompatible with erltc Guesses if a give name refers to a file or a directory. Uses Erlang parser/compiler instead of erlt to avoid syntax conflicts
Copyright Ericsson AB 1997 - 2017 . All Rights Reserved . Copyright ( c ) Facebook , Inc. and its affiliates . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(erltc). NOTE : what you see below is based on copy - pasted erlang / lib / stdlib-3.7 / src / erl_compile.erl ( R21 ) -include_lib("kernel/include/file.hrl"). -include("erlt_common.hrl"). -export([ main/1, api/1, init/1 ]). Macro to avoid misspellings . -define(STDERR, standard_error). NOTE : this record definition was copy - pasted from erlang / lib / stdlib-3.7 / include / erl_compile.hrl ( R21 ) -record(options, { includes = [] :: [file:filename()], outdir = "." :: file:filename(), output_type = undefined :: atom(), defines = [] :: [atom() | {atom(), _}], Preprocessor defines . Each warning = 1 :: non_neg_integer(), warnings , 1 - standard level , 2 , 3 , ... - more warnings ) . verbose = false :: boolean(), optimize = 999, Compiler specific options . specific = [] :: [_], outfile = "" :: file:filename(), cwd :: file:filename(), skip_type_checking = false --skip - type - checking used in Sterlang tests that compare its internal parser to the erltc parser . }). NOTE : this piece was copy - pasted from erlang / lib / compiler-7.3 / src / compile.erl ( R21 ) -import(lists, [ member/2, reverse/1, reverse/2, keyfind/3, last/1, map/2, flatmap/2, foreach/2, foldr/3, any/2 ]). make_erl_options(Opts) -> #options{ includes = Includes, defines = Defines, outdir = Outdir, warning = Warning, verbose = Verbose, specific = Specific, output_type = OutputType, cwd = Cwd, skip_type_checking = SkipTypeChecking } = Opts, Options = [skip_type_checking || SkipTypeChecking] ++ [verbose || Verbose] ++ [report_warnings || Warning =/= 0] ++ map( fun ({Name, Value}) -> {d, Name, Value}; (Name) -> {d, Name} end, Defines ) ++ case OutputType of undefined -> []; jam -> [jam]; beam -> [beam]; native -> [native] end, Options ++ [ report_errors, {cwd, Cwd}, {outdir, Outdir} | [{i, Dir} || Dir <- Includes] ] ++ Specific. main(Args) -> case api(Args) of ok -> my_halt(0); error -> my_halt(1); {error, Msg} -> io:format(standard_error, "Error: ~p~n", [Msg]), my_halt(2) end. init(RebarState) -> rebar_prv_erlt:init(RebarState). handle_path_args([]) -> []; handle_path_args(["-pa", Path | T]) -> code:add_patha(Path), handle_path_args(T); handle_path_args(["-pz", Path | T]) -> code:add_pathz(Path), handle_path_args(T); handle_path_args([H | T]) -> [H | handle_path_args(T)]. -type cmd_line_arg() :: atom() | string(). -spec my_halt(_) -> no_return(). my_halt(Reason) -> erlang:halt(Reason). api(Args0) -> Args = handle_path_args(Args0), process_flag(trap_exit, true), Pid = spawn_link(compiler_runner(Args)), receive {'EXIT', Pid, {compiler_result, Result}} -> Result; {'EXIT', Pid, {compiler_error, Error}} -> io:put_chars(?STDERR, Error), io:nl(?STDERR), error; {'EXIT', Pid, Reason} -> io:format(?STDERR, "Runtime error: ~tp~n", [Reason]), error end. -spec compiler_runner([cmd_line_arg()]) -> fun(() -> no_return()). compiler_runner(List) -> fun() -> Path = [D || D <- code:get_path(), D =/= "."], true = code:set_path(Path), exit({compiler_result, compile1(List)}) end. Parses the first part of the option list compile1(Args0) -> {ok, Cwd} = file:get_cwd(), {BuildArgs, Args} = lists:partition(fun(Arg) -> Arg =:= "--build" end, Args0), ShouldBuildMultipleFiles = BuildArgs =/= [], case ShouldBuildMultipleFiles of true -> erlt_build:main(Args); false -> compile1(Args, #options{outdir = Cwd, cwd = Cwd}) end. compile1(["--" | Files], Opts) -> compile2(Files, Opts); compile1(["-" ++ Option | T], Opts) -> parse_generic_option(Option, T, Opts); compile1(["+" ++ Option | Rest], Opts) -> Term = make_term(Option), Specific = Opts#options.specific, compile1(Rest, Opts#options{specific = [Term | Specific]}); compile1(Files, Opts) -> compile2(Files, Opts). parse_generic_option("b" ++ Opt, T0, Opts) -> {OutputType, T} = get_option("b", Opt, T0), compile1(T, Opts#options{output_type = list_to_atom(OutputType)}); parse_generic_option("D" ++ Opt, T0, #options{defines = Defs} = Opts) -> {Val0, T} = get_option("D", Opt, T0), {Key0, Val1} = split_at_equals(Val0, []), Key = list_to_atom(Key0), case Val1 of [] -> compile1(T, Opts#options{defines = [Key | Defs]}); Val2 -> Val = make_term(Val2), compile1(T, Opts#options{defines = [{Key, Val} | Defs]}) end; parse_generic_option("help", _, _Opts) -> usage(); parse_generic_option("I" ++ Opt, T0, #options{cwd = Cwd} = Opts) -> {Dir, T} = get_option("I", Opt, T0), AbsDir = filename:absname(Dir, Cwd), compile1(T, Opts#options{includes = [AbsDir | Opts#options.includes]}); parse_generic_option("M" ++ Opt, T0, #options{specific = Spec} = Opts) -> case parse_dep_option(Opt, T0) of error -> error; {SpecOpts, T} -> compile1(T, Opts#options{specific = SpecOpts ++ Spec}) end; parse_generic_option("o" ++ Opt, T0, #options{cwd = Cwd} = Opts) -> {Dir, T} = get_option("o", Opt, T0), AbsName = filename:absname(Dir, Cwd), case file_or_directory(AbsName) of file -> compile1(T, Opts#options{outfile = AbsName}); directory -> compile1(T, Opts#options{outdir = AbsName}) end; parse_generic_option("O" ++ Opt, T, Opts) -> case Opt of "" -> compile1(T, Opts#options{optimize = 1}); _ -> Term = make_term(Opt), compile1(T, Opts#options{optimize = Term}) end; parse_generic_option("v", T, Opts) -> compile1(T, Opts#options{verbose = true}); parse_generic_option("W" ++ Warn, T, #options{specific = Spec} = Opts) -> case Warn of "all" -> compile1(T, Opts#options{warning = 999}); "error" -> compile1(T, Opts#options{specific = [warnings_as_errors | Spec]}); "" -> compile1(T, Opts#options{warning = 1}); _ -> try list_to_integer(Warn) of Level -> compile1(T, Opts#options{warning = Level}) catch error:badarg -> usage() end end; parse_generic_option("B", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['B' | Spec]}); parse_generic_option("A", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['A' | Spec]}); parse_generic_option("E", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['E' | Spec]}); parse_generic_option("P", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['P' | Spec]}); parse_generic_option("S", T, #options{specific = Spec} = Opts) -> compile1(T, Opts#options{specific = ['S' | Spec]}); parse_generic_option("-build-phase", T0, #options{specific = Spec} = Opts) -> {PhaseString, T} = get_option("build-phase", "", T0), Phase = case PhaseString of "scan" -> scan; "compile" -> compile; _ -> exit( {compiler_error, "Invalid --build-phase '" ++ PhaseString ++ "'; must be 'scan' or 'compile'"} ) end, PhaseOpt = {build_phase, Phase}, compile1(T, Opts#options{specific = [PhaseOpt | Spec]}); parse_generic_option("-build-dir", T0, #options{specific = Spec} = Opts) -> {BuildDir, T} = get_option("-build-dir", "", T0), BuildDirOpt = {build_dir, BuildDir}, compile1(T, Opts#options{specific = [BuildDirOpt | Spec]}); parse_generic_option("-skip-type-checking", T, Opts) -> compile1(T, Opts#options{skip_type_checking = true}); parse_generic_option(Option, _T, _Opts) -> io:format(?STDERR, "Unknown option: -~ts\n", [Option]), usage(). parse_dep_option("", T) -> {[makedep, {makedep_output, standard_io}], T}; parse_dep_option("D", T) -> {[makedep], T}; parse_dep_option("2", T) -> {[makedep, makedep2], T}; parse_dep_option("MD", T) -> {[makedep_side_effect], T}; parse_dep_option("F" ++ Opt, T0) -> {File, T} = get_option("MF", Opt, T0), {[makedep, {makedep_output, File}], T}; parse_dep_option("G", T) -> {[makedep_add_missing], T}; parse_dep_option("P", T) -> {[makedep_phony], T}; parse_dep_option("Q" ++ Opt, T0) -> {Target, T} = get_option("MT", Opt, T0), {[makedep_quote_target, {makedep_target, Target}], T}; parse_dep_option("T" ++ Opt, T0) -> {Target, T} = get_option("MT", Opt, T0), {[{makedep_target, Target}], T}; parse_dep_option(Opt, _T) -> io:format(?STDERR, "Unknown option: -M~ts\n", [Opt]), usage(). usage() -> H = [ {"-b type", "type of output file (e.g. beam)"}, {"-d", "turn on debugging of erlc itself"}, {"-Dname", "define name"}, {"-Dname=value", "define name to have value"}, {"-help", "shows this help text"}, {"-I path", "where to search for include files"}, {"-M", "generate a rule for make(1) describing the dependencies"}, {"-M2", "similar to -M, but also includes dependencies on .beam files from behaviors and parse transforms"}, {"-MF file", "write the dependencies to 'file'"}, {"-MT target", "change the target of the rule emitted by dependency " "generation"}, {"-MQ target", "same as -MT but quote characters special to make(1)"}, {"-MG", "consider missing headers as generated files and add them to " "the dependencies"}, {"-MP", "add a phony target for each dependency"}, {"-MD", "same as -M -MT file (with default 'file')"}, {"-MMD", "generate dependencies as a side-effect"}, {"-o name", "name output directory or file"}, {"-pa path", "add path to the front of Erlang's code path"}, {"-pz path", "add path to the end of Erlang's code path"}, NOTE : this option is a no - op , because erltc is escript ; on the other hand , -smp is enabled by default these days , so it is a no - op in any {"-smp", "compile using SMP emulator"}, {"-v", "verbose compiler output"}, {"-Werror", "make all warnings into errors"}, {"-W0", "disable warnings"}, {"-Wnumber", "set warning level to number"}, {"-Wall", "enable all warnings"}, {"-W", "enable warnings (default; same as -W1)"}, {"-E", "generate listing of expanded code (Erlang compiler)"}, {"-S", "generate assembly listing (Erlang compiler)"}, {"-P", "generate listing of preprocessed code (Erlang compiler)"}, {"+term", "pass the Erlang term unchanged to the compiler"} ], io:put_chars(?STDERR, [ "Usage: erlc [Options] file.ext ...\n", "Options:\n", [io_lib:format("~-14s ~s\n", [K, D]) || {K, D} <- H] ]), error. get_option(_Name, [], [[C | _] = Option | T]) when C =/= $- -> {Option, T}; get_option(_Name, [_ | _] = Option, T) -> {Option, T}; get_option(Name, _, _) -> exit({compiler_error, "No value given to -" ++ Name ++ " option"}). split_at_equals([$= | T], Acc) -> {lists:reverse(Acc), T}; split_at_equals([H | T], Acc) -> split_at_equals(T, [H | Acc]); split_at_equals([], Acc) -> {lists:reverse(Acc), []}. compile2(Files, #options{cwd = Cwd, includes = Incl} = Opts0) -> Opts = Opts0#options{includes = lists:reverse(Incl)}, case Files of [] -> ok; [File] -> compile3(File, Cwd, Opts); _ -> TODO , XXX : the reason we do not support compiling multiple .erl files in erltc , is because , as a first step , we need to know the important in Erlang v2 as we start adding more features that rely io:put_chars( ?STDERR, "erltc expects only one input file, " "but more than one input files were given.\n" ), error end. compile3(File, Cwd, Options) -> Root = filename:rootname(File), InFile = filename:absname(Root, Cwd), invoke the Erlang compiler on .erl , use the original erlc code path for case filename:extension(File) of ?SOURCE_FILE_EXTENSION -> CompileOptions = make_erl_options(Options), case catch erlt_compile:compile(InFile, CompileOptions) of ok -> ok; error -> error; {'EXIT', Reason} -> io:format(?STDERR, "erlt compiler failed:\n~p~n", [Reason]), error; Other -> io:format(?STDERR, "erlt compiler returned:\n~p~n", [Other]), error end; _ -> code : ( ) used by erl_compile . One thing we could do to make this compatible throughout is , instead of escript , use a shell script or modified erlc.c to call io:put_chars(?STDERR, "erltc does not support compiling non .erlt files\n"), error end. file_or_directory(Name) -> case file:read_file_info(Name) of {ok, #file_info{type = regular}} -> file; {ok, _} -> directory; {error, _} -> case filename:extension(Name) of [] -> directory; _Other -> file end end. Makes an Erlang term given a string . make_term(Str) -> case erl_scan:string(Str) of {ok, Tokens, _} -> case erl_parse:parse_term(Tokens ++ [{dot, erl_anno:new(1)}]) of {ok, Term} -> Term; {error, {_, _, Reason}} -> io:format(?STDERR, "~ts: ~ts~n", [Reason, Str]), throw(error) end; {error, {_, _, Reason}, _} -> io:format(?STDERR, "~ts: ~ts~n", [Reason, Str]), throw(error) end.
3c95f448c4aa23d2b7b33426f33f59ab7efa58f692ec51f3d974b7fed193bafa
ddmcdonald/sparser
ns-unknown-rd-items-phase3-10401-10800.lisp
(IN-PACKAGE :SP) (DEFPARAMETER SPARSER::*NS-RD-PHASE3-10401-10800* '("2P-MRLC" "A+P" "A-172" "A-43" "A-498" "A-C" "A-D" "A-E" "A-GVGD" "A-H" "A-allele" "A-deficiency" "A-deficient" "A-loop" "A-type" "A1" "A1-treated" "A1062T" "A1257T" "A1315T" "A1k" "A2" "A20" "A20-1" "A20-2" "A20-2-resistant" "A20-OTUmt" "A20-ZnF5-7" "A20-ΔOTU" "A20-ΔZnF" "A202T" "A279T" "A2λ" "A366T" "A431-III" "A431-P" "A491ins" "A549P" "A5780G" "A750P" "A750del" "A840T" "A859T" "AAD-COUP-TFII" "AAD-NR" "AAV1" "AAV1-tTA" "AAV1-tTA-IRES-zsGreen" "ABPA" "ABT-869" "ACAs" "ACT-1" "ACY-738" "ACh" "AD001" "ADAM" "ADHWDSKNVSCKNC" "ADRr" "ADRrE2" "AEC" "AECs" "AEW541" "AF163764.1" "AFAC10" "AFU" "AG" "AG1204" "AG1478-treatment" "AG538" "AGGTCA" "AGK2" "AI-S" "AIB" "AIDS-infected" "AIEC" "AIIB2" "AJ289875.1" "AJCC" "AJK" "AK027769" "AKP" "AKTi" "AKTi-1" "ALIS" "ALMS1" "AM" "AMBRA" "AMP-K" "AMs" "ANRASSF1" "AO" "AP-1-like" "AP-1-luc" "AP-180" "AP-1A" "AP-1B" "AP-23573" "AP-MS" "AP12816a" "AP2γ" "AP4+RAS" "AP4-ER" "APBT2" "APBT6" "APLP1" "APPPPS1" "APPPS1" "APRs" "APSMs" "APV" "AQOA-A" "AR-N" "AR-co-activator" "AR-enhanced" "AR-gene" "AR-mediated" "AR-miR-21" "ARD527" "ARE-luciferase" "ARHGEF33" "ARKO" "ARMS–Scorpion" "ARMS–scorpion" "ARN-509" "ARNT1" "ARPCs" "ARRY-438162" "ARTPs" "ARVO" "AR–DNA" "AS-ODN" "AS-PCR" "ASC-J9" "ASCA" "ASC–J9" "ASP–PCR" "ATCC" "ATG6" "ATM-2" "ATM-and-Rad53-like" "ATM-pathway" "ATMi" "ATN1" "ATN2" "ATP-citrate" "ATR-dependent" "ATR-serine15" "ATRO" "ATS" "ATTG" "ATXN2" "AUF" "AX" "AY034471" "AY326428.1" "Ab708" "Abcam" "Abcl2" "Abnet" "Abr" "Ac-TDG" "AcK" "Actin-dependant" "Ad-GFP" "Ad-IκB" "Ad-PTEN" "Ad-Skp2" "Ad-ZBP-89" "Ad-β-Gal" "AdCARas" "AdCASrc" "AdDUSP4" "AdJLB1" "AdSpry4" "Adeno-Null" "Affymetrix" "Africa" "African" "African-American" "African-Americans" "Africans" "AgRP" "Agouti" "AhR-p38-C" "Akt-activation" "Akt-fibroblast" "Akt1" "Akt1promoted" "Alaskan" "Alb-cre" "Alexa" "Alexa488" "Alu" "Alzheimer" "Alzheimer´s" "Alzihamer" "America" "American" "Americans" "Ammirante" "Amot" "Amot-Yap" "Amot-p130N" "Amots" "Amsterdam" "Ant-D-loop" "Antigen" "Antineutrophil" "Api5" "Arf-null" "Arg-Val-Leu" "Arg-rich" "Arg194Trp" "Arg399Cln" "Arg399Gln" "Arizona" "Arp2" "Arq501" "Arq761" "Asian" "Asians" "Atox-1" "Autoantigen-1" "Aux1–Swa2p" "Avl9" "Avl9p" "Azare" "A + " "Aβo–PrP" "Aβ–PrP" "Aγ" "Aδ" "A–C" "A–S1C" "A–S4D" "A–S6E" "A→C" "A→G" "B-ATF" "B-D" "B-F" "B-acute" "B-boxes" "B-catenin" "B-family" "B-form" "B-lymphoid" "B-lymphoma" "B-lymphomas" "B-to-T-cell" "B-to-T-cell-connecting" "B-type" "B1" "B10" "B2" "B3" "B5" "B6" "B721.221-GFP-H-RasG12V" "B721.221-cell" "BACH1-FBXL17" "BACH1-MAF" "BAEC" "BAK1del" "BAK1mut" "BAK1wt" "BAPTA-AM" "BAW667" "BAW667+PPY-A" "BAX" "BBLF2" "BCAAs" "BCL-xl" "BCL11A-XL" "BCL2-immunoreactivity" "BCL2-like" "BCL2-negative" "BCL2-positive" "BCL7A" "BCR-ABL1" "BCSCs" "BDCA3" "BEMAD" "BGK" "BH1" "BH3-domain" "BH3-mimetic" "BH3-mimetics" "BH3-only" "BHA2.1" "BHT" "BILAG" "BIR2" "BIR3" "BIRB0796" "BJ" "BK" "BLBCs" "BM73" "BME" "BMIs" "BMI≤24" "BML" "BML-1" "BML-11" "BML-5" "BML-7" "BML281" "BMPR-1A" "BMPR-1B" "BMPRs" "BOADICEA" "BOLERO2" "BPH1" "BRAF+PTCs" "BRAF-AA" "BRAF-ED" "BRAF-genotype" "BRC" "BRCA2and" "BRCAPro" "BRCT–BRCT-mediated" "BRID" "BSCL1" "BSCL1-4" "BSCL3" "BSCL4" "BSE" "BTB474" "BUZ" "BXPC3s" "BZ-9000" "Background" "BafA" "Bak-independent" "Bannayan-Zonana" "Barbano" "Barry-Hamilton" "Basal" "Basel" "Basso" "Bcl" "Bcl-2-antagonist" "Bcl-XL" "Bcl-xl" "Bcl2" "Bcl2-family" "Bead-bound" "Beclin1-core" "Begg" "Begger" "Belfast" "Benjamini" "Benjamini-Hochberg" "Bennett" "Benvenuti" "Beva" "Bgl" "Bgl3" "BhGLM" "Bi" "Bi-transgenic" "BiFC" "Biesecker" "Bim" "Bim-S" "Bim-interaction" "Bio" "Bio-Rad" "BioRad" "Biosystems" "BirA" "BirA-tag" "Birmingham" "Bitplane" "Black" "Blood-borne" "Bmi1" "Bmi1-self" "Bmi1-targeting-shRNA" "Bolero-2" "Bonferroni" "Boroumand-Noughabi" "Bortezomib-treatment" "Boyden" "Bp65" "Br426" "Br731" "Branched-chain" "Brandwein" "Brandwein-Gensler" "BrdU-label" "Break-Induced" "Brenner" "Breslow" "Bristol" "Broader" "Btz" "Burkitt" "Bx" "Byers" "B–2D" "B–C" "B–D" "B–H" "C-C" "C-G" "C-Luc" "C-NHEJ" "C-NHEJ-dependent" "C-NHEJ-mediated" "C-TAD" "C-TADs" "C-allele" "C-allelecontaining" "C-helix" "C-labelled" "C-lobe" "C-lobes" "C-luc" "C-mass" "C-region" "C-sections" "C-src" "C-terminally" "C-treated" "C-type" "C1" "C1-mediated" "C10orf26" "C139A" "C147A" "C181S" "C184S" "C186S" "C18LL" "C1orf24" "C2" "C2-CH" "C2-domain" "C28" "C3" "C35-co-transfected" "C4" "C450ins" "C472S" "C540ins" "C56BL6J" "C57BL6" "C6" "C6orf47" "C779A" "C782A" "CAB" "CAIS" "CALHM1" "CALHM2" "CALHM3" "CALPAIN" "CALPAIN7" "CALR3" "CAP8AP2" "CARD14" "CARDIA" "CARN-like" "CARe" "CASMC" "CASP8AP2" "CASrc" "CC+GC" "CCAAT" "CCCG" "CCFR" "CCG-1423" "CCL" "CCL-20" "CCL2ab" "CCR2S" "CCR2atg" "CCT007093" "CCTNs" "CD-FBS" "CD-associated" "CD11cCre" "CD28-induced" "CD28RE" "CD44+" "CD44S" "CD44V" "CD44V6" "CD8-Nef" "CDC42BPG" "CDH-1" "CDH-2" "CDK4-6" "CDK4-D-type" "CDK6R31C" "CEC" "CED-10" "CELSR1" "CEP128" "CEP17" "CEP6" "CEP8" "CEU" "CFSs" "CFTR-172" "CFTR-172-induced" "CG" "CG-E" "CGAG" "CGH-microarrays" "CGL" "CH11" "CH99021" "CHI3L1" "CHME3" "CI1040" "CIA2" "CIA2A-CIA1" "CIA2A-IRP2" "CIA2B-CIA1-MMS19" "CIA2B-MMS19" "CICs" "CID-MS" "CIN3" "CINII" "CJO" "CK-1" "CK-19" "CK-2" "CKIδ" "CL" "CLB-Bar" "CLB-Ga" "CLB-Re" "CM5-postive" "CMV-driven" "CNNM2" "CNQX" "COG" "COLD-PCR" "COMPASS" "COPII" "COUP" "COUP-TF" "COUP-TFs" "COUPTF-II" "COX-2-765" "COX-IV" "CP-868,596" "CPSCs" "CR-1" "CR-2" "CRAC" "CRCC" "CREB-like" "CRIB" "CRL-5872" "CRM-197" "CRN2" "CRS-PCR" "CRs" "CSC-like" "CSCs" "CSPCs" "CSPs" "CT+CC" "CT+TT" "CTCE-9908" "CTCs" "CTG" "CTNNA3" "CTTNB1" "CVB3" "CVs" "CWWG" "CYP2C19*2" "Cadherin" "Calphostin" "CamKII-tTA" "CamKIIα-tTA" "Campenot" "Canu" "Capsulin" "Carlo" "Case1" "Case2" "Casein" "Caucasian" "Caucasians" "Cavin-1" "Cbp" "Cbp\\PAG" "Cd12" "Cdc25-EF" "Cdc42" "Cdk1" "Cdk11" "Cdk2" "Cdk4" "Cdk7" "Celsr" "Celsr1" "Cernunnos" "Cfd1-Nbp35" "ChIP" "ChIP-PCR" "ChIP-on-Chip" "ChIP-on-chip" "ChIP-qPCR" "ChIP-reChIP" "Chan" "Chang" "Chc1-RFP" "Chemically-engineered" "Chen" "Chi-square" "Chi-squares" "Chng" "Chompret" "Chrom" "Chung" "Cia2" "Cip" "Clark" "Class-I" "Classical-EMT" "CldU" "Clinico-pathological" "CoIP" "CoMCont" "CoMTb" "CoRNR" "CoRNR1and" "CoRNR2" "ColE1" "Collins" "Colorado" "CompPASS" "Conclusion" "Conclusions" "Congo" "Coomassie" "Cooperativity-dependent" "Cortot" "CovalAb" "Cox-regression" "Coxsackievirus" "CpG-dense" "CpG-island" "Cr-fragment" "Cre" "Cre-driver" "Cre-negative" "Creutzfeld-Jacob" "Crohn" "Cross-regulation" "Crumb3" "Crus" "Cruz" "CtBP24" "CtIP-mediated" "Ctr" "Ct∼12" "Cu" "Cul1" "Cul1-Skp1-Fbw7" "Cullin-RING" "Cullin-Ring" "Cy1" "CyclinD1and" "CyclinD1as" "Cys-LT" "Cys-LT-mediated" "Cys-LTs" "Cys-X2-4-Cys-X35-50-Cys-X2-His" "CysLTR" "Cysteine-to-alanine" "Cysteinyl" "Cα" "C–E" "C→A" "C→G" "C→T" "D-SZ" "D-box" "D-loop" "D-motif" "D11" "D146N" "D1R" "D1R-GFP" "D2" "D2-GFP" "D3" "D4" "D4D6" "D4GDI" "D4Z4" "D5" "D5F3" "D770GY" "DA-like" "DALIS" "DALS" "DAVID" "DBN-S647" "DCIS-like" "DCN1-RBX1" "DCP-LA" "DCR" "DCRs" "DDK" "DDR-proficient" "DEF-A" "DGV" "DH" "DHO" "DHX30" "DIPGs" "DIV" "DK4" "DK6" "DM-W" "DM24h" "DMTs" "DNA-DNA" "DNA-DSB" "DNA-Damage" "DNA-Damage-Induced" "DNA-TDG-p300" "DNA-damage-independent" "DNA-damage-induced" "DNA-mismatch-repair" "DNA-protein" "DNA–FLA" "DNA–protein" "DNCsk" "DNP-HSA" "DNQ" "DNSrc" "DNaseI" "DO1" "DOI" "DOPAC" "DPO-PCR" "DPYD-MIR137" "DQ-BSA" "DQ™-Red" "DR-4" "DR-GFP" "DR5-like" "DSB-R" "DSBs" "DSGxxS" "DSTYK" "DU145" "DU145Kd" "DUF1669" "DUF59" "DUX4-fl" "DUX4-s" "DZNep" "Dako" "Daniele" "Danish" "Danvers" "Daugaard" "De-repressing" "Defazio-Eli" "Dendra-tau" "Denmark" "Deshaies" "Design" "Dex" "Dex-inducibility" "Dhand" "DiYF" "DiYF-knockin" "Diamond-Blackfan" "Dipeptidyl" "Discs" "Doebele" "Donnell" "Double-strand" "Down-modulation" "Down-stream" "Doxo" "Dre2" "DsRed-Monomer-tagged" "Dual-priming" "Dulbecco" "Duval" "D–5G" "D–E" "D–S1F" "E-Abstract" "E-CMF" "E-GFP" "E-MTAB-37" "E-T-CMF" "E-box" "E-boxes" "E-cadheirn" "E-cadherin-expressing" "E-cadherin-negative" "E-guggulsterone" "E-value" "E-x-x-x-x-C" "E10a" "E10del" "E10del2" "E17b" "E2-promoter" "E2A-HLF" "E2F-7" "E2F-7-bound" "E2F-7-depleted" "E2F-8" "E2F-controlled" "E2F1-8" "E2F1-dependent" "E2F1-induced" "E2F1-inducing" "E2F1-mediated" "E2F1-negative" "E2F1-positive" "E2F1-target" "E2F1and" "E2F3a" "E2F3b" "E2F6-dependent" "E2F6-depleted" "E2F7a" "E3-ligase" "E3-ligase-like" "E3-ligases" "E3-ubiquitin" "E3RS" "E4" "E4BP4" "E5" "E572A" "E6" "E6-associated" "E6-induced" "E6-mediated" "E6-p53-p300" "E6-positive" "E616del" "E64c" "E6BP" "E6L50G" "E6a" "E7" "E709A+G719C" "E746-A750" "E7del" "E8" "E8.0" "E8.75" "E9.5" "EA1" "EBPa" "EBPb" "EBPd" "EC1-4" "EC1-EC5" "EC2" "EC50" "ECFP" "ECFP-Mcl1L" "ECFP-Mcl1L-overexpressing" "ECM+C" "ECM-adhesion" "ECOG" "ED" "EE" "EEG" "EFGR" "EGF-ligand" "EGF-like" "EGFP-tag" "EGFR-MEK-dependent" "EGFR-P" "EGFR-PI3K-dependent" "EGFR-dependently" "EGFR-family" "EGFRvIII" "EGFRwt" "EGFRwt-EGFRvIII-RIP1" "EGR" "EH1" "EH2" "EIIIB" "EL11-26" "EL12-15" "EL12-58" "ELISAs" "EMEA" "EMT-TF" "EMT-TF-induced" "EMT-TFs" "EMT-like" "EMT-mRNA" "EMT-phenotype" "EMT-targeting" "EMVs" "EN2" "ENST00000527240" "EP" "ER+" "ER++" "ER+BC" "ER+BC-treated" "ER+positive" "ER+ve" "ER-E2F1" "ER-E2F1cells" "ER-signalling" "ER-to-Golgi" "ER0" "ERAP1a" "ERAP1b" "ERE2-TK-LUC" "EREs" "ERK-independent" "ERS" "ERα+Ets1" "ERα+Ets1+estradiol" "ERα+estradiol" "ESCRT" "ESCRTs" "ESR1-TA" "ET-CMF" "EUFA-423" "EURTAC" "EV-C2" "EV-C4" "EVCT" "EVCTs" "EVH1" "EX-EGFP-M02" "EX-EGFP-M02-vector" "EYFP" "EYFP-Mcl1L" "East-Asian" "Edinburgh" "Edmonson-Steiner" "Egger" "Eighty-nine" "Eighty-one" "Eighty-seven" "Eighty-six" "Ejlertsen" "Elston" "Eluates" "EnSCs" "Enhancer-Promoter" "EphA" "EphA2-CAV1" "EphA2-Kinase" "EphA2-host" "EphA2-immunoprecipitates" "EphA2-kd" "EphA2-sterile" "EphA2-ΔKD" "EphA2-ΔSAM" "EphA2sh-RNA" "Ephrin-EphR" "Epicardin" "Epithelial-Mesenchymal" "Epithelial-mesenchymal" "Epithelial-to-Mesenchymal" "Epithelial–mesenchymal" "Epithelium" "Epsin" "Epsin-15" "Epsin15" "Eptsein-Barr" "ErB" "ErB3" "Erb2-driven" "ErbB" "ErbB2-dependent" "ErbB2-driven" "ErbB2-expressing" "ErbB2-independent" "ErbB2-induced" "ErbB2-only" "ErbB2-overexpressing" "ErbB2-positive" "ErbB2-related" "ErbB2-specific" "ErbB2-transformed" "ErbB3" "ErbB4-induced" "Erk1-negative" "Erk1-positive" "ErlR" "Erythrocytes" "Ethylene-diamine" "Ets1" "Ets1-expressing" "Ets2" "Europe" "European" "European-descent" "Europeans" "Evans" "Ex5-MBNL1" "Exo70p" "Exo84p" "Exome" "Eμ-myc" "E–6G" "E–S2H" "F-BAR" "F-BAR–FX" "F-SNP" "F1" "F2" "F3" "F4" "FAD" "FAIRE" "FAM83" "FAM83D" "FAS-receptor" "FASL" "FAs" "FBCs" "FBLX20" "FBP-1" "FBS-replete" "FBXL1" "FBXL11" "FBXL6" "FBXL7" "FBXLs" "FBXW" "FBXW1" "FBXW7α" "FBXWα" "FC=1.19" "FC=1.2" "FC=1.4" "FEF" "FEV1" "FFLs" "FGFR-2-III-b" "FGFR-2-IIIb" "FGFR-2-IIIb-specific" "FGFR-3" "FGFR-IIIb" "FGFR-invariant" "FGFR3-Capan-2" "FGFR3-IIIb" "FGFR3-IIIc" "FGFR3-IIIc-KD" "FGFR3K" "FGR2b" "FH" "FICZ" "FIF" "FISH" "FK-1" "FK1" "FK506-FKBP12" "FKBP12-rapamycin" "FKSG30" "FLA9500" "FLAG" "FLAG-BCL11A-XL" "FLAG-DBN" "FLAG-EL" "FLAG-LMW-E" "FLAG-hSIRT1-FL" "FLAG-hSIRT1-NT" "FLAG-tag" "FLICE-like" "FLJ36031-PIK3CG" "FLT3-ITD" "FLT3-ITD-induced" "FLU-inducedγ-H2AX" "FLX-treated" "FMG" "FMO2" "FN-null" "FNAB" "FNAs" "FOLFOX6" "FOXO" "FOXO4a" "FRA1-WT-BS" "FRA1-wild-type-binding" "FRA16D" "FRA2C" "FRA2Ccen" "FRA2Ctel" "FRCn" "FREEC" "FRG" "FRG1" "FRG2" "FRMP" "FS" "FSHD-1" "FSHD-2" "FSK" "FSXXLXXL" "FTS-1" "FU" "FX" "FXRXLRXL" "FXRα" "Factor-Kappa" "FadA" "FadAc" "FamHS" "FancD2-mUb" "Fbw" "Fbw7-directed" "FcϵRI" "Fe" "Fe-only" "Features" "Fes" "Fifty-six" "Fine-mapping" "Fine-needle" "Fischer" "Fish-oil" "Five-fluorouracil" "Flag" "Flag-DBN" "Flag-E6" "Flag-HA-tagged" "Flag-M2" "Flag-Mst2" "Flag-Polκ" "Flag-REV1-expressed" "Flag-Ubi" "Flag-Yap" "Flag-tag" "Flotilin-1" "Flow-cytometric" "Fluor-488-conjugated" "FoSTeS" "Follow-up" "Forty-eight" "Forty-five" "Forty-four" "Forty-one" "Forty-three" "FosL" "Fourier-transform" "Foxo" "Foxo33" "Foxo3a-high" "Foxo3a-low" "Foxp3" "France" "Fraumeni" "French" "Frey" "Fs" "Fuhrman" "Functional" "Fura-2-AM" "FusionSeq" "Fyn" "F–S6H" "G-486T" "G-6-Pc" "G-C" "G-DNA" "G-KAP1" "G-LISA" "G-Luc" "G-YL" "G-agarose" "G-allele" "G-coupled" "G-ratios" "G-substate" "G-substates" "G-substrates" "G0" "G0-G1" "G0-like" "G1" "G1-G3" "G1-S" "G1-to-S" "G10" "G1–S" "G2" "G242fs" "G2E" "G2M" "G2–M" "G3-unifocal" "G6P" "G719A" "G719X" "G724fs" "G770GY" "GA" "GADD45α" "GAL4-PNR-mediated" "GAS-like" "GBCs" "GBM12" "GBM13" "GBM9" "GBM9-NS" "GBM95" "GCHM" "GCN4" "GCTA" "GDF" "GDZ" "GEF-dead" "GEF-induced" "GEF-mediated" "GEF40" "GENOA" "GEO2R" "GEO45130" "GFAP-IκBα-dn" "GFAP-Iκbα-dn" "GFP-DFCP1" "GFP-Exo70-induced" "GFP-Exo70-positive" "GFP-FRMD7-transfected" "GFP-H-Ras-enriched" "GFP-H-RasG12V" "GFP-H-RasG12V-labeled" "GFP-H-RasG12V-rich" "GFP-PAK1-S223A" "GFP-PTENΔD" "GFP-REV1-UBM" "GFP-RNF38ΔRING" "GFP-SCRIB" "GFP-Snc1" "GFP-Snc1p" "GFP-lifetimes" "GFP-mut3" "GFP-tag" "GFPRNF38" "GGC-GAC" "GGT-GTT" "GH-hPrlR" "GH-promoter" "GI" "GIP-receptor" "GL" "GLI1ΔNES" "GLI1ΔNLS" "GNE-929" "GOS-28" "GRC-1" "GRE" "GREs" "GSCs-by" "GSE1159" "GSE12417" "GSE15434" "GSE17317" "GSE19784" "GSE23022" "GSE25021" "GSE28198" "GSE39314" "GSE41322" "GSE46695" "GSE49046" "GSE6365" "GSE6477" "GSE6891" "GSE8611" "GSK" "GSK3β-CA" "GSK3β-KD" "GST-A20-ZnF5-7" "GST-A20-ZnF5-7mt" "GST-ATM-2" "GST-EC5" "GST-Homer1c" "GST-Hrr25" "GST-LBD" "GST-Lst1p" "GST-Lyn-SH3" "GST-Nyv1p" "GST-RASSF5-SARAH" "GST-RNA" "GST-SOCS4-SH2" "GST-SOCS5-SH2" "GST-Sec22p" "GST-Sec23p" "GST-Sec24p" "GST-Sec31p" "GST-Sec9c" "GST-Snc2p" "GST-Sso2p" "GST-TB" "GST-ZO-1-K253A" "GST-cIAP" "GST-hSIRT1-NT" "GST-pull" "GST-pulldown" "GT-1" "GT19" "GT6" "GT7" "GTIC" "GTICs" "GTIIC" "GTPase-RhoA" "GTs" "GUVs" "GW" "GWAS-PheWAS" "GWASs" "GX" "GX15-070" "GXP" "GYJ-A" "GZBDK" "GZBDZ" "GaQ3-treatment" "Gag-Pol" "Gain" "Gain-of-Function" "Gain-of-function" "Gallbladder" "GenBank" "GeneCards" "GeneChip" "Genentech" "Genome-wide" "Genotype-phenotype" "Gensini" "Gensler" "German" "Germany" "Gerota" "Glc7p" "Gleason" "Gli" "Glomus" "Glutathione-Sepharose" "Gly1121ValfsX3" "Gly158-Asp172" "GoldenGate" "Gottle" "Grp" "Grp78" "Guinier" "Gupta" "Gy" "Gγ" "G–A" "G–C" "G–T" "G–agarose" "G→A" "G→C" "G→T" "H&E" "H-14-3-3zeta" "H-2Kb-tsA58" "H-E" "H-L" "H-MADD3A-YFP" "H-Ras-GTP" "H-RasG12V" "H-RasG12V-labeled" "H-WtMADD-YFP" "H-bonds" "H1" "H113A" "H115A" "H168R" "H179Y" "H1975" "H1993" "H1H1" "H1N1" "H2" "H2009" "H2Bub" "H2Bub-dependent" "H2Bub-independent" "H2H2" "H3" "H3-K4" "H3-T11" "H3-dependent" "H3-histone" "H3-like" "H37" "H37Ra" "H3K18" "H3K18ac" "H3K27" "H3K36" "H3K4Q" "H3K4m2" "H3K4m3" "H3K9" "H3KR" "H3R2" "H3ac-SET1C" "H4" "H4K20" "H4KR" "H4Lys12" "H538A" "H83,86L" "HA-E2F1" "HA-Mst2" "HA-Ub-K63-only" "HA-Ubi" "HA-YAP" "HA-cCbl" "HA-tagged-USF2" "HADDOCK" "HAECs" "HAFoxp3" "HAdV-C5" "HB-239" "HBII-239" "HBS+STAT3" "HC" "HCASM" "HCASMC" "HCC728" "HCC829" "HCIP" "HCIPs" "HCT116Bax" "HCT116KRAS" "HD" "HDFs" "HDMECs" "HEAT" "HEC-50" "HECD-1" "HELQ-1" "HELQ-BCDX2" "HELQ-defective" "HER" "HER-1–4" "HER-2+" "HER-2-low" "HER1-3" "HER1-4" "HER1–4" "HER2-negative" "HER2-normal" "HER2Bi" "HER2Bi-ATC" "HER2Bi-Ab" "HER2Bi-armed" "HER3phosphorylation" "HERi-HERj" "HFD" "HFSN1" "HG-U133" "HGGs" "HGMD" "HGS-OvCa" "HIBECs" "HIF" "HIF1+USF2" "HIF1-α" "HIF1α+STAT3C" "HIF1α+USF2" "HIF1α-C" "HIF1α-N" "HIF1αDPA" "HIF1αTM" "HIF1αTM+STAT3C" "HIF1αTM+USF2" "HIF2" "HIF2+USF2" "HIF2-mediated" "HIF2α-C" "HIF2α-N" "HIF2αDPA" "HIF2αTM" "HIF2αTM+STAT3C" "HIF2αTM+USF2" "HIFα" "HIFα112" "HIFα122" "HIFα211" "HIFα221" "HIV+IVDU" "HIV+IVDUs" "HIV-Tat" "HIV-protein" "HIV-proteins" "HLA-DRB9" "HLH" "HME-Snail" "HMLE-Slug" "HMLE-Snail" "HMLE-Snail-ER" "HMLE-Twist" "HMLE-Twist-ER" "HMSC" "HMSCs" "HMVEC-d" "HNPC" "HOSE11-24-96" "HOSE17-1" "HOSE96-9-18" "HOXA6" "HP-1" "HPASMCs" "HPFS" "HPV16-positives" "HPV16-transgenic" "HR" "HR-HPV" "HR-HPVs" "HR10.198" "HR2.765" "HR231" "HR=0.47" "HR=1.0" "HR=1.2" "HR=1.3" "HR=1.44" "HR=1.51" "HR=1.53" "HR=1.54" "HR=1.9" "HR=2.1" "HR=4.2" "HR=6.3" "HRG-beta" "HRs" "HSM" "HSP-27" "HSP70-Cluc" "HSTF-1" "HSV-1" "HT12" "HTB175" "HTC116" "HTC75" "HTM" "Haas-Kogan" "Hace" "Hace1-HECT" "Halotag-p62" "Han" "HapMap" "HapMap3" "Hardy-Weinberg" "Hardy-Zuckerman" "Hardy–Weinberg" "Harvey" "Hawaiian" "Hb" "Hct" "HeCOG" "HeLa-OCT4" "Helicase" "Helicase-like" "Hematoxylin–eosin" "Heme" "Hepa" "Hetero-oligomerization" "Heterozygotes" "Hh" "Hi-C" "High-grade" "High-risk" "Hipple–Lindau" "Hippo" "Hippo-RASSF1-LATS" "Hippo-Salvador" "Hippo-Yap" "Hippo-responsive" "His-Beclin1" "His-E1" "His-Flag-Ubi" "His-GLI" "His-GLI1" "His-Hsp70" "His-Plk1" "His-Stub1" "His-Ubc5Hb" "His-V5-XPA" "His-hTDG" "His6" "His6-Sso1p" "Hispanic" "Histoscores" "Hmga" "Hnf" "Hnf-1α" "Hnf-3α" "Hnf-3β" "Hnf-4α" "Hochberg" "Hodges" "Hodgkin" "Hoechst" "Holliday" "Holst" "Homer" "Homer1" "Homer1a" "HomerEVH1" "Homma" "Homo-or" "Homozygotes" "Hong" "Hoogsteen" "Hrr25p" "Hsa-miR-105" "Hsp70" "Huggins" "Human610K" "Hypercalciuria" "Hz" "I+II" "I-BAR" "I-III" "I-OMe-AG538" "I-SceI" "I-SceI-based" "I-SceI-induced" "I-SceI-transfected" "I-Tfn" "I-V" "I-map" "I-transferrin" "I-x-V" "I2" "I230A" "I8V" "IAA" "IASLC" "IAV" "IB4-immunoreactive" "IBD-U" "IBDU" "IBS" "IC-NST" "IC50" "IC90" "ICBP50" "ICOS-L" "ICOS-L-mIgFc" "ICP34.5" "ICP6" "ID" "IDBCs" "IDCs" "IECs" "IEF" "IFN-g" "IFN-ɣ" "IFN-κ" "IFN-λ" "IFN-λR" "IGF-1-induced" "IGF-1-signaling" "IGF-1R-activated" "IGF-1was" "IGFR-1R-mediated" "IHF" "IIA" "III+IV" "III-map" "IIICS" "IIIα" "III–IV" "IIa" "IIα" "II–IV" "IKK-ε" "IKKβ" "IL-1R-dependently" "IL-36γ" "IL-6-receptor-mediated" "IL-6Rα" "IL2-κB–DNA–protein" "IL4production" "ILBCs" "IN" "IN-LEDGF" "INF-α-induced" "INGI" "INGI-FVG" "INGI-VB" "INSS" "IOVS" "IP+WB" "IP-kinase" "IPG-IEF" "IPQA" "IPs" "IQ" "IQR" "IR-A" "IR-A-mediated" "IR-A–pcDNA3.1" "IRES2" "IR–B" "ISG" "ISGF3γ" "ISGs" "ISKS" "ISceI" "ISceI-cleavage" "ITC" "IVDUs" "IVIG" "IVIS-100" "IVS" "IVS17+1G" "IVa2" "Ibadan" "Ig-κB" "IgA" "IgAλ" "IgGλ" "IgVH" "Igf1rβ" "IkappaA-kinase" "Ikeda" "Illumina" "ImageJ" "Imaris" "Imetelstat" "Immuno-cytochemical" "Immuno-isolation" "Importin-α" "Improta" "Indian" "Indians" "Insulin-induced" "Inter-individual" "Inter-observer" "Intra-aortic" "Invitrogen" "Irt-like" "Iss1p" "Iwig" "IĸBα" "Iκ-Bα" "IκBα-dn" "I–III" "I–IV" "I–VI" "I∼II" "J3" "J82-bladder" "JAH" "JAM-A–null" "JAMM" "JCF" "JCL" "JEFF" "JFF" "JFH1" "JFP" "JGW" "JH" "JH1" "JHS" "JHS-ARIC" "JJC" "JK" "JPT" "JPX-9" "JS-31" "JSF" "JTV-1" "JUND" "JWF" "JZ" "Jacobs" "Jak-STAT3" "Jak1and" "Japanese" "Jedi" "Jedi-1" "Joazeiro" "Johansson" "John-Aryankalayil" "Johnson" "Ju-Seog" "J–S2L" "K-I" "K-MT" "K-cells" "K-linkage" "K-linked" "K120" "K164" "K18" "K203" "K23" "K23V" "K259" "K2R" "K3" "K3-MARCH" "K3-treated" "K370" "K486" "K4E" "K540A" "K567X" "K571A" "K5E" "K5N" "K6" "K63" "K63-polyUb" "K72H" "K777" "K8" "KAP-1-depleted" "KC3" "KCl-pretreatment" "KD" "KFK" "KIM-PTP" "KIM-peptide" "KIMKIS" "KP46" "KR" "KRAB" "KRAB-ZFP-associated" "KRF-1" "KS" "KTS" "KV" "KX" "KXGS" "KXS" "KXXS" "KYL" "Kagan" "Kanei-Ishii" "Kaplan" "Kaplan-Meier" "Kaplan–Meier" "Kaposi" "Ki-67" "Ki-67-positive" "Ki67" "Kim" "Kip" "Kirsten" "Knock-down" "Knock-in" "Knocking-down" "Korah" "Korea" "Korean" "KpnI" "Kruppel" "Kruskal-Wallis" "Kruskal–Wallis" "Krüppel" "Ku" "Ku-hTR" "Kuo" "Kuriyan" "K–M" "K–S2P" "L-Dopa-induced" "L-PHA" "L-X-L-X-φ" "L-type" "L1" "L1-5" "L1-RTP" "L1-RTP-inducing" "L19" "L19F" "L2" "L262-Q264" "L269fs" "L2K" "L2K+pcDNA3.1" "L2K+pcDNA3.1-miR-124" "L3" "L319A" "L38" "L38I" "L4" "L4-100K" "L4-22K" "L4-33K" "L4P" "L5" "L56Br-1" "L747-S751" "L747-S752" "LBDs" "LC3-I" "LC3-punctae" "LC3B-I" "LC3B-II" "LC3II" "LCB" "LCDD-LCs" "LCLs" "LE" "LEF" "LEF-Luc" "LETFs" "LF82" "LFB" "LFL" "LGL2" "LGR" "LGRs" "LIFRβ" "LINE-1" "LISA" "LL360" "LLL12" "LM609" "LMP2A" "LMP2B" "LMW" "LMW-E" "LMW-E-expressing" "LMW-E-overexpressing" "LMW-E–expressing" "LNCaP" "LNCaP-LUC" "LNGFR" "LNGFR-BirA-tag" "LNT14" "LOC10013023" "LOC84989" "LOVD" "LPMf" "LPR" "LPS" "LPS-Stub1-induced" "LPxY" "LPxY-PPxY" "LQ" "LQQLL" "LR-Test" "LRP-ICD" "LRP1-ICD" "LRRC8s" "LRT" "LRY" "LRs" "LTE" "LTGCs" "LTR-luc" "LTs" "LTβR-stimulation-induced" "LUVs" "LUX-Lung" "LV-K" "LV-Stub1" "LV-WT" "LXRα" "LXXXLXXXI" "LY1" "LY29004" "Lab-Tek" "Lai" "Lapachone" "Larger-scale" "Latino" "Lats1" "Lats1-Yap" "Lauren" "Layton" "Ldb" "Ldb17p" "Leica" "Let-7" "Let-7a" "Let-7c" "Leu858→Arg" "Leucine-insulin-mTORC1" "Lewy" "LexA-RID1" "LexA-RID2" "Lgl" "Lgl1" "Lgl3SA" "Li" "Li-Fraumeni" "Li-Fraumeni-like" "Lieberman-Aiden" "Lifeact" "Lifeline-basal" "LigI" "Lindau" "Lingo-1" "Lipid" "Lipid-Raft" "Liposomes" "Lipotoxicity-induced" "Liu" "Liu-Bryan" "Live-dead" "Li–Fraumeni" "Li–Fraumeni-like" "Loberg" "Log-Rank" "Log-rank" "Lohr" "Long-range" "Lopez" "Lopez-Andres" "Lopez-Knowles" "Lopez-Vicente" "Loss-of-function" "Low-dose" "Lu" "Luc" "Luminex" "Lunardi" "Luo" "Luu" "Lv-MEK" "LxxLL" "Lyn" "Lys-147" "Lys-172" "Lys-382" "Lys-433" "Lys-788" "Lys-849" "Lys-Gly" "Lys48" "Lys48-linked" "Lys63-linked" "Lys63-ubiquitin" "Lysm" "Lyz2" "L–S6O" "M-IgVH" "M0" "M14" "M1k" "M1λ" "M2-like" "M210B4" "M227A" "M2λ" "M5" "M6" "MADS" "MADS-box" "MAL" "MAP-K" "MAPK-pathway" "MAPK-pathways" "MAPK4K" "MAPKK-like" "MAR" "MAS" "MB-435S" "MBCs" "MBII-239" "MCF-7-MEK5-ERK5-shRNA" "MCF10ADCIS" "MCF7-Cd" "MCF7-Cd2" "MCF7breast" "MDA-MB" "MDA-MB-231-D3H2-LN" "MDA-MB-231-PELP1-shRNA" "MDA-MB-231-PELP1shRNA" "MDA453R" "MDAMD-231-PELP1shRNA" "MEDLINE" "MEF2s" "MEGS" "MEKi" "MEN5" "MEN8" "MESA" "MHC" "MHC-1" "MHC-I" "MHCCLM3" "MILE" "MILLIPLEX" "MIR-106B-25" "MIR-17–92" "MIR106A" "MIR106B" "MIR1296" "MIR137" "MIR143-NOTCH" "MIR143-NOTCH2" "MIR143-fusion" "MIR168a" "MIR93" "MK" "MK-571" "MK2i" "MKC-LC" "MKI" "MKK3b" "ML-120B" "ML171" "MLLC" "MM" "MM-BIR" "MM231" "MM231-LN" "MMCLs" "MMTV-ErbB2" "MMTV-PyMT" "MMTVneu" "MO7e" "MONO-MAC6" "MOPC-141" "MPMQ" "MRCKβ" "MREC" "MRL" "MRLCs" "MRTF-B" "MS" "MSCV-driven" "MSFM" "MSH2-null" "MSI-H" "MST2" "MT-1A" "MT-1E" "MT-2A" "MT-3" "MTEP" "MTF" "MTF-1" "MTS" "MUC5AC-negative" "MV-1" "MVs" "MYC+RAS" "MYC-protein-expressing" "MYC-protein-negative" "MYC-protein-positive" "MYCN-protein-negative" "MYCN-protein-positive" "Mal-PEGylation" "Manders" "Mantel-Cox" "Mantel-Haenszel" "Map" "Materials" "Matias-guiu" "Matsukawa" "Mazal" "McGill" "Mcl" "Mcl1-stability" "Mcl1ES" "Mcl1L" "Mcl1jh" "Mcl1s" "Mdm2-null" "Mec1" "Meier" "Meta-regression" "Metabochip" "Methodology" "Methods" "Mexico" "Mg" "Mi-2a" "MiR-192" "MiR-200" "MiR-27a" "MiR-329" "MiR-376c" "MiR-379" "MiR-433" "MiRNA-125b" "MiRNA-768-3p" "MiRNAs" "MiRNAs-886-5p" "Mia-PaCa2" "MicroPET" "MicroRNA-21" "Microautophagy" "Microhomology" "Micromilieu" "Microsystems" "Middle-South" "Milk-driven" "Milk-mediated" "Milliplex" "Millipore" "MiniSOG-mCherry" "Mir-17-92" "MitoTracker" "Mitosis-Karyorrhexis" "Mizuki" "Mizutani" "Mn" "Mo7ep210" "Moderate-to-strong" "Moelans" "MommeR1" "Monocyte-microglial" "Monte" "Morris" "Motin" "Mousnier" "Mst1" "Mt" "Mt-p53" "Mu-PACK" "Mucosae" "Multi-ethnic" "Munfus-McCray" "Mus81-Eme1" "MyD88s" "Myc" "Myc-53" "Myc-A20-WT" "Myc-EphA2" "Myc-I" "Myc-Lats1" "Myc-Mst2" "Myc-and" "Myers" "Myo2p" "N-Phe" "N-R" "N-TAD" "N-TADs" "N-acetyl" "N-acetyltransferase" "N-arginine" "N-degron" "N-end" "N-glycosylated" "N-glycosylation" "N-labeled" "N-lobe" "N-methyl" "N-methyl-N" "N-nitrosamines" "N-nitrosoguanidine" "N-recognin" "N1" "N2" "N3" "N4–6" "N=15" "N=39" "N=8" "NA" "NADH-dehydrogenase" "NAM-sensitivity" "NAMEC-RAS" "NAMEC-RAS-Tom" "NAMEC-Tom" "NAMEC-Tom-RAS" "NAMEC11" "NAMEC8" "NAMECs" "NB1141" "NB1142" "NB27" "NBRA-A" "NBRE-A" "NBRE-A-mediated" "NBRE-B" "NBRE-C" "NBRE-like" "NBUD" "NCBI" "NCBI36" "NCI" "NCI-H295R" "NCI-H322" "NCOAs" "NCT01237067" "NCT01445418" "NCT01466660" "NC_000019.9" "NDW" "NE-GOF" "NEJ002" "NES-like" "NES=2.05" "NF-B" "NF-H" "NF-Κb" "NF-κB-we" "NF-κB1" "NF-κB–DNA" "NF1-patient" "NFR2" "NFT" "NFTs" "NGF-axon" "NGF-treatment" "NGFβ" "NHWs" "NID+L" "NKI" "NKX3" "NL" "NLR" "NLS-SYFP-DBD" "NLS-SYFP-tagged" "NLS-like" "NLS2" "NLSs" "NMP1" "NM_006297.2" "NNA" "NO" "NOD-SCID" "NOD-like" "NOTCH1-3" "NOTCH2-CEP128" "NP" "NPM-ALK-driven" "NPM-ALK-negative" "NP_006288.2" "NQO1+ cells" "NQO1+cells" "NQO1-cells" "NR-coregulators" "NR2E" "NR2F" "NR3B1" "NR4R" "NRF2-ARE" "NRF2-ARE-activation" "NRF2-ARE-mediated" "NRF2-MAF" "NRG1-dependent" "NRG1s" "NSD" "NSTEMI" "NTC-mimic" "Naidu" "Nanoliposomes" "Nault" "Nd" "Necrostatin-7" "Nef-PI3K-PAK" "Nerve" "Nes8Cre" "Nestin-BrdU" "NetNES" "Ni-NTA" "Nielsen" "Niemann" "Niemann-Pick" "Ninety-eight" "Ninety-six" "Nissl" "Niu" "Nkx" "Nkx-2" "Nkx3-1-expressing" "No" "Nonsmall" "North-East" "Notch-Akt" "Notch-PTEN-Akt" "Notch-dependent" "Notch1" "Notch1ICD" "Notch2" "Notch2ICD" "Notch3" "Notch3-ICD" "Notch3-ICD-binding" "Notch3-ICD-transfected" "Notch3ICD" "Novartis" "Nox" "Noxa-levels" "Noxa-precipitates" "Np73" "Nr-ferm" "Nrf" "Nrf2-ARE" "Nrf2-dependence" "Nrf2-null" "Nu-va" "Nu-vb" "NuRD" "Nuc" "Nuc-pYStat5" "Nuc-pYStat5-positive" "Nucleo" "Nur77–reportedly" "Nurr1a" "Nurr1b" "Nurr77" "N = 7" "O-6-methylguanine-DNA" "O-GlcNAcylated" "O-GlcNAcylation" "O-GlcNAcylation–dependent" "O-GlcNAcylation–independent" "O-linked" "O-methylated" "OATS" "OB" "OB-1" "OB-fold" "OCI-ly19" "OCM-1" "OCTT2" "OD490" "ODC-1" "OHdG" "OMIM" "OPC" "OPCs" "OR1" "OR=0.20" "OR=0.36" "OR=0.47" "OR=0.49" "OR=0.60" "OR=0.64" "OR=0.69" "OR=0.70" "OR=0.80" "OR=1.26" "OR=1.33" "OR=1.51" "OR=3.05" "ORP-150" "ORR" "OV-C35-M1" "OV-C35-M2" "OV-C35-M3" "OV-MV1" "OV-MV2" "Oas1g" "Occludens-1" "Oct4A" "Off-rate" "Oiso" "Oliveras-Ferraros" "Oncology" "Oncomine" "One-third" "One-way" "Ooi" "Orbitrap" "Os" "Over-activation" "P+1" "P1-P3" "P17" "P17L" "P256fs" "P4" "P442HfsX9" "P4D1" "P6" "P65" "P65A" "P9" "P=0.00064" "P=0.0022" "P=0.0029" "P=0.0084" "P=0.0248" "P=0.035" "P=3E-16" "P= 0.9990" "PA25001" "PAHS012" "PANC-1-P" "PANC140" "PANC410" "PANC420" "PARD3L" "PARPi" "PAS" "PASMC" "PASMCs" "PAb" "PAb240" "PAb240-positive" "PBD" "PBL" "PBTs" "PC-3AR" "PC-3AR9" "PC12-conditional" "PC14-PE6" "PCNA-mUb-dependent" "PCNA-mUb-independent" "PCNAK164R" "PCR-RFLP" "PCR–ASP" "PCs" "PDGF" "PDGFR-IV" "PDGFRα" "PDGFβR" "PDZ1" "PDZ1-3" "PDZ2-domain" "PDZ3" "PDZ4" "PECAM" "PELP1-miR200a" "PELP1-shRNA-mediated" "PEST" "PFS=3" "PG" "PGDF-BB" "PGK" "PGNase-F" "PH-domain" "PI3K-CA" "PI3K-like" "PI3KCA" "PI3KKs" "PI3P" "PIE-1" "PIKKs" "PINK1-KDD" "PITA" "PIXα" "PKCßII" "PKCβ-DN" "PKCβII" "PKCη" "PKCι" "PKCλ" "PKM1" "PLCδ" "PMC42-LA" "PNA-PCR" "POL32" "POLδ" "POLη" "POLι" "POLκ" "POT1-TPP1-insensitive" "POU-homeodomain" "POUNDS" "PP" "PP2A-like" "PP30" "PPAA" "PPY-A" "PPY-A+BAW667" "PPY-A+SCF-block" "PPY-A-treated" "PPxY" "PQ" "PR-619" "PR-negative" "PR-positive" "PRC3" "PRF5" "PRMs" "PRTF" "PS" "PS1xMTEP" "PS647-DBN" "PSA-promoter" "PSChimera" "PTEN-DBN" "PTEN-activity" "PTEN-exosomes" "PTEN-intact" "PTEN-null" "PTENC2" "PTENΔD" "PTPMeg2" "PTPSL-like" "PTRF-Cavin" "PY1" "PY2" "PY20" "PY3" "PaCa" "Pab240" "Pab240-positive" "PacMetUT1" "Pacific" "Paired-box" "Paired-end" "Pairwise" "Pak" "Pam" "Pam3Cys4" "Pan-1" "Pan-Asia" "Par3-Lgl" "Pardee" "Parkin-SY5Y" "Parkinson" "Patel" "Patients" "Patj" "Pax-2" "Pbx" "Pbx-1" "Pdgfrα" "Pearson" "Peifer" "Pemetrexed" "Pena-Diaz" "Penicillin-Streptomycin" "Peptidylprolyl" "Perez" "Perhaps" "Peutz-Jeghers" "PgR0" "PgRSDF-1" "Phase-contrast" "PheWAS" "Philadelphia" "Phosphoinositide-3" "Pitstop2" "Plk1" "Plus2" "Pod" "Pod-1" "Poitiers" "Pol" "Pol3" "Poleward" "Polo-Box" "Poly-ADP" "Poly-ADP-ribose" "PolyI" "PolyPhen" "PolyPhen-2" "Polβ" "Polη" "Polι" "Polκ-UBZ" "Post-Synaptic" "Pp53" "Pph21" "Pph21p" "PrP-Fc" "PrP-His" "Preso1" "PriGO7A" "PriGO8A" "PriGO9A" "Primer3" "Principal" "Principle" "Pro-IL-1β" "Pro-inflammatory" "Procaspase-3" "Profiler" "Prognosis-Based" "Promega" "Protein-1" "Protein-DNA" "Protein-level" "Proteolipid" "Proteome" "Proteome-wide" "ProtoArray" "Prusiner" "Ptdins" "Ptdins-3,4,5-P3" "Ptdins-3,4,5-P3-activated" "Puerto" "Pull-down" "PvuII" "P = 0.001" "P = 0.00004" "P = 0.0001" "P = 0.013" "P = 0.014" "P = 0.020" "P = 0.024" "P = 0.030" "P = 0.036" "P = 0.045" "P = 0.49" "P = 0.63" "P = 1" "Q-Q" "Q-SNARE" "Q-test" "Q-tests" "Q1" "Q2" "Q3" "QD-IHF" "QD-quantification" "QDs" "QKI-5" "QUE-NL" "QUE-NL-exposed" "QUE-NL-induced" "QUE-NL-treated" "QUE-NLs" "QUE-NLs-induced" "QW" "QZ" "Qa" "Qa-SNARES" "Qbc-SNARE" "Qiagen" "Qian" "Qu" "Quantile-quantile" "Quantitle-quantile" "Qur" "R-2HA2Flag-Api5" "R-2HA2flag-Api5" "R-CHOP" "R-SMAD" "R-SMAD-co-SMAD" "R-SNARE" "R-SNAREs" "R-like" "R-mediated" "R-squared" "R110-YVAD" "R11EE" "R12" "R122" "R171X" "R249S" "R273C" "R273H" "R282W" "R335X" "R4A" "R5" "R748-S752" "R848" "R=0.07" "RAB8B" "RACE-PCR" "RACK1s" "RAD3-related" "RAD51-SAM" "RAD51-foci-negative" "RAD51-foci-positive" "RAD51share" "RARβ2" "RAS-G12V-transformed" "RAS-RAF-pathway" "RAS-association" "RAS-induced" "RAS-mediated" "RASFF1B" "RASFF1C" "RASSF1A-cytoskeletal" "RASSF1A-microtubule" "RASSF1C" "RB-expressing" "RB-positive" "RBAP-46" "RCC4T" "RECORD-1" "REV1-UBM" "REX" "REX2a" "RFLP" "RFP-Ruby-tagged" "RFP-SCR" "RFP1.3" "RFS-1" "RGQ" "RID1-like" "RIG-1" "RIG-I-like" "RING-CH" "RING-finger" "RIPA" "RL95-2-IR-A" "RL95-2–IR-A" "RM-ANOVA" "RMSD" "RMSE" "RMSEs" "RNA" "RNA-DNA" "RNA22" "RNAPII" "RNPC1a" "RNPC1b" "RNU24" "RNU6" "RNU6-2" "RNU6B" "RNase-ChIP" "ROC-AUC" "ROCK-induced" "ROCK-mediated" "ROCK∆3-expressing" "ROKβ" "ROR" "ROR-1" "RORβ" "ROS-driven" "ROSA26" "RPN2-MF" "RPTEC" "RPTECs" "RQ-PCR" "RR-only" "RRE-containing" "RRL" "RRLs" "RRRCWWGYYY" "RRXCXXGXYX-XRXCXXGXYY" "RSMADs" "RTK" "RTK-invariant" "RTP" "RTqPCR" "RV16" "RV1b" "RVL" "Rab-like" "Rac-GTP" "Rac-interacting" "Rac1" "Rac1-RhoGDIα" "Rac1-regulatory" "Rac1GEF" "Rac1GTP" "Rac1GTPlevels" "Rac1Q61L" "Rac1V12G" "Rac2-null" "RacGAP" "Racial" "Rad3" "Rad3-related" "Rad51-ssDNA" "Rad51C-like" "Rad6" "Radiation-and" "Radio-TLC" "Radio-high-performance" "Radioactive" "Ran-GTP" "Rap-specific" "Ras-Association" "Ras-association" "RasGRP-CAT" "RasPRG1" "Ras•GDP" "Ras•GTP" "Rat" "Rb-MI" "Rb-family" "Re-ChIP" "Re-expression" "Re-internalized" "Re-introduction" "Re-probing" "ReChIP" "Red-labeled" "Regulatory-Sma" "Reis-Filho" "RelA" "Remarks" "Replicate" "Results" "Ret-CoR" "Rev" "Rev-erbβ" "Rho-GDIα" "Rho-GDP" "Rho-GTP" "Rho-Rock" "Rho-Rock-driven" "Rho-family" "Rho-kinase" "Rho-like" "RhoA-GTP" "RhoA-GTPase" "RhoA-ROCK" "RhoA-signaling" "RhoAV14" "RhoA–SRF–Dsg1" "RhoGDI-FLAG-tagged" "RhoGDI1" "RhoGDI2L" "RhoGDIs" "RhoGDIɑ" "RhoGTPases" "Ribophorin-1" "Rican" "Rich-Edwards" "Rico" "Rictor" "Rictor-depleted" "Rictor-mediated" "Rictor-specific" "Rictor–independent" "Rij" "Riplet" "Riplet-C21A" "Risk-dependent" "Ro-32-0432" "Roche" "Roche-Genentech" "Rock-dependent" "Rong" "Ross-Innes" "Rotterdam" "Royds" "Rs10497968" "Rs1978873" "Rs845552" "RskS" "RskS380" "Rubicon" "Ruschoff" "RxS" "R→H" "S-JH" "S-Methionine-labeled" "S-XL" "S-labeled" "S-methionine" "S-nitroso-glutathione" "S-nitrosocysteine" "S-phases" "S-radiolabeled" "S-transferases" "S1" "S12" "S138A" "S14" "S146A" "S146A-Cdh1" "S14A" "S14B" "S15" "S15B" "S19" "S1981" "S19A" "S19B" "S19C" "S19D" "S19E" "S1C" "S1D" "S1E" "S1F" "S1–S5" "S208-A209" "S223A" "S223E" "S235" "S240R" "S240R-DNA" "S2A" "S2B" "S2B–C" "S2C" "S2D" "S2J" "S2K" "S2L" "S3" "S363" "S3B" "S3C" "S3E" "S4" "S473" "S4A" "S4B" "S4C" "S4D" "S5D" "S5F" "S6" "S647-DBN" "S6A" "S6B" "S6RP" "S7" "S76A" "S7A" "S7B" "S7C" "S7F" "S8" "S807" "S8A" "S8B" "S8D" "S8E" "S8F" "S9" "SA-β-galactosidade" "SAHA" "SAKK19" "SAL" "SAM208-210LEA" "SARAH" "SARM1-His" "SARMS" "SCC-R" "SCC-S" "SCCs" "SCEs" "SCF-FBXL" "SCID-Beige" "SDF" "SDF-α" "SDS-page" "SDS-polyacrylamide" "SDS–polyacrylamide" "SD≥6" "SD≥6months" "SERT-LPR" "SERTLPR" "SES" "SES-CD" "SET1C-Mediated" "SET1C-independent" "SET1C-mediated" "SET1C-p300" "SET1C-p53" "SF" "SFB-LMW-E" "SFC" "SFD2" "SH2-phospho-tyrosine" "SIM3" "SIMs" "SIRE" "SIRT1-7" "SIRT1-FL" "SIRT1-NT" "SIRT1-defective" "SIRT1expression" "SIRTs" "SISH" "SIVmac239" "SK" "SK-EV-C1" "SK-EV-C3" "SK-EV-C4" "SK-N-DZ" "SK-β1-C1" "SK28" "SKCO-15" "SKG" "SKL" "SKP1-CUL1-F-box" "SL" "SLC39A" "SM-actin" "SMAD-1" "SMAD-responsive" "SMARTpool" "SNAG" "SNC1" "SNF-related" "SNO-parkin" "SNOC" "SNP-Nexus" "SNP-SNP" "SNP-chip" "SNP-heritability" "SNpc" "SOCS1-7" "SOCS36E" "SOD1transgenic" "SOLAR" "SOMAmer" "SOMAmers" "SOS-CAT" "SPE-7" "SPL" "SR-IκB" "SR-IκBα" "SREBP-1or-2" "SRF-dependent" "SRF-mediated" "SRF-null" "SRGP-1" "SRH" "SRs" "SS" "SSBR" "STAT" "STAT#1" "STAT3-C" "STAT3-driven" "STAT3-independent" "STAT3C" "STAT3F" "STE20-like" "STEMI" "STEP-like" "STGC" "STGCs" "SUM-44" "SV40-Cluc" "SVs" "SWI353" "SYFP" "SYPRO" "SYPRO-Ruby" "SZ" "Sanger" "Sap155p" "Sap185p" "Sap190p" "Sap4p" "Sar1p" "Sar1p-GTP" "Sarcoma" "Sardinia" "Sardinian" "SceI" "Schwann" "Sec1" "Sec1-munc18" "Sec13p" "Sec13p-Sec31p" "Sec1p" "Sec22p" "Sec23" "Sec23p-Sec24p" "Sec31" "Sec4-GTP" "Sec4p–Sec15p" "Sec4–Sec15" "Sec5-3xGFP" "Sec6-2xmCH" "Sec6-GFP" "Sec8-2xmCH" "Sec9p" "Segat" "Self-renewal" "Self-reported" "Semi-quantitative" "Ser-15-p53" "Ser12" "Ser12-specific" "Ser15" "Ser159" "Ser19" "Ser1981" "Ser2" "Ser235" "Ser2448" "Ser4" "Ser8" "Ser807" "Ser9" "Sertoli-cell" "Set1C" "Sevenless" "Seventy-seven" "Seventy-two" "Shaefer" "Shanxi" "Shc-1" "Shien" "Sholl-plug" "Short-term" "SiHa-OCT4" "Siglec-1" "Sigma-Aldrich" "Significance" "Significances" "SinceGrm5" "Single-nucleotide" "Single-strand" "Sip1" "Sirt" "Sirt1–Sirt7" "Sirtuins" "Sixty-six" "Sixty-three" "Skp1-Cullin1-F-box" "Sle1c2" "Slit-Robo" "Slower-migrating" "Slug-mediated" "Smad1" "Small-molecule" "Snail" "Snc1" "Snc1p–Sso1p–Sec9p" "Snc2-M2" "Snc2-M2p" "Snc2-V39A" "Snc2p–Sec6p" "Snc–Sec6p" "Soft-tissue" "Somers" "Son-of-Sevenless" "Sox" "Spanish" "Spearman" "SpiroMeta" "Sponge-induced" "Sponge-mediated" "Sponge-reduced" "Springer-Bio" "Sprouty" "Sprouty4" "Spry4-null" "Spry4f" "Squibb" "Src" "Src-family" "Src-regulatory" "Ssk2" "Ssk2p" "Sskp2" "Sso1p" "Sso1p–Sec9p" "Sso2p" "Stadler" "Ste11" "Ste20" "Ste20-like" "Stockholm" "Strep" "Strep-Tactin" "Stress-induced" "Stub1-IRES-dsRed2" "Sturm" "Sub-group" "SupF" "Super-resolution" "Suplem" "Supple­mental" "Suv4-20h1.1" "Swa2p" "Sweden-PGC" "Swedish" "Swiss" "Switzerland" "T-77C" "T-LAK" "T-Lymphoid" "T-Lymphotropic" "T-P-X-R" "T-S" "T-STAR" "T-STAT3" "T-X-X-X-Phospho-S" "T-allele" "T-binding" "T-cell" "T-lymphoid" "T-lymphoma" "T-lymphomas" "T-rich" "T-vector" "T1" "T1-T3" "T109-F113" "T134A" "T166A" "T174A" "T180" "T180A" "T1G2.2" "T1G3.1" "T1G4.2" "T284" "T284R" "T284R-DNA" "T2DM" "T3" "T306D" "T308" "T359" "T36" "T37" "T4" "T47DR" "T5" "T599dup" "T790M" "T85" "T88" "TA-r" "TAA" "TACE-dependently" "TAM67" "TAMRAD" "TAP-A20-containing" "TAP-A20-overexpressing" "TAPI" "TAPI-1" "TATA" "TATA-less" "TAZ-regulated" "TAZ2" "TAZS89A" "TAZΔ393" "TAp" "TAp73" "TBB" "TBH" "TBR" "TBSA" "TBSA≥20%" "TC" "TC-10" "TCF-4-mediated" "TCF-binding" "TD" "TDCs" "TDG1" "TDL" "TDLUs" "TEA" "TEF-2" "TEFb" "TEFb-dependent" "TEV" "TEV-GFP-10" "TF-N" "TFN-α" "TGF-β-induced" "TGFBR2-3" "TGFβ1-blockade" "TH-A" "TH-B" "TH-C" "THAB-S2" "THAP" "THAP-S2" "THAP1-S1" "THAP1-S2" "THAP1-induced" "THAP1-regulated" "THM" "TIN" "TKI-EGFR-based" "TKI-treated" "TM" "TM+MM" "TM+TT" "TMPRSS4-negative" "TMPRSS4-positive" "TMRM" "TN" "TNBCs" "TNF-receptor" "TNF-superfamily" "TNFR-2" "TOM" "TOPOIIα" "TRA-1-60" "TRAF" "TRAF31P2" "TRAF3IP2-_rs33980500" "TRAF3IP2_rs33980500" "TRAPP" "TRAPPI" "TRCP" "TRCP2" "TROSY" "TROSY-HSQC" "TRPC6-p53-RE" "TRPC6-p53RE" "TRUS" "TRα" "TS" "TSEs" "TSS10" "TT29201" "TTF-1-negative" "TTF=6.1" "TTF=7.4" "TTN5AA" "TTSP" "TTSPs" "TUJ1" "TURBT" "TURP" "TY" "TZ" "Table2" "Tah18" "Tailless" "Taiwan" "Taiwanese" "Take-home" "Taken" "TaqMan" "Taqman" "Target-Scan" "TargetScan" "TargetScanS" "Tat" "Tat-TAR" "Tat-induced" "Tat-inhibitory" "Tat-mediated" "Tax" "Tax-1" "Tax-2" "Tax-HA" "Tax-NBs" "Tax-induced" "Tax-mediated" "TdR" "Tead" "Teffector-like" "Tek" "Tert" "Tert-butanol" "Testa" "Tet-o-MYC" "TetP-α-synuclein" "Tfn" "Tg" "Tg6799" "Th-1" "Th-17" "Th-2" "Th1-polarization" "Th17-driven" "Th2" "Thakran" "TheErbB2" "TheraScreen" "Thin-section" "Thioglycolate" "Thirty-eight" "Thirty-five" "Thirty-four" "Thirty-nine" "Thomas" "Thr-pro" "Thr-specific" "Thr163" "Thr18" "Thr1989" "Thr218" "Thr308" "Thr37" "Thr4" "Three-dimensional" "Tiam1-C-1199" "Tiam1-C1199-induced" "Tiffen" "Time-course" "Time-lapse" "Tokyo" "Toll" "Tomita" "TopoIIα" "Topoisomerase-IIA" "Topo–DNA" "TrF" "TrF-pathway" "TrFs" "Trans-Activator" "Trans-membrane" "Translocated" "Transwell-invasion" "TrioD1" "Tris-EDTA" "Tris-HCl" "Tris–HCl" "TrkA" "TrkA-immunoreactive" "Trp53" "Trs33p" "TrueBlot" "Tryptophan" "Tryptophan-GH-IGF-1-mTORC1" "Tryptophan-GIP-GH-IGF-1-mTORC1" "Tsai" "Tubastatin" "Tuj-1" "Tuj-1-postive" "Tukey" "Tumor-node-metastasis" "Tweedie" "Tween-20" "Twenty-eight" "Twenty-five" "Twenty-four" "Twenty-nine" "Twenty-one" "Twenty-three" "Twenty-two" "Two-hybrid" "Two-locus" "Two-variant" "Tyr-572" "Tyr-742" "Tyr1007" "Tyr220" "Tyr551Stop" "T→A" "T→G" "U-IgVH" "U-rich" "U1" "U133" "U133A" "U1control" "U1wt" "U21459" "U23674" "U251" "U251-vIII" "U251vIII" "U251vIIIwt" "U26" "U2932" "U3" "U373" "U73122" "UA" "UACR" "UBMs" "UCBs" "UGI" "UGT2B15*2" "UICC" "UK" "UK-Pan-1" "UM-UC-9" "USA" "USB" "USF2+HBS" "USF2∆basic" "USF81" "UTR-mut" "UTRs" "UV-irradiation" "UV-mutagenesis" "UV-radiation" "UVC" "Ub-K48R" "Ub-K63-specific" "Ub-K63R" "Ub-Ub" "Ub-ligase" "UbcH2" "Uev1a" "Uso1p" "Utah" "V-AKT" "V-FITC" "V-HA-RAS" "V-Ki-ras2" "V-RAF-1" "V3b" "V5" "V5-tagged" "V544ins" "V6" "VAD" "VATS" "VB" "VDQ-002" "VE-cad-Cre" "VE1-antibody" "VI" "VMC" "VPS34-dependent" "VSV" "VSV-G" "VSV-G-ts45" "VSV-G–GFP" "VU0155056" "VU0359595" "VYSXWLXXY" "Value" "Vancouver" "Variants" "Vastus" "Vectibix" "Vector" "Vegf-A" "VeraTag" "Villeurbanne" "Vimentin" "Vincent-Salomon" "Vogelstein" "Vpr-host" "Vpr-treated" "W437X" "W515K" "W659A" "WASP" "WBC" "WJTOG3405" "WNT" "WSP" "WST" "WST-1" "WST-8" "WT-Cdh1" "WT-Cdh1-expressing" "WT-Vpr" "WT1-B" "WT1-D" "WT1-like" "WT1-shRNA3repressed" "WT1enhanced" "WTcells" "Wald" "Wallis" "Warburg" "Watson" "Watson–Crick" "Weinberg" "Weisberg" "Weri-Rb1" "Werner" "Western-blot" "Western-blots" "White" "Whitney" "Whole-cell" "Wiernik" "Wilcoxon" "Wright-Giemsa" "Wsh" "Wt-EphA2" "Wt-EphA2-Myc" "Wt-HA-c-Cbl" "Wt-c-Cbl" "Wu" "Wuillème-Toumi" "Wv" "X-11787" "X-DL" "X-inactivation" "X-irradiation" "X-linked" "X-ray" "X-rays" "X1" "X100" "X12" "X1w" "X4" "X9A" "XAip1" "XG" "XL-ICN" "XLF-defective" "XPA-UVDE" "XPA-importin-α7" "XPA-ΔNLS" "XPro1595" "XRCC1-BRCTII" "XRCC1-defective" "XRCC1BII" "XRCC1LL360" "XRCC1w" "XRCC1–LigIIIα" "XTT" "XX" "XY" "Xia" "Xrcc3-like" "Xu" "Y-family" "Y201X" "Y202" "Y229E" "Y229F" "Y233E" "Y233F" "Y2H" "Y352" "Y352E" "Y352F" "Y39F" "Y50F" "Y5R1c52" "Y647F" "Y648F" "Y656A" "YAP-IF" "YAP-IHC" "YAP1-1" "YAP5SA" "YAPS94A" "YCK" "YFP-DBN" "YHL017W" "YHR122w" "YI" "YL" "YPK2" "YRI" "YS" "YSXXLXXL" "YVO4" "YXXM" "Yang" "Yang-1" "Yang1" "Yap" "Yap-Amot-p130" "Yap-Tead-mediated" "Yap-Tead–dependent" "Yap-Tead–mediated" "Yap1081" "Yap1801" "Yap1802" "Yap1802p" "Yes" "Yes-associated" "Yin" "Ykt6p" "York" "Yorkie" "Yoruba" "Ypt1" "Ypt1p" "Z-VAD" "Z-guggulsterone" "Z=0.727" "ZAL4" "ZBKR1" "ZFNs" "ZIP6-M" "ZIP6-Y" "ZIP6-mediated" "ZO" "ZO-1-PDZ2" "ZO-1-S168A-Flag" "ZO-1-S168D-Flag" "ZO-1-WT-Flag" "ZR-75" "ZR-PELP1" "ZR-PELP1-141-mimetic" "ZR-PELP1-200a-mimetic" "ZR-PELP1-GFP-Luc" "ZR75" "ZR75-PELP1-shRNA" "ZR75PELP1-shRNA" "ZZ" "Zeng" "Zetterberg" "Zhang" "Zhao" "Zhou" "Zhu" "Zinc-finger-leucine" "Zn" "Zn-finger" "Zn1" "ZnF" "ZnFs" "ZnPP" "Zou" "aCGH" "aPI3K" "aPKC" "aPKCs" "above-noted" "ac-KIGS" "ac-Lys" "acetyl-lysine" "acetylated-KXGS" "acetylated-lysine" "acetylation-deacetylation" "acetylation-mimetic" "achaete" "achaete-schute" "acid-locked" "acid-soluble" "acids-PCR" "acinar-predominant" "acral" "actin-cytoskeleton" "actin-like" "actinomyosin" "actin–yellow" "activated-cell" "activation-loop" "activators" "actively-transcribed" "adSIRT1" "adduct" "adducts" "adeno" "adeno-null" "adenomatoid" "adherent-invasive" "adhesiveness" "adipocyte-like" "adipose-derived" "adipose-related" "adult-onset" "advanced-stage" "adverse-effect" "aeruginosa" "affinity-purify" "aflatoxin-B1" "agar" "age-associated" "age-dependent" "age≤69" "aggregate-prone" "aggresome-like" "agonism" "agonists" "agreed-upon" "aily-1" "air-liquid" "air–medium" "alfa-fetoprotein" "algorithm" "algorithms" "all-atom" "all-or-nothing" "all-time" "allele-A" "allele-C" "allele-G" "allele-T" "alleles" "allodynia" "allograft" "alpha-helical" "alpha-positive" "alternative-splice" "alveoli" "amino-acid" "amino-terminal" "amino-terminus" "aminoacids" "amoeboid" "amphisomes" "amplicon" "amplicons" "amplification-driven" "amyloid-like" "amyloids" "anchorage-independence" "and-761" "andA2λ" "andBrca1" "andErbB2" "andGrm5" "andPyMT" "andTP53" "and\\or" "andand" "andp21" "andp27" "androgen-dependence" "androgen-deprivation" "androgen-independence" "androgen-receptor" "aneuploidy" "aneurysm" "aneurysms" "angiogenic-related" "angiomotin-like" "anilino" "anilino-monoindolylmaleimide" "anisotropy" "anorexia" "antagomir" "antagomirs" "ante-phase" "antibodies" "antigen" "antigen-specificity" "antigens" "antisense-ODN" "antitumour" "aorta-derived" "ap-proach" "apical-basal" "apm4" "apo-EF1" "apoE-null" "apoptosis-functional" "apoptosis-relevant" "apoptosis-stimuli" "apoptotic-like" "apoptotic-proliferation" "aptamer" "aptamers" "arcade-like" "arginine-rich" "arginine-to-leucine" "arisen" "arm-mediated" "armadillo-repeats" "armed-ATC" "array-CGH" "arrest-defective" "as-yet-unidentified" "asthma-like" "astroglia" "astroglial-derived" "at-risk" "atomic-level" "atrophins" "atypia" "authors" "auto-activation" "auto-antibodies" "auto-inhibited" "auto-inhibitory" "auto-regulatory" "autocrine-dependent" "autophagic-dependent" "autophagy-lysosome" "autoradiography" "auxillin" "avg" "a–d" "b-actin" "b-d" "b0+Σ" "b1" "b2" "bHLH+PAS" "bHLH-LZ" "back-to-back" "back-up" "background-to-target" "bafilomycin" "bare-decorated" "barrier-permeable" "basal-like" "base-line" "base-long" "base-pair" "base-pairs" "baseline-like" "basic-helix-loop-helix" "basic-leucine" "bead-microarrays" "beads-on-a-string" "begun" "benzo" "beta-activated" "beta-oxidation" "better-known" "between-765G" "between-766" "between-run" "between-study" "bevacizumab-erlotinib" "bi-allelic" "bi-directionally" "bi-orientation" "bi-parametric" "bi-partite" "bi-phasic" "bi-weekly" "bifida" "bilayer" "bilayers" "biliverdin" "bio-energetic" "bio-photonic" "biologically-independent" "bis" "bisphosphate" "bivariate" "blockers" "blood-based" "blood-brain" "blood-brain-barrier" "blood-derived" "blood–brain" "blot-based" "blue-shifted" "body-associated" "bone-like" "bone-marrow-derived" "bone-tropic" "bothEts2" "bothp21" "bothp53" "box-and-whisker" "bp-CpG" "brainstem" "branched-chain" "break-apart" "break-dependent" "break-induced" "break-prone" "breakpoint" "breakpoints" "breast-like" "broad-acting" "broad-range" "broad-ranging" "broad-spectrum" "bronchoconstrictors" "bronchoscopy" "bulge-loop" "bundle-like" "butanol" "by-product" "by-products" "by16" "byTP53" "byp27" "b–d" "b–j" "c-Cbl-C3HC4C5" "c-MycER" "c-NHEJ" "c-Src-dependent" "c-Src-induced" "c-Src-mediated" "c-e" "c-neu" "c-src-phalloidin" "c1" "cFN" "cIAPs" "cJUN" "cXPA" "caAkt" "caC" "caSTAT3" "cadmium-induced" "calcein-AM" "calcium-bilirubinate" "callosum" "calorimetry" "cancer-like" "cancer-predisposition" "caner" "cap-complex" "cap-dependent" "capillaries" "capillary-like" "capillary-tube" "capsid" "carbazole" "carbon-oxygen" "carbon-sulfur" "carbonyl" "carboplatin+olaparib" "carboplatin-gemcitabine" "carboplatin-paclitaxel" "carboplatin-pemetrexed" "carboplatin-vinorelbine" "carboplatin–olaparib" "carboxyl" "carboxyl-terminal" "carboxyl-terminus" "carboxylcytosine" "carcinogen-DNA" "carcinogens" "cardiotrophin-like" "cargo-modifying" "carotid" "carriers" "carry-over" "cartilage-like" "case-by-case" "case-control" "case-controls" "case-specific" "casepase9" "case–control" "caspase-1-dependent" "caspase-like" "castration-induced" "castration-mediated" "castration-resistant" "castration-sensitive" "castration-sensitivity" "catalytic-domain" "catechol-O-methyl" "catenin-mediated" "catenin-membrane-positive" "cation–π" "cause-and-effect" "caveolae-like" "cavin-3-GFP-expressing" "cavin-GFP" "cavin-MiniSOG" "cavins" "ccRCC" "ccRCCs" "cel-miR-67" "cell-autonomous" "cell-cycle-related" "cell-extracellular-matrix" "cell-in-cell" "cell-intrinsic" "cell-like" "cell-malignant" "cell-permeable" "cell-polarity" "cell-to-cell" "cell-to-medium" "cell-type-specific" "cells" "cellular-movement" "centromere" "cerebellum" "cerevisiae" "cetuximab-naïve" "cetuximab-treatment" "cfDNA" "cg08008233" "cg12215675" "chain-mimetics" "chaperone--a" "charcoal-dextran" "charcoal-stripped" "checkpoint-dependent" "checkpoint-insensitive" "checkpoint-proficient" "chemically-engineered" "chemically-induced" "chemically-synthesized" "chemo" "chemo-protective" "chemo-radiation" "chemo-responsiveness" "chemo-sensitivity" "chemo-sensitizers" "chemo-therapeutics" "chemo-therapies" "chemoattractant" "chemoresistance" "chemoresistant" "chemotherapeutically-induced" "chemotherapy-naïve" "chi-square" "chi-squared" "childhood-onset" "cholesterol-dependent" "cholesterol-induced" "choline" "choroid" "chosen" "chr10" "chr2" "chr3∶196,792,172" "chr5" "chr6" "chrRCC" "chrRCCs" "chrX" "chromatid" "chromatids" "chromatin-RNA" "chromatin-remodeling" "chromophobe" "chromosome-specific" "circletail" "cis-elements" "cis-regulatory" "cisplatin-docetaxel" "cisplatin-etoposide" "cisplatin-gemcitabine" "cisplatin-pemetrexed" "cisplatin-vinorelbine" "cisplatin-vinorelbine-gemcitabine" "cistrome" "cistron" "class-1" "class-I" "classifier" "clean-up" "clearer" "clinic-pathological" "clinically-approved" "clinically-relevant" "clinicians" "clinico" "clinico-pathological" "clinics–agnostic" "clone-11" "close-by" "cluster-like" "coactivator-3" "coarse-grained" "cobblestone-like" "cocaine-Tat" "coding-gene" "codon" "codon-12" "codons" "cof" "cofilactin" "coiled-coil" "coli" "collagen-1A2" "collagens" "collectives" "colony-formation" "colony-forming" "combination-induced" "combinations" "combined-cocaine" "commercially-available" "compacta" "compartment-specific" "complex-the" "components" "concentration-dependence" "conditionalEts2" "conductance" "conductances" "confounder" "congenita" "conjunctiva" "connective-tissue" "consecutively-collected" "conshRNA" "contact-inhibited" "context-specificity" "continuum" "control-ShRNA" "control-nevi" "control-nevus" "control-pcDNA" "control-shRNA" "control-siRNA" "controlPyMT" "control±S" "cooperativity-dependent" "cooperativity-dependently" "cooperativity-independent" "cooperativity-reducing" "copy-number" "core-domain" "coregulators" "correlation=0.98" "cortico-striatal" "cost-effective" "cost-effectiveness" "costimulation-induced" "counter-intuitive" "counter-part" "counter-productive" "covariate" "covariates" "coworkers" "cow´s" "crescent-shaped" "cribriform" "crista" "cross-activate" "cross-activation" "cross-binding" "cross-breeding" "cross-complementation" "cross-complementing" "cross-complementing-1" "cross-contamination" "cross-inhibited" "cross-inhibition" "cross-linker" "cross-reactivity" "cross-resistance" "cross-section" "cross-sectional" "cross-study" "cross-validate" "cross-validation" "cross-β" "crossover" "crypt-villus" "crypts-villus" "cullin-RING" "current-smokers" "current-to-voltage" "curvature-inducing" "cut-off" "cutpoint" "cy-totoxicity" "cyan" "cycleave" "cyclin-A-mediated" "cyclin-B-mediated" "cyclin-CDK" "cyclin-D3" "cyclin-E-dependent" "cyclin-depended-kinase" "cyclinAsubstrate" "cyclinD-CDK" "cyclins" "cyclobutane–pyrimidine" "cypridina" "cys-LT" "cys-LT-activated" "cys-LT-dependent" "cys-LT-induced" "cys-LT-mediated" "cys-LT-responsive" "cys-LTs" "cytAco" "cyto" "cyto-construction" "cyto-protective" "cytochromes" "cytokeratin-19" "cytokine-treatment" "cytology" "cytosol-to-membrane" "c–e" "d-f" "dEGFR" "dG" "dHL-60" "dPLB" "dPLB-985" "dRASSF" "damage-binding" "damage-dependent" "damage-independent" "damage-induced" "damage-inducible" "damage-inducing" "damage-regulated" "damage-responsive" "damage-signaling" "database-TargetScan" "database-identified" "databases" "dataset" "datasets" "day-to-day" "dbSNP" "dbSNP-Reference" "de-activated" "de-aggregated" "de-aggregation" "de-condensation" "de-differentiated" "de-novo" "de-regulate" "de-regulated" "de-regulation" "de-represses" "de-repression" "de-repressive" "de-ubiquitinase" "de2-7" "deacetylase-defective" "death-receptor-induced" "decay-promoting" "deep-sequence" "deeper" "degron" "degrons" "dehydrogenase-5" "del11" "del11q" "del126-133" "del158-172" "del17" "del17p" "del19" "delGly158-Asp172" "delL747-E749" "deleted-loop" "delta-mtDNA" "dendritic-like" "density-dependent" "deoxycitidine" "deoxynucleotidyl" "deoxyuridine" "dependent-RNA" "dependent-manner" "depolarization-induced" "der" "dermato-pathologist" "desmocollin-1" "desmoglein-1" "desmogleins" "detachment-induced" "detergent-insoluble" "di-arginine" "di-methylated" "di-substituted" "diabetes-associated" "diabetes-dependent" "diabetes-increased" "diabetes-induced" "diabetes–increased" "diabetes–induced" "diaminobenzidine" "dichroism" "diet-derived" "diet-fed" "diet–genotype" "differentiated-like" "dihydroxy" "dimer-level" "dimer-to-monomer" "dimers" "dimorphism" "dimorphisms" "dinucleotides" "diploid" "diplotype" "discoideum" "discrepant" "disease-relevant" "dithiobis" "dnSTAT3" "doi" "dominant-negative" "donor-to-donor" "dormancy" "dosage-dependent" "dosage-sensitive" "dose-and" "dose-based" "dose-dependency" "dose-dependently" "dose-response" "dose-responses" "dose–response" "dot-like" "double-blind" "double-block" "double-membrane" "double-minute" "double-negative" "double-proline" "double-strand" "double-thymidine" "down-expressed" "down-expressing" "down-modulated" "down-modulating" "down-modulation" "down-stream" "down-weights" "doxy" "doxy-treatment" "doxycyline" "drawn" "driven-tumors" "droplets" "drug-overhang" "drugs" "ds" "dsDNA" "dual-function" "dual-label" "dual-phosphorylation" "dual-priming" "dual-reporter" "dual-specific" "dual-targeting" "dual-tilt" "duct-lobular" "duplexes" "duration=24" "duration=7.4" "dwarfism" "dying-back" "dyn" "dyscrasia" "dyscrasias" "dysfunction-induced" "dyslipidemia" "dysplasia" "dyspnea" "d–f" "e-08" "eEF2-56T" "eHELQ" "eIF4" "eLife" "eQTL" "eSNPs" "eXRCC2" "early-late" "early-onset" "early-passage" "early-phase" "early-region" "early-stage" "ebpα" "echinoderm" "ectdomain" "ectodomain" "ectodomains" "ectopically-expressed" "edema" "effector-like" "egg-shell" "electron-dense" "element-1" "element-binding" "element-variable" "eluate" "embryopathy" "empty-shRNA" "en-bloc" "end-organ" "end-product" "end-resection" "end-stage" "end-to-end" "endoderm" "endometria" "endometrioid" "endometrium" "endometrium-like" "endoplasmic-reticulum-located" "endothelia" "endothelial-independent" "endothelial-like" "endothelial-marker" "endothelial-specific" "endpoint" "endpoints" "energy-modulated" "enhancer" "enhancer-binding" "enhancer-core" "enhancer-promoter" "enhancer–promoter" "enriched-phenotype" "entero-insular" "environmental-genetic" "enzyme-DNA" "enzyme-E2" "enzyme-substrate" "enzymes" "enzyme–DNA" "eosin" "epeat" "eph" "epicardium" "epigenome" "epithelia" "epithelial-cell" "epithelial-derived" "epithelial-like" "epithelial-mesenchymal" "epithelial-sensitive" "epithelial-specific" "epithelial-stromal" "epithelial-targeted" "epithelial-to-mesenchymal" "epithelial-type" "epithelial–mesenchymal" "epithelial–targeted" "epithelium" "epitheloid" "epitope-tag-specific" "epsilon" "epsilon-amino" "equi-molar" "erlotinib-naïve" "error-containing" "erythroid-2-related" "estradiol-dependence" "estrogen-dependence" "eta" "ethnic-specific" "ets" "ever-smoker" "ever-smokers" "ex" "ex-smokers" "ex-vivo" "examinedGrm5" "excited-state" "exogenously-expressed" "exon-level" "exon17" "exon19" "exon21" "exon9" "exons" "exosome" "exportin-cargo" "exposed-breast" "extension–retraction" "extra-cell" "extra-genital" "extra-helical" "extra-mitochondrial" "extra-nuclear" "extra-oral" "extra-synaptic" "extracellular-initiated" "extract-based" "extract-induced" "ezrin-like" "e–f" "e−05" "fC" "factor-1" "factor-4" "factors" "failure-to-thrive" "falciparum" "fall-off" "fat-diet" "fatpad" "feed-back" "feed-forward" "feedback-regulatory" "feedforward" "female-specific" "fermentans" "fetal-specific" "fibroblast-like" "fibulin-like" "fifty-seven" "filled-in" "filopodia-like" "filter-trap" "fine-mapping" "fine-needle" "fine-tune" "fine-tuned" "fine-tunes" "fine-tuning" "first-degree" "first-generation" "first-in-human" "first-line" "fish-oil" "five-stranded" "five-year" "flask-like" "flexibly-tethered" "flow-cytometry" "flow-driven" "flow-intensity" "flow-through" "flow-thru" "flox" "fluorescence-in-situ-hybridization" "fluorescence-lifetime" "fluorophore" "flux–it" "fms-like" "focus-forming" "folic" "follow-up" "followed-up" "footpad" "footpads" "force-stimulated" "forebrain" "former-smokers" "formyl" "formyl-Met-Leu-Phe" "formyl-peptides" "formylcytosine" "forty-four" "four-aa" "four-and-a-half" "four-color" "four-helix" "four-point-one" "four-way" "fractions" "frame-by-frame" "frame-shift" "frameshift" "free-EGFR" "freeze-substitution" "freeze-thaw" "fresh-frozen" "fromErbB2" "fromErrfi1" "fromEts2" "fromGrm5" "fromHomer1" "fromHomer1a" "fromPin1" "fromPyMT" "fromp53" "front-line" "frozen" "full-site" "full-text" "function-2" "functionalities" "fusiform" "g-l" "g-ratios" "gARPCs" "gDNA" "gain-of-function" "gastro" "gastro-esophageal" "gastro-intestinal" "gatekeeper" "gel-filtration" "gel-shift" "gender-by-SNP" "gene-aspirin" "gene-by-environment" "gene-carrier" "gene-disease" "gene-environment" "gene-gene" "gene-phenotype" "gene-therapy" "gene-trap" "gene-wise" "genes" "genetically-engineered" "genetically-susceptibility" "gene–diet" "gene–disease" "gene–environmental" "gene–gene" "genitalia" "genitals" "genome-wide" "genotype-disease" "genotype-phenotype" "genotype-selectable" "genotypes" "genotype–diet" "germ-line" "germinal-center" "germline" "giants" "glia" "glomeruli" "glomerulonephritis" "glucagon-like" "glutamate-rich" "glutathione-sepharose" "glycosylase-formed" "glycosylase-generated" "goat-anti-human" "goat-anti-mouse" "goes" "goosecoid" "gp-120" "gp120-CXCR4" "gpK8.1A" "gradients" "grainyhead-like" "granular-shaped" "greater" "greatest" "green-labeled" "growth-repressive" "g–i" "g–j" "h2" "hBRCA1" "hCD45" "hESC" "hESCs" "hEnSCs" "hGH" "hGHR" "hIL-6" "hIgG" "hMCM7" "hNSC" "hNSCs" "hSET1" "hSIRT1-FL" "hSIRT1-NT" "hTH-3174" "hTH-3174-luc" "hTH-NBRE-A" "hTR-Imetelstat" "hTR-Ku" "half-a-million" "half-dozen" "half-life" "half-lives" "half-maximal" "half-saturated" "half-saturating" "half-saturation" "half-site" "half-sites" "half-stoichiometric" "hand-containing" "hand-foot" "hands-on" "haploChIP" "haplotype" "haplotypes" "head-to-head" "head-to-tail" "healthy-state" "heat-map" "heat-shock" "heatmap" "heavier" "helical-domain" "helices" "helix" "helix-loop-helix" "helix–loop–helix" "helq-1" "hemangiopericytoma-like" "hemato-endothelial" "hematoxilin-eosin" "hematoxylin-eosin" "hepato-carcinogenesis" "hepatoid" "heregulin-alpha" "hetero-dimer" "hetero-dimers" "hetero-oligomerises" "hetero-oligomers" "heterogeneous-mutated" "heterotetramer" "heterotetramers" "heterozygote" "hexamethylene-bis-acetamide" "hg18" "hg19" "hidden" "high-DNA-flexibility" "high-MW" "high-accuracy" "high-affinity" "high-blood-flow-dependent" "high-concentration" "high-concentrations" "high-confidence" "high-content" "high-density" "high-dose" "high-fat" "high-frequency" "high-glucose" "high-grade" "high-incidence" "high-invasive" "high-level" "high-levels" "high-molecular-mass" "high-molecular-weight" "high-order" "high-penetrance" "high-performance" "high-pressure" "high-quality" "high-resolution" "high-risk" "high-stage" "high-stress" "high-tumour" "high-value" "higher-molecular-mass" "higher-order" "higher–molecular" "highly-conserved" "highly-prevalent" "hindlimb" "hindpaw" "histochemistry" "histologically-defined" "histologies" "histology" "histone2" "histopathology" "history–on" "histoscore" "histotype" "histotypes" "hoc" "holo" "holo-complex" "holo-receptor" "homeodomain" "homo-oligomerization" "homo-oligomers" "homo-or" "homogenates" "homolog" "homologies" "homologs" "homologue-1" "homology-2" "homozygote" "homozygousEts2" "hormone-independence" "hospital-base" "host-cell" "host-virus" "hot-spot" "hotspot" "hotspots" "hour-time" "house-keeping" "hrr25" "hrr25-5" "hsa-miR-125b-1" "hsa-miR-125b-2" "htert" "hydrogen-bond" "hydrogenase-like" "hydroxy" "hydroxylase-positive" "hyper-IgE" "hyper-cholesterolemia" "hyper-immunoglobulin" "hyper-proliferation" "hyper-proliferative" "hyperdiploid" "hyperinsulinemia" "hyperoxia" "hyperresponsiveness" "hypo-acetylation" "hypo-phosphorylated" "hypocomplementemia" "hypomagnesemia" "hypoxia-related" "h " "h–4" "h–9" "h–t9" "iRBC" "iTRAQ" "identity-by-state" "ie" "ii" "ii-iv" "iii" "ii–iv" "ill-defined" "image-converted" "immediate-early" "immune-compensatory" "immune-complex" "immune-deficient" "immune-mediated" "immune-purified" "immune-reactivity" "immuno-EM" "immuno-electron" "immuno-fluorescence" "immuno-fluorescent" "immuno-histochemistry" "immuno-isolates" "immuno-isolation" "immuno-precipitant" "immuno-precipitate" "immuno-precipitated" "immuno-precipitation" "immunoassay" "immunoassays" "immunocomplexes" "immunocytochemistry" "immunoglobulin" "immunoglobulin-like" "immunohistochemistry" "immunophenotype" "immunophenotypes" "immunoprecipitatedwith" "immunoprecipitation-mass" "immunoprecipitations" "immunoscore" "immunosurveillance" "immunotherapies" "immunotherapy" "impedance" "importin-α" "importin-α1" "importin-α4-XPA" "importin-α5" "importin-α7-beads" "importin-β" "importins-α1" "importins-α4" "in-activation" "in-between" "in-cell" "in-depth" "in-flow" "in-frame" "in-gel" "in-human" "in-silico" "in-situ" "in-stent" "in-vitro" "in-vivo" "inErbB2" "inErrfi1" "inGrm5" "inHomer1" "inHomer1a" "inMCF-7" "inPARP1" "inParkin" "inPyMT" "inTP53" "incretin" "independently-generated" "induced-apoptosis" "induced-entosis" "inflammation-associated" "inflammation-induced" "inflammation-mediated" "infra-red" "ingrowth" "inhibitor-5" "inhibitor-IV" "inhibitor-IV-treated" "inhibitor-anthracycline" "inhibitor-α" "inhibitors" "inhibitors-of" "initiated-BER" "inp21" "ins" "insula" "insulin-GSK-3-p27" "insulin-like" "insulin-positive" "insulin-producing" "insulin-receptor-related" "insulin-stimulated" "int" "integrators" "inter-cell" "inter-chromosomal" "inter-class" "inter-genic" "inter-group" "inter-helix" "inter-individual" "inter-kinetochore" "inter-observer" "inter-relationships" "inter-subunit" "inter-tumor" "interactome" "interactomes" "interdomain" "interferon-κ" "interlobe" "intermediate-like" "intermediate-resistant" "intermediate-risk" "intermediate-sized" "intermembrane" "internalization–most" "interobserver" "interquartile" "interstitium" "interstrand" "intra-Golgi" "intra-aortic" "intra-chromosomal" "intra-individual" "intra-lesional" "intra-osseous" "intra-protein" "intra-renal" "intra-tibia" "intra-tumor" "intra-tumour" "intra-vascular" "intracardiac" "intracarotid" "intratumour" "intron-exon" "introns" "inva-siveness" "invasion-inhibitory" "invasion-metastasis" "invasion-suppressive" "inverse-BAR" "inverse-variance" "in–out" "iodoani" "iodoani-lino" "ionic" "irradiation-dependent" "irradiation-induced" "ischemia-reperfusion" "islets" "isoform-selective" "isoforms" "isomers" "isotope-coded" "isotype" "isozymes" "iv" "junction-associated" "k-MT" "k-MTs" "kDa" "kappa-B" "kappaB" "karyotype" "kbp" "kcal" "ketoacid" "kexin" "kg" "kinase-2" "kinase-defective" "kinase-interaction" "kinase-specificity" "kinase1" "kinases" "kinesin-like" "knock-down" "knock-down-induced" "knock-downs" "knock-in" "knocked-down" "knockin" "knocking-down" "knocking-out" "knowledge-base" "ku11ees" "ku12es" "labeling-intensity" "laboratory-specific" "laevis" "lambda" "lamellipodia-like" "lammilopodia" "lane3" "large-cell" "large-cohort-based" "large-diameter" "large-flat" "large-scale" "large-size" "laser-capture" "laser-induced" "late-G1" "late-acting" "late-onset" "late-phase" "late-recurring" "late-stage" "lateralis" "lattice-like" "lavage" "leading-edge" "leave-one-out" "left-shifted" "lentiviral-mediated" "lepidic-non-mucinous" "let-7a" "let-7g" "let7a" "let7b" "let7c" "let7f" "lethal-7a" "leucine-zipper" "leucoderma" "leukemia-1" "leukemia-2" "leukocytes" "leukoderma" "life-expectancy" "lifecycle" "lifespan" "ligand-receptor" "light-chain" "limb-specific" "limiting-dilution" "lincRNA-p21" "line-widths" "lineage-specific" "lipid-kinase" "lipid-phosphatase" "lipofectamine2000" "lipoproteins" "liposome" "lipoxygenase-mediated" "littermate" "littermates" "live-cell" "live-threatening" "lncRNA" "lo" "load-driven" "localizations" "location-dependence" "location-specific" "locus-specific" "log-additive" "log-phase" "log-rank" "long-acting" "long-axis" "long-lasting" "long-lived" "long-patch" "long-range" "long-standing" "long-time" "long-timescale" "long-tract" "longer-term" "loss-of" "loss-of-function" "lot-to-lot" "low-MW" "low-activity" "low-affinity" "low-cost" "low-density" "low-dosage" "low-dose" "low-fat" "low-frequency" "low-glucose" "low-grade" "low-incidence" "low-intensity" "low-level" "low-moderate" "low-molecular-weight" "low-oxygen" "low-penetrance" "low-percentage" "low-power" "low-quality" "low-risk" "low-scale" "low-serum" "low-throughput" "low-volume" "lower-contrast" "loxP" "lpr" "lumens" "luminal-like" "lung-only" "lupus-like" "lymph-node" "lymph-node-positive" "lymphadenopathy" "lymphoblastoid" "lymphoid-enhancer-factor-1" "lymphoma-like" "lysine-to-arginine" "lysine4" "lysosome-mediated" "lκBα" "m3" "mCherry" "mCherry-DBN" "mCherry-LC3" "mCherry-Lifeact" "mFadA" "mGluR-Pin1" "mGluR-SIC" "mGluR5FR" "mGluR5TSAA" "mL " "mNBRE-A1" "mNBRE-A2" "mRID1" "mRNA" "mRNA-level" "mSIN3A" "mSIN3a" "mSOD1" "mSin3A" "mTOCR2" "mTOR-AKT-PI3K-PTEN" "mTORC1-driver" "mTORC1-p70S6K-mediated" "mU" "mV" "mYap" "macro-microvascular" "macro-vascular" "macronodules" "macrophage-like" "magnesium-dependent" "main-effect" "malarial-induced" "male-to-female" "malignant-dampening" "mammary-specific" "mammosphere" "mammospheres" "map-2" "marker–positive" "mastectomy" "master-switch" "matched-pair" "materno-neonatal" "matrix-remodeling" "maturity-onset" "mcg" "mdDA" "mdm2-antagonist" "mean ± standard" "mean±S" "mean±SD" "mean±sd" "mean±standard" "mean ± SD" "mean ± standard" "mechano" "mechano-sensitivity" "mediated-sensitization" "melanocortin" "melanocortin-1" "melanogaster" "mellitus" "membrane-deformation" "membrane-depolarization" "membrane-distal" "membrane-non-binding" "membrane-proximal" "memory-resting" "mesangium" "mesencephalon" "mesenchymal-epithelial" "mesenchymal-like" "mesenchymal-refractory" "mesenchymal-specific" "mesenchymal-to-epithelial" "mesenchyme" "mesenchymoangioblast-like" "mesendoderm" "mesentery" "mesh-like" "meshwork" "meshworks" "mesoderm" "mesoscale" "meta-analytic" "meta-regression" "meta-static" "metabolically-stressed" "metabolome" "metal-bound" "metal-response" "metalloestrogen" "metalloestrogens" "metalloproteinase-1" "metastamir" "metastamirs" "metastasis-related" "metastectomy" "methyl-guanosine" "methyl-lysine" "methyladenine" "methylcytosine" "methylome" "miR-100" "miR-101" "miR-103" "miR-105" "miR-105-specific" "miR-106" "miR-106b" "miR-107" "miR-122" "miR-1225-5p" "miR-122KO" "miR-124" "miR-124-based" "miR-124-induced" "miR-124-mediated" "miR-1246" "miR-124a" "miR-125b-1" "miR-125b-sponge-transfected" "miR-126" "miR-128" "miR-129" "miR-130b" "miR-133" "miR-137" "miR-138" "miR-141" "miR-143" "miR-143-based" "miR-144" "miR-145" "miR-146" "miR-146a" "miR-148a" "miR-15" "miR-155" "miR-155-induced" "miR-15a" "miR-16" "miR-17" "miR-17-92" "miR-1915" "miR-192" "miR-193a" "miR-195" "miR-196a" "miR-197" "miR-199a" "miR-19b" "miR-200" "miR-200-independent" "miR-200-promoter-Luc" "miR-200b" "miR-203" "miR-205" "miR-20a" "miR-21-AR" "miR-21-controlled" "miR-21-forced" "miR-21-induced" "miR-21-liposomal" "miR-21-mediated" "miR-21-regulated" "miR-21-targeted" "miR-214" "miR-215" "miR-22" "miR-25" "miR-26a" "miR-26b" "miR-27a" "miR-27a*-IH" "miR-27a-SL" "miR-27b" "miR-27b-3p" "miR-27b-5p" "miR-29a" "miR-29b-driven" "miR-29c" "miR-30d" "miR-31" "miR-329" "miR-329-expression" "miR-329-inhibited" "miR-329-overexpressing" "miR-34" "miR-34-dependent" "miR-34-mediated" "miR-34-regulated" "miR-34b" "miR-34c" "miR-34c-depleted" "miR-34c-expressing" "miR-368" "miR-371-5p" "miR-376" "miR-376a" "miR-376b" "miR-376c" "miR-376c-3p" "miR-376c-transfected" "miR-379" "miR-379-410" "miR-429" "miR-433" "miR-433-binding" "miR-449a" "miR-451" "miR-494" "miR-503" "miR-503-binding" "miR-503-regulated" "miR-503-suppressed" "miR-503-transfected" "miR-675" "miR-744" "miR-766" "miR-768-3p" "miR-768-5p" "miR-9" "miR-93" "miR-99a" "miR-99b" "miR-US4-1" "miR-negative" "miR-transfer" "miR141" "miR145" "miR17" "miR200" "miR200a" "miR200b-200a-429" "miR200b-independent" "miR200c-141" "miR379" "miR768-3p" "miR99b" "miRNA" "miRNA-125b" "miRNA-125b-1" "miRNA-141" "miRNA-143" "miRNA-200a" "miRNA-200c" "miRNA-21" "miRNA-576" "miRNA-767" "miRNA-768" "miRNA-768-3p" "miRNA-768-5p" "miRNA-886-5p" "miRNA200b-200a-429" "miRNA200c" "miRNA768-3p" "miRanda" "miRtarget2" "micro-PET" "micro-aggregates" "micro-biosensor" "micro-dissection" "micro-homologies" "micro-irradiation" "micro-lesions" "micro-molar" "micro-ribonucleic" "micro-vascular" "microRNA" "microRNA-124" "microRNA-204" "microRNA-21" "microRNA-26a" "microRNA-503" "microRNAs" "microdomains" "microenvironment-mediated" "micrographs" "micropipette" "microsatellite" "microtiter" "microtubule-associated" "microvasculature" "microvesicles" "microvessel" "microvessels" "mid-G1" "mid-gestation" "mid-late" "mid-plane" "midbrain" "midbrain–hindbrain" "midzone" "military-related" "milk-derived" "milk-miR-29b-mediated" "milk´s" "minP" "minP≤0.05" "mini-satellites" "minor-groove" "mir-143" "mir-29a" "mir-29c" "mir200c" "mis-localization" "mis-localize" "mis-segregate" "mis-segregation" "mis-sense" "missense" "mmBrca2" "mmpTRPC63p-luc2" "moDC" "moDCs" "mock-infected" "mock-transfected" "mock-treated" "moderate-strong" "moderate-to-severe" "modifica-tions" "modifications" "moesinezrin-radixin–like" "molecules" "mono-O-GlcNAcylated" "mono-SUMOylated" "mono-cultured" "mono-exponential" "mono-lobed" "mono-palmitoylated" "mono-palmitoylation" "mono-therapy" "mono-treatment" "mono-treatments" "mono-ubiquitin" "monoamine" "monocyte-derived" "monocyte-endothelial" "monocyte-lineage" "monocyte-microglial" "monolayer" "monomer-oligomer" "monosomy" "monotherapy" "months" "morbidities" "more-or-less" "more-than-10-fold" "morpholino" "morpholino-IPQA" "morpholinos" "morphology-dependent" "morphometry" "mortem" "mother-bud" "motile" "mouthwash" "mtp53" "muCIA" "muCIA2A" "muCIA2A-myc" "mucosa" "multi-SNPs" "multi-cellular" "multi-centric" "multi-colour" "multi-copy" "multi-drug" "multi-ethnic" "multi-factorial" "multi-functional" "multi-institutional" "multi-meric" "multi-modality" "multi-organ" "multi-parametric" "multi-protein" "multi-stage" "multi-step" "multi-subunit" "multi-variate" "multi-vesicular" "multidomain" "multiforme" "multimers" "multiple-target" "multiple-testing" "multiplex-ligation-dependent" "multiprotein" "multisite" "multistage" "multisubunit" "multivariate" "muscle-invasive" "muscle-specific" "muscleblind-like-1" "mut1" "mut2" "mutant-NSCLC" "mutations" "mutationsNotch2" "mutp53" "myDC" "myDCs" "myc-CK1δ" "myelopathy" "myocardium" "myocyte-specific" "myoepithelium" "myofiber" "myofibroblast-like" "myoid" "myosin-II" "myosinII" "myotonia" "myotonic-dystrophy-like" "n-6" "n-fold" "n=1" "n=103" "n=118" "n=13" "n=16" "n=195" "n=2" "n=20" "n=23" "n=3" "n=30" "n=34" "n=35" "n=36" "n=4" "n=40" "n=5" "n=6" "n=7" "n=8" "n=84" "n=9" "nLC-MALDI-TOF" "nLC-Q-TOF" "nRNP" "nXPA" "nano" "nano-biosensor" "nano-scale" "nanoLC-MS" "nanoscale" "nanotube-like" "napsin" "naïve" "near-complete" "near-endogenous" "near-field" "near-infrared" "near-normal" "near-saturating" "near-significance" "near-stoichiometric" "nearMECP2" "necropsy" "necrostatin-5" "necrostatins" "negative-curvature" "negative-feedback" "neo-RSK4" "neo-adjuvant" "neoadjuvant" "neocortex" "neointima" "neonate´s" "nephritis-like" "nephropathy" "nerves" "network-dependent" "network-level" "neu-positive" "neurite" "neuroendocrine" "neuroepithelium" "neuron-like" "neuronal-enriched" "neuronal-like" "neuropathology" "neurosphere" "neurospheres" "neurosurgery" "neutrophil-like" "never-smokers" "never-smoking" "new-onset" "newly-generated" "next-generation" "nick-end" "nigricans" "nitro" "nitrosoguanidine" "no-flow" "no-smoking" "node-positive" "nonLR" "noncardia" "noncarriers" "nonhistone" "nonmalignant" "nonmeta-bolizable" "nonmuscle" "nonredundant" "nonsense-mediated" "nontarget" "normal-like" "not-yet" "nt" "ntRNA" "nts" "nucleatum" "nucleophosmin1" "nucleus-only" "nucleus-positive" "nutrient-proficient" "nutrient-replete" "nutrient-response" "nystagmus" "n = 103" "n = 2" "n = 5" "n = 6" "n = 7" "n = 8" "n = 1" "n = 13" "n = 16" "n = 2" "n = 20" "n = 23" "n = 3" "n = 4" "n = 5" "n = 6" "n = 8" "oBII" "oHSV" "occludens-1" "occludes" "occurrences" "octamers" "octyl-glucoside" "oestrogen" "oestrogens" "of-transcription" "of4EBP1" "ofCdk6" "ofMBNL1" "off-target" "off-the-shelf" "ofp21" "ofp27" "ofp53" "of≤24" "oil-derived" "oil-red" "oldPyMT" "oleic" "oligo" "oligodendroglial-predominant" "oligonucleotide-PCR" "oligos" "on-column" "on-going" "on-site" "on-treatment" "on-trial" "onGrm1" "oncogene-driven" "oncogenes" "oncology" "oncomir" "one-copy" "one-dimensional" "one-electron" "one-ended" "one-factor" "one-fifth" "one-half" "one-sided" "one-step" "one-third" "one-thousand" "one-way" "open-angle" "open-label" "orGrm5" "orHomer1" "orPyMT" "orchidectomy" "organoids" "ortholog" "orthologue" "orthologues" "osteoblasts" "osteogenic-like" "outcome–namely" "over-activate" "over-activated" "over-activation" "over-interpret" "over-interpreted" "over-phosphorylation" "over-stimulate" "over-treatment" "overview" "oxoG" "oxygenase-1" "p(NBRE)" "p-c-Met" "p-c-met" "p110a" "p120-VE" "p120-catnin" "p125luc" "p16+" "p16-Leiden" "p16-defective" "p16-proficient" "p160s" "p21WAF1" "p21waf1" "p27SJ" "p27kip" "p27–30" "p300-ASH2L" "p300-dependent" "p300-enhanced" "p38CKO" "p38MAPK" "p38SJ" "p38i" "p38α-dependence" "p38β" "p3xE2F-luc" "p4EBP1" "p50α" "p53-DNA" "p53-RE" "p53-SET1C" "p53-and" "p53-binding-site" "p53-defective" "p53-dependent" "p53-haploinsufficient" "p53-minimal" "p53-null" "p53-p300" "p53-promoter" "p53-reporter" "p53C" "p53CKO" "p53ER" "p53MH" "p53R175H" "p53R273H" "p53R280K" "p53REs" "p53WT" "p55α" "p62ΔTB" "p70S6" "p85α" "p90rskSer380" "p=0.00001" "p=0.00002" "p=0.00003" "p=0.00004" "p=0.00009" "p=0.0001" "p=0.00014" "p=0.00016" "p=0.00017" "p=0.00019" "p=0.0002" "p=0.000215" "p=0.00022" "p=0.00037" "p=0.00039" "p=0.0004" "p=0.0008" "p=0.001" "p=0.0012" "p=0.0013" "p=0.0014" "p=0.0015" "p=0.0016" "p=0.002" "p=0.0020" "p=0.0026" "p=0.003" "p=0.004" "p=0.0045" "p=0.0048" "p=0.006" "p=0.007" "p=0.008" "p=0.009" "p=0.0091" "p=0.01" "p=0.012" "p=0.013" "p=0.014" "p=0.015" "p=0.016" "p=0.0161" "p=0.017" "p=0.018" "p=0.019" "p=0.0196" "p=0.02" "p=0.020" "p=0.022" "p=0.023" "p=0.024" "p=0.0247" "p=0.025" "p=0.029" "p=0.03" "p=0.030" "p=0.032" "p=0.033" "p=0.034" "p=0.036" "p=0.037" "p=0.04" "p=0.0413" "p=0.042" "p=0.043" "p=0.045" "p=0.05" "p=0.056" "p=0.068" "p=0.083" "p=0.086" "p=0.095" "p=0.14" "p=0.16" "p=0.17" "p=0.21" "p=0.26" "p=0.27" "p=0.319" "p=0.33" "p=0.37" "p=0.39" "p=0.40" "p=0.42" "p=0.427" "p=0.47" "p=0.49" "p=0.57" "p=0.59" "p=0.63" "p=0.70" "p=0.71" "p=0.8" "p=0.802" "p=0.83" "p=0.95" "p=1" "p=1.0" "p=1.0×10" "p=1.1×10" "p=1.3×10" "p=1.4" "p=1.4×10" "p=1.6" "p=1.6×10" "p=2.0×10" "p=2.1×10" "p=2.3×10" "p=2.5×10" "p=2.6×10" "p=2.7×10" "p=2.9×10" "p=3.2×10" "p=3.3×10" "p=3.6×10" "p=3.8×10" "p=3.9×10" "p=4.1×10" "p=4.6×10" "p=4.9×10" "p=5.3×10" "p=5.9×10" "p=6.7×10" "p=6×10" "p=7.5×10" "pA" "pAB240" "pAKT" "pAKT1" "pANCA" "pAP1-SEAP" "pAR-binding" "pATM" "pAb1801" "pAb421" "pAkt1" "pBABE-E2F1" "pBABE-E2F1-3" "pBabe" "pBabe-puro" "pCAG-myc-treated" "pCDNA-ING4" "pCEP4" "pCMV" "pCMV-5" "pCMV-Flag-MSH2" "pCR" "pCRKL" "pCdk5" "pChk1" "pDNA" "pDNA-PK" "pEBG" "pEF06R" "pEGFP-C1" "pEGFP-N1-p53" "pEGFP-Polκ" "pEGFP-hGLI1" "pEGFR" "pERK" "pERK1" "pERK5" "pEZ-AMO1" "pEZ-MT01" "pEZ-MT01-derived" "pF" "pFPV25.1" "pF±0.5" "pG68" "pGL-2" "pGL2-Bim-Basic" "pGL2-basic" "pGL3-208" "pGL3-275" "pGL3-Basic" "pGL3-basic" "pGL3-promoter" "pGL3M" "pGL3M-ROCK1-3" "pGL3–E2F1-3" "pGSK3β" "pH" "pHDAC2" "pINDUCER-DUSP4" "pJAK2" "pJak1" "pJak2" "pKAP-1" "pKIT" "pLEX-STAT3α" "pLEX-STAT3β" "pLL3.7-GFP" "pLL3.7-WT1" "pLL3.7-WT1-shRNA" "pLRP" "pLRP-ICD" "pMADD" "pMIR-GRB2mt" "pMIR-TGFBR2" "pMLC" "pMMP3" "pMSCV" "pMSCV-Cdk6-puro" "pMSCV-puro" "pMSCV-puro-based" "pN" "pNPM1" "pPAK1" "pPDGFRβ" "pPI" "pPI3-K" "pPKCα-p120" "pRBC" "pRBCs" "pRPA32" "pRTR" "pRTR-pri-miR-34a" "pS" "pS-P" "pS1126-P" "pS262" "pS32" "pS396" "pS473-AKT" "pS536" "pS647-DBN" "pS647-Drebrin" "pS6RP" "pSIN-Fluc" "pSTAT1" "pSTAT3" "pSTAT3α" "pSer146-Cdh1" "pSilencer2.1-U6-miR-203" "pSrc" "pSrc-416" "pSrc-Y416" "pStat" "pStat-3" "pSupFG1" "pSuper" "pSuper-27a" "pSuper-empty" "pT" "pT1-2" "pT180" "pT2-4" "pT3" "pT3-4" "pT4" "pT72" "pTNM" "pTP" "pTQ" "pTRPC" "pTRPC6p-luc1" "pTRPC6p-luc2" "pTopBP1" "pV" "pY1007" "pY1033" "pY1092" "pY1289" "pY239" "pY317" "pY705" "pack-year" "pack-years" "pair-wise" "paired-box" "paired-end" "palmitoyl" "pan-AKT" "pan-Bcl-2" "pan-HDAC" "pan-HDACi" "pan-PI3K" "pan-Ras" "pan-SIRT" "pan-WT" "pan-caspase" "pan-isoform" "pan-neurotrophin" "pan-phosphotyrosine" "pan-specific" "papillary-pattern" "par-4" "para-aminosalicyclic" "paracrine" "paralog" "paralogues" "paraproteins" "parenchyma" "parental-506" "parkin-Pp53" "parotid" "parthanatos" "pathogen-associated" "pathogen-recognition" "pathophysiology" "pathways" "pathways-homologous" "patient-tumor" "patients" "pattern-based" "pattern-recognition" "pcDNA-His-GLI1" "pcDNA1" "pcDNA3-Notch3-ICD" "pcDNA3-Par-4" "pcDNA3-THAP1" "pcDNA3.1" "pcDNA3.1-E2F1" "pcDNA3.1-EGFP" "pcDNA3.1-EGFP-NLK" "pcDNA3.1-HA-E2F1" "pcDNA3.1-c-Jun" "pcDNA3.1-entry" "pcDNA3.1-miR-124" "pcDNA3.1-myc-HisA" "pediatric-specific" "penetrance" "penton" "peptidase-4" "peptidase–activating" "peptide-1" "peptide-mimic" "peptidyl-prolyl" "per-allele" "per-test" "perception-linked" "peri-cancer" "peri-nuclear" "peri-operative" "peri-tumor" "peritoneum" "pes-ARKO–TRAMP" "pf11eei" "pf11ees" "pf12" "pf12ei" "pf12es" "pf21" "pf21s" "pf22s" "pfEMP-1" "phTH-3174-Luc" "phase-contrast" "phase-specific" "phenome" "phenome-associations" "phenome-wide" "phenotype-genotype" "phenyl" "phos-phatidylinositol-3,4,5-trisphosphate" "phosphatase-kinase" "phosphatidylbutanol-d" "phosphatidylinositol-3-kinase–like" "phosphatidylinositol-3-phosphate" "phospho-EGFR" "phospho-Ets2" "phospho-SFK" "phospho-Src" "phospho-c-Met" "phosphoAkt" "phosphoHER3" "phosphoHER4" "phosphoJAK" "phosphoTyr317" "phosphoatase-mediated" "phosphoinositide-3" "phosphoinositides" "phosphopeptide" "phosphopeptides" "phosphor-Igf1rβ" "phosphor-Ser" "phosphor-array" "phosphor-arrays" "phosphorylation-SFKs-Syk" "phosphosignals" "phosphosites" "phosphotyrosines" "phosphotyrosyl" "photo-converted" "photo-stability" "photo-switchable" "photo-switching" "photoacceptors" "photonuclear-specific" "photoproducts" "phyllodes" "physical-induction" "physician-referral" "pi3k1" "picoseconds" "pifithrin-α" "pixel" "pixels" "place-cell" "placebo-controlled" "plakophilin-1" "plasma-membrane-located" "plasmacytoid" "plasmids" "plasmin" "plasmon" "platinum-DNA" "platinum–DNA" "ploidy" "plug-weight" "pluripotency-associated" "pm" "pmaxGFP" "pmir-GLO" "pmir-GLO-ATG16L1-3" "point-mutated" "point-mutation" "pol-defective" "polarity-associated" "pola­rization" "polo-box" "polo-like" "poly-ADP" "poly-sumoylated" "poly-sumoylation" "poly-ubiquination" "polyADP" "polyI" "polycomb-repressive" "polymerase-1" "polymerase-η" "polymorphism" "polymorphisms" "polynucleotide" "polynucleotides" "polyprotein" "polyproteins" "polysomy" "polyubiquitine-chains" "pontine" "poorer" "poorly-differentiated" "populations" "pore-forming" "positive-control" "post-CPT" "post-GWAS" "post-IR" "post-MI" "post-PCN" "post-SCI" "post-UV" "post-adjuvant" "post-autopsy" "post-culturing" "post-erlotinib-treated" "post-exercise" "post-hoc" "post-implantation" "post-incubation" "post-infection" "post-injection" "post-injury" "post-integration" "post-intracarotid" "post-irradiation" "post-ischemic" "post-menopausal" "post-mitosis" "post-mitotic" "post-mortem" "post-natal" "post-nuclear" "post-operative" "post-partum" "post-pemetrexed" "post-pristane" "post-procedure" "post-radiotherapy" "post-replicative" "post-small" "post-sort" "post-synaptic" "post-transcription" "post-transcriptional" "post-transcriptionally" "post-transcriptomic" "post-transfection" "post-translation" "post-translational" "post-translationally" "post-treatment" "post-zygotic" "postmortem" "postpartum" "power=0.8" "pph21" "predicted-to-be-deleterious" "pressure-induced" "pretest" "pri" "pri-let-7" "pri-miR-122" "pri-miR-125b-1" "pri-miR-125b-2" "pri-miR-34a" "primary-NSCLC" "primitive-NSCLC" "prion-like" "prionoid" "priori" "pro-EMT" "pro-IL-1α" "pro-IL-1β" "pro-IL1β" "pro-LC3" "pro-angiogenic" "pro-apoptosis" "pro-arrest" "pro-carcinogenic" "pro-caspase-1" "pro-death" "pro-differentiation" "pro-fibrotic" "pro-growth" "pro-inflammation" "pro-inflammatory" "pro-inflammatory-secretory" "pro-invasive" "pro-ligand" "pro-ligands" "pro-metastatic" "pro-migratory" "pro-proliferative" "pro-protein" "pro-senescence" "pro-survival" "pro-tumor" "pro-tumorigenic" "pro-tumour" "pro-tumourigenic" "proMMP-9" "proband" "probands" "probeset" "probeset-by-probeset" "probesets" "procaspase-3" "progenitors" "progesterone-receptor-negative" "prognosis-associated" "programs" "prolactin-acidosis" "proliferator-activated" "proline-stretch" "promoter-associated" "promoter-distal" "promoter-reporter" "promoter-specific" "promyeloid" "proof-of-concept" "proof-of-principal" "proof-of-principle" "propria" "prostaglandins" "prostatectomy" "proteasome-mediated" "protein-1" "protein-10" "protein-2" "protein-DNA" "protein-coding" "protein-fusion" "protein-interaction" "protein-level" "protein-like" "protein-like-4" "protein-lipid" "protein-membrane" "protein-only" "proteins" "protein–DNA" "protein–drug" "protein–platinum" "proteome" "proteomes" "proteosome" "protocol-quality" "protofibrils" "proton-dependent" "proton-induced" "protooncogene" "protrusion–retraction" "proven" "proximity-based" "pro–α-factor" "pseudo-aggregates" "pseudo-hypertrophy" "pseudo-kinase" "pseudogenes" "pseudovirus" "psiCHECK2" "pull-down" "pull-downs" "purine-pyrimidine" "puro" "pyroglutamine" "p " "p = 0.001" "p = 0.0012" "p = 0.0013" "p = 0.002" "p = 0.003" "p = 0.004" "p = 0.006" "p = 0.007" "p = 0.008" "p = 0.009" "p = 0.01" "p = 0.022" "p = 0.029" "p = 0.03" "p = 0.04" "p = 0.042" "p = 0.068" "p≤0.05" "qBiomarker" "qChIP" "qPCR" "quality-controlled" "quantile-quantile" "quasi-insufficiency" "quinazolin-6-yl" "quinone oxidoreductase" "quinoxaline" "r2" "r2=0.23" "r=-0.542" "r=-0.556" "r=-0.625" "r=-0.633" "r=-0.769" "r=0.043" "r=0.235" "r=0.237" "r=0.249" "r=0.254" "r=0.260" "r=0.264" "r=0.268" "r=0.284" "r=0.300" "r=0.357" "r=0.380" "r=0.410" "r=0.450" "r=0.480" "r=0.513" "r=0.517" "r=0.520" "r=0.525" "r=0.532" "r=0.544" "r=0.547" "r=0.601" "r=0.606" "r=0.695" "r=0.707" "rASB10" "rASB10v3" "rIL-12" "rIL-27" "rIL-4" "rIL-6" "rIL-6-stimulated" "rQNestin34.5" "rTg4510" "rVista" "rVpr" "race-based" "race-specific" "radiation-induced" "radiation-mediated" "radiation-stimulated" "radiation-treated" "radio-HPLC" "radio-resistance" "radio-therapeutic" "radio-therapy" "radioresistance" "radioresistant" "radiosurgery" "radiotracer" "random-effect" "random-effects" "rank-sum" "rapalog" "rapalogs" "rapalogues" "rare-cutting" "rarer" "ratio=1.90" "ratio=2.34" "rationally-designed" "ratio≥2" "re-ChIP" "re-ChIPed" "re-added" "re-addition" "re-administration" "re-analyzed" "re-annealing" "re-attach" "re-biopsied" "re-biopsy" "re-challenged" "re-characterization" "re-consider" "re-constituted" "re-counted" "re-distributed" "re-distributing" "re-distribution" "re-engineering" "re-enter" "re-entry" "re-establish" "re-establishment" "re-examine" "re-examined" "re-express" "re-expressed" "re-expressing" "re-expression" "re-fashioned" "re-feeding" "re-grow" "re-growth" "re-incubated" "re-initiate" "re-internalized" "re-introduction" "re-localization" "re-opened" "re-organisation" "re-organization" "re-plated" "re-quantified" "re-sensitize" "re-stimulation" "re-synthesis" "re-tested" "re-treatment" "re-uptaking" "re-using" "reChIP" "reaction-restriction" "reaction–restriction" "read-out" "readout" "readouts" "receptor-2" "receptor-Fc" "receptor-chain" "receptor-ligand" "receptor-like" "receptor-proximal" "receptor-receptor" "receptor-α" "receptor-γ" "receptors-negative" "red-colored" "red-emitting" "red-labeled" "red-stained" "ref" "refractoriness" "refs" "region-leucine" "regs" "regulators" "regulatory-associated" "renilla" "replication-associated" "replication-blocking" "replication-born" "replicons" "reponse" "reporter-coding" "reporter-gene" "repressors" "repressors–including" "repressp15" "research-use" "residue–residue" "resistant-cellular" "respiratory-related" "responders" "resting-state" "resting-states" "retrovirus" "reuptake" "reverse-trancriptase" "reverse-transcripase" "rhLOXL2" "rhodamine-phalloidin" "ribophorin" "ribose" "ribose-5-phosphate" "ring-like" "risk-associated" "risk-stratification" "risk-stratify" "rod-like" "rotarod" "round-like" "rs1001581" "rs1005346" "rs1006737" "rs1018119" "rs10306135" "rs1034528" "rs10463316" "rs10497968" "rs10506328" "rs10860757" "rs10914144" "rs11065987" "rs11077947" "rs11238349" "rs11249433" "rs11255458" "rs113420705" "rs1136201" "rs1137070" "rs1155865" "rs115939516" "rs11602954" "rs11658698" "rs1198588" "rs12089041" "rs12146808" "rs12190287" "rs12190287-G" "rs12190827" "rs12192087" "rs12192087-C" "rs12212067" "rs12450046" "rs12524865" "rs12526453" "rs12602885" "rs12680762" "rs12845396" "rs13190932" "rs13190932_A + " "rs13190932_G" "rs13190932_G " "rs13196377" "rs13196377_A + " "rs13196377_G" "rs13196377_G " "rs13210247" "rs13210247_A" "rs13210247_G" "rs1333049" "rs13538" "rs1354034" "rs1382566" "rs143181039" "rs1462872" "rs1471384" "rs1522813" "rs152524" "rs1566819" "rs1596776" "rs16260" "rs16430" "rs1668873" "rs16847082" "rs16847416" "rs16905644" "rs17036508" "rs17099156" "rs17408757" "rs1745837" "rs17586365" "rs17691888" "rs1800954" "rs1801200" "rs1810132" "rs182123615" "rs1836721" "rs1846522" "rs1883965" "rs1887582" "rs1902023" "rs1946816" "rs1960669" "rs1978873" "rs1982346" "rs20417" "rs20424" "rs2075112" "rs2077647" "rs2079147" "rs2180748" "rs2233678" "rs2233679" "rs2233682" "rs2234693" "rs2237570" "rs2247128" "rs2268641" "rs2274223" "rs2285332" "rs2290257" "rs2295080" "rs240943" "rs2436389" "rs250092" "rs250108" "rs2536" "rs25405" "rs25406" "rs25487" "rs2628476" "rs265155" "rs2736340" "rs2736340-located" "rs2745557" "rs28362491" "rs28493229" "rs2943641" "rs2943641T-allele" "rs2950390" "rs2981582" "rs308379" "rs308382" "rs308435" "rs3087386" "rs3184504" "rs3217989" "rs334558" "rs334558 " "rs33980500" "rs33980500_T" "rs33980500_T " "rs342240" "rs35220450" "rs35682" "rs35683" "rs36228499" "rs3729558" "rs3730668" "rs3755557" "rs3755557 " "rs3755557–rs334558" "rs3789587" "rs3792136" "rs3806317" "rs381299" "rs3819299" "rs3842787" "rs385893" "rs4006531" "rs4244285" "rs4252596" "rs4379723" "rs4481204" "rs458017" "rs462779" "rs465646" "rs4680" "rs4730751" "rs4746554" "rs4796793" "rs4821877" "rs4895441" "rs4912868" "rs4912876" "rs4969170" "rs4977574" "rs5029748" "rs5030980" "rs5744533" "rs5744533-rs5744724" "rs5744720" "rs5744724" "rs6001512" "rs6065" "rs6314" "rs6475606" "rs6478565" "rs653178" "rs6534365" "rs6538998" "rs6546857" "rs6895139" "rs6941583" "rs6954351" "rs6993775" "rs6995402" "rs7101" "rs712829" "rs712830" "rs71372224" "rs7149242" "rs7216812" "rs72689236" "rs7308665" "rs739496" "rs749924" "rs7543272" "rs7700205" "rs7768030" "rs78190160" "rs7961894" "rs8074277" "rs8305" "rs845552" "rs869190" "rs879500" "rs912127" "rs9324889" "rs9349379" "rs9399137" "rs9622978" "rs9660992" "rs9788973" "rs9900280" "rythroid" "s00403-013-1407-9" "s13402-013-0143-7" "s6" "sCD40L" "saline-treated" "salt-and-pepper" "salt-bridge" "same-patient" "sapiens" "scatterplot" "schute" "score≤7" "score≥7" "scorpion-amplified" "scratch-wound" "se" "sec12-4" "sec2-41" "sec4-8" "second-generation" "second-line" "second-most-common" "second-passage" "second-site" "second-wave" "secondaries" "seed-sequence-dependent" "seeding-nucleation" "seizure-like" "selectinand" "self-administration" "self-aggregation" "self-assembly" "self-associate" "self-association" "self-cannibalization" "self-cleavage" "self-cleavages" "self-defense" "self-digestion" "self-duplication" "self-interaction" "self-limited" "self-multimerize" "self-oligomerizes" "self-peptide-MHC-I" "self-reactive" "self-regulated" "self-renew" "self-renewal" "self-renewal-related" "self-reported" "self-sufficiency" "self-tolerance" "self-tolerant" "self-ubiquitination" "semi" "semi-quantitative" "semi-solid" "senescence-associated-β-galactosidase" "sensitizers" "sepharose-Ac-TDG-peptide" "seq" "sequelae" "sequence-based" "sequence-independent" "sequence-specific" "sequestome1" "serine-threnine" "serines" "serosa" "set-point" "set-up" "several-micro-second" "several-year" "severely-affected" "sex-associated" "sex-differences" "sex-linked" "sex-specific" "sh-Amot" "sh-E6" "sh177" "shApi5" "shCCAR1" "shCTL" "shCdh1-treated" "shCont" "shControl" "shCtrl" "shDUSP4" "shEphA2" "shHbo1-4" "shHbo1-5" "shHbo1-5R" "shKIT" "shNC" "shNS" "shNT" "shRIP" "shRIP-1-L11" "shRIP1" "shRIP1-L11" "shRNA" "shRNA-empty" "shRNA1" "shRNAs" "shROCK1" "shROCK1#1" "shROCK1-#1" "shRPN" "shRPN2-UTR" "shRPN2-site2" "shRSK4" "shRSK4-GRC-1" "shSAFB1" "shSCR" "shSTAT3" "shTAZ" "shTRAF6" "shUNG" "shYAP" "sham-treatment" "shape-induced" "sheet-like" "shock-induced" "short-in" "short-patch" "short-range" "short-term" "shut-off" "shβ-TRCP" "si-p53-1" "si-p53-2" "si3098" "si471" "siAR" "siApi5" "siCON" "siCONTROL" "siCont" "siDUSP4" "siE2F1" "siE2F6" "siEGFR" "siFBXL17" "siGRB2" "siGRB2-1" "siGRB2-2" "siGRB2s" "siKPNA2" "siKPNA2#1" "siKPNA2#1cells" "siKPNA2#2" "siLSD#1" "siLSD#2" "siMBNL1-Ex5" "siMMP3" "siMSH2" "siNotch1" "siNotch2" "siNotch3" "siPARG" "siPP6-07" "siPP6-08" "siPP6-transfected" "siPTEN" "siRNA" "siRNA+pcDNA3.1+Myc" "siRNA-1" "siRNA-2" "siRNA-2-treated" "siRNA-Neg" "siRNA-RB" "siRNAs" "siROCK" "siROCK1-#2" "siROCK1-#3" "siRPL11" "siRPL23" "siRPL29" "siRPL30" "siRPL37" "siRPL5" "siRPS14" "siRPS15" "siRPS20" "siRPS6" "siSTAT3" "siTiam1" "sib-pair" "sibling-control" "side-by-side" "side-effect" "side-population" "sidechain" "signal-to-background" "signaling-driven" "signaling-to-protrusion" "signed-rank" "silencing-mediated" "silico" "simpler" "simplest" "single-base" "single-break" "single-cell" "single-cell-based" "single-dose" "single-drug" "single-gene" "single-locus" "single-marker" "single-mutant" "single-nucleotide" "single-regimen" "single-strand" "single-target" "singleEts2" "sino" "sino-nasal" "sirtuin" "sit4" "site-PCR" "site-specific" "sites" "situ" "sixty-five" "siβ-TRCP" "slow-infusion" "slow-moving" "slow-release" "slower-migrating" "slowly-progressive" "smLRP1" "small-angle" "small-cell" "small-hairpin" "small-hairpin-RNA" "small-interfering" "small-interfering-RNA" "small-molecule" "small-vessel" "smokers" "snMcl1" "snc2" "snc2-M2" "snc2-V39M42A" "snoRNA" "socio-economic" "sodium-induced" "soft-agar" "soft-tissue" "solid-predominant" "solute" "solutes" "spacer" "spacers" "spatio" "spatio-microenvironmental" "spatio-temporal" "spec-trometry" "specific-inhibition" "speck-like" "sphere-formation" "sphere-like" "spheroid-like" "sphingosine" "spike-like" "spiked-in" "spina" "spindle-like" "spindle-shape" "spinning-disk" "splice-site" "spliced-in" "spliceopathy" "spn-A" "spn-B" "spn-C" "spn-D" "spongiform" "spot-like" "squamous-cell" "square-discriminant" "srGAP" "srGAP1-dependent" "srGAP1-depleted" "srGAP1-mediated" "srGAPs" "stable-isotope" "stainings" "stand-alone" "start-sites" "starved-cells" "steady-state" "stem-cell" "stem-cell-based" "stem-cells" "stem-like" "stem-loop" "stemness" "step-by-step" "step-wise" "stepwise" "steroid-resistant" "strand-specific" "streptavidin-flag-S" "streptavidin–biotin" "stress-activated" "stress-dependent" "stress-induced" "stress-inducible" "stress-mediated" "stress-specific" "stressful" "stressors" "stress–activated" "stress–responsive" "striations" "stroma-dominant" "stroma-poor" "stroma-rich" "stromal-derived" "stromal-epithelial" "stromal-expressed" "stromal-specific" "stromal–epithelial" "stromelysin" "structure-function" "structure-specific" "structure-wise" "structure–function" "study-atherosclerosis" "study-collective" "sub-G1" "sub-analysis" "sub-cellular" "sub-class" "sub-clinical" "sub-complex" "sub-complexes" "sub-confluent" "sub-cortical" "sub-cutaneous" "sub-domains" "sub-endothelial" "sub-epithelial" "sub-family" "sub-group" "sub-kilobase" "sub-lethal" "sub-line" "sub-lines" "sub-localization" "sub-pathways" "sub-population" "sub-region" "sub-regions" "sub-section" "sub-set" "sub-stoichiometric" "sub-threshold" "sub-toxic" "sub-types" "sub-zero" "subG" "subG1" "subclass" "subclasses" "subcomplexes" "subdiploid" "sublines" "subphenotypes" "subset" "subsets" "substrate-1" "substrate-MADD" "substrates" "substratesp70" "subtilisin" "subtilisin-like" "subtype" "succinate" "succinimidylpropionate" "sugar-phosphate" "sulfonate" "sun-exposure" "super-antigens" "super-repressor" "super-shift" "super-shifted" "supernatant" "supernatants" "suppressor-like" "suppressor-of-fused" "suppressp70" "supra-lethal" "sural" "survival-concentration" "survive-to" "swa2" "switch-like" "switching-off" "symmetry-related" "synapse" "synapses" "synthesis-dependent" "t5" "tARPC" "tARPCs" "tagSNP" "tagSNPs" "tail-vein" "tamoxifin" "tandem-affinity" "target-cell" "target-gene" "tau–microtubule" "tdTomato" "telomerase-accessory" "telomerase-associated" "telomerase-independent" "temperature-sensitive" "template-containing" "temporal-specific" "ten-eleven" "tension-dependent" "terminal-deoxynucleotidyl-transferase" "tert-butanol" "test-threshold" "tet-off" "tet-transactivator" "tetBim-ECFP-Mcl1L" "tetBim-EYFP-Mcl1L" "tetNoxa-ECFP-Mcl1L" "tetNoxa-EYFP-Mcl1L" "thanp53" "thatp27" "the-765" "theFoxO3a" "theGrm1" "theRosa26" "thep27" "therapy-based" "therapy-naïve" "therapy-resistance" "therapy-resistant" "therapy-resistant-MCL" "therapy-treated" "thio-phosphoramidate" "thioflavin" "third-highest" "third-line" "third-most-changed" "thirty-nine" "three-arm" "three-component" "three-dimensional" "three-factor" "three-gene" "three-pathway" "three-quarter-sites" "three-stranded" "three-way" "threoine" "thrombocythemia" "through-out" "thymine–thymine" "thymocytes" "time-course" "time-dependant" "time-lapse" "time-point" "time-points" "time-to-progression" "time-to-recurrence" "tissue-dependant" "tissue-specific" "titer" "titers" "titres" "toEx5-MBNL1" "toTRAF6" "toll-like" "tomograms" "top-down" "top-right" "top53" "topology" "toses" "tosis" "total-JAK2" "toto" "toxicants" "toxicities" "trait-associated" "trans-bronchial" "trans-dominant" "trans-genes" "trans-membrane" "trans-phosphorlyation" "transcript-inductions" "transcription-3" "transcription-5a" "transcription-5b" "transcription-PCR" "transcription-competent" "transcription-quantitative" "transcriptome" "transcriptome-wide" "transcriptomes" "transcripts" "transducer" "transfectedHomer1" "transfections" "transferase-mediated" "transgenes" "transgenic-immunodeficient" "transit-amplifying" "transitional-type" "translation-stop" "translocase-1" "transplantedp53" "transwell" "transwells" "treatment-naive" "treatment-naïve" "treatments" "triangular-shaped" "triphosphate" "triple-ChIP" "triple-negative" "trisphosphate" "triton-insoluble" "trypsin-like" "tryptase-positive" "ts" "tsO45" "tubal" "tubo-ovarian" "tubule" "tubules" "tubulo-interstitial" "tumor-angiogenesis" "tumor-like" "tumor-promotive" "tumor-selectivity" "tumor-suppressive" "tumor-to-background" "tumor-to-blood" "tumor-to-muscle" "tumor-to-vector" "tumors" "tumour-associated" "tumour-derived" "tumour-growth" "tumour-node-metastasis" "tumour-propagation" "tumour-suppressive" "tumour-suppressor" "turn-over" "twenty-two" "two-SNP" "two-ended" "two-hit" "two-hour" "two-hybrid" "two-member" "two-pronged" "two-step" "two-tailed" "two-thirds" "two-tiered" "two-to-four" "two-way" "two-year" "twofold-higher" "type-1" "type-2-diabetes" "tyrosine-phosphorylation-dependent" "tyrosine-to-phenylalanine" "uHL-60" "ubiquitin-and" "ubiquitin-chain" "ubiquitination-defective" "ubiquitine" "ubiquitine-ligase" "ubiquitin–proteasome-mediated" "ubiquity-lation" "ug" "ultrastructure" "ultrathin" "ultraviolet-induced" "un" "un-surgery" "unarmed-ATC" "unclassified-IBD" "uncoupler" "under-powered" "under-replicated" "under-ridding" "undergoes" "undergone" "undertaken" "uni" "uni-directional" "univariate" "unresponsiveness" "up-to-date" "upto" "uracil-DNA" "urea" "users" "usingHomer1" "uteri" "uveal" "v-Ki-ras2" "v-erb-b2" "v-ets" "v-ki-ras2" "v1" "v2.2" "v3" "vIII" "values" "variants" "vascular-like" "veh" "vehicle-treated" "vera" "vesicle-associated" "vessels" "villi" "villus" "vimentin-null" "vinclocolin" "viral-induced" "viral-infected" "virally-transduced" "viremia" "virus-1" "virus-host" "virus-like" "vitro" "vivo" "vorinostat-epirubicin" "vorinsotat" "voxel" "vs.1" "vs.12" "vs.ErbB2" "vs.Ets2" "vs.PyMT" "vt" "vulgaris" "wavelength-dependent" "web-based" "websites" "well-adapted" "well-annotated" "well-being" "well-characterised" "well-circumscribed" "well-conserved" "well-coordinated" "well-defined" "well-demarcated" "well-designed" "well-differentiated" "well-documented" "well-formed" "well-matched" "well-powered" "well-recognized" "well-regulated" "well-resolved" "well-separated" "well-studied" "well-tolerated" "well-written" "western-blot" "western-blots" "western-blotting" "whole-brain" "whole-cell" "whole-exome" "whole-genome" "whole-tumor" "widefield" "wildtype-tumors" "withEts2" "withPARP1" "withdrawn" "within-family" "within-run" "wk" "workers" "workflow" "world-wide" "written" "wtMADD" "wtSTAT3" "wtp53" "x-E-x-x-aromatic" "x-Q-x-x-D" "x-ray" "x100" "xMAP" "xenotransplant" "xenotransplants" "y-axis" "yap1801" "yap1802" "year-old" "yet-to-be-identified" "z-VAD" "z-guggulsterone" "z-stacks" "zeta" "zinc-dependent" "zinc-mediated" "zipper-interacting" "zipper-like" "zona" "zsGreen" "zymography" "× 10" "×1" "×10" "×100" "×3" "×FLAG" "×His" "×MOG" "× 10" "× 10 " "× 10" "× 100" "Δ1" "Δ1-110" "Δ175–244" "Δ1–75" "Δ23-111" "Δ3" "Δ349" "Δ369" "Δ393–414" "Δ4" "Δ40p53" "Δ40p53-dependent" "Δ40p53-encoding" "Δ40p53-infected" "Δ40p53-transduced" "Δ40p53V" "Δ40p53V-transduced" "Δ431–490" "Δ628–630" "Δ746-750" "Δ8" "ΔATF3" "ΔC" "ΔC-box-Cdh1" "ΔC12" "ΔCREB" "ΔCore" "ΔCt" "ΔCtBP" "ΔCt " "ΔD" "ΔDBD2" "ΔE9" "ΔEF1" "ΔEGFR" "ΔEx3" "ΔEx5-MBNL" "ΔEx5-MBNL1" "ΔF" "ΔFHA" "ΔFizzy-Cdh1" "ΔG" "ΔKD" "ΔL" "ΔMADSMEF2" "ΔN" "ΔNES" "ΔNp73" "ΔOB" "ΔRING" "ΔS1" "ΔSAM" "ΔTB" "Δbromo" "Δcysteine" "Δcysteine-rich" "Δp85" "Δsit4" "ΔΔCt" "ΔΔCt " "ΔΨ" "ΔΨm" "ΨKX" "ΨKXE" "α--like" "α-1" "α-2" "α-6" "α-ARNT1" "α-Ac" "α-AhR" "α-BACH1" "α-EGFP" "α-ERα" "α-GFP" "α-Mst2" "α-amino" "α-and" "α-aquaporin-1" "α-cell" "α-cells" "α-globin-like" "α-helical" "α-helices" "α-ketoacid" "α-lactalbumin" "α-phalloidin" "α-receptor" "α-related" "α-subunits" "α0" "α2β1" "α3β1" "α4β1" "α5-integrin" "α5PPAA" "α5WT" "α6β4" "α7" "α=5×10" "αC" "αCD28" "αCD3" "αCDK4" "αCDK6" "αD" "αD–αE" "αE" "αERKO" "αG" "αV" "αcyclinD3" "αp27" "ανβ3" "β-2" "β-Lap" "β-Lap-induced" "β-Lap-treated" "β-Lapachone" "β-Lapachone-induced" "β-ME" "β-TRCP" "β-TRCP-dependent" "β-TRCP-depletion-mediated" "β-TRCP-mediated" "β-TRCP-recognizable" "β-TRCP1" "β-TRCP2" "β-activated" "β-catenin-non-response" "β-catenin-response" "β-chemotactic" "β-elimination" "β-fodrin" "β-globin-like" "β-lap" "β-lap-exposed" "β-lap-induced" "β-lap-resistant" "β-lap-treated" "β-lapachone" "β-lapachone-induced" "β-mercapoethanol" "β-oxidation" "β-peptide" "β-sheet" "β-sheet-rich" "β-sheets" "β-sodium" "β-subunit" "β-subunits" "β-transducing" "β1-6" "β1-6-branching" "β1-integrins" "β3" "β3-null" "β4–β7" "β6" "β7–β8" "β8" "βERKO" "βI" "βII" "βc" "βic" "β–activated" "γ-GCS" "γ-GCSh" "γ-globins" "γ-glutamyl-cysteine" "γ-irradiated" "γ-irradiation" "γ-phosphate" "γ-radiation" "γ-rays" "γ2" "γhistone2AX" "γδ-intergenic" "δ-cells" "δ-elimination" "ε-amino" "ε-dependent" "εC" "ζ-zeta" "ι-involved" "ι-mediated" "ι-related" "κB-luc" "μg" "μg " "μl" "μmol" "μmoles" "π-cation" "σ1" "χ2" "χ²" "ψ-K-x-D" "ψKxExxSP" "ϕ-x" "ϵRI" "”m" "€overruled" "↑G1" "∆11" "∆3" "∆C-TAD" "∆GAP" "∆IH" "∆N-TAD" "∆PAS" "∆bHLH" "∆basic" "−141" "−200b" "−429" "−β" "≧31.2%" "〈2" "fiber" "(p"))
null
https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/code/s/tools/ns-stuff/old-unknown/ns-unknown-rd-items-phase3-10401-10800.lisp
lisp
(IN-PACKAGE :SP) (DEFPARAMETER SPARSER::*NS-RD-PHASE3-10401-10800* '("2P-MRLC" "A+P" "A-172" "A-43" "A-498" "A-C" "A-D" "A-E" "A-GVGD" "A-H" "A-allele" "A-deficiency" "A-deficient" "A-loop" "A-type" "A1" "A1-treated" "A1062T" "A1257T" "A1315T" "A1k" "A2" "A20" "A20-1" "A20-2" "A20-2-resistant" "A20-OTUmt" "A20-ZnF5-7" "A20-ΔOTU" "A20-ΔZnF" "A202T" "A279T" "A2λ" "A366T" "A431-III" "A431-P" "A491ins" "A549P" "A5780G" "A750P" "A750del" "A840T" "A859T" "AAD-COUP-TFII" "AAD-NR" "AAV1" "AAV1-tTA" "AAV1-tTA-IRES-zsGreen" "ABPA" "ABT-869" "ACAs" "ACT-1" "ACY-738" "ACh" "AD001" "ADAM" "ADHWDSKNVSCKNC" "ADRr" "ADRrE2" "AEC" "AECs" "AEW541" "AF163764.1" "AFAC10" "AFU" "AG" "AG1204" "AG1478-treatment" "AG538" "AGGTCA" "AGK2" "AI-S" "AIB" "AIDS-infected" "AIEC" "AIIB2" "AJ289875.1" "AJCC" "AJK" "AK027769" "AKP" "AKTi" "AKTi-1" "ALIS" "ALMS1" "AM" "AMBRA" "AMP-K" "AMs" "ANRASSF1" "AO" "AP-1-like" "AP-1-luc" "AP-180" "AP-1A" "AP-1B" "AP-23573" "AP-MS" "AP12816a" "AP2γ" "AP4+RAS" "AP4-ER" "APBT2" "APBT6" "APLP1" "APPPPS1" "APPPS1" "APRs" "APSMs" "APV" "AQOA-A" "AR-N" "AR-co-activator" "AR-enhanced" "AR-gene" "AR-mediated" "AR-miR-21" "ARD527" "ARE-luciferase" "ARHGEF33" "ARKO" "ARMS–Scorpion" "ARMS–scorpion" "ARN-509" "ARNT1" "ARPCs" "ARRY-438162" "ARTPs" "ARVO" "AR–DNA" "AS-ODN" "AS-PCR" "ASC-J9" "ASCA" "ASC–J9" "ASP–PCR" "ATCC" "ATG6" "ATM-2" "ATM-and-Rad53-like" "ATM-pathway" "ATMi" "ATN1" "ATN2" "ATP-citrate" "ATR-dependent" "ATR-serine15" "ATRO" "ATS" "ATTG" "ATXN2" "AUF" "AX" "AY034471" "AY326428.1" "Ab708" "Abcam" "Abcl2" "Abnet" "Abr" "Ac-TDG" "AcK" "Actin-dependant" "Ad-GFP" "Ad-IκB" "Ad-PTEN" "Ad-Skp2" "Ad-ZBP-89" "Ad-β-Gal" "AdCARas" "AdCASrc" "AdDUSP4" "AdJLB1" "AdSpry4" "Adeno-Null" "Affymetrix" "Africa" "African" "African-American" "African-Americans" "Africans" "AgRP" "Agouti" "AhR-p38-C" "Akt-activation" "Akt-fibroblast" "Akt1" "Akt1promoted" "Alaskan" "Alb-cre" "Alexa" "Alexa488" "Alu" "Alzheimer" "Alzheimer´s" "Alzihamer" "America" "American" "Americans" "Ammirante" "Amot" "Amot-Yap" "Amot-p130N" "Amots" "Amsterdam" "Ant-D-loop" "Antigen" "Antineutrophil" "Api5" "Arf-null" "Arg-Val-Leu" "Arg-rich" "Arg194Trp" "Arg399Cln" "Arg399Gln" "Arizona" "Arp2" "Arq501" "Arq761" "Asian" "Asians" "Atox-1" "Autoantigen-1" "Aux1–Swa2p" "Avl9" "Avl9p" "Azare" "A + " "Aβo–PrP" "Aβ–PrP" "Aγ" "Aδ" "A–C" "A–S1C" "A–S4D" "A–S6E" "A→C" "A→G" "B-ATF" "B-D" "B-F" "B-acute" "B-boxes" "B-catenin" "B-family" "B-form" "B-lymphoid" "B-lymphoma" "B-lymphomas" "B-to-T-cell" "B-to-T-cell-connecting" "B-type" "B1" "B10" "B2" "B3" "B5" "B6" "B721.221-GFP-H-RasG12V" "B721.221-cell" "BACH1-FBXL17" "BACH1-MAF" "BAEC" "BAK1del" "BAK1mut" "BAK1wt" "BAPTA-AM" "BAW667" "BAW667+PPY-A" "BAX" "BBLF2" "BCAAs" "BCL-xl" "BCL11A-XL" "BCL2-immunoreactivity" "BCL2-like" "BCL2-negative" "BCL2-positive" "BCL7A" "BCR-ABL1" "BCSCs" "BDCA3" "BEMAD" "BGK" "BH1" "BH3-domain" "BH3-mimetic" "BH3-mimetics" "BH3-only" "BHA2.1" "BHT" "BILAG" "BIR2" "BIR3" "BIRB0796" "BJ" "BK" "BLBCs" "BM73" "BME" "BMIs" "BMI≤24" "BML" "BML-1" "BML-11" "BML-5" "BML-7" "BML281" "BMPR-1A" "BMPR-1B" "BMPRs" "BOADICEA" "BOLERO2" "BPH1" "BRAF+PTCs" "BRAF-AA" "BRAF-ED" "BRAF-genotype" "BRC" "BRCA2and" "BRCAPro" "BRCT–BRCT-mediated" "BRID" "BSCL1" "BSCL1-4" "BSCL3" "BSCL4" "BSE" "BTB474" "BUZ" "BXPC3s" "BZ-9000" "Background" "BafA" "Bak-independent" "Bannayan-Zonana" "Barbano" "Barry-Hamilton" "Basal" "Basel" "Basso" "Bcl" "Bcl-2-antagonist" "Bcl-XL" "Bcl-xl" "Bcl2" "Bcl2-family" "Bead-bound" "Beclin1-core" "Begg" "Begger" "Belfast" "Benjamini" "Benjamini-Hochberg" "Bennett" "Benvenuti" "Beva" "Bgl" "Bgl3" "BhGLM" "Bi" "Bi-transgenic" "BiFC" "Biesecker" "Bim" "Bim-S" "Bim-interaction" "Bio" "Bio-Rad" "BioRad" "Biosystems" "BirA" "BirA-tag" "Birmingham" "Bitplane" "Black" "Blood-borne" "Bmi1" "Bmi1-self" "Bmi1-targeting-shRNA" "Bolero-2" "Bonferroni" "Boroumand-Noughabi" "Bortezomib-treatment" "Boyden" "Bp65" "Br426" "Br731" "Branched-chain" "Brandwein" "Brandwein-Gensler" "BrdU-label" "Break-Induced" "Brenner" "Breslow" "Bristol" "Broader" "Btz" "Burkitt" "Bx" "Byers" "B–2D" "B–C" "B–D" "B–H" "C-C" "C-G" "C-Luc" "C-NHEJ" "C-NHEJ-dependent" "C-NHEJ-mediated" "C-TAD" "C-TADs" "C-allele" "C-allelecontaining" "C-helix" "C-labelled" "C-lobe" "C-lobes" "C-luc" "C-mass" "C-region" "C-sections" "C-src" "C-terminally" "C-treated" "C-type" "C1" "C1-mediated" "C10orf26" "C139A" "C147A" "C181S" "C184S" "C186S" "C18LL" "C1orf24" "C2" "C2-CH" "C2-domain" "C28" "C3" "C35-co-transfected" "C4" "C450ins" "C472S" "C540ins" "C56BL6J" "C57BL6" "C6" "C6orf47" "C779A" "C782A" "CAB" "CAIS" "CALHM1" "CALHM2" "CALHM3" "CALPAIN" "CALPAIN7" "CALR3" "CAP8AP2" "CARD14" "CARDIA" "CARN-like" "CARe" "CASMC" "CASP8AP2" "CASrc" "CC+GC" "CCAAT" "CCCG" "CCFR" "CCG-1423" "CCL" "CCL-20" "CCL2ab" "CCR2S" "CCR2atg" "CCT007093" "CCTNs" "CD-FBS" "CD-associated" "CD11cCre" "CD28-induced" "CD28RE" "CD44+" "CD44S" "CD44V" "CD44V6" "CD8-Nef" "CDC42BPG" "CDH-1" "CDH-2" "CDK4-6" "CDK4-D-type" "CDK6R31C" "CEC" "CED-10" "CELSR1" "CEP128" "CEP17" "CEP6" "CEP8" "CEU" "CFSs" "CFTR-172" "CFTR-172-induced" "CG" "CG-E" "CGAG" "CGH-microarrays" "CGL" "CH11" "CH99021" "CHI3L1" "CHME3" "CI1040" "CIA2" "CIA2A-CIA1" "CIA2A-IRP2" "CIA2B-CIA1-MMS19" "CIA2B-MMS19" "CICs" "CID-MS" "CIN3" "CINII" "CJO" "CK-1" "CK-19" "CK-2" "CKIδ" "CL" "CLB-Bar" "CLB-Ga" "CLB-Re" "CM5-postive" "CMV-driven" "CNNM2" "CNQX" "COG" "COLD-PCR" "COMPASS" "COPII" "COUP" "COUP-TF" "COUP-TFs" "COUPTF-II" "COX-2-765" "COX-IV" "CP-868,596" "CPSCs" "CR-1" "CR-2" "CRAC" "CRCC" "CREB-like" "CRIB" "CRL-5872" "CRM-197" "CRN2" "CRS-PCR" "CRs" "CSC-like" "CSCs" "CSPCs" "CSPs" "CT+CC" "CT+TT" "CTCE-9908" "CTCs" "CTG" "CTNNA3" "CTTNB1" "CVB3" "CVs" "CWWG" "CYP2C19*2" "Cadherin" "Calphostin" "CamKII-tTA" "CamKIIα-tTA" "Campenot" "Canu" "Capsulin" "Carlo" "Case1" "Case2" "Casein" "Caucasian" "Caucasians" "Cavin-1" "Cbp" "Cbp\\PAG" "Cd12" "Cdc25-EF" "Cdc42" "Cdk1" "Cdk11" "Cdk2" "Cdk4" "Cdk7" "Celsr" "Celsr1" "Cernunnos" "Cfd1-Nbp35" "ChIP" "ChIP-PCR" "ChIP-on-Chip" "ChIP-on-chip" "ChIP-qPCR" "ChIP-reChIP" "Chan" "Chang" "Chc1-RFP" "Chemically-engineered" "Chen" "Chi-square" "Chi-squares" "Chng" "Chompret" "Chrom" "Chung" "Cia2" "Cip" "Clark" "Class-I" "Classical-EMT" "CldU" "Clinico-pathological" "CoIP" "CoMCont" "CoMTb" "CoRNR" "CoRNR1and" "CoRNR2" "ColE1" "Collins" "Colorado" "CompPASS" "Conclusion" "Conclusions" "Congo" "Coomassie" "Cooperativity-dependent" "Cortot" "CovalAb" "Cox-regression" "Coxsackievirus" "CpG-dense" "CpG-island" "Cr-fragment" "Cre" "Cre-driver" "Cre-negative" "Creutzfeld-Jacob" "Crohn" "Cross-regulation" "Crumb3" "Crus" "Cruz" "CtBP24" "CtIP-mediated" "Ctr" "Ct∼12" "Cu" "Cul1" "Cul1-Skp1-Fbw7" "Cullin-RING" "Cullin-Ring" "Cy1" "CyclinD1and" "CyclinD1as" "Cys-LT" "Cys-LT-mediated" "Cys-LTs" "Cys-X2-4-Cys-X35-50-Cys-X2-His" "CysLTR" "Cysteine-to-alanine" "Cysteinyl" "Cα" "C–E" "C→A" "C→G" "C→T" "D-SZ" "D-box" "D-loop" "D-motif" "D11" "D146N" "D1R" "D1R-GFP" "D2" "D2-GFP" "D3" "D4" "D4D6" "D4GDI" "D4Z4" "D5" "D5F3" "D770GY" "DA-like" "DALIS" "DALS" "DAVID" "DBN-S647" "DCIS-like" "DCN1-RBX1" "DCP-LA" "DCR" "DCRs" "DDK" "DDR-proficient" "DEF-A" "DGV" "DH" "DHO" "DHX30" "DIPGs" "DIV" "DK4" "DK6" "DM-W" "DM24h" "DMTs" "DNA-DNA" "DNA-DSB" "DNA-Damage" "DNA-Damage-Induced" "DNA-TDG-p300" "DNA-damage-independent" "DNA-damage-induced" "DNA-mismatch-repair" "DNA-protein" "DNA–FLA" "DNA–protein" "DNCsk" "DNP-HSA" "DNQ" "DNSrc" "DNaseI" "DO1" "DOI" "DOPAC" "DPO-PCR" "DPYD-MIR137" "DQ-BSA" "DQ™-Red" "DR-4" "DR-GFP" "DR5-like" "DSB-R" "DSBs" "DSGxxS" "DSTYK" "DU145" "DU145Kd" "DUF1669" "DUF59" "DUX4-fl" "DUX4-s" "DZNep" "Dako" "Daniele" "Danish" "Danvers" "Daugaard" "De-repressing" "Defazio-Eli" "Dendra-tau" "Denmark" "Deshaies" "Design" "Dex" "Dex-inducibility" "Dhand" "DiYF" "DiYF-knockin" "Diamond-Blackfan" "Dipeptidyl" "Discs" "Doebele" "Donnell" "Double-strand" "Down-modulation" "Down-stream" "Doxo" "Dre2" "DsRed-Monomer-tagged" "Dual-priming" "Dulbecco" "Duval" "D–5G" "D–E" "D–S1F" "E-Abstract" "E-CMF" "E-GFP" "E-MTAB-37" "E-T-CMF" "E-box" "E-boxes" "E-cadheirn" "E-cadherin-expressing" "E-cadherin-negative" "E-guggulsterone" "E-value" "E-x-x-x-x-C" "E10a" "E10del" "E10del2" "E17b" "E2-promoter" "E2A-HLF" "E2F-7" "E2F-7-bound" "E2F-7-depleted" "E2F-8" "E2F-controlled" "E2F1-8" "E2F1-dependent" "E2F1-induced" "E2F1-inducing" "E2F1-mediated" "E2F1-negative" "E2F1-positive" "E2F1-target" "E2F1and" "E2F3a" "E2F3b" "E2F6-dependent" "E2F6-depleted" "E2F7a" "E3-ligase" "E3-ligase-like" "E3-ligases" "E3-ubiquitin" "E3RS" "E4" "E4BP4" "E5" "E572A" "E6" "E6-associated" "E6-induced" "E6-mediated" "E6-p53-p300" "E6-positive" "E616del" "E64c" "E6BP" "E6L50G" "E6a" "E7" "E709A+G719C" "E746-A750" "E7del" "E8" "E8.0" "E8.75" "E9.5" "EA1" "EBPa" "EBPb" "EBPd" "EC1-4" "EC1-EC5" "EC2" "EC50" "ECFP" "ECFP-Mcl1L" "ECFP-Mcl1L-overexpressing" "ECM+C" "ECM-adhesion" "ECOG" "ED" "EE" "EEG" "EFGR" "EGF-ligand" "EGF-like" "EGFP-tag" "EGFR-MEK-dependent" "EGFR-P" "EGFR-PI3K-dependent" "EGFR-dependently" "EGFR-family" "EGFRvIII" "EGFRwt" "EGFRwt-EGFRvIII-RIP1" "EGR" "EH1" "EH2" "EIIIB" "EL11-26" "EL12-15" "EL12-58" "ELISAs" "EMEA" "EMT-TF" "EMT-TF-induced" "EMT-TFs" "EMT-like" "EMT-mRNA" "EMT-phenotype" "EMT-targeting" "EMVs" "EN2" "ENST00000527240" "EP" "ER+" "ER++" "ER+BC" "ER+BC-treated" "ER+positive" "ER+ve" "ER-E2F1" "ER-E2F1cells" "ER-signalling" "ER-to-Golgi" "ER0" "ERAP1a" "ERAP1b" "ERE2-TK-LUC" "EREs" "ERK-independent" "ERS" "ERα+Ets1" "ERα+Ets1+estradiol" "ERα+estradiol" "ESCRT" "ESCRTs" "ESR1-TA" "ET-CMF" "EUFA-423" "EURTAC" "EV-C2" "EV-C4" "EVCT" "EVCTs" "EVH1" "EX-EGFP-M02" "EX-EGFP-M02-vector" "EYFP" "EYFP-Mcl1L" "East-Asian" "Edinburgh" "Edmonson-Steiner" "Egger" "Eighty-nine" "Eighty-one" "Eighty-seven" "Eighty-six" "Ejlertsen" "Elston" "Eluates" "EnSCs" "Enhancer-Promoter" "EphA" "EphA2-CAV1" "EphA2-Kinase" "EphA2-host" "EphA2-immunoprecipitates" "EphA2-kd" "EphA2-sterile" "EphA2-ΔKD" "EphA2-ΔSAM" "EphA2sh-RNA" "Ephrin-EphR" "Epicardin" "Epithelial-Mesenchymal" "Epithelial-mesenchymal" "Epithelial-to-Mesenchymal" "Epithelial–mesenchymal" "Epithelium" "Epsin" "Epsin-15" "Epsin15" "Eptsein-Barr" "ErB" "ErB3" "Erb2-driven" "ErbB" "ErbB2-dependent" "ErbB2-driven" "ErbB2-expressing" "ErbB2-independent" "ErbB2-induced" "ErbB2-only" "ErbB2-overexpressing" "ErbB2-positive" "ErbB2-related" "ErbB2-specific" "ErbB2-transformed" "ErbB3" "ErbB4-induced" "Erk1-negative" "Erk1-positive" "ErlR" "Erythrocytes" "Ethylene-diamine" "Ets1" "Ets1-expressing" "Ets2" "Europe" "European" "European-descent" "Europeans" "Evans" "Ex5-MBNL1" "Exo70p" "Exo84p" "Exome" "Eμ-myc" "E–6G" "E–S2H" "F-BAR" "F-BAR–FX" "F-SNP" "F1" "F2" "F3" "F4" "FAD" "FAIRE" "FAM83" "FAM83D" "FAS-receptor" "FASL" "FAs" "FBCs" "FBLX20" "FBP-1" "FBS-replete" "FBXL1" "FBXL11" "FBXL6" "FBXL7" "FBXLs" "FBXW" "FBXW1" "FBXW7α" "FBXWα" "FC=1.19" "FC=1.2" "FC=1.4" "FEF" "FEV1" "FFLs" "FGFR-2-III-b" "FGFR-2-IIIb" "FGFR-2-IIIb-specific" "FGFR-3" "FGFR-IIIb" "FGFR-invariant" "FGFR3-Capan-2" "FGFR3-IIIb" "FGFR3-IIIc" "FGFR3-IIIc-KD" "FGFR3K" "FGR2b" "FH" "FICZ" "FIF" "FISH" "FK-1" "FK1" "FK506-FKBP12" "FKBP12-rapamycin" "FKSG30" "FLA9500" "FLAG" "FLAG-BCL11A-XL" "FLAG-DBN" "FLAG-EL" "FLAG-LMW-E" "FLAG-hSIRT1-FL" "FLAG-hSIRT1-NT" "FLAG-tag" "FLICE-like" "FLJ36031-PIK3CG" "FLT3-ITD" "FLT3-ITD-induced" "FLU-inducedγ-H2AX" "FLX-treated" "FMG" "FMO2" "FN-null" "FNAB" "FNAs" "FOLFOX6" "FOXO" "FOXO4a" "FRA1-WT-BS" "FRA1-wild-type-binding" "FRA16D" "FRA2C" "FRA2Ccen" "FRA2Ctel" "FRCn" "FREEC" "FRG" "FRG1" "FRG2" "FRMP" "FS" "FSHD-1" "FSHD-2" "FSK" "FSXXLXXL" "FTS-1" "FU" "FX" "FXRXLRXL" "FXRα" "Factor-Kappa" "FadA" "FadAc" "FamHS" "FancD2-mUb" "Fbw" "Fbw7-directed" "FcϵRI" "Fe" "Fe-only" "Features" "Fes" "Fifty-six" "Fine-mapping" "Fine-needle" "Fischer" "Fish-oil" "Five-fluorouracil" "Flag" "Flag-DBN" "Flag-E6" "Flag-HA-tagged" "Flag-M2" "Flag-Mst2" "Flag-Polκ" "Flag-REV1-expressed" "Flag-Ubi" "Flag-Yap" "Flag-tag" "Flotilin-1" "Flow-cytometric" "Fluor-488-conjugated" "FoSTeS" "Follow-up" "Forty-eight" "Forty-five" "Forty-four" "Forty-one" "Forty-three" "FosL" "Fourier-transform" "Foxo" "Foxo33" "Foxo3a-high" "Foxo3a-low" "Foxp3" "France" "Fraumeni" "French" "Frey" "Fs" "Fuhrman" "Functional" "Fura-2-AM" "FusionSeq" "Fyn" "F–S6H" "G-486T" "G-6-Pc" "G-C" "G-DNA" "G-KAP1" "G-LISA" "G-Luc" "G-YL" "G-agarose" "G-allele" "G-coupled" "G-ratios" "G-substate" "G-substates" "G-substrates" "G0" "G0-G1" "G0-like" "G1" "G1-G3" "G1-S" "G1-to-S" "G10" "G1–S" "G2" "G242fs" "G2E" "G2M" "G2–M" "G3-unifocal" "G6P" "G719A" "G719X" "G724fs" "G770GY" "GA" "GADD45α" "GAL4-PNR-mediated" "GAS-like" "GBCs" "GBM12" "GBM13" "GBM9" "GBM9-NS" "GBM95" "GCHM" "GCN4" "GCTA" "GDF" "GDZ" "GEF-dead" "GEF-induced" "GEF-mediated" "GEF40" "GENOA" "GEO2R" "GEO45130" "GFAP-IκBα-dn" "GFAP-Iκbα-dn" "GFP-DFCP1" "GFP-Exo70-induced" "GFP-Exo70-positive" "GFP-FRMD7-transfected" "GFP-H-Ras-enriched" "GFP-H-RasG12V" "GFP-H-RasG12V-labeled" "GFP-H-RasG12V-rich" "GFP-PAK1-S223A" "GFP-PTENΔD" "GFP-REV1-UBM" "GFP-RNF38ΔRING" "GFP-SCRIB" "GFP-Snc1" "GFP-Snc1p" "GFP-lifetimes" "GFP-mut3" "GFP-tag" "GFPRNF38" "GGC-GAC" "GGT-GTT" "GH-hPrlR" "GH-promoter" "GI" "GIP-receptor" "GL" "GLI1ΔNES" "GLI1ΔNLS" "GNE-929" "GOS-28" "GRC-1" "GRE" "GREs" "GSCs-by" "GSE1159" "GSE12417" "GSE15434" "GSE17317" "GSE19784" "GSE23022" "GSE25021" "GSE28198" "GSE39314" "GSE41322" "GSE46695" "GSE49046" "GSE6365" "GSE6477" "GSE6891" "GSE8611" "GSK" "GSK3β-CA" "GSK3β-KD" "GST-A20-ZnF5-7" "GST-A20-ZnF5-7mt" "GST-ATM-2" "GST-EC5" "GST-Homer1c" "GST-Hrr25" "GST-LBD" "GST-Lst1p" "GST-Lyn-SH3" "GST-Nyv1p" "GST-RASSF5-SARAH" "GST-RNA" "GST-SOCS4-SH2" "GST-SOCS5-SH2" "GST-Sec22p" "GST-Sec23p" "GST-Sec24p" "GST-Sec31p" "GST-Sec9c" "GST-Snc2p" "GST-Sso2p" "GST-TB" "GST-ZO-1-K253A" "GST-cIAP" "GST-hSIRT1-NT" "GST-pull" "GST-pulldown" "GT-1" "GT19" "GT6" "GT7" "GTIC" "GTICs" "GTIIC" "GTPase-RhoA" "GTs" "GUVs" "GW" "GWAS-PheWAS" "GWASs" "GX" "GX15-070" "GXP" "GYJ-A" "GZBDK" "GZBDZ" "GaQ3-treatment" "Gag-Pol" "Gain" "Gain-of-Function" "Gain-of-function" "Gallbladder" "GenBank" "GeneCards" "GeneChip" "Genentech" "Genome-wide" "Genotype-phenotype" "Gensini" "Gensler" "German" "Germany" "Gerota" "Glc7p" "Gleason" "Gli" "Glomus" "Glutathione-Sepharose" "Gly1121ValfsX3" "Gly158-Asp172" "GoldenGate" "Gottle" "Grp" "Grp78" "Guinier" "Gupta" "Gy" "Gγ" "G–A" "G–C" "G–T" "G–agarose" "G→A" "G→C" "G→T" "H&E" "H-14-3-3zeta" "H-2Kb-tsA58" "H-E" "H-L" "H-MADD3A-YFP" "H-Ras-GTP" "H-RasG12V" "H-RasG12V-labeled" "H-WtMADD-YFP" "H-bonds" "H1" "H113A" "H115A" "H168R" "H179Y" "H1975" "H1993" "H1H1" "H1N1" "H2" "H2009" "H2Bub" "H2Bub-dependent" "H2Bub-independent" "H2H2" "H3" "H3-K4" "H3-T11" "H3-dependent" "H3-histone" "H3-like" "H37" "H37Ra" "H3K18" "H3K18ac" "H3K27" "H3K36" "H3K4Q" "H3K4m2" "H3K4m3" "H3K9" "H3KR" "H3R2" "H3ac-SET1C" "H4" "H4K20" "H4KR" "H4Lys12" "H538A" "H83,86L" "HA-E2F1" "HA-Mst2" "HA-Ub-K63-only" "HA-Ubi" "HA-YAP" "HA-cCbl" "HA-tagged-USF2" "HADDOCK" "HAECs" "HAFoxp3" "HAdV-C5" "HB-239" "HBII-239" "HBS+STAT3" "HC" "HCASM" "HCASMC" "HCC728" "HCC829" "HCIP" "HCIPs" "HCT116Bax" "HCT116KRAS" "HD" "HDFs" "HDMECs" "HEAT" "HEC-50" "HECD-1" "HELQ-1" "HELQ-BCDX2" "HELQ-defective" "HER" "HER-1–4" "HER-2+" "HER-2-low" "HER1-3" "HER1-4" "HER1–4" "HER2-negative" "HER2-normal" "HER2Bi" "HER2Bi-ATC" "HER2Bi-Ab" "HER2Bi-armed" "HER3phosphorylation" "HERi-HERj" "HFD" "HFSN1" "HG-U133" "HGGs" "HGMD" "HGS-OvCa" "HIBECs" "HIF" "HIF1+USF2" "HIF1-α" "HIF1α+STAT3C" "HIF1α+USF2" "HIF1α-C" "HIF1α-N" "HIF1αDPA" "HIF1αTM" "HIF1αTM+STAT3C" "HIF1αTM+USF2" "HIF2" "HIF2+USF2" "HIF2-mediated" "HIF2α-C" "HIF2α-N" "HIF2αDPA" "HIF2αTM" "HIF2αTM+STAT3C" "HIF2αTM+USF2" "HIFα" "HIFα112" "HIFα122" "HIFα211" "HIFα221" "HIV+IVDU" "HIV+IVDUs" "HIV-Tat" "HIV-protein" "HIV-proteins" "HLA-DRB9" "HLH" "HME-Snail" "HMLE-Slug" "HMLE-Snail" "HMLE-Snail-ER" "HMLE-Twist" "HMLE-Twist-ER" "HMSC" "HMSCs" "HMVEC-d" "HNPC" "HOSE11-24-96" "HOSE17-1" "HOSE96-9-18" "HOXA6" "HP-1" "HPASMCs" "HPFS" "HPV16-positives" "HPV16-transgenic" "HR" "HR-HPV" "HR-HPVs" "HR10.198" "HR2.765" "HR231" "HR=0.47" "HR=1.0" "HR=1.2" "HR=1.3" "HR=1.44" "HR=1.51" "HR=1.53" "HR=1.54" "HR=1.9" "HR=2.1" "HR=4.2" "HR=6.3" "HRG-beta" "HRs" "HSM" "HSP-27" "HSP70-Cluc" "HSTF-1" "HSV-1" "HT12" "HTB175" "HTC116" "HTC75" "HTM" "Haas-Kogan" "Hace" "Hace1-HECT" "Halotag-p62" "Han" "HapMap" "HapMap3" "Hardy-Weinberg" "Hardy-Zuckerman" "Hardy–Weinberg" "Harvey" "Hawaiian" "Hb" "Hct" "HeCOG" "HeLa-OCT4" "Helicase" "Helicase-like" "Hematoxylin–eosin" "Heme" "Hepa" "Hetero-oligomerization" "Heterozygotes" "Hh" "Hi-C" "High-grade" "High-risk" "Hipple–Lindau" "Hippo" "Hippo-RASSF1-LATS" "Hippo-Salvador" "Hippo-Yap" "Hippo-responsive" "His-Beclin1" "His-E1" "His-Flag-Ubi" "His-GLI" "His-GLI1" "His-Hsp70" "His-Plk1" "His-Stub1" "His-Ubc5Hb" "His-V5-XPA" "His-hTDG" "His6" "His6-Sso1p" "Hispanic" "Histoscores" "Hmga" "Hnf" "Hnf-1α" "Hnf-3α" "Hnf-3β" "Hnf-4α" "Hochberg" "Hodges" "Hodgkin" "Hoechst" "Holliday" "Holst" "Homer" "Homer1" "Homer1a" "HomerEVH1" "Homma" "Homo-or" "Homozygotes" "Hong" "Hoogsteen" "Hrr25p" "Hsa-miR-105" "Hsp70" "Huggins" "Human610K" "Hypercalciuria" "Hz" "I+II" "I-BAR" "I-III" "I-OMe-AG538" "I-SceI" "I-SceI-based" "I-SceI-induced" "I-SceI-transfected" "I-Tfn" "I-V" "I-map" "I-transferrin" "I-x-V" "I2" "I230A" "I8V" "IAA" "IASLC" "IAV" "IB4-immunoreactive" "IBD-U" "IBDU" "IBS" "IC-NST" "IC50" "IC90" "ICBP50" "ICOS-L" "ICOS-L-mIgFc" "ICP34.5" "ICP6" "ID" "IDBCs" "IDCs" "IECs" "IEF" "IFN-g" "IFN-ɣ" "IFN-κ" "IFN-λ" "IFN-λR" "IGF-1-induced" "IGF-1-signaling" "IGF-1R-activated" "IGF-1was" "IGFR-1R-mediated" "IHF" "IIA" "III+IV" "III-map" "IIICS" "IIIα" "III–IV" "IIa" "IIα" "II–IV" "IKK-ε" "IKKβ" "IL-1R-dependently" "IL-36γ" "IL-6-receptor-mediated" "IL-6Rα" "IL2-κB–DNA–protein" "IL4production" "ILBCs" "IN" "IN-LEDGF" "INF-α-induced" "INGI" "INGI-FVG" "INGI-VB" "INSS" "IOVS" "IP+WB" "IP-kinase" "IPG-IEF" "IPQA" "IPs" "IQ" "IQR" "IR-A" "IR-A-mediated" "IR-A–pcDNA3.1" "IRES2" "IR–B" "ISG" "ISGF3γ" "ISGs" "ISKS" "ISceI" "ISceI-cleavage" "ITC" "IVDUs" "IVIG" "IVIS-100" "IVS" "IVS17+1G" "IVa2" "Ibadan" "Ig-κB" "IgA" "IgAλ" "IgGλ" "IgVH" "Igf1rβ" "IkappaA-kinase" "Ikeda" "Illumina" "ImageJ" "Imaris" "Imetelstat" "Immuno-cytochemical" "Immuno-isolation" "Importin-α" "Improta" "Indian" "Indians" "Insulin-induced" "Inter-individual" "Inter-observer" "Intra-aortic" "Invitrogen" "Irt-like" "Iss1p" "Iwig" "IĸBα" "Iκ-Bα" "IκBα-dn" "I–III" "I–IV" "I–VI" "I∼II" "J3" "J82-bladder" "JAH" "JAM-A–null" "JAMM" "JCF" "JCL" "JEFF" "JFF" "JFH1" "JFP" "JGW" "JH" "JH1" "JHS" "JHS-ARIC" "JJC" "JK" "JPT" "JPX-9" "JS-31" "JSF" "JTV-1" "JUND" "JWF" "JZ" "Jacobs" "Jak-STAT3" "Jak1and" "Japanese" "Jedi" "Jedi-1" "Joazeiro" "Johansson" "John-Aryankalayil" "Johnson" "Ju-Seog" "J–S2L" "K-I" "K-MT" "K-cells" "K-linkage" "K-linked" "K120" "K164" "K18" "K203" "K23" "K23V" "K259" "K2R" "K3" "K3-MARCH" "K3-treated" "K370" "K486" "K4E" "K540A" "K567X" "K571A" "K5E" "K5N" "K6" "K63" "K63-polyUb" "K72H" "K777" "K8" "KAP-1-depleted" "KC3" "KCl-pretreatment" "KD" "KFK" "KIM-PTP" "KIM-peptide" "KIMKIS" "KP46" "KR" "KRAB" "KRAB-ZFP-associated" "KRF-1" "KS" "KTS" "KV" "KX" "KXGS" "KXS" "KXXS" "KYL" "Kagan" "Kanei-Ishii" "Kaplan" "Kaplan-Meier" "Kaplan–Meier" "Kaposi" "Ki-67" "Ki-67-positive" "Ki67" "Kim" "Kip" "Kirsten" "Knock-down" "Knock-in" "Knocking-down" "Korah" "Korea" "Korean" "KpnI" "Kruppel" "Kruskal-Wallis" "Kruskal–Wallis" "Krüppel" "Ku" "Ku-hTR" "Kuo" "Kuriyan" "K–M" "K–S2P" "L-Dopa-induced" "L-PHA" "L-X-L-X-φ" "L-type" "L1" "L1-5" "L1-RTP" "L1-RTP-inducing" "L19" "L19F" "L2" "L262-Q264" "L269fs" "L2K" "L2K+pcDNA3.1" "L2K+pcDNA3.1-miR-124" "L3" "L319A" "L38" "L38I" "L4" "L4-100K" "L4-22K" "L4-33K" "L4P" "L5" "L56Br-1" "L747-S751" "L747-S752" "LBDs" "LC3-I" "LC3-punctae" "LC3B-I" "LC3B-II" "LC3II" "LCB" "LCDD-LCs" "LCLs" "LE" "LEF" "LEF-Luc" "LETFs" "LF82" "LFB" "LFL" "LGL2" "LGR" "LGRs" "LIFRβ" "LINE-1" "LISA" "LL360" "LLL12" "LM609" "LMP2A" "LMP2B" "LMW" "LMW-E" "LMW-E-expressing" "LMW-E-overexpressing" "LMW-E–expressing" "LNCaP" "LNCaP-LUC" "LNGFR" "LNGFR-BirA-tag" "LNT14" "LOC10013023" "LOC84989" "LOVD" "LPMf" "LPR" "LPS" "LPS-Stub1-induced" "LPxY" "LPxY-PPxY" "LQ" "LQQLL" "LR-Test" "LRP-ICD" "LRP1-ICD" "LRRC8s" "LRT" "LRY" "LRs" "LTE" "LTGCs" "LTR-luc" "LTs" "LTβR-stimulation-induced" "LUVs" "LUX-Lung" "LV-K" "LV-Stub1" "LV-WT" "LXRα" "LXXXLXXXI" "LY1" "LY29004" "Lab-Tek" "Lai" "Lapachone" "Larger-scale" "Latino" "Lats1" "Lats1-Yap" "Lauren" "Layton" "Ldb" "Ldb17p" "Leica" "Let-7" "Let-7a" "Let-7c" "Leu858→Arg" "Leucine-insulin-mTORC1" "Lewy" "LexA-RID1" "LexA-RID2" "Lgl" "Lgl1" "Lgl3SA" "Li" "Li-Fraumeni" "Li-Fraumeni-like" "Lieberman-Aiden" "Lifeact" "Lifeline-basal" "LigI" "Lindau" "Lingo-1" "Lipid" "Lipid-Raft" "Liposomes" "Lipotoxicity-induced" "Liu" "Liu-Bryan" "Live-dead" "Li–Fraumeni" "Li–Fraumeni-like" "Loberg" "Log-Rank" "Log-rank" "Lohr" "Long-range" "Lopez" "Lopez-Andres" "Lopez-Knowles" "Lopez-Vicente" "Loss-of-function" "Low-dose" "Lu" "Luc" "Luminex" "Lunardi" "Luo" "Luu" "Lv-MEK" "LxxLL" "Lyn" "Lys-147" "Lys-172" "Lys-382" "Lys-433" "Lys-788" "Lys-849" "Lys-Gly" "Lys48" "Lys48-linked" "Lys63-linked" "Lys63-ubiquitin" "Lysm" "Lyz2" "L–S6O" "M-IgVH" "M0" "M14" "M1k" "M1λ" "M2-like" "M210B4" "M227A" "M2λ" "M5" "M6" "MADS" "MADS-box" "MAL" "MAP-K" "MAPK-pathway" "MAPK-pathways" "MAPK4K" "MAPKK-like" "MAR" "MAS" "MB-435S" "MBCs" "MBII-239" "MCF-7-MEK5-ERK5-shRNA" "MCF10ADCIS" "MCF7-Cd" "MCF7-Cd2" "MCF7breast" "MDA-MB" "MDA-MB-231-D3H2-LN" "MDA-MB-231-PELP1-shRNA" "MDA-MB-231-PELP1shRNA" "MDA453R" "MDAMD-231-PELP1shRNA" "MEDLINE" "MEF2s" "MEGS" "MEKi" "MEN5" "MEN8" "MESA" "MHC" "MHC-1" "MHC-I" "MHCCLM3" "MILE" "MILLIPLEX" "MIR-106B-25" "MIR-17–92" "MIR106A" "MIR106B" "MIR1296" "MIR137" "MIR143-NOTCH" "MIR143-NOTCH2" "MIR143-fusion" "MIR168a" "MIR93" "MK" "MK-571" "MK2i" "MKC-LC" "MKI" "MKK3b" "ML-120B" "ML171" "MLLC" "MM" "MM-BIR" "MM231" "MM231-LN" "MMCLs" "MMTV-ErbB2" "MMTV-PyMT" "MMTVneu" "MO7e" "MONO-MAC6" "MOPC-141" "MPMQ" "MRCKβ" "MREC" "MRL" "MRLCs" "MRTF-B" "MS" "MSCV-driven" "MSFM" "MSH2-null" "MSI-H" "MST2" "MT-1A" "MT-1E" "MT-2A" "MT-3" "MTEP" "MTF" "MTF-1" "MTS" "MUC5AC-negative" "MV-1" "MVs" "MYC+RAS" "MYC-protein-expressing" "MYC-protein-negative" "MYC-protein-positive" "MYCN-protein-negative" "MYCN-protein-positive" "Mal-PEGylation" "Manders" "Mantel-Cox" "Mantel-Haenszel" "Map" "Materials" "Matias-guiu" "Matsukawa" "Mazal" "McGill" "Mcl" "Mcl1-stability" "Mcl1ES" "Mcl1L" "Mcl1jh" "Mcl1s" "Mdm2-null" "Mec1" "Meier" "Meta-regression" "Metabochip" "Methodology" "Methods" "Mexico" "Mg" "Mi-2a" "MiR-192" "MiR-200" "MiR-27a" "MiR-329" "MiR-376c" "MiR-379" "MiR-433" "MiRNA-125b" "MiRNA-768-3p" "MiRNAs" "MiRNAs-886-5p" "Mia-PaCa2" "MicroPET" "MicroRNA-21" "Microautophagy" "Microhomology" "Micromilieu" "Microsystems" "Middle-South" "Milk-driven" "Milk-mediated" "Milliplex" "Millipore" "MiniSOG-mCherry" "Mir-17-92" "MitoTracker" "Mitosis-Karyorrhexis" "Mizuki" "Mizutani" "Mn" "Mo7ep210" "Moderate-to-strong" "Moelans" "MommeR1" "Monocyte-microglial" "Monte" "Morris" "Motin" "Mousnier" "Mst1" "Mt" "Mt-p53" "Mu-PACK" "Mucosae" "Multi-ethnic" "Munfus-McCray" "Mus81-Eme1" "MyD88s" "Myc" "Myc-53" "Myc-A20-WT" "Myc-EphA2" "Myc-I" "Myc-Lats1" "Myc-Mst2" "Myc-and" "Myers" "Myo2p" "N-Phe" "N-R" "N-TAD" "N-TADs" "N-acetyl" "N-acetyltransferase" "N-arginine" "N-degron" "N-end" "N-glycosylated" "N-glycosylation" "N-labeled" "N-lobe" "N-methyl" "N-methyl-N" "N-nitrosamines" "N-nitrosoguanidine" "N-recognin" "N1" "N2" "N3" "N4–6" "N=15" "N=39" "N=8" "NA" "NADH-dehydrogenase" "NAM-sensitivity" "NAMEC-RAS" "NAMEC-RAS-Tom" "NAMEC-Tom" "NAMEC-Tom-RAS" "NAMEC11" "NAMEC8" "NAMECs" "NB1141" "NB1142" "NB27" "NBRA-A" "NBRE-A" "NBRE-A-mediated" "NBRE-B" "NBRE-C" "NBRE-like" "NBUD" "NCBI" "NCBI36" "NCI" "NCI-H295R" "NCI-H322" "NCOAs" "NCT01237067" "NCT01445418" "NCT01466660" "NC_000019.9" "NDW" "NE-GOF" "NEJ002" "NES-like" "NES=2.05" "NF-B" "NF-H" "NF-Κb" "NF-κB-we" "NF-κB1" "NF-κB–DNA" "NF1-patient" "NFR2" "NFT" "NFTs" "NGF-axon" "NGF-treatment" "NGFβ" "NHWs" "NID+L" "NKI" "NKX3" "NL" "NLR" "NLS-SYFP-DBD" "NLS-SYFP-tagged" "NLS-like" "NLS2" "NLSs" "NMP1" "NM_006297.2" "NNA" "NO" "NOD-SCID" "NOD-like" "NOTCH1-3" "NOTCH2-CEP128" "NP" "NPM-ALK-driven" "NPM-ALK-negative" "NP_006288.2" "NQO1+ cells" "NQO1+cells" "NQO1-cells" "NR-coregulators" "NR2E" "NR2F" "NR3B1" "NR4R" "NRF2-ARE" "NRF2-ARE-activation" "NRF2-ARE-mediated" "NRF2-MAF" "NRG1-dependent" "NRG1s" "NSD" "NSTEMI" "NTC-mimic" "Naidu" "Nanoliposomes" "Nault" "Nd" "Necrostatin-7" "Nef-PI3K-PAK" "Nerve" "Nes8Cre" "Nestin-BrdU" "NetNES" "Ni-NTA" "Nielsen" "Niemann" "Niemann-Pick" "Ninety-eight" "Ninety-six" "Nissl" "Niu" "Nkx" "Nkx-2" "Nkx3-1-expressing" "No" "Nonsmall" "North-East" "Notch-Akt" "Notch-PTEN-Akt" "Notch-dependent" "Notch1" "Notch1ICD" "Notch2" "Notch2ICD" "Notch3" "Notch3-ICD" "Notch3-ICD-binding" "Notch3-ICD-transfected" "Notch3ICD" "Novartis" "Nox" "Noxa-levels" "Noxa-precipitates" "Np73" "Nr-ferm" "Nrf" "Nrf2-ARE" "Nrf2-dependence" "Nrf2-null" "Nu-va" "Nu-vb" "NuRD" "Nuc" "Nuc-pYStat5" "Nuc-pYStat5-positive" "Nucleo" "Nur77–reportedly" "Nurr1a" "Nurr1b" "Nurr77" "N = 7" "O-6-methylguanine-DNA" "O-GlcNAcylated" "O-GlcNAcylation" "O-GlcNAcylation–dependent" "O-GlcNAcylation–independent" "O-linked" "O-methylated" "OATS" "OB" "OB-1" "OB-fold" "OCI-ly19" "OCM-1" "OCTT2" "OD490" "ODC-1" "OHdG" "OMIM" "OPC" "OPCs" "OR1" "OR=0.20" "OR=0.36" "OR=0.47" "OR=0.49" "OR=0.60" "OR=0.64" "OR=0.69" "OR=0.70" "OR=0.80" "OR=1.26" "OR=1.33" "OR=1.51" "OR=3.05" "ORP-150" "ORR" "OV-C35-M1" "OV-C35-M2" "OV-C35-M3" "OV-MV1" "OV-MV2" "Oas1g" "Occludens-1" "Oct4A" "Off-rate" "Oiso" "Oliveras-Ferraros" "Oncology" "Oncomine" "One-third" "One-way" "Ooi" "Orbitrap" "Os" "Over-activation" "P+1" "P1-P3" "P17" "P17L" "P256fs" "P4" "P442HfsX9" "P4D1" "P6" "P65" "P65A" "P9" "P=0.00064" "P=0.0022" "P=0.0029" "P=0.0084" "P=0.0248" "P=0.035" "P=3E-16" "P= 0.9990" "PA25001" "PAHS012" "PANC-1-P" "PANC140" "PANC410" "PANC420" "PARD3L" "PARPi" "PAS" "PASMC" "PASMCs" "PAb" "PAb240" "PAb240-positive" "PBD" "PBL" "PBTs" "PC-3AR" "PC-3AR9" "PC12-conditional" "PC14-PE6" "PCNA-mUb-dependent" "PCNA-mUb-independent" "PCNAK164R" "PCR-RFLP" "PCR–ASP" "PCs" "PDGF" "PDGFR-IV" "PDGFRα" "PDGFβR" "PDZ1" "PDZ1-3" "PDZ2-domain" "PDZ3" "PDZ4" "PECAM" "PELP1-miR200a" "PELP1-shRNA-mediated" "PEST" "PFS=3" "PG" "PGDF-BB" "PGK" "PGNase-F" "PH-domain" "PI3K-CA" "PI3K-like" "PI3KCA" "PI3KKs" "PI3P" "PIE-1" "PIKKs" "PINK1-KDD" "PITA" "PIXα" "PKCßII" "PKCβ-DN" "PKCβII" "PKCη" "PKCι" "PKCλ" "PKM1" "PLCδ" "PMC42-LA" "PNA-PCR" "POL32" "POLδ" "POLη" "POLι" "POLκ" "POT1-TPP1-insensitive" "POU-homeodomain" "POUNDS" "PP" "PP2A-like" "PP30" "PPAA" "PPY-A" "PPY-A+BAW667" "PPY-A+SCF-block" "PPY-A-treated" "PPxY" "PQ" "PR-619" "PR-negative" "PR-positive" "PRC3" "PRF5" "PRMs" "PRTF" "PS" "PS1xMTEP" "PS647-DBN" "PSA-promoter" "PSChimera" "PTEN-DBN" "PTEN-activity" "PTEN-exosomes" "PTEN-intact" "PTEN-null" "PTENC2" "PTENΔD" "PTPMeg2" "PTPSL-like" "PTRF-Cavin" "PY1" "PY2" "PY20" "PY3" "PaCa" "Pab240" "Pab240-positive" "PacMetUT1" "Pacific" "Paired-box" "Paired-end" "Pairwise" "Pak" "Pam" "Pam3Cys4" "Pan-1" "Pan-Asia" "Par3-Lgl" "Pardee" "Parkin-SY5Y" "Parkinson" "Patel" "Patients" "Patj" "Pax-2" "Pbx" "Pbx-1" "Pdgfrα" "Pearson" "Peifer" "Pemetrexed" "Pena-Diaz" "Penicillin-Streptomycin" "Peptidylprolyl" "Perez" "Perhaps" "Peutz-Jeghers" "PgR0" "PgRSDF-1" "Phase-contrast" "PheWAS" "Philadelphia" "Phosphoinositide-3" "Pitstop2" "Plk1" "Plus2" "Pod" "Pod-1" "Poitiers" "Pol" "Pol3" "Poleward" "Polo-Box" "Poly-ADP" "Poly-ADP-ribose" "PolyI" "PolyPhen" "PolyPhen-2" "Polβ" "Polη" "Polι" "Polκ-UBZ" "Post-Synaptic" "Pp53" "Pph21" "Pph21p" "PrP-Fc" "PrP-His" "Preso1" "PriGO7A" "PriGO8A" "PriGO9A" "Primer3" "Principal" "Principle" "Pro-IL-1β" "Pro-inflammatory" "Procaspase-3" "Profiler" "Prognosis-Based" "Promega" "Protein-1" "Protein-DNA" "Protein-level" "Proteolipid" "Proteome" "Proteome-wide" "ProtoArray" "Prusiner" "Ptdins" "Ptdins-3,4,5-P3" "Ptdins-3,4,5-P3-activated" "Puerto" "Pull-down" "PvuII" "P = 0.001" "P = 0.00004" "P = 0.0001" "P = 0.013" "P = 0.014" "P = 0.020" "P = 0.024" "P = 0.030" "P = 0.036" "P = 0.045" "P = 0.49" "P = 0.63" "P = 1" "Q-Q" "Q-SNARE" "Q-test" "Q-tests" "Q1" "Q2" "Q3" "QD-IHF" "QD-quantification" "QDs" "QKI-5" "QUE-NL" "QUE-NL-exposed" "QUE-NL-induced" "QUE-NL-treated" "QUE-NLs" "QUE-NLs-induced" "QW" "QZ" "Qa" "Qa-SNARES" "Qbc-SNARE" "Qiagen" "Qian" "Qu" "Quantile-quantile" "Quantitle-quantile" "Qur" "R-2HA2Flag-Api5" "R-2HA2flag-Api5" "R-CHOP" "R-SMAD" "R-SMAD-co-SMAD" "R-SNARE" "R-SNAREs" "R-like" "R-mediated" "R-squared" "R110-YVAD" "R11EE" "R12" "R122" "R171X" "R249S" "R273C" "R273H" "R282W" "R335X" "R4A" "R5" "R748-S752" "R848" "R=0.07" "RAB8B" "RACE-PCR" "RACK1s" "RAD3-related" "RAD51-SAM" "RAD51-foci-negative" "RAD51-foci-positive" "RAD51share" "RARβ2" "RAS-G12V-transformed" "RAS-RAF-pathway" "RAS-association" "RAS-induced" "RAS-mediated" "RASFF1B" "RASFF1C" "RASSF1A-cytoskeletal" "RASSF1A-microtubule" "RASSF1C" "RB-expressing" "RB-positive" "RBAP-46" "RCC4T" "RECORD-1" "REV1-UBM" "REX" "REX2a" "RFLP" "RFP-Ruby-tagged" "RFP-SCR" "RFP1.3" "RFS-1" "RGQ" "RID1-like" "RIG-1" "RIG-I-like" "RING-CH" "RING-finger" "RIPA" "RL95-2-IR-A" "RL95-2–IR-A" "RM-ANOVA" "RMSD" "RMSE" "RMSEs" "RNA" "RNA-DNA" "RNA22" "RNAPII" "RNPC1a" "RNPC1b" "RNU24" "RNU6" "RNU6-2" "RNU6B" "RNase-ChIP" "ROC-AUC" "ROCK-induced" "ROCK-mediated" "ROCK∆3-expressing" "ROKβ" "ROR" "ROR-1" "RORβ" "ROS-driven" "ROSA26" "RPN2-MF" "RPTEC" "RPTECs" "RQ-PCR" "RR-only" "RRE-containing" "RRL" "RRLs" "RRRCWWGYYY" "RRXCXXGXYX-XRXCXXGXYY" "RSMADs" "RTK" "RTK-invariant" "RTP" "RTqPCR" "RV16" "RV1b" "RVL" "Rab-like" "Rac-GTP" "Rac-interacting" "Rac1" "Rac1-RhoGDIα" "Rac1-regulatory" "Rac1GEF" "Rac1GTP" "Rac1GTPlevels" "Rac1Q61L" "Rac1V12G" "Rac2-null" "RacGAP" "Racial" "Rad3" "Rad3-related" "Rad51-ssDNA" "Rad51C-like" "Rad6" "Radiation-and" "Radio-TLC" "Radio-high-performance" "Radioactive" "Ran-GTP" "Rap-specific" "Ras-Association" "Ras-association" "RasGRP-CAT" "RasPRG1" "Ras•GDP" "Ras•GTP" "Rat" "Rb-MI" "Rb-family" "Re-ChIP" "Re-expression" "Re-internalized" "Re-introduction" "Re-probing" "ReChIP" "Red-labeled" "Regulatory-Sma" "Reis-Filho" "RelA" "Remarks" "Replicate" "Results" "Ret-CoR" "Rev" "Rev-erbβ" "Rho-GDIα" "Rho-GDP" "Rho-GTP" "Rho-Rock" "Rho-Rock-driven" "Rho-family" "Rho-kinase" "Rho-like" "RhoA-GTP" "RhoA-GTPase" "RhoA-ROCK" "RhoA-signaling" "RhoAV14" "RhoA–SRF–Dsg1" "RhoGDI-FLAG-tagged" "RhoGDI1" "RhoGDI2L" "RhoGDIs" "RhoGDIɑ" "RhoGTPases" "Ribophorin-1" "Rican" "Rich-Edwards" "Rico" "Rictor" "Rictor-depleted" "Rictor-mediated" "Rictor-specific" "Rictor–independent" "Rij" "Riplet" "Riplet-C21A" "Risk-dependent" "Ro-32-0432" "Roche" "Roche-Genentech" "Rock-dependent" "Rong" "Ross-Innes" "Rotterdam" "Royds" "Rs10497968" "Rs1978873" "Rs845552" "RskS" "RskS380" "Rubicon" "Ruschoff" "RxS" "R→H" "S-JH" "S-Methionine-labeled" "S-XL" "S-labeled" "S-methionine" "S-nitroso-glutathione" "S-nitrosocysteine" "S-phases" "S-radiolabeled" "S-transferases" "S1" "S12" "S138A" "S14" "S146A" "S146A-Cdh1" "S14A" "S14B" "S15" "S15B" "S19" "S1981" "S19A" "S19B" "S19C" "S19D" "S19E" "S1C" "S1D" "S1E" "S1F" "S1–S5" "S208-A209" "S223A" "S223E" "S235" "S240R" "S240R-DNA" "S2A" "S2B" "S2B–C" "S2C" "S2D" "S2J" "S2K" "S2L" "S3" "S363" "S3B" "S3C" "S3E" "S4" "S473" "S4A" "S4B" "S4C" "S4D" "S5D" "S5F" "S6" "S647-DBN" "S6A" "S6B" "S6RP" "S7" "S76A" "S7A" "S7B" "S7C" "S7F" "S8" "S807" "S8A" "S8B" "S8D" "S8E" "S8F" "S9" "SA-β-galactosidade" "SAHA" "SAKK19" "SAL" "SAM208-210LEA" "SARAH" "SARM1-His" "SARMS" "SCC-R" "SCC-S" "SCCs" "SCEs" "SCF-FBXL" "SCID-Beige" "SDF" "SDF-α" "SDS-page" "SDS-polyacrylamide" "SDS–polyacrylamide" "SD≥6" "SD≥6months" "SERT-LPR" "SERTLPR" "SES" "SES-CD" "SET1C-Mediated" "SET1C-independent" "SET1C-mediated" "SET1C-p300" "SET1C-p53" "SF" "SFB-LMW-E" "SFC" "SFD2" "SH2-phospho-tyrosine" "SIM3" "SIMs" "SIRE" "SIRT1-7" "SIRT1-FL" "SIRT1-NT" "SIRT1-defective" "SIRT1expression" "SIRTs" "SISH" "SIVmac239" "SK" "SK-EV-C1" "SK-EV-C3" "SK-EV-C4" "SK-N-DZ" "SK-β1-C1" "SK28" "SKCO-15" "SKG" "SKL" "SKP1-CUL1-F-box" "SL" "SLC39A" "SM-actin" "SMAD-1" "SMAD-responsive" "SMARTpool" "SNAG" "SNC1" "SNF-related" "SNO-parkin" "SNOC" "SNP-Nexus" "SNP-SNP" "SNP-chip" "SNP-heritability" "SNpc" "SOCS1-7" "SOCS36E" "SOD1transgenic" "SOLAR" "SOMAmer" "SOMAmers" "SOS-CAT" "SPE-7" "SPL" "SR-IκB" "SR-IκBα" "SREBP-1or-2" "SRF-dependent" "SRF-mediated" "SRF-null" "SRGP-1" "SRH" "SRs" "SS" "SSBR" "STAT" "STAT#1" "STAT3-C" "STAT3-driven" "STAT3-independent" "STAT3C" "STAT3F" "STE20-like" "STEMI" "STEP-like" "STGC" "STGCs" "SUM-44" "SV40-Cluc" "SVs" "SWI353" "SYFP" "SYPRO" "SYPRO-Ruby" "SZ" "Sanger" "Sap155p" "Sap185p" "Sap190p" "Sap4p" "Sar1p" "Sar1p-GTP" "Sarcoma" "Sardinia" "Sardinian" "SceI" "Schwann" "Sec1" "Sec1-munc18" "Sec13p" "Sec13p-Sec31p" "Sec1p" "Sec22p" "Sec23" "Sec23p-Sec24p" "Sec31" "Sec4-GTP" "Sec4p–Sec15p" "Sec4–Sec15" "Sec5-3xGFP" "Sec6-2xmCH" "Sec6-GFP" "Sec8-2xmCH" "Sec9p" "Segat" "Self-renewal" "Self-reported" "Semi-quantitative" "Ser-15-p53" "Ser12" "Ser12-specific" "Ser15" "Ser159" "Ser19" "Ser1981" "Ser2" "Ser235" "Ser2448" "Ser4" "Ser8" "Ser807" "Ser9" "Sertoli-cell" "Set1C" "Sevenless" "Seventy-seven" "Seventy-two" "Shaefer" "Shanxi" "Shc-1" "Shien" "Sholl-plug" "Short-term" "SiHa-OCT4" "Siglec-1" "Sigma-Aldrich" "Significance" "Significances" "SinceGrm5" "Single-nucleotide" "Single-strand" "Sip1" "Sirt" "Sirt1–Sirt7" "Sirtuins" "Sixty-six" "Sixty-three" "Skp1-Cullin1-F-box" "Sle1c2" "Slit-Robo" "Slower-migrating" "Slug-mediated" "Smad1" "Small-molecule" "Snail" "Snc1" "Snc1p–Sso1p–Sec9p" "Snc2-M2" "Snc2-M2p" "Snc2-V39A" "Snc2p–Sec6p" "Snc–Sec6p" "Soft-tissue" "Somers" "Son-of-Sevenless" "Sox" "Spanish" "Spearman" "SpiroMeta" "Sponge-induced" "Sponge-mediated" "Sponge-reduced" "Springer-Bio" "Sprouty" "Sprouty4" "Spry4-null" "Spry4f" "Squibb" "Src" "Src-family" "Src-regulatory" "Ssk2" "Ssk2p" "Sskp2" "Sso1p" "Sso1p–Sec9p" "Sso2p" "Stadler" "Ste11" "Ste20" "Ste20-like" "Stockholm" "Strep" "Strep-Tactin" "Stress-induced" "Stub1-IRES-dsRed2" "Sturm" "Sub-group" "SupF" "Super-resolution" "Suplem" "Supple­mental" "Suv4-20h1.1" "Swa2p" "Sweden-PGC" "Swedish" "Swiss" "Switzerland" "T-77C" "T-LAK" "T-Lymphoid" "T-Lymphotropic" "T-P-X-R" "T-S" "T-STAR" "T-STAT3" "T-X-X-X-Phospho-S" "T-allele" "T-binding" "T-cell" "T-lymphoid" "T-lymphoma" "T-lymphomas" "T-rich" "T-vector" "T1" "T1-T3" "T109-F113" "T134A" "T166A" "T174A" "T180" "T180A" "T1G2.2" "T1G3.1" "T1G4.2" "T284" "T284R" "T284R-DNA" "T2DM" "T3" "T306D" "T308" "T359" "T36" "T37" "T4" "T47DR" "T5" "T599dup" "T790M" "T85" "T88" "TA-r" "TAA" "TACE-dependently" "TAM67" "TAMRAD" "TAP-A20-containing" "TAP-A20-overexpressing" "TAPI" "TAPI-1" "TATA" "TATA-less" "TAZ-regulated" "TAZ2" "TAZS89A" "TAZΔ393" "TAp" "TAp73" "TBB" "TBH" "TBR" "TBSA" "TBSA≥20%" "TC" "TC-10" "TCF-4-mediated" "TCF-binding" "TD" "TDCs" "TDG1" "TDL" "TDLUs" "TEA" "TEF-2" "TEFb" "TEFb-dependent" "TEV" "TEV-GFP-10" "TF-N" "TFN-α" "TGF-β-induced" "TGFBR2-3" "TGFβ1-blockade" "TH-A" "TH-B" "TH-C" "THAB-S2" "THAP" "THAP-S2" "THAP1-S1" "THAP1-S2" "THAP1-induced" "THAP1-regulated" "THM" "TIN" "TKI-EGFR-based" "TKI-treated" "TM" "TM+MM" "TM+TT" "TMPRSS4-negative" "TMPRSS4-positive" "TMRM" "TN" "TNBCs" "TNF-receptor" "TNF-superfamily" "TNFR-2" "TOM" "TOPOIIα" "TRA-1-60" "TRAF" "TRAF31P2" "TRAF3IP2-_rs33980500" "TRAF3IP2_rs33980500" "TRAPP" "TRAPPI" "TRCP" "TRCP2" "TROSY" "TROSY-HSQC" "TRPC6-p53-RE" "TRPC6-p53RE" "TRUS" "TRα" "TS" "TSEs" "TSS10" "TT29201" "TTF-1-negative" "TTF=6.1" "TTF=7.4" "TTN5AA" "TTSP" "TTSPs" "TUJ1" "TURBT" "TURP" "TY" "TZ" "Table2" "Tah18" "Tailless" "Taiwan" "Taiwanese" "Take-home" "Taken" "TaqMan" "Taqman" "Target-Scan" "TargetScan" "TargetScanS" "Tat" "Tat-TAR" "Tat-induced" "Tat-inhibitory" "Tat-mediated" "Tax" "Tax-1" "Tax-2" "Tax-HA" "Tax-NBs" "Tax-induced" "Tax-mediated" "TdR" "Tead" "Teffector-like" "Tek" "Tert" "Tert-butanol" "Testa" "Tet-o-MYC" "TetP-α-synuclein" "Tfn" "Tg" "Tg6799" "Th-1" "Th-17" "Th-2" "Th1-polarization" "Th17-driven" "Th2" "Thakran" "TheErbB2" "TheraScreen" "Thin-section" "Thioglycolate" "Thirty-eight" "Thirty-five" "Thirty-four" "Thirty-nine" "Thomas" "Thr-pro" "Thr-specific" "Thr163" "Thr18" "Thr1989" "Thr218" "Thr308" "Thr37" "Thr4" "Three-dimensional" "Tiam1-C-1199" "Tiam1-C1199-induced" "Tiffen" "Time-course" "Time-lapse" "Tokyo" "Toll" "Tomita" "TopoIIα" "Topoisomerase-IIA" "Topo–DNA" "TrF" "TrF-pathway" "TrFs" "Trans-Activator" "Trans-membrane" "Translocated" "Transwell-invasion" "TrioD1" "Tris-EDTA" "Tris-HCl" "Tris–HCl" "TrkA" "TrkA-immunoreactive" "Trp53" "Trs33p" "TrueBlot" "Tryptophan" "Tryptophan-GH-IGF-1-mTORC1" "Tryptophan-GIP-GH-IGF-1-mTORC1" "Tsai" "Tubastatin" "Tuj-1" "Tuj-1-postive" "Tukey" "Tumor-node-metastasis" "Tweedie" "Tween-20" "Twenty-eight" "Twenty-five" "Twenty-four" "Twenty-nine" "Twenty-one" "Twenty-three" "Twenty-two" "Two-hybrid" "Two-locus" "Two-variant" "Tyr-572" "Tyr-742" "Tyr1007" "Tyr220" "Tyr551Stop" "T→A" "T→G" "U-IgVH" "U-rich" "U1" "U133" "U133A" "U1control" "U1wt" "U21459" "U23674" "U251" "U251-vIII" "U251vIII" "U251vIIIwt" "U26" "U2932" "U3" "U373" "U73122" "UA" "UACR" "UBMs" "UCBs" "UGI" "UGT2B15*2" "UICC" "UK" "UK-Pan-1" "UM-UC-9" "USA" "USB" "USF2+HBS" "USF2∆basic" "USF81" "UTR-mut" "UTRs" "UV-irradiation" "UV-mutagenesis" "UV-radiation" "UVC" "Ub-K48R" "Ub-K63-specific" "Ub-K63R" "Ub-Ub" "Ub-ligase" "UbcH2" "Uev1a" "Uso1p" "Utah" "V-AKT" "V-FITC" "V-HA-RAS" "V-Ki-ras2" "V-RAF-1" "V3b" "V5" "V5-tagged" "V544ins" "V6" "VAD" "VATS" "VB" "VDQ-002" "VE-cad-Cre" "VE1-antibody" "VI" "VMC" "VPS34-dependent" "VSV" "VSV-G" "VSV-G-ts45" "VSV-G–GFP" "VU0155056" "VU0359595" "VYSXWLXXY" "Value" "Vancouver" "Variants" "Vastus" "Vectibix" "Vector" "Vegf-A" "VeraTag" "Villeurbanne" "Vimentin" "Vincent-Salomon" "Vogelstein" "Vpr-host" "Vpr-treated" "W437X" "W515K" "W659A" "WASP" "WBC" "WJTOG3405" "WNT" "WSP" "WST" "WST-1" "WST-8" "WT-Cdh1" "WT-Cdh1-expressing" "WT-Vpr" "WT1-B" "WT1-D" "WT1-like" "WT1-shRNA3repressed" "WT1enhanced" "WTcells" "Wald" "Wallis" "Warburg" "Watson" "Watson–Crick" "Weinberg" "Weisberg" "Weri-Rb1" "Werner" "Western-blot" "Western-blots" "White" "Whitney" "Whole-cell" "Wiernik" "Wilcoxon" "Wright-Giemsa" "Wsh" "Wt-EphA2" "Wt-EphA2-Myc" "Wt-HA-c-Cbl" "Wt-c-Cbl" "Wu" "Wuillème-Toumi" "Wv" "X-11787" "X-DL" "X-inactivation" "X-irradiation" "X-linked" "X-ray" "X-rays" "X1" "X100" "X12" "X1w" "X4" "X9A" "XAip1" "XG" "XL-ICN" "XLF-defective" "XPA-UVDE" "XPA-importin-α7" "XPA-ΔNLS" "XPro1595" "XRCC1-BRCTII" "XRCC1-defective" "XRCC1BII" "XRCC1LL360" "XRCC1w" "XRCC1–LigIIIα" "XTT" "XX" "XY" "Xia" "Xrcc3-like" "Xu" "Y-family" "Y201X" "Y202" "Y229E" "Y229F" "Y233E" "Y233F" "Y2H" "Y352" "Y352E" "Y352F" "Y39F" "Y50F" "Y5R1c52" "Y647F" "Y648F" "Y656A" "YAP-IF" "YAP-IHC" "YAP1-1" "YAP5SA" "YAPS94A" "YCK" "YFP-DBN" "YHL017W" "YHR122w" "YI" "YL" "YPK2" "YRI" "YS" "YSXXLXXL" "YVO4" "YXXM" "Yang" "Yang-1" "Yang1" "Yap" "Yap-Amot-p130" "Yap-Tead-mediated" "Yap-Tead–dependent" "Yap-Tead–mediated" "Yap1081" "Yap1801" "Yap1802" "Yap1802p" "Yes" "Yes-associated" "Yin" "Ykt6p" "York" "Yorkie" "Yoruba" "Ypt1" "Ypt1p" "Z-VAD" "Z-guggulsterone" "Z=0.727" "ZAL4" "ZBKR1" "ZFNs" "ZIP6-M" "ZIP6-Y" "ZIP6-mediated" "ZO" "ZO-1-PDZ2" "ZO-1-S168A-Flag" "ZO-1-S168D-Flag" "ZO-1-WT-Flag" "ZR-75" "ZR-PELP1" "ZR-PELP1-141-mimetic" "ZR-PELP1-200a-mimetic" "ZR-PELP1-GFP-Luc" "ZR75" "ZR75-PELP1-shRNA" "ZR75PELP1-shRNA" "ZZ" "Zeng" "Zetterberg" "Zhang" "Zhao" "Zhou" "Zhu" "Zinc-finger-leucine" "Zn" "Zn-finger" "Zn1" "ZnF" "ZnFs" "ZnPP" "Zou" "aCGH" "aPI3K" "aPKC" "aPKCs" "above-noted" "ac-KIGS" "ac-Lys" "acetyl-lysine" "acetylated-KXGS" "acetylated-lysine" "acetylation-deacetylation" "acetylation-mimetic" "achaete" "achaete-schute" "acid-locked" "acid-soluble" "acids-PCR" "acinar-predominant" "acral" "actin-cytoskeleton" "actin-like" "actinomyosin" "actin–yellow" "activated-cell" "activation-loop" "activators" "actively-transcribed" "adSIRT1" "adduct" "adducts" "adeno" "adeno-null" "adenomatoid" "adherent-invasive" "adhesiveness" "adipocyte-like" "adipose-derived" "adipose-related" "adult-onset" "advanced-stage" "adverse-effect" "aeruginosa" "affinity-purify" "aflatoxin-B1" "agar" "age-associated" "age-dependent" "age≤69" "aggregate-prone" "aggresome-like" "agonism" "agonists" "agreed-upon" "aily-1" "air-liquid" "air–medium" "alfa-fetoprotein" "algorithm" "algorithms" "all-atom" "all-or-nothing" "all-time" "allele-A" "allele-C" "allele-G" "allele-T" "alleles" "allodynia" "allograft" "alpha-helical" "alpha-positive" "alternative-splice" "alveoli" "amino-acid" "amino-terminal" "amino-terminus" "aminoacids" "amoeboid" "amphisomes" "amplicon" "amplicons" "amplification-driven" "amyloid-like" "amyloids" "anchorage-independence" "and-761" "andA2λ" "andBrca1" "andErbB2" "andGrm5" "andPyMT" "andTP53" "and\\or" "andand" "andp21" "andp27" "androgen-dependence" "androgen-deprivation" "androgen-independence" "androgen-receptor" "aneuploidy" "aneurysm" "aneurysms" "angiogenic-related" "angiomotin-like" "anilino" "anilino-monoindolylmaleimide" "anisotropy" "anorexia" "antagomir" "antagomirs" "ante-phase" "antibodies" "antigen" "antigen-specificity" "antigens" "antisense-ODN" "antitumour" "aorta-derived" "ap-proach" "apical-basal" "apm4" "apo-EF1" "apoE-null" "apoptosis-functional" "apoptosis-relevant" "apoptosis-stimuli" "apoptotic-like" "apoptotic-proliferation" "aptamer" "aptamers" "arcade-like" "arginine-rich" "arginine-to-leucine" "arisen" "arm-mediated" "armadillo-repeats" "armed-ATC" "array-CGH" "arrest-defective" "as-yet-unidentified" "asthma-like" "astroglia" "astroglial-derived" "at-risk" "atomic-level" "atrophins" "atypia" "authors" "auto-activation" "auto-antibodies" "auto-inhibited" "auto-inhibitory" "auto-regulatory" "autocrine-dependent" "autophagic-dependent" "autophagy-lysosome" "autoradiography" "auxillin" "avg" "a–d" "b-actin" "b-d" "b0+Σ" "b1" "b2" "bHLH+PAS" "bHLH-LZ" "back-to-back" "back-up" "background-to-target" "bafilomycin" "bare-decorated" "barrier-permeable" "basal-like" "base-line" "base-long" "base-pair" "base-pairs" "baseline-like" "basic-helix-loop-helix" "basic-leucine" "bead-microarrays" "beads-on-a-string" "begun" "benzo" "beta-activated" "beta-oxidation" "better-known" "between-765G" "between-766" "between-run" "between-study" "bevacizumab-erlotinib" "bi-allelic" "bi-directionally" "bi-orientation" "bi-parametric" "bi-partite" "bi-phasic" "bi-weekly" "bifida" "bilayer" "bilayers" "biliverdin" "bio-energetic" "bio-photonic" "biologically-independent" "bis" "bisphosphate" "bivariate" "blockers" "blood-based" "blood-brain" "blood-brain-barrier" "blood-derived" "blood–brain" "blot-based" "blue-shifted" "body-associated" "bone-like" "bone-marrow-derived" "bone-tropic" "bothEts2" "bothp21" "bothp53" "box-and-whisker" "bp-CpG" "brainstem" "branched-chain" "break-apart" "break-dependent" "break-induced" "break-prone" "breakpoint" "breakpoints" "breast-like" "broad-acting" "broad-range" "broad-ranging" "broad-spectrum" "bronchoconstrictors" "bronchoscopy" "bulge-loop" "bundle-like" "butanol" "by-product" "by-products" "by16" "byTP53" "byp27" "b–d" "b–j" "c-Cbl-C3HC4C5" "c-MycER" "c-NHEJ" "c-Src-dependent" "c-Src-induced" "c-Src-mediated" "c-e" "c-neu" "c-src-phalloidin" "c1" "cFN" "cIAPs" "cJUN" "cXPA" "caAkt" "caC" "caSTAT3" "cadmium-induced" "calcein-AM" "calcium-bilirubinate" "callosum" "calorimetry" "cancer-like" "cancer-predisposition" "caner" "cap-complex" "cap-dependent" "capillaries" "capillary-like" "capillary-tube" "capsid" "carbazole" "carbon-oxygen" "carbon-sulfur" "carbonyl" "carboplatin+olaparib" "carboplatin-gemcitabine" "carboplatin-paclitaxel" "carboplatin-pemetrexed" "carboplatin-vinorelbine" "carboplatin–olaparib" "carboxyl" "carboxyl-terminal" "carboxyl-terminus" "carboxylcytosine" "carcinogen-DNA" "carcinogens" "cardiotrophin-like" "cargo-modifying" "carotid" "carriers" "carry-over" "cartilage-like" "case-by-case" "case-control" "case-controls" "case-specific" "casepase9" "case–control" "caspase-1-dependent" "caspase-like" "castration-induced" "castration-mediated" "castration-resistant" "castration-sensitive" "castration-sensitivity" "catalytic-domain" "catechol-O-methyl" "catenin-mediated" "catenin-membrane-positive" "cation–π" "cause-and-effect" "caveolae-like" "cavin-3-GFP-expressing" "cavin-GFP" "cavin-MiniSOG" "cavins" "ccRCC" "ccRCCs" "cel-miR-67" "cell-autonomous" "cell-cycle-related" "cell-extracellular-matrix" "cell-in-cell" "cell-intrinsic" "cell-like" "cell-malignant" "cell-permeable" "cell-polarity" "cell-to-cell" "cell-to-medium" "cell-type-specific" "cells" "cellular-movement" "centromere" "cerebellum" "cerevisiae" "cetuximab-naïve" "cetuximab-treatment" "cfDNA" "cg08008233" "cg12215675" "chain-mimetics" "chaperone--a" "charcoal-dextran" "charcoal-stripped" "checkpoint-dependent" "checkpoint-insensitive" "checkpoint-proficient" "chemically-engineered" "chemically-induced" "chemically-synthesized" "chemo" "chemo-protective" "chemo-radiation" "chemo-responsiveness" "chemo-sensitivity" "chemo-sensitizers" "chemo-therapeutics" "chemo-therapies" "chemoattractant" "chemoresistance" "chemoresistant" "chemotherapeutically-induced" "chemotherapy-naïve" "chi-square" "chi-squared" "childhood-onset" "cholesterol-dependent" "cholesterol-induced" "choline" "choroid" "chosen" "chr10" "chr2" "chr3∶196,792,172" "chr5" "chr6" "chrRCC" "chrRCCs" "chrX" "chromatid" "chromatids" "chromatin-RNA" "chromatin-remodeling" "chromophobe" "chromosome-specific" "circletail" "cis-elements" "cis-regulatory" "cisplatin-docetaxel" "cisplatin-etoposide" "cisplatin-gemcitabine" "cisplatin-pemetrexed" "cisplatin-vinorelbine" "cisplatin-vinorelbine-gemcitabine" "cistrome" "cistron" "class-1" "class-I" "classifier" "clean-up" "clearer" "clinic-pathological" "clinically-approved" "clinically-relevant" "clinicians" "clinico" "clinico-pathological" "clinics–agnostic" "clone-11" "close-by" "cluster-like" "coactivator-3" "coarse-grained" "cobblestone-like" "cocaine-Tat" "coding-gene" "codon" "codon-12" "codons" "cof" "cofilactin" "coiled-coil" "coli" "collagen-1A2" "collagens" "collectives" "colony-formation" "colony-forming" "combination-induced" "combinations" "combined-cocaine" "commercially-available" "compacta" "compartment-specific" "complex-the" "components" "concentration-dependence" "conditionalEts2" "conductance" "conductances" "confounder" "congenita" "conjunctiva" "connective-tissue" "consecutively-collected" "conshRNA" "contact-inhibited" "context-specificity" "continuum" "control-ShRNA" "control-nevi" "control-nevus" "control-pcDNA" "control-shRNA" "control-siRNA" "controlPyMT" "control±S" "cooperativity-dependent" "cooperativity-dependently" "cooperativity-independent" "cooperativity-reducing" "copy-number" "core-domain" "coregulators" "correlation=0.98" "cortico-striatal" "cost-effective" "cost-effectiveness" "costimulation-induced" "counter-intuitive" "counter-part" "counter-productive" "covariate" "covariates" "coworkers" "cow´s" "crescent-shaped" "cribriform" "crista" "cross-activate" "cross-activation" "cross-binding" "cross-breeding" "cross-complementation" "cross-complementing" "cross-complementing-1" "cross-contamination" "cross-inhibited" "cross-inhibition" "cross-linker" "cross-reactivity" "cross-resistance" "cross-section" "cross-sectional" "cross-study" "cross-validate" "cross-validation" "cross-β" "crossover" "crypt-villus" "crypts-villus" "cullin-RING" "current-smokers" "current-to-voltage" "curvature-inducing" "cut-off" "cutpoint" "cy-totoxicity" "cyan" "cycleave" "cyclin-A-mediated" "cyclin-B-mediated" "cyclin-CDK" "cyclin-D3" "cyclin-E-dependent" "cyclin-depended-kinase" "cyclinAsubstrate" "cyclinD-CDK" "cyclins" "cyclobutane–pyrimidine" "cypridina" "cys-LT" "cys-LT-activated" "cys-LT-dependent" "cys-LT-induced" "cys-LT-mediated" "cys-LT-responsive" "cys-LTs" "cytAco" "cyto" "cyto-construction" "cyto-protective" "cytochromes" "cytokeratin-19" "cytokine-treatment" "cytology" "cytosol-to-membrane" "c–e" "d-f" "dEGFR" "dG" "dHL-60" "dPLB" "dPLB-985" "dRASSF" "damage-binding" "damage-dependent" "damage-independent" "damage-induced" "damage-inducible" "damage-inducing" "damage-regulated" "damage-responsive" "damage-signaling" "database-TargetScan" "database-identified" "databases" "dataset" "datasets" "day-to-day" "dbSNP" "dbSNP-Reference" "de-activated" "de-aggregated" "de-aggregation" "de-condensation" "de-differentiated" "de-novo" "de-regulate" "de-regulated" "de-regulation" "de-represses" "de-repression" "de-repressive" "de-ubiquitinase" "de2-7" "deacetylase-defective" "death-receptor-induced" "decay-promoting" "deep-sequence" "deeper" "degron" "degrons" "dehydrogenase-5" "del11" "del11q" "del126-133" "del158-172" "del17" "del17p" "del19" "delGly158-Asp172" "delL747-E749" "deleted-loop" "delta-mtDNA" "dendritic-like" "density-dependent" "deoxycitidine" "deoxynucleotidyl" "deoxyuridine" "dependent-RNA" "dependent-manner" "depolarization-induced" "der" "dermato-pathologist" "desmocollin-1" "desmoglein-1" "desmogleins" "detachment-induced" "detergent-insoluble" "di-arginine" "di-methylated" "di-substituted" "diabetes-associated" "diabetes-dependent" "diabetes-increased" "diabetes-induced" "diabetes–increased" "diabetes–induced" "diaminobenzidine" "dichroism" "diet-derived" "diet-fed" "diet–genotype" "differentiated-like" "dihydroxy" "dimer-level" "dimer-to-monomer" "dimers" "dimorphism" "dimorphisms" "dinucleotides" "diploid" "diplotype" "discoideum" "discrepant" "disease-relevant" "dithiobis" "dnSTAT3" "doi" "dominant-negative" "donor-to-donor" "dormancy" "dosage-dependent" "dosage-sensitive" "dose-and" "dose-based" "dose-dependency" "dose-dependently" "dose-response" "dose-responses" "dose–response" "dot-like" "double-blind" "double-block" "double-membrane" "double-minute" "double-negative" "double-proline" "double-strand" "double-thymidine" "down-expressed" "down-expressing" "down-modulated" "down-modulating" "down-modulation" "down-stream" "down-weights" "doxy" "doxy-treatment" "doxycyline" "drawn" "driven-tumors" "droplets" "drug-overhang" "drugs" "ds" "dsDNA" "dual-function" "dual-label" "dual-phosphorylation" "dual-priming" "dual-reporter" "dual-specific" "dual-targeting" "dual-tilt" "duct-lobular" "duplexes" "duration=24" "duration=7.4" "dwarfism" "dying-back" "dyn" "dyscrasia" "dyscrasias" "dysfunction-induced" "dyslipidemia" "dysplasia" "dyspnea" "d–f" "e-08" "eEF2-56T" "eHELQ" "eIF4" "eLife" "eQTL" "eSNPs" "eXRCC2" "early-late" "early-onset" "early-passage" "early-phase" "early-region" "early-stage" "ebpα" "echinoderm" "ectdomain" "ectodomain" "ectodomains" "ectopically-expressed" "edema" "effector-like" "egg-shell" "electron-dense" "element-1" "element-binding" "element-variable" "eluate" "embryopathy" "empty-shRNA" "en-bloc" "end-organ" "end-product" "end-resection" "end-stage" "end-to-end" "endoderm" "endometria" "endometrioid" "endometrium" "endometrium-like" "endoplasmic-reticulum-located" "endothelia" "endothelial-independent" "endothelial-like" "endothelial-marker" "endothelial-specific" "endpoint" "endpoints" "energy-modulated" "enhancer" "enhancer-binding" "enhancer-core" "enhancer-promoter" "enhancer–promoter" "enriched-phenotype" "entero-insular" "environmental-genetic" "enzyme-DNA" "enzyme-E2" "enzyme-substrate" "enzymes" "enzyme–DNA" "eosin" "epeat" "eph" "epicardium" "epigenome" "epithelia" "epithelial-cell" "epithelial-derived" "epithelial-like" "epithelial-mesenchymal" "epithelial-sensitive" "epithelial-specific" "epithelial-stromal" "epithelial-targeted" "epithelial-to-mesenchymal" "epithelial-type" "epithelial–mesenchymal" "epithelial–targeted" "epithelium" "epitheloid" "epitope-tag-specific" "epsilon" "epsilon-amino" "equi-molar" "erlotinib-naïve" "error-containing" "erythroid-2-related" "estradiol-dependence" "estrogen-dependence" "eta" "ethnic-specific" "ets" "ever-smoker" "ever-smokers" "ex" "ex-smokers" "ex-vivo" "examinedGrm5" "excited-state" "exogenously-expressed" "exon-level" "exon17" "exon19" "exon21" "exon9" "exons" "exosome" "exportin-cargo" "exposed-breast" "extension–retraction" "extra-cell" "extra-genital" "extra-helical" "extra-mitochondrial" "extra-nuclear" "extra-oral" "extra-synaptic" "extracellular-initiated" "extract-based" "extract-induced" "ezrin-like" "e–f" "e−05" "fC" "factor-1" "factor-4" "factors" "failure-to-thrive" "falciparum" "fall-off" "fat-diet" "fatpad" "feed-back" "feed-forward" "feedback-regulatory" "feedforward" "female-specific" "fermentans" "fetal-specific" "fibroblast-like" "fibulin-like" "fifty-seven" "filled-in" "filopodia-like" "filter-trap" "fine-mapping" "fine-needle" "fine-tune" "fine-tuned" "fine-tunes" "fine-tuning" "first-degree" "first-generation" "first-in-human" "first-line" "fish-oil" "five-stranded" "five-year" "flask-like" "flexibly-tethered" "flow-cytometry" "flow-driven" "flow-intensity" "flow-through" "flow-thru" "flox" "fluorescence-in-situ-hybridization" "fluorescence-lifetime" "fluorophore" "flux–it" "fms-like" "focus-forming" "folic" "follow-up" "followed-up" "footpad" "footpads" "force-stimulated" "forebrain" "former-smokers" "formyl" "formyl-Met-Leu-Phe" "formyl-peptides" "formylcytosine" "forty-four" "four-aa" "four-and-a-half" "four-color" "four-helix" "four-point-one" "four-way" "fractions" "frame-by-frame" "frame-shift" "frameshift" "free-EGFR" "freeze-substitution" "freeze-thaw" "fresh-frozen" "fromErbB2" "fromErrfi1" "fromEts2" "fromGrm5" "fromHomer1" "fromHomer1a" "fromPin1" "fromPyMT" "fromp53" "front-line" "frozen" "full-site" "full-text" "function-2" "functionalities" "fusiform" "g-l" "g-ratios" "gARPCs" "gDNA" "gain-of-function" "gastro" "gastro-esophageal" "gastro-intestinal" "gatekeeper" "gel-filtration" "gel-shift" "gender-by-SNP" "gene-aspirin" "gene-by-environment" "gene-carrier" "gene-disease" "gene-environment" "gene-gene" "gene-phenotype" "gene-therapy" "gene-trap" "gene-wise" "genes" "genetically-engineered" "genetically-susceptibility" "gene–diet" "gene–disease" "gene–environmental" "gene–gene" "genitalia" "genitals" "genome-wide" "genotype-disease" "genotype-phenotype" "genotype-selectable" "genotypes" "genotype–diet" "germ-line" "germinal-center" "germline" "giants" "glia" "glomeruli" "glomerulonephritis" "glucagon-like" "glutamate-rich" "glutathione-sepharose" "glycosylase-formed" "glycosylase-generated" "goat-anti-human" "goat-anti-mouse" "goes" "goosecoid" "gp-120" "gp120-CXCR4" "gpK8.1A" "gradients" "grainyhead-like" "granular-shaped" "greater" "greatest" "green-labeled" "growth-repressive" "g–i" "g–j" "h2" "hBRCA1" "hCD45" "hESC" "hESCs" "hEnSCs" "hGH" "hGHR" "hIL-6" "hIgG" "hMCM7" "hNSC" "hNSCs" "hSET1" "hSIRT1-FL" "hSIRT1-NT" "hTH-3174" "hTH-3174-luc" "hTH-NBRE-A" "hTR-Imetelstat" "hTR-Ku" "half-a-million" "half-dozen" "half-life" "half-lives" "half-maximal" "half-saturated" "half-saturating" "half-saturation" "half-site" "half-sites" "half-stoichiometric" "hand-containing" "hand-foot" "hands-on" "haploChIP" "haplotype" "haplotypes" "head-to-head" "head-to-tail" "healthy-state" "heat-map" "heat-shock" "heatmap" "heavier" "helical-domain" "helices" "helix" "helix-loop-helix" "helix–loop–helix" "helq-1" "hemangiopericytoma-like" "hemato-endothelial" "hematoxilin-eosin" "hematoxylin-eosin" "hepato-carcinogenesis" "hepatoid" "heregulin-alpha" "hetero-dimer" "hetero-dimers" "hetero-oligomerises" "hetero-oligomers" "heterogeneous-mutated" "heterotetramer" "heterotetramers" "heterozygote" "hexamethylene-bis-acetamide" "hg18" "hg19" "hidden" "high-DNA-flexibility" "high-MW" "high-accuracy" "high-affinity" "high-blood-flow-dependent" "high-concentration" "high-concentrations" "high-confidence" "high-content" "high-density" "high-dose" "high-fat" "high-frequency" "high-glucose" "high-grade" "high-incidence" "high-invasive" "high-level" "high-levels" "high-molecular-mass" "high-molecular-weight" "high-order" "high-penetrance" "high-performance" "high-pressure" "high-quality" "high-resolution" "high-risk" "high-stage" "high-stress" "high-tumour" "high-value" "higher-molecular-mass" "higher-order" "higher–molecular" "highly-conserved" "highly-prevalent" "hindlimb" "hindpaw" "histochemistry" "histologically-defined" "histologies" "histology" "histone2" "histopathology" "history–on" "histoscore" "histotype" "histotypes" "hoc" "holo" "holo-complex" "holo-receptor" "homeodomain" "homo-oligomerization" "homo-oligomers" "homo-or" "homogenates" "homolog" "homologies" "homologs" "homologue-1" "homology-2" "homozygote" "homozygousEts2" "hormone-independence" "hospital-base" "host-cell" "host-virus" "hot-spot" "hotspot" "hotspots" "hour-time" "house-keeping" "hrr25" "hrr25-5" "hsa-miR-125b-1" "hsa-miR-125b-2" "htert" "hydrogen-bond" "hydrogenase-like" "hydroxy" "hydroxylase-positive" "hyper-IgE" "hyper-cholesterolemia" "hyper-immunoglobulin" "hyper-proliferation" "hyper-proliferative" "hyperdiploid" "hyperinsulinemia" "hyperoxia" "hyperresponsiveness" "hypo-acetylation" "hypo-phosphorylated" "hypocomplementemia" "hypomagnesemia" "hypoxia-related" "h " "h–4" "h–9" "h–t9" "iRBC" "iTRAQ" "identity-by-state" "ie" "ii" "ii-iv" "iii" "ii–iv" "ill-defined" "image-converted" "immediate-early" "immune-compensatory" "immune-complex" "immune-deficient" "immune-mediated" "immune-purified" "immune-reactivity" "immuno-EM" "immuno-electron" "immuno-fluorescence" "immuno-fluorescent" "immuno-histochemistry" "immuno-isolates" "immuno-isolation" "immuno-precipitant" "immuno-precipitate" "immuno-precipitated" "immuno-precipitation" "immunoassay" "immunoassays" "immunocomplexes" "immunocytochemistry" "immunoglobulin" "immunoglobulin-like" "immunohistochemistry" "immunophenotype" "immunophenotypes" "immunoprecipitatedwith" "immunoprecipitation-mass" "immunoprecipitations" "immunoscore" "immunosurveillance" "immunotherapies" "immunotherapy" "impedance" "importin-α" "importin-α1" "importin-α4-XPA" "importin-α5" "importin-α7-beads" "importin-β" "importins-α1" "importins-α4" "in-activation" "in-between" "in-cell" "in-depth" "in-flow" "in-frame" "in-gel" "in-human" "in-silico" "in-situ" "in-stent" "in-vitro" "in-vivo" "inErbB2" "inErrfi1" "inGrm5" "inHomer1" "inHomer1a" "inMCF-7" "inPARP1" "inParkin" "inPyMT" "inTP53" "incretin" "independently-generated" "induced-apoptosis" "induced-entosis" "inflammation-associated" "inflammation-induced" "inflammation-mediated" "infra-red" "ingrowth" "inhibitor-5" "inhibitor-IV" "inhibitor-IV-treated" "inhibitor-anthracycline" "inhibitor-α" "inhibitors" "inhibitors-of" "initiated-BER" "inp21" "ins" "insula" "insulin-GSK-3-p27" "insulin-like" "insulin-positive" "insulin-producing" "insulin-receptor-related" "insulin-stimulated" "int" "integrators" "inter-cell" "inter-chromosomal" "inter-class" "inter-genic" "inter-group" "inter-helix" "inter-individual" "inter-kinetochore" "inter-observer" "inter-relationships" "inter-subunit" "inter-tumor" "interactome" "interactomes" "interdomain" "interferon-κ" "interlobe" "intermediate-like" "intermediate-resistant" "intermediate-risk" "intermediate-sized" "intermembrane" "internalization–most" "interobserver" "interquartile" "interstitium" "interstrand" "intra-Golgi" "intra-aortic" "intra-chromosomal" "intra-individual" "intra-lesional" "intra-osseous" "intra-protein" "intra-renal" "intra-tibia" "intra-tumor" "intra-tumour" "intra-vascular" "intracardiac" "intracarotid" "intratumour" "intron-exon" "introns" "inva-siveness" "invasion-inhibitory" "invasion-metastasis" "invasion-suppressive" "inverse-BAR" "inverse-variance" "in–out" "iodoani" "iodoani-lino" "ionic" "irradiation-dependent" "irradiation-induced" "ischemia-reperfusion" "islets" "isoform-selective" "isoforms" "isomers" "isotope-coded" "isotype" "isozymes" "iv" "junction-associated" "k-MT" "k-MTs" "kDa" "kappa-B" "kappaB" "karyotype" "kbp" "kcal" "ketoacid" "kexin" "kg" "kinase-2" "kinase-defective" "kinase-interaction" "kinase-specificity" "kinase1" "kinases" "kinesin-like" "knock-down" "knock-down-induced" "knock-downs" "knock-in" "knocked-down" "knockin" "knocking-down" "knocking-out" "knowledge-base" "ku11ees" "ku12es" "labeling-intensity" "laboratory-specific" "laevis" "lambda" "lamellipodia-like" "lammilopodia" "lane3" "large-cell" "large-cohort-based" "large-diameter" "large-flat" "large-scale" "large-size" "laser-capture" "laser-induced" "late-G1" "late-acting" "late-onset" "late-phase" "late-recurring" "late-stage" "lateralis" "lattice-like" "lavage" "leading-edge" "leave-one-out" "left-shifted" "lentiviral-mediated" "lepidic-non-mucinous" "let-7a" "let-7g" "let7a" "let7b" "let7c" "let7f" "lethal-7a" "leucine-zipper" "leucoderma" "leukemia-1" "leukemia-2" "leukocytes" "leukoderma" "life-expectancy" "lifecycle" "lifespan" "ligand-receptor" "light-chain" "limb-specific" "limiting-dilution" "lincRNA-p21" "line-widths" "lineage-specific" "lipid-kinase" "lipid-phosphatase" "lipofectamine2000" "lipoproteins" "liposome" "lipoxygenase-mediated" "littermate" "littermates" "live-cell" "live-threatening" "lncRNA" "lo" "load-driven" "localizations" "location-dependence" "location-specific" "locus-specific" "log-additive" "log-phase" "log-rank" "long-acting" "long-axis" "long-lasting" "long-lived" "long-patch" "long-range" "long-standing" "long-time" "long-timescale" "long-tract" "longer-term" "loss-of" "loss-of-function" "lot-to-lot" "low-MW" "low-activity" "low-affinity" "low-cost" "low-density" "low-dosage" "low-dose" "low-fat" "low-frequency" "low-glucose" "low-grade" "low-incidence" "low-intensity" "low-level" "low-moderate" "low-molecular-weight" "low-oxygen" "low-penetrance" "low-percentage" "low-power" "low-quality" "low-risk" "low-scale" "low-serum" "low-throughput" "low-volume" "lower-contrast" "loxP" "lpr" "lumens" "luminal-like" "lung-only" "lupus-like" "lymph-node" "lymph-node-positive" "lymphadenopathy" "lymphoblastoid" "lymphoid-enhancer-factor-1" "lymphoma-like" "lysine-to-arginine" "lysine4" "lysosome-mediated" "lκBα" "m3" "mCherry" "mCherry-DBN" "mCherry-LC3" "mCherry-Lifeact" "mFadA" "mGluR-Pin1" "mGluR-SIC" "mGluR5FR" "mGluR5TSAA" "mL " "mNBRE-A1" "mNBRE-A2" "mRID1" "mRNA" "mRNA-level" "mSIN3A" "mSIN3a" "mSOD1" "mSin3A" "mTOCR2" "mTOR-AKT-PI3K-PTEN" "mTORC1-driver" "mTORC1-p70S6K-mediated" "mU" "mV" "mYap" "macro-microvascular" "macro-vascular" "macronodules" "macrophage-like" "magnesium-dependent" "main-effect" "malarial-induced" "male-to-female" "malignant-dampening" "mammary-specific" "mammosphere" "mammospheres" "map-2" "marker–positive" "mastectomy" "master-switch" "matched-pair" "materno-neonatal" "matrix-remodeling" "maturity-onset" "mcg" "mdDA" "mdm2-antagonist" "mean ± standard" "mean±S" "mean±SD" "mean±sd" "mean±standard" "mean ± SD" "mean ± standard" "mechano" "mechano-sensitivity" "mediated-sensitization" "melanocortin" "melanocortin-1" "melanogaster" "mellitus" "membrane-deformation" "membrane-depolarization" "membrane-distal" "membrane-non-binding" "membrane-proximal" "memory-resting" "mesangium" "mesencephalon" "mesenchymal-epithelial" "mesenchymal-like" "mesenchymal-refractory" "mesenchymal-specific" "mesenchymal-to-epithelial" "mesenchyme" "mesenchymoangioblast-like" "mesendoderm" "mesentery" "mesh-like" "meshwork" "meshworks" "mesoderm" "mesoscale" "meta-analytic" "meta-regression" "meta-static" "metabolically-stressed" "metabolome" "metal-bound" "metal-response" "metalloestrogen" "metalloestrogens" "metalloproteinase-1" "metastamir" "metastamirs" "metastasis-related" "metastectomy" "methyl-guanosine" "methyl-lysine" "methyladenine" "methylcytosine" "methylome" "miR-100" "miR-101" "miR-103" "miR-105" "miR-105-specific" "miR-106" "miR-106b" "miR-107" "miR-122" "miR-1225-5p" "miR-122KO" "miR-124" "miR-124-based" "miR-124-induced" "miR-124-mediated" "miR-1246" "miR-124a" "miR-125b-1" "miR-125b-sponge-transfected" "miR-126" "miR-128" "miR-129" "miR-130b" "miR-133" "miR-137" "miR-138" "miR-141" "miR-143" "miR-143-based" "miR-144" "miR-145" "miR-146" "miR-146a" "miR-148a" "miR-15" "miR-155" "miR-155-induced" "miR-15a" "miR-16" "miR-17" "miR-17-92" "miR-1915" "miR-192" "miR-193a" "miR-195" "miR-196a" "miR-197" "miR-199a" "miR-19b" "miR-200" "miR-200-independent" "miR-200-promoter-Luc" "miR-200b" "miR-203" "miR-205" "miR-20a" "miR-21-AR" "miR-21-controlled" "miR-21-forced" "miR-21-induced" "miR-21-liposomal" "miR-21-mediated" "miR-21-regulated" "miR-21-targeted" "miR-214" "miR-215" "miR-22" "miR-25" "miR-26a" "miR-26b" "miR-27a" "miR-27a*-IH" "miR-27a-SL" "miR-27b" "miR-27b-3p" "miR-27b-5p" "miR-29a" "miR-29b-driven" "miR-29c" "miR-30d" "miR-31" "miR-329" "miR-329-expression" "miR-329-inhibited" "miR-329-overexpressing" "miR-34" "miR-34-dependent" "miR-34-mediated" "miR-34-regulated" "miR-34b" "miR-34c" "miR-34c-depleted" "miR-34c-expressing" "miR-368" "miR-371-5p" "miR-376" "miR-376a" "miR-376b" "miR-376c" "miR-376c-3p" "miR-376c-transfected" "miR-379" "miR-379-410" "miR-429" "miR-433" "miR-433-binding" "miR-449a" "miR-451" "miR-494" "miR-503" "miR-503-binding" "miR-503-regulated" "miR-503-suppressed" "miR-503-transfected" "miR-675" "miR-744" "miR-766" "miR-768-3p" "miR-768-5p" "miR-9" "miR-93" "miR-99a" "miR-99b" "miR-US4-1" "miR-negative" "miR-transfer" "miR141" "miR145" "miR17" "miR200" "miR200a" "miR200b-200a-429" "miR200b-independent" "miR200c-141" "miR379" "miR768-3p" "miR99b" "miRNA" "miRNA-125b" "miRNA-125b-1" "miRNA-141" "miRNA-143" "miRNA-200a" "miRNA-200c" "miRNA-21" "miRNA-576" "miRNA-767" "miRNA-768" "miRNA-768-3p" "miRNA-768-5p" "miRNA-886-5p" "miRNA200b-200a-429" "miRNA200c" "miRNA768-3p" "miRanda" "miRtarget2" "micro-PET" "micro-aggregates" "micro-biosensor" "micro-dissection" "micro-homologies" "micro-irradiation" "micro-lesions" "micro-molar" "micro-ribonucleic" "micro-vascular" "microRNA" "microRNA-124" "microRNA-204" "microRNA-21" "microRNA-26a" "microRNA-503" "microRNAs" "microdomains" "microenvironment-mediated" "micrographs" "micropipette" "microsatellite" "microtiter" "microtubule-associated" "microvasculature" "microvesicles" "microvessel" "microvessels" "mid-G1" "mid-gestation" "mid-late" "mid-plane" "midbrain" "midbrain–hindbrain" "midzone" "military-related" "milk-derived" "milk-miR-29b-mediated" "milk´s" "minP" "minP≤0.05" "mini-satellites" "minor-groove" "mir-143" "mir-29a" "mir-29c" "mir200c" "mis-localization" "mis-localize" "mis-segregate" "mis-segregation" "mis-sense" "missense" "mmBrca2" "mmpTRPC63p-luc2" "moDC" "moDCs" "mock-infected" "mock-transfected" "mock-treated" "moderate-strong" "moderate-to-severe" "modifica-tions" "modifications" "moesinezrin-radixin–like" "molecules" "mono-O-GlcNAcylated" "mono-SUMOylated" "mono-cultured" "mono-exponential" "mono-lobed" "mono-palmitoylated" "mono-palmitoylation" "mono-therapy" "mono-treatment" "mono-treatments" "mono-ubiquitin" "monoamine" "monocyte-derived" "monocyte-endothelial" "monocyte-lineage" "monocyte-microglial" "monolayer" "monomer-oligomer" "monosomy" "monotherapy" "months" "morbidities" "more-or-less" "more-than-10-fold" "morpholino" "morpholino-IPQA" "morpholinos" "morphology-dependent" "morphometry" "mortem" "mother-bud" "motile" "mouthwash" "mtp53" "muCIA" "muCIA2A" "muCIA2A-myc" "mucosa" "multi-SNPs" "multi-cellular" "multi-centric" "multi-colour" "multi-copy" "multi-drug" "multi-ethnic" "multi-factorial" "multi-functional" "multi-institutional" "multi-meric" "multi-modality" "multi-organ" "multi-parametric" "multi-protein" "multi-stage" "multi-step" "multi-subunit" "multi-variate" "multi-vesicular" "multidomain" "multiforme" "multimers" "multiple-target" "multiple-testing" "multiplex-ligation-dependent" "multiprotein" "multisite" "multistage" "multisubunit" "multivariate" "muscle-invasive" "muscle-specific" "muscleblind-like-1" "mut1" "mut2" "mutant-NSCLC" "mutations" "mutationsNotch2" "mutp53" "myDC" "myDCs" "myc-CK1δ" "myelopathy" "myocardium" "myocyte-specific" "myoepithelium" "myofiber" "myofibroblast-like" "myoid" "myosin-II" "myosinII" "myotonia" "myotonic-dystrophy-like" "n-6" "n-fold" "n=1" "n=103" "n=118" "n=13" "n=16" "n=195" "n=2" "n=20" "n=23" "n=3" "n=30" "n=34" "n=35" "n=36" "n=4" "n=40" "n=5" "n=6" "n=7" "n=8" "n=84" "n=9" "nLC-MALDI-TOF" "nLC-Q-TOF" "nRNP" "nXPA" "nano" "nano-biosensor" "nano-scale" "nanoLC-MS" "nanoscale" "nanotube-like" "napsin" "naïve" "near-complete" "near-endogenous" "near-field" "near-infrared" "near-normal" "near-saturating" "near-significance" "near-stoichiometric" "nearMECP2" "necropsy" "necrostatin-5" "necrostatins" "negative-curvature" "negative-feedback" "neo-RSK4" "neo-adjuvant" "neoadjuvant" "neocortex" "neointima" "neonate´s" "nephritis-like" "nephropathy" "nerves" "network-dependent" "network-level" "neu-positive" "neurite" "neuroendocrine" "neuroepithelium" "neuron-like" "neuronal-enriched" "neuronal-like" "neuropathology" "neurosphere" "neurospheres" "neurosurgery" "neutrophil-like" "never-smokers" "never-smoking" "new-onset" "newly-generated" "next-generation" "nick-end" "nigricans" "nitro" "nitrosoguanidine" "no-flow" "no-smoking" "node-positive" "nonLR" "noncardia" "noncarriers" "nonhistone" "nonmalignant" "nonmeta-bolizable" "nonmuscle" "nonredundant" "nonsense-mediated" "nontarget" "normal-like" "not-yet" "nt" "ntRNA" "nts" "nucleatum" "nucleophosmin1" "nucleus-only" "nucleus-positive" "nutrient-proficient" "nutrient-replete" "nutrient-response" "nystagmus" "n = 103" "n = 2" "n = 5" "n = 6" "n = 7" "n = 8" "n = 1" "n = 13" "n = 16" "n = 2" "n = 20" "n = 23" "n = 3" "n = 4" "n = 5" "n = 6" "n = 8" "oBII" "oHSV" "occludens-1" "occludes" "occurrences" "octamers" "octyl-glucoside" "oestrogen" "oestrogens" "of-transcription" "of4EBP1" "ofCdk6" "ofMBNL1" "off-target" "off-the-shelf" "ofp21" "ofp27" "ofp53" "of≤24" "oil-derived" "oil-red" "oldPyMT" "oleic" "oligo" "oligodendroglial-predominant" "oligonucleotide-PCR" "oligos" "on-column" "on-going" "on-site" "on-treatment" "on-trial" "onGrm1" "oncogene-driven" "oncogenes" "oncology" "oncomir" "one-copy" "one-dimensional" "one-electron" "one-ended" "one-factor" "one-fifth" "one-half" "one-sided" "one-step" "one-third" "one-thousand" "one-way" "open-angle" "open-label" "orGrm5" "orHomer1" "orPyMT" "orchidectomy" "organoids" "ortholog" "orthologue" "orthologues" "osteoblasts" "osteogenic-like" "outcome–namely" "over-activate" "over-activated" "over-activation" "over-interpret" "over-interpreted" "over-phosphorylation" "over-stimulate" "over-treatment" "overview" "oxoG" "oxygenase-1" "p(NBRE)" "p-c-Met" "p-c-met" "p110a" "p120-VE" "p120-catnin" "p125luc" "p16+" "p16-Leiden" "p16-defective" "p16-proficient" "p160s" "p21WAF1" "p21waf1" "p27SJ" "p27kip" "p27–30" "p300-ASH2L" "p300-dependent" "p300-enhanced" "p38CKO" "p38MAPK" "p38SJ" "p38i" "p38α-dependence" "p38β" "p3xE2F-luc" "p4EBP1" "p50α" "p53-DNA" "p53-RE" "p53-SET1C" "p53-and" "p53-binding-site" "p53-defective" "p53-dependent" "p53-haploinsufficient" "p53-minimal" "p53-null" "p53-p300" "p53-promoter" "p53-reporter" "p53C" "p53CKO" "p53ER" "p53MH" "p53R175H" "p53R273H" "p53R280K" "p53REs" "p53WT" "p55α" "p62ΔTB" "p70S6" "p85α" "p90rskSer380" "p=0.00001" "p=0.00002" "p=0.00003" "p=0.00004" "p=0.00009" "p=0.0001" "p=0.00014" "p=0.00016" "p=0.00017" "p=0.00019" "p=0.0002" "p=0.000215" "p=0.00022" "p=0.00037" "p=0.00039" "p=0.0004" "p=0.0008" "p=0.001" "p=0.0012" "p=0.0013" "p=0.0014" "p=0.0015" "p=0.0016" "p=0.002" "p=0.0020" "p=0.0026" "p=0.003" "p=0.004" "p=0.0045" "p=0.0048" "p=0.006" "p=0.007" "p=0.008" "p=0.009" "p=0.0091" "p=0.01" "p=0.012" "p=0.013" "p=0.014" "p=0.015" "p=0.016" "p=0.0161" "p=0.017" "p=0.018" "p=0.019" "p=0.0196" "p=0.02" "p=0.020" "p=0.022" "p=0.023" "p=0.024" "p=0.0247" "p=0.025" "p=0.029" "p=0.03" "p=0.030" "p=0.032" "p=0.033" "p=0.034" "p=0.036" "p=0.037" "p=0.04" "p=0.0413" "p=0.042" "p=0.043" "p=0.045" "p=0.05" "p=0.056" "p=0.068" "p=0.083" "p=0.086" "p=0.095" "p=0.14" "p=0.16" "p=0.17" "p=0.21" "p=0.26" "p=0.27" "p=0.319" "p=0.33" "p=0.37" "p=0.39" "p=0.40" "p=0.42" "p=0.427" "p=0.47" "p=0.49" "p=0.57" "p=0.59" "p=0.63" "p=0.70" "p=0.71" "p=0.8" "p=0.802" "p=0.83" "p=0.95" "p=1" "p=1.0" "p=1.0×10" "p=1.1×10" "p=1.3×10" "p=1.4" "p=1.4×10" "p=1.6" "p=1.6×10" "p=2.0×10" "p=2.1×10" "p=2.3×10" "p=2.5×10" "p=2.6×10" "p=2.7×10" "p=2.9×10" "p=3.2×10" "p=3.3×10" "p=3.6×10" "p=3.8×10" "p=3.9×10" "p=4.1×10" "p=4.6×10" "p=4.9×10" "p=5.3×10" "p=5.9×10" "p=6.7×10" "p=6×10" "p=7.5×10" "pA" "pAB240" "pAKT" "pAKT1" "pANCA" "pAP1-SEAP" "pAR-binding" "pATM" "pAb1801" "pAb421" "pAkt1" "pBABE-E2F1" "pBABE-E2F1-3" "pBabe" "pBabe-puro" "pCAG-myc-treated" "pCDNA-ING4" "pCEP4" "pCMV" "pCMV-5" "pCMV-Flag-MSH2" "pCR" "pCRKL" "pCdk5" "pChk1" "pDNA" "pDNA-PK" "pEBG" "pEF06R" "pEGFP-C1" "pEGFP-N1-p53" "pEGFP-Polκ" "pEGFP-hGLI1" "pEGFR" "pERK" "pERK1" "pERK5" "pEZ-AMO1" "pEZ-MT01" "pEZ-MT01-derived" "pF" "pFPV25.1" "pF±0.5" "pG68" "pGL-2" "pGL2-Bim-Basic" "pGL2-basic" "pGL3-208" "pGL3-275" "pGL3-Basic" "pGL3-basic" "pGL3-promoter" "pGL3M" "pGL3M-ROCK1-3" "pGL3–E2F1-3" "pGSK3β" "pH" "pHDAC2" "pINDUCER-DUSP4" "pJAK2" "pJak1" "pJak2" "pKAP-1" "pKIT" "pLEX-STAT3α" "pLEX-STAT3β" "pLL3.7-GFP" "pLL3.7-WT1" "pLL3.7-WT1-shRNA" "pLRP" "pLRP-ICD" "pMADD" "pMIR-GRB2mt" "pMIR-TGFBR2" "pMLC" "pMMP3" "pMSCV" "pMSCV-Cdk6-puro" "pMSCV-puro" "pMSCV-puro-based" "pN" "pNPM1" "pPAK1" "pPDGFRβ" "pPI" "pPI3-K" "pPKCα-p120" "pRBC" "pRBCs" "pRPA32" "pRTR" "pRTR-pri-miR-34a" "pS" "pS-P" "pS1126-P" "pS262" "pS32" "pS396" "pS473-AKT" "pS536" "pS647-DBN" "pS647-Drebrin" "pS6RP" "pSIN-Fluc" "pSTAT1" "pSTAT3" "pSTAT3α" "pSer146-Cdh1" "pSilencer2.1-U6-miR-203" "pSrc" "pSrc-416" "pSrc-Y416" "pStat" "pStat-3" "pSupFG1" "pSuper" "pSuper-27a" "pSuper-empty" "pT" "pT1-2" "pT180" "pT2-4" "pT3" "pT3-4" "pT4" "pT72" "pTNM" "pTP" "pTQ" "pTRPC" "pTRPC6p-luc1" "pTRPC6p-luc2" "pTopBP1" "pV" "pY1007" "pY1033" "pY1092" "pY1289" "pY239" "pY317" "pY705" "pack-year" "pack-years" "pair-wise" "paired-box" "paired-end" "palmitoyl" "pan-AKT" "pan-Bcl-2" "pan-HDAC" "pan-HDACi" "pan-PI3K" "pan-Ras" "pan-SIRT" "pan-WT" "pan-caspase" "pan-isoform" "pan-neurotrophin" "pan-phosphotyrosine" "pan-specific" "papillary-pattern" "par-4" "para-aminosalicyclic" "paracrine" "paralog" "paralogues" "paraproteins" "parenchyma" "parental-506" "parkin-Pp53" "parotid" "parthanatos" "pathogen-associated" "pathogen-recognition" "pathophysiology" "pathways" "pathways-homologous" "patient-tumor" "patients" "pattern-based" "pattern-recognition" "pcDNA-His-GLI1" "pcDNA1" "pcDNA3-Notch3-ICD" "pcDNA3-Par-4" "pcDNA3-THAP1" "pcDNA3.1" "pcDNA3.1-E2F1" "pcDNA3.1-EGFP" "pcDNA3.1-EGFP-NLK" "pcDNA3.1-HA-E2F1" "pcDNA3.1-c-Jun" "pcDNA3.1-entry" "pcDNA3.1-miR-124" "pcDNA3.1-myc-HisA" "pediatric-specific" "penetrance" "penton" "peptidase-4" "peptidase–activating" "peptide-1" "peptide-mimic" "peptidyl-prolyl" "per-allele" "per-test" "perception-linked" "peri-cancer" "peri-nuclear" "peri-operative" "peri-tumor" "peritoneum" "pes-ARKO–TRAMP" "pf11eei" "pf11ees" "pf12" "pf12ei" "pf12es" "pf21" "pf21s" "pf22s" "pfEMP-1" "phTH-3174-Luc" "phase-contrast" "phase-specific" "phenome" "phenome-associations" "phenome-wide" "phenotype-genotype" "phenyl" "phos-phatidylinositol-3,4,5-trisphosphate" "phosphatase-kinase" "phosphatidylbutanol-d" "phosphatidylinositol-3-kinase–like" "phosphatidylinositol-3-phosphate" "phospho-EGFR" "phospho-Ets2" "phospho-SFK" "phospho-Src" "phospho-c-Met" "phosphoAkt" "phosphoHER3" "phosphoHER4" "phosphoJAK" "phosphoTyr317" "phosphoatase-mediated" "phosphoinositide-3" "phosphoinositides" "phosphopeptide" "phosphopeptides" "phosphor-Igf1rβ" "phosphor-Ser" "phosphor-array" "phosphor-arrays" "phosphorylation-SFKs-Syk" "phosphosignals" "phosphosites" "phosphotyrosines" "phosphotyrosyl" "photo-converted" "photo-stability" "photo-switchable" "photo-switching" "photoacceptors" "photonuclear-specific" "photoproducts" "phyllodes" "physical-induction" "physician-referral" "pi3k1" "picoseconds" "pifithrin-α" "pixel" "pixels" "place-cell" "placebo-controlled" "plakophilin-1" "plasma-membrane-located" "plasmacytoid" "plasmids" "plasmin" "plasmon" "platinum-DNA" "platinum–DNA" "ploidy" "plug-weight" "pluripotency-associated" "pm" "pmaxGFP" "pmir-GLO" "pmir-GLO-ATG16L1-3" "point-mutated" "point-mutation" "pol-defective" "polarity-associated" "pola­rization" "polo-box" "polo-like" "poly-ADP" "poly-sumoylated" "poly-sumoylation" "poly-ubiquination" "polyADP" "polyI" "polycomb-repressive" "polymerase-1" "polymerase-η" "polymorphism" "polymorphisms" "polynucleotide" "polynucleotides" "polyprotein" "polyproteins" "polysomy" "polyubiquitine-chains" "pontine" "poorer" "poorly-differentiated" "populations" "pore-forming" "positive-control" "post-CPT" "post-GWAS" "post-IR" "post-MI" "post-PCN" "post-SCI" "post-UV" "post-adjuvant" "post-autopsy" "post-culturing" "post-erlotinib-treated" "post-exercise" "post-hoc" "post-implantation" "post-incubation" "post-infection" "post-injection" "post-injury" "post-integration" "post-intracarotid" "post-irradiation" "post-ischemic" "post-menopausal" "post-mitosis" "post-mitotic" "post-mortem" "post-natal" "post-nuclear" "post-operative" "post-partum" "post-pemetrexed" "post-pristane" "post-procedure" "post-radiotherapy" "post-replicative" "post-small" "post-sort" "post-synaptic" "post-transcription" "post-transcriptional" "post-transcriptionally" "post-transcriptomic" "post-transfection" "post-translation" "post-translational" "post-translationally" "post-treatment" "post-zygotic" "postmortem" "postpartum" "power=0.8" "pph21" "predicted-to-be-deleterious" "pressure-induced" "pretest" "pri" "pri-let-7" "pri-miR-122" "pri-miR-125b-1" "pri-miR-125b-2" "pri-miR-34a" "primary-NSCLC" "primitive-NSCLC" "prion-like" "prionoid" "priori" "pro-EMT" "pro-IL-1α" "pro-IL-1β" "pro-IL1β" "pro-LC3" "pro-angiogenic" "pro-apoptosis" "pro-arrest" "pro-carcinogenic" "pro-caspase-1" "pro-death" "pro-differentiation" "pro-fibrotic" "pro-growth" "pro-inflammation" "pro-inflammatory" "pro-inflammatory-secretory" "pro-invasive" "pro-ligand" "pro-ligands" "pro-metastatic" "pro-migratory" "pro-proliferative" "pro-protein" "pro-senescence" "pro-survival" "pro-tumor" "pro-tumorigenic" "pro-tumour" "pro-tumourigenic" "proMMP-9" "proband" "probands" "probeset" "probeset-by-probeset" "probesets" "procaspase-3" "progenitors" "progesterone-receptor-negative" "prognosis-associated" "programs" "prolactin-acidosis" "proliferator-activated" "proline-stretch" "promoter-associated" "promoter-distal" "promoter-reporter" "promoter-specific" "promyeloid" "proof-of-concept" "proof-of-principal" "proof-of-principle" "propria" "prostaglandins" "prostatectomy" "proteasome-mediated" "protein-1" "protein-10" "protein-2" "protein-DNA" "protein-coding" "protein-fusion" "protein-interaction" "protein-level" "protein-like" "protein-like-4" "protein-lipid" "protein-membrane" "protein-only" "proteins" "protein–DNA" "protein–drug" "protein–platinum" "proteome" "proteomes" "proteosome" "protocol-quality" "protofibrils" "proton-dependent" "proton-induced" "protooncogene" "protrusion–retraction" "proven" "proximity-based" "pro–α-factor" "pseudo-aggregates" "pseudo-hypertrophy" "pseudo-kinase" "pseudogenes" "pseudovirus" "psiCHECK2" "pull-down" "pull-downs" "purine-pyrimidine" "puro" "pyroglutamine" "p " "p = 0.001" "p = 0.0012" "p = 0.0013" "p = 0.002" "p = 0.003" "p = 0.004" "p = 0.006" "p = 0.007" "p = 0.008" "p = 0.009" "p = 0.01" "p = 0.022" "p = 0.029" "p = 0.03" "p = 0.04" "p = 0.042" "p = 0.068" "p≤0.05" "qBiomarker" "qChIP" "qPCR" "quality-controlled" "quantile-quantile" "quasi-insufficiency" "quinazolin-6-yl" "quinone oxidoreductase" "quinoxaline" "r2" "r2=0.23" "r=-0.542" "r=-0.556" "r=-0.625" "r=-0.633" "r=-0.769" "r=0.043" "r=0.235" "r=0.237" "r=0.249" "r=0.254" "r=0.260" "r=0.264" "r=0.268" "r=0.284" "r=0.300" "r=0.357" "r=0.380" "r=0.410" "r=0.450" "r=0.480" "r=0.513" "r=0.517" "r=0.520" "r=0.525" "r=0.532" "r=0.544" "r=0.547" "r=0.601" "r=0.606" "r=0.695" "r=0.707" "rASB10" "rASB10v3" "rIL-12" "rIL-27" "rIL-4" "rIL-6" "rIL-6-stimulated" "rQNestin34.5" "rTg4510" "rVista" "rVpr" "race-based" "race-specific" "radiation-induced" "radiation-mediated" "radiation-stimulated" "radiation-treated" "radio-HPLC" "radio-resistance" "radio-therapeutic" "radio-therapy" "radioresistance" "radioresistant" "radiosurgery" "radiotracer" "random-effect" "random-effects" "rank-sum" "rapalog" "rapalogs" "rapalogues" "rare-cutting" "rarer" "ratio=1.90" "ratio=2.34" "rationally-designed" "ratio≥2" "re-ChIP" "re-ChIPed" "re-added" "re-addition" "re-administration" "re-analyzed" "re-annealing" "re-attach" "re-biopsied" "re-biopsy" "re-challenged" "re-characterization" "re-consider" "re-constituted" "re-counted" "re-distributed" "re-distributing" "re-distribution" "re-engineering" "re-enter" "re-entry" "re-establish" "re-establishment" "re-examine" "re-examined" "re-express" "re-expressed" "re-expressing" "re-expression" "re-fashioned" "re-feeding" "re-grow" "re-growth" "re-incubated" "re-initiate" "re-internalized" "re-introduction" "re-localization" "re-opened" "re-organisation" "re-organization" "re-plated" "re-quantified" "re-sensitize" "re-stimulation" "re-synthesis" "re-tested" "re-treatment" "re-uptaking" "re-using" "reChIP" "reaction-restriction" "reaction–restriction" "read-out" "readout" "readouts" "receptor-2" "receptor-Fc" "receptor-chain" "receptor-ligand" "receptor-like" "receptor-proximal" "receptor-receptor" "receptor-α" "receptor-γ" "receptors-negative" "red-colored" "red-emitting" "red-labeled" "red-stained" "ref" "refractoriness" "refs" "region-leucine" "regs" "regulators" "regulatory-associated" "renilla" "replication-associated" "replication-blocking" "replication-born" "replicons" "reponse" "reporter-coding" "reporter-gene" "repressors" "repressors–including" "repressp15" "research-use" "residue–residue" "resistant-cellular" "respiratory-related" "responders" "resting-state" "resting-states" "retrovirus" "reuptake" "reverse-trancriptase" "reverse-transcripase" "rhLOXL2" "rhodamine-phalloidin" "ribophorin" "ribose" "ribose-5-phosphate" "ring-like" "risk-associated" "risk-stratification" "risk-stratify" "rod-like" "rotarod" "round-like" "rs1001581" "rs1005346" "rs1006737" "rs1018119" "rs10306135" "rs1034528" "rs10463316" "rs10497968" "rs10506328" "rs10860757" "rs10914144" "rs11065987" "rs11077947" "rs11238349" "rs11249433" "rs11255458" "rs113420705" "rs1136201" "rs1137070" "rs1155865" "rs115939516" "rs11602954" "rs11658698" "rs1198588" "rs12089041" "rs12146808" "rs12190287" "rs12190287-G" "rs12190827" "rs12192087" "rs12192087-C" "rs12212067" "rs12450046" "rs12524865" "rs12526453" "rs12602885" "rs12680762" "rs12845396" "rs13190932" "rs13190932_A + " "rs13190932_G" "rs13190932_G " "rs13196377" "rs13196377_A + " "rs13196377_G" "rs13196377_G " "rs13210247" "rs13210247_A" "rs13210247_G" "rs1333049" "rs13538" "rs1354034" "rs1382566" "rs143181039" "rs1462872" "rs1471384" "rs1522813" "rs152524" "rs1566819" "rs1596776" "rs16260" "rs16430" "rs1668873" "rs16847082" "rs16847416" "rs16905644" "rs17036508" "rs17099156" "rs17408757" "rs1745837" "rs17586365" "rs17691888" "rs1800954" "rs1801200" "rs1810132" "rs182123615" "rs1836721" "rs1846522" "rs1883965" "rs1887582" "rs1902023" "rs1946816" "rs1960669" "rs1978873" "rs1982346" "rs20417" "rs20424" "rs2075112" "rs2077647" "rs2079147" "rs2180748" "rs2233678" "rs2233679" "rs2233682" "rs2234693" "rs2237570" "rs2247128" "rs2268641" "rs2274223" "rs2285332" "rs2290257" "rs2295080" "rs240943" "rs2436389" "rs250092" "rs250108" "rs2536" "rs25405" "rs25406" "rs25487" "rs2628476" "rs265155" "rs2736340" "rs2736340-located" "rs2745557" "rs28362491" "rs28493229" "rs2943641" "rs2943641T-allele" "rs2950390" "rs2981582" "rs308379" "rs308382" "rs308435" "rs3087386" "rs3184504" "rs3217989" "rs334558" "rs334558 " "rs33980500" "rs33980500_T" "rs33980500_T " "rs342240" "rs35220450" "rs35682" "rs35683" "rs36228499" "rs3729558" "rs3730668" "rs3755557" "rs3755557 " "rs3755557–rs334558" "rs3789587" "rs3792136" "rs3806317" "rs381299" "rs3819299" "rs3842787" "rs385893" "rs4006531" "rs4244285" "rs4252596" "rs4379723" "rs4481204" "rs458017" "rs462779" "rs465646" "rs4680" "rs4730751" "rs4746554" "rs4796793" "rs4821877" "rs4895441" "rs4912868" "rs4912876" "rs4969170" "rs4977574" "rs5029748" "rs5030980" "rs5744533" "rs5744533-rs5744724" "rs5744720" "rs5744724" "rs6001512" "rs6065" "rs6314" "rs6475606" "rs6478565" "rs653178" "rs6534365" "rs6538998" "rs6546857" "rs6895139" "rs6941583" "rs6954351" "rs6993775" "rs6995402" "rs7101" "rs712829" "rs712830" "rs71372224" "rs7149242" "rs7216812" "rs72689236" "rs7308665" "rs739496" "rs749924" "rs7543272" "rs7700205" "rs7768030" "rs78190160" "rs7961894" "rs8074277" "rs8305" "rs845552" "rs869190" "rs879500" "rs912127" "rs9324889" "rs9349379" "rs9399137" "rs9622978" "rs9660992" "rs9788973" "rs9900280" "rythroid" "s00403-013-1407-9" "s13402-013-0143-7" "s6" "sCD40L" "saline-treated" "salt-and-pepper" "salt-bridge" "same-patient" "sapiens" "scatterplot" "schute" "score≤7" "score≥7" "scorpion-amplified" "scratch-wound" "se" "sec12-4" "sec2-41" "sec4-8" "second-generation" "second-line" "second-most-common" "second-passage" "second-site" "second-wave" "secondaries" "seed-sequence-dependent" "seeding-nucleation" "seizure-like" "selectinand" "self-administration" "self-aggregation" "self-assembly" "self-associate" "self-association" "self-cannibalization" "self-cleavage" "self-cleavages" "self-defense" "self-digestion" "self-duplication" "self-interaction" "self-limited" "self-multimerize" "self-oligomerizes" "self-peptide-MHC-I" "self-reactive" "self-regulated" "self-renew" "self-renewal" "self-renewal-related" "self-reported" "self-sufficiency" "self-tolerance" "self-tolerant" "self-ubiquitination" "semi" "semi-quantitative" "semi-solid" "senescence-associated-β-galactosidase" "sensitizers" "sepharose-Ac-TDG-peptide" "seq" "sequelae" "sequence-based" "sequence-independent" "sequence-specific" "sequestome1" "serine-threnine" "serines" "serosa" "set-point" "set-up" "several-micro-second" "several-year" "severely-affected" "sex-associated" "sex-differences" "sex-linked" "sex-specific" "sh-Amot" "sh-E6" "sh177" "shApi5" "shCCAR1" "shCTL" "shCdh1-treated" "shCont" "shControl" "shCtrl" "shDUSP4" "shEphA2" "shHbo1-4" "shHbo1-5" "shHbo1-5R" "shKIT" "shNC" "shNS" "shNT" "shRIP" "shRIP-1-L11" "shRIP1" "shRIP1-L11" "shRNA" "shRNA-empty" "shRNA1" "shRNAs" "shROCK1" "shROCK1#1" "shROCK1-#1" "shRPN" "shRPN2-UTR" "shRPN2-site2" "shRSK4" "shRSK4-GRC-1" "shSAFB1" "shSCR" "shSTAT3" "shTAZ" "shTRAF6" "shUNG" "shYAP" "sham-treatment" "shape-induced" "sheet-like" "shock-induced" "short-in" "short-patch" "short-range" "short-term" "shut-off" "shβ-TRCP" "si-p53-1" "si-p53-2" "si3098" "si471" "siAR" "siApi5" "siCON" "siCONTROL" "siCont" "siDUSP4" "siE2F1" "siE2F6" "siEGFR" "siFBXL17" "siGRB2" "siGRB2-1" "siGRB2-2" "siGRB2s" "siKPNA2" "siKPNA2#1" "siKPNA2#1cells" "siKPNA2#2" "siLSD#1" "siLSD#2" "siMBNL1-Ex5" "siMMP3" "siMSH2" "siNotch1" "siNotch2" "siNotch3" "siPARG" "siPP6-07" "siPP6-08" "siPP6-transfected" "siPTEN" "siRNA" "siRNA+pcDNA3.1+Myc" "siRNA-1" "siRNA-2" "siRNA-2-treated" "siRNA-Neg" "siRNA-RB" "siRNAs" "siROCK" "siROCK1-#2" "siROCK1-#3" "siRPL11" "siRPL23" "siRPL29" "siRPL30" "siRPL37" "siRPL5" "siRPS14" "siRPS15" "siRPS20" "siRPS6" "siSTAT3" "siTiam1" "sib-pair" "sibling-control" "side-by-side" "side-effect" "side-population" "sidechain" "signal-to-background" "signaling-driven" "signaling-to-protrusion" "signed-rank" "silencing-mediated" "silico" "simpler" "simplest" "single-base" "single-break" "single-cell" "single-cell-based" "single-dose" "single-drug" "single-gene" "single-locus" "single-marker" "single-mutant" "single-nucleotide" "single-regimen" "single-strand" "single-target" "singleEts2" "sino" "sino-nasal" "sirtuin" "sit4" "site-PCR" "site-specific" "sites" "situ" "sixty-five" "siβ-TRCP" "slow-infusion" "slow-moving" "slow-release" "slower-migrating" "slowly-progressive" "smLRP1" "small-angle" "small-cell" "small-hairpin" "small-hairpin-RNA" "small-interfering" "small-interfering-RNA" "small-molecule" "small-vessel" "smokers" "snMcl1" "snc2" "snc2-M2" "snc2-V39M42A" "snoRNA" "socio-economic" "sodium-induced" "soft-agar" "soft-tissue" "solid-predominant" "solute" "solutes" "spacer" "spacers" "spatio" "spatio-microenvironmental" "spatio-temporal" "spec-trometry" "specific-inhibition" "speck-like" "sphere-formation" "sphere-like" "spheroid-like" "sphingosine" "spike-like" "spiked-in" "spina" "spindle-like" "spindle-shape" "spinning-disk" "splice-site" "spliced-in" "spliceopathy" "spn-A" "spn-B" "spn-C" "spn-D" "spongiform" "spot-like" "squamous-cell" "square-discriminant" "srGAP" "srGAP1-dependent" "srGAP1-depleted" "srGAP1-mediated" "srGAPs" "stable-isotope" "stainings" "stand-alone" "start-sites" "starved-cells" "steady-state" "stem-cell" "stem-cell-based" "stem-cells" "stem-like" "stem-loop" "stemness" "step-by-step" "step-wise" "stepwise" "steroid-resistant" "strand-specific" "streptavidin-flag-S" "streptavidin–biotin" "stress-activated" "stress-dependent" "stress-induced" "stress-inducible" "stress-mediated" "stress-specific" "stressful" "stressors" "stress–activated" "stress–responsive" "striations" "stroma-dominant" "stroma-poor" "stroma-rich" "stromal-derived" "stromal-epithelial" "stromal-expressed" "stromal-specific" "stromal–epithelial" "stromelysin" "structure-function" "structure-specific" "structure-wise" "structure–function" "study-atherosclerosis" "study-collective" "sub-G1" "sub-analysis" "sub-cellular" "sub-class" "sub-clinical" "sub-complex" "sub-complexes" "sub-confluent" "sub-cortical" "sub-cutaneous" "sub-domains" "sub-endothelial" "sub-epithelial" "sub-family" "sub-group" "sub-kilobase" "sub-lethal" "sub-line" "sub-lines" "sub-localization" "sub-pathways" "sub-population" "sub-region" "sub-regions" "sub-section" "sub-set" "sub-stoichiometric" "sub-threshold" "sub-toxic" "sub-types" "sub-zero" "subG" "subG1" "subclass" "subclasses" "subcomplexes" "subdiploid" "sublines" "subphenotypes" "subset" "subsets" "substrate-1" "substrate-MADD" "substrates" "substratesp70" "subtilisin" "subtilisin-like" "subtype" "succinate" "succinimidylpropionate" "sugar-phosphate" "sulfonate" "sun-exposure" "super-antigens" "super-repressor" "super-shift" "super-shifted" "supernatant" "supernatants" "suppressor-like" "suppressor-of-fused" "suppressp70" "supra-lethal" "sural" "survival-concentration" "survive-to" "swa2" "switch-like" "switching-off" "symmetry-related" "synapse" "synapses" "synthesis-dependent" "t5" "tARPC" "tARPCs" "tagSNP" "tagSNPs" "tail-vein" "tamoxifin" "tandem-affinity" "target-cell" "target-gene" "tau–microtubule" "tdTomato" "telomerase-accessory" "telomerase-associated" "telomerase-independent" "temperature-sensitive" "template-containing" "temporal-specific" "ten-eleven" "tension-dependent" "terminal-deoxynucleotidyl-transferase" "tert-butanol" "test-threshold" "tet-off" "tet-transactivator" "tetBim-ECFP-Mcl1L" "tetBim-EYFP-Mcl1L" "tetNoxa-ECFP-Mcl1L" "tetNoxa-EYFP-Mcl1L" "thanp53" "thatp27" "the-765" "theFoxO3a" "theGrm1" "theRosa26" "thep27" "therapy-based" "therapy-naïve" "therapy-resistance" "therapy-resistant" "therapy-resistant-MCL" "therapy-treated" "thio-phosphoramidate" "thioflavin" "third-highest" "third-line" "third-most-changed" "thirty-nine" "three-arm" "three-component" "three-dimensional" "three-factor" "three-gene" "three-pathway" "three-quarter-sites" "three-stranded" "three-way" "threoine" "thrombocythemia" "through-out" "thymine–thymine" "thymocytes" "time-course" "time-dependant" "time-lapse" "time-point" "time-points" "time-to-progression" "time-to-recurrence" "tissue-dependant" "tissue-specific" "titer" "titers" "titres" "toEx5-MBNL1" "toTRAF6" "toll-like" "tomograms" "top-down" "top-right" "top53" "topology" "toses" "tosis" "total-JAK2" "toto" "toxicants" "toxicities" "trait-associated" "trans-bronchial" "trans-dominant" "trans-genes" "trans-membrane" "trans-phosphorlyation" "transcript-inductions" "transcription-3" "transcription-5a" "transcription-5b" "transcription-PCR" "transcription-competent" "transcription-quantitative" "transcriptome" "transcriptome-wide" "transcriptomes" "transcripts" "transducer" "transfectedHomer1" "transfections" "transferase-mediated" "transgenes" "transgenic-immunodeficient" "transit-amplifying" "transitional-type" "translation-stop" "translocase-1" "transplantedp53" "transwell" "transwells" "treatment-naive" "treatment-naïve" "treatments" "triangular-shaped" "triphosphate" "triple-ChIP" "triple-negative" "trisphosphate" "triton-insoluble" "trypsin-like" "tryptase-positive" "ts" "tsO45" "tubal" "tubo-ovarian" "tubule" "tubules" "tubulo-interstitial" "tumor-angiogenesis" "tumor-like" "tumor-promotive" "tumor-selectivity" "tumor-suppressive" "tumor-to-background" "tumor-to-blood" "tumor-to-muscle" "tumor-to-vector" "tumors" "tumour-associated" "tumour-derived" "tumour-growth" "tumour-node-metastasis" "tumour-propagation" "tumour-suppressive" "tumour-suppressor" "turn-over" "twenty-two" "two-SNP" "two-ended" "two-hit" "two-hour" "two-hybrid" "two-member" "two-pronged" "two-step" "two-tailed" "two-thirds" "two-tiered" "two-to-four" "two-way" "two-year" "twofold-higher" "type-1" "type-2-diabetes" "tyrosine-phosphorylation-dependent" "tyrosine-to-phenylalanine" "uHL-60" "ubiquitin-and" "ubiquitin-chain" "ubiquitination-defective" "ubiquitine" "ubiquitine-ligase" "ubiquitin–proteasome-mediated" "ubiquity-lation" "ug" "ultrastructure" "ultrathin" "ultraviolet-induced" "un" "un-surgery" "unarmed-ATC" "unclassified-IBD" "uncoupler" "under-powered" "under-replicated" "under-ridding" "undergoes" "undergone" "undertaken" "uni" "uni-directional" "univariate" "unresponsiveness" "up-to-date" "upto" "uracil-DNA" "urea" "users" "usingHomer1" "uteri" "uveal" "v-Ki-ras2" "v-erb-b2" "v-ets" "v-ki-ras2" "v1" "v2.2" "v3" "vIII" "values" "variants" "vascular-like" "veh" "vehicle-treated" "vera" "vesicle-associated" "vessels" "villi" "villus" "vimentin-null" "vinclocolin" "viral-induced" "viral-infected" "virally-transduced" "viremia" "virus-1" "virus-host" "virus-like" "vitro" "vivo" "vorinostat-epirubicin" "vorinsotat" "voxel" "vs.1" "vs.12" "vs.ErbB2" "vs.Ets2" "vs.PyMT" "vt" "vulgaris" "wavelength-dependent" "web-based" "websites" "well-adapted" "well-annotated" "well-being" "well-characterised" "well-circumscribed" "well-conserved" "well-coordinated" "well-defined" "well-demarcated" "well-designed" "well-differentiated" "well-documented" "well-formed" "well-matched" "well-powered" "well-recognized" "well-regulated" "well-resolved" "well-separated" "well-studied" "well-tolerated" "well-written" "western-blot" "western-blots" "western-blotting" "whole-brain" "whole-cell" "whole-exome" "whole-genome" "whole-tumor" "widefield" "wildtype-tumors" "withEts2" "withPARP1" "withdrawn" "within-family" "within-run" "wk" "workers" "workflow" "world-wide" "written" "wtMADD" "wtSTAT3" "wtp53" "x-E-x-x-aromatic" "x-Q-x-x-D" "x-ray" "x100" "xMAP" "xenotransplant" "xenotransplants" "y-axis" "yap1801" "yap1802" "year-old" "yet-to-be-identified" "z-VAD" "z-guggulsterone" "z-stacks" "zeta" "zinc-dependent" "zinc-mediated" "zipper-interacting" "zipper-like" "zona" "zsGreen" "zymography" "× 10" "×1" "×10" "×100" "×3" "×FLAG" "×His" "×MOG" "× 10" "× 10 " "× 10" "× 100" "Δ1" "Δ1-110" "Δ175–244" "Δ1–75" "Δ23-111" "Δ3" "Δ349" "Δ369" "Δ393–414" "Δ4" "Δ40p53" "Δ40p53-dependent" "Δ40p53-encoding" "Δ40p53-infected" "Δ40p53-transduced" "Δ40p53V" "Δ40p53V-transduced" "Δ431–490" "Δ628–630" "Δ746-750" "Δ8" "ΔATF3" "ΔC" "ΔC-box-Cdh1" "ΔC12" "ΔCREB" "ΔCore" "ΔCt" "ΔCtBP" "ΔCt " "ΔD" "ΔDBD2" "ΔE9" "ΔEF1" "ΔEGFR" "ΔEx3" "ΔEx5-MBNL" "ΔEx5-MBNL1" "ΔF" "ΔFHA" "ΔFizzy-Cdh1" "ΔG" "ΔKD" "ΔL" "ΔMADSMEF2" "ΔN" "ΔNES" "ΔNp73" "ΔOB" "ΔRING" "ΔS1" "ΔSAM" "ΔTB" "Δbromo" "Δcysteine" "Δcysteine-rich" "Δp85" "Δsit4" "ΔΔCt" "ΔΔCt " "ΔΨ" "ΔΨm" "ΨKX" "ΨKXE" "α--like" "α-1" "α-2" "α-6" "α-ARNT1" "α-Ac" "α-AhR" "α-BACH1" "α-EGFP" "α-ERα" "α-GFP" "α-Mst2" "α-amino" "α-and" "α-aquaporin-1" "α-cell" "α-cells" "α-globin-like" "α-helical" "α-helices" "α-ketoacid" "α-lactalbumin" "α-phalloidin" "α-receptor" "α-related" "α-subunits" "α0" "α2β1" "α3β1" "α4β1" "α5-integrin" "α5PPAA" "α5WT" "α6β4" "α7" "α=5×10" "αC" "αCD28" "αCD3" "αCDK4" "αCDK6" "αD" "αD–αE" "αE" "αERKO" "αG" "αV" "αcyclinD3" "αp27" "ανβ3" "β-2" "β-Lap" "β-Lap-induced" "β-Lap-treated" "β-Lapachone" "β-Lapachone-induced" "β-ME" "β-TRCP" "β-TRCP-dependent" "β-TRCP-depletion-mediated" "β-TRCP-mediated" "β-TRCP-recognizable" "β-TRCP1" "β-TRCP2" "β-activated" "β-catenin-non-response" "β-catenin-response" "β-chemotactic" "β-elimination" "β-fodrin" "β-globin-like" "β-lap" "β-lap-exposed" "β-lap-induced" "β-lap-resistant" "β-lap-treated" "β-lapachone" "β-lapachone-induced" "β-mercapoethanol" "β-oxidation" "β-peptide" "β-sheet" "β-sheet-rich" "β-sheets" "β-sodium" "β-subunit" "β-subunits" "β-transducing" "β1-6" "β1-6-branching" "β1-integrins" "β3" "β3-null" "β4–β7" "β6" "β7–β8" "β8" "βERKO" "βI" "βII" "βc" "βic" "β–activated" "γ-GCS" "γ-GCSh" "γ-globins" "γ-glutamyl-cysteine" "γ-irradiated" "γ-irradiation" "γ-phosphate" "γ-radiation" "γ-rays" "γ2" "γhistone2AX" "γδ-intergenic" "δ-cells" "δ-elimination" "ε-amino" "ε-dependent" "εC" "ζ-zeta" "ι-involved" "ι-mediated" "ι-related" "κB-luc" "μg" "μg " "μl" "μmol" "μmoles" "π-cation" "σ1" "χ2" "χ²" "ψ-K-x-D" "ψKxExxSP" "ϕ-x" "ϵRI" "”m" "€overruled" "↑G1" "∆11" "∆3" "∆C-TAD" "∆GAP" "∆IH" "∆N-TAD" "∆PAS" "∆bHLH" "∆basic" "−141" "−200b" "−429" "−β" "≧31.2%" "〈2" "fiber" "(p"))
7c4859a3c17385b0d942624dacb69804d102137bb5c6f6a2e12429aa1517f148
patricoferris/meio
main.ml
open Eio let spawn ~clock min max = Switch.run @@ fun sw -> for i = min to max do Fiber.fork ~sw (fun () -> Time.sleep clock (float_of_int i)); Time.sleep clock (float_of_int (max - i)) done Based on the Tokio Console example application let main clock = let p, r = Promise.create () in Switch.run @@ fun sw -> (* A long running task *) Fiber.fork ~sw (fun () -> traceln "Waiting"; Promise.await p; traceln "Done"); Fiber.both (fun () -> spawn ~clock 5 10) (fun () -> spawn ~clock 10 30); Promise.resolve r () let () = Eio_main.run @@ fun env -> Ctf.with_tracing @@ fun () -> let clock = Stdenv.clock env in main clock
null
https://raw.githubusercontent.com/patricoferris/meio/635b3dcaecd84ffacb2b6f7d2990cb668d61d5bb/example/main.ml
ocaml
A long running task
open Eio let spawn ~clock min max = Switch.run @@ fun sw -> for i = min to max do Fiber.fork ~sw (fun () -> Time.sleep clock (float_of_int i)); Time.sleep clock (float_of_int (max - i)) done Based on the Tokio Console example application let main clock = let p, r = Promise.create () in Switch.run @@ fun sw -> Fiber.fork ~sw (fun () -> traceln "Waiting"; Promise.await p; traceln "Done"); Fiber.both (fun () -> spawn ~clock 5 10) (fun () -> spawn ~clock 10 30); Promise.resolve r () let () = Eio_main.run @@ fun env -> Ctf.with_tracing @@ fun () -> let clock = Stdenv.clock env in main clock
ed3d466a642f45a3c2d7ce084f171aa37fb3ac936c8b692a1cf137e226f4db0a
MarcWeber/hasktags
testcase4.hs
-- to be found logM -- to be found debugM -- to be found infoM -- to be found noticeM -- to be found warningM -- to be found errorM -- to be found criticalM -- to be found alertM -- to be found emergencyM -- to be found traplogging to be found to be found getLogger -- to be found getRootLogger -- to be found rootLoggerName to be found to be found setHandlers -- to be found getLevel to be found setLevel -- to be found saveGlobalLogger -- to be found updateGlobalLogger {-# OPTIONS -fglasgow-exts #-} arch - tag : Logger main definition Copyright ( C ) 2004 - 2006 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 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 Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2004-2006 John Goerzen <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} | Module : System . Log . Logger Copyright : Copyright ( C ) 2004 - 2006 License : GNU LGPL , version 2.1 or above Maintainer : < > Stability : provisional Portability : portable Haskell Logging Framework , Primary Interface Written by , jgoerzen\@complete.org Welcome to the error and information logging system for Haskell . This system is patterned after Python\ 's @logging@ module , < -logging.html > and some of the documentation here was based on documentation there . To log a message , you perform operations on ' Logger 's . Each ' Logger ' has a name , and they are arranged hierarchically . Periods serve as separators . Therefore , a ' Logger ' named \"foo\ " is the parent of loggers \"foo.printing\ " , \"foo.html\ " , and \"foo.io\ " . These names can be anything you want . They 're used to indicate the area of an application or library in which a logged message originates . Later you will see how you can use this concept to fine - tune logging behaviors based on specific application areas . You can also tune logging behaviors based upon how important a message is . Each message you log will have an importance associated with it . The different importance levels are given by the ' Priority ' type . I 've also provided some convenient functions that correspond to these importance levels : ' debugM ' through ' emergencyM ' log messages with the specified importance . Now , an importance level ( or ' Priority ' ) is associated not just with a particular message but also with a ' Logger ' . If the ' Priority ' of a given log message is lower than the ' Priority ' configured in the ' Logger ' , that message is ignored . This way , you can globally control how verbose your logging output is . Now , let 's follow what happens under the hood when you log a message . We 'll assume for the moment that you are logging something with a high enough ' Priority ' that it passes the test in your ' Logger ' . In your code , you 'll call ' logM ' or something like ' debugM ' to log the message . Your ' Logger ' decides to accept the message . What next ? Well , we also have a notion of /handlers/ ( ' LogHandler 's , to be precise ) . A ' LogHandler ' is a thing that takes a message and sends it somewhere . That \"somewhere\ " may be your screen ( via standard error ) , your system 's logging infrastructure ( via syslog ) , a file , or other things . Each ' Logger ' can have zero or more ' LogHandler 's associated with it . When your ' Logger ' has a message to log , it passes it to every ' LogHandler ' it knows of to process . What 's more , it is also passed to /all handlers of all ancestors of the Logger/ , regardless of whether those ' Logger 's would normally have passed on the message . To give you one extra little knob to turn , ' LogHandler 's can also have importance levels ( ' Priority ' ) associated with them in the same way that ' Logger 's do . They act just like the ' Priority ' value in the ' Logger 's -- as a filter . It 's useful , for instance , to make sure that under no circumstances will a mere ' DEBUG ' message show up in your syslog . There are three built - in handlers given in two built - in modules : " System . Log . Handler . Simple " and " System . Log . Handler . Syslog " . There is a special logger known as the /root logger/ that sits at the top of the logger hierarchy . It is always present , and handlers attached there will be called for every message . You can use ' getRootLogger ' to get it or ' rootLoggerName ' to work with it by name . Here 's an example to illustrate some of these concepts : > import System . Log . Logger > import System . Log . Handler . Syslog > > -- By default , all messages of level WARNING and above are sent to stderr . > -- Everything else is ignored . > > -- " MyApp . Component " is an arbitrary string ; you can tune > -- logging behavior based on it later . > main = do > debugM " MyApp . Component " " This is a debug message -- never to be seen " > warningM " MyApp . Component2 " " Something Bad is about to happen . " > > -- Copy everything to syslog from here on out . > s < - openlog " SyslogStuff " [ PID ] USER DEBUG > updateGlobalLogger rootLoggerName ( s ) > > errorM " MyApp . Component " " This is going to stderr and syslog . " > > -- Now we 'd like to see everything from BuggyComponent > -- at DEBUG or higher go to syslog and stderr . > -- Also , we 'd like to still ignore things less than > -- WARNING in other areas . > -- > -- So , we adjust the Logger for MyApp . Component . > > updateGlobalLogger " MyApp . BuggyComponent " > ( setLevel DEBUG ) > > -- This message will go to syslog and stderr > debugM " MyApp . BuggyComponent " " This buggy component is buggy " > > -- This message will go to syslog and stderr too . > warningM " MyApp . BuggyComponent " " Still Buggy " > > -- This message goes nowhere . > debugM " MyApp . WorkingComponent " " Hello " Module : System.Log.Logger Copyright : Copyright (C) 2004-2006 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <> Stability : provisional Portability: portable Haskell Logging Framework, Primary Interface Written by John Goerzen, jgoerzen\@complete.org Welcome to the error and information logging system for Haskell. This system is patterned after Python\'s @logging@ module, <-logging.html> and some of the documentation here was based on documentation there. To log a message, you perform operations on 'Logger's. Each 'Logger' has a name, and they are arranged hierarchically. Periods serve as separators. Therefore, a 'Logger' named \"foo\" is the parent of loggers \"foo.printing\", \"foo.html\", and \"foo.io\". These names can be anything you want. They're used to indicate the area of an application or library in which a logged message originates. Later you will see how you can use this concept to fine-tune logging behaviors based on specific application areas. You can also tune logging behaviors based upon how important a message is. Each message you log will have an importance associated with it. The different importance levels are given by the 'Priority' type. I've also provided some convenient functions that correspond to these importance levels: 'debugM' through 'emergencyM' log messages with the specified importance. Now, an importance level (or 'Priority') is associated not just with a particular message but also with a 'Logger'. If the 'Priority' of a given log message is lower than the 'Priority' configured in the 'Logger', that message is ignored. This way, you can globally control how verbose your logging output is. Now, let's follow what happens under the hood when you log a message. We'll assume for the moment that you are logging something with a high enough 'Priority' that it passes the test in your 'Logger'. In your code, you'll call 'logM' or something like 'debugM' to log the message. Your 'Logger' decides to accept the message. What next? Well, we also have a notion of /handlers/ ('LogHandler's, to be precise). A 'LogHandler' is a thing that takes a message and sends it somewhere. That \"somewhere\" may be your screen (via standard error), your system's logging infrastructure (via syslog), a file, or other things. Each 'Logger' can have zero or more 'LogHandler's associated with it. When your 'Logger' has a message to log, it passes it to every 'LogHandler' it knows of to process. What's more, it is also passed to /all handlers of all ancestors of the Logger/, regardless of whether those 'Logger's would normally have passed on the message. To give you one extra little knob to turn, 'LogHandler's can also have importance levels ('Priority') associated with them in the same way that 'Logger's do. They act just like the 'Priority' value in the 'Logger's -- as a filter. It's useful, for instance, to make sure that under no circumstances will a mere 'DEBUG' message show up in your syslog. There are three built-in handlers given in two built-in modules: "System.Log.Handler.Simple" and "System.Log.Handler.Syslog". There is a special logger known as the /root logger/ that sits at the top of the logger hierarchy. It is always present, and handlers attached there will be called for every message. You can use 'getRootLogger' to get it or 'rootLoggerName' to work with it by name. Here's an example to illustrate some of these concepts: > import System.Log.Logger > import System.Log.Handler.Syslog > > -- By default, all messages of level WARNING and above are sent to stderr. > -- Everything else is ignored. > > -- "MyApp.Component" is an arbitrary string; you can tune > -- logging behavior based on it later. > main = do > debugM "MyApp.Component" "This is a debug message -- never to be seen" > warningM "MyApp.Component2" "Something Bad is about to happen." > > -- Copy everything to syslog from here on out. > s <- openlog "SyslogStuff" [PID] USER DEBUG > updateGlobalLogger rootLoggerName (addHandler s) > > errorM "MyApp.Component" "This is going to stderr and syslog." > > -- Now we'd like to see everything from BuggyComponent > -- at DEBUG or higher go to syslog and stderr. > -- Also, we'd like to still ignore things less than > -- WARNING in other areas. > -- > -- So, we adjust the Logger for MyApp.Component. > > updateGlobalLogger "MyApp.BuggyComponent" > (setLevel DEBUG) > > -- This message will go to syslog and stderr > debugM "MyApp.BuggyComponent" "This buggy component is buggy" > > -- This message will go to syslog and stderr too. > warningM "MyApp.BuggyComponent" "Still Buggy" > > -- This message goes nowhere. > debugM "MyApp.WorkingComponent" "Hello" -} module System.Log.Logger( -- * Basic Types Logger, -- ** Re-Exported from System.Log Priority(..), -- * Logging Messages -- ** Basic logM, -- ** Utility Functions -- These functions are wrappers for 'logM' to -- make your job easier. debugM, infoM, noticeM, warningM, errorM, criticalM, alertM, emergencyM, traplogging, -- ** Logging to a particular Logger by object logL, -- * Logger Manipulation | These functions help you work with loggers . There are some special things to be aware of . First of all , whenever you first access a given logger by name , it magically springs to life . It has a default ' Priority ' of ' DEBUG ' and an empty handler list -- which means that it will inherit whatever its parents do . special things to be aware of. First of all, whenever you first access a given logger by name, it magically springs to life. It has a default 'Priority' of 'DEBUG' and an empty handler list -- which means that it will inherit whatever its parents do. -} * * Finding \/ Creating Loggers getLogger, getRootLogger, rootLoggerName, -- ** Modifying Loggers | Keep in mind that " here is modification in the sense . We do not actually cause mutation in a specific ' Logger ' . Rather , we return you a new ' Logger ' object with the change applied . Also , please note that these functions will not have an effect on the global ' Logger ' hierarchy . You may use your new ' Logger 's locally , but other functions wo n't see the changes . To make a change global , you 'll need to use ' updateGlobalLogger ' or ' saveGlobalLogger ' . sense. We do not actually cause mutation in a specific 'Logger'. Rather, we return you a new 'Logger' object with the change applied. Also, please note that these functions will not have an effect on the global 'Logger' hierarchy. You may use your new 'Logger's locally, but other functions won't see the changes. To make a change global, you'll need to use 'updateGlobalLogger' or 'saveGlobalLogger'. -} addHandler, setHandlers, getLevel, setLevel, -- ** Saving Your Changes {- | These functions commit changes you've made to loggers to the global logger hierarchy. -} saveGlobalLogger, updateGlobalLogger ) where import System.Log import System.Log.Handler(LogHandler) import qualified System.Log.Handler(handle) import System.Log.Handler.Simple import System.IO import System.IO.Unsafe import Control.Concurrent.MVar import Data.List(map, isPrefixOf) import qualified Data.Map as Map import qualified Control.Exception import Control.Monad.Error --------------------------------------------------------------------------- -- Basic logger types --------------------------------------------------------------------------- data HandlerT = forall a. LogHandler a => HandlerT a data Logger = Logger { level :: Priority, handlers :: [HandlerT], name :: String} type LogTree = Map.Map String Logger {- | This is the base class for the various log handlers. They should all adhere to this class. -} --------------------------------------------------------------------------- Utilities --------------------------------------------------------------------------- -- | The name of the root logger, which is always defined and present -- on the system. rootLoggerName = "" | Placeholders created when a new logger must be created . This is used only for the root logger default for now , as all others crawl up the tree to find a sensible default . only for the root logger default for now, as all others crawl up the tree to find a sensible default. -} placeholder :: Logger placeholder = Logger {level = WARNING, handlers = [], name = ""} --------------------------------------------------------------------------- -- Logger Tree Storage --------------------------------------------------------------------------- | The log tree . Initialize it with a default root logger and ( FIXME ) a logger for MissingH itself . # NOINLINE logTree # logTree :: MVar LogTree -- note: only kick up tree if handled locally logTree = unsafePerformIO $ do h <- streamHandler stderr DEBUG newMVar (Map.singleton rootLoggerName (Logger {level = WARNING, name = "", handlers = [HandlerT h]})) {- | Given a name, return all components of it, starting from the root. Example return value: >["", "MissingH", "System.Cmd.Utils", "System.Cmd.Utils.pOpen"] -} componentsOfName :: String -> [String] componentsOfName name = let joinComp [] _ = [] joinComp (x:xs) [] = x : joinComp xs x joinComp (x:xs) accum = let newlevel = accum ++ "." ++ x in newlevel : joinComp xs newlevel in rootLoggerName : joinComp (split "." name) [] --------------------------------------------------------------------------- -- Logging With Location --------------------------------------------------------------------------- {- | Log a message using the given logger at a given priority. -} logM :: String -- ^ Name of the logger to use -> Priority -- ^ Priority of this message -> String -- ^ The log text itself -> IO () logM logname pri msg = do l <- getLogger logname logL l pri msg --------------------------------------------------------------------------- -- Utility functions --------------------------------------------------------------------------- {- | Log a message at 'DEBUG' priority -} debugM :: String -- ^ Logger name -> String -- ^ Log message -> IO () debugM s = logM s DEBUG {- | Log a message at 'INFO' priority -} infoM :: String -- ^ Logger name -> String -- ^ Log message -> IO () infoM s = logM s INFO {- | Log a message at 'NOTICE' priority -} noticeM :: String -- ^ Logger name -> String -- ^ Log message -> IO () noticeM s = logM s NOTICE {- | Log a message at 'WARNING' priority -} warningM :: String -- ^ Logger name -> String -- ^ Log message -> IO () warningM s = logM s WARNING {- | Log a message at 'ERROR' priority -} errorM :: String -- ^ Logger name -> String -- ^ Log message -> IO () errorM s = logM s ERROR {- | Log a message at 'CRITICAL' priority -} criticalM :: String -- ^ Logger name -> String -- ^ Log message -> IO () criticalM s = logM s CRITICAL {- | Log a message at 'ALERT' priority -} alertM :: String -- ^ Logger name -> String -- ^ Log message -> IO () alertM s = logM s ALERT {- | Log a message at 'EMERGENCY' priority -} emergencyM :: String -- ^ Logger name -> String -- ^ Log message -> IO () emergencyM s = logM s EMERGENCY --------------------------------------------------------------------------- Public Logger Interaction Support --------------------------------------------------------------------------- -- | Returns the logger for the given name. If no logger with that name -- exists, creates new loggers and any necessary parent loggers, with -- no connected handlers. getLogger :: String -> IO Logger getLogger lname = modifyMVar logTree $ \lt -> case Map.lookup lname lt of Just x -> return (lt, x) -- A logger exists; return it and leave tree Nothing -> do -- Add logger(s). Then call myself to retrieve it. let newlt = createLoggers (componentsOfName lname) lt result <- Map.lookup lname newlt return (newlt, result) where createLoggers :: [String] -> LogTree -> LogTree createLoggers [] lt = lt -- No names to add; return tree unmodified createLoggers (x:xs) lt = -- Add logger to tree if Map.member x lt then createLoggers xs lt else createLoggers xs (Map.insert x ((modellogger lt) {name=x}) lt) modellogger :: LogTree -> Logger -- the modellogger is what we use for adding new loggers modellogger lt = findmodellogger lt (reverse $ componentsOfName lname) findmodellogger _ [] = error "findmodellogger: root logger does not exist?!" findmodellogger lt (x:xs) = case Map.lookup x lt of Left (_::String) -> findmodellogger lt xs Right logger -> logger {handlers = []} -- | Returns the root logger. getRootLogger :: IO Logger getRootLogger = getLogger rootLoggerName -- | Log a message, assuming the current logger's level permits it. logL :: Logger -> Priority -> String -> IO () logL l pri msg = handle l (pri, msg) -- | Handle a log request. handle :: Logger -> LogRecord -> IO () handle l (pri, msg) = let parentHandlers [] = return [] parentHandlers name = let pname = (head . drop 1 . reverse . componentsOfName) name in do ( join " , " foo ) --putStrLn pname putStrLn " 1 " parent <- getLogger pname putStrLn " 2 " next <- parentHandlers pname putStrLn " 3 " return ((handlers parent) ++ next) in if pri >= (level l) then do ph <- parentHandlers (name l) sequence_ (handlerActions (ph ++ (handlers l)) (pri, msg) (name l)) else return () -- | Call a handler given a HandlerT. callHandler :: LogRecord -> String -> HandlerT -> IO () callHandler lr loggername ht = case ht of HandlerT x -> System.Log.Handler.handle x lr loggername -- | Generate IO actions for the handlers. handlerActions :: [HandlerT] -> LogRecord -> String -> [IO ()] handlerActions h lr loggername = map (callHandler lr loggername ) h -- | Add handler to 'Logger'. Returns a new 'Logger'. addHandler :: LogHandler a => a -> Logger -> Logger addHandler h l= l{handlers = (HandlerT h) : (handlers l)} -- | Set the 'Logger'\'s list of handlers to the list supplied. All existing handlers are removed first . setHandlers :: LogHandler a => [a] -> Logger -> Logger setHandlers hl l = l{handlers = map (\h -> HandlerT h) hl} -- | Returns the "level" of the logger. Items beneath this -- level will be ignored. getLevel :: Logger -> Priority getLevel l = level l -- | Sets the "level" of the 'Logger'. Returns a new -- 'Logger' object with the new level. setLevel :: Priority -> Logger -> Logger setLevel p l = l{level = p} -- | Updates the global record for the given logger to take into -- account any changes you may have made. saveGlobalLogger :: Logger -> IO () saveGlobalLogger l = modifyMVar_ logTree (\lt -> return $ Map.insert (name l) l lt) | Helps you make changes on the given logger . Takes a function that makes changes and writes those changes back to the global database . Here 's an example from above ( \"s\ " is a ' LogHandler ' ): > updateGlobalLogger " MyApp . BuggyComponent " > ( setLevel DEBUG . [ s ] ) that makes changes and writes those changes back to the global database. Here's an example from above (\"s\" is a 'LogHandler'): > updateGlobalLogger "MyApp.BuggyComponent" > (setLevel DEBUG . setHandlers [s]) -} updateGlobalLogger :: String -- ^ Logger name -> (Logger -> Logger) -- ^ Function to call -> IO () updateGlobalLogger ln func = do l <- getLogger ln saveGlobalLogger (func l) | Traps exceptions that may occur , logging them , then passing them on . Takes a logger name , priority , leading description text ( you can set it to @\"\"@ if you do n't want any ) , and action to run . Takes a logger name, priority, leading description text (you can set it to @\"\"@ if you don't want any), and action to run. -} traplogging :: String -- Logger name -> Priority -- Logging priority -> String -- Descriptive text to prepend to logged messages -> IO a -- Action to run -> IO a -- Return value traplogging logger priority desc action = let realdesc = case desc of "" -> "" x -> x ++ ": " handler e = do logM logger priority (realdesc ++ (show e)) Control.Exception.throw e -- Re-raise it in Control.Exception.catch action handler {- This function pulled in from MissingH to avoid a dep on it -} split :: Eq a => [a] -> [a] -> [[a]] split _ [] = [] split delim str = let (firstline, remainder) = breakList (isPrefixOf delim) str in firstline : case remainder of [] -> [] x -> if x == delim then [] : [] else split delim (drop (length delim) x) This function also pulled from MissingH breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) This function also pulled from MissingH spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list) where (ys,zs) = spanList func xs
null
https://raw.githubusercontent.com/MarcWeber/hasktags/65bcbecb695f0d2f31c2436958480535b8193b6c/testcases/testcase4.hs
haskell
to be found logM to be found debugM to be found infoM to be found noticeM to be found warningM to be found errorM to be found criticalM to be found alertM to be found emergencyM to be found traplogging to be found getRootLogger to be found rootLoggerName to be found getLevel to be found saveGlobalLogger to be found updateGlobalLogger # OPTIONS -fglasgow-exts # as a filter . It 's useful , for instance , to make sure that By default , all messages of level WARNING and above are sent to stderr . Everything else is ignored . " MyApp . Component " is an arbitrary string ; you can tune logging behavior based on it later . Copy everything to syslog from here on out . Now we 'd like to see everything from BuggyComponent at DEBUG or higher go to syslog and stderr . Also , we 'd like to still ignore things less than WARNING in other areas . So , we adjust the Logger for MyApp . Component . This message will go to syslog and stderr This message will go to syslog and stderr too . This message goes nowhere . as a filter. It's useful, for instance, to make sure that By default, all messages of level WARNING and above are sent to stderr. Everything else is ignored. "MyApp.Component" is an arbitrary string; you can tune logging behavior based on it later. Copy everything to syslog from here on out. Now we'd like to see everything from BuggyComponent at DEBUG or higher go to syslog and stderr. Also, we'd like to still ignore things less than WARNING in other areas. So, we adjust the Logger for MyApp.Component. This message will go to syslog and stderr This message will go to syslog and stderr too. This message goes nowhere. * Basic Types ** Re-Exported from System.Log * Logging Messages ** Basic ** Utility Functions These functions are wrappers for 'logM' to make your job easier. ** Logging to a particular Logger by object * Logger Manipulation which means that it will inherit whatever its which means that it will inherit whatever its ** Modifying Loggers ** Saving Your Changes | These functions commit changes you've made to loggers to the global logger hierarchy. ------------------------------------------------------------------------- Basic logger types ------------------------------------------------------------------------- | This is the base class for the various log handlers. They should all adhere to this class. ------------------------------------------------------------------------- ------------------------------------------------------------------------- | The name of the root logger, which is always defined and present on the system. ------------------------------------------------------------------------- Logger Tree Storage ------------------------------------------------------------------------- note: only kick up tree if handled locally | Given a name, return all components of it, starting from the root. Example return value: >["", "MissingH", "System.Cmd.Utils", "System.Cmd.Utils.pOpen"] ------------------------------------------------------------------------- Logging With Location ------------------------------------------------------------------------- | Log a message using the given logger at a given priority. ^ Name of the logger to use ^ Priority of this message ^ The log text itself ------------------------------------------------------------------------- Utility functions ------------------------------------------------------------------------- | Log a message at 'DEBUG' priority ^ Logger name ^ Log message | Log a message at 'INFO' priority ^ Logger name ^ Log message | Log a message at 'NOTICE' priority ^ Logger name ^ Log message | Log a message at 'WARNING' priority ^ Logger name ^ Log message | Log a message at 'ERROR' priority ^ Logger name ^ Log message | Log a message at 'CRITICAL' priority ^ Logger name ^ Log message | Log a message at 'ALERT' priority ^ Logger name ^ Log message | Log a message at 'EMERGENCY' priority ^ Logger name ^ Log message ------------------------------------------------------------------------- ------------------------------------------------------------------------- | Returns the logger for the given name. If no logger with that name exists, creates new loggers and any necessary parent loggers, with no connected handlers. A logger exists; return it and leave tree Add logger(s). Then call myself to retrieve it. No names to add; return tree unmodified Add logger to tree the modellogger is what we use for adding new loggers | Returns the root logger. | Log a message, assuming the current logger's level permits it. | Handle a log request. putStrLn pname | Call a handler given a HandlerT. | Generate IO actions for the handlers. | Add handler to 'Logger'. Returns a new 'Logger'. | Set the 'Logger'\'s list of handlers to the list supplied. | Returns the "level" of the logger. Items beneath this level will be ignored. | Sets the "level" of the 'Logger'. Returns a new 'Logger' object with the new level. | Updates the global record for the given logger to take into account any changes you may have made. ^ Logger name ^ Function to call Logger name Logging priority Descriptive text to prepend to logged messages Action to run Return value Re-raise it This function pulled in from MissingH to avoid a dep on it
to be found to be found getLogger to be found to be found setHandlers to be found setLevel arch - tag : Logger main definition Copyright ( C ) 2004 - 2006 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 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 Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2004-2006 John Goerzen <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} | Module : System . Log . Logger Copyright : Copyright ( C ) 2004 - 2006 License : GNU LGPL , version 2.1 or above Maintainer : < > Stability : provisional Portability : portable Haskell Logging Framework , Primary Interface Written by , jgoerzen\@complete.org Welcome to the error and information logging system for Haskell . This system is patterned after Python\ 's @logging@ module , < -logging.html > and some of the documentation here was based on documentation there . To log a message , you perform operations on ' Logger 's . Each ' Logger ' has a name , and they are arranged hierarchically . Periods serve as separators . Therefore , a ' Logger ' named \"foo\ " is the parent of loggers \"foo.printing\ " , \"foo.html\ " , and \"foo.io\ " . These names can be anything you want . They 're used to indicate the area of an application or library in which a logged message originates . Later you will see how you can use this concept to fine - tune logging behaviors based on specific application areas . You can also tune logging behaviors based upon how important a message is . Each message you log will have an importance associated with it . The different importance levels are given by the ' Priority ' type . I 've also provided some convenient functions that correspond to these importance levels : ' debugM ' through ' emergencyM ' log messages with the specified importance . Now , an importance level ( or ' Priority ' ) is associated not just with a particular message but also with a ' Logger ' . If the ' Priority ' of a given log message is lower than the ' Priority ' configured in the ' Logger ' , that message is ignored . This way , you can globally control how verbose your logging output is . Now , let 's follow what happens under the hood when you log a message . We 'll assume for the moment that you are logging something with a high enough ' Priority ' that it passes the test in your ' Logger ' . In your code , you 'll call ' logM ' or something like ' debugM ' to log the message . Your ' Logger ' decides to accept the message . What next ? Well , we also have a notion of /handlers/ ( ' LogHandler 's , to be precise ) . A ' LogHandler ' is a thing that takes a message and sends it somewhere . That \"somewhere\ " may be your screen ( via standard error ) , your system 's logging infrastructure ( via syslog ) , a file , or other things . Each ' Logger ' can have zero or more ' LogHandler 's associated with it . When your ' Logger ' has a message to log , it passes it to every ' LogHandler ' it knows of to process . What 's more , it is also passed to /all handlers of all ancestors of the Logger/ , regardless of whether those ' Logger 's would normally have passed on the message . To give you one extra little knob to turn , ' LogHandler 's can also have importance levels ( ' Priority ' ) associated with them in the same way that ' Logger 's do . They act just like the ' Priority ' value in the under no circumstances will a mere ' DEBUG ' message show up in your syslog . There are three built - in handlers given in two built - in modules : " System . Log . Handler . Simple " and " System . Log . Handler . Syslog " . There is a special logger known as the /root logger/ that sits at the top of the logger hierarchy . It is always present , and handlers attached there will be called for every message . You can use ' getRootLogger ' to get it or ' rootLoggerName ' to work with it by name . Here 's an example to illustrate some of these concepts : > import System . Log . Logger > import System . Log . Handler . Syslog > > > main = do > debugM " MyApp . Component " " This is a debug message -- never to be seen " > warningM " MyApp . Component2 " " Something Bad is about to happen . " > > s < - openlog " SyslogStuff " [ PID ] USER DEBUG > updateGlobalLogger rootLoggerName ( s ) > > errorM " MyApp . Component " " This is going to stderr and syslog . " > > > updateGlobalLogger " MyApp . BuggyComponent " > ( setLevel DEBUG ) > > debugM " MyApp . BuggyComponent " " This buggy component is buggy " > > warningM " MyApp . BuggyComponent " " Still Buggy " > > debugM " MyApp . WorkingComponent " " Hello " Module : System.Log.Logger Copyright : Copyright (C) 2004-2006 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <> Stability : provisional Portability: portable Haskell Logging Framework, Primary Interface Written by John Goerzen, jgoerzen\@complete.org Welcome to the error and information logging system for Haskell. This system is patterned after Python\'s @logging@ module, <-logging.html> and some of the documentation here was based on documentation there. To log a message, you perform operations on 'Logger's. Each 'Logger' has a name, and they are arranged hierarchically. Periods serve as separators. Therefore, a 'Logger' named \"foo\" is the parent of loggers \"foo.printing\", \"foo.html\", and \"foo.io\". These names can be anything you want. They're used to indicate the area of an application or library in which a logged message originates. Later you will see how you can use this concept to fine-tune logging behaviors based on specific application areas. You can also tune logging behaviors based upon how important a message is. Each message you log will have an importance associated with it. The different importance levels are given by the 'Priority' type. I've also provided some convenient functions that correspond to these importance levels: 'debugM' through 'emergencyM' log messages with the specified importance. Now, an importance level (or 'Priority') is associated not just with a particular message but also with a 'Logger'. If the 'Priority' of a given log message is lower than the 'Priority' configured in the 'Logger', that message is ignored. This way, you can globally control how verbose your logging output is. Now, let's follow what happens under the hood when you log a message. We'll assume for the moment that you are logging something with a high enough 'Priority' that it passes the test in your 'Logger'. In your code, you'll call 'logM' or something like 'debugM' to log the message. Your 'Logger' decides to accept the message. What next? Well, we also have a notion of /handlers/ ('LogHandler's, to be precise). A 'LogHandler' is a thing that takes a message and sends it somewhere. That \"somewhere\" may be your screen (via standard error), your system's logging infrastructure (via syslog), a file, or other things. Each 'Logger' can have zero or more 'LogHandler's associated with it. When your 'Logger' has a message to log, it passes it to every 'LogHandler' it knows of to process. What's more, it is also passed to /all handlers of all ancestors of the Logger/, regardless of whether those 'Logger's would normally have passed on the message. To give you one extra little knob to turn, 'LogHandler's can also have importance levels ('Priority') associated with them in the same way that 'Logger's do. They act just like the 'Priority' value in the under no circumstances will a mere 'DEBUG' message show up in your syslog. There are three built-in handlers given in two built-in modules: "System.Log.Handler.Simple" and "System.Log.Handler.Syslog". There is a special logger known as the /root logger/ that sits at the top of the logger hierarchy. It is always present, and handlers attached there will be called for every message. You can use 'getRootLogger' to get it or 'rootLoggerName' to work with it by name. Here's an example to illustrate some of these concepts: > import System.Log.Logger > import System.Log.Handler.Syslog > > > main = do > debugM "MyApp.Component" "This is a debug message -- never to be seen" > warningM "MyApp.Component2" "Something Bad is about to happen." > > s <- openlog "SyslogStuff" [PID] USER DEBUG > updateGlobalLogger rootLoggerName (addHandler s) > > errorM "MyApp.Component" "This is going to stderr and syslog." > > > updateGlobalLogger "MyApp.BuggyComponent" > (setLevel DEBUG) > > debugM "MyApp.BuggyComponent" "This buggy component is buggy" > > warningM "MyApp.BuggyComponent" "Still Buggy" > > debugM "MyApp.WorkingComponent" "Hello" -} module System.Log.Logger( Logger, Priority(..), logM, debugM, infoM, noticeM, warningM, errorM, criticalM, alertM, emergencyM, traplogging, logL, | These functions help you work with loggers . There are some special things to be aware of . First of all , whenever you first access a given logger by name , it magically springs to life . It has a default ' Priority ' of ' DEBUG ' parents do . special things to be aware of. First of all, whenever you first access a given logger by name, it magically springs to life. It has a default 'Priority' of 'DEBUG' parents do. -} * * Finding \/ Creating Loggers getLogger, getRootLogger, rootLoggerName, | Keep in mind that " here is modification in the sense . We do not actually cause mutation in a specific ' Logger ' . Rather , we return you a new ' Logger ' object with the change applied . Also , please note that these functions will not have an effect on the global ' Logger ' hierarchy . You may use your new ' Logger 's locally , but other functions wo n't see the changes . To make a change global , you 'll need to use ' updateGlobalLogger ' or ' saveGlobalLogger ' . sense. We do not actually cause mutation in a specific 'Logger'. Rather, we return you a new 'Logger' object with the change applied. Also, please note that these functions will not have an effect on the global 'Logger' hierarchy. You may use your new 'Logger's locally, but other functions won't see the changes. To make a change global, you'll need to use 'updateGlobalLogger' or 'saveGlobalLogger'. -} addHandler, setHandlers, getLevel, setLevel, saveGlobalLogger, updateGlobalLogger ) where import System.Log import System.Log.Handler(LogHandler) import qualified System.Log.Handler(handle) import System.Log.Handler.Simple import System.IO import System.IO.Unsafe import Control.Concurrent.MVar import Data.List(map, isPrefixOf) import qualified Data.Map as Map import qualified Control.Exception import Control.Monad.Error data HandlerT = forall a. LogHandler a => HandlerT a data Logger = Logger { level :: Priority, handlers :: [HandlerT], name :: String} type LogTree = Map.Map String Logger Utilities rootLoggerName = "" | Placeholders created when a new logger must be created . This is used only for the root logger default for now , as all others crawl up the tree to find a sensible default . only for the root logger default for now, as all others crawl up the tree to find a sensible default. -} placeholder :: Logger placeholder = Logger {level = WARNING, handlers = [], name = ""} | The log tree . Initialize it with a default root logger and ( FIXME ) a logger for MissingH itself . # NOINLINE logTree # logTree :: MVar LogTree logTree = unsafePerformIO $ do h <- streamHandler stderr DEBUG newMVar (Map.singleton rootLoggerName (Logger {level = WARNING, name = "", handlers = [HandlerT h]})) componentsOfName :: String -> [String] componentsOfName name = let joinComp [] _ = [] joinComp (x:xs) [] = x : joinComp xs x joinComp (x:xs) accum = let newlevel = accum ++ "." ++ x in newlevel : joinComp xs newlevel in rootLoggerName : joinComp (split "." name) [] -> IO () logM logname pri msg = do l <- getLogger logname logL l pri msg -> IO () debugM s = logM s DEBUG -> IO () infoM s = logM s INFO -> IO () noticeM s = logM s NOTICE -> IO () warningM s = logM s WARNING -> IO () errorM s = logM s ERROR -> IO () criticalM s = logM s CRITICAL -> IO () alertM s = logM s ALERT -> IO () emergencyM s = logM s EMERGENCY Public Logger Interaction Support getLogger :: String -> IO Logger getLogger lname = modifyMVar logTree $ \lt -> case Map.lookup lname lt of Nothing -> do let newlt = createLoggers (componentsOfName lname) lt result <- Map.lookup lname newlt return (newlt, result) where createLoggers :: [String] -> LogTree -> LogTree if Map.member x lt then createLoggers xs lt else createLoggers xs (Map.insert x ((modellogger lt) {name=x}) lt) modellogger :: LogTree -> Logger modellogger lt = findmodellogger lt (reverse $ componentsOfName lname) findmodellogger _ [] = error "findmodellogger: root logger does not exist?!" findmodellogger lt (x:xs) = case Map.lookup x lt of Left (_::String) -> findmodellogger lt xs Right logger -> logger {handlers = []} getRootLogger :: IO Logger getRootLogger = getLogger rootLoggerName logL :: Logger -> Priority -> String -> IO () logL l pri msg = handle l (pri, msg) handle :: Logger -> LogRecord -> IO () handle l (pri, msg) = let parentHandlers [] = return [] parentHandlers name = let pname = (head . drop 1 . reverse . componentsOfName) name in do ( join " , " foo ) putStrLn " 1 " parent <- getLogger pname putStrLn " 2 " next <- parentHandlers pname putStrLn " 3 " return ((handlers parent) ++ next) in if pri >= (level l) then do ph <- parentHandlers (name l) sequence_ (handlerActions (ph ++ (handlers l)) (pri, msg) (name l)) else return () callHandler :: LogRecord -> String -> HandlerT -> IO () callHandler lr loggername ht = case ht of HandlerT x -> System.Log.Handler.handle x lr loggername handlerActions :: [HandlerT] -> LogRecord -> String -> [IO ()] handlerActions h lr loggername = map (callHandler lr loggername ) h addHandler :: LogHandler a => a -> Logger -> Logger addHandler h l= l{handlers = (HandlerT h) : (handlers l)} All existing handlers are removed first . setHandlers :: LogHandler a => [a] -> Logger -> Logger setHandlers hl l = l{handlers = map (\h -> HandlerT h) hl} getLevel :: Logger -> Priority getLevel l = level l setLevel :: Priority -> Logger -> Logger setLevel p l = l{level = p} saveGlobalLogger :: Logger -> IO () saveGlobalLogger l = modifyMVar_ logTree (\lt -> return $ Map.insert (name l) l lt) | Helps you make changes on the given logger . Takes a function that makes changes and writes those changes back to the global database . Here 's an example from above ( \"s\ " is a ' LogHandler ' ): > updateGlobalLogger " MyApp . BuggyComponent " > ( setLevel DEBUG . [ s ] ) that makes changes and writes those changes back to the global database. Here's an example from above (\"s\" is a 'LogHandler'): > updateGlobalLogger "MyApp.BuggyComponent" > (setLevel DEBUG . setHandlers [s]) -} -> IO () updateGlobalLogger ln func = do l <- getLogger ln saveGlobalLogger (func l) | Traps exceptions that may occur , logging them , then passing them on . Takes a logger name , priority , leading description text ( you can set it to @\"\"@ if you do n't want any ) , and action to run . Takes a logger name, priority, leading description text (you can set it to @\"\"@ if you don't want any), and action to run. -} traplogging logger priority desc action = let realdesc = case desc of "" -> "" x -> x ++ ": " handler e = do logM logger priority (realdesc ++ (show e)) in Control.Exception.catch action handler split :: Eq a => [a] -> [a] -> [[a]] split _ [] = [] split delim str = let (firstline, remainder) = breakList (isPrefixOf delim) str in firstline : case remainder of [] -> [] x -> if x == delim then [] : [] else split delim (drop (length delim) x) This function also pulled from MissingH breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) This function also pulled from MissingH spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list) where (ys,zs) = spanList func xs
e8e1bdb48fb1a800326e3eca605682caeee577a758acf72e1e2531c2cf8f33ad
koto-bank/lbge
image-loader-test.lisp
(define-test image-loader-test ((:i :lbge.image)) (testing "Loading TGA" (let ((tga (i:load-image #P"test-file.tga"))) TGA (ok (eq 'i:image (type-of tga))) (ok (= 128 (i:width tga))) (ok (= 128 (i:height tga))))) (testing "Loading PNG" (let ((png (i:load-image #P"test-file.png"))) ;; PNG (ok (eq 'i:image (type-of png))) (ok (= 272 (i:width png))) (ok (= 170 (i:height png))) (ok (eq :rgb8 (i:channels png))))))
null
https://raw.githubusercontent.com/koto-bank/lbge/6be4b3212ea87288b1ee2a655e9a1bb30a74dd27/src/image-loader/t/image-loader-test.lisp
lisp
PNG
(define-test image-loader-test ((:i :lbge.image)) (testing "Loading TGA" (let ((tga (i:load-image #P"test-file.tga"))) TGA (ok (eq 'i:image (type-of tga))) (ok (= 128 (i:width tga))) (ok (= 128 (i:height tga))))) (testing "Loading PNG" (let ((png (i:load-image #P"test-file.png"))) (ok (eq 'i:image (type-of png))) (ok (= 272 (i:width png))) (ok (= 170 (i:height png))) (ok (eq :rgb8 (i:channels png))))))
a51af6f9f6e3520bc29cd09f074a2ab276abf0c6ca5a0ce3c1ec4f85b56218ad
phantomics/seed
style.base.lisp
;;;; style.base.lisp (in-package #:seed.foreign.browser-spec.style.base) (defparameter *local-package-name* (package-name *package*)) (defmacro foundational-browser-style-base () "Generate the paths for the style source files." (mapcar (lambda (item) (asdf:system-relative-pathname (intern *local-package-name* "KEYWORD") item)) (list "./node_modules/bootstrap/dist/css/bootstrap.min.css" ;; "./node_modules/react-select/dist/react-select.css" "./node_modules/codemirror/lib/codemirror.css" "./node_modules/codemirror/theme/solarized.css")))
null
https://raw.githubusercontent.com/phantomics/seed/f128969c671c078543574395d6b23a1a5f2723f8/seed.foreign.browser-spec.style.base/style.base.lisp
lisp
style.base.lisp "./node_modules/react-select/dist/react-select.css"
(in-package #:seed.foreign.browser-spec.style.base) (defparameter *local-package-name* (package-name *package*)) (defmacro foundational-browser-style-base () "Generate the paths for the style source files." (mapcar (lambda (item) (asdf:system-relative-pathname (intern *local-package-name* "KEYWORD") item)) (list "./node_modules/bootstrap/dist/css/bootstrap.min.css" "./node_modules/codemirror/lib/codemirror.css" "./node_modules/codemirror/theme/solarized.css")))
15938e754b4c9f5406129c8a6859e41b5a2c2b25370fa4d33487712c1a64edb4
chovencorp/erlangzmq
router_with_dealer.erl
@copyright 2016 Choven Corp. %% This file is part of erlangzmq . %% erlangzmq is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% erlangzmq 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 Affero General Public License for more details. %% You should have received a copy of the GNU Affero General Public License along with erlangzmq . If not , see < / > -module(router_with_dealer). -export([main/0]). start_worker(Identity) -> Parent = self(), spawn_link( fun () -> {ok, Socket} = erlangzmq:socket(dealer, Identity), {ok, _PeerPid} = erlangzmq:connect(Socket, tcp, "localhost", 5585), worker_loop(Socket, Identity, Parent) end ). worker_loop(Socket, Identity, Parent) -> {ok, Multipart} = erlangzmq:recv_multipart(Socket), case Multipart of [<<"EXIT">>] -> ok; _ -> Parent ! {recv, Identity, Multipart} end. main() -> application:ensure_started(erlangzmq), {ok, Socket} = erlangzmq:socket(router), {ok, _BindPid} = erlangzmq:bind(Socket, tcp, "localhost", 5585), start_worker("A"), start_worker("B"), timer:sleep(100), %% wait workers to be established ok = erlangzmq:send_multipart(Socket, [<<"A">>, <<"My message one">>]), ok = erlangzmq:send_multipart(Socket, [<<"B">>, <<"My message two">>]), ok = erlangzmq:send_multipart(Socket, [<<"A">>, <<"EXIT">>]), ok = erlangzmq:send_multipart(Socket, [<<"B">>, <<"EXIT">>]), MessageA = receive {recv, "A", MultipartA} -> MultipartA end, MessageB = receive {recv, "B", MultipartB} -> MultipartB end, io:format("Received: ~p...~p\n", [MessageA, MessageB]).
null
https://raw.githubusercontent.com/chovencorp/erlangzmq/2be5c3b36dd78b010d1790a8f74ae2e823f5a424/examples/router_with_dealer.erl
erlang
(at your option) any later version. erlangzmq 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 Affero General Public License for more details. wait workers to be established
@copyright 2016 Choven Corp. This file is part of erlangzmq . erlangzmq is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Affero General Public License along with erlangzmq . If not , see < / > -module(router_with_dealer). -export([main/0]). start_worker(Identity) -> Parent = self(), spawn_link( fun () -> {ok, Socket} = erlangzmq:socket(dealer, Identity), {ok, _PeerPid} = erlangzmq:connect(Socket, tcp, "localhost", 5585), worker_loop(Socket, Identity, Parent) end ). worker_loop(Socket, Identity, Parent) -> {ok, Multipart} = erlangzmq:recv_multipart(Socket), case Multipart of [<<"EXIT">>] -> ok; _ -> Parent ! {recv, Identity, Multipart} end. main() -> application:ensure_started(erlangzmq), {ok, Socket} = erlangzmq:socket(router), {ok, _BindPid} = erlangzmq:bind(Socket, tcp, "localhost", 5585), start_worker("A"), start_worker("B"), ok = erlangzmq:send_multipart(Socket, [<<"A">>, <<"My message one">>]), ok = erlangzmq:send_multipart(Socket, [<<"B">>, <<"My message two">>]), ok = erlangzmq:send_multipart(Socket, [<<"A">>, <<"EXIT">>]), ok = erlangzmq:send_multipart(Socket, [<<"B">>, <<"EXIT">>]), MessageA = receive {recv, "A", MultipartA} -> MultipartA end, MessageB = receive {recv, "B", MultipartB} -> MultipartB end, io:format("Received: ~p...~p\n", [MessageA, MessageB]).
88028d2ec6ab2e91950214da32c8da19758a9db4c098f39470e13a7429b478b5
glebec/haskell-programming-allen-moronuki
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # module Main where import Control.Exception import Control.Monad (forever) import Data.List (intersperse) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Typeable import Database.SQLite.Simple hiding (bind, close) import qualified Database.SQLite.Simple as SQLite import Database.SQLite.Simple.Types import Network.Socket hiding (recv) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Network.Socket.ByteString (recv, sendAll) import Text.RawString.QQ data User = User { userId :: Integer , username :: Text , shell :: Text , homeDirectory :: Text , realName :: Text , phone :: Text } deriving (Eq, Show) instance FromRow User where fromRow = User <$> field <*> field <*> field <*> field <*> field <*> field instance ToRow User where toRow User{..} = toRow (userId, username, shell, homeDirectory, realName, phone) createUsers :: Query createUsers = [r| CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, shell TEXT, homeDirectory TEXT, realName TEXT, phone TEXT) |] insertUser :: Query insertUser = "INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)" allUsers :: Query allUsers = "SELECT * FROM users" getUserQuery :: Query getUserQuery = "SELECT * FROM users WHERE username = ?" data DuplicateData = DuplicateData deriving (Eq, Show, Typeable) instance Exception DuplicateData type UserRow = (Null, Text, Text, Text, Text, Text) getUser :: Connection -> Text -> IO (Maybe User) getUser conn username = do results <- query conn getUserQuery (Only username) case results of [] -> pure Nothing [user] -> pure $ Just user _ -> throwIO DuplicateData createDatabase :: IO () createDatabase = do conn <- open "finger.db" execute_ conn createUsers execute conn insertUser meRow rows <- query_ conn allUsers mapM_ print (rows :: [User]) SQLite.close conn where meRow :: UserRow meRow = (Null, "glebec", "/bin/zsh", "/home/glebec", "G. Lebec", "555-123-4567") returnUsers :: Connection -> Socket -> IO () returnUsers dbConn soc = do rows <- query_ dbConn allUsers let usernames = map username rows newlineSeparated = T.concat $ intersperse "\n" usernames sendAll soc (encodeUtf8 newlineSeparated) formatUser :: User -> ByteString formatUser (User _ username shell homeDir realName _) = BS.concat [ "Login: ", e username, "\t\t\t\t", "Name: ", e realName, "\n", "Directory: ", e homeDir, "\t\t\t", "Shell: ", e shell, "\n" ] where e = encodeUtf8 returnUser :: Connection -> Socket -> Text -> IO () returnUser dbConn soc username = do maybeUser <- getUser dbConn (T.strip username) case maybeUser of Nothing -> do putStrLn $ "Couldn't find matching user for username: " ++ show username sendAll soc "That user was not found." Just user -> sendAll soc (formatUser user) handleQuery :: Connection -> Socket -> IO () handleQuery dbConn soc = do msg <- recv soc 1024 case msg of "\n" -> returnUsers dbConn soc name -> returnUser dbConn soc (decodeUtf8 name) handleQueries :: Connection -> Socket -> IO () handleQueries dbConn sock = forever $ do (soc, _) <- accept sock putStrLn "Got connection, handling query" handleQuery dbConn soc close soc main :: IO () main = withSocketsDo $ do addrInfos <- getAddrInfo (Just $ defaultHints {addrFlags = [AI_PASSIVE]}) Nothing (Just "79") let serverAddr = head addrInfos sock <- socket (addrFamily serverAddr) Stream defaultProtocol bind sock (addrAddress serverAddr) one connection at a time conn <- open "finger.db" handleQueries conn sock SQLite.close conn close sock
null
https://raw.githubusercontent.com/glebec/haskell-programming-allen-moronuki/99bd232f523e426d18a5e096f1cf771228c55f52/31-final-project/fingerd/src/Main.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # module Main where import Control.Exception import Control.Monad (forever) import Data.List (intersperse) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Typeable import Database.SQLite.Simple hiding (bind, close) import qualified Database.SQLite.Simple as SQLite import Database.SQLite.Simple.Types import Network.Socket hiding (recv) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Network.Socket.ByteString (recv, sendAll) import Text.RawString.QQ data User = User { userId :: Integer , username :: Text , shell :: Text , homeDirectory :: Text , realName :: Text , phone :: Text } deriving (Eq, Show) instance FromRow User where fromRow = User <$> field <*> field <*> field <*> field <*> field <*> field instance ToRow User where toRow User{..} = toRow (userId, username, shell, homeDirectory, realName, phone) createUsers :: Query createUsers = [r| CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, shell TEXT, homeDirectory TEXT, realName TEXT, phone TEXT) |] insertUser :: Query insertUser = "INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)" allUsers :: Query allUsers = "SELECT * FROM users" getUserQuery :: Query getUserQuery = "SELECT * FROM users WHERE username = ?" data DuplicateData = DuplicateData deriving (Eq, Show, Typeable) instance Exception DuplicateData type UserRow = (Null, Text, Text, Text, Text, Text) getUser :: Connection -> Text -> IO (Maybe User) getUser conn username = do results <- query conn getUserQuery (Only username) case results of [] -> pure Nothing [user] -> pure $ Just user _ -> throwIO DuplicateData createDatabase :: IO () createDatabase = do conn <- open "finger.db" execute_ conn createUsers execute conn insertUser meRow rows <- query_ conn allUsers mapM_ print (rows :: [User]) SQLite.close conn where meRow :: UserRow meRow = (Null, "glebec", "/bin/zsh", "/home/glebec", "G. Lebec", "555-123-4567") returnUsers :: Connection -> Socket -> IO () returnUsers dbConn soc = do rows <- query_ dbConn allUsers let usernames = map username rows newlineSeparated = T.concat $ intersperse "\n" usernames sendAll soc (encodeUtf8 newlineSeparated) formatUser :: User -> ByteString formatUser (User _ username shell homeDir realName _) = BS.concat [ "Login: ", e username, "\t\t\t\t", "Name: ", e realName, "\n", "Directory: ", e homeDir, "\t\t\t", "Shell: ", e shell, "\n" ] where e = encodeUtf8 returnUser :: Connection -> Socket -> Text -> IO () returnUser dbConn soc username = do maybeUser <- getUser dbConn (T.strip username) case maybeUser of Nothing -> do putStrLn $ "Couldn't find matching user for username: " ++ show username sendAll soc "That user was not found." Just user -> sendAll soc (formatUser user) handleQuery :: Connection -> Socket -> IO () handleQuery dbConn soc = do msg <- recv soc 1024 case msg of "\n" -> returnUsers dbConn soc name -> returnUser dbConn soc (decodeUtf8 name) handleQueries :: Connection -> Socket -> IO () handleQueries dbConn sock = forever $ do (soc, _) <- accept sock putStrLn "Got connection, handling query" handleQuery dbConn soc close soc main :: IO () main = withSocketsDo $ do addrInfos <- getAddrInfo (Just $ defaultHints {addrFlags = [AI_PASSIVE]}) Nothing (Just "79") let serverAddr = head addrInfos sock <- socket (addrFamily serverAddr) Stream defaultProtocol bind sock (addrAddress serverAddr) one connection at a time conn <- open "finger.db" handleQueries conn sock SQLite.close conn close sock
4751de05c8cfc3bec957a74a81d53086b859643e92e02d748136386db905c100
modular-macros/ocaml-macros
terminfo.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Basic interface to the terminfo database type status = | Uninitialised | Bad_term | Good_term of int ;; external setup : out_channel -> status = "caml_terminfo_setup";; external backup : int -> unit = "caml_terminfo_backup";; external standout : bool -> unit = "caml_terminfo_standout";; external resume : int -> unit = "caml_terminfo_resume";;
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/utils/terminfo.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Basic interface to the terminfo database type status = | Uninitialised | Bad_term | Good_term of int ;; external setup : out_channel -> status = "caml_terminfo_setup";; external backup : int -> unit = "caml_terminfo_backup";; external standout : bool -> unit = "caml_terminfo_standout";; external resume : int -> unit = "caml_terminfo_resume";;
f542f084992f3d37849a139c8824896f2568053a9bd30b6c54f0cda161b46c1f
sig-gis/gridfire
fuel_models_test.clj
(ns gridfire.fuel-models-test (:require [clojure.test :refer :all] [gridfire.fuel-models :refer :all] [gridfire.behaveplus-results :refer :all])) ;; Checks live fuel moisture of extinction and dynamic fuel loading for the S&B40 fuel models under fully cured conditions (deftest moisturize-test-dry (doseq [num sb40-fuel-models] (let [gridfire-fuel-model-dry (build-fuel-model num) gridfire-fuel-model-wet (moisturize gridfire-fuel-model-dry (test-fuel-moisture :dry)) gridfire-M_x-live (* 100 (-> gridfire-fuel-model-wet :M_x :live :herbaceous)) gridfire-fraction-cured (if (pos? (-> gridfire-fuel-model-dry :w_o :live :herbaceous)) (* 100 (/ (-> gridfire-fuel-model-wet :w_o :dead :herbaceous) (-> gridfire-fuel-model-dry :w_o :live :herbaceous))) 0) behaveplus-outputs (-> (:name gridfire-fuel-model-dry) (behaveplus5-surface-fire-values-dry-no-wind-no-slope)) behaveplus-M_x-live (behaveplus-outputs 4) behaveplus-fraction-cured (behaveplus-outputs 6)] all are within 1 % except TU2 at -6 % (is (within gridfire-fraction-cured behaveplus-fraction-cured 0.1))))) Checks live fuel moisture of extinction and dynamic fuel loading for the S&B40 fuel models under 50 % cured conditions (deftest moisturize-test-mid (doseq [num sb40-fuel-models] (let [gridfire-fuel-model-dry (build-fuel-model num) gridfire-fuel-model-wet (moisturize gridfire-fuel-model-dry (test-fuel-moisture :mid)) gridfire-M_x-live (* 100 (-> gridfire-fuel-model-wet :M_x :live :herbaceous)) gridfire-fraction-cured (if (pos? (-> gridfire-fuel-model-dry :w_o :live :herbaceous)) (* 100 (/ (-> gridfire-fuel-model-wet :w_o :dead :herbaceous) (-> gridfire-fuel-model-dry :w_o :live :herbaceous))) 0) behaveplus-outputs (-> (:name gridfire-fuel-model-dry) (behaveplus5-surface-fire-values-mid-no-wind-no-slope)) behaveplus-M_x-live (behaveplus-outputs 4) behaveplus-fraction-cured (behaveplus-outputs 6)] all are within 1 % except TU2 at -6 % (is (within gridfire-fraction-cured behaveplus-fraction-cured 0.1))))) ;; TODO: Add moisturize-test-wet (comment (run-tests) )
null
https://raw.githubusercontent.com/sig-gis/gridfire/44aeaf56fceb01f61b21db6220d2cb562a92570b/test/gridfire/fuel_models_test.clj
clojure
Checks live fuel moisture of extinction and dynamic fuel loading for the S&B40 fuel models under fully cured conditions TODO: Add moisturize-test-wet
(ns gridfire.fuel-models-test (:require [clojure.test :refer :all] [gridfire.fuel-models :refer :all] [gridfire.behaveplus-results :refer :all])) (deftest moisturize-test-dry (doseq [num sb40-fuel-models] (let [gridfire-fuel-model-dry (build-fuel-model num) gridfire-fuel-model-wet (moisturize gridfire-fuel-model-dry (test-fuel-moisture :dry)) gridfire-M_x-live (* 100 (-> gridfire-fuel-model-wet :M_x :live :herbaceous)) gridfire-fraction-cured (if (pos? (-> gridfire-fuel-model-dry :w_o :live :herbaceous)) (* 100 (/ (-> gridfire-fuel-model-wet :w_o :dead :herbaceous) (-> gridfire-fuel-model-dry :w_o :live :herbaceous))) 0) behaveplus-outputs (-> (:name gridfire-fuel-model-dry) (behaveplus5-surface-fire-values-dry-no-wind-no-slope)) behaveplus-M_x-live (behaveplus-outputs 4) behaveplus-fraction-cured (behaveplus-outputs 6)] all are within 1 % except TU2 at -6 % (is (within gridfire-fraction-cured behaveplus-fraction-cured 0.1))))) Checks live fuel moisture of extinction and dynamic fuel loading for the S&B40 fuel models under 50 % cured conditions (deftest moisturize-test-mid (doseq [num sb40-fuel-models] (let [gridfire-fuel-model-dry (build-fuel-model num) gridfire-fuel-model-wet (moisturize gridfire-fuel-model-dry (test-fuel-moisture :mid)) gridfire-M_x-live (* 100 (-> gridfire-fuel-model-wet :M_x :live :herbaceous)) gridfire-fraction-cured (if (pos? (-> gridfire-fuel-model-dry :w_o :live :herbaceous)) (* 100 (/ (-> gridfire-fuel-model-wet :w_o :dead :herbaceous) (-> gridfire-fuel-model-dry :w_o :live :herbaceous))) 0) behaveplus-outputs (-> (:name gridfire-fuel-model-dry) (behaveplus5-surface-fire-values-mid-no-wind-no-slope)) behaveplus-M_x-live (behaveplus-outputs 4) behaveplus-fraction-cured (behaveplus-outputs 6)] all are within 1 % except TU2 at -6 % (is (within gridfire-fraction-cured behaveplus-fraction-cured 0.1))))) (comment (run-tests) )
da85c12180104b8b2d24f3952c6bb53ddc4917186cfa4af3a900f79843837d14
Helium4Haskell/helium
DataAppTyvar.hs
module DataAppTyvar where data A a = A (a Int)
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticerrors/DataAppTyvar.hs
haskell
module DataAppTyvar where data A a = A (a Int)
d7255ec5d36b36ab09c48bf98edfa9e3198e1dbc137f9b92e248ba5d9862ddfc
saikyun/clobits
ni.clj
;; This file is autogenerated -- probably shouldn't modify it by hand (clojure.core/ns clobits.ncurses.ni (:import clobits.wrappers.IWrapperNI) (:gen-class)) (clojure.core/defn free [^clobits.wrappers.IWrapperNI ptr] (clobits.ncurses.ni.interop/free (.unwrap ptr))) (clojure.core/defn malloc ^clobits.wrappers.WrapVoid [^long size] (new clobits.wrappers.WrapVoid (clobits.ncurses.ni.interop/malloc size))) (clojure.core/defn initscr ^clobits.wrappers.WrapVoid [] (new clobits.wrappers.WrapVoid (clobits.ncurses.ni.interop/initscr))) (clojure.core/defn delwin ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/delwin (.unwrap win))) (clojure.core/defn endwin ^long [] (clobits.ncurses.ni.interop/endwin)) (clojure.core/defn noecho ^long [] (clobits.ncurses.ni.interop/noecho)) (clojure.core/defn curs-set ^long [^long visibility] (clobits.ncurses.ni.interop/curs-set visibility)) (clojure.core/defn mvprintw ^long [^long y ^long x ^clobits.wrappers.IWrapperNI fmt] (clobits.ncurses.ni.interop/mvprintw y x (.unwrap fmt))) (clojure.core/defn clear ^long [] (clobits.ncurses.ni.interop/clear)) (clojure.core/defn getmaxx ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/getmaxx (.unwrap win))) (clojure.core/defn getmaxy ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/getmaxy (.unwrap win))) (clojure.core/defn getmaxyx [^clobits.wrappers.IWrapperNI win ^long y ^long x] (clobits.ncurses.ni.interop/getmaxyx (.unwrap win) y x)) (clojure.core/defn printw ^long [^clobits.wrappers.IWrapperNI arg0] (clobits.ncurses.ni.interop/printw (.unwrap arg0))) (clojure.core/defn refresh ^long [] (clobits.ncurses.ni.interop/refresh)) (clojure.core/defn wrefresh ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/wrefresh (.unwrap win)))
null
https://raw.githubusercontent.com/saikyun/clobits/67bc60cbf6bed8a5178d552d3485e4117fb4df10/examples/ncurses/gen-src/clj/clobits/ncurses/ni.clj
clojure
This file is autogenerated -- probably shouldn't modify it by hand
(clojure.core/ns clobits.ncurses.ni (:import clobits.wrappers.IWrapperNI) (:gen-class)) (clojure.core/defn free [^clobits.wrappers.IWrapperNI ptr] (clobits.ncurses.ni.interop/free (.unwrap ptr))) (clojure.core/defn malloc ^clobits.wrappers.WrapVoid [^long size] (new clobits.wrappers.WrapVoid (clobits.ncurses.ni.interop/malloc size))) (clojure.core/defn initscr ^clobits.wrappers.WrapVoid [] (new clobits.wrappers.WrapVoid (clobits.ncurses.ni.interop/initscr))) (clojure.core/defn delwin ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/delwin (.unwrap win))) (clojure.core/defn endwin ^long [] (clobits.ncurses.ni.interop/endwin)) (clojure.core/defn noecho ^long [] (clobits.ncurses.ni.interop/noecho)) (clojure.core/defn curs-set ^long [^long visibility] (clobits.ncurses.ni.interop/curs-set visibility)) (clojure.core/defn mvprintw ^long [^long y ^long x ^clobits.wrappers.IWrapperNI fmt] (clobits.ncurses.ni.interop/mvprintw y x (.unwrap fmt))) (clojure.core/defn clear ^long [] (clobits.ncurses.ni.interop/clear)) (clojure.core/defn getmaxx ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/getmaxx (.unwrap win))) (clojure.core/defn getmaxy ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/getmaxy (.unwrap win))) (clojure.core/defn getmaxyx [^clobits.wrappers.IWrapperNI win ^long y ^long x] (clobits.ncurses.ni.interop/getmaxyx (.unwrap win) y x)) (clojure.core/defn printw ^long [^clobits.wrappers.IWrapperNI arg0] (clobits.ncurses.ni.interop/printw (.unwrap arg0))) (clojure.core/defn refresh ^long [] (clobits.ncurses.ni.interop/refresh)) (clojure.core/defn wrefresh ^long [^clobits.wrappers.IWrapperNI win] (clobits.ncurses.ni.interop/wrefresh (.unwrap win)))
f7a93ce782e7836261338e357080c30ca7c67104268ac03abaef6605b29ea529
bobzhang/fan
rec_patt.ml
let f = fun ?s () -> s; let g ?s = f ?s (); let ? ( s=3 ) = 3 ;
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/testr/rec_patt.ml
ocaml
let f = fun ?s () -> s; let g ?s = f ?s (); let ? ( s=3 ) = 3 ;
40b28c04ffcc3f5842b7081246c95d2bff785d367e13248149ce7b5edf6b5f59
degree9/enterprise
headers.cljs
(ns degree9.headers (:require [goog.object :as obj] [degree9.debug :as dbg])) (dbg/defdebug debug "degree9:enterprise:headers") ;; Feathers Headers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- req-headers [req] (obj/get req "headers")) (defn- req-feathers [req] (obj/get req "feathers")) (defn- fs-headers! [fs headers] (obj/set fs "headers" headers)) (defn- fs-headers [req res next] (fs-headers! (req-feathers req) (req-headers req)) (next)) (defn feathers-headers [app] (debug "Initializing Headers API.") (doto app (.use fs-headers))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
null
https://raw.githubusercontent.com/degree9/enterprise/36e4f242c18b1dde54d5a15c668b17dc800c01ff/src/degree9/headers.cljs
clojure
Feathers Headers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns degree9.headers (:require [goog.object :as obj] [degree9.debug :as dbg])) (dbg/defdebug debug "degree9:enterprise:headers") (defn- req-headers [req] (obj/get req "headers")) (defn- req-feathers [req] (obj/get req "feathers")) (defn- fs-headers! [fs headers] (obj/set fs "headers" headers)) (defn- fs-headers [req res next] (fs-headers! (req-feathers req) (req-headers req)) (next)) (defn feathers-headers [app] (debug "Initializing Headers API.") (doto app (.use fs-headers)))
8102ad222d9785cc89a6f2ac63d6cd1f1121578b5612bccc56dc13330265ac3d
austral/austral
Cli.mli
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions . See LICENSE file for details . SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE file for details. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *) (** This module implements the compiler's command line interface. *) (** The entry point function for the compiler. *) val main : string list -> unit
null
https://raw.githubusercontent.com/austral/austral/69b6f7de36cc9576483acd1ac4a31bf52074dbd1/lib/Cli.mli
ocaml
* This module implements the compiler's command line interface. * The entry point function for the compiler.
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions . See LICENSE file for details . SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE file for details. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *) val main : string list -> unit
2853456ee385d5f0c1c07adc81cc6d1c06555194d2baed0d7b23366b8e2ea828
ghcjs/ghcjs
gEq2.hs
# LANGUAGE TypeOperators , DefaultSignatures , FlexibleInstances , DeriveGeneric # # LANGUAGE FlexibleContexts # module Main where import GHC.Generics hiding (C, D) class GEq' f where geq' :: f a -> f a -> Bool instance GEq' U1 where geq' _ _ = True instance (GEq c) => GEq' (K1 i c) where geq' (K1 a) (K1 b) = geq a b -- No instances for P or Rec because geq is only applicable to types of kind * instance (GEq' a) => GEq' (M1 i c a) where geq' (M1 a) (M1 b) = geq' a b instance (GEq' a, GEq' b) => GEq' (a :+: b) where geq' (L1 a) (L1 b) = geq' a b geq' (R1 a) (R1 b) = geq' a b geq' _ _ = False instance (GEq' a, GEq' b) => GEq' (a :*: b) where geq' (a1 :*: b1) (a2 :*: b2) = geq' a1 a2 && geq' b1 b2 class GEq a where geq :: a -> a -> Bool default geq :: (Generic a, GEq' (Rep a)) => a -> a -> Bool geq x y = geq' (from x) (from y) -- Base types instances (ad-hoc) instance GEq Char where geq = (==) instance GEq Int where geq = (==) instance GEq Float where geq = (==) -- Generic instances instance ( GEq a ) = > GEq ( Maybe a ) instance ( GEq a ) = > GEq [ a ] -- Generic instances instance (GEq a) => GEq (Maybe a) instance (GEq a) => GEq [a] -} data C = C0 | C1 deriving Generic data D a = D0 | D1 { d11 :: a, d12 :: (D a) } deriving Generic data (:**:) a b = a :**: b deriving Generic -- Example values c0 = C0 c1 = C1 d0 :: D Char d0 = D0 d1 = D1 'p' D0 p1 :: Int :**: Char p1 = 3 :**: 'p' Generic instances instance GEq C instance (GEq a) => GEq (D a) instance (GEq a, GEq b) => GEq (a :**: b) -- Tests teq0 = geq c0 c1 teq1 = geq d0 d1 teq2 = geq d0 d0 teq3 = geq p1 p1 main = mapM_ print [teq0, teq1, teq2, teq3]
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/generics/geq/gEq2.hs
haskell
No instances for P or Rec because geq is only applicable to types of kind * Base types instances (ad-hoc) Generic instances Generic instances Example values Tests
# LANGUAGE TypeOperators , DefaultSignatures , FlexibleInstances , DeriveGeneric # # LANGUAGE FlexibleContexts # module Main where import GHC.Generics hiding (C, D) class GEq' f where geq' :: f a -> f a -> Bool instance GEq' U1 where geq' _ _ = True instance (GEq c) => GEq' (K1 i c) where geq' (K1 a) (K1 b) = geq a b instance (GEq' a) => GEq' (M1 i c a) where geq' (M1 a) (M1 b) = geq' a b instance (GEq' a, GEq' b) => GEq' (a :+: b) where geq' (L1 a) (L1 b) = geq' a b geq' (R1 a) (R1 b) = geq' a b geq' _ _ = False instance (GEq' a, GEq' b) => GEq' (a :*: b) where geq' (a1 :*: b1) (a2 :*: b2) = geq' a1 a2 && geq' b1 b2 class GEq a where geq :: a -> a -> Bool default geq :: (Generic a, GEq' (Rep a)) => a -> a -> Bool geq x y = geq' (from x) (from y) instance GEq Char where geq = (==) instance GEq Int where geq = (==) instance GEq Float where geq = (==) instance ( GEq a ) = > GEq ( Maybe a ) instance ( GEq a ) = > GEq [ a ] instance (GEq a) => GEq (Maybe a) instance (GEq a) => GEq [a] -} data C = C0 | C1 deriving Generic data D a = D0 | D1 { d11 :: a, d12 :: (D a) } deriving Generic data (:**:) a b = a :**: b deriving Generic c0 = C0 c1 = C1 d0 :: D Char d0 = D0 d1 = D1 'p' D0 p1 :: Int :**: Char p1 = 3 :**: 'p' Generic instances instance GEq C instance (GEq a) => GEq (D a) instance (GEq a, GEq b) => GEq (a :**: b) teq0 = geq c0 c1 teq1 = geq d0 d1 teq2 = geq d0 d0 teq3 = geq p1 p1 main = mapM_ print [teq0, teq1, teq2, teq3]
66fda2e756d36e4bbe4e2420ed688104131dac4c67abb1360606a37204dcaf5a
diku-dk/futhark
Futhark.hs
| Re - export the external modules for convenience . module Language.Futhark ( module Language.Futhark.Syntax, module Language.Futhark.Prop, module Language.Futhark.FreeVars, module Language.Futhark.Pretty, Ident, DimIndex, Slice, AppExp, Exp, Pat, ModExp, ModParam, SigExp, ModBind, SigBind, ValBind, Dec, Spec, Prog, TypeBind, StructTypeArg, ScalarType, TypeParam, Case, ) where import Language.Futhark.FreeVars import Language.Futhark.Pretty import Language.Futhark.Prop import Language.Futhark.Syntax -- | An identifier with type- and aliasing information. type Ident = IdentBase Info VName -- | An index with type information. type DimIndex = DimIndexBase Info VName -- | A slice with type information. type Slice = SliceBase Info VName -- | An expression with type information. type Exp = ExpBase Info VName -- | An application expression with type information. type AppExp = AppExpBase Info VName -- | A pattern with type information. type Pat = PatBase Info VName -- | An constant declaration with type information. type ValBind = ValBindBase Info VName -- | A type binding with type information. type TypeBind = TypeBindBase Info VName -- | A type-checked module binding. type ModBind = ModBindBase Info VName -- | A type-checked module type binding. type SigBind = SigBindBase Info VName -- | A type-checked module expression. type ModExp = ModExpBase Info VName -- | A type-checked module parameter. type ModParam = ModParamBase Info VName -- | A type-checked module type expression. type SigExp = SigExpBase Info VName -- | A type-checked declaration. type Dec = DecBase Info VName -- | A type-checked specification. type Spec = SpecBase Info VName -- | An Futhark program with type information. type Prog = ProgBase Info VName -- | A known type arg with shape annotations. type StructTypeArg = TypeArg Size -- | A type-checked type parameter. type TypeParam = TypeParamBase VName -- | A known scalar type with no shape annotations. type ScalarType = ScalarTypeBase () -- | A type-checked case (of a match expression). type Case = CaseBase Info VName
null
https://raw.githubusercontent.com/diku-dk/futhark/5a0507692af97edcfb392f29ae9489694ed22913/src/Language/Futhark.hs
haskell
| An identifier with type- and aliasing information. | An index with type information. | A slice with type information. | An expression with type information. | An application expression with type information. | A pattern with type information. | An constant declaration with type information. | A type binding with type information. | A type-checked module binding. | A type-checked module type binding. | A type-checked module expression. | A type-checked module parameter. | A type-checked module type expression. | A type-checked declaration. | A type-checked specification. | An Futhark program with type information. | A known type arg with shape annotations. | A type-checked type parameter. | A known scalar type with no shape annotations. | A type-checked case (of a match expression).
| Re - export the external modules for convenience . module Language.Futhark ( module Language.Futhark.Syntax, module Language.Futhark.Prop, module Language.Futhark.FreeVars, module Language.Futhark.Pretty, Ident, DimIndex, Slice, AppExp, Exp, Pat, ModExp, ModParam, SigExp, ModBind, SigBind, ValBind, Dec, Spec, Prog, TypeBind, StructTypeArg, ScalarType, TypeParam, Case, ) where import Language.Futhark.FreeVars import Language.Futhark.Pretty import Language.Futhark.Prop import Language.Futhark.Syntax type Ident = IdentBase Info VName type DimIndex = DimIndexBase Info VName type Slice = SliceBase Info VName type Exp = ExpBase Info VName type AppExp = AppExpBase Info VName type Pat = PatBase Info VName type ValBind = ValBindBase Info VName type TypeBind = TypeBindBase Info VName type ModBind = ModBindBase Info VName type SigBind = SigBindBase Info VName type ModExp = ModExpBase Info VName type ModParam = ModParamBase Info VName type SigExp = SigExpBase Info VName type Dec = DecBase Info VName type Spec = SpecBase Info VName type Prog = ProgBase Info VName type StructTypeArg = TypeArg Size type TypeParam = TypeParamBase VName type ScalarType = ScalarTypeBase () type Case = CaseBase Info VName
590e6523482553ae587a83e19f2cecb33fe2a8c1d63ea899b0bc54db68c2c6d2
rd--/hsc3
lfTri.help.hs
-- lfTri ; see <> lfTri ar 500 1 * 0.1 lfTri ; used as both Oscillator and LFO lfTri ar (lfTri kr 4 0 * 400 + 400) 0 * 0.1 -- lfTri ; multiple phases let f = lfTri kr 0.4 (mce [0..3]) * 200 + 400 in mix (lfTri ar f 0 * 0.1) lfTri ; let x = midiCps (mouseX kr 20 72 Linear 0.2) e = xLine kr 0.01 1 20 DoNothing o1 = triAS 25 x * (1 - e) o2 = lfTri ar x 0 * e in mce2 o1 o2 * 0.1 lfTri ; c.f . dpw3Tri fast sweeps lfTri ar (mouseX kr 200 12000 Exponential 0.2) 0 * 0.1 lfTri ; c.f . dpw3Tri efficiency let f = X.randNId 50 'α' 50 5000 in splay (lfTri ar f 0) 1 0.1 0 True ---- ; drawings Sound.Sc3.Plot.plot_ugen1 0.1 (lfTri ar 40 0) Sound.Sc3.Plot.plot_ugen1 0.1 (lfTri ar (xLine kr 1 800 0.1 DoNothing) 0)
null
https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Ugen/lfTri.help.hs
haskell
lfTri ; see <> lfTri ; multiple phases -- ; drawings
lfTri ar 500 1 * 0.1 lfTri ; used as both Oscillator and LFO lfTri ar (lfTri kr 4 0 * 400 + 400) 0 * 0.1 let f = lfTri kr 0.4 (mce [0..3]) * 200 + 400 in mix (lfTri ar f 0 * 0.1) lfTri ; let x = midiCps (mouseX kr 20 72 Linear 0.2) e = xLine kr 0.01 1 20 DoNothing o1 = triAS 25 x * (1 - e) o2 = lfTri ar x 0 * e in mce2 o1 o2 * 0.1 lfTri ; c.f . dpw3Tri fast sweeps lfTri ar (mouseX kr 200 12000 Exponential 0.2) 0 * 0.1 lfTri ; c.f . dpw3Tri efficiency let f = X.randNId 50 'α' 50 5000 in splay (lfTri ar f 0) 1 0.1 0 True Sound.Sc3.Plot.plot_ugen1 0.1 (lfTri ar 40 0) Sound.Sc3.Plot.plot_ugen1 0.1 (lfTri ar (xLine kr 1 800 0.1 DoNothing) 0)
31be8ce16367687328b7054cb8600f372012a4327af20dbf49e16fd434fae043
neongreen/haskell-ex
BigInt.hs
module BigInt where import Data.List import Data.Monoid data Sign = Pos | Neg deriving (Eq, Show) -- | A representation of a natural (non-negative) number: 0 is @[]@ , 123 is @[3,2,1]@. type Nat = [Int] data BigInt = BigInt { -- | Sign (positive or negative). 0 is considered positive. sign :: Sign, nat :: Nat } deriving (Eq, Show) instance Ord BigInt where compare a b = case (sign a, sign b) of (Pos, Pos) -> compareNat (nat a) (nat b) (Neg, Neg) -> compareNat (nat b) (nat a) (Neg, Pos) -> LT (Pos, Neg) -> GT compareNat :: Nat -> Nat -> Ordering compareNat (a:as) (b:bs) = compareNat as bs <> compare a b compareNat [] [] = EQ compareNat [] _ = LT compareNat _ [] = GT | Bring all digits into the ( 0,9 ) interval and remove leading zeroes . Deals both with overflow and underflow : > > > normalise [ 12,10,5 ] [ 2,1,6 ] > > > normalise [ -1,9 ] [ 9,8 ] Bring all digits into the (0,9) interval and remove leading zeroes. Deals both with overflow and underflow: >>> normalise [12,10,5] [2,1,6] >>> normalise [-1,9] [9,8] -} normalise :: Nat -> Nat normalise = dropWhileEnd (== 0) . go where go [] = [] go [x] | x < 0 = error "normalise: negative number" | x <= 9 = [x] | otherwise = x `mod` 10 : go [x `div` 10] go (x:y:zs) = x' : go ((y+d):zs) where (d, x') = divMod x 10 zipDigits :: (Int -> Int -> Int) -> Nat -> Nat -> Nat zipDigits f [] [] = [] zipDigits f (x:xs) [] = f x 0 : zipDigits f xs [] zipDigits f [] (y:ys) = f 0 y : zipDigits f [] ys zipDigits f (x:xs) (y:ys) = f x y : zipDigits f xs ys addNat :: Nat -> Nat -> Nat addNat a b = normalise (zipDigits (+) a b) subNat :: Nat -> Nat -> Nat subNat a b = normalise (zipDigits (-) a b) mulNat :: Nat -> Nat -> Nat mulNat a b = normalise $ foldr (zipDigits (+)) [] partials where partials = [replicate i 0 ++ map (*x) b | (i, x) <- zip [0..] a] biToInteger :: BigInt -> Integer biToInteger (BigInt Pos xs) = natToInteger xs biToInteger (BigInt Neg xs) = negate (natToInteger xs) natToInteger :: Nat -> Integer natToInteger = sum . zipWith (*) (iterate (10*) 1) . map toInteger integerToNat :: Integer -> Nat integerToNat 0 = [] integerToNat n = fromInteger m : integerToNat d where (d, m) = divMod n 10 instance Num BigInt where fromInteger n = BigInt { sign = if n >= 0 then Pos else Neg, nat = integerToNat (abs n) } negate (BigInt Pos []) = BigInt Pos [] negate (BigInt Pos xs) = BigInt Neg xs negate (BigInt Neg xs) = BigInt Pos xs abs bi = bi {sign = Pos} signum 0 = 0 signum bi = bi {nat = [1]} (+) a b = case (sign a, sign b) of (Pos, Pos) -> BigInt {sign = Pos, nat = addNat (nat a) (nat b)} (Neg, Neg) -> BigInt {sign = Neg, nat = addNat (nat a) (nat b)} (Pos, Neg) | a >= (-b) -> BigInt {sign = Pos, nat = subNat (nat a) (nat b)} | otherwise -> BigInt {sign = Neg, nat = subNat (nat b) (nat a)} (Neg, Pos) -> b + a -- just use the (Pos, Neg) case (*) a b = BigInt { sign = if a == 0 || b == 0 || sign a == sign b then Pos else Neg, nat = mulNat (nat a) (nat b) }
null
https://raw.githubusercontent.com/neongreen/haskell-ex/345115444fdf370a43390fd942e2851b9b1963ad/week2/bigint/neongreen/src/BigInt.hs
haskell
| A representation of a natural (non-negative) number: | Sign (positive or negative). 0 is considered positive. just use the (Pos, Neg) case
module BigInt where import Data.List import Data.Monoid data Sign = Pos | Neg deriving (Eq, Show) 0 is @[]@ , 123 is @[3,2,1]@. type Nat = [Int] data BigInt = BigInt { sign :: Sign, nat :: Nat } deriving (Eq, Show) instance Ord BigInt where compare a b = case (sign a, sign b) of (Pos, Pos) -> compareNat (nat a) (nat b) (Neg, Neg) -> compareNat (nat b) (nat a) (Neg, Pos) -> LT (Pos, Neg) -> GT compareNat :: Nat -> Nat -> Ordering compareNat (a:as) (b:bs) = compareNat as bs <> compare a b compareNat [] [] = EQ compareNat [] _ = LT compareNat _ [] = GT | Bring all digits into the ( 0,9 ) interval and remove leading zeroes . Deals both with overflow and underflow : > > > normalise [ 12,10,5 ] [ 2,1,6 ] > > > normalise [ -1,9 ] [ 9,8 ] Bring all digits into the (0,9) interval and remove leading zeroes. Deals both with overflow and underflow: >>> normalise [12,10,5] [2,1,6] >>> normalise [-1,9] [9,8] -} normalise :: Nat -> Nat normalise = dropWhileEnd (== 0) . go where go [] = [] go [x] | x < 0 = error "normalise: negative number" | x <= 9 = [x] | otherwise = x `mod` 10 : go [x `div` 10] go (x:y:zs) = x' : go ((y+d):zs) where (d, x') = divMod x 10 zipDigits :: (Int -> Int -> Int) -> Nat -> Nat -> Nat zipDigits f [] [] = [] zipDigits f (x:xs) [] = f x 0 : zipDigits f xs [] zipDigits f [] (y:ys) = f 0 y : zipDigits f [] ys zipDigits f (x:xs) (y:ys) = f x y : zipDigits f xs ys addNat :: Nat -> Nat -> Nat addNat a b = normalise (zipDigits (+) a b) subNat :: Nat -> Nat -> Nat subNat a b = normalise (zipDigits (-) a b) mulNat :: Nat -> Nat -> Nat mulNat a b = normalise $ foldr (zipDigits (+)) [] partials where partials = [replicate i 0 ++ map (*x) b | (i, x) <- zip [0..] a] biToInteger :: BigInt -> Integer biToInteger (BigInt Pos xs) = natToInteger xs biToInteger (BigInt Neg xs) = negate (natToInteger xs) natToInteger :: Nat -> Integer natToInteger = sum . zipWith (*) (iterate (10*) 1) . map toInteger integerToNat :: Integer -> Nat integerToNat 0 = [] integerToNat n = fromInteger m : integerToNat d where (d, m) = divMod n 10 instance Num BigInt where fromInteger n = BigInt { sign = if n >= 0 then Pos else Neg, nat = integerToNat (abs n) } negate (BigInt Pos []) = BigInt Pos [] negate (BigInt Pos xs) = BigInt Neg xs negate (BigInt Neg xs) = BigInt Pos xs abs bi = bi {sign = Pos} signum 0 = 0 signum bi = bi {nat = [1]} (+) a b = case (sign a, sign b) of (Pos, Pos) -> BigInt {sign = Pos, nat = addNat (nat a) (nat b)} (Neg, Neg) -> BigInt {sign = Neg, nat = addNat (nat a) (nat b)} (Pos, Neg) | a >= (-b) -> BigInt {sign = Pos, nat = subNat (nat a) (nat b)} | otherwise -> BigInt {sign = Neg, nat = subNat (nat b) (nat a)} (*) a b = BigInt { sign = if a == 0 || b == 0 || sign a == sign b then Pos else Neg, nat = mulNat (nat a) (nat b) }
5d3372be949cff93665acc77ebc8389a4f22a137827b9fcc00efc67ba4ae3c64
solita/mnt-teet
user_info.cljs
(ns teet.user.user-info "Show user info in the UI, automatically resolved user information. FIXME: remove after dummy users are not needed" (:require [teet.user.user-model :as user-model] [teet.app-state :as app-state])) (def mock-users [{:user/id #uuid "4c8ec140-4bd8-403b-866f-d2d5db9bdf74" :user/person-id "12345678900" :user/given-name "Danny D." :user/family-name "Manager" :user/email "" :user/organization "Maanteeamet"} {:user/id #uuid "ccbedb7b-ab30-405c-b389-292cdfe85271" :user/person-id "33445566770" :user/given-name "Carla" :user/family-name "Consultant" :user/email "" :user/organization "ACME Road Consulting, Ltd."} {:user/id #uuid "fa8af5b7-df45-41ba-93d0-603c543c880d" :user/person-id "94837264730" :user/given-name "Benjamin" :user/family-name "Boss" :user/email "" :user/organization "Maanteeamet"} {:user/id #uuid "fa8af5b7-df45-41ba-93d0-603c543c8801" :user/person-id "12345678955" :user/given-name "Irma I." :user/family-name "Consultant" :user/email "" :user/organization "Maanteeamet"}]) (def user-name user-model/user-name) (def user-name-and-email user-model/user-name-and-email) (defn list-user-ids [] (map :user/id mock-users)) (defn me [] (user-name @app-state/user))
null
https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/frontend/src/cljs/teet/user/user_info.cljs
clojure
(ns teet.user.user-info "Show user info in the UI, automatically resolved user information. FIXME: remove after dummy users are not needed" (:require [teet.user.user-model :as user-model] [teet.app-state :as app-state])) (def mock-users [{:user/id #uuid "4c8ec140-4bd8-403b-866f-d2d5db9bdf74" :user/person-id "12345678900" :user/given-name "Danny D." :user/family-name "Manager" :user/email "" :user/organization "Maanteeamet"} {:user/id #uuid "ccbedb7b-ab30-405c-b389-292cdfe85271" :user/person-id "33445566770" :user/given-name "Carla" :user/family-name "Consultant" :user/email "" :user/organization "ACME Road Consulting, Ltd."} {:user/id #uuid "fa8af5b7-df45-41ba-93d0-603c543c880d" :user/person-id "94837264730" :user/given-name "Benjamin" :user/family-name "Boss" :user/email "" :user/organization "Maanteeamet"} {:user/id #uuid "fa8af5b7-df45-41ba-93d0-603c543c8801" :user/person-id "12345678955" :user/given-name "Irma I." :user/family-name "Consultant" :user/email "" :user/organization "Maanteeamet"}]) (def user-name user-model/user-name) (def user-name-and-email user-model/user-name-and-email) (defn list-user-ids [] (map :user/id mock-users)) (defn me [] (user-name @app-state/user))
10bab31c297cecc5c7ca2ed6714d36fca3d91a13d1444a649f61d34eef3d9065
webyrd/mediKanren
mk.rkt
#lang racket/base (require racket/list racket/include racket/stream ) (provide run run* run-stream == =/= fresh conde symbolo numbero absento project var? fail succeed choice inc unify walk walk* mplus mplus* bind bind* take take-stream reify ) ;; extra stuff for racket ;; due mostly to samth (define (list-sort f l) (sort l f)) (define (remp f l) (filter-not f l)) (define (call-with-string-output-port f) (define p (open-output-string)) (f p) (get-output-string p)) (define (exists f l) (ormap f l)) (define for-all andmap) (define (find f l) (cond [(memf f l) => car] [else #f])) (define memp memf) (define (var*? v) (var? (car v))) ; Substitution representation (define empty-subst-map (hasheq)) (define subst-map-length hash-count) ; Returns #f if not found, or a pair of u and the result of the lookup. ; This distinguishes between #f indicating absence and being the result. (define subst-map-lookup (lambda (u S) (hash-ref S u unbound))) (define (subst-map-add S var val) (hash-set S var val)) (define subst-map-eq? eq?) Constraint store representation (define empty-C (hasheq)) (define set-c (lambda (v c st) (state (state-S st) (hash-set (state-C st) v c)))) (define lookup-c (lambda (v st) (hash-ref (state-C st) v empty-c))) (define remove-c (lambda (v st) (state (state-S st) (hash-remove (state-C st) v)))) ; Scope object. ; Used to determine whether a branch has occured between variable creation ; and unification to allow the set-var-val! optimization in subst-add. Both variables ; and substitutions will contain a scope. When a substitution flows through a ; conde it is assigned a new scope. ; Creates a new scope that is not scope-eq? to any other scope (define new-scope (lambda () (list 'scope))) ; Scope used when variable bindings should always be made in the substitution, ; as in disequality solving and reification. We don't want to set-var-val! a ; variable when checking if a disequality constraint holds! (define nonlocal-scope (list 'non-local-scope)) (define scope-eq? eq?) ; Logic variable object. ; Contains: ; val - value for variable assigned by unification using set-var-val! optimization. ; unbound if not yet set or stored in substitution. ; scope - scope that the variable was created in. idx - unique numeric index for the variable . Used by the trie substitution representation . ; Variable objects are compared by object identity. ; The unique val for variables that have not yet been bound to a value ; or are bound in the substitution (define unbound (list 'unbound)) (define var (let ((counter -1)) (lambda (scope) (set! counter (+ 1 counter)) (vector unbound scope counter)))) ; Vectors are not allowed as terms, so terms that are vectors are variables. (define var? (lambda (x) (vector? x))) (define var-eq? eq?) (define var-val (lambda (x) (vector-ref x 0))) (define set-var-val! (lambda (x v) (vector-set! x 0 v))) (define var-scope (lambda (x) (vector-ref x 1))) (define var-idx (lambda (x) (vector-ref x 2))) ; Substitution object. ; Contains: ; map - mapping of variables to values ; scope - scope at current program point, for set-var-val! optimization. Updated at conde. ; Included in the substitution because it is required to fully define the substitution ; and how it is to be extended. ; ; Implementation of the substitution map depends on the Scheme used, as we need a map. See mk.rkt and mk-vicare.scm . (define subst (lambda (mapping scope) (cons mapping scope))) (define subst-map car) (define subst-scope cdr) (define subst-length (lambda (S) (subst-map-length (subst-map S)))) (define subst-with-scope (lambda (S new-scope) (subst (subst-map S) new-scope))) (define empty-subst (subst empty-subst-map (new-scope))) (define subst-add (lambda (S x v) ; set-var-val! optimization: set the value directly on the variable ; object if we haven't branched since its creation ; (the scope of the variable and the substitution are the same). ; Otherwise extend the substitution mapping. (if (scope-eq? (var-scope x) (subst-scope S)) (begin (set-var-val! x v) S) (subst (subst-map-add (subst-map S) x v) (subst-scope S))))) (define subst-lookup (lambda (u S) ; set-var-val! optimization. ; Tried checking the scope here to avoid a subst-map-lookup ; if it was definitely unbound, but that was slower. (if (not (eq? (var-val u) unbound)) (var-val u) (subst-map-lookup u (subst-map S))))) ; Association object. Describes an association mapping the lhs to the rhs . Returned by unification ; to describe the associations that were added to the substitution (whose representation ; is opaque) and used to represent disequality constraints. (define lhs car) (define rhs cdr) Constraint record object . ; ; Describes the constraints attached to a single variable. ; ; Contains: T - type constraint . ' symbolo ' or # f to indicate no constraint ; D - list of disequality constraints. Each disequality is a list of associations. ; The constraint is violated if all associated variables are equal in the ; substitution simultaneously. D could contain duplicate constraints (created ; by distinct =/= calls). A given disequality constraint is only attached to one of the variables involved , as all components of the constraint must be ; violated to cause failure. A - list of absento constraints . Each constraint is a ground atom . The list contains ; no duplicates. (define empty-c `(#f () ())) (define c-T (lambda (c) (car c))) (define c-D (lambda (c) (cadr c))) (define c-A (lambda (c) (caddr c))) (define c-with-T (lambda (c T) (list T (c-D c) (c-A c)))) (define c-with-D (lambda (c D) (list (c-T c) D (c-A c)))) (define c-with-A (lambda (c A) (list (c-T c) (c-D c) A))) Constraint store object . ; Mapping of representative variable to constraint record. Constraints are ; always on the representative element and must be moved / merged when that ; element changes. ; Implementation depends on the Scheme used, as we need a map. See mk.rkt and mk-vicare.scm . State object . The state is the value that is passed through the search . ; Contains: ; S - the substitution ; C - the constraint store (define state (lambda (S C) (cons S C))) (define state-S (lambda (st) (car st))) (define state-C (lambda (st) (cdr st))) (define empty-state (state empty-subst empty-C)) (define state-with-scope (lambda (st new-scope) (state (subst-with-scope (state-S st) new-scope) (state-C st)))) Unification (define walk (lambda (u S) (if (var? u) (let ((val (subst-lookup u S))) (if (eq? val unbound) u (walk val S))) u))) (define occurs-check (lambda (x v S) (let ((v (walk v S))) (cond ((var? v) (var-eq? v x)) ((pair? v) (or (occurs-check x (car v) S) (occurs-check x (cdr v) S))) (else #f))))) (define ext-s-check (lambda (x v S) (cond ((occurs-check x v S) (values #f #f)) (else (values (subst-add S x v) `((,x . ,v))))))) ; Returns as values the extended substitution and a list of associations added during the unification , or ( values # f # f ) if the unification failed . ; ; Right now appends the list of added values from sub-unifications. Alternatively ; could be threaded monadically, which could be faster or slower. (define unify (lambda (u v s) (let ((u (walk u s)) (v (walk v s))) (cond ((eq? u v) (values s '())) ((var? u) (ext-s-check u v s)) ((var? v) (ext-s-check v u s)) ((and (pair? u) (pair? v)) (let-values (((s added-car) (unify (car u) (car v) s))) (if s (let-values (((s added-cdr) (unify (cdr u) (cdr v) s))) (values s (append added-car added-cdr))) (values #f #f)))) ((equal? u v) (values s '())) (else (values #f #f)))))) (define unify* (lambda (S+ S) (unify (map lhs S+) (map rhs S+) S))) Search SearchStream : # f | Procedure | State | ( Pair State ( - > SearchStream ) ) SearchStream constructor types . Names inspired by the plus monad ? ; -> SearchStream (define mzero (lambda () #f)) ; c: State ; -> SearchStream (define unit (lambda (c) c)) ; c: State ; f: (-> SearchStream) ; -> SearchStream ; ; f is a thunk to avoid unnecessary computation in the case that c is the ; last answer needed to satisfy the query. (define choice (lambda (c f) (cons c f))) e : SearchStream ; -> (-> SearchStream) (define-syntax inc (syntax-rules () ((_ e) (lambda () e)))) ; Goal: (State -> SearchStream) e : SearchStream ; -> Goal (define-syntax lambdag@ (syntax-rules () ((_ (st) e) (lambda (st) e)))) ; Match on search streams. The state type must not be a pair with a procedure ; in its cdr. ; ; (() e0) failure ; ((f) e1) inc for interleaving. separate from success or failure to ensure ; it goes all the way to the top of the tree. ; ((c) e2) single result. Used rather than (choice c (inc (mzero))) to avoid ; returning to search a part of the tree that will inevitably fail. ; ((c f) e3) multiple results. (define-syntax case-inf (syntax-rules () ((_ e (() e0) ((f^) e1) ((c^) e2) ((c f) e3)) (let ((c-inf e)) (cond ((not c-inf) e0) ((procedure? c-inf) (let ((f^ c-inf)) e1)) ((not (and (pair? c-inf) (procedure? (cdr c-inf)))) (let ((c^ c-inf)) e2)) (else (let ((c (car c-inf)) (f (cdr c-inf))) e3))))))) ; c-inf: SearchStream ; f: (-> SearchStream) ; -> SearchStream ; f is a thunk to avoid unnecesarry computation in the case that the first ; answer produced by c-inf is enough to satisfy the query. (define mplus (lambda (c-inf f) (case-inf c-inf (() (f)) ((f^) (inc (mplus (f) f^))) ((c) (choice c f)) ((c f^) (choice c (inc (mplus (f) f^))))))) ; c-inf: SearchStream ; g: Goal ; -> SearchStream (define bind (lambda (c-inf g) (case-inf c-inf (() (mzero)) ((f) (inc (bind (f) g))) ((c) (g c)) ((c f) (mplus (g c) (inc (bind (f) g))))))) Int , SearchStream - > ( ) (define take (lambda (n f) (cond ((and n (zero? n)) '()) (else (case-inf (f) (() '()) ((f) (take n f)) ((c) (cons c '())) ((c f) (cons c (take (and n (- n 1)) f)))))))) (define take-stream (lambda (f) (case-inf (f) (() '()) ((f) (take-stream f)) ((c) (stream-cons c '())) ((c f) (stream-cons c (take-stream f)))))) ; -> SearchStream (define-syntax bind* (syntax-rules () ((_ e) e) ((_ e g0 g ...) (bind* (bind e g0) g ...)))) ; -> SearchStream (define-syntax mplus* (syntax-rules () ((_ e) e) ((_ e0 e ...) (mplus e0 (inc (mplus* e ...)))))) ; -> Goal (define-syntax fresh (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (st) ; this inc triggers interleaving (inc (let ((scope (subst-scope (state-S st)))) (let ((x (var scope)) ...) (bind* (g0 st) g ...)))))))) ; -> Goal (define-syntax conde (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (st) ; this inc triggers interleaving (inc (let ((st (state-with-scope st (new-scope)))) (mplus* (bind* (g0 st) g ...) (bind* (g1 st) g^ ...) ...))))))) (define-syntax run (syntax-rules () ((_ n (q) g0 g ...) (take n (inc ((fresh (q) g0 g ... (lambdag@ (st) (let ((st (state-with-scope st nonlocal-scope))) (let ((z ((reify q) st))) (choice z (lambda () (lambda () #f))))))) empty-state)))) ((_ n (q0 q1 q ...) g0 g ...) (run n (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x)))))) (define-syntax run* (syntax-rules () ((_ (q0 q ...) g0 g ...) (run #f (q0 q ...) g0 g ...)))) (define-syntax run-stream (syntax-rules () ((_ (q) g0 g ...) (take-stream (inc ((fresh (q) g0 g ... (lambdag@ (st) (let ((st (state-with-scope st nonlocal-scope))) (let ((z ((reify q) st))) (choice z (lambda () (lambda () #f))))))) empty-state)))) ((_ (q0 q1 q ...) g0 g ...) (run-stream (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x)))))) ; Constraints ; C refers to the constraint store map ; c refers to an individual constraint record ; Constraint: State -> #f | State ; ( note that a Constraint is a Goal but a Goal is not a Constraint . Constraint implementations currently use this more restrained type . See ` and - foldl ` ; and `update-constraints`.) ; Requirements for type constraints: 1 . Must be positive , not negative . not - pairo would n't work . 2 . Each type must have infinitely many possible values to avoid ; incorrectness in combination with disequality constraints, like: ; (fresh (x) (booleano x) (=/= x #t) (=/= x #f)) (define type-constraint (lambda (type-pred type-id) (lambda (u) (lambdag@ (st) (let ((term (walk u (state-S st)))) (cond ((type-pred term) st) ((var? term) (let* ((c (lookup-c term st)) (T (c-T c))) (cond ((eq? T type-id) st) ((not T) (set-c term (c-with-T c type-id) st)) (else #f)))) (else #f))))))) (define symbolo (type-constraint symbol? 'symbolo)) (define numbero (type-constraint number? 'numbero)) (define (add-to-D st v d) (let* ((c (lookup-c v st)) (c^ (c-with-D c (cons d (c-D c))))) (set-c v c^ st))) (define =/=* (lambda (S+) (lambdag@ (st) (let-values (((S added) (unify* S+ (subst-with-scope (state-S st) nonlocal-scope)))) (cond ((not S) st) ((null? added) #f) (else Choose one of the disequality elements ( el ) to attach the constraint to . Only ; need to choose one because all must fail to cause the constraint to fail. (let ((el (car added))) (let ((st (add-to-D st (car el) added))) (if (var? (cdr el)) (add-to-D st (cdr el) added) st))))))))) (define =/= (lambda (u v) (=/=* `((,u . ,v))))) (define absento (lambda (ground-atom term) (lambdag@ (st) (let ((term (walk term (state-S st)))) (cond ((pair? term) (let ((st^ ((absento ground-atom (car term)) st))) (and st^ ((absento ground-atom (cdr term)) st^)))) ((eqv? term ground-atom) #f) ((var? term) (let* ((c (lookup-c term st)) (A (c-A c))) (if (memv ground-atom A) st (let ((c^ (c-with-A c (cons ground-atom A)))) (set-c term c^ st))))) (else st)))))) Fold lst with proc and initial value init . If proc ever returns # f , ; return with #f immediately. Used for applying a series of constraints ; to a state, failing if any operation fails. (define (and-foldl proc init lst) (if (null? lst) init (let ([res (proc (car lst) init)]) (and res (and-foldl proc res (cdr lst)))))) (define == (lambda (u v) (lambdag@ (st) (let-values (((S added) (unify u v (state-S st)))) (if S (and-foldl update-constraints (state S (state-C st)) added) #f))))) ; Not fully optimized. Could do absento update with fewer hash-refs / hash-sets. (define update-constraints (lambda (a st) (let ([old-c (lookup-c (lhs a) st)]) (if (eq? old-c empty-c) st (let ((st (remove-c (lhs a) st))) (and-foldl (lambda (op st) (op st)) st (append (if (eq? (c-T old-c) 'symbolo) (list (symbolo (rhs a))) '()) (if (eq? (c-T old-c) 'numbero) (list (numbero (rhs a))) '()) (map (lambda (atom) (absento atom (rhs a))) (c-A old-c)) (map (lambda (d) (=/=* d)) (c-D old-c))))))))) ; Reification (define walk* (lambda (v S) (let ((v (walk v S))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) S) (walk* (cdr v) S))) (else v))))) (define vars (lambda (term acc) (cond ((var? term) (cons term acc)) ((pair? term) (vars (cdr term) (vars (car term) acc))) (else acc)))) (define-syntax project (syntax-rules () ((_ (x ...) g g* ...) (lambdag@ (st) (let ((x (walk* x (state-S st))) ...) ((fresh () g g* ...) st)))))) ; Create a constraint store of the old representation from a state object, ; so that we can use the old reifier. Only accumulates constraints related ; to the variable being reified which makes things a bit faster. (define c-from-st (lambda (st x) (let ((vs (vars (walk* x (state-S st)) '()))) (foldl (lambda (v c-store) (let ((c (lookup-c v st))) (let ((S (state-S st)) (D (c->D c-store)) (Y (c->Y c-store)) (N (c->N c-store)) (T (c->T c-store)) (T^ (c-T c)) (D^ (c-D c)) (A^ (c-A c))) `(,S ,(append D^ D) ,(if (eq? T^ 'symbolo) (cons v Y) Y) ,(if (eq? T^ 'numbero) (cons v N) N) ,(append (map (lambda (atom) (cons atom v)) A^) T))))) `(,(state-S st) () () () ()) (remove-duplicates vs))))) (define reify (lambda (x) (lambda (st) (let ((c (c-from-st st x))) (let ((c (cycle c))) (let* ((S (c->S c)) (D (walk* (c->D c) S)) (Y (walk* (c->Y c) S)) (N (walk* (c->N c) S)) (T (walk* (c->T c) S))) (let ((v (walk* x S))) (let ((R (reify-S v (subst empty-subst-map nonlocal-scope)))) (reify+ v R (let ((D (remp (lambda (d) (let ((dw (walk* d S))) (anyvar? dw R))) (rem-xx-from-d c)))) (rem-subsumed D)) (remp (lambda (y) (var? (walk y R))) Y) (remp (lambda (n) (var? (walk n R))) N) (remp (lambda (t) (anyvar? t R)) T)))))))))) ; Bits from the old constraint implementation, still used for reification. ; In this part of the code, c refers to the ; old constraint store with components: ; S - substitution ; D - disequality constraints ; Y - symbolo ; N - numbero ; T - absento (define c->S (lambda (c) (car c))) (define c->D (lambda (c) (cadr c))) (define c->Y (lambda (c) (caddr c))) (define c->N (lambda (c) (cadddr c))) (define c->T (lambda (c) (cadddr (cdr c)))) ; Syntax for reification goal objects using the old constraint store (define-syntax lambdar@ (syntax-rules (:) ((_ (c) e) (lambda (c) e)) ((_ (c : S D Y N T) e) (lambda (c) (let ((S (c->S c)) (D (c->D c)) (Y (c->Y c)) (N (c->N c)) (T (c->T c))) e))))) (define tagged? (lambda (S Y y^) (exists (lambda (y) (eqv? (walk y S) y^)) Y))) (define untyped-var? (lambda (S Y N t^) (let ((in-type? (lambda (y) (var-eq? (walk y S) t^)))) (and (var? t^) (not (exists in-type? Y)) (not (exists in-type? N)))))) (define reify-S (lambda (v S) (let ((v (walk v S))) (cond ((var? v) (let ((n (subst-length S))) (let ((name (reify-name n))) (subst-add S v name)))) ((pair? v) (let ((S (reify-S (car v) S))) (reify-S (cdr v) S))) (else S))))) (define reify-name (lambda (n) (string->symbol (string-append "_" "." (number->string n))))) (define drop-dot (lambda (X) (map (lambda (t) (let ((a (lhs t)) (d (rhs t))) `(,a ,d))) X))) (define sorter (lambda (ls) (list-sort lex<=? ls))) (define lex<=? (lambda (x y) (string<=? (datum->string x) (datum->string y)))) (define datum->string (lambda (x) (call-with-string-output-port (lambda (p) (display x p))))) (define anyvar? (lambda (u r) (cond ((pair? u) (or (anyvar? (car u) r) (anyvar? (cdr u) r))) (else (var? (walk u r)))))) (define member* (lambda (u v) (cond ((equal? u v) #t) ((pair? v) (or (member* u (car v)) (member* u (cdr v)))) (else #f)))) (define drop-N-b/c-const (lambdar@ (c : S D Y N T) (let ((const? (lambda (n) (not (var? (walk n S)))))) (cond ((find const? N) => (lambda (n) `(,S ,D ,Y ,(remq1 n N) ,T))) (else c))))) (define drop-Y-b/c-const (lambdar@ (c : S D Y N T) (let ((const? (lambda (y) (not (var? (walk y S)))))) (cond ((find const? Y) => (lambda (y) `(,S ,D ,(remq1 y Y) ,N ,T))) (else c))))) (define remq1 (lambda (elem ls) (cond ((null? ls) '()) ((eq? (car ls) elem) (cdr ls)) (else (cons (car ls) (remq1 elem (cdr ls))))))) (define same-var? (lambda (v) (lambda (v^) (and (var? v) (var? v^) (var-eq? v v^))))) (define find-dup (lambda (f S) (lambda (set) (let loop ((set^ set)) (cond ((null? set^) #f) (else (let ((elem (car set^))) (let ((elem^ (walk elem S))) (cond ((find (lambda (elem^^) ((f elem^) (walk elem^^ S))) (cdr set^)) elem) (else (loop (cdr set^)))))))))))) (define drop-N-b/c-dup-var (lambdar@ (c : S D Y N T) (cond (((find-dup same-var? S) N) => (lambda (n) `(,S ,D ,Y ,(remq1 n N) ,T))) (else c)))) (define drop-Y-b/c-dup-var (lambdar@ (c : S D Y N T) (cond (((find-dup same-var? S) Y) => (lambda (y) `(,S ,D ,(remq1 y Y) ,N ,T))) (else c)))) (define var-type-mismatch? (lambda (S Y N t1^ t2^) (cond ((num? S N t1^) (not (num? S N t2^))) ((sym? S Y t1^) (not (sym? S Y t2^))) (else #f)))) (define term-ununifiable? (lambda (S Y N t1 t2) (let ((t1^ (walk t1 S)) (t2^ (walk t2 S))) (cond ((or (untyped-var? S Y N t1^) (untyped-var? S Y N t2^)) #f) ((var? t1^) (var-type-mismatch? S Y N t1^ t2^)) ((var? t2^) (var-type-mismatch? S Y N t2^ t1^)) ((and (pair? t1^) (pair? t2^)) (or (term-ununifiable? S Y N (car t1^) (car t2^)) (term-ununifiable? S Y N (cdr t1^) (cdr t2^)))) (else (not (eqv? t1^ t2^))))))) (define T-term-ununifiable? (lambda (S Y N) (lambda (t1) (let ((t1^ (walk t1 S))) (letrec ((t2-check (lambda (t2) (let ((t2^ (walk t2 S))) (if (pair? t2^) (and (term-ununifiable? S Y N t1^ t2^) (t2-check (car t2^)) (t2-check (cdr t2^))) (term-ununifiable? S Y N t1^ t2^)))))) t2-check))))) (define num? (lambda (S N n) (let ((n (walk n S))) (cond ((var? n) (tagged? S N n)) (else (number? n)))))) (define sym? (lambda (S Y y) (let ((y (walk y S))) (cond ((var? y) (tagged? S Y y)) (else (symbol? y)))))) (define drop-T-b/c-Y-and-N (lambdar@ (c : S D Y N T) (let ((drop-t? (T-term-ununifiable? S Y N))) (cond ((find (lambda (t) ((drop-t? (lhs t)) (rhs t))) T) => (lambda (t) `(,S ,D ,Y ,N ,(remq1 t T)))) (else c))))) (define move-T-to-D-b/c-t2-atom (lambdar@ (c : S D Y N T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((and (not (untyped-var? S Y N t2^)) (not (pair? t2^))) (let ((T (remq1 t T))) `(,S ((,t) . ,D) ,Y ,N ,T))) (else #f)))) T)) (else c)))) (define terms-pairwise=? (lambda (pr-a^ pr-d^ t-a^ t-d^ S) (or (and (term=? pr-a^ t-a^ S) (term=? pr-d^ t-a^ S)) (and (term=? pr-a^ t-d^ S) (term=? pr-d^ t-a^ S))))) (define T-superfluous-pr? (lambda (S Y N T) (lambda (pr) (let ((pr-a^ (walk (lhs pr) S)) (pr-d^ (walk (rhs pr) S))) (cond ((exists (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S))) T) (for-all (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (or (not (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S)) (untyped-var? S Y N t-d^) (pair? t-d^)))) T)) (else #f)))))) (define drop-from-D-b/c-T (lambdar@ (c : S D Y N T) (cond ((find (lambda (d) (exists (T-superfluous-pr? S Y N T) d)) D) => (lambda (d) `(,S ,(remq1 d D) ,Y ,N ,T))) (else c)))) (define drop-t-b/c-t2-occurs-t1 (lambdar@ (c : S D Y N T) (cond ((find (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (mem-check t-d^ t-a^ S))) T) => (lambda (t) `(,S ,D ,Y ,N ,(remq1 t T)))) (else c)))) (define split-t-move-to-d-b/c-pair (lambdar@ (c : S D Y N T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((pair? t2^) (let ((ta `(,(lhs t) . ,(car t2^))) (td `(,(lhs t) . ,(cdr t2^)))) (let ((T `(,ta ,td . ,(remq1 t T)))) `(,S ((,t) . ,D) ,Y ,N ,T)))) (else #f)))) T)) (else c)))) (define find-d-conflict (lambda (S Y N) (lambda (D) (find (lambda (d) (exists (lambda (pr) (term-ununifiable? S Y N (lhs pr) (rhs pr))) d)) D)))) (define drop-D-b/c-Y-or-N (lambdar@ (c : S D Y N T) (cond (((find-d-conflict S Y N) D) => (lambda (d) `(,S ,(remq1 d D) ,Y ,N ,T))) (else c)))) (define cycle (lambdar@ (c) (let loop ((c^ c) (fns^ (LOF)) (n (length (LOF)))) (cond ((zero? n) c^) ((null? fns^) (loop c^ (LOF) n)) (else (let ((c^^ ((car fns^) c^))) (cond ((not (eq? c^^ c^)) (loop c^^ (cdr fns^) (length (LOF)))) (else (loop c^ (cdr fns^) (sub1 n)))))))))) (define mem-check (lambda (u t S) (let ((t (walk t S))) (cond ((pair? t) (or (term=? u t S) (mem-check u (car t) S) (mem-check u (cdr t) S))) (else (term=? u t S)))))) (define term=? (lambda (u t S) (let-values (((S added) (unify u t (subst-with-scope S nonlocal-scope)))) (and S (null? added))))) (define ground-non-<type>? (lambda (pred) (lambda (u S) (let ((u (walk u S))) (cond ((var? u) #f) (else (not (pred u)))))))) (define ground-non-symbol? (ground-non-<type>? symbol?)) (define ground-non-number? (ground-non-<type>? number?)) (define succeed (== #f #f)) (define fail (== #f #t)) (define ==fail-check (lambda (S0 D Y N T) (let ([S0 (subst-with-scope S0 nonlocal-scope)]) (cond ((atomic-fail-check S0 Y ground-non-symbol?) #t) ((atomic-fail-check S0 N ground-non-number?) #t) ((symbolo-numbero-fail-check S0 Y N) #t) ((=/=-fail-check S0 D) #t) ((absento-fail-check S0 T) #t) (else #f))))) (define atomic-fail-check (lambda (S A pred) (exists (lambda (a) (pred (walk a S) S)) A))) (define symbolo-numbero-fail-check (lambda (S A N) (let ((N (map (lambda (n) (walk n S)) N))) (exists (lambda (a) (exists (same-var? (walk a S)) N)) A)))) (define absento-fail-check (lambda (S T) (exists (lambda (t) (mem-check (lhs t) (rhs t) S)) T))) (define =/=-fail-check (lambda (S D) (exists (d-fail-check S) D))) (define d-fail-check (lambda (S) (lambda (d) (let-values (((S added) (unify* d S))) (and S (null? added)))))) (define reify+ (lambda (v R D Y N T) (form (walk* v R) (walk* D R) (walk* Y R) (walk* N R) (rem-subsumed-T (walk* T R))))) (define form (lambda (v D Y N T) (let ((fd (sort-D D)) (fy (sorter Y)) (fn (sorter N)) (ft (sorter T))) (let ((fd (if (null? fd) fd (let ((fd (drop-dot-D fd))) `((=/= . ,fd))))) (fy (if (null? fy) fy `((sym . ,fy)))) (fn (if (null? fn) fn `((num . ,fn)))) (ft (if (null? ft) ft (let ((ft (drop-dot ft))) `((absento . ,ft)))))) (cond ((and (null? fd) (null? fy) (null? fn) (null? ft)) v) (else (append `(,v) fd fn fy ft))))))) (define sort-D (lambda (D) (sorter (map sort-d D)))) (define sort-d (lambda (d) (list-sort (lambda (x y) (lex<=? (car x) (car y))) (map sort-pr d)))) (define drop-dot-D (lambda (D) (map drop-dot D))) (define lex<-reified-name? (lambda (r) (char<? (string-ref (datum->string r) 0) #\_))) (define sort-pr (lambda (pr) (let ((l (lhs pr)) (r (rhs pr))) (cond ((lex<-reified-name? r) pr) ((lex<=? r l) `(,r . ,l)) (else pr))))) (define rem-subsumed (lambda (D) (let rem-subsumed ((D D) (d^* '())) (cond ((null? D) d^*) ((or (subsumed? (car D) (cdr D)) (subsumed? (car D) d^*)) (rem-subsumed (cdr D) d^*)) (else (rem-subsumed (cdr D) (cons (car D) d^*))))))) (define subsumed? (lambda (d d*) (cond ((null? d*) #f) (else (let-values (((S ignore) (unify* d (subst empty-subst-map nonlocal-scope)))) (let-values (((S+ added) (unify* (car d*) S))) (or (and S+ (null? added)) (subsumed? d (cdr d*))))))))) (define rem-xx-from-d (lambdar@ (c : S D Y N T) (let ((D (walk* D S))) (remp not (map (lambda (d) (let-values (((S0 ignore) (unify* d S))) (cond ((not S0) #f) ((==fail-check S0 '() Y N T) #f) (else (let-values (((S added) (unify* d (subst empty-subst-map nonlocal-scope)))) added))))) D))))) (define rem-subsumed-T (lambda (T) (let rem-subsumed ((T T) (T^ '())) (cond ((null? T) T^) (else (let ((lit (lhs (car T))) (big (rhs (car T)))) (cond ((or (subsumed-T? lit big (cdr T)) (subsumed-T? lit big T^)) (rem-subsumed (cdr T) T^)) (else (rem-subsumed (cdr T) (cons (car T) T^)))))))))) (define subsumed-T? (lambda (lit big T) (cond ((null? T) #f) (else (let ((lit^ (lhs (car T))) (big^ (rhs (car T)))) (or (and (eq? big big^) (member* lit^ lit)) (subsumed-T? lit big (cdr T)))))))) (define LOF (lambda () `(,drop-N-b/c-const ,drop-Y-b/c-const ,drop-Y-b/c-dup-var ,drop-N-b/c-dup-var ,drop-D-b/c-Y-or-N ,drop-T-b/c-Y-and-N ,move-T-to-D-b/c-t2-atom ,split-t-move-to-d-b/c-pair ,drop-from-D-b/c-T ,drop-t-b/c-t2-occurs-t1)))
null
https://raw.githubusercontent.com/webyrd/mediKanren/a2b80ea94f66bcdd4305b9369ad4184c2afe9829/attic/pharos/mk.rkt
racket
extra stuff for racket due mostly to samth Substitution representation Returns #f if not found, or a pair of u and the result of the lookup. This distinguishes between #f indicating absence and being the result. Scope object. Used to determine whether a branch has occured between variable creation and unification to allow the set-var-val! optimization in subst-add. Both variables and substitutions will contain a scope. When a substitution flows through a conde it is assigned a new scope. Creates a new scope that is not scope-eq? to any other scope Scope used when variable bindings should always be made in the substitution, as in disequality solving and reification. We don't want to set-var-val! a variable when checking if a disequality constraint holds! Logic variable object. Contains: val - value for variable assigned by unification using set-var-val! optimization. unbound if not yet set or stored in substitution. scope - scope that the variable was created in. Variable objects are compared by object identity. The unique val for variables that have not yet been bound to a value or are bound in the substitution Vectors are not allowed as terms, so terms that are vectors are variables. Substitution object. Contains: map - mapping of variables to values scope - scope at current program point, for set-var-val! optimization. Updated at conde. Included in the substitution because it is required to fully define the substitution and how it is to be extended. Implementation of the substitution map depends on the Scheme used, as we need a map. See mk.rkt set-var-val! optimization: set the value directly on the variable object if we haven't branched since its creation (the scope of the variable and the substitution are the same). Otherwise extend the substitution mapping. set-var-val! optimization. Tried checking the scope here to avoid a subst-map-lookup if it was definitely unbound, but that was slower. Association object. to describe the associations that were added to the substitution (whose representation is opaque) and used to represent disequality constraints. Describes the constraints attached to a single variable. Contains: D - list of disequality constraints. Each disequality is a list of associations. The constraint is violated if all associated variables are equal in the substitution simultaneously. D could contain duplicate constraints (created by distinct =/= calls). A given disequality constraint is only attached to violated to cause failure. no duplicates. Mapping of representative variable to constraint record. Constraints are always on the representative element and must be moved / merged when that element changes. Implementation depends on the Scheme used, as we need a map. See mk.rkt Contains: S - the substitution C - the constraint store Returns as values the extended substitution and a list of associations added Right now appends the list of added values from sub-unifications. Alternatively could be threaded monadically, which could be faster or slower. -> SearchStream c: State -> SearchStream c: State f: (-> SearchStream) -> SearchStream f is a thunk to avoid unnecessary computation in the case that c is the last answer needed to satisfy the query. -> (-> SearchStream) Goal: (State -> SearchStream) -> Goal Match on search streams. The state type must not be a pair with a procedure in its cdr. (() e0) failure ((f) e1) inc for interleaving. separate from success or failure to ensure it goes all the way to the top of the tree. ((c) e2) single result. Used rather than (choice c (inc (mzero))) to avoid returning to search a part of the tree that will inevitably fail. ((c f) e3) multiple results. c-inf: SearchStream f: (-> SearchStream) -> SearchStream answer produced by c-inf is enough to satisfy the query. c-inf: SearchStream g: Goal -> SearchStream -> SearchStream -> SearchStream -> Goal this inc triggers interleaving -> Goal this inc triggers interleaving Constraints C refers to the constraint store map c refers to an individual constraint record Constraint: State -> #f | State and `update-constraints`.) Requirements for type constraints: incorrectness in combination with disequality constraints, like: (fresh (x) (booleano x) (=/= x #t) (=/= x #f)) need to choose one because all must fail to cause the constraint to fail. return with #f immediately. Used for applying a series of constraints to a state, failing if any operation fails. Not fully optimized. Could do absento update with fewer hash-refs / hash-sets. Reification Create a constraint store of the old representation from a state object, so that we can use the old reifier. Only accumulates constraints related to the variable being reified which makes things a bit faster. Bits from the old constraint implementation, still used for reification. In this part of the code, c refers to the old constraint store with components: S - substitution D - disequality constraints Y - symbolo N - numbero T - absento Syntax for reification goal objects using the old constraint store
#lang racket/base (require racket/list racket/include racket/stream ) (provide run run* run-stream == =/= fresh conde symbolo numbero absento project var? fail succeed choice inc unify walk walk* mplus mplus* bind bind* take take-stream reify ) (define (list-sort f l) (sort l f)) (define (remp f l) (filter-not f l)) (define (call-with-string-output-port f) (define p (open-output-string)) (f p) (get-output-string p)) (define (exists f l) (ormap f l)) (define for-all andmap) (define (find f l) (cond [(memf f l) => car] [else #f])) (define memp memf) (define (var*? v) (var? (car v))) (define empty-subst-map (hasheq)) (define subst-map-length hash-count) (define subst-map-lookup (lambda (u S) (hash-ref S u unbound))) (define (subst-map-add S var val) (hash-set S var val)) (define subst-map-eq? eq?) Constraint store representation (define empty-C (hasheq)) (define set-c (lambda (v c st) (state (state-S st) (hash-set (state-C st) v c)))) (define lookup-c (lambda (v st) (hash-ref (state-C st) v empty-c))) (define remove-c (lambda (v st) (state (state-S st) (hash-remove (state-C st) v)))) (define new-scope (lambda () (list 'scope))) (define nonlocal-scope (list 'non-local-scope)) (define scope-eq? eq?) idx - unique numeric index for the variable . Used by the trie substitution representation . (define unbound (list 'unbound)) (define var (let ((counter -1)) (lambda (scope) (set! counter (+ 1 counter)) (vector unbound scope counter)))) (define var? (lambda (x) (vector? x))) (define var-eq? eq?) (define var-val (lambda (x) (vector-ref x 0))) (define set-var-val! (lambda (x v) (vector-set! x 0 v))) (define var-scope (lambda (x) (vector-ref x 1))) (define var-idx (lambda (x) (vector-ref x 2))) and mk-vicare.scm . (define subst (lambda (mapping scope) (cons mapping scope))) (define subst-map car) (define subst-scope cdr) (define subst-length (lambda (S) (subst-map-length (subst-map S)))) (define subst-with-scope (lambda (S new-scope) (subst (subst-map S) new-scope))) (define empty-subst (subst empty-subst-map (new-scope))) (define subst-add (lambda (S x v) (if (scope-eq? (var-scope x) (subst-scope S)) (begin (set-var-val! x v) S) (subst (subst-map-add (subst-map S) x v) (subst-scope S))))) (define subst-lookup (lambda (u S) (if (not (eq? (var-val u) unbound)) (var-val u) (subst-map-lookup u (subst-map S))))) Describes an association mapping the lhs to the rhs . Returned by unification (define lhs car) (define rhs cdr) Constraint record object . T - type constraint . ' symbolo ' or # f to indicate no constraint one of the variables involved , as all components of the constraint must be A - list of absento constraints . Each constraint is a ground atom . The list contains (define empty-c `(#f () ())) (define c-T (lambda (c) (car c))) (define c-D (lambda (c) (cadr c))) (define c-A (lambda (c) (caddr c))) (define c-with-T (lambda (c T) (list T (c-D c) (c-A c)))) (define c-with-D (lambda (c D) (list (c-T c) D (c-A c)))) (define c-with-A (lambda (c A) (list (c-T c) (c-D c) A))) Constraint store object . and mk-vicare.scm . State object . The state is the value that is passed through the search . (define state (lambda (S C) (cons S C))) (define state-S (lambda (st) (car st))) (define state-C (lambda (st) (cdr st))) (define empty-state (state empty-subst empty-C)) (define state-with-scope (lambda (st new-scope) (state (subst-with-scope (state-S st) new-scope) (state-C st)))) Unification (define walk (lambda (u S) (if (var? u) (let ((val (subst-lookup u S))) (if (eq? val unbound) u (walk val S))) u))) (define occurs-check (lambda (x v S) (let ((v (walk v S))) (cond ((var? v) (var-eq? v x)) ((pair? v) (or (occurs-check x (car v) S) (occurs-check x (cdr v) S))) (else #f))))) (define ext-s-check (lambda (x v S) (cond ((occurs-check x v S) (values #f #f)) (else (values (subst-add S x v) `((,x . ,v))))))) during the unification , or ( values # f # f ) if the unification failed . (define unify (lambda (u v s) (let ((u (walk u s)) (v (walk v s))) (cond ((eq? u v) (values s '())) ((var? u) (ext-s-check u v s)) ((var? v) (ext-s-check v u s)) ((and (pair? u) (pair? v)) (let-values (((s added-car) (unify (car u) (car v) s))) (if s (let-values (((s added-cdr) (unify (cdr u) (cdr v) s))) (values s (append added-car added-cdr))) (values #f #f)))) ((equal? u v) (values s '())) (else (values #f #f)))))) (define unify* (lambda (S+ S) (unify (map lhs S+) (map rhs S+) S))) Search SearchStream : # f | Procedure | State | ( Pair State ( - > SearchStream ) ) SearchStream constructor types . Names inspired by the plus monad ? (define mzero (lambda () #f)) (define unit (lambda (c) c)) (define choice (lambda (c f) (cons c f))) e : SearchStream (define-syntax inc (syntax-rules () ((_ e) (lambda () e)))) e : SearchStream (define-syntax lambdag@ (syntax-rules () ((_ (st) e) (lambda (st) e)))) (define-syntax case-inf (syntax-rules () ((_ e (() e0) ((f^) e1) ((c^) e2) ((c f) e3)) (let ((c-inf e)) (cond ((not c-inf) e0) ((procedure? c-inf) (let ((f^ c-inf)) e1)) ((not (and (pair? c-inf) (procedure? (cdr c-inf)))) (let ((c^ c-inf)) e2)) (else (let ((c (car c-inf)) (f (cdr c-inf))) e3))))))) f is a thunk to avoid unnecesarry computation in the case that the first (define mplus (lambda (c-inf f) (case-inf c-inf (() (f)) ((f^) (inc (mplus (f) f^))) ((c) (choice c f)) ((c f^) (choice c (inc (mplus (f) f^))))))) (define bind (lambda (c-inf g) (case-inf c-inf (() (mzero)) ((f) (inc (bind (f) g))) ((c) (g c)) ((c f) (mplus (g c) (inc (bind (f) g))))))) Int , SearchStream - > ( ) (define take (lambda (n f) (cond ((and n (zero? n)) '()) (else (case-inf (f) (() '()) ((f) (take n f)) ((c) (cons c '())) ((c f) (cons c (take (and n (- n 1)) f)))))))) (define take-stream (lambda (f) (case-inf (f) (() '()) ((f) (take-stream f)) ((c) (stream-cons c '())) ((c f) (stream-cons c (take-stream f)))))) (define-syntax bind* (syntax-rules () ((_ e) e) ((_ e g0 g ...) (bind* (bind e g0) g ...)))) (define-syntax mplus* (syntax-rules () ((_ e) e) ((_ e0 e ...) (mplus e0 (inc (mplus* e ...)))))) (define-syntax fresh (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (st) (inc (let ((scope (subst-scope (state-S st)))) (let ((x (var scope)) ...) (bind* (g0 st) g ...)))))))) (define-syntax conde (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (st) (inc (let ((st (state-with-scope st (new-scope)))) (mplus* (bind* (g0 st) g ...) (bind* (g1 st) g^ ...) ...))))))) (define-syntax run (syntax-rules () ((_ n (q) g0 g ...) (take n (inc ((fresh (q) g0 g ... (lambdag@ (st) (let ((st (state-with-scope st nonlocal-scope))) (let ((z ((reify q) st))) (choice z (lambda () (lambda () #f))))))) empty-state)))) ((_ n (q0 q1 q ...) g0 g ...) (run n (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x)))))) (define-syntax run* (syntax-rules () ((_ (q0 q ...) g0 g ...) (run #f (q0 q ...) g0 g ...)))) (define-syntax run-stream (syntax-rules () ((_ (q) g0 g ...) (take-stream (inc ((fresh (q) g0 g ... (lambdag@ (st) (let ((st (state-with-scope st nonlocal-scope))) (let ((z ((reify q) st))) (choice z (lambda () (lambda () #f))))))) empty-state)))) ((_ (q0 q1 q ...) g0 g ...) (run-stream (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x)))))) ( note that a Constraint is a Goal but a Goal is not a Constraint . Constraint implementations currently use this more restrained type . See ` and - foldl ` 1 . Must be positive , not negative . not - pairo would n't work . 2 . Each type must have infinitely many possible values to avoid (define type-constraint (lambda (type-pred type-id) (lambda (u) (lambdag@ (st) (let ((term (walk u (state-S st)))) (cond ((type-pred term) st) ((var? term) (let* ((c (lookup-c term st)) (T (c-T c))) (cond ((eq? T type-id) st) ((not T) (set-c term (c-with-T c type-id) st)) (else #f)))) (else #f))))))) (define symbolo (type-constraint symbol? 'symbolo)) (define numbero (type-constraint number? 'numbero)) (define (add-to-D st v d) (let* ((c (lookup-c v st)) (c^ (c-with-D c (cons d (c-D c))))) (set-c v c^ st))) (define =/=* (lambda (S+) (lambdag@ (st) (let-values (((S added) (unify* S+ (subst-with-scope (state-S st) nonlocal-scope)))) (cond ((not S) st) ((null? added) #f) (else Choose one of the disequality elements ( el ) to attach the constraint to . Only (let ((el (car added))) (let ((st (add-to-D st (car el) added))) (if (var? (cdr el)) (add-to-D st (cdr el) added) st))))))))) (define =/= (lambda (u v) (=/=* `((,u . ,v))))) (define absento (lambda (ground-atom term) (lambdag@ (st) (let ((term (walk term (state-S st)))) (cond ((pair? term) (let ((st^ ((absento ground-atom (car term)) st))) (and st^ ((absento ground-atom (cdr term)) st^)))) ((eqv? term ground-atom) #f) ((var? term) (let* ((c (lookup-c term st)) (A (c-A c))) (if (memv ground-atom A) st (let ((c^ (c-with-A c (cons ground-atom A)))) (set-c term c^ st))))) (else st)))))) Fold lst with proc and initial value init . If proc ever returns # f , (define (and-foldl proc init lst) (if (null? lst) init (let ([res (proc (car lst) init)]) (and res (and-foldl proc res (cdr lst)))))) (define == (lambda (u v) (lambdag@ (st) (let-values (((S added) (unify u v (state-S st)))) (if S (and-foldl update-constraints (state S (state-C st)) added) #f))))) (define update-constraints (lambda (a st) (let ([old-c (lookup-c (lhs a) st)]) (if (eq? old-c empty-c) st (let ((st (remove-c (lhs a) st))) (and-foldl (lambda (op st) (op st)) st (append (if (eq? (c-T old-c) 'symbolo) (list (symbolo (rhs a))) '()) (if (eq? (c-T old-c) 'numbero) (list (numbero (rhs a))) '()) (map (lambda (atom) (absento atom (rhs a))) (c-A old-c)) (map (lambda (d) (=/=* d)) (c-D old-c))))))))) (define walk* (lambda (v S) (let ((v (walk v S))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) S) (walk* (cdr v) S))) (else v))))) (define vars (lambda (term acc) (cond ((var? term) (cons term acc)) ((pair? term) (vars (cdr term) (vars (car term) acc))) (else acc)))) (define-syntax project (syntax-rules () ((_ (x ...) g g* ...) (lambdag@ (st) (let ((x (walk* x (state-S st))) ...) ((fresh () g g* ...) st)))))) (define c-from-st (lambda (st x) (let ((vs (vars (walk* x (state-S st)) '()))) (foldl (lambda (v c-store) (let ((c (lookup-c v st))) (let ((S (state-S st)) (D (c->D c-store)) (Y (c->Y c-store)) (N (c->N c-store)) (T (c->T c-store)) (T^ (c-T c)) (D^ (c-D c)) (A^ (c-A c))) `(,S ,(append D^ D) ,(if (eq? T^ 'symbolo) (cons v Y) Y) ,(if (eq? T^ 'numbero) (cons v N) N) ,(append (map (lambda (atom) (cons atom v)) A^) T))))) `(,(state-S st) () () () ()) (remove-duplicates vs))))) (define reify (lambda (x) (lambda (st) (let ((c (c-from-st st x))) (let ((c (cycle c))) (let* ((S (c->S c)) (D (walk* (c->D c) S)) (Y (walk* (c->Y c) S)) (N (walk* (c->N c) S)) (T (walk* (c->T c) S))) (let ((v (walk* x S))) (let ((R (reify-S v (subst empty-subst-map nonlocal-scope)))) (reify+ v R (let ((D (remp (lambda (d) (let ((dw (walk* d S))) (anyvar? dw R))) (rem-xx-from-d c)))) (rem-subsumed D)) (remp (lambda (y) (var? (walk y R))) Y) (remp (lambda (n) (var? (walk n R))) N) (remp (lambda (t) (anyvar? t R)) T)))))))))) (define c->S (lambda (c) (car c))) (define c->D (lambda (c) (cadr c))) (define c->Y (lambda (c) (caddr c))) (define c->N (lambda (c) (cadddr c))) (define c->T (lambda (c) (cadddr (cdr c)))) (define-syntax lambdar@ (syntax-rules (:) ((_ (c) e) (lambda (c) e)) ((_ (c : S D Y N T) e) (lambda (c) (let ((S (c->S c)) (D (c->D c)) (Y (c->Y c)) (N (c->N c)) (T (c->T c))) e))))) (define tagged? (lambda (S Y y^) (exists (lambda (y) (eqv? (walk y S) y^)) Y))) (define untyped-var? (lambda (S Y N t^) (let ((in-type? (lambda (y) (var-eq? (walk y S) t^)))) (and (var? t^) (not (exists in-type? Y)) (not (exists in-type? N)))))) (define reify-S (lambda (v S) (let ((v (walk v S))) (cond ((var? v) (let ((n (subst-length S))) (let ((name (reify-name n))) (subst-add S v name)))) ((pair? v) (let ((S (reify-S (car v) S))) (reify-S (cdr v) S))) (else S))))) (define reify-name (lambda (n) (string->symbol (string-append "_" "." (number->string n))))) (define drop-dot (lambda (X) (map (lambda (t) (let ((a (lhs t)) (d (rhs t))) `(,a ,d))) X))) (define sorter (lambda (ls) (list-sort lex<=? ls))) (define lex<=? (lambda (x y) (string<=? (datum->string x) (datum->string y)))) (define datum->string (lambda (x) (call-with-string-output-port (lambda (p) (display x p))))) (define anyvar? (lambda (u r) (cond ((pair? u) (or (anyvar? (car u) r) (anyvar? (cdr u) r))) (else (var? (walk u r)))))) (define member* (lambda (u v) (cond ((equal? u v) #t) ((pair? v) (or (member* u (car v)) (member* u (cdr v)))) (else #f)))) (define drop-N-b/c-const (lambdar@ (c : S D Y N T) (let ((const? (lambda (n) (not (var? (walk n S)))))) (cond ((find const? N) => (lambda (n) `(,S ,D ,Y ,(remq1 n N) ,T))) (else c))))) (define drop-Y-b/c-const (lambdar@ (c : S D Y N T) (let ((const? (lambda (y) (not (var? (walk y S)))))) (cond ((find const? Y) => (lambda (y) `(,S ,D ,(remq1 y Y) ,N ,T))) (else c))))) (define remq1 (lambda (elem ls) (cond ((null? ls) '()) ((eq? (car ls) elem) (cdr ls)) (else (cons (car ls) (remq1 elem (cdr ls))))))) (define same-var? (lambda (v) (lambda (v^) (and (var? v) (var? v^) (var-eq? v v^))))) (define find-dup (lambda (f S) (lambda (set) (let loop ((set^ set)) (cond ((null? set^) #f) (else (let ((elem (car set^))) (let ((elem^ (walk elem S))) (cond ((find (lambda (elem^^) ((f elem^) (walk elem^^ S))) (cdr set^)) elem) (else (loop (cdr set^)))))))))))) (define drop-N-b/c-dup-var (lambdar@ (c : S D Y N T) (cond (((find-dup same-var? S) N) => (lambda (n) `(,S ,D ,Y ,(remq1 n N) ,T))) (else c)))) (define drop-Y-b/c-dup-var (lambdar@ (c : S D Y N T) (cond (((find-dup same-var? S) Y) => (lambda (y) `(,S ,D ,(remq1 y Y) ,N ,T))) (else c)))) (define var-type-mismatch? (lambda (S Y N t1^ t2^) (cond ((num? S N t1^) (not (num? S N t2^))) ((sym? S Y t1^) (not (sym? S Y t2^))) (else #f)))) (define term-ununifiable? (lambda (S Y N t1 t2) (let ((t1^ (walk t1 S)) (t2^ (walk t2 S))) (cond ((or (untyped-var? S Y N t1^) (untyped-var? S Y N t2^)) #f) ((var? t1^) (var-type-mismatch? S Y N t1^ t2^)) ((var? t2^) (var-type-mismatch? S Y N t2^ t1^)) ((and (pair? t1^) (pair? t2^)) (or (term-ununifiable? S Y N (car t1^) (car t2^)) (term-ununifiable? S Y N (cdr t1^) (cdr t2^)))) (else (not (eqv? t1^ t2^))))))) (define T-term-ununifiable? (lambda (S Y N) (lambda (t1) (let ((t1^ (walk t1 S))) (letrec ((t2-check (lambda (t2) (let ((t2^ (walk t2 S))) (if (pair? t2^) (and (term-ununifiable? S Y N t1^ t2^) (t2-check (car t2^)) (t2-check (cdr t2^))) (term-ununifiable? S Y N t1^ t2^)))))) t2-check))))) (define num? (lambda (S N n) (let ((n (walk n S))) (cond ((var? n) (tagged? S N n)) (else (number? n)))))) (define sym? (lambda (S Y y) (let ((y (walk y S))) (cond ((var? y) (tagged? S Y y)) (else (symbol? y)))))) (define drop-T-b/c-Y-and-N (lambdar@ (c : S D Y N T) (let ((drop-t? (T-term-ununifiable? S Y N))) (cond ((find (lambda (t) ((drop-t? (lhs t)) (rhs t))) T) => (lambda (t) `(,S ,D ,Y ,N ,(remq1 t T)))) (else c))))) (define move-T-to-D-b/c-t2-atom (lambdar@ (c : S D Y N T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((and (not (untyped-var? S Y N t2^)) (not (pair? t2^))) (let ((T (remq1 t T))) `(,S ((,t) . ,D) ,Y ,N ,T))) (else #f)))) T)) (else c)))) (define terms-pairwise=? (lambda (pr-a^ pr-d^ t-a^ t-d^ S) (or (and (term=? pr-a^ t-a^ S) (term=? pr-d^ t-a^ S)) (and (term=? pr-a^ t-d^ S) (term=? pr-d^ t-a^ S))))) (define T-superfluous-pr? (lambda (S Y N T) (lambda (pr) (let ((pr-a^ (walk (lhs pr) S)) (pr-d^ (walk (rhs pr) S))) (cond ((exists (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S))) T) (for-all (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (or (not (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S)) (untyped-var? S Y N t-d^) (pair? t-d^)))) T)) (else #f)))))) (define drop-from-D-b/c-T (lambdar@ (c : S D Y N T) (cond ((find (lambda (d) (exists (T-superfluous-pr? S Y N T) d)) D) => (lambda (d) `(,S ,(remq1 d D) ,Y ,N ,T))) (else c)))) (define drop-t-b/c-t2-occurs-t1 (lambdar@ (c : S D Y N T) (cond ((find (lambda (t) (let ((t-a^ (walk (lhs t) S)) (t-d^ (walk (rhs t) S))) (mem-check t-d^ t-a^ S))) T) => (lambda (t) `(,S ,D ,Y ,N ,(remq1 t T)))) (else c)))) (define split-t-move-to-d-b/c-pair (lambdar@ (c : S D Y N T) (cond ((exists (lambda (t) (let ((t2^ (walk (rhs t) S))) (cond ((pair? t2^) (let ((ta `(,(lhs t) . ,(car t2^))) (td `(,(lhs t) . ,(cdr t2^)))) (let ((T `(,ta ,td . ,(remq1 t T)))) `(,S ((,t) . ,D) ,Y ,N ,T)))) (else #f)))) T)) (else c)))) (define find-d-conflict (lambda (S Y N) (lambda (D) (find (lambda (d) (exists (lambda (pr) (term-ununifiable? S Y N (lhs pr) (rhs pr))) d)) D)))) (define drop-D-b/c-Y-or-N (lambdar@ (c : S D Y N T) (cond (((find-d-conflict S Y N) D) => (lambda (d) `(,S ,(remq1 d D) ,Y ,N ,T))) (else c)))) (define cycle (lambdar@ (c) (let loop ((c^ c) (fns^ (LOF)) (n (length (LOF)))) (cond ((zero? n) c^) ((null? fns^) (loop c^ (LOF) n)) (else (let ((c^^ ((car fns^) c^))) (cond ((not (eq? c^^ c^)) (loop c^^ (cdr fns^) (length (LOF)))) (else (loop c^ (cdr fns^) (sub1 n)))))))))) (define mem-check (lambda (u t S) (let ((t (walk t S))) (cond ((pair? t) (or (term=? u t S) (mem-check u (car t) S) (mem-check u (cdr t) S))) (else (term=? u t S)))))) (define term=? (lambda (u t S) (let-values (((S added) (unify u t (subst-with-scope S nonlocal-scope)))) (and S (null? added))))) (define ground-non-<type>? (lambda (pred) (lambda (u S) (let ((u (walk u S))) (cond ((var? u) #f) (else (not (pred u)))))))) (define ground-non-symbol? (ground-non-<type>? symbol?)) (define ground-non-number? (ground-non-<type>? number?)) (define succeed (== #f #f)) (define fail (== #f #t)) (define ==fail-check (lambda (S0 D Y N T) (let ([S0 (subst-with-scope S0 nonlocal-scope)]) (cond ((atomic-fail-check S0 Y ground-non-symbol?) #t) ((atomic-fail-check S0 N ground-non-number?) #t) ((symbolo-numbero-fail-check S0 Y N) #t) ((=/=-fail-check S0 D) #t) ((absento-fail-check S0 T) #t) (else #f))))) (define atomic-fail-check (lambda (S A pred) (exists (lambda (a) (pred (walk a S) S)) A))) (define symbolo-numbero-fail-check (lambda (S A N) (let ((N (map (lambda (n) (walk n S)) N))) (exists (lambda (a) (exists (same-var? (walk a S)) N)) A)))) (define absento-fail-check (lambda (S T) (exists (lambda (t) (mem-check (lhs t) (rhs t) S)) T))) (define =/=-fail-check (lambda (S D) (exists (d-fail-check S) D))) (define d-fail-check (lambda (S) (lambda (d) (let-values (((S added) (unify* d S))) (and S (null? added)))))) (define reify+ (lambda (v R D Y N T) (form (walk* v R) (walk* D R) (walk* Y R) (walk* N R) (rem-subsumed-T (walk* T R))))) (define form (lambda (v D Y N T) (let ((fd (sort-D D)) (fy (sorter Y)) (fn (sorter N)) (ft (sorter T))) (let ((fd (if (null? fd) fd (let ((fd (drop-dot-D fd))) `((=/= . ,fd))))) (fy (if (null? fy) fy `((sym . ,fy)))) (fn (if (null? fn) fn `((num . ,fn)))) (ft (if (null? ft) ft (let ((ft (drop-dot ft))) `((absento . ,ft)))))) (cond ((and (null? fd) (null? fy) (null? fn) (null? ft)) v) (else (append `(,v) fd fn fy ft))))))) (define sort-D (lambda (D) (sorter (map sort-d D)))) (define sort-d (lambda (d) (list-sort (lambda (x y) (lex<=? (car x) (car y))) (map sort-pr d)))) (define drop-dot-D (lambda (D) (map drop-dot D))) (define lex<-reified-name? (lambda (r) (char<? (string-ref (datum->string r) 0) #\_))) (define sort-pr (lambda (pr) (let ((l (lhs pr)) (r (rhs pr))) (cond ((lex<-reified-name? r) pr) ((lex<=? r l) `(,r . ,l)) (else pr))))) (define rem-subsumed (lambda (D) (let rem-subsumed ((D D) (d^* '())) (cond ((null? D) d^*) ((or (subsumed? (car D) (cdr D)) (subsumed? (car D) d^*)) (rem-subsumed (cdr D) d^*)) (else (rem-subsumed (cdr D) (cons (car D) d^*))))))) (define subsumed? (lambda (d d*) (cond ((null? d*) #f) (else (let-values (((S ignore) (unify* d (subst empty-subst-map nonlocal-scope)))) (let-values (((S+ added) (unify* (car d*) S))) (or (and S+ (null? added)) (subsumed? d (cdr d*))))))))) (define rem-xx-from-d (lambdar@ (c : S D Y N T) (let ((D (walk* D S))) (remp not (map (lambda (d) (let-values (((S0 ignore) (unify* d S))) (cond ((not S0) #f) ((==fail-check S0 '() Y N T) #f) (else (let-values (((S added) (unify* d (subst empty-subst-map nonlocal-scope)))) added))))) D))))) (define rem-subsumed-T (lambda (T) (let rem-subsumed ((T T) (T^ '())) (cond ((null? T) T^) (else (let ((lit (lhs (car T))) (big (rhs (car T)))) (cond ((or (subsumed-T? lit big (cdr T)) (subsumed-T? lit big T^)) (rem-subsumed (cdr T) T^)) (else (rem-subsumed (cdr T) (cons (car T) T^)))))))))) (define subsumed-T? (lambda (lit big T) (cond ((null? T) #f) (else (let ((lit^ (lhs (car T))) (big^ (rhs (car T)))) (or (and (eq? big big^) (member* lit^ lit)) (subsumed-T? lit big (cdr T)))))))) (define LOF (lambda () `(,drop-N-b/c-const ,drop-Y-b/c-const ,drop-Y-b/c-dup-var ,drop-N-b/c-dup-var ,drop-D-b/c-Y-or-N ,drop-T-b/c-Y-and-N ,move-T-to-D-b/c-t2-atom ,split-t-move-to-d-b/c-pair ,drop-from-D-b/c-T ,drop-t-b/c-t2-occurs-t1)))
d01dddcb487c5cd8b92bd30b123c76496aa71ab6f4a1c49a2a41e8789e418ce5
david-broman/modelyze
bitSet.ml
* Bitset - Efficient bit sets * Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library 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 * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Bitset - Efficient bit sets * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type intern let bcreate : int -> intern = Obj.magic String.create external fast_get : intern -> int -> int = "%string_unsafe_get" external fast_set : intern -> int -> int -> unit = "%string_unsafe_set" external fast_bool : int -> bool = "%identity" let fast_blit : intern -> int -> intern -> int -> int -> unit = Obj.magic String.blit let fast_fill : intern -> int -> int -> int -> unit = Obj.magic String.fill let fast_length : intern -> int= Obj.magic String.length let bget s ndx = assert (ndx >= 0 && ndx < fast_length s); fast_get s ndx let bset s ndx v = assert (ndx >= 0 && ndx < fast_length s); fast_set s ndx v let bblit src srcoff dst dstoff len = assert (srcoff >= 0 && dstoff >= 0 && len >= 0); fast_blit src srcoff dst dstoff len let bfill dst start len c = assert (start >= 0 && len >= 0); fast_fill dst start len c exception Negative_index of string type t = { mutable data : intern; mutable len : int; } let error fname = raise (Negative_index fname) let empty() = { data = bcreate 0; len = 0; } let int_size = 7 (* value used to round up index *) let log_int_size = 3 (* number of shifts *) let create n = if n < 0 then error "create"; let size = (n+int_size) lsr log_int_size in let b = bcreate size in bfill b 0 size 0; { data = b; len = size; } let copy t = let b = bcreate t.len in bblit t.data 0 b 0 t.len; { data = b; len = t.len } let clone = copy let set t x = if x < 0 then error "set"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos >= size then begin let b = bcreate (pos+1) in bblit t.data 0 b 0 size; bfill b size (pos - size + 1) 0; t.len <- pos + 1; t.data <- b; end; bset t.data pos ((bget t.data pos) lor (1 lsl delta)) let unset t x = if x < 0 then error "unset"; let pos = x lsr log_int_size and delta = x land int_size in if pos < t.len then bset t.data pos ((bget t.data pos) land (0xFF lxor (1 lsl delta))) let toggle t x = if x < 0 then error "toggle"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos >= size then begin let b = bcreate (pos+1) in bblit t.data 0 b 0 size; bfill b size (pos - size + 1) 0; t.len <- pos + 1; t.data <- b; end; bset t.data pos ((bget t.data pos) lxor (1 lsl delta)) let put t = function | true -> set t | false -> unset t let is_set t x = if x < 0 then error "is_set"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos < size then fast_bool (((bget t.data pos) lsr delta) land 1) else false exception Break_int of int (* Find highest set element or raise Not_found *) let find_msb t = Find highest set bit in a byte . Does not work with zero . let byte_msb b = assert (b <> 0); let rec loop n = if b land (1 lsl n) = 0 then loop (n-1) else n in loop 7 in let n = t.len - 1 and buf = t.data in try for i = n downto 0 do let byte = bget buf i in if byte <> 0 then raise (Break_int ((i lsl log_int_size)+(byte_msb byte))) done; raise Not_found with Break_int n -> n | _ -> raise Not_found let compare t1 t2 = let some_msb b = try Some (find_msb b) with Not_found -> None in match (some_msb t1, some_msb t2) with (None, Some _) -> -1 (* 0-y -> -1 *) x-0 - > 1 0 - 0 - > 0 | (Some a, Some b) -> (* x-y *) if a < b then -1 else if a > b then 1 else begin (* MSBs differ, we need to scan arrays until we find a difference *) let ndx = a lsr log_int_size in assert (ndx < t1.len && ndx < t2.len); try for i = ndx downto 0 do let b1 = bget t1.data i and b2 = bget t2.data i in if b1 <> b2 then raise (Break_int (compare b1 b2)) done; 0 with Break_int res -> res end let equals t1 t2 = compare t1 t2 = 0 let partial_count t x = let rec nbits x = if x = 0 then 0 else if fast_bool (x land 1) then 1 + (nbits (x lsr 1)) else nbits (x lsr 1) in let size = t.len in let pos = x lsr log_int_size and delta = x land int_size in let rec loop n acc = if n = size then acc else let x = bget t.data n in loop (n+1) (acc + nbits x) in if pos >= size then 0 else loop (pos+1) (nbits ((bget t.data pos) lsr delta)) let count t = partial_count t 0 Find the first set bit in the bit array let find_first_set b n = TODO there are many ways to speed this up . Lookup table would be one way to speed this up . one way to speed this up. *) let find_lsb b = assert (b <> 0); let rec loop n = if b land (1 lsl n) <> 0 then n else loop (n+1) in loop 0 in let buf = b.data in let rec find_bit byte_ndx bit_offs = if byte_ndx >= b.len then None else let byte = (bget buf byte_ndx) lsr bit_offs in if byte = 0 then find_bit (byte_ndx + 1) 0 else Some ((find_lsb byte) + (byte_ndx lsl log_int_size) + bit_offs) in find_bit (n lsr log_int_size) (n land int_size) let enum t = let rec make n = let cur = ref n in let rec next () = match find_first_set t !cur with Some elem -> cur := (elem+1); elem | None -> raise Enum.No_more_elements in Enum.make ~next ~count:(fun () -> partial_count t !cur) ~clone:(fun () -> make !cur) in make 0 let raw_create size = let b = bcreate size in bfill b 0 size 0; { data = b; len = size } let inter a b = let max_size = max a.len b.len in let d = raw_create max_size in let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in Note : rest of the array is set to zero automatically for i = 0 to sl-1 do bset d.data i ((bget abuf i) land (bget bbuf i)) done; d (* Note: rest of the array is handled automatically correct, since we took a copy of the bigger set. *) let union a b = let d = if a.len > b.len then copy a else copy b in let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset d.data i ((bget abuf i) lor (bget bbuf i)) done; d let diff a b = let maxlen = max a.len b.len in let buf = bcreate maxlen in bblit a.data 0 buf 0 a.len; let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset buf i ((bget abuf i) land (lnot (bget bbuf i))) done; { data = buf; len = maxlen } let sym_diff a b = let maxlen = max a.len b.len in let buf = bcreate maxlen in Copy larger ( assumes missing bits are zero ) bblit (if a.len > b.len then a.data else b.data) 0 buf 0 maxlen; let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset buf i ((bget abuf i) lxor (bget bbuf i)) done; { data = buf; len = maxlen } TODO the following set operations can be made faster if you do the set operation in - place instead of taking a copy . But be careful when the sizes of the bitvector strings differ . set operation in-place instead of taking a copy. But be careful when the sizes of the bitvector strings differ. *) let intersect t t' = let d = inter t t' in t.data <- d.data; t.len <- d.len let differentiate t t' = let d = diff t t' in t.data <- d.data; t.len <- d.len let unite t t' = let d = union t t' in t.data <- d.data; t.len <- d.len let differentiate_sym t t' = let d = sym_diff t t' in t.data <- d.data; t.len <- d.len
null
https://raw.githubusercontent.com/david-broman/modelyze/e48c934283e683e268a9dfd0fed49d3c10277298/ext/extlib/bitSet.ml
ocaml
value used to round up index number of shifts Find highest set element or raise Not_found 0-y -> -1 x-y MSBs differ, we need to scan arrays until we find a difference Note: rest of the array is handled automatically correct, since we took a copy of the bigger set.
* Bitset - Efficient bit sets * Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library 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 * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Bitset - Efficient bit sets * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type intern let bcreate : int -> intern = Obj.magic String.create external fast_get : intern -> int -> int = "%string_unsafe_get" external fast_set : intern -> int -> int -> unit = "%string_unsafe_set" external fast_bool : int -> bool = "%identity" let fast_blit : intern -> int -> intern -> int -> int -> unit = Obj.magic String.blit let fast_fill : intern -> int -> int -> int -> unit = Obj.magic String.fill let fast_length : intern -> int= Obj.magic String.length let bget s ndx = assert (ndx >= 0 && ndx < fast_length s); fast_get s ndx let bset s ndx v = assert (ndx >= 0 && ndx < fast_length s); fast_set s ndx v let bblit src srcoff dst dstoff len = assert (srcoff >= 0 && dstoff >= 0 && len >= 0); fast_blit src srcoff dst dstoff len let bfill dst start len c = assert (start >= 0 && len >= 0); fast_fill dst start len c exception Negative_index of string type t = { mutable data : intern; mutable len : int; } let error fname = raise (Negative_index fname) let empty() = { data = bcreate 0; len = 0; } let create n = if n < 0 then error "create"; let size = (n+int_size) lsr log_int_size in let b = bcreate size in bfill b 0 size 0; { data = b; len = size; } let copy t = let b = bcreate t.len in bblit t.data 0 b 0 t.len; { data = b; len = t.len } let clone = copy let set t x = if x < 0 then error "set"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos >= size then begin let b = bcreate (pos+1) in bblit t.data 0 b 0 size; bfill b size (pos - size + 1) 0; t.len <- pos + 1; t.data <- b; end; bset t.data pos ((bget t.data pos) lor (1 lsl delta)) let unset t x = if x < 0 then error "unset"; let pos = x lsr log_int_size and delta = x land int_size in if pos < t.len then bset t.data pos ((bget t.data pos) land (0xFF lxor (1 lsl delta))) let toggle t x = if x < 0 then error "toggle"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos >= size then begin let b = bcreate (pos+1) in bblit t.data 0 b 0 size; bfill b size (pos - size + 1) 0; t.len <- pos + 1; t.data <- b; end; bset t.data pos ((bget t.data pos) lxor (1 lsl delta)) let put t = function | true -> set t | false -> unset t let is_set t x = if x < 0 then error "is_set"; let pos = x lsr log_int_size and delta = x land int_size in let size = t.len in if pos < size then fast_bool (((bget t.data pos) lsr delta) land 1) else false exception Break_int of int let find_msb t = Find highest set bit in a byte . Does not work with zero . let byte_msb b = assert (b <> 0); let rec loop n = if b land (1 lsl n) = 0 then loop (n-1) else n in loop 7 in let n = t.len - 1 and buf = t.data in try for i = n downto 0 do let byte = bget buf i in if byte <> 0 then raise (Break_int ((i lsl log_int_size)+(byte_msb byte))) done; raise Not_found with Break_int n -> n | _ -> raise Not_found let compare t1 t2 = let some_msb b = try Some (find_msb b) with Not_found -> None in match (some_msb t1, some_msb t2) with x-0 - > 1 0 - 0 - > 0 if a < b then -1 else if a > b then 1 else begin let ndx = a lsr log_int_size in assert (ndx < t1.len && ndx < t2.len); try for i = ndx downto 0 do let b1 = bget t1.data i and b2 = bget t2.data i in if b1 <> b2 then raise (Break_int (compare b1 b2)) done; 0 with Break_int res -> res end let equals t1 t2 = compare t1 t2 = 0 let partial_count t x = let rec nbits x = if x = 0 then 0 else if fast_bool (x land 1) then 1 + (nbits (x lsr 1)) else nbits (x lsr 1) in let size = t.len in let pos = x lsr log_int_size and delta = x land int_size in let rec loop n acc = if n = size then acc else let x = bget t.data n in loop (n+1) (acc + nbits x) in if pos >= size then 0 else loop (pos+1) (nbits ((bget t.data pos) lsr delta)) let count t = partial_count t 0 Find the first set bit in the bit array let find_first_set b n = TODO there are many ways to speed this up . Lookup table would be one way to speed this up . one way to speed this up. *) let find_lsb b = assert (b <> 0); let rec loop n = if b land (1 lsl n) <> 0 then n else loop (n+1) in loop 0 in let buf = b.data in let rec find_bit byte_ndx bit_offs = if byte_ndx >= b.len then None else let byte = (bget buf byte_ndx) lsr bit_offs in if byte = 0 then find_bit (byte_ndx + 1) 0 else Some ((find_lsb byte) + (byte_ndx lsl log_int_size) + bit_offs) in find_bit (n lsr log_int_size) (n land int_size) let enum t = let rec make n = let cur = ref n in let rec next () = match find_first_set t !cur with Some elem -> cur := (elem+1); elem | None -> raise Enum.No_more_elements in Enum.make ~next ~count:(fun () -> partial_count t !cur) ~clone:(fun () -> make !cur) in make 0 let raw_create size = let b = bcreate size in bfill b 0 size 0; { data = b; len = size } let inter a b = let max_size = max a.len b.len in let d = raw_create max_size in let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in Note : rest of the array is set to zero automatically for i = 0 to sl-1 do bset d.data i ((bget abuf i) land (bget bbuf i)) done; d let union a b = let d = if a.len > b.len then copy a else copy b in let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset d.data i ((bget abuf i) lor (bget bbuf i)) done; d let diff a b = let maxlen = max a.len b.len in let buf = bcreate maxlen in bblit a.data 0 buf 0 a.len; let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset buf i ((bget abuf i) land (lnot (bget bbuf i))) done; { data = buf; len = maxlen } let sym_diff a b = let maxlen = max a.len b.len in let buf = bcreate maxlen in Copy larger ( assumes missing bits are zero ) bblit (if a.len > b.len then a.data else b.data) 0 buf 0 maxlen; let sl = min a.len b.len in let abuf = a.data and bbuf = b.data in for i = 0 to sl-1 do bset buf i ((bget abuf i) lxor (bget bbuf i)) done; { data = buf; len = maxlen } TODO the following set operations can be made faster if you do the set operation in - place instead of taking a copy . But be careful when the sizes of the bitvector strings differ . set operation in-place instead of taking a copy. But be careful when the sizes of the bitvector strings differ. *) let intersect t t' = let d = inter t t' in t.data <- d.data; t.len <- d.len let differentiate t t' = let d = diff t t' in t.data <- d.data; t.len <- d.len let unite t t' = let d = union t t' in t.data <- d.data; t.len <- d.len let differentiate_sym t t' = let d = sym_diff t t' in t.data <- d.data; t.len <- d.len
d74c500319d096c65c896db9b22211747e34f280b73bd5c33ddee00a3228b613
KestrelInstitute/Specware
comment-hack.lisp
-*- Mode : LISP ; Package : Parser ; Base : 10 ; Syntax : Common - Lisp -*- (in-package :Parser4) (defun comment-blank-lines (&optional (n 1)) ;; No ";;;" prefix, just a blank line... (format t "~&~V%" n)) (defun comment (format-string &rest format-args) (let* ((str (apply #'format nil format-string format-args)) (old-i 0) (n (length str))) (dotimes (i n) (let ((char (schar str i))) (when (eq char #\newline) (one-line-comment (subseq str old-i i)) (setq old-i (1+ i))))) (when (< old-i n) (one-line-comment (subseq str old-i n))))) (defun one-line-comment (str) ;; main comment routine uses this for each line to be output (format t "~&;;; ~A~&" str) (force-output t)) (defun trim-whitespace (str) (string-trim '(#\space #\tab #\newline #\page) str))
null
https://raw.githubusercontent.com/KestrelInstitute/Specware/2be6411c55f26432bf5c9e2f7778128898220c24/Library/Algorithms/Parsing/Chart/Handwritten/Lisp/comment-hack.lisp
lisp
Package : Parser ; Base : 10 ; Syntax : Common - Lisp -*- No ";;;" prefix, just a blank line... main comment routine uses this for each line to be output
(in-package :Parser4) (defun comment-blank-lines (&optional (n 1)) (format t "~&~V%" n)) (defun comment (format-string &rest format-args) (let* ((str (apply #'format nil format-string format-args)) (old-i 0) (n (length str))) (dotimes (i n) (let ((char (schar str i))) (when (eq char #\newline) (one-line-comment (subseq str old-i i)) (setq old-i (1+ i))))) (when (< old-i n) (one-line-comment (subseq str old-i n))))) (defun one-line-comment (str) (format t "~&;;; ~A~&" str) (force-output t)) (defun trim-whitespace (str) (string-trim '(#\space #\tab #\newline #\page) str))
3d9a5940e6064e28b6f0c8a8785e606a452e4338262b41323d101ca22a27cd54
techascent/tech.datatype
sparse_buffer_test.clj
(ns tech.v2.datatype.sparse.sparse-buffer-test (:require [tech.v2.datatype.sparse.protocols :as sparse-proto] [tech.v2.datatype :as dtype] [tech.v2.datatype.sparse.sparse-buffer] [clojure.test :refer :all])) (defn ->pairs [item-seq] (->> item-seq (mapv (fn [{:keys [data-index global-index]}] [data-index global-index])))) (deftest base-sparse-sanity (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1]) next-sparse (dtype/make-container :sparse :float32 [0 2 0 4 0 6])] (is (= [[0 0] [1 2] [2 4] [3 6]] (->pairs (sparse-proto/safe-index-seq test-sparse)))) (is (= [[0 0] [1 2] [2 4]] (->pairs (-> (dtype/sub-buffer test-sparse 0 6) (sparse-proto/safe-index-seq))))) (is (= [[0 1] [1 3] [2 5]] (->pairs (sparse-proto/safe-index-seq next-sparse)))) (is (= (mapv float [1 0 1 0 1 0 1]) (dtype/->vector test-sparse))) (is (= (mapv float [0 2 0 4 0 6]) (dtype/->vector next-sparse))) (let [test-sparse (dtype/copy! next-sparse test-sparse)] (is (= (mapv float [0 2 0 4 0 6 1]) (dtype/->vector test-sparse)))) (is (= (mapv float [4 0 6]) (-> (dtype/sub-buffer test-sparse 3 3) (dtype/sub-buffer 0 3) dtype/->vector))) (is (= [[0 0] [1 2]] (-> (dtype/sub-buffer test-sparse 3 3) (dtype/sub-buffer 0 3) sparse-proto/safe-index-seq ->pairs))) (let [new-buffer (dtype/copy! (float-array (range 5 8)) (dtype/sub-buffer test-sparse 3 3))] (is (= (mapv float [5 6 7]) (dtype/->vector new-buffer))) (is (= (mapv float [0 2 0 5 6 7 1]) (dtype/->vector test-sparse)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 2 0 3 0 4 0]) new-buffer (dtype/sub-buffer test-sparse 1 3)] (is (= (mapv float [0 2 0]) (dtype/->vector new-buffer)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1 0]) new-buffer (dtype/set-constant! (dtype/sub-buffer test-sparse 1 3) 0 0 3)] (is (= (mapv float [0 0 0]) (dtype/->vector new-buffer))) (is (= (mapv float [1 0 0 0 1 0 1 0]) (dtype/->vector test-sparse)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1 0]) new-buffer (dtype/copy! (float-array (range 5 8)) (dtype/sub-buffer test-sparse 1 3))] (is (= (mapv float [5 6 7]) (dtype/->vector new-buffer))) (is (= (mapv float [1 5 6 7 1 0 1 0]) (dtype/->vector test-sparse)))))) (deftest unsigned-data (let [test-data [255 254 0 1 2 3] src-buffer (short-array test-data) n-elems (dtype/ecount src-buffer) dst-buffer (dtype/make-container :sparse :uint8 n-elems) byte-buffer (byte-array n-elems)] (dtype/copy! src-buffer dst-buffer) (is (= test-data (dtype/->vector dst-buffer))) (is (thrown? Throwable (dtype/copy! dst-buffer byte-buffer))) (let [casted-bytes (dtype/copy! dst-buffer 0 byte-buffer 0 n-elems {:unchecked? true})] (is (= [-1 -2 0 1 2 3] (vec casted-bytes)))) ;;The item-by-item interfaces always check (is (thrown? Throwable (dtype/set-value! dst-buffer 2 -1))) (is (thrown? Throwable (dtype/set-value! dst-buffer 2 256))) (let [new-buf (float-array n-elems)] (dtype/copy! dst-buffer new-buf) (is (= test-data (mapv long new-buf)))) (let [sub-buf (dtype/sub-buffer dst-buffer 1 (- n-elems 1)) test-ary (short-array (dtype/ecount sub-buf))] (dtype/copy! sub-buf test-ary) (is (= [254 0 1 2 3] (vec test-ary))) (is (= 254 (dtype/get-value sub-buf 0))) (dtype/set-value! sub-buf 1 255) (dtype/copy! sub-buf test-ary) (is (= [254 255 1 2 3] (vec test-ary))) (is (= [254 255 1 2 3] (-> (dtype/clone sub-buf) (dtype/->vector)))) (is (= :uint8 (-> (dtype/clone dst-buffer) (dtype/get-datatype)))))))
null
https://raw.githubusercontent.com/techascent/tech.datatype/8cc83d771d9621d580fd5d4d0625005bd7ab0e0c/test/tech/v2/datatype/sparse/sparse_buffer_test.clj
clojure
The item-by-item interfaces always check
(ns tech.v2.datatype.sparse.sparse-buffer-test (:require [tech.v2.datatype.sparse.protocols :as sparse-proto] [tech.v2.datatype :as dtype] [tech.v2.datatype.sparse.sparse-buffer] [clojure.test :refer :all])) (defn ->pairs [item-seq] (->> item-seq (mapv (fn [{:keys [data-index global-index]}] [data-index global-index])))) (deftest base-sparse-sanity (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1]) next-sparse (dtype/make-container :sparse :float32 [0 2 0 4 0 6])] (is (= [[0 0] [1 2] [2 4] [3 6]] (->pairs (sparse-proto/safe-index-seq test-sparse)))) (is (= [[0 0] [1 2] [2 4]] (->pairs (-> (dtype/sub-buffer test-sparse 0 6) (sparse-proto/safe-index-seq))))) (is (= [[0 1] [1 3] [2 5]] (->pairs (sparse-proto/safe-index-seq next-sparse)))) (is (= (mapv float [1 0 1 0 1 0 1]) (dtype/->vector test-sparse))) (is (= (mapv float [0 2 0 4 0 6]) (dtype/->vector next-sparse))) (let [test-sparse (dtype/copy! next-sparse test-sparse)] (is (= (mapv float [0 2 0 4 0 6 1]) (dtype/->vector test-sparse)))) (is (= (mapv float [4 0 6]) (-> (dtype/sub-buffer test-sparse 3 3) (dtype/sub-buffer 0 3) dtype/->vector))) (is (= [[0 0] [1 2]] (-> (dtype/sub-buffer test-sparse 3 3) (dtype/sub-buffer 0 3) sparse-proto/safe-index-seq ->pairs))) (let [new-buffer (dtype/copy! (float-array (range 5 8)) (dtype/sub-buffer test-sparse 3 3))] (is (= (mapv float [5 6 7]) (dtype/->vector new-buffer))) (is (= (mapv float [0 2 0 5 6 7 1]) (dtype/->vector test-sparse)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 2 0 3 0 4 0]) new-buffer (dtype/sub-buffer test-sparse 1 3)] (is (= (mapv float [0 2 0]) (dtype/->vector new-buffer)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1 0]) new-buffer (dtype/set-constant! (dtype/sub-buffer test-sparse 1 3) 0 0 3)] (is (= (mapv float [0 0 0]) (dtype/->vector new-buffer))) (is (= (mapv float [1 0 0 0 1 0 1 0]) (dtype/->vector test-sparse)))) (let [test-sparse (dtype/make-container :sparse :float32 [1 0 1 0 1 0 1 0]) new-buffer (dtype/copy! (float-array (range 5 8)) (dtype/sub-buffer test-sparse 1 3))] (is (= (mapv float [5 6 7]) (dtype/->vector new-buffer))) (is (= (mapv float [1 5 6 7 1 0 1 0]) (dtype/->vector test-sparse)))))) (deftest unsigned-data (let [test-data [255 254 0 1 2 3] src-buffer (short-array test-data) n-elems (dtype/ecount src-buffer) dst-buffer (dtype/make-container :sparse :uint8 n-elems) byte-buffer (byte-array n-elems)] (dtype/copy! src-buffer dst-buffer) (is (= test-data (dtype/->vector dst-buffer))) (is (thrown? Throwable (dtype/copy! dst-buffer byte-buffer))) (let [casted-bytes (dtype/copy! dst-buffer 0 byte-buffer 0 n-elems {:unchecked? true})] (is (= [-1 -2 0 1 2 3] (vec casted-bytes)))) (is (thrown? Throwable (dtype/set-value! dst-buffer 2 -1))) (is (thrown? Throwable (dtype/set-value! dst-buffer 2 256))) (let [new-buf (float-array n-elems)] (dtype/copy! dst-buffer new-buf) (is (= test-data (mapv long new-buf)))) (let [sub-buf (dtype/sub-buffer dst-buffer 1 (- n-elems 1)) test-ary (short-array (dtype/ecount sub-buf))] (dtype/copy! sub-buf test-ary) (is (= [254 0 1 2 3] (vec test-ary))) (is (= 254 (dtype/get-value sub-buf 0))) (dtype/set-value! sub-buf 1 255) (dtype/copy! sub-buf test-ary) (is (= [254 255 1 2 3] (vec test-ary))) (is (= [254 255 1 2 3] (-> (dtype/clone sub-buf) (dtype/->vector)))) (is (= :uint8 (-> (dtype/clone dst-buffer) (dtype/get-datatype)))))))
c46ec93b7365083204be4f0509843cfddb02d62129d73331fa632232085ae0b3
ertugrulcetin/procedure.async
async.clj
(ns procedure.async (:require [manifold.deferred :as d] [manifold.stream :as s] [weavejester.dependency :as dep] [clojure.tools.logging :as log] [clojure.string :as str])) (defonce procedure-map (atom {})) (defonce deps (atom (dep/graph))) (defonce validation-fn (atom nil)) (defn dependencies [id] (if-let [deps (get (:dependencies @deps) id)] (cons id (map dependencies deps)) [id])) (defn dependents [id] (if-let [depends (get (:dependents @deps) id)] (cons id (map dependents depends)) [id])) (defn register-validation-fn! "Validation function (optional) can only return true, false and a string. If it returns string which indicates validation failed with an error message. (register-validation-fn! (fn [schema data] (or (malli/validate schema data) (malli/humanize (malli/explain schema data)))))" [f] (reset! validation-fn f)) (defn dispatch "Dispatches socket, req and data to procedure. (dispatch ::get-employee-list-by-company {:req req :socket socket :data \"Company A\" :send-fn (fn [socket result] (s/put! socket result))})" [pro-name payload] {:pre [((every-pred :req :socket :send-fn) payload)]} (let [{:keys [stream async-flow] :as pro} (get @procedure-map pro-name)] (when-not pro (throw (ex-info (str "Procedure " pro " is not defined.") {}))) (when-not (realized? async-flow) @async-flow) (s/put! stream payload))) (defn dispatch-sync "Sync version of dispatch function that returns a response. It's a blocking operation. It should be used inside reg-pros (when there is a need for calling other reg-pros with different params)." [pro-name payload] {:pre [(:req payload)]} (let [d (d/deferred)] (dispatch pro-name (assoc payload ::deliver (fn [_ result] (d/success! d result)) :socket (fn []) :send-fn (fn [_ _]))) @d)) (defn cancel-pro [pro-name] (some-> @procedure-map pro-name :stream (s/put! (Exception.)))) (defmacro validate-if-exists [pro-name s param result] `(when-let [m# (get-in @procedure-map [~s :data-response-schema-map])] (when-not @validation-fn (throw (ex-info "You need to register validation fn `(register-validation-fn!)` in order to use data validation!" {}))) (let [validation-fn# @validation-fn data-validation-result# (when (:data m#) (validation-fn# (:data m#) ~param)) response-validation-result# (when (:response m#) (validation-fn# (:response m#) ~result))] (when (and (not (nil? data-validation-result#)) (not (true? data-validation-result#))) (throw (ex-info (str "Data validation failed for " ~pro-name (when (string? data-validation-result#) (str " - " data-validation-result#))) {}))) (when (and (not (nil? response-validation-result#)) (not (true? response-validation-result#))) (throw (ex-info (str "Response validation failed for " ~pro-name (when (string? response-validation-result#) (str " - " response-validation-result#))) {})))))) (defn merge-kw [k] (str/replace (str/join "-" (remove nil? [(namespace k) (name k)])) "." "-")) (defmacro create-async-flow [pro-name] (let [topo-sorted-deps (-> (get-in @procedure.async/procedure-map [pro-name :topo-sort]))] `(let [stream# (get-in @procedure.async/procedure-map [~pro-name :stream])] (log/debug "Initializing async flow for" ~pro-name) (d/loop [~@(mapcat (fn [s#] [(symbol (merge-kw s#)) `(d/deferred)]) topo-sorted-deps)] (d/chain (s/take! stream# ::drained) (fn [~'payload] (log/debug "Got the payload for" ~pro-name) (when (instance? Throwable ~'payload) (log/debug "Cancelling async flow...") (s/close! stream#) (throw ~'payload)) ;; It should not hit here ever, let's keep logging to be safe just in case (when (identical? ::drained ~'payload) (log/error "Stream drained - cancelling async flow") (s/close! stream#) (throw (ex-info "Drained stream" {}))) ~@(map (fn [s#] `(d/success! ~(symbol (merge-kw s#)) (:data ~'payload))) topo-sorted-deps) ~'payload) (fn [~'payload] (log/debug "Processing async flow for" ~pro-name) (d/chain (d/let-flow [~@(mapcat (fn [s#] [(symbol (merge-kw s#)) `(d/future (d/chain ~(symbol (merge-kw s#)) (fn [_#] (let [deps# ~(mapv (comp symbol merge-kw) (get-in @procedure-map [s# :deps]))] (if (seq deps#) (conj deps# ~'payload) ~'payload))) (fn [params#] (when-not (or (and (vector? params#) (some #(instance? Throwable %) params#)) (instance? Throwable params#) (nil? params#)) (try (if-let [f# (get-in @procedure-map [~s# :fn])] (let [result# ((f#) params#) data# (:data ~'payload)] (validate-if-exists ~pro-name ~s# data# result#) result#) (throw (ex-info (str "Procedure not defined: " ~s#) {}))) (catch Throwable e# e#))))))]) topo-sorted-deps)] (log/debug "All procedures are realized -" ~pro-name) (try (let [send-fn# (or (::deliver ~'payload) (:send-fn ~'payload))] (if-let [e# (some #(when (instance? Throwable %) %) ~(mapv (comp symbol merge-kw) topo-sorted-deps))] (let [err-msg# (.getMessage ^Exception e#)] (log/error e# "Error occurred for" ~pro-name) (send-fn# (:socket ~'payload) {:id ~pro-name :error err-msg#})) (let [result# ~(symbol (merge-kw (last topo-sorted-deps)))] (log/debug "Sending data for" ~pro-name "Data:" result#) (send-fn# (:socket ~'payload) {:id ~pro-name :result result#})))) (catch Throwable e# (log/error e# "Something went wrong when sending data back to the client! -" ~pro-name)))))) (fn [_#] (log/debug "Process completed for" ~pro-name) (d/recur ~@(map (fn [_#] `(d/deferred)) (range (count topo-sorted-deps)))))))))) (defmacro reg-pro "Defines a procedure with any doc-string or deps added to the procedure map. data-&-response-schema-map? defines a map with optional keys :data and :response that contain data or response schema. e.g.; (reg-pro :current-user (fn [{:keys [req]}] (println \"Request: \" req) {:user (get-user-by-username (-> req :query-params (get \"username\")))})) (reg-pro :get-current-users-favorite-songs [:current-user] {:data [:map [:category string?]] :response [:map [:songs (vector string?)]]} (fn [current-user {:keys [req data]}] (let [user-id (-> current-user :user :id) music-category (:category data)] {:songs (get-favorite-songs-by-user-id-and-music-category user-id music-category)})))" {:arglists '([name-kw doc-string? deps? data-&-response-schema-map? body])} [pro-name & fdecl] (when-not *compile-files* (let [m (if (string? (first fdecl)) {:doc (first fdecl)} {}) fdecl (if (string? (first fdecl)) (next fdecl) fdecl) m (if (vector? (first fdecl)) (assoc m :deps (first fdecl)) m) fdecl (if (vector? (first fdecl)) (next fdecl) fdecl) m (if (map? (first fdecl)) (assoc m :data-response-schema-map (first fdecl)) m)] `(when-not '~(:ns &env) (when-not (fn? ~(last fdecl)) (throw (ex-info "Last argument must be a function" {}))) (swap! procedure-map update ~pro-name merge (merge {:fn (bound-fn* (fn [] (eval '~(last fdecl)))) :data-response-schema-map nil} ~m)) (reset! deps (dep/graph)) (doseq [[k# v#] @procedure-map] (swap! deps (fn [deps#] (reduce #(dep/depend %1 k# %2) deps# (:deps v#))))) (doseq [[k# _#] @procedure-map] (let [dependencies# (dependencies k#) topo-sort# (filter (-> dependencies# flatten set) (dep/topo-sort @deps)) topo-sort# (if (empty? topo-sort#) [k#] topo-sort#)] (swap! procedure-map assoc-in [k# :topo-sort] topo-sort#))) (doseq [k# (distinct (flatten (dependents ~pro-name)))] (let [stream# (get-in @procedure-map [k# :stream]) async-flow# (get-in @procedure-map [k# :async-flow]) new-stream# (s/stream)] (when stream# (when (realized? async-flow#) (s/put! stream# (Exception.))) (s/close! stream#)) (swap! procedure-map (fn [m#] (-> m# (assoc-in [k# :stream] new-stream#) (assoc-in [k# :async-flow] (delay (eval `(create-async-flow ~k#)))))))))))))
null
https://raw.githubusercontent.com/ertugrulcetin/procedure.async/2f9af363904c297ef8332e4710db899c5c94e7cd/src/procedure/async.clj
clojure
It should not hit here ever, let's keep logging to be safe just in case
(ns procedure.async (:require [manifold.deferred :as d] [manifold.stream :as s] [weavejester.dependency :as dep] [clojure.tools.logging :as log] [clojure.string :as str])) (defonce procedure-map (atom {})) (defonce deps (atom (dep/graph))) (defonce validation-fn (atom nil)) (defn dependencies [id] (if-let [deps (get (:dependencies @deps) id)] (cons id (map dependencies deps)) [id])) (defn dependents [id] (if-let [depends (get (:dependents @deps) id)] (cons id (map dependents depends)) [id])) (defn register-validation-fn! "Validation function (optional) can only return true, false and a string. If it returns string which indicates validation failed with an error message. (register-validation-fn! (fn [schema data] (or (malli/validate schema data) (malli/humanize (malli/explain schema data)))))" [f] (reset! validation-fn f)) (defn dispatch "Dispatches socket, req and data to procedure. (dispatch ::get-employee-list-by-company {:req req :socket socket :data \"Company A\" :send-fn (fn [socket result] (s/put! socket result))})" [pro-name payload] {:pre [((every-pred :req :socket :send-fn) payload)]} (let [{:keys [stream async-flow] :as pro} (get @procedure-map pro-name)] (when-not pro (throw (ex-info (str "Procedure " pro " is not defined.") {}))) (when-not (realized? async-flow) @async-flow) (s/put! stream payload))) (defn dispatch-sync "Sync version of dispatch function that returns a response. It's a blocking operation. It should be used inside reg-pros (when there is a need for calling other reg-pros with different params)." [pro-name payload] {:pre [(:req payload)]} (let [d (d/deferred)] (dispatch pro-name (assoc payload ::deliver (fn [_ result] (d/success! d result)) :socket (fn []) :send-fn (fn [_ _]))) @d)) (defn cancel-pro [pro-name] (some-> @procedure-map pro-name :stream (s/put! (Exception.)))) (defmacro validate-if-exists [pro-name s param result] `(when-let [m# (get-in @procedure-map [~s :data-response-schema-map])] (when-not @validation-fn (throw (ex-info "You need to register validation fn `(register-validation-fn!)` in order to use data validation!" {}))) (let [validation-fn# @validation-fn data-validation-result# (when (:data m#) (validation-fn# (:data m#) ~param)) response-validation-result# (when (:response m#) (validation-fn# (:response m#) ~result))] (when (and (not (nil? data-validation-result#)) (not (true? data-validation-result#))) (throw (ex-info (str "Data validation failed for " ~pro-name (when (string? data-validation-result#) (str " - " data-validation-result#))) {}))) (when (and (not (nil? response-validation-result#)) (not (true? response-validation-result#))) (throw (ex-info (str "Response validation failed for " ~pro-name (when (string? response-validation-result#) (str " - " response-validation-result#))) {})))))) (defn merge-kw [k] (str/replace (str/join "-" (remove nil? [(namespace k) (name k)])) "." "-")) (defmacro create-async-flow [pro-name] (let [topo-sorted-deps (-> (get-in @procedure.async/procedure-map [pro-name :topo-sort]))] `(let [stream# (get-in @procedure.async/procedure-map [~pro-name :stream])] (log/debug "Initializing async flow for" ~pro-name) (d/loop [~@(mapcat (fn [s#] [(symbol (merge-kw s#)) `(d/deferred)]) topo-sorted-deps)] (d/chain (s/take! stream# ::drained) (fn [~'payload] (log/debug "Got the payload for" ~pro-name) (when (instance? Throwable ~'payload) (log/debug "Cancelling async flow...") (s/close! stream#) (throw ~'payload)) (when (identical? ::drained ~'payload) (log/error "Stream drained - cancelling async flow") (s/close! stream#) (throw (ex-info "Drained stream" {}))) ~@(map (fn [s#] `(d/success! ~(symbol (merge-kw s#)) (:data ~'payload))) topo-sorted-deps) ~'payload) (fn [~'payload] (log/debug "Processing async flow for" ~pro-name) (d/chain (d/let-flow [~@(mapcat (fn [s#] [(symbol (merge-kw s#)) `(d/future (d/chain ~(symbol (merge-kw s#)) (fn [_#] (let [deps# ~(mapv (comp symbol merge-kw) (get-in @procedure-map [s# :deps]))] (if (seq deps#) (conj deps# ~'payload) ~'payload))) (fn [params#] (when-not (or (and (vector? params#) (some #(instance? Throwable %) params#)) (instance? Throwable params#) (nil? params#)) (try (if-let [f# (get-in @procedure-map [~s# :fn])] (let [result# ((f#) params#) data# (:data ~'payload)] (validate-if-exists ~pro-name ~s# data# result#) result#) (throw (ex-info (str "Procedure not defined: " ~s#) {}))) (catch Throwable e# e#))))))]) topo-sorted-deps)] (log/debug "All procedures are realized -" ~pro-name) (try (let [send-fn# (or (::deliver ~'payload) (:send-fn ~'payload))] (if-let [e# (some #(when (instance? Throwable %) %) ~(mapv (comp symbol merge-kw) topo-sorted-deps))] (let [err-msg# (.getMessage ^Exception e#)] (log/error e# "Error occurred for" ~pro-name) (send-fn# (:socket ~'payload) {:id ~pro-name :error err-msg#})) (let [result# ~(symbol (merge-kw (last topo-sorted-deps)))] (log/debug "Sending data for" ~pro-name "Data:" result#) (send-fn# (:socket ~'payload) {:id ~pro-name :result result#})))) (catch Throwable e# (log/error e# "Something went wrong when sending data back to the client! -" ~pro-name)))))) (fn [_#] (log/debug "Process completed for" ~pro-name) (d/recur ~@(map (fn [_#] `(d/deferred)) (range (count topo-sorted-deps)))))))))) (defmacro reg-pro "Defines a procedure with any doc-string or deps added to the procedure map. data-&-response-schema-map? defines a map with optional keys :data and :response that contain data or response schema. (reg-pro :current-user (fn [{:keys [req]}] (println \"Request: \" req) {:user (get-user-by-username (-> req :query-params (get \"username\")))})) (reg-pro :get-current-users-favorite-songs [:current-user] {:data [:map [:category string?]] :response [:map [:songs (vector string?)]]} (fn [current-user {:keys [req data]}] (let [user-id (-> current-user :user :id) music-category (:category data)] {:songs (get-favorite-songs-by-user-id-and-music-category user-id music-category)})))" {:arglists '([name-kw doc-string? deps? data-&-response-schema-map? body])} [pro-name & fdecl] (when-not *compile-files* (let [m (if (string? (first fdecl)) {:doc (first fdecl)} {}) fdecl (if (string? (first fdecl)) (next fdecl) fdecl) m (if (vector? (first fdecl)) (assoc m :deps (first fdecl)) m) fdecl (if (vector? (first fdecl)) (next fdecl) fdecl) m (if (map? (first fdecl)) (assoc m :data-response-schema-map (first fdecl)) m)] `(when-not '~(:ns &env) (when-not (fn? ~(last fdecl)) (throw (ex-info "Last argument must be a function" {}))) (swap! procedure-map update ~pro-name merge (merge {:fn (bound-fn* (fn [] (eval '~(last fdecl)))) :data-response-schema-map nil} ~m)) (reset! deps (dep/graph)) (doseq [[k# v#] @procedure-map] (swap! deps (fn [deps#] (reduce #(dep/depend %1 k# %2) deps# (:deps v#))))) (doseq [[k# _#] @procedure-map] (let [dependencies# (dependencies k#) topo-sort# (filter (-> dependencies# flatten set) (dep/topo-sort @deps)) topo-sort# (if (empty? topo-sort#) [k#] topo-sort#)] (swap! procedure-map assoc-in [k# :topo-sort] topo-sort#))) (doseq [k# (distinct (flatten (dependents ~pro-name)))] (let [stream# (get-in @procedure-map [k# :stream]) async-flow# (get-in @procedure-map [k# :async-flow]) new-stream# (s/stream)] (when stream# (when (realized? async-flow#) (s/put! stream# (Exception.))) (s/close! stream#)) (swap! procedure-map (fn [m#] (-> m# (assoc-in [k# :stream] new-stream#) (assoc-in [k# :async-flow] (delay (eval `(create-async-flow ~k#)))))))))))))
2b53957e80ea9ce2710cf7e9b4c0c0a12853edee55611cc3409380839307f474
roburio/albatross
vmm_resources.ml
( c ) 2017 , 2018 , all rights reserved open Vmm_core let ( let* ) = Result.bind type t = { policies : Policy.t Vmm_trie.t ; block_devices : (int * bool) Vmm_trie.t ; unikernels : Unikernel.t Vmm_trie.t ; } let pp ppf t = Vmm_trie.fold Name.root_path t.policies (fun id p () -> Fmt.pf ppf "policy %a: %a@." Name.pp id Policy.pp p) () ; Vmm_trie.fold Name.root_path t.block_devices (fun id (size, used) () -> Fmt.pf ppf "block device %a: %d MB (used %B)@." Name.pp id size used) () ; Vmm_trie.fold Name.root_path t.unikernels (fun id vm () -> Fmt.pf ppf "vm %a: %a@." Name.pp id Unikernel.pp_config vm.Unikernel.config) () let empty = { policies = Vmm_trie.empty ; block_devices = Vmm_trie.empty ; unikernels = Vmm_trie.empty } let policy_metrics = let open Metrics in let doc = "VMM resource policies" in let data policy = Data.v [ uint "maximum unikernels" policy.Policy.vms ; uint "maximum memory" policy.Policy.memory ; uint "maximum block" (match policy.Policy.block with None -> 0 | Some x -> x) ] in let tag = Tags.string "domain" in Src.v ~doc ~tags:Tags.[tag] ~data "vmm-policies" let no_policy = Policy.{ vms = 0 ; cpuids = IS.empty ; memory = 0 ; block = None ; bridges = String_set.empty } (* we should confirm the following invariant: Vm or Block have no siblings *) let block_usage t path = Vmm_trie.fold path t.block_devices (fun _ (size, act) (active, inactive) -> if act then active + size, inactive else active, inactive + size) (0, 0) let total_block_usage t path = let act, inact = block_usage t path in act + inact let vm_usage t path = Vmm_trie.fold path t.unikernels (fun _ vm (vms, memory) -> (succ vms, memory + vm.Unikernel.config.Unikernel.memory)) (0, 0) let unikernel_metrics = let open Metrics in let doc = "VMM unikernels" in let data (t, path) = let vms, memory = vm_usage t path and act, inact = block_usage t path in Data.v [ uint "attached used block" act ; uint "unattached used block" inact ; uint "total used block" (act + inact) ; uint "running unikernels" vms ; uint "used memory" memory ] in let tag = Tags.string "domain" in Src.v ~doc ~tags:Tags.[tag] ~data "vmm-unikernels" let report_vms t name = let rec doit path = let str = Name.path_to_string path in Metrics.add unikernel_metrics (fun x -> x str) (fun d -> d (t, path)); if Name.is_root_path path then () else doit (Name.parent_path path) in doit (Name.path name) let find_vm t name = Vmm_trie.find name t.unikernels let find_policy t path = Vmm_trie.find (Vmm_core.Name.create_of_path path) t.policies let find_block t name = Vmm_trie.find name t.block_devices let set_block_usage t name active = match Vmm_trie.find name t with | None -> invalid_arg ("block device " ^ Name.to_string name ^ " not in trie") | Some (size, curr) -> if curr = active then invalid_arg ("block device " ^ Name.to_string name ^ " already in state " ^ (if curr then "active" else "inactive")) else fst (Vmm_trie.insert name (size, active) t) let use_blocks t name vm active = match vm.Unikernel.config.Unikernel.block_devices with | [] -> t | blocks -> let block_names = List.map (fun (bd, dev, _sector_size) -> let bd = match dev with None -> bd | Some b -> b in Name.block_name name bd) blocks in List.fold_left (fun t' n -> set_block_usage t' n active) t block_names let remove_vm t name = match find_vm t name with | None -> Error (`Msg "unknown vm") | Some vm -> let block_devices = use_blocks t.block_devices name vm false in let unikernels = Vmm_trie.remove name t.unikernels in let t' = { t with block_devices ; unikernels } in report_vms t' name; Ok t' let remove_policy t path = match find_policy t path with | None -> Error (`Msg "unknown policy") | Some _ -> let policies = Vmm_trie.remove (Vmm_core.Name.create_of_path path) t.policies in Metrics.add policy_metrics (fun x -> x (Name.path_to_string path)) (fun d -> d no_policy); Ok { t with policies } let remove_block t name = match find_block t name with | None -> Error (`Msg (Fmt.str "unknown block device %s" (Name.to_string name))) | Some (_, active) -> if active then Error (`Msg (Fmt.str "block device %s in use" (Name.to_string name))) else let block_devices = Vmm_trie.remove name t.block_devices in let t' = { t with block_devices } in report_vms t' name; Ok t' let bridge_allowed set s = String_set.mem s set let check_policy (p : Policy.t) (running_vms, used_memory) (vm : Unikernel.config) = if succ running_vms > p.Policy.vms then Error (`Msg (Fmt.str "maximum amount of unikernels (%d) reached" p.Policy.vms)) else if vm.Unikernel.memory > p.Policy.memory - used_memory then Error (`Msg (Fmt.str "maximum allowed memory (%d, used %d) would be exceeded (requesting %d)" p.Policy.memory used_memory vm.Unikernel.memory)) else if not (IS.mem vm.Unikernel.cpuid p.Policy.cpuids) then Error (`Msg "CPUid is not allowed by policy") else match List.partition (bridge_allowed p.Policy.bridges) (Unikernel.bridges vm) with | _, [] -> Ok () | _, disallowed -> Error (`Msg (Fmt.str "bridges %a not allowed by policy" Fmt.(list ~sep:(any ", ") string) disallowed)) let check_vm t name vm = let policy_ok = let path = Name.path name in match find_policy t path with | None -> Ok () | Some p -> let used = vm_usage t path in check_policy p used vm and block_ok = List.fold_left (fun r (block, dev, _sector_size) -> let* () = r in let bl = match dev with Some b -> b | None -> block in let block_name = Name.block_name name bl in match find_block t block_name with | None -> Error (`Msg (Fmt.str "block device %s not found" (Name.to_string block_name))) | Some (_, active) -> if active then Error (`Msg (Fmt.str "block device %s already in use" (Name.to_string block_name))) else Ok ()) (Ok ()) vm.block_devices and vm_ok = match find_vm t name with | None -> Ok () | Some _ -> Error (`Msg "vm with same name already exists") in let* () = policy_ok in let* () = block_ok in vm_ok let insert_vm t name vm = let unikernels, old = Vmm_trie.insert name vm t.unikernels in (match old with None -> () | Some _ -> invalid_arg ("unikernel " ^ Name.to_string name ^ " already exists in trie")) ; let block_devices = use_blocks t.block_devices name vm true in let t' = { t with unikernels ; block_devices } in report_vms t' name; t' let check_block t name size = let block_ok = match find_block t name with | Some _ -> Error (`Msg (Fmt.str "block device with name %a already exists" Name.pp name)) | None -> Ok () and policy_ok = let path = Name.path name in match find_policy t path with | None -> Ok () | Some p -> let used = total_block_usage t path in match p.Policy.block with | None -> Error (`Msg "no block devices are allowed by policy") | Some limit -> if size <= limit - used then Ok () else Error (`Msg (Fmt.str "block device policy limit of %d MB (used %d MB) would be exceeded by the request (%d MB)" limit used size)) in let* () = block_ok in policy_ok let insert_block t name size = let* () = check_block t name size in let block_devices = fst (Vmm_trie.insert name (size, false) t.block_devices) in let t' = { t with block_devices } in report_vms t' name; Ok t' let sub_policy ~super ~sub = let sub_block sub super = match super, sub with | None, None -> true | Some _, None -> true | Some x, Some y -> x >= y | None, Some _ -> false in if super.Policy.vms < sub.Policy.vms then Error (`Msg (Fmt.str "policy above allows %d unikernels, which is fewer than %d" super.Policy.vms sub.Policy.vms)) else if super.Policy.memory < sub.Policy.memory then Error (`Msg (Fmt.str "policy above allows %d MB memory, which is fewer than %d MB" super.Policy.memory sub.Policy.memory)) else if not (IS.subset sub.Policy.cpuids super.Policy.cpuids) then Error (`Msg (Fmt.str "policy above allows CPUids %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") int) (IS.elements super.Policy.cpuids) Fmt.(list ~sep:(any ", ") int) (IS.elements sub.Policy.cpuids))) else if not (String_set.subset sub.Policy.bridges super.Policy.bridges) then Error (`Msg (Fmt.str "policy above allows bridges %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") string) (String_set.elements super.Policy.bridges) Fmt.(list ~sep:(any ", ") string) (String_set.elements sub.Policy.bridges))) else if not (sub_block sub.Policy.block super.Policy.block) then Error (`Msg (Fmt.str "policy above allows %d MB block storage, which is fewer than %d MB" (match super.Policy.block with None -> 0 | Some x -> x) (match sub.Policy.block with None -> 0 | Some x -> x))) else Ok () let check_policies_above t path sub = let rec go prefix = if Name.is_root_path prefix then Ok () else let* () = match find_policy t prefix with | None -> Ok () | Some super -> sub_policy ~super ~sub in go (Name.parent_path prefix) in go (Name.parent_path path) let check_policies_below t path super = Vmm_trie.fold path t.policies (fun name policy res -> let* () = res in if Name.is_root name then res else sub_policy ~super ~sub:policy) (Ok ()) let check_vms t path p = let (vms, used_memory) = vm_usage t path and block = total_block_usage t path in let bridges, cpuids = Vmm_trie.fold path t.unikernels (fun _ vm (bridges, cpuids) -> let config = vm.Unikernel.config in (String_set.(union (of_list (Unikernel.bridges config)) bridges), IS.add config.Unikernel.cpuid cpuids)) (String_set.empty, IS.empty) in let policy_block = match p.Policy.block with None -> 0 | Some x -> x in if not (IS.subset cpuids p.Policy.cpuids) then Error (`Msg (Fmt.str "policy allows CPUids %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") int) (IS.elements p.Policy.cpuids) Fmt.(list ~sep:(any ", ") int) (IS.elements cpuids))) else if not (String_set.subset bridges p.Policy.bridges) then Error (`Msg (Fmt.str "policy allows bridges %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") string) (String_set.elements p.Policy.bridges) Fmt.(list ~sep:(any ", ") string) (String_set.elements bridges))) else if vms > p.Policy.vms then Error (`Msg (Fmt.str "unikernel would exceed running unikernel limit set by policy to %d, running %d" p.Policy.vms vms)) else if used_memory > p.Policy.memory then Error (`Msg (Fmt.str "unikernel would exceed running memory limit set by policy to %d MB, used %d MB" p.Policy.memory used_memory)) else if block > policy_block then Error (`Msg (Fmt.str "unikernel would exceed running block storage limit set by policy to %d MB, used %d MB" policy_block block)) else Ok () let insert_policy t path p = let* () = check_policies_above t path p in let* () = check_policies_below t path p in let* () = check_vms t path p in let policies = fst (Vmm_trie.insert (Vmm_core.Name.create_of_path path) p t.policies) in Metrics.add policy_metrics (fun x -> x (Name.path_to_string path)) (fun d -> d p); Ok { t with policies }
null
https://raw.githubusercontent.com/roburio/albatross/06ce35c1386a601e92ee6282102fd775588661f6/src/vmm_resources.ml
ocaml
we should confirm the following invariant: Vm or Block have no siblings
( c ) 2017 , 2018 , all rights reserved open Vmm_core let ( let* ) = Result.bind type t = { policies : Policy.t Vmm_trie.t ; block_devices : (int * bool) Vmm_trie.t ; unikernels : Unikernel.t Vmm_trie.t ; } let pp ppf t = Vmm_trie.fold Name.root_path t.policies (fun id p () -> Fmt.pf ppf "policy %a: %a@." Name.pp id Policy.pp p) () ; Vmm_trie.fold Name.root_path t.block_devices (fun id (size, used) () -> Fmt.pf ppf "block device %a: %d MB (used %B)@." Name.pp id size used) () ; Vmm_trie.fold Name.root_path t.unikernels (fun id vm () -> Fmt.pf ppf "vm %a: %a@." Name.pp id Unikernel.pp_config vm.Unikernel.config) () let empty = { policies = Vmm_trie.empty ; block_devices = Vmm_trie.empty ; unikernels = Vmm_trie.empty } let policy_metrics = let open Metrics in let doc = "VMM resource policies" in let data policy = Data.v [ uint "maximum unikernels" policy.Policy.vms ; uint "maximum memory" policy.Policy.memory ; uint "maximum block" (match policy.Policy.block with None -> 0 | Some x -> x) ] in let tag = Tags.string "domain" in Src.v ~doc ~tags:Tags.[tag] ~data "vmm-policies" let no_policy = Policy.{ vms = 0 ; cpuids = IS.empty ; memory = 0 ; block = None ; bridges = String_set.empty } let block_usage t path = Vmm_trie.fold path t.block_devices (fun _ (size, act) (active, inactive) -> if act then active + size, inactive else active, inactive + size) (0, 0) let total_block_usage t path = let act, inact = block_usage t path in act + inact let vm_usage t path = Vmm_trie.fold path t.unikernels (fun _ vm (vms, memory) -> (succ vms, memory + vm.Unikernel.config.Unikernel.memory)) (0, 0) let unikernel_metrics = let open Metrics in let doc = "VMM unikernels" in let data (t, path) = let vms, memory = vm_usage t path and act, inact = block_usage t path in Data.v [ uint "attached used block" act ; uint "unattached used block" inact ; uint "total used block" (act + inact) ; uint "running unikernels" vms ; uint "used memory" memory ] in let tag = Tags.string "domain" in Src.v ~doc ~tags:Tags.[tag] ~data "vmm-unikernels" let report_vms t name = let rec doit path = let str = Name.path_to_string path in Metrics.add unikernel_metrics (fun x -> x str) (fun d -> d (t, path)); if Name.is_root_path path then () else doit (Name.parent_path path) in doit (Name.path name) let find_vm t name = Vmm_trie.find name t.unikernels let find_policy t path = Vmm_trie.find (Vmm_core.Name.create_of_path path) t.policies let find_block t name = Vmm_trie.find name t.block_devices let set_block_usage t name active = match Vmm_trie.find name t with | None -> invalid_arg ("block device " ^ Name.to_string name ^ " not in trie") | Some (size, curr) -> if curr = active then invalid_arg ("block device " ^ Name.to_string name ^ " already in state " ^ (if curr then "active" else "inactive")) else fst (Vmm_trie.insert name (size, active) t) let use_blocks t name vm active = match vm.Unikernel.config.Unikernel.block_devices with | [] -> t | blocks -> let block_names = List.map (fun (bd, dev, _sector_size) -> let bd = match dev with None -> bd | Some b -> b in Name.block_name name bd) blocks in List.fold_left (fun t' n -> set_block_usage t' n active) t block_names let remove_vm t name = match find_vm t name with | None -> Error (`Msg "unknown vm") | Some vm -> let block_devices = use_blocks t.block_devices name vm false in let unikernels = Vmm_trie.remove name t.unikernels in let t' = { t with block_devices ; unikernels } in report_vms t' name; Ok t' let remove_policy t path = match find_policy t path with | None -> Error (`Msg "unknown policy") | Some _ -> let policies = Vmm_trie.remove (Vmm_core.Name.create_of_path path) t.policies in Metrics.add policy_metrics (fun x -> x (Name.path_to_string path)) (fun d -> d no_policy); Ok { t with policies } let remove_block t name = match find_block t name with | None -> Error (`Msg (Fmt.str "unknown block device %s" (Name.to_string name))) | Some (_, active) -> if active then Error (`Msg (Fmt.str "block device %s in use" (Name.to_string name))) else let block_devices = Vmm_trie.remove name t.block_devices in let t' = { t with block_devices } in report_vms t' name; Ok t' let bridge_allowed set s = String_set.mem s set let check_policy (p : Policy.t) (running_vms, used_memory) (vm : Unikernel.config) = if succ running_vms > p.Policy.vms then Error (`Msg (Fmt.str "maximum amount of unikernels (%d) reached" p.Policy.vms)) else if vm.Unikernel.memory > p.Policy.memory - used_memory then Error (`Msg (Fmt.str "maximum allowed memory (%d, used %d) would be exceeded (requesting %d)" p.Policy.memory used_memory vm.Unikernel.memory)) else if not (IS.mem vm.Unikernel.cpuid p.Policy.cpuids) then Error (`Msg "CPUid is not allowed by policy") else match List.partition (bridge_allowed p.Policy.bridges) (Unikernel.bridges vm) with | _, [] -> Ok () | _, disallowed -> Error (`Msg (Fmt.str "bridges %a not allowed by policy" Fmt.(list ~sep:(any ", ") string) disallowed)) let check_vm t name vm = let policy_ok = let path = Name.path name in match find_policy t path with | None -> Ok () | Some p -> let used = vm_usage t path in check_policy p used vm and block_ok = List.fold_left (fun r (block, dev, _sector_size) -> let* () = r in let bl = match dev with Some b -> b | None -> block in let block_name = Name.block_name name bl in match find_block t block_name with | None -> Error (`Msg (Fmt.str "block device %s not found" (Name.to_string block_name))) | Some (_, active) -> if active then Error (`Msg (Fmt.str "block device %s already in use" (Name.to_string block_name))) else Ok ()) (Ok ()) vm.block_devices and vm_ok = match find_vm t name with | None -> Ok () | Some _ -> Error (`Msg "vm with same name already exists") in let* () = policy_ok in let* () = block_ok in vm_ok let insert_vm t name vm = let unikernels, old = Vmm_trie.insert name vm t.unikernels in (match old with None -> () | Some _ -> invalid_arg ("unikernel " ^ Name.to_string name ^ " already exists in trie")) ; let block_devices = use_blocks t.block_devices name vm true in let t' = { t with unikernels ; block_devices } in report_vms t' name; t' let check_block t name size = let block_ok = match find_block t name with | Some _ -> Error (`Msg (Fmt.str "block device with name %a already exists" Name.pp name)) | None -> Ok () and policy_ok = let path = Name.path name in match find_policy t path with | None -> Ok () | Some p -> let used = total_block_usage t path in match p.Policy.block with | None -> Error (`Msg "no block devices are allowed by policy") | Some limit -> if size <= limit - used then Ok () else Error (`Msg (Fmt.str "block device policy limit of %d MB (used %d MB) would be exceeded by the request (%d MB)" limit used size)) in let* () = block_ok in policy_ok let insert_block t name size = let* () = check_block t name size in let block_devices = fst (Vmm_trie.insert name (size, false) t.block_devices) in let t' = { t with block_devices } in report_vms t' name; Ok t' let sub_policy ~super ~sub = let sub_block sub super = match super, sub with | None, None -> true | Some _, None -> true | Some x, Some y -> x >= y | None, Some _ -> false in if super.Policy.vms < sub.Policy.vms then Error (`Msg (Fmt.str "policy above allows %d unikernels, which is fewer than %d" super.Policy.vms sub.Policy.vms)) else if super.Policy.memory < sub.Policy.memory then Error (`Msg (Fmt.str "policy above allows %d MB memory, which is fewer than %d MB" super.Policy.memory sub.Policy.memory)) else if not (IS.subset sub.Policy.cpuids super.Policy.cpuids) then Error (`Msg (Fmt.str "policy above allows CPUids %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") int) (IS.elements super.Policy.cpuids) Fmt.(list ~sep:(any ", ") int) (IS.elements sub.Policy.cpuids))) else if not (String_set.subset sub.Policy.bridges super.Policy.bridges) then Error (`Msg (Fmt.str "policy above allows bridges %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") string) (String_set.elements super.Policy.bridges) Fmt.(list ~sep:(any ", ") string) (String_set.elements sub.Policy.bridges))) else if not (sub_block sub.Policy.block super.Policy.block) then Error (`Msg (Fmt.str "policy above allows %d MB block storage, which is fewer than %d MB" (match super.Policy.block with None -> 0 | Some x -> x) (match sub.Policy.block with None -> 0 | Some x -> x))) else Ok () let check_policies_above t path sub = let rec go prefix = if Name.is_root_path prefix then Ok () else let* () = match find_policy t prefix with | None -> Ok () | Some super -> sub_policy ~super ~sub in go (Name.parent_path prefix) in go (Name.parent_path path) let check_policies_below t path super = Vmm_trie.fold path t.policies (fun name policy res -> let* () = res in if Name.is_root name then res else sub_policy ~super ~sub:policy) (Ok ()) let check_vms t path p = let (vms, used_memory) = vm_usage t path and block = total_block_usage t path in let bridges, cpuids = Vmm_trie.fold path t.unikernels (fun _ vm (bridges, cpuids) -> let config = vm.Unikernel.config in (String_set.(union (of_list (Unikernel.bridges config)) bridges), IS.add config.Unikernel.cpuid cpuids)) (String_set.empty, IS.empty) in let policy_block = match p.Policy.block with None -> 0 | Some x -> x in if not (IS.subset cpuids p.Policy.cpuids) then Error (`Msg (Fmt.str "policy allows CPUids %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") int) (IS.elements p.Policy.cpuids) Fmt.(list ~sep:(any ", ") int) (IS.elements cpuids))) else if not (String_set.subset bridges p.Policy.bridges) then Error (`Msg (Fmt.str "policy allows bridges %a, which is not a superset of %a" Fmt.(list ~sep:(any ", ") string) (String_set.elements p.Policy.bridges) Fmt.(list ~sep:(any ", ") string) (String_set.elements bridges))) else if vms > p.Policy.vms then Error (`Msg (Fmt.str "unikernel would exceed running unikernel limit set by policy to %d, running %d" p.Policy.vms vms)) else if used_memory > p.Policy.memory then Error (`Msg (Fmt.str "unikernel would exceed running memory limit set by policy to %d MB, used %d MB" p.Policy.memory used_memory)) else if block > policy_block then Error (`Msg (Fmt.str "unikernel would exceed running block storage limit set by policy to %d MB, used %d MB" policy_block block)) else Ok () let insert_policy t path p = let* () = check_policies_above t path p in let* () = check_policies_below t path p in let* () = check_vms t path p in let policies = fst (Vmm_trie.insert (Vmm_core.Name.create_of_path path) p t.policies) in Metrics.add policy_metrics (fun x -> x (Name.path_to_string path)) (fun d -> d p); Ok { t with policies }
bc7a741dfb8e83c8b6d97b2dc342b45da55882bb3dda0b81dd675c15439df6b2
sellout/haskerwaul
Idempotency.hs
module Haskerwaul.Law.Idempotency where import Haskerwaul.Category.Monoidal.Cartesian import Haskerwaul.Law import Haskerwaul.Object import Haskerwaul.Relation.Equality -- | [nLab]() idempotency :: (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Law c EqualityRelation a a idempotency op' = Law id (op' . diagonal)
null
https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Law/Idempotency.hs
haskell
| [nLab]()
module Haskerwaul.Law.Idempotency where import Haskerwaul.Category.Monoidal.Cartesian import Haskerwaul.Law import Haskerwaul.Object import Haskerwaul.Relation.Equality idempotency :: (CartesianMonoidalCategory c, Ob c a) => Prod c a a `c` a -> Law c EqualityRelation a a idempotency op' = Law id (op' . diagonal)
01e4993411055d5c89198e18abc3c1511291700af7a5801ac2a9ebb62217914e
gren-lang/compiler
Module.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -Wall # module Type.Constrain.Module ( constrain, ) where import AST.Canonical qualified as Can import Data.Map.Strict qualified as Map import Data.Name qualified as Name import Gren.ModuleName qualified as ModuleName import Reporting.Annotation qualified as A import Reporting.Error.Type qualified as E import Type.Constrain.Expression qualified as Expr import Type.Instantiate qualified as Instantiate import Type.Type (Constraint (..), Type (..), mkFlexVar, nameToRigid, never, (==>)) CONSTRAIN constrain :: Can.Module -> IO Constraint constrain (Can.Module home _ _ decls _ _ _ effects) = case effects of Can.NoEffects -> constrainDecls decls CSaveTheEnvironment Can.Ports ports -> Map.foldrWithKey letPort (constrainDecls decls CSaveTheEnvironment) ports Can.Manager r0 r1 r2 manager -> case manager of Can.Cmd cmdName -> letCmd home cmdName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager Can.Sub subName -> letSub home subName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager Can.Fx cmdName subName -> letCmd home cmdName =<< letSub home subName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager -- CONSTRAIN DECLARATIONS constrainDecls :: Can.Decls -> Constraint -> IO Constraint constrainDecls decls finalConstraint = case decls of Can.Declare def otherDecls -> Expr.constrainDef Map.empty def =<< constrainDecls otherDecls finalConstraint Can.DeclareRec def defs otherDecls -> Expr.constrainRecursiveDefs Map.empty (def : defs) =<< constrainDecls otherDecls finalConstraint Can.SaveTheEnvironment -> return finalConstraint -- PORT HELPERS letPort :: Name.Name -> Can.Port -> IO Constraint -> IO Constraint letPort name port_ makeConstraint = case port_ of Can.Incoming freeVars _ srcType -> do vars <- Map.traverseWithKey (\k _ -> nameToRigid k) freeVars tipe <- Instantiate.fromSrcType (Map.map VarN vars) srcType let header = Map.singleton name (A.At A.zero tipe) CLet (Map.elems vars) [] header CTrue <$> makeConstraint Can.Outgoing freeVars _ srcType -> do vars <- Map.traverseWithKey (\k _ -> nameToRigid k) freeVars tipe <- Instantiate.fromSrcType (Map.map VarN vars) srcType let header = Map.singleton name (A.At A.zero tipe) CLet (Map.elems vars) [] header CTrue <$> makeConstraint -- EFFECT MANAGER HELPERS letCmd :: ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint letCmd home tipe constraint = do msgVar <- mkFlexVar let msg = VarN msgVar let cmdType = FunN (AppN home tipe [msg]) (AppN ModuleName.cmd Name.cmd [msg]) let header = Map.singleton "command" (A.At A.zero cmdType) return $ CLet [msgVar] [] header CTrue constraint letSub :: ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint letSub home tipe constraint = do msgVar <- mkFlexVar let msg = VarN msgVar let subType = FunN (AppN home tipe [msg]) (AppN ModuleName.sub Name.sub [msg]) let header = Map.singleton "subscription" (A.At A.zero subType) return $ CLet [msgVar] [] header CTrue constraint constrainEffects :: ModuleName.Canonical -> A.Region -> A.Region -> A.Region -> Can.Manager -> IO Constraint constrainEffects home r0 r1 r2 manager = do s0 <- mkFlexVar s1 <- mkFlexVar s2 <- mkFlexVar m1 <- mkFlexVar m2 <- mkFlexVar sm1 <- mkFlexVar sm2 <- mkFlexVar let state0 = VarN s0 let state1 = VarN s1 let state2 = VarN s2 let msg1 = VarN m1 let msg2 = VarN m2 let self1 = VarN sm1 let self2 = VarN sm2 let onSelfMsg = router msg2 self2 ==> self2 ==> state2 ==> task state2 let onEffects = case manager of Can.Cmd cmd -> router msg1 self1 ==> effectList home cmd msg1 ==> state1 ==> task state1 Can.Sub sub -> router msg1 self1 ==> effectList home sub msg1 ==> state1 ==> task state1 Can.Fx cmd sub -> router msg1 self1 ==> effectList home cmd msg1 ==> effectList home sub msg1 ==> state1 ==> task state1 let effectCons = CAnd [ CLocal r0 "init" (E.NoExpectation (task state0)), CLocal r1 "onEffects" (E.NoExpectation onEffects), CLocal r2 "onSelfMsg" (E.NoExpectation onSelfMsg), CEqual r1 E.Effects state0 (E.NoExpectation state1), CEqual r2 E.Effects state0 (E.NoExpectation state2), CEqual r2 E.Effects self1 (E.NoExpectation self2) ] CLet [] [s0, s1, s2, m1, m2, sm1, sm2] Map.empty effectCons <$> case manager of Can.Cmd cmd -> checkMap "cmdMap" home cmd CSaveTheEnvironment Can.Sub sub -> checkMap "subMap" home sub CSaveTheEnvironment Can.Fx cmd sub -> checkMap "cmdMap" home cmd =<< checkMap "subMap" home sub CSaveTheEnvironment effectList :: ModuleName.Canonical -> Name.Name -> Type -> Type effectList home name msg = AppN ModuleName.array Name.array [AppN home name [msg]] task :: Type -> Type task answer = AppN ModuleName.platform Name.task [never, answer] router :: Type -> Type -> Type router msg self = AppN ModuleName.platform Name.router [msg, self] checkMap :: Name.Name -> ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint checkMap name home tipe constraint = do a <- mkFlexVar b <- mkFlexVar let mapType = toMapType home tipe (VarN a) (VarN b) let mapCon = CLocal A.zero name (E.NoExpectation mapType) return $ CLet [a, b] [] Map.empty mapCon constraint toMapType :: ModuleName.Canonical -> Name.Name -> Type -> Type -> Type toMapType home tipe a b = (a ==> b) ==> AppN home tipe [a] ==> AppN home tipe [b]
null
https://raw.githubusercontent.com/gren-lang/compiler/49d5e5c5994a846d82c9518dcee06112c7630664/compiler/src/Type/Constrain/Module.hs
haskell
# LANGUAGE OverloadedStrings # CONSTRAIN DECLARATIONS PORT HELPERS EFFECT MANAGER HELPERS
# OPTIONS_GHC -Wall # module Type.Constrain.Module ( constrain, ) where import AST.Canonical qualified as Can import Data.Map.Strict qualified as Map import Data.Name qualified as Name import Gren.ModuleName qualified as ModuleName import Reporting.Annotation qualified as A import Reporting.Error.Type qualified as E import Type.Constrain.Expression qualified as Expr import Type.Instantiate qualified as Instantiate import Type.Type (Constraint (..), Type (..), mkFlexVar, nameToRigid, never, (==>)) CONSTRAIN constrain :: Can.Module -> IO Constraint constrain (Can.Module home _ _ decls _ _ _ effects) = case effects of Can.NoEffects -> constrainDecls decls CSaveTheEnvironment Can.Ports ports -> Map.foldrWithKey letPort (constrainDecls decls CSaveTheEnvironment) ports Can.Manager r0 r1 r2 manager -> case manager of Can.Cmd cmdName -> letCmd home cmdName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager Can.Sub subName -> letSub home subName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager Can.Fx cmdName subName -> letCmd home cmdName =<< letSub home subName =<< constrainDecls decls =<< constrainEffects home r0 r1 r2 manager constrainDecls :: Can.Decls -> Constraint -> IO Constraint constrainDecls decls finalConstraint = case decls of Can.Declare def otherDecls -> Expr.constrainDef Map.empty def =<< constrainDecls otherDecls finalConstraint Can.DeclareRec def defs otherDecls -> Expr.constrainRecursiveDefs Map.empty (def : defs) =<< constrainDecls otherDecls finalConstraint Can.SaveTheEnvironment -> return finalConstraint letPort :: Name.Name -> Can.Port -> IO Constraint -> IO Constraint letPort name port_ makeConstraint = case port_ of Can.Incoming freeVars _ srcType -> do vars <- Map.traverseWithKey (\k _ -> nameToRigid k) freeVars tipe <- Instantiate.fromSrcType (Map.map VarN vars) srcType let header = Map.singleton name (A.At A.zero tipe) CLet (Map.elems vars) [] header CTrue <$> makeConstraint Can.Outgoing freeVars _ srcType -> do vars <- Map.traverseWithKey (\k _ -> nameToRigid k) freeVars tipe <- Instantiate.fromSrcType (Map.map VarN vars) srcType let header = Map.singleton name (A.At A.zero tipe) CLet (Map.elems vars) [] header CTrue <$> makeConstraint letCmd :: ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint letCmd home tipe constraint = do msgVar <- mkFlexVar let msg = VarN msgVar let cmdType = FunN (AppN home tipe [msg]) (AppN ModuleName.cmd Name.cmd [msg]) let header = Map.singleton "command" (A.At A.zero cmdType) return $ CLet [msgVar] [] header CTrue constraint letSub :: ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint letSub home tipe constraint = do msgVar <- mkFlexVar let msg = VarN msgVar let subType = FunN (AppN home tipe [msg]) (AppN ModuleName.sub Name.sub [msg]) let header = Map.singleton "subscription" (A.At A.zero subType) return $ CLet [msgVar] [] header CTrue constraint constrainEffects :: ModuleName.Canonical -> A.Region -> A.Region -> A.Region -> Can.Manager -> IO Constraint constrainEffects home r0 r1 r2 manager = do s0 <- mkFlexVar s1 <- mkFlexVar s2 <- mkFlexVar m1 <- mkFlexVar m2 <- mkFlexVar sm1 <- mkFlexVar sm2 <- mkFlexVar let state0 = VarN s0 let state1 = VarN s1 let state2 = VarN s2 let msg1 = VarN m1 let msg2 = VarN m2 let self1 = VarN sm1 let self2 = VarN sm2 let onSelfMsg = router msg2 self2 ==> self2 ==> state2 ==> task state2 let onEffects = case manager of Can.Cmd cmd -> router msg1 self1 ==> effectList home cmd msg1 ==> state1 ==> task state1 Can.Sub sub -> router msg1 self1 ==> effectList home sub msg1 ==> state1 ==> task state1 Can.Fx cmd sub -> router msg1 self1 ==> effectList home cmd msg1 ==> effectList home sub msg1 ==> state1 ==> task state1 let effectCons = CAnd [ CLocal r0 "init" (E.NoExpectation (task state0)), CLocal r1 "onEffects" (E.NoExpectation onEffects), CLocal r2 "onSelfMsg" (E.NoExpectation onSelfMsg), CEqual r1 E.Effects state0 (E.NoExpectation state1), CEqual r2 E.Effects state0 (E.NoExpectation state2), CEqual r2 E.Effects self1 (E.NoExpectation self2) ] CLet [] [s0, s1, s2, m1, m2, sm1, sm2] Map.empty effectCons <$> case manager of Can.Cmd cmd -> checkMap "cmdMap" home cmd CSaveTheEnvironment Can.Sub sub -> checkMap "subMap" home sub CSaveTheEnvironment Can.Fx cmd sub -> checkMap "cmdMap" home cmd =<< checkMap "subMap" home sub CSaveTheEnvironment effectList :: ModuleName.Canonical -> Name.Name -> Type -> Type effectList home name msg = AppN ModuleName.array Name.array [AppN home name [msg]] task :: Type -> Type task answer = AppN ModuleName.platform Name.task [never, answer] router :: Type -> Type -> Type router msg self = AppN ModuleName.platform Name.router [msg, self] checkMap :: Name.Name -> ModuleName.Canonical -> Name.Name -> Constraint -> IO Constraint checkMap name home tipe constraint = do a <- mkFlexVar b <- mkFlexVar let mapType = toMapType home tipe (VarN a) (VarN b) let mapCon = CLocal A.zero name (E.NoExpectation mapType) return $ CLet [a, b] [] Map.empty mapCon constraint toMapType :: ModuleName.Canonical -> Name.Name -> Type -> Type -> Type toMapType home tipe a b = (a ==> b) ==> AppN home tipe [a] ==> AppN home tipe [b]
ca8976993c635b0fbbbd0d5a45b935a7602f5e91f1b9e1f5c693da466fb54ffc
scicloj/wadogo
index.clj
# Wadogo scales Wadogo is the library which brings various transformations between domain and range ( codomain ) , either continuous or discrete . The idea is based on [ d3 - scale]( / d3 / d3 - scale ) and originally was a part of [ cljplot]( / generateme / cljplot ) library . There are 13 different scales with unified api . * The ` wadogo ` name came up after trying to translate word ` scale ` into different languages using [ google translate]( = en&tl = sw&text = = translate ) . Swahili word was very pleasant and was choosen on zulip chat by a community . Funny enough is that ` wadogo ` does n't mean ` scale ` at all but ` small ` or ` little ` . Translator failed here . * ^{:nextjournal.clerk/visibility :hide-ns :nextjournal.clerk/no-cache true :nextjournal.clerk/toc :collapsed} (ns index (:require [nextjournal.clerk :as clerk] [wadogo.scale :as s] [fastmath.core :as m])) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn cont->cont ([scale] (cont->cont scale {})) ([scale {:keys [w h] :or {w 400 h 200}}] (let [x1 (first (s/domain scale)) x2 (last (s/domain scale))] {:mode "vega-lite" :width w :height h :data {:values (map (partial zipmap [:domain :range]) (map #(vector % (scale %)) (m/slice-range x1 x2 80)))} :mark "line" :encoding {:x {:field "domain" :type "quantitative" :axis {:values (s/format scale)}} :y {:field "range" :type "quantitative"}}}))) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn cont->discrete [scale selector] (let [y (s/range scale) x (selector scale)] {:mode "vega-lite" :width 400 :height 200 :data {:values (map (fn [x y] {:y y :x1 (first x) :x2 (second x)}) x y)} :mark "bar" :encoding {:y {:field "y" :type "ordinal"} :x {:field "x1" :type "quantitative"} :x2 {:field "x2"}}})) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn bands-chart [scales] {:mode "vega-lite" :width 500 :height 200 :data {:values (mapcat (fn [scale] (let [n (s/data scale :name)] (map #(assoc % :name n) (s/data scale :bands)))) scales)} :encoding {:y {:field "name" :axis {:title nil}} :x {:type "quantitative" :axis {:title nil}}} :layer [{:mark "rule" :encoding {:x {:field "rstart"} :x2 {:field "rend"}}} {:mark {:type "circle" :stroke "green" :opacity 0.9} :encoding {:x {:field "point"}}}]}) ;; ## Scales ;; The scale is a structure which helps to transform one set of values into another. There are many different ways of mapping between domain and range, collected in the table below. ^{::clerk/visibility #{:hide}} (clerk/table {:head ["scale kind" "domain" "range" "info"] :rows [[:linear "continuous, numerical" "continuous, numerical" "linear"] [:log "continuous, numerical, positive values" "continuous, numerical" "logarithmic, base=10.0"] [:symlog "continuous, numerical" "continuous, numerical" "logarithmic (symmetric), base=10.0"] [:pow "continuous, numerical" "continuous, numerical" "power, exponent=0.5"] [:interpolated "continuous, numerical, segmented" "continuous, numerical" "interpolated function, linear by default"] [:quantize "continuous" "discrete, any or quantization data" "splits domain into evenly sized segments"] [:datetime "continuous, temporal" "continuous, numerical" "temporal"] [:histogram "data, numerical" "discrete, numerical or bin data" "splits data into bins"] [:quantile "data, numerical" "discrete, numerical or quantile data" "splits data into quantiles"] [:threshold "continuous, numerical" "discrete, any or segment data" "splits data into segments by given thresholds"] [:bands "discrete, any" "discrete, numerical or bin data" "assigns domain values into evenly sized segments"] [:ordinal "discrete, any" "discrete, any" "maps domain and range values"] [:constant "any" "any" "returns constant value"]]}) ;; Scale acts as a mathematical function with defined inverse in most cases. Additionally there is a selection of helper functions to access range, domain, representation values (ticks) and scale modifications. # # # Custom scales Wadogo allows creation of custom continuous numerical scale from provided ` forward ` and ` inverse ` functions . See examples below . ;; ## Basics ;; Let's import `wadago.scale` name space as an entry point (require '[wadogo.scale :as s]) ;; To illustrate functions we'll use the logarithmic scale mapping `[2.0 5.0]` domain to `[-1.0 1.0]` range. To create any scale we use `scale` multimethod. Parameters are optional and there as some defaults for every scale kind. (def logarithmic (s/scale :log {:domain [0.5 1001.0] :range [-1.0 1.0]})) (clerk/vl (cont->cont logarithmic)) # # # Scaling ;; To perform scaling, use a scale as a function or call `forward` function. (map logarithmic [0.0 2.0 3.0 6.0 8.0]) (s/forward logarithmic 1.0) ;; In most cases inverse transformation is also possible (s/inverse logarithmic -1.0) # # # Fields ;; Scale itself is a custom type, implementing `IFn` interface and containing following fields: ;; * `kind` - kind of the scale ;; * `domain` - domain of the transformation ;; * `range` - range of the transformation ;; * `data` - any data as a map, some scales store additional information there. ^{::clerk/visibility :hide} (clerk/example (s/kind logarithmic) (s/domain logarithmic) (s/range logarithmic) (s/data logarithmic)) ;; We can also read particular key from `data` field. (s/data logarithmic :base) # # # Size ;; To get information about size of the domain or range (default), call `size`. ^{::clerk/visibility :hide} (clerk/example (s/size logarithmic :domain) (s/size logarithmic :range) (s/size logarithmic)) # # # Updating scale ;; To change some of the fields while keeping the others you can call `with-` functions. ^{::clerk/visibility :hide} (clerk/example (s/with-domain logarithmic [100.0 200.0]) (s/with-range logarithmic [99.0 -99.0]) (s/with-data logarithmic {:anything 11.0}) (s/with-data logarithmic :anything 11.0) (s/with-data logarithmic :anything 11.0 :something 22) (s/with-kind logarithmic :linear)) # # # Ticks ;; Every scale is able to produce `ticks`, ie. sequence of values which is taken from domain (or range in certain cases). User can also provide own ticks or expected number of ticks. The exact number of returned ticks can differ from expected number of ticks. ^{::clerk/visibility :hide} (clerk/example (s/ticks logarithmic) (s/ticks (s/with-ticks logarithmic 2)) (s/ticks logarithmic 2) ;; same as above (s/ticks (s/with-ticks logarithmic [1 50 500]))) (clerk/vl (cont->cont (s/with-ticks logarithmic [1 50 500]))) # # # Formatting Ticks ( or any values ) can be formatter to a string . ` wadogo ` provides some default formatters for different kind of scales . ;; * `format` - formats ticks or provided sequence ;; * `formatter` returns a formatter ;; Custom formatter can be provided by setting `formatter` key during scale creation. ^{::clerk/visibility :hide} (clerk/example (s/format logarithmic) (s/format (s/with-formatter logarithmic (comp str int))) ((s/formatter logarithmic) 33.343000001)) # # # # Formatting numbers ;; Formatting ints or doubles can be parametrized by providing `:formatting-params` data map. ;; There are following parameters for doubles ;; * `:digits` - number of decimal digits, digits can be negative or positive, default: `-8` * positive - decimal part will have exact number of digits ( padded by zeros ) * negative - trailing zeros will be truncated * ` : threshold ` - when to switch into scientific notation , default : ` 8 ` * ` : na ` - how to convert ` nil ` , default : ` " NA " ` * ` : how to convert ` # # NaN ` , default : ` " NaN " ` * ` : inf ` - how to convert ` # # Inf ` , default : ` " ∞ " ` * ` : -inf ` - how to convert ` # # -Inf ` , default : ` " -∞ " ` (s/format (s/scale :linear {:formatter-params {:digits 4}})) ;; In case of integers, parameters are: * ` : digits ` - number of digits with padding with leading zeros , default : ` 0 ` ( no leading zeros ) ;; * `:hex?` - print as hexadecimal number * ` : na ` - how to convert ` nil ` , default : ` " NA " ` (s/format (s/scale :quantize {:range [0 2 4 6 9 nil 11111] :formatter-params {:hex? true :digits 4}})) # # # # Datetime ;; In case of `datetime` scale, default formatter recognizes datetime domain and adopt format accordingly. You may use `java-time/format` to create own formtatter. (require '[java-time :as dt]) (def years-scale (s/scale :datetime {:domain [(dt/local-date 2012) (dt/local-date 2101)]})) (def minutes-scale (s/scale :datetime {:domain [(dt/local-time 12 1 0 0) (dt/local-time 12 15 0 0)]})) ^{::clerk/visibility :hide} (clerk/example (s/ticks years-scale) ;; ticks (s/format years-scale) ;; formatted ticks (s/ticks minutes-scale) (s/format minutes-scale)) # # # Other ;; To convert any scale to a map, call `->map` function. (s/->map logarithmic) ;; List of all scales and type of their transformation is stored in `scale-kinds` and `mapping` vars. s/scale-kinds s/mapping ;; ## Numerical scales (continuous -> continuous) ;; This group of scales transform continuous domain into continuous range of numbers. ;; We have here: ;; * linear ;; * logarithmic ;; * symmetric log ;; * exponential ;; * interpolated (require '[wadogo.config :as cfg]) # # # Linear scale Linear scale maps a domain $ [ d_1 , d_2]$ to range $ [ r_1 , r_2]$ using following formula $ $ scale_{linear}(x ) = r_1 + \frac{r_2 - r_1}{d_2 - d_1}(x - d_1)$$ (def linear-scale (s/scale :linear {:domain [0.0 1.0] :range [-100.0 100.0]})) (clerk/vl (cont->cont linear-scale)) (clerk/example (cfg/default-params :linear) ;; default domain and range (s/scale :linear) ;; default scale, identity (linear-scale 0.2) ;; forward scaling ((s/with-range linear-scale [100.0 -100.0]) 0.2) ;; reversed range (s/inverse linear-scale 0.2) ;; inverse scaling (s/ticks linear-scale) ;; default ticks 3 ticks (s/format linear-scale) ;; ticks after formatting ) ;; Scale from data also can be created: (def linear-scale-data-domain (s/with-domain linear-scale (repeatedly 10 rand))) (clerk/vl (cont->cont linear-scale-data-domain)) (clerk/example (s/domain linear-scale-data-domain) ;; domain from data (linear-scale-data-domain 0.2) ;; forward scaling (s/inverse linear-scale-data-domain 0.2) ;; inverse scaling (s/ticks linear-scale-data-domain) ;; default ticks (s/format linear-scale-data-domain) ;; ticks after formatting ) # # # Logarithmic scale Logarithmic scale transforms lineary log of value from log of domain $ [ d_1,d_2]$ into range $ [ r_1,r_2]$. Domain should n't include ` 0.0 ` . $ $ \begin{align}scale_{log}(x ) & = r_1 + \frac{r_2 - r_1}{\log(d_2)-\log(d_1)}(\log(x)-\log(d_1 ) ) \\ & = r_1 + ( r_2 - r_1)\log_{\frac{d2}{d1}}(\frac{x}{d_1})\end{align}$$ (def log-scale (s/scale :log {:domain [0.1 100] :range [-100 100]})) (clerk/vl (cont->cont log-scale)) (clerk/example (cfg/default-params :log) ;; default domain and range (s/scale :log) ;; default scale (log-scale 0.2) ;; forward scaling ((s/with-range log-scale [100.0 -100.0]) 0.2) ;; reversed range (s/inverse log-scale 0.2) ;; inverse scaling (s/ticks log-scale) ;; default ticks 3 ticks (s/format log-scale) ;; ticks after formatting ) Let 's construct scale with base ` 2 ` , negative domain and reversed range . Scaling does n't rely on base , the result for ` base=2 ` is the same as for ` base=10 ` . The only difference is in ticks . (def log-scale-base-2 (-> log-scale (s/with-data :base 2.0) (s/with-domain [-0.25 -256]) (s/with-range [100 10]))) (clerk/vl (cont->cont log-scale-base-2)) (clerk/example (log-scale-base-2 -16) ;; forward scaling (s/inverse log-scale-base-2 50 ) ;; inverse scaling (s/ticks log-scale-base-2) ;; default ticks (s/format log-scale-base-2) ;; ticks after formatting (s/format (-> log-scale (s/with-domain [1 5000]) (s/with-data :base 16))) ;; ticks with another base and domain ) # # # Symmetric log scale In case where domain includes ` 0.0 ` , symmetric log scale can be used . $ $ symlog_{C , b}(x)=sgn(x)\log_b\left ( 1+\left| \frac{x}{C}\right| \right)$$ Flatness parameter $ C$ equals $ \frac{1}{\ln(base)}$ by default or can be provided by user . $ symlog$ function is later normalized to a domain and to a desired range . $ $ scale_{symlog}(x ) = r_1 + \frac{r_2 - r_1}{symlog(d_2)-symlog(d_1)}(symlog(x)-symlog(d_1))$$ (def symmetric-log-scale (s/scale :symlog {:domain [-7.0 5.0] :range [-20 100]})) (clerk/vl (cont->cont symmetric-log-scale)) (clerk/example (cfg/default-params :symlog) ;; default domain and range (s/scale :symlog) ;; default scale (symmetric-log-scale 0.2) ;; forward scaling ((s/with-range symmetric-log-scale [100.0 -100.0]) 0.2) ;; reversed range (s/inverse symmetric-log-scale 0.2) ;; inverse scaling (s/ticks symmetric-log-scale) ;; default ticks 3 ticks (s/format symmetric-log-scale) ;; ticks after formatting ) ;; Ticks are the same as in linear scale. ;; Changing base, changes the slope of the curve around `0.0`. We need to reset `:C` as well (if not, previous value will be used). (def symmetric-log-scale-base-2 (s/with-data symmetric-log-scale :base 2 :C nil)) (clerk/vl (cont->cont symmetric-log-scale-base-2)) # # # Power scale Power scale uses exponent ( ` 0.5 ` by default ) to scale input . ;; $$scale_{power_a}(x)=r_1+\frac{r_2-r_1}{d_2^a-d_1^a}(x^a-d_1^a)$$ (def power-scale (s/scale :pow {:domain [0 20] :range [-7 3]})) (clerk/vl (cont->cont power-scale)) (clerk/example (cfg/default-params :pow) ;; default domain and range (s/scale :pow) ;; default scale (power-scale 0.2) ;; forward scaling ((s/with-range power-scale [100.0 -100.0]) 0.2) ;; reversed range (s/inverse power-scale 0.2) ;; inverse scaling (s/ticks power-scale) ;; default ticks 3 ticks (s/format power-scale) ;; ticks after formatting ) ;; Other exponenents can be set by changing `:exponent` data. (def power-2-scale (s/with-data power-scale :exponent 2.0)) (clerk/vl (cont->cont power-2-scale)) # # # Interpolated scale This scale interpolates between points created from domain and range , ie . ( d_i , r_i)$. ` : interpolator ` parameter defines the method of interpolation , ` : interpolator - params ` is a list of parameters for ` interpolation ` function . Please refer [ fastmath.interpolation]( / fastmath / fastmath.interpolation.html#var - interpolators-1d - list ) namespace for a list of functions and interpolation names . (def interpolated-scale (s/scale :interpolated {:domain [1 2 4 6 10] :range [-7 0 2 4 20]})) (clerk/vl (cont->cont interpolated-scale)) (clerk/example (cfg/default-params :interpolated) ;; default domain and range (s/scale :interpolated) ;; default scale (interpolated-scale 0.2) ;; forward scaling ((s/with-range interpolated-scale [100.0 -100.0]) 0.2) ;; reversed range (s/inverse interpolated-scale 0.2) ;; inverse scaling (s/ticks interpolated-scale) ;; default ticks 3 ticks (s/format interpolated-scale) ;; ticks after formatting ) # # # Other interpolators (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :monotone))) (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :shepard))) (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :loess :interpolator-params [0.7 2]))) ;; ## Datetime scale (continuous -> continuous) This is linear scale which domain is a temporal interval and range is numerical . [ clojure.java - time]( / dm3 / clojure.java - time ) is used as a Java 8 datetime API . Any ` java.time.temporal . Temporal ` is supported . (def datetime-scale (s/scale :datetime {:domain [(dt/zoned-date-time 2001 10 20 4) (dt/zoned-date-time 2010 10 20 5)] :range [0 100]})) (clerk/example (cfg/default-params :datetime) ;; default domain and range (s/scale :datetime) ;; default scale (datetime-scale (dt/zoned-date-time 2002 10 20 4)) ;; forward scaling (s/inverse datetime-scale 0.2) ;; inverse scaling (s/ticks datetime-scale) ;; default ticks 3 ticks (s/format datetime-scale) ;; ticks after formatting ) (def time-scale (s/with-domain datetime-scale [(dt/local-time 12) (dt/local-time 13)])) (clerk/example (time-scale (dt/local-time 12 13)) ;; forward scaling (s/inverse time-scale 0.2) ;; inverse scaling (s/ticks time-scale) ;; default ticks 3 ticks (s/format time-scale) ;; ticks after formatting ) ;; ## Slicing data (continuous -> discrete) ;; This set of scales creates discrete points from slicing data or interval (as a domain) into smaller intervals. Following scales are defined: ;; * histogram ;; * quantile ;; * quantize ;; * threshold Forward scaling by default returns interval i d. If second ( optional ) parameter is set to true , a map with interval details is returned . Inverse scaling accepts interval i d and also returns a map with interval info . ; ;; Additionally `s/data` contains some internal interval information. Intervals are constructed following way . First is $ ( -\infin , v_1)$ , second is $ [ v_1 , v_2)$ , ... , and last is $ [ v_n,\infin)$ (def data (map m/sq (repeatedly 150 rand))) # # # Histogram Creates histogram bins from a data . ` : range ` can be used to define number of bins or a method of estimation ( one of : ` : sqrt ` , ` : sturges ` , ` : rice ` , ` : doane ` , ` : ` or ` : freedman - diaconis ` same as ` : default ` ) . (defn bin-intervals "Create intervals from histogram data" [scale] (-> (map first (-> scale (s/data :bins))) vec (conj (-> scale s/domain s/extent last)) (->> (partition 2 1)))) (def histogram-scale (s/scale :histogram {:domain data})) (clerk/vl (cont->discrete histogram-scale bin-intervals)) (clerk/example (s/range histogram-scale) ;; calculated range, bins (s/domain histogram-scale) ;; original data, here as java array (histogram-scale 0.5) ;; returns bin id returns additional data about (s/inverse histogram-scale 2) ;; same as above, returns bin data (s/ticks histogram-scale) ;; default ticks, same as range 3 ticks (s/data histogram-scale) ;; bins data [start point, bin count] ) ;; Different bin sizes (bin-intervals (s/with-range histogram-scale :sturges)) (bin-intervals (s/with-range histogram-scale 12)) # # # Quantized data It 's actually the same as ` : histogram ` with the difference in ` range ` which is a list of names . (defn quantize-intervals [scale] (let [[start end] (s/extent (s/domain scale))] (-> scale (s/data :thresholds) (conj start) vec (conj end) (->> (partition 2 1))))) (def quantize-scale (s/scale :quantize {:domain data :range [:a :b :c "fourth" 5 ::last]})) (clerk/vl (cont->discrete quantize-scale quantize-intervals)) (clerk/example range , names (s/domain quantize-scale) ;; interval (from data) returns name returns additional data about (s/inverse quantize-scale :b) ;; same as above, returns bin data (s/ticks quantize-scale) ;; default ticks, same as range 3 ticks (s/data quantize-scale) ;; interval start points ) # # # Thresholds ;; Domain should contain values which define interval endpoints. Each interval is assigned to a given range value. (def threshold-scale (s/scale :threshold {:domain [0 1 4 5 9] :range [:a :b :c "fourth" 5 ::last]})) (clerk/example (s/range threshold-scale) ;; range, interval names (s/domain threshold-scale) ;; interval start/end points (threshold-scale 4.5) ;; returns interval name (threshold-scale 4.5 true) ;; returns additional data about interval (s/inverse threshold-scale :b) ;; same as above, returns bin data (s/ticks threshold-scale) ;; default ticks, same as range 3 ticks (s/data threshold-scale) ;; interval start points ) # # # Quantiles Divides data by quantiles ( ` : range ` ) . ` : estimation - strategy ` can be either ` : legacy ` ( [ method description]( / proper / commons - math / javadocs / api-3.6 / org / apache / commons / / stat / descriptive / rank / Percentile.html ) ) or one from ` : r1 ` to ` : r9 ` ( [ estimation strategies]( / wiki / Quantile#Estimating_quantiles_from_a_sample ) ) (defn quantile-intervals "Create intervals from quantile scale data." [scale] (let [[start end] (s/extent (s/domain scale))] (-> (map first (-> scale (s/data :quantiles))) (conj start) vec (conj end) (->> (partition 2 1))))) (def quantile-scale (s/scale :quantile {:domain data})) (clerk/vl (cont->discrete quantile-scale quantile-intervals)) (clerk/example (s/range quantile-scale) ;; calculated range, bins (s/domain quantile-scale) ;; original data, here as java array (quantile-scale 0.5) ;; returns bin id returns additional data about (quantile-scale 0.9 true) (s/inverse quantile-scale 2) ;; same as above, return bin data (s/ticks quantile-scale) ;; default ticks, same as range 2 ticks ) 10 quantiles with R7 strategy (-> quantile-scale (s/with-range [0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]) (s/with-data :estimation-strategy :r7) quantile-intervals) ;; ## Bands (discrete -> continuous) ;; Bands scale maps a discrete value from a domain to a numerical value within assigned interval from a range. Intervals ( bands ) are created by slicing a range and shrinking them with padding parameters . ` padding - out ` controls outer gaps , ` padding - in ` controls gaps between bands . ` align ` controls position of the representative point inside a band . Values should be from ` 0.0 ` ( no padding , left alignment ) to ` 1.0 ` ( full padding , right alignment ) . ;; Align can be: * a number ( from ` 0.0 ` to ` 1.0 ` ) ;; * `:spread` which spreads a point from left to right for each band consecutively. ;; * a list of numbers (def bands-scale (s/scale :bands {:domain (range 5) :range [-5.0 5.0]})) (clerk/vl (bands-chart [(s/with-data bands-scale :name "padding: 0, align: 0.5, default") (s/with-data bands-scale :name "padding-out: 0.4" :padding-out 0.4) (s/with-data bands-scale :name "padding-in: 0.4" :padding-in 0.4) (s/with-data bands-scale :name "padding: 0.8" :padding-out 0.8 :padding-in 0.8) (s/with-data bands-scale :name "padding: 0.1" :padding-out 0.1 :padding-in 0.1) (s/with-data bands-scale :name "align: 0.2, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align 0.2) (s/with-data bands-scale :name "align: 0.8, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align 0.8) (s/with-data bands-scale :name "align: :spread, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align :spread) (s/with-data bands-scale :name "align: [list], padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align [0.2 0.8 0.5 0.1 0.9])])) # # Ordinal ( discrete - > discrete ) ;; Maps values from domain to a range. (def ordinal-scale (s/scale :ordinal {:domain [:a :b "11" 0] :range [-3 :some-key [2 3] {:a -11}]})) (map ordinal-scale [0 :a :b "11" :other-key]) (map (partial s/inverse ordinal-scale) [0 -3 :some-key [2 3] {:a -11}]) ;; ## Constant ;; Constant scale just maps domain value into range value (and back for inverse). (def constant-scale (s/scale :constant {:domain "any domain value" :range :any-range-value})) ^{::clerk/visibility :hide} (clerk/example (s/range constant-scale) (s/domain constant-scale) (constant-scale :in) ;; always returns range (s/inverse constant-scale 0) ;; always returns domain ) # # Custom scales ;; Creation of custom continuous numerical scale can be done with `defcustom` function. `forward` and `inverse` functions should be provided as parameters (along with a scale name). Let 's create some scales based on [ ggplot2 transformations]( - book.org / scale - position.html#scale - transformation ) and [ Sigmoid wiki]( / wiki / Sigmoid_function ) # # # asn (s/defcustom :asn #(m/atanh %) #(m/tanh %)) (def asn-scale (s/scale :asn {:domain [-0.99 0.99] :range [0.0 1.0]})) (clerk/vl (cont->cont asn-scale)) ^{::clerk/visibility :hide} (clerk/example (asn-scale 0.2) (s/inverse asn-scale 0.5383)) # # # logit (s/defcustom :logit m/logit m/sigmoid) (def logit-scale (s/scale :logit {:domain [0.1 0.9] :range [0.0 1.0]})) (clerk/vl (cont->cont logit-scale)) ^{::clerk/visibility :hide} (clerk/example (logit-scale 0.2) (s/inverse logit-scale 0.1845)) # # # probit (require '[fastmath.random :as rnd]) (s/defcustom :probit #(rnd/cdf rnd/default-normal %) #(rnd/icdf rnd/default-normal %)) (def probit-scale (s/scale :probit {:domain [-5.0 5.0] :range [0.0 1.0]})) (clerk/vl (cont->cont probit-scale)) ^{::clerk/visibility :hide} (clerk/example (probit-scale 0.2) (s/inverse probit-scale 0.5793)) # # # reciprocal (s/defcustom :reciprocal #(/ %) #(/ %)) (def reciprocal-scale (s/scale :reciprocal {:domain [0.1 5.0] :range [0.0 1.0]})) (clerk/vl (cont->cont reciprocal-scale)) ^{::clerk/visibility :hide} (clerk/example (reciprocal-scale 0.2) (s/inverse reciprocal-scale 0.510204)) # # # Gudermannian (s/defcustom :gudermannian #(* 2.0 (m/atan (m/tanh (* 0.5 %)))) #(* 2.0 (m/atanh (m/tan (* 0.5 %))))) (def gudermannian-scale (s/scale :gudermannian {:domain [-2.0 2.0] :range [0.0 1.0]})) (clerk/vl (cont->cont gudermannian-scale)) ^{::clerk/visibility :hide} (clerk/example (gudermannian-scale 0.2) (s/inverse gudermannian-scale 0.5763)) # # # Algebraic (s/defcustom :algebraic #(/ % (m/sqrt (inc (* % %)))) #(/ % (m/sqrt (- 1.0 (* % %))))) (def algebraic-scale (s/scale :algebraic {:domain [-2.0 2.0] :range [0.0 1.0]})) (clerk/vl (cont->cont algebraic-scale)) ^{::clerk/visibility :hide} (clerk/example (algebraic-scale 0.2) (s/inverse algebraic-scale 0.6096)) # # # Distribution ;; You can also make scale from any probability distribution based on `cdf` and `icdf` functions. (require '[fastmath.random :as rng]) (def pascal-distribution (rng/distribution :pascal {:p 0.3 :r 10})) (s/defcustom :pascal (partial rng/cdf pascal-distribution) (partial rng/icdf pascal-distribution)) (def pascal-scale (s/scale :pascal {:domain [0.0 20.0] :range [0.0 1.0]})) (clerk/vl (cont->cont pascal-scale)) ^{::clerk/visibility :hide} (clerk/example (pascal-scale 10.0) (s/inverse pascal-scale 0.1166)) ;; ## Source code ;; [![]()]() Source code is available on [ github]( / scicloj / wadogo ) . ^{::clerk/visibility :hide ::clerk/viewer :hide-result} (comment (clerk/serve! {:browse? false}) (clerk/show! "index.clj") (clerk/build! {:paths ["index.clj"] :out-path "docs"}) (clerk/clear-cache!) (clerk/recompute!) (clerk/halt!))
null
https://raw.githubusercontent.com/scicloj/wadogo/ae293aa28d6da55719c3f2771649c2f2e56b692b/index.clj
clojure
## Scales The scale is a structure which helps to transform one set of values into another. There are many different ways of mapping between domain and range, collected in the table below. Scale acts as a mathematical function with defined inverse in most cases. Additionally there is a selection of helper functions to access range, domain, representation values (ticks) and scale modifications. ## Basics Let's import `wadago.scale` name space as an entry point To illustrate functions we'll use the logarithmic scale mapping `[2.0 5.0]` domain to `[-1.0 1.0]` range. To create any scale we use `scale` multimethod. Parameters are optional and there as some defaults for every scale kind. To perform scaling, use a scale as a function or call `forward` function. In most cases inverse transformation is also possible Scale itself is a custom type, implementing `IFn` interface and containing following fields: * `kind` - kind of the scale * `domain` - domain of the transformation * `range` - range of the transformation * `data` - any data as a map, some scales store additional information there. We can also read particular key from `data` field. To get information about size of the domain or range (default), call `size`. To change some of the fields while keeping the others you can call `with-` functions. Every scale is able to produce `ticks`, ie. sequence of values which is taken from domain (or range in certain cases). User can also provide own ticks or expected number of ticks. The exact number of returned ticks can differ from expected number of ticks. same as above * `format` - formats ticks or provided sequence * `formatter` returns a formatter Custom formatter can be provided by setting `formatter` key during scale creation. Formatting ints or doubles can be parametrized by providing `:formatting-params` data map. There are following parameters for doubles * `:digits` - number of decimal digits, digits can be negative or positive, default: `-8` In case of integers, parameters are: * `:hex?` - print as hexadecimal number In case of `datetime` scale, default formatter recognizes datetime domain and adopt format accordingly. You may use `java-time/format` to create own formtatter. ticks formatted ticks To convert any scale to a map, call `->map` function. List of all scales and type of their transformation is stored in `scale-kinds` and `mapping` vars. ## Numerical scales (continuous -> continuous) This group of scales transform continuous domain into continuous range of numbers. We have here: * linear * logarithmic * symmetric log * exponential * interpolated default domain and range default scale, identity forward scaling reversed range inverse scaling default ticks ticks after formatting Scale from data also can be created: domain from data forward scaling inverse scaling default ticks ticks after formatting default domain and range default scale forward scaling reversed range inverse scaling default ticks ticks after formatting forward scaling inverse scaling default ticks ticks after formatting ticks with another base and domain default domain and range default scale forward scaling reversed range inverse scaling default ticks ticks after formatting Ticks are the same as in linear scale. Changing base, changes the slope of the curve around `0.0`. We need to reset `:C` as well (if not, previous value will be used). $$scale_{power_a}(x)=r_1+\frac{r_2-r_1}{d_2^a-d_1^a}(x^a-d_1^a)$$ default domain and range default scale forward scaling reversed range inverse scaling default ticks ticks after formatting Other exponenents can be set by changing `:exponent` data. default domain and range default scale forward scaling reversed range inverse scaling default ticks ticks after formatting ## Datetime scale (continuous -> continuous) default domain and range default scale forward scaling inverse scaling default ticks ticks after formatting forward scaling inverse scaling default ticks ticks after formatting ## Slicing data (continuous -> discrete) This set of scales creates discrete points from slicing data or interval (as a domain) into smaller intervals. Following scales are defined: * histogram * quantile * quantize * threshold Additionally `s/data` contains some internal interval information. calculated range, bins original data, here as java array returns bin id same as above, returns bin data default ticks, same as range bins data [start point, bin count] Different bin sizes interval (from data) same as above, returns bin data default ticks, same as range interval start points Domain should contain values which define interval endpoints. Each interval is assigned to a given range value. range, interval names interval start/end points returns interval name returns additional data about interval same as above, returns bin data default ticks, same as range interval start points calculated range, bins original data, here as java array returns bin id same as above, return bin data default ticks, same as range ## Bands (discrete -> continuous) Bands scale maps a discrete value from a domain to a numerical value within assigned interval from a range. Align can be: * `:spread` which spreads a point from left to right for each band consecutively. * a list of numbers Maps values from domain to a range. ## Constant Constant scale just maps domain value into range value (and back for inverse). always returns range always returns domain Creation of custom continuous numerical scale can be done with `defcustom` function. `forward` and `inverse` functions should be provided as parameters (along with a scale name). You can also make scale from any probability distribution based on `cdf` and `icdf` functions. ## Source code [![]()]()
# Wadogo scales Wadogo is the library which brings various transformations between domain and range ( codomain ) , either continuous or discrete . The idea is based on [ d3 - scale]( / d3 / d3 - scale ) and originally was a part of [ cljplot]( / generateme / cljplot ) library . There are 13 different scales with unified api . * The ` wadogo ` name came up after trying to translate word ` scale ` into different languages using [ google translate]( = en&tl = sw&text = = translate ) . Swahili word was very pleasant and was choosen on zulip chat by a community . Funny enough is that ` wadogo ` does n't mean ` scale ` at all but ` small ` or ` little ` . Translator failed here . * ^{:nextjournal.clerk/visibility :hide-ns :nextjournal.clerk/no-cache true :nextjournal.clerk/toc :collapsed} (ns index (:require [nextjournal.clerk :as clerk] [wadogo.scale :as s] [fastmath.core :as m])) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn cont->cont ([scale] (cont->cont scale {})) ([scale {:keys [w h] :or {w 400 h 200}}] (let [x1 (first (s/domain scale)) x2 (last (s/domain scale))] {:mode "vega-lite" :width w :height h :data {:values (map (partial zipmap [:domain :range]) (map #(vector % (scale %)) (m/slice-range x1 x2 80)))} :mark "line" :encoding {:x {:field "domain" :type "quantitative" :axis {:values (s/format scale)}} :y {:field "range" :type "quantitative"}}}))) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn cont->discrete [scale selector] (let [y (s/range scale) x (selector scale)] {:mode "vega-lite" :width 400 :height 200 :data {:values (map (fn [x y] {:y y :x1 (first x) :x2 (second x)}) x y)} :mark "bar" :encoding {:y {:field "y" :type "ordinal"} :x {:field "x1" :type "quantitative"} :x2 {:field "x2"}}})) ^{::clerk/visibility :fold ::clerk/viewer :hide-result} (defn bands-chart [scales] {:mode "vega-lite" :width 500 :height 200 :data {:values (mapcat (fn [scale] (let [n (s/data scale :name)] (map #(assoc % :name n) (s/data scale :bands)))) scales)} :encoding {:y {:field "name" :axis {:title nil}} :x {:type "quantitative" :axis {:title nil}}} :layer [{:mark "rule" :encoding {:x {:field "rstart"} :x2 {:field "rend"}}} {:mark {:type "circle" :stroke "green" :opacity 0.9} :encoding {:x {:field "point"}}}]}) ^{::clerk/visibility #{:hide}} (clerk/table {:head ["scale kind" "domain" "range" "info"] :rows [[:linear "continuous, numerical" "continuous, numerical" "linear"] [:log "continuous, numerical, positive values" "continuous, numerical" "logarithmic, base=10.0"] [:symlog "continuous, numerical" "continuous, numerical" "logarithmic (symmetric), base=10.0"] [:pow "continuous, numerical" "continuous, numerical" "power, exponent=0.5"] [:interpolated "continuous, numerical, segmented" "continuous, numerical" "interpolated function, linear by default"] [:quantize "continuous" "discrete, any or quantization data" "splits domain into evenly sized segments"] [:datetime "continuous, temporal" "continuous, numerical" "temporal"] [:histogram "data, numerical" "discrete, numerical or bin data" "splits data into bins"] [:quantile "data, numerical" "discrete, numerical or quantile data" "splits data into quantiles"] [:threshold "continuous, numerical" "discrete, any or segment data" "splits data into segments by given thresholds"] [:bands "discrete, any" "discrete, numerical or bin data" "assigns domain values into evenly sized segments"] [:ordinal "discrete, any" "discrete, any" "maps domain and range values"] [:constant "any" "any" "returns constant value"]]}) # # # Custom scales Wadogo allows creation of custom continuous numerical scale from provided ` forward ` and ` inverse ` functions . See examples below . (require '[wadogo.scale :as s]) (def logarithmic (s/scale :log {:domain [0.5 1001.0] :range [-1.0 1.0]})) (clerk/vl (cont->cont logarithmic)) # # # Scaling (map logarithmic [0.0 2.0 3.0 6.0 8.0]) (s/forward logarithmic 1.0) (s/inverse logarithmic -1.0) # # # Fields ^{::clerk/visibility :hide} (clerk/example (s/kind logarithmic) (s/domain logarithmic) (s/range logarithmic) (s/data logarithmic)) (s/data logarithmic :base) # # # Size ^{::clerk/visibility :hide} (clerk/example (s/size logarithmic :domain) (s/size logarithmic :range) (s/size logarithmic)) # # # Updating scale ^{::clerk/visibility :hide} (clerk/example (s/with-domain logarithmic [100.0 200.0]) (s/with-range logarithmic [99.0 -99.0]) (s/with-data logarithmic {:anything 11.0}) (s/with-data logarithmic :anything 11.0) (s/with-data logarithmic :anything 11.0 :something 22) (s/with-kind logarithmic :linear)) # # # Ticks ^{::clerk/visibility :hide} (clerk/example (s/ticks logarithmic) (s/ticks (s/with-ticks logarithmic 2)) (s/ticks (s/with-ticks logarithmic [1 50 500]))) (clerk/vl (cont->cont (s/with-ticks logarithmic [1 50 500]))) # # # Formatting Ticks ( or any values ) can be formatter to a string . ` wadogo ` provides some default formatters for different kind of scales . ^{::clerk/visibility :hide} (clerk/example (s/format logarithmic) (s/format (s/with-formatter logarithmic (comp str int))) ((s/formatter logarithmic) 33.343000001)) # # # # Formatting numbers * positive - decimal part will have exact number of digits ( padded by zeros ) * negative - trailing zeros will be truncated * ` : threshold ` - when to switch into scientific notation , default : ` 8 ` * ` : na ` - how to convert ` nil ` , default : ` " NA " ` * ` : how to convert ` # # NaN ` , default : ` " NaN " ` * ` : inf ` - how to convert ` # # Inf ` , default : ` " ∞ " ` * ` : -inf ` - how to convert ` # # -Inf ` , default : ` " -∞ " ` (s/format (s/scale :linear {:formatter-params {:digits 4}})) * ` : digits ` - number of digits with padding with leading zeros , default : ` 0 ` ( no leading zeros ) * ` : na ` - how to convert ` nil ` , default : ` " NA " ` (s/format (s/scale :quantize {:range [0 2 4 6 9 nil 11111] :formatter-params {:hex? true :digits 4}})) # # # # Datetime (require '[java-time :as dt]) (def years-scale (s/scale :datetime {:domain [(dt/local-date 2012) (dt/local-date 2101)]})) (def minutes-scale (s/scale :datetime {:domain [(dt/local-time 12 1 0 0) (dt/local-time 12 15 0 0)]})) ^{::clerk/visibility :hide} (clerk/example (s/ticks minutes-scale) (s/format minutes-scale)) # # # Other (s/->map logarithmic) s/scale-kinds s/mapping (require '[wadogo.config :as cfg]) # # # Linear scale Linear scale maps a domain $ [ d_1 , d_2]$ to range $ [ r_1 , r_2]$ using following formula $ $ scale_{linear}(x ) = r_1 + \frac{r_2 - r_1}{d_2 - d_1}(x - d_1)$$ (def linear-scale (s/scale :linear {:domain [0.0 1.0] :range [-100.0 100.0]})) (clerk/vl (cont->cont linear-scale)) (clerk/example 3 ticks ) (def linear-scale-data-domain (s/with-domain linear-scale (repeatedly 10 rand))) (clerk/vl (cont->cont linear-scale-data-domain)) (clerk/example ) # # # Logarithmic scale Logarithmic scale transforms lineary log of value from log of domain $ [ d_1,d_2]$ into range $ [ r_1,r_2]$. Domain should n't include ` 0.0 ` . $ $ \begin{align}scale_{log}(x ) & = r_1 + \frac{r_2 - r_1}{\log(d_2)-\log(d_1)}(\log(x)-\log(d_1 ) ) \\ & = r_1 + ( r_2 - r_1)\log_{\frac{d2}{d1}}(\frac{x}{d_1})\end{align}$$ (def log-scale (s/scale :log {:domain [0.1 100] :range [-100 100]})) (clerk/vl (cont->cont log-scale)) (clerk/example 3 ticks ) Let 's construct scale with base ` 2 ` , negative domain and reversed range . Scaling does n't rely on base , the result for ` base=2 ` is the same as for ` base=10 ` . The only difference is in ticks . (def log-scale-base-2 (-> log-scale (s/with-data :base 2.0) (s/with-domain [-0.25 -256]) (s/with-range [100 10]))) (clerk/vl (cont->cont log-scale-base-2)) (clerk/example (s/format (-> log-scale (s/with-domain [1 5000]) ) # # # Symmetric log scale In case where domain includes ` 0.0 ` , symmetric log scale can be used . $ $ symlog_{C , b}(x)=sgn(x)\log_b\left ( 1+\left| \frac{x}{C}\right| \right)$$ Flatness parameter $ C$ equals $ \frac{1}{\ln(base)}$ by default or can be provided by user . $ symlog$ function is later normalized to a domain and to a desired range . $ $ scale_{symlog}(x ) = r_1 + \frac{r_2 - r_1}{symlog(d_2)-symlog(d_1)}(symlog(x)-symlog(d_1))$$ (def symmetric-log-scale (s/scale :symlog {:domain [-7.0 5.0] :range [-20 100]})) (clerk/vl (cont->cont symmetric-log-scale)) (clerk/example 3 ticks ) (def symmetric-log-scale-base-2 (s/with-data symmetric-log-scale :base 2 :C nil)) (clerk/vl (cont->cont symmetric-log-scale-base-2)) # # # Power scale Power scale uses exponent ( ` 0.5 ` by default ) to scale input . (def power-scale (s/scale :pow {:domain [0 20] :range [-7 3]})) (clerk/vl (cont->cont power-scale)) (clerk/example 3 ticks ) (def power-2-scale (s/with-data power-scale :exponent 2.0)) (clerk/vl (cont->cont power-2-scale)) # # # Interpolated scale This scale interpolates between points created from domain and range , ie . ( d_i , r_i)$. ` : interpolator ` parameter defines the method of interpolation , ` : interpolator - params ` is a list of parameters for ` interpolation ` function . Please refer [ fastmath.interpolation]( / fastmath / fastmath.interpolation.html#var - interpolators-1d - list ) namespace for a list of functions and interpolation names . (def interpolated-scale (s/scale :interpolated {:domain [1 2 4 6 10] :range [-7 0 2 4 20]})) (clerk/vl (cont->cont interpolated-scale)) (clerk/example 3 ticks ) # # # Other interpolators (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :monotone))) (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :shepard))) (clerk/vl (cont->cont (s/with-data interpolated-scale :interpolator :loess :interpolator-params [0.7 2]))) This is linear scale which domain is a temporal interval and range is numerical . [ clojure.java - time]( / dm3 / clojure.java - time ) is used as a Java 8 datetime API . Any ` java.time.temporal . Temporal ` is supported . (def datetime-scale (s/scale :datetime {:domain [(dt/zoned-date-time 2001 10 20 4) (dt/zoned-date-time 2010 10 20 5)] :range [0 100]})) (clerk/example 3 ticks ) (def time-scale (s/with-domain datetime-scale [(dt/local-time 12) (dt/local-time 13)])) (clerk/example 3 ticks ) Forward scaling by default returns interval i d. If second ( optional ) parameter is set to true , a map with interval details is returned . Inverse scaling accepts interval i d and also returns a map with interval info . Intervals are constructed following way . First is $ ( -\infin , v_1)$ , second is $ [ v_1 , v_2)$ , ... , and last is $ [ v_n,\infin)$ (def data (map m/sq (repeatedly 150 rand))) # # # Histogram Creates histogram bins from a data . ` : range ` can be used to define number of bins or a method of estimation ( one of : ` : sqrt ` , ` : sturges ` , ` : rice ` , ` : doane ` , ` : ` or ` : freedman - diaconis ` same as ` : default ` ) . (defn bin-intervals "Create intervals from histogram data" [scale] (-> (map first (-> scale (s/data :bins))) vec (conj (-> scale s/domain s/extent last)) (->> (partition 2 1)))) (def histogram-scale (s/scale :histogram {:domain data})) (clerk/vl (cont->discrete histogram-scale bin-intervals)) (clerk/example returns additional data about 3 ticks ) (bin-intervals (s/with-range histogram-scale :sturges)) (bin-intervals (s/with-range histogram-scale 12)) # # # Quantized data It 's actually the same as ` : histogram ` with the difference in ` range ` which is a list of names . (defn quantize-intervals [scale] (let [[start end] (s/extent (s/domain scale))] (-> scale (s/data :thresholds) (conj start) vec (conj end) (->> (partition 2 1))))) (def quantize-scale (s/scale :quantize {:domain data :range [:a :b :c "fourth" 5 ::last]})) (clerk/vl (cont->discrete quantize-scale quantize-intervals)) (clerk/example range , names returns name returns additional data about 3 ticks ) # # # Thresholds (def threshold-scale (s/scale :threshold {:domain [0 1 4 5 9] :range [:a :b :c "fourth" 5 ::last]})) (clerk/example 3 ticks ) # # # Quantiles Divides data by quantiles ( ` : range ` ) . ` : estimation - strategy ` can be either ` : legacy ` ( [ method description]( / proper / commons - math / javadocs / api-3.6 / org / apache / commons / / stat / descriptive / rank / Percentile.html ) ) or one from ` : r1 ` to ` : r9 ` ( [ estimation strategies]( / wiki / Quantile#Estimating_quantiles_from_a_sample ) ) (defn quantile-intervals "Create intervals from quantile scale data." [scale] (let [[start end] (s/extent (s/domain scale))] (-> (map first (-> scale (s/data :quantiles))) (conj start) vec (conj end) (->> (partition 2 1))))) (def quantile-scale (s/scale :quantile {:domain data})) (clerk/vl (cont->discrete quantile-scale quantile-intervals)) (clerk/example returns additional data about (quantile-scale 0.9 true) 2 ticks ) 10 quantiles with R7 strategy (-> quantile-scale (s/with-range [0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]) (s/with-data :estimation-strategy :r7) quantile-intervals) Intervals ( bands ) are created by slicing a range and shrinking them with padding parameters . ` padding - out ` controls outer gaps , ` padding - in ` controls gaps between bands . ` align ` controls position of the representative point inside a band . Values should be from ` 0.0 ` ( no padding , left alignment ) to ` 1.0 ` ( full padding , right alignment ) . * a number ( from ` 0.0 ` to ` 1.0 ` ) (def bands-scale (s/scale :bands {:domain (range 5) :range [-5.0 5.0]})) (clerk/vl (bands-chart [(s/with-data bands-scale :name "padding: 0, align: 0.5, default") (s/with-data bands-scale :name "padding-out: 0.4" :padding-out 0.4) (s/with-data bands-scale :name "padding-in: 0.4" :padding-in 0.4) (s/with-data bands-scale :name "padding: 0.8" :padding-out 0.8 :padding-in 0.8) (s/with-data bands-scale :name "padding: 0.1" :padding-out 0.1 :padding-in 0.1) (s/with-data bands-scale :name "align: 0.2, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align 0.2) (s/with-data bands-scale :name "align: 0.8, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align 0.8) (s/with-data bands-scale :name "align: :spread, padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align :spread) (s/with-data bands-scale :name "align: [list], padding: 0.1" :padding-out 0.1 :padding-in 0.1 :align [0.2 0.8 0.5 0.1 0.9])])) # # Ordinal ( discrete - > discrete ) (def ordinal-scale (s/scale :ordinal {:domain [:a :b "11" 0] :range [-3 :some-key [2 3] {:a -11}]})) (map ordinal-scale [0 :a :b "11" :other-key]) (map (partial s/inverse ordinal-scale) [0 -3 :some-key [2 3] {:a -11}]) (def constant-scale (s/scale :constant {:domain "any domain value" :range :any-range-value})) ^{::clerk/visibility :hide} (clerk/example (s/range constant-scale) (s/domain constant-scale) ) # # Custom scales Let 's create some scales based on [ ggplot2 transformations]( - book.org / scale - position.html#scale - transformation ) and [ Sigmoid wiki]( / wiki / Sigmoid_function ) # # # asn (s/defcustom :asn #(m/atanh %) #(m/tanh %)) (def asn-scale (s/scale :asn {:domain [-0.99 0.99] :range [0.0 1.0]})) (clerk/vl (cont->cont asn-scale)) ^{::clerk/visibility :hide} (clerk/example (asn-scale 0.2) (s/inverse asn-scale 0.5383)) # # # logit (s/defcustom :logit m/logit m/sigmoid) (def logit-scale (s/scale :logit {:domain [0.1 0.9] :range [0.0 1.0]})) (clerk/vl (cont->cont logit-scale)) ^{::clerk/visibility :hide} (clerk/example (logit-scale 0.2) (s/inverse logit-scale 0.1845)) # # # probit (require '[fastmath.random :as rnd]) (s/defcustom :probit #(rnd/cdf rnd/default-normal %) #(rnd/icdf rnd/default-normal %)) (def probit-scale (s/scale :probit {:domain [-5.0 5.0] :range [0.0 1.0]})) (clerk/vl (cont->cont probit-scale)) ^{::clerk/visibility :hide} (clerk/example (probit-scale 0.2) (s/inverse probit-scale 0.5793)) # # # reciprocal (s/defcustom :reciprocal #(/ %) #(/ %)) (def reciprocal-scale (s/scale :reciprocal {:domain [0.1 5.0] :range [0.0 1.0]})) (clerk/vl (cont->cont reciprocal-scale)) ^{::clerk/visibility :hide} (clerk/example (reciprocal-scale 0.2) (s/inverse reciprocal-scale 0.510204)) # # # Gudermannian (s/defcustom :gudermannian #(* 2.0 (m/atan (m/tanh (* 0.5 %)))) #(* 2.0 (m/atanh (m/tan (* 0.5 %))))) (def gudermannian-scale (s/scale :gudermannian {:domain [-2.0 2.0] :range [0.0 1.0]})) (clerk/vl (cont->cont gudermannian-scale)) ^{::clerk/visibility :hide} (clerk/example (gudermannian-scale 0.2) (s/inverse gudermannian-scale 0.5763)) # # # Algebraic (s/defcustom :algebraic #(/ % (m/sqrt (inc (* % %)))) #(/ % (m/sqrt (- 1.0 (* % %))))) (def algebraic-scale (s/scale :algebraic {:domain [-2.0 2.0] :range [0.0 1.0]})) (clerk/vl (cont->cont algebraic-scale)) ^{::clerk/visibility :hide} (clerk/example (algebraic-scale 0.2) (s/inverse algebraic-scale 0.6096)) # # # Distribution (require '[fastmath.random :as rng]) (def pascal-distribution (rng/distribution :pascal {:p 0.3 :r 10})) (s/defcustom :pascal (partial rng/cdf pascal-distribution) (partial rng/icdf pascal-distribution)) (def pascal-scale (s/scale :pascal {:domain [0.0 20.0] :range [0.0 1.0]})) (clerk/vl (cont->cont pascal-scale)) ^{::clerk/visibility :hide} (clerk/example (pascal-scale 10.0) (s/inverse pascal-scale 0.1166)) Source code is available on [ github]( / scicloj / wadogo ) . ^{::clerk/visibility :hide ::clerk/viewer :hide-result} (comment (clerk/serve! {:browse? false}) (clerk/show! "index.clj") (clerk/build! {:paths ["index.clj"] :out-path "docs"}) (clerk/clear-cache!) (clerk/recompute!) (clerk/halt!))
eeade1c9098ed06f39a71610b6c7e842cdba48aecaaa72a409b127d5014ae242
hslua/hslua
Documentation.hs
{-# LANGUAGE OverloadedStrings #-} | Module : HsLua . Packaging . Documentation Copyright : © 2020 - 2023 : MIT Maintainer : < tarleb+ > Provides a function to print documentation if available . Module : HsLua.Packaging.Documentation Copyright : © 2020-2023 Albert Krewinkel License : MIT Maintainer : Albert Krewinkel <tarleb+> Provides a function to print documentation if available. -} module HsLua.Packaging.Documentation ( documentation , getdocumentation , registerDocumentation , pushModuleDoc , pushTypeDoc , pushFunctionDoc , pushFieldDoc , docsField ) where import Data.Version (showVersion) import HsLua.Core as Lua import HsLua.Marshalling import HsLua.Packaging.Types import HsLua.Typing (TypeDocs (..), typeSpecToString) -- | Function that retrieves documentation. documentation :: LuaError e => DocumentedFunction e documentation = DocumentedFunction { callFunction = documentationHaskellFunction , functionName = "documentation" , functionDoc = FunctionDoc { functionDescription = "Retrieves the documentation of the given object." , parameterDocs = [ ParameterDoc { parameterName = "value" , parameterType = "any" , parameterDescription = "documented object" , parameterIsOptional = False } ] , functionResultsDocs = ResultsDocList [ ResultValueDoc "string|nil" "docstring" ] , functionSince = Nothing } } -- | Function that returns the documentation of a given object, or @nil@ -- if no documentation is available. documentationHaskellFunction :: LuaError e => LuaE e NumResults documentationHaskellFunction = isnoneornil (nthBottom 1) >>= \case True -> failLua "expected a non-nil value as argument 1" _ -> NumResults 1 <$ getdocumentation top -- | Pushes the documentation for the element at the given stack index. -- Returns the type of the documentation object. getdocumentation :: LuaError e => StackIndex -> LuaE e Lua.Type getdocumentation idx = do idx' <- absindex idx pushDocumentationTable pushvalue idx' rawget (nth 2) <* Lua.remove (nth 2) -- remove documentation table -- | Registers the object at the top of the stack as documentation for the object at index @idx@. Pops the documentation of the stack . registerDocumentation :: LuaError e => StackIndex -- ^ @idx@ -> LuaE e () registerDocumentation idx = do checkstack' 10 "registerDocumentation" -- keep some buffer idx' <- absindex idx pushDocumentationTable pushvalue idx' -- the documented object pushvalue (nth 3) -- documentation object rawset (nth 3) -- add to docs table pop 2 -- docs table and documentation object -- | Pushes the documentation table that's stored in the registry to the -- top of the stack, creating it if necessary. The documentation table -- is indexed by the documented objects, like module tables and -- functions, and contains documentation strings as values. -- The table is an ephemeron table , i.e. , an entry gets garbage -- collected if the key is no longer reachable. pushDocumentationTable :: LuaError e => LuaE e () pushDocumentationTable = Lua.getfield registryindex docsField >>= \case Lua.TypeTable -> return () -- documentation table already initialized _ -> do pop 1 -- pop non-table value newtable -- create documentation table Make it an " ephemeron table " and .. collect docs if documented object is GCed pushvalue top -- add copy of table to registry setfield registryindex docsField -- | Name of the registry field holding the documentation table. The -- documentation table is indexed by the documented objects, like module -- tables and functions, and contains documentation strings as values. -- The table is an ephemeron table , i.e. , an entry gets garbage -- collected if the key is no longer reachable. docsField :: Name docsField = "HsLua docs" -- | Pushes the documentation of a module as a table with string fields @name@ and @description@. pushModuleDoc :: LuaError e => Pusher e (Module e) pushModuleDoc = pushAsTable [ ("name", pushName . moduleName) , ("description", pushText . moduleDescription) , ("fields", pushList pushFieldDoc . moduleFields) , ("functions", pushList pushFunctionDoc . moduleFunctions) ] -- | Pushes the documentation of a field as a table with string fields @name@ and @description@. pushFieldDoc :: LuaError e => Pusher e (Field e) pushFieldDoc = pushAsTable [ ("name", pushText . fieldName) , ("type", pushString . typeSpecToString . fieldType) , ("description", pushText . fieldDescription) ] -- | Pushes the documentation of a function as a table with string -- fields, @name@, @description@, and @since@, sequence field -- @parameters@, and sequence or string field @results@. pushFunctionDoc :: LuaError e => Pusher e (DocumentedFunction e) pushFunctionDoc fun = pushAsTable [ ("name", pushName . const (functionName fun)) , ("description", pushText . functionDescription) , ("parameters", pushList pushParameterDoc . parameterDocs) , ("results", pushResultsDoc . functionResultsDocs) , ("since", maybe pushnil (pushString . showVersion) . functionSince) ] (functionDoc fun) -- | Pushes the documentation of a parameter as a table with boolean field @optional@ and string fields @name@ , @type@ , and @description@. pushParameterDoc :: LuaError e => Pusher e ParameterDoc pushParameterDoc = pushAsTable [ ("name", pushText . parameterName) , ("type", pushText . parameterType) , ("description", pushText . parameterDescription) , ("optional", pushBool . parameterIsOptional) ] -- | Pushes a the documentation for a function's return values as either -- a simple string, or as a sequence of tables with @type@ and -- @description@ fields. pushResultsDoc :: LuaError e => Pusher e ResultsDoc pushResultsDoc = \case ResultsDocMult desc -> pushText desc ResultsDocList resultDocs -> pushList pushResultValueDoc resultDocs -- | Pushes the documentation of a single result value as a table with fields @type@ and @description@. pushResultValueDoc :: LuaError e => Pusher e ResultValueDoc pushResultValueDoc = pushAsTable [ ("type", pushText . resultValueType) , ("description", pushText . resultValueDescription) ] -- | Pushes documentation for a custom type. pushTypeDoc :: LuaError e => Pusher e TypeDocs pushTypeDoc = pushAsTable [ ("name", pushName . typeName) , ("description", pushText . typeDescription) , ("registry", maybe pushnil pushName . typeRegistry) ]
null
https://raw.githubusercontent.com/hslua/hslua/e86d00dfa8b0915f3060c9e618fc3e373048d9c2/hslua-packaging/src/HsLua/Packaging/Documentation.hs
haskell
# LANGUAGE OverloadedStrings # | Function that retrieves documentation. | Function that returns the documentation of a given object, or @nil@ if no documentation is available. | Pushes the documentation for the element at the given stack index. Returns the type of the documentation object. remove documentation table | Registers the object at the top of the stack as documentation for ^ @idx@ keep some buffer the documented object documentation object add to docs table docs table and documentation object | Pushes the documentation table that's stored in the registry to the top of the stack, creating it if necessary. The documentation table is indexed by the documented objects, like module tables and functions, and contains documentation strings as values. collected if the key is no longer reachable. documentation table already initialized pop non-table value create documentation table add copy of table to registry | Name of the registry field holding the documentation table. The documentation table is indexed by the documented objects, like module tables and functions, and contains documentation strings as values. collected if the key is no longer reachable. | Pushes the documentation of a module as a table with string fields | Pushes the documentation of a field as a table with string fields | Pushes the documentation of a function as a table with string fields, @name@, @description@, and @since@, sequence field @parameters@, and sequence or string field @results@. | Pushes the documentation of a parameter as a table with boolean | Pushes a the documentation for a function's return values as either a simple string, or as a sequence of tables with @type@ and @description@ fields. | Pushes the documentation of a single result value as a table with | Pushes documentation for a custom type.
| Module : HsLua . Packaging . Documentation Copyright : © 2020 - 2023 : MIT Maintainer : < tarleb+ > Provides a function to print documentation if available . Module : HsLua.Packaging.Documentation Copyright : © 2020-2023 Albert Krewinkel License : MIT Maintainer : Albert Krewinkel <tarleb+> Provides a function to print documentation if available. -} module HsLua.Packaging.Documentation ( documentation , getdocumentation , registerDocumentation , pushModuleDoc , pushTypeDoc , pushFunctionDoc , pushFieldDoc , docsField ) where import Data.Version (showVersion) import HsLua.Core as Lua import HsLua.Marshalling import HsLua.Packaging.Types import HsLua.Typing (TypeDocs (..), typeSpecToString) documentation :: LuaError e => DocumentedFunction e documentation = DocumentedFunction { callFunction = documentationHaskellFunction , functionName = "documentation" , functionDoc = FunctionDoc { functionDescription = "Retrieves the documentation of the given object." , parameterDocs = [ ParameterDoc { parameterName = "value" , parameterType = "any" , parameterDescription = "documented object" , parameterIsOptional = False } ] , functionResultsDocs = ResultsDocList [ ResultValueDoc "string|nil" "docstring" ] , functionSince = Nothing } } documentationHaskellFunction :: LuaError e => LuaE e NumResults documentationHaskellFunction = isnoneornil (nthBottom 1) >>= \case True -> failLua "expected a non-nil value as argument 1" _ -> NumResults 1 <$ getdocumentation top getdocumentation :: LuaError e => StackIndex -> LuaE e Lua.Type getdocumentation idx = do idx' <- absindex idx pushDocumentationTable pushvalue idx' the object at index @idx@. Pops the documentation of the stack . registerDocumentation :: LuaError e -> LuaE e () registerDocumentation idx = do idx' <- absindex idx pushDocumentationTable The table is an ephemeron table , i.e. , an entry gets garbage pushDocumentationTable :: LuaError e => LuaE e () pushDocumentationTable = Lua.getfield registryindex docsField >>= \case _ -> do Make it an " ephemeron table " and .. collect docs if documented object is GCed setfield registryindex docsField The table is an ephemeron table , i.e. , an entry gets garbage docsField :: Name docsField = "HsLua docs" @name@ and @description@. pushModuleDoc :: LuaError e => Pusher e (Module e) pushModuleDoc = pushAsTable [ ("name", pushName . moduleName) , ("description", pushText . moduleDescription) , ("fields", pushList pushFieldDoc . moduleFields) , ("functions", pushList pushFunctionDoc . moduleFunctions) ] @name@ and @description@. pushFieldDoc :: LuaError e => Pusher e (Field e) pushFieldDoc = pushAsTable [ ("name", pushText . fieldName) , ("type", pushString . typeSpecToString . fieldType) , ("description", pushText . fieldDescription) ] pushFunctionDoc :: LuaError e => Pusher e (DocumentedFunction e) pushFunctionDoc fun = pushAsTable [ ("name", pushName . const (functionName fun)) , ("description", pushText . functionDescription) , ("parameters", pushList pushParameterDoc . parameterDocs) , ("results", pushResultsDoc . functionResultsDocs) , ("since", maybe pushnil (pushString . showVersion) . functionSince) ] (functionDoc fun) field @optional@ and string fields @name@ , @type@ , and @description@. pushParameterDoc :: LuaError e => Pusher e ParameterDoc pushParameterDoc = pushAsTable [ ("name", pushText . parameterName) , ("type", pushText . parameterType) , ("description", pushText . parameterDescription) , ("optional", pushBool . parameterIsOptional) ] pushResultsDoc :: LuaError e => Pusher e ResultsDoc pushResultsDoc = \case ResultsDocMult desc -> pushText desc ResultsDocList resultDocs -> pushList pushResultValueDoc resultDocs fields @type@ and @description@. pushResultValueDoc :: LuaError e => Pusher e ResultValueDoc pushResultValueDoc = pushAsTable [ ("type", pushText . resultValueType) , ("description", pushText . resultValueDescription) ] pushTypeDoc :: LuaError e => Pusher e TypeDocs pushTypeDoc = pushAsTable [ ("name", pushName . typeName) , ("description", pushText . typeDescription) , ("registry", maybe pushnil pushName . typeRegistry) ]
52bcb38a098579d661702b60dd1dac379de3b59c96c9fcf4ea43fad2ac62ab52
fredlund/McErlang
mce_erl_analyze_project.erl
Copyright ( c ) 2009 , %% All rights reserved. %% %% Redistribution and use in source and binary forms, with or without %% modification, are permitted provided that the following conditions are met: %% %% Redistributions of source code must retain the above copyright %% notice, this list of conditions and the following disclaimer. %% %% Redistributions in binary form must reproduce the above copyright %% notice, this list of conditions and the following disclaimer in the %% documentation and/or other materials provided with the distribution. %% %% Neither the name of the copyright holders nor the %% names of its contributors may be used to endorse or promote products %% derived from this software without specific prior written permission. %% %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' %% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR %% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR %% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, %% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR %% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF %% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @author 2006 - 2009 %% @doc @private -module(mce_erl_analyze_project). -export([start/1,analyze/2]). start([LibPath,Dir]) -> analyze(LibPath,Dir), halt(). analyze(McErlangTopDir,Dir) -> {ok, X} = xref:start(s,[{xref_mode,modules}]), xref:set_library_path(X,[Dir|mcErlangEbinDirs(McErlangTopDir)]), xref:add_directory(X,Dir), {ok,Result} = xref:analyze(X,undefined_functions), io:format("Undefined functions:~n"), lists:foreach (fun ({Module,Name,Arity}) -> io:format(" ~p:~p/~p~n",[Module,Name,Arity]) end, Result). mcErlangEbinDirs(TopDir) -> [TopDir++"/ebin", TopDir++"/languages/erlang/ebin", TopDir++"/monitors/ebin", TopDir++"/abstractions/ebin"].
null
https://raw.githubusercontent.com/fredlund/McErlang/25b38a38a729fdb3c3d2afb9be016bbb14237792/languages/erlang/src/mce_erl_analyze_project.erl
erlang
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: %% Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. %% Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. %% Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS 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. @doc
Copyright ( c ) 2009 , IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR @author 2006 - 2009 @private -module(mce_erl_analyze_project). -export([start/1,analyze/2]). start([LibPath,Dir]) -> analyze(LibPath,Dir), halt(). analyze(McErlangTopDir,Dir) -> {ok, X} = xref:start(s,[{xref_mode,modules}]), xref:set_library_path(X,[Dir|mcErlangEbinDirs(McErlangTopDir)]), xref:add_directory(X,Dir), {ok,Result} = xref:analyze(X,undefined_functions), io:format("Undefined functions:~n"), lists:foreach (fun ({Module,Name,Arity}) -> io:format(" ~p:~p/~p~n",[Module,Name,Arity]) end, Result). mcErlangEbinDirs(TopDir) -> [TopDir++"/ebin", TopDir++"/languages/erlang/ebin", TopDir++"/monitors/ebin", TopDir++"/abstractions/ebin"].
f4eaf1d6b398c2c3ab0995d8d156612d1dce2f4600a0748140119768a8cfa2d7
softwarelanguageslab/maf
unsafe_send.scm
From SOTER benchmarks ( unsafe_send ) . Description from SOTER : This example illustrates the " Verify Absence - of - Errors " mode . The server expects a tuple { REQUEST , PID - OF - SENDER } but the main sends to it an atom instead of its pid , then generating an exception when the server tries to send back a response to what he assumes to be a pid . The verification step discovers a genuine counter - example . To inspect the error trace run bfc on the generated model and look at the trace alongside the dot model of the ACS . (let* ((server-actor (actor "server" () (message (x p) (send p message x) (become server-actor)) (bye () (terminate)))) (server (create server-actor))) (send server message 'hi 'bye))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/be58e02c63d25cab5b48fdf7b737b68b882e9dca/test/concurrentScheme/actors/contracts/soter/unsafe_send.scm
scheme
From SOTER benchmarks ( unsafe_send ) . Description from SOTER : This example illustrates the " Verify Absence - of - Errors " mode . The server expects a tuple { REQUEST , PID - OF - SENDER } but the main sends to it an atom instead of its pid , then generating an exception when the server tries to send back a response to what he assumes to be a pid . The verification step discovers a genuine counter - example . To inspect the error trace run bfc on the generated model and look at the trace alongside the dot model of the ACS . (let* ((server-actor (actor "server" () (message (x p) (send p message x) (become server-actor)) (bye () (terminate)))) (server (create server-actor))) (send server message 'hi 'bye))
7936c31821ccc37561619a8fc5f3b723ad67e61df9fabb9c1fbf24dfb0b87df7
ekmett/categories
Braided.hs
# LANGUAGE CPP # #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 # LANGUAGE Trustworthy # #endif # LANGUAGE MultiParamTypeClasses # ------------------------------------------------------------------------------------------- -- | -- Module : Control.Category.Braided Copyright : 2008 - 2012 -- License : BSD -- Maintainer : < > -- Stability : experimental -- Portability: portable -- ------------------------------------------------------------------------------------------- module Control.Category.Braided ( Braided(..) , Symmetric , swap ) where import Control . Categorical . Bifunctor import Control.Category.Associative | A braided ( co)(monoidal or associative ) category can commute the arguments of its bi - endofunctor . the laws : > associate . braid . associate = second braid . associate . first braid > disassociate . braid . disassociate = first braid . disassociate . second braid If the category is Monoidal the following laws should be satisfied > idr . = idl > idl . braid = idr If the category is Comonoidal the following laws should be satisfied > braid . coidr = coidl > braid . coidl = coidr > associate . braid . associate = second braid . associate . first braid > disassociate . braid . disassociate = first braid . disassociate . second braid If the category is Monoidal the following laws should be satisfied > idr . braid = idl > idl . braid = idr If the category is Comonoidal the following laws should be satisfied > braid . coidr = coidl > braid . coidl = coidr -} class Associative k p => Braided k p where braid :: k (p a b) (p b a) instance Braided (->) Either where braid (Left a) = Right a braid (Right b) = Left b instance Braided (->) (,) where braid ~(a,b) = (b,a) - RULES " braid / associate / braid " second braid . associate . first braid = associate . braid . associate " braid / disassociate / braid " first braid . disassociate . second braid = disassociate . braid . disassociate - "braid/associate/braid" second braid . associate . first braid = associate . braid . associate "braid/disassociate/braid" first braid . disassociate . second braid = disassociate . braid . disassociate --} {- | If we have a symmetric (co)'Monoidal' category, you get the additional law: > swap . swap = id -} class Braided k p => Symmetric k p swap :: Symmetric k p => k (p a b) (p b a) swap = braid {-- RULES "swap/swap" swap . swap = id --} instance Symmetric (->) Either instance Symmetric (->) (,)
null
https://raw.githubusercontent.com/ekmett/categories/4a02808d28b275f59d9d6c08f0c2d329ee567a97/old/src/Control/Category/Braided.hs
haskell
----------------------------------------------------------------------------------------- | Module : Control.Category.Braided License : BSD Stability : experimental Portability: portable ----------------------------------------------------------------------------------------- } | If we have a symmetric (co)'Monoidal' category, you get the additional law: > swap . swap = id - RULES "swap/swap" swap . swap = id -
# LANGUAGE CPP # #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 # LANGUAGE Trustworthy # #endif # LANGUAGE MultiParamTypeClasses # Copyright : 2008 - 2012 Maintainer : < > module Control.Category.Braided ( Braided(..) , Symmetric , swap ) where import Control . Categorical . Bifunctor import Control.Category.Associative | A braided ( co)(monoidal or associative ) category can commute the arguments of its bi - endofunctor . the laws : > associate . braid . associate = second braid . associate . first braid > disassociate . braid . disassociate = first braid . disassociate . second braid If the category is Monoidal the following laws should be satisfied > idr . = idl > idl . braid = idr If the category is Comonoidal the following laws should be satisfied > braid . coidr = coidl > braid . coidl = coidr > associate . braid . associate = second braid . associate . first braid > disassociate . braid . disassociate = first braid . disassociate . second braid If the category is Monoidal the following laws should be satisfied > idr . braid = idl > idl . braid = idr If the category is Comonoidal the following laws should be satisfied > braid . coidr = coidl > braid . coidl = coidr -} class Associative k p => Braided k p where braid :: k (p a b) (p b a) instance Braided (->) Either where braid (Left a) = Right a braid (Right b) = Left b instance Braided (->) (,) where braid ~(a,b) = (b,a) - RULES " braid / associate / braid " second braid . associate . first braid = associate . braid . associate " braid / disassociate / braid " first braid . disassociate . second braid = disassociate . braid . disassociate - "braid/associate/braid" second braid . associate . first braid = associate . braid . associate "braid/disassociate/braid" first braid . disassociate . second braid = disassociate . braid . disassociate class Braided k p => Symmetric k p swap :: Symmetric k p => k (p a b) (p b a) swap = braid instance Symmetric (->) Either instance Symmetric (->) (,)
d8e220284aedd512828ab375ddd7cf42833bf6526ef1d70ae84cc577bf11f3bc
seriyps/mtproto_proxy
gen_timeout.erl
@author < > ( C ) 2018 , %%% @doc %%% %%% @end Created : 9 Apr 2018 by < > -module(gen_timeout). -export([new/1, set_timeout/2, bump/1, reset/1, is_expired/1, time_to_message/1, time_left/1]). -export([upgrade/1]). -export_type([tout/0, opts/0]). -record(timeout, {ref :: reference() | undefined, last_bump :: integer(), message :: any(), unit = second :: erlang:time_unit(), timeout :: timeout_type()}). -type timeout_type() :: non_neg_integer() | {env, App :: atom(), Name :: atom(), Default :: non_neg_integer()}. -type opts() :: #{message => any(), unit => erlang:time_unit(), timeout := timeout_type()}. -opaque tout() :: #timeout{}. -define(MS_PER_SEC, 1000). -spec new(opts()) -> tout(). new(Opts) -> Default = #{message => timeout, unit => second}, #{message := Message, timeout := Timeout, unit := Unit} = maps:merge(Default, Opts), TODO : get rid of 2 system_time/1 calls in ` new + reset ` reset(#timeout{message = Message, unit = Unit, last_bump = erlang:system_time(Unit), timeout = Timeout}). -spec set_timeout(timeout_type(), tout()) -> tout(). set_timeout(Timeout, S) -> reset(S#timeout{timeout = Timeout}). -spec bump(tout()) -> tout(). bump(#timeout{unit = Unit} = S) -> S#timeout{last_bump = erlang:system_time(Unit)}. -spec reset(tout()) -> tout(). reset(#timeout{ref = Ref, message = Message, unit = Unit} = S) -> (is_reference(Ref)) andalso erlang:cancel_timer(Ref), SendAfter = max(time_left(S), 0), After = erlang:convert_time_unit(SendAfter, Unit, millisecond), Ref1 = erlang:send_after(After, self(), Message), S#timeout{ref = Ref1}. -spec is_expired(tout()) -> boolean(). is_expired(S) -> time_left(S) =< 0. -spec time_to_message(tout()) -> non_neg_integer() | false. time_to_message(#timeout{ref = Ref}) -> erlang:read_timer(Ref). -spec time_left(tout()) -> integer(). time_left(#timeout{last_bump = LastBump, unit = Unit} = S) -> Timeout = get_timeout(S), Now = erlang:system_time(Unit), ExpiresAt = LastBump + Timeout, ExpiresAt - Now. upgrade({timeout, Ref, LastBump, Message, Timeout}) -> Timeout1 = case Timeout of {sec, Val} -> Val; _ -> Timeout end, #timeout{ref = Ref, last_bump = LastBump, message = Message, timeout = Timeout1, unit = second}. Internal get_timeout(#timeout{timeout = {env, App, Name, Default}}) -> application:get_env(App, Name, Default); get_timeout(#timeout{timeout = Sec}) -> Sec. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). new_expire_test() -> T = new(#{timeout => 100, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), ?assert(time_left(T) > 0), ?assert(time_to_message(T) > 0), ok= recv(?FUNCTION_NAME), ?assert(time_left(T) =< 0), ?assert(is_expired(T)). reset_test() -> T = new(#{timeout => 100, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), T1 = reset(T), ?assertNot(is_expired(T1)), ok = recv(?FUNCTION_NAME), ?assert(is_expired(T1)). bump_test() -> T = new(#{timeout => 1000, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), TimeToMessage0 = time_to_message(T), timer:sleep(600), T1 = bump(T), ?assert((TimeToMessage0 - 600) >= time_to_message(T1), "Bump doesn't affect timer message"), timer:sleep(500), %% Got message, but not yet expired ?assertEqual(false, time_to_message(T1)), ?assertNot(is_expired(T1)), ok = recv(?FUNCTION_NAME), ?assertNot(is_expired(T1)), T2 = reset(T1), ok = recv(?FUNCTION_NAME), ?assert(is_expired(T2)). recv(What) -> receive What -> ok after 5000 -> error({timeout, What}) end. -endif.
null
https://raw.githubusercontent.com/seriyps/mtproto_proxy/5ad7c536da57ff89dea488941c7ff4711372d858/src/gen_timeout.erl
erlang
@doc @end Got message, but not yet expired
@author < > ( C ) 2018 , Created : 9 Apr 2018 by < > -module(gen_timeout). -export([new/1, set_timeout/2, bump/1, reset/1, is_expired/1, time_to_message/1, time_left/1]). -export([upgrade/1]). -export_type([tout/0, opts/0]). -record(timeout, {ref :: reference() | undefined, last_bump :: integer(), message :: any(), unit = second :: erlang:time_unit(), timeout :: timeout_type()}). -type timeout_type() :: non_neg_integer() | {env, App :: atom(), Name :: atom(), Default :: non_neg_integer()}. -type opts() :: #{message => any(), unit => erlang:time_unit(), timeout := timeout_type()}. -opaque tout() :: #timeout{}. -define(MS_PER_SEC, 1000). -spec new(opts()) -> tout(). new(Opts) -> Default = #{message => timeout, unit => second}, #{message := Message, timeout := Timeout, unit := Unit} = maps:merge(Default, Opts), TODO : get rid of 2 system_time/1 calls in ` new + reset ` reset(#timeout{message = Message, unit = Unit, last_bump = erlang:system_time(Unit), timeout = Timeout}). -spec set_timeout(timeout_type(), tout()) -> tout(). set_timeout(Timeout, S) -> reset(S#timeout{timeout = Timeout}). -spec bump(tout()) -> tout(). bump(#timeout{unit = Unit} = S) -> S#timeout{last_bump = erlang:system_time(Unit)}. -spec reset(tout()) -> tout(). reset(#timeout{ref = Ref, message = Message, unit = Unit} = S) -> (is_reference(Ref)) andalso erlang:cancel_timer(Ref), SendAfter = max(time_left(S), 0), After = erlang:convert_time_unit(SendAfter, Unit, millisecond), Ref1 = erlang:send_after(After, self(), Message), S#timeout{ref = Ref1}. -spec is_expired(tout()) -> boolean(). is_expired(S) -> time_left(S) =< 0. -spec time_to_message(tout()) -> non_neg_integer() | false. time_to_message(#timeout{ref = Ref}) -> erlang:read_timer(Ref). -spec time_left(tout()) -> integer(). time_left(#timeout{last_bump = LastBump, unit = Unit} = S) -> Timeout = get_timeout(S), Now = erlang:system_time(Unit), ExpiresAt = LastBump + Timeout, ExpiresAt - Now. upgrade({timeout, Ref, LastBump, Message, Timeout}) -> Timeout1 = case Timeout of {sec, Val} -> Val; _ -> Timeout end, #timeout{ref = Ref, last_bump = LastBump, message = Message, timeout = Timeout1, unit = second}. Internal get_timeout(#timeout{timeout = {env, App, Name, Default}}) -> application:get_env(App, Name, Default); get_timeout(#timeout{timeout = Sec}) -> Sec. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). new_expire_test() -> T = new(#{timeout => 100, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), ?assert(time_left(T) > 0), ?assert(time_to_message(T) > 0), ok= recv(?FUNCTION_NAME), ?assert(time_left(T) =< 0), ?assert(is_expired(T)). reset_test() -> T = new(#{timeout => 100, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), T1 = reset(T), ?assertNot(is_expired(T1)), ok = recv(?FUNCTION_NAME), ?assert(is_expired(T1)). bump_test() -> T = new(#{timeout => 1000, unit => millisecond, message => ?FUNCTION_NAME}), ?assertNot(is_expired(T)), TimeToMessage0 = time_to_message(T), timer:sleep(600), T1 = bump(T), ?assert((TimeToMessage0 - 600) >= time_to_message(T1), "Bump doesn't affect timer message"), timer:sleep(500), ?assertEqual(false, time_to_message(T1)), ?assertNot(is_expired(T1)), ok = recv(?FUNCTION_NAME), ?assertNot(is_expired(T1)), T2 = reset(T1), ok = recv(?FUNCTION_NAME), ?assert(is_expired(T2)). recv(What) -> receive What -> ok after 5000 -> error({timeout, What}) end. -endif.
d84e0e3ba1daf0d937abd5727beecf4283012ed36a6ae897a302b11c5038d3dc
bsansouci/bsb-native
translobj.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) open Misc open Primitive open Asttypes open Longident open Lambda (* Get oo primitives identifiers *) let oo_prim name = try transl_normal_path (fst (Env.lookup_value (Ldot (Lident "CamlinternalOO", name)) Env.empty)) with Not_found -> fatal_error ("Primitive " ^ name ^ " not found.") (* Share blocks *) let consts : (structured_constant, Ident.t) Hashtbl.t = Hashtbl.create 17 let share c = match c with Const_block (n, _, l) when l <> [] -> begin try Lvar (Hashtbl.find consts c) with Not_found -> let id = Ident.create "shared" in Hashtbl.add consts c id; Lvar id end | _ -> Lconst c (* Collect labels *) let cache_required = ref false let method_cache = ref lambda_unit let method_count = ref 0 let method_table = ref [] let meth_tag s = Lconst(Const_base(Const_int(Btype.hash_variant s))) let next_cache tag = let n = !method_count in incr method_count; (tag, [!method_cache; Lconst(Const_base(Const_int n))]) let rec is_path = function Lvar _ | Lprim (Pgetglobal _, [], _) | Lconst _ -> true | Lprim (Pfield _, [lam], _) -> is_path lam | Lprim ((Parrayrefu _ | Parrayrefs _), [lam1; lam2], _) -> is_path lam1 && is_path lam2 | _ -> false let meth obj lab = let tag = meth_tag lab in if not (!cache_required && !Clflags.native_code) then (tag, []) else if not (is_path obj) then next_cache tag else try let r = List.assoc obj !method_table in try (tag, List.assoc tag !r) with Not_found -> let p = next_cache tag in r := p :: !r; p with Not_found -> let p = next_cache tag in method_table := (obj, ref [p]) :: !method_table; p let reset_labels () = Hashtbl.clear consts; method_count := 0; method_table := [] (* Insert labels *) let string s = Lconst (Const_base (Const_string (s, None))) let int n = Lconst (Const_base (Const_int n)) let prim_makearray = { prim_name = "caml_make_vect"; prim_arity = 2; prim_alloc = true; prim_native_name = ""; prim_native_float = false} (* Also use it for required globals *) let transl_label_init expr = let expr = Hashtbl.fold (fun c id expr -> Llet(Alias, id, Lconst c, expr)) consts expr in let expr = List.fold_right (fun id expr -> Lsequence(Lprim(Pgetglobal id, [], Location.none), expr)) (Env.get_required_globals ()) expr in Env.reset_required_globals (); reset_labels (); expr let transl_store_label_init glob size f arg = method_cache := Lprim(Pfield (size, Fld_na), [Lprim(Pgetglobal glob, [], Location.none)], Location.none); let expr = f arg in let (size, expr) = if !method_count = 0 then (size, expr) else (size+1, Lsequence( Lprim(Psetfield(size, false, Fld_set_na), [Lprim(Pgetglobal glob, [], Location.none); Lprim (Pccall prim_makearray, [int !method_count; int 0], Location.none)], Location.none), expr)) in (size, transl_label_init expr) (* Share classes *) let wrapping = ref false let top_env = ref Env.empty let classes = ref [] let method_ids = ref IdentSet.empty let oo_add_class id = classes := id :: !classes; (!top_env, !cache_required) let oo_wrap env req f x = if !wrapping then if !cache_required then f x else try cache_required := true; let lam = f x in cache_required := false; lam with exn -> cache_required := false; raise exn else try wrapping := true; cache_required := req; top_env := env; classes := []; method_ids := IdentSet.empty; let lambda = f x in let lambda = List.fold_left (fun lambda id -> Llet(StrictOpt, id, Lprim(Pmakeblock(0, Lambda.default_tag_info, Mutable), [lambda_unit; lambda_unit; lambda_unit], Location.none), lambda)) lambda !classes in wrapping := false; top_env := Env.empty; lambda with exn -> wrapping := false; top_env := Env.empty; raise exn let reset () = Hashtbl.clear consts; cache_required := false; method_cache := lambda_unit; method_count := 0; method_table := []; wrapping := false; top_env := Env.empty; classes := []; method_ids := IdentSet.empty
null
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/bytecomp/translobj.ml
ocaml
********************************************************************* OCaml ********************************************************************* Get oo primitives identifiers Share blocks Collect labels Insert labels Also use it for required globals Share classes
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . open Misc open Primitive open Asttypes open Longident open Lambda let oo_prim name = try transl_normal_path (fst (Env.lookup_value (Ldot (Lident "CamlinternalOO", name)) Env.empty)) with Not_found -> fatal_error ("Primitive " ^ name ^ " not found.") let consts : (structured_constant, Ident.t) Hashtbl.t = Hashtbl.create 17 let share c = match c with Const_block (n, _, l) when l <> [] -> begin try Lvar (Hashtbl.find consts c) with Not_found -> let id = Ident.create "shared" in Hashtbl.add consts c id; Lvar id end | _ -> Lconst c let cache_required = ref false let method_cache = ref lambda_unit let method_count = ref 0 let method_table = ref [] let meth_tag s = Lconst(Const_base(Const_int(Btype.hash_variant s))) let next_cache tag = let n = !method_count in incr method_count; (tag, [!method_cache; Lconst(Const_base(Const_int n))]) let rec is_path = function Lvar _ | Lprim (Pgetglobal _, [], _) | Lconst _ -> true | Lprim (Pfield _, [lam], _) -> is_path lam | Lprim ((Parrayrefu _ | Parrayrefs _), [lam1; lam2], _) -> is_path lam1 && is_path lam2 | _ -> false let meth obj lab = let tag = meth_tag lab in if not (!cache_required && !Clflags.native_code) then (tag, []) else if not (is_path obj) then next_cache tag else try let r = List.assoc obj !method_table in try (tag, List.assoc tag !r) with Not_found -> let p = next_cache tag in r := p :: !r; p with Not_found -> let p = next_cache tag in method_table := (obj, ref [p]) :: !method_table; p let reset_labels () = Hashtbl.clear consts; method_count := 0; method_table := [] let string s = Lconst (Const_base (Const_string (s, None))) let int n = Lconst (Const_base (Const_int n)) let prim_makearray = { prim_name = "caml_make_vect"; prim_arity = 2; prim_alloc = true; prim_native_name = ""; prim_native_float = false} let transl_label_init expr = let expr = Hashtbl.fold (fun c id expr -> Llet(Alias, id, Lconst c, expr)) consts expr in let expr = List.fold_right (fun id expr -> Lsequence(Lprim(Pgetglobal id, [], Location.none), expr)) (Env.get_required_globals ()) expr in Env.reset_required_globals (); reset_labels (); expr let transl_store_label_init glob size f arg = method_cache := Lprim(Pfield (size, Fld_na), [Lprim(Pgetglobal glob, [], Location.none)], Location.none); let expr = f arg in let (size, expr) = if !method_count = 0 then (size, expr) else (size+1, Lsequence( Lprim(Psetfield(size, false, Fld_set_na), [Lprim(Pgetglobal glob, [], Location.none); Lprim (Pccall prim_makearray, [int !method_count; int 0], Location.none)], Location.none), expr)) in (size, transl_label_init expr) let wrapping = ref false let top_env = ref Env.empty let classes = ref [] let method_ids = ref IdentSet.empty let oo_add_class id = classes := id :: !classes; (!top_env, !cache_required) let oo_wrap env req f x = if !wrapping then if !cache_required then f x else try cache_required := true; let lam = f x in cache_required := false; lam with exn -> cache_required := false; raise exn else try wrapping := true; cache_required := req; top_env := env; classes := []; method_ids := IdentSet.empty; let lambda = f x in let lambda = List.fold_left (fun lambda id -> Llet(StrictOpt, id, Lprim(Pmakeblock(0, Lambda.default_tag_info, Mutable), [lambda_unit; lambda_unit; lambda_unit], Location.none), lambda)) lambda !classes in wrapping := false; top_env := Env.empty; lambda with exn -> wrapping := false; top_env := Env.empty; raise exn let reset () = Hashtbl.clear consts; cache_required := false; method_cache := lambda_unit; method_count := 0; method_table := []; wrapping := false; top_env := Env.empty; classes := []; method_ids := IdentSet.empty
5914173f1e8841449d841e07cf448732413e6be434415e0fa626b7079d590607
clojure-interop/java-jdk
TransformerHandler.clj
(ns javax.xml.transform.sax.TransformerHandler "A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.transform.sax TransformerHandler])) (defn set-result "Set the Result associated with this TransformerHandler to be used for the transformation. result - A Result instance, should not be null. - `javax.xml.transform.Result` throws: java.lang.IllegalArgumentException - if result is invalid for some reason." ([^TransformerHandler this ^javax.xml.transform.Result result] (-> this (.setResult result)))) (defn set-system-id "Set the base ID (URI or system ID) from where relative URLs will be resolved. system-id - Base URI for the source tree. - `java.lang.String`" ([^TransformerHandler this ^java.lang.String system-id] (-> this (.setSystemId system-id)))) (defn get-system-id "Get the base ID (URI or system ID) from where relative URLs will be resolved. returns: The systemID that was set with setSystemId(java.lang.String). - `java.lang.String`" (^java.lang.String [^TransformerHandler this] (-> this (.getSystemId)))) (defn get-transformer "Get the Transformer associated with this handler, which is needed in order to set parameters and output properties. returns: Transformer associated with this TransformerHandler. - `javax.xml.transform.Transformer`" (^javax.xml.transform.Transformer [^TransformerHandler this] (-> this (.getTransformer))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/transform/sax/TransformerHandler.clj
clojure
(ns javax.xml.transform.sax.TransformerHandler "A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.transform.sax TransformerHandler])) (defn set-result "Set the Result associated with this TransformerHandler to be used for the transformation. result - A Result instance, should not be null. - `javax.xml.transform.Result` throws: java.lang.IllegalArgumentException - if result is invalid for some reason." ([^TransformerHandler this ^javax.xml.transform.Result result] (-> this (.setResult result)))) (defn set-system-id "Set the base ID (URI or system ID) from where relative URLs will be resolved. system-id - Base URI for the source tree. - `java.lang.String`" ([^TransformerHandler this ^java.lang.String system-id] (-> this (.setSystemId system-id)))) (defn get-system-id "Get the base ID (URI or system ID) from where relative URLs will be resolved. returns: The systemID that was set with setSystemId(java.lang.String). - `java.lang.String`" (^java.lang.String [^TransformerHandler this] (-> this (.getSystemId)))) (defn get-transformer "Get the Transformer associated with this handler, which is needed in order to set parameters and output properties. returns: Transformer associated with this TransformerHandler. - `javax.xml.transform.Transformer`" (^javax.xml.transform.Transformer [^TransformerHandler this] (-> this (.getTransformer))))
3e9dbf35fd4e60686ca7bce89158c6fac047b7173ce60fe00ae942fc5c93cd88
javalib-team/sawja
jCRA.ml
* This file is part of SAWJA * Copyright ( c)2007 ( Université de Rennes 1 ) * Copyright ( c)2007 , 2008 , 2009 ( CNRS ) * Copyright ( c)2009 ( INRIA ) * * 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 * < / > . * This file is part of SAWJA * Copyright (c)2007 Tiphaine Turpin (Université de Rennes 1) * Copyright (c)2007, 2008, 2009 Laurent Hubert (CNRS) * Copyright (c)2009 Nicolas Barre (INRIA) * * 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 * </>. *) open Javalib_pack open JBasics open JCode open Javalib open JProgram let rec update_interfaces classes_map ioc interfaces cs = match ioc with | Class c -> ClassMap.fold (fun i_sig i interfaces -> let s = try ClassMap.find i_sig interfaces with _ -> ClassSet.empty in let interfaces = ClassMap.add i_sig (ClassSet.add cs s) interfaces in update_interfaces classes_map (Interface i) interfaces cs ) c.c_interfaces interfaces | Interface i -> ClassMap.fold (fun i_sig i interfaces -> let s = try ClassMap.find i_sig interfaces with _ -> ClassSet.empty in let interfaces = ClassMap.add i_sig (ClassSet.add cs s) interfaces in update_interfaces classes_map (Interface i) interfaces cs ) i.i_interfaces interfaces exception Class_not_found of class_name let add_classFile c classes_map interfaces = let imap = List.fold_left (fun imap iname -> let i = try match (ClassMap.find iname classes_map) with | Interface i -> i | Class _ -> raise (Class_structure_error (JDumpBasics.class_name c.c_name ^" is declared to implements " ^JDumpBasics.class_name iname ^", which is a class and not an interface.")) with Not_found -> raise (Class_not_found iname) in ClassMap.add iname i imap ) ClassMap.empty c.Javalib.c_interfaces in let c_super = match c.c_super_class with | None -> None | Some super -> try let c_super_info = ClassMap.find super classes_map in match c_super_info with | Class c -> Some c | Interface _ -> raise (Class_structure_error (JDumpBasics.class_name c.c_name ^" is declared to extends " ^JDumpBasics.class_name super ^", which is an interface and not a class.") ) with Not_found -> raise (Class_not_found super) in let c_info = Class (make_class_node c c_super imap) in interfaces := update_interfaces classes_map c_info !interfaces c.c_name; ClassMap.add c.c_name c_info classes_map let add_interfaceFile c classes_map = let imap = List.fold_left (fun imap iname -> let i = try match (ClassMap.find iname classes_map) with | Interface i -> i | Class c' -> raise (Class_structure_error ("Interface "^JDumpBasics.class_name c.i_name ^" is declared to extends " ^JDumpBasics.class_name c'.c_info.c_name ^", which is an interface and not a class.") ) with Not_found -> raise (Class_not_found iname) in ClassMap.add iname i imap ) ClassMap.empty c.Javalib.i_interfaces and super = try match (ClassMap.find java_lang_object classes_map) with | Class c -> c | Interface _ -> raise (Class_structure_error"java.lang.Object is declared as an interface.") with Not_found -> raise (Class_not_found java_lang_object) in let i_info = Interface (make_interface_node c super imap) in ClassMap.add c.i_name i_info classes_map let add_one_node f classes_map interfaces = match f with | JInterface i -> add_interfaceFile i classes_map | JClass c -> add_classFile c classes_map interfaces let add_class_referenced c classmap to_add = Array.iter (function | ConstMethod (TClass cn,_) | ConstInterfaceMethod (cn,_) | ConstField (cn,_) | ConstClass (TClass cn) -> if not (ClassMap.mem cn classmap) then to_add := cn::!to_add | _ -> ()) (Javalib.get_consts c) let get_class class_path jclasses_map cs = try ClassMap.find cs !jclasses_map with Not_found -> try let c = Javalib.get_class class_path cs in jclasses_map := ClassMap.add cs c !jclasses_map; c; with No_class_found _ -> raise (Class_not_found cs) let rec add_node class_path c classes_map interfaces = let jclasses_map = ref ClassMap.empty in let to_add = ref [] in let classes_map = try let cname = Javalib.get_name c in if not (ClassMap.mem cname classes_map) then begin add_class_referenced c !jclasses_map to_add; add_one_node c classes_map interfaces end else classes_map with Class_not_found cs -> let missing_class = get_class class_path jclasses_map cs in add_node class_path c (add_node class_path missing_class classes_map interfaces) interfaces in begin let p_classes = ref classes_map in try while true do let cs = List.hd !to_add in to_add := List.tl !to_add; if not (ClassMap.mem cs !p_classes) then let c = get_class class_path jclasses_map cs in p_classes := add_node class_path c !p_classes interfaces done; !p_classes with Failure _ -> !p_classes end let get_children_classes c children_classes = let cs = c.c_info.c_name in try ClassMap.find cs !children_classes with _ -> let classes = List.fold_right (fun c cmap -> if not(c.c_info.c_abstract) then ClassMap.add c.c_info.c_name c cmap else cmap ) (c :: (get_all_children_classes c)) ClassMap.empty in children_classes := ClassMap.add cs classes !children_classes; classes let static_virtual_lookup virtual_lookup_map children_classes c ms = let cs = c.c_info.c_name in try ClassMethodMap.find (make_cms cs ms) !virtual_lookup_map with | _ -> let instantiated_classes = get_children_classes c children_classes in let cmmap = JControlFlow.invoke_virtual_lookup ~c:(Some c) ms instantiated_classes in let cmset = ClassMethodMaptoSet.to_set cmmap in virtual_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !virtual_lookup_map; cmset let static_interface_lookup interface_lookup_map classes_map interfaces children_classes i ms = let cs = i.i_info.i_name in try ClassMethodMap.find (make_cms cs ms) !interface_lookup_map with | _ -> let equivalent_classes = try ClassMap.find cs interfaces with _ -> ClassSet.empty in let instantiated_classes = ClassSet.fold (fun cs cmap -> let ioc_info = ClassMap.find cs classes_map in let ioc = ioc_info in match ioc with | Interface _ -> assert false | Class c -> let classes = get_children_classes c children_classes in ClassMap.merge (fun x _ -> x) cmap classes ) equivalent_classes ClassMap.empty in let cmmap = JControlFlow.invoke_interface_lookup ~i:(Some i) ms instantiated_classes in let cmset = ClassMethodMaptoSet.to_set cmmap in interface_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !interface_lookup_map; cmset let static_static_lookup static_lookup_map c ms = let cs = c.c_info.c_name in try ClassMethodMap.find (make_cms cs ms) !static_lookup_map with | _ -> let (_,cm) = JControlFlow.invoke_static_lookup c ms in let cmset = ClassMethodSet.add cm.cm_class_method_signature ClassMethodSet.empty in static_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !static_lookup_map; cmset let static_special_lookup special_lookup_map current_class c ms = let ccs = get_name current_class in let cs = c.c_info.c_name in let ccmmap = try ClassMap.find ccs !special_lookup_map with _ -> ClassMethodMap.empty in try ClassMethodMap.find (make_cms cs ms) ccmmap with | _ -> let (_,cm) = JControlFlow.invoke_special_lookup current_class c ms in let cmset = ClassMethodSet.add cm.cm_class_method_signature ClassMethodSet.empty in special_lookup_map := ClassMap.add ccs (ClassMethodMap.add (make_cms cs ms) cmset ccmmap) !special_lookup_map; cmset let static_lookup_method = let virtual_lookup_map = ref ClassMethodMap.empty and interface_lookup_map = ref ClassMethodMap.empty and static_lookup_map = ref ClassMethodMap.empty and special_lookup_map = ref ClassMap.empty and children_classes = ref ClassMap.empty in fun classes_map interfaces cs ms pp -> let m = get_method (ClassMap.find cs classes_map) ms in match m with | AbstractMethod _ -> failwith "Can't call static_lookup on Abstract Methods" | ConcreteMethod cm -> (match cm.cm_implementation with | Native -> failwith "Can't call static_lookup on Native methods" | Java code -> let opcode = (Lazy.force code).c_code.(pp) in (match opcode with | OpInvoke (`Interface ccs, cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Class _ -> failwith "Impossible InvokeInterface" | Interface i -> i in static_interface_lookup interface_lookup_map classes_map interfaces children_classes cc cms | OpInvoke (`Virtual (TClass ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeVirtual" | Class c -> c in static_virtual_lookup virtual_lookup_map children_classes cc cms | OpInvoke (`Virtual (TArray _), cms) -> (* should only happen with [clone()] *) let cobj = let ioc = (ClassMap.find java_lang_object classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeVirtual" | Class c -> c in static_virtual_lookup virtual_lookup_map children_classes cobj cms | OpInvoke (`Static (_,ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeStatic" | Class c -> c in static_static_lookup static_lookup_map cc cms | OpInvoke (`Special (_,ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeSpecial" | Class c -> c in let current_class = (ClassMap.find cs classes_map) in static_special_lookup special_lookup_map current_class cc cms | _ -> raise Not_found ) ) let default_classes = List.map make_cn ["java.lang.Class"; "java.lang.System"; "java.lang.String"; "java.lang.Thread"; "java.lang.ThreadGroup"; "java.lang.ref.Finalizer"; "java.lang.OutOfMemoryError"; "java.lang.NullPointerException"; "java.lang.ArrayStoreException"; "java.lang.ArithmeticException"; "java.lang.StackOverflowError"; "java.lang.IllegalMonitorStateException"; "java.lang.Compiler"; "java.lang.reflect.Method"; "java.lang.reflect.Field"] let parse_program ?(other_classes=default_classes) class_path names = let class_path = Javalib.class_path class_path in try let class_map = ref begin List.fold_left (fun clmap cn -> let c = Javalib.get_class class_path cn in let c_name = Javalib.get_name c in ClassMap.add c_name c clmap ) ClassMap.empty (other_classes @ names) end in let interfaces = ref ClassMap.empty in let p_classes = ClassMap.fold (fun _ c classes -> add_node class_path c classes interfaces) !class_map ClassMap.empty in let parsed_methods = ClassMap.fold (fun _ ioc_info cmmap -> let ioc = ioc_info in MethodMap.fold (fun _ cm cmmap -> ClassMethodMap.add cm.cm_class_method_signature (ioc,cm) cmmap ) (get_concrete_methods ioc) cmmap ) p_classes ClassMethodMap.empty in Javalib.close_class_path class_path; { classes = p_classes; parsed_methods = parsed_methods; static_lookup_method = static_lookup_method p_classes !interfaces } with e -> Javalib.close_class_path class_path; raise e let parse_program_bench ?(other_classes=default_classes) class_path names = let time_start = Sys.time() in ignore(parse_program ~other_classes class_path names); let time_stop = Sys.time() in Printf.printf "program parsed in %fs.\n" (time_stop-.time_start)
null
https://raw.githubusercontent.com/javalib-team/sawja/da39f9c1c4fc52a1a1a6350be0e39789812b6c00/src/jCRA.ml
ocaml
should only happen with [clone()]
* This file is part of SAWJA * Copyright ( c)2007 ( Université de Rennes 1 ) * Copyright ( c)2007 , 2008 , 2009 ( CNRS ) * Copyright ( c)2009 ( INRIA ) * * 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 * < / > . * This file is part of SAWJA * Copyright (c)2007 Tiphaine Turpin (Université de Rennes 1) * Copyright (c)2007, 2008, 2009 Laurent Hubert (CNRS) * Copyright (c)2009 Nicolas Barre (INRIA) * * 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 * </>. *) open Javalib_pack open JBasics open JCode open Javalib open JProgram let rec update_interfaces classes_map ioc interfaces cs = match ioc with | Class c -> ClassMap.fold (fun i_sig i interfaces -> let s = try ClassMap.find i_sig interfaces with _ -> ClassSet.empty in let interfaces = ClassMap.add i_sig (ClassSet.add cs s) interfaces in update_interfaces classes_map (Interface i) interfaces cs ) c.c_interfaces interfaces | Interface i -> ClassMap.fold (fun i_sig i interfaces -> let s = try ClassMap.find i_sig interfaces with _ -> ClassSet.empty in let interfaces = ClassMap.add i_sig (ClassSet.add cs s) interfaces in update_interfaces classes_map (Interface i) interfaces cs ) i.i_interfaces interfaces exception Class_not_found of class_name let add_classFile c classes_map interfaces = let imap = List.fold_left (fun imap iname -> let i = try match (ClassMap.find iname classes_map) with | Interface i -> i | Class _ -> raise (Class_structure_error (JDumpBasics.class_name c.c_name ^" is declared to implements " ^JDumpBasics.class_name iname ^", which is a class and not an interface.")) with Not_found -> raise (Class_not_found iname) in ClassMap.add iname i imap ) ClassMap.empty c.Javalib.c_interfaces in let c_super = match c.c_super_class with | None -> None | Some super -> try let c_super_info = ClassMap.find super classes_map in match c_super_info with | Class c -> Some c | Interface _ -> raise (Class_structure_error (JDumpBasics.class_name c.c_name ^" is declared to extends " ^JDumpBasics.class_name super ^", which is an interface and not a class.") ) with Not_found -> raise (Class_not_found super) in let c_info = Class (make_class_node c c_super imap) in interfaces := update_interfaces classes_map c_info !interfaces c.c_name; ClassMap.add c.c_name c_info classes_map let add_interfaceFile c classes_map = let imap = List.fold_left (fun imap iname -> let i = try match (ClassMap.find iname classes_map) with | Interface i -> i | Class c' -> raise (Class_structure_error ("Interface "^JDumpBasics.class_name c.i_name ^" is declared to extends " ^JDumpBasics.class_name c'.c_info.c_name ^", which is an interface and not a class.") ) with Not_found -> raise (Class_not_found iname) in ClassMap.add iname i imap ) ClassMap.empty c.Javalib.i_interfaces and super = try match (ClassMap.find java_lang_object classes_map) with | Class c -> c | Interface _ -> raise (Class_structure_error"java.lang.Object is declared as an interface.") with Not_found -> raise (Class_not_found java_lang_object) in let i_info = Interface (make_interface_node c super imap) in ClassMap.add c.i_name i_info classes_map let add_one_node f classes_map interfaces = match f with | JInterface i -> add_interfaceFile i classes_map | JClass c -> add_classFile c classes_map interfaces let add_class_referenced c classmap to_add = Array.iter (function | ConstMethod (TClass cn,_) | ConstInterfaceMethod (cn,_) | ConstField (cn,_) | ConstClass (TClass cn) -> if not (ClassMap.mem cn classmap) then to_add := cn::!to_add | _ -> ()) (Javalib.get_consts c) let get_class class_path jclasses_map cs = try ClassMap.find cs !jclasses_map with Not_found -> try let c = Javalib.get_class class_path cs in jclasses_map := ClassMap.add cs c !jclasses_map; c; with No_class_found _ -> raise (Class_not_found cs) let rec add_node class_path c classes_map interfaces = let jclasses_map = ref ClassMap.empty in let to_add = ref [] in let classes_map = try let cname = Javalib.get_name c in if not (ClassMap.mem cname classes_map) then begin add_class_referenced c !jclasses_map to_add; add_one_node c classes_map interfaces end else classes_map with Class_not_found cs -> let missing_class = get_class class_path jclasses_map cs in add_node class_path c (add_node class_path missing_class classes_map interfaces) interfaces in begin let p_classes = ref classes_map in try while true do let cs = List.hd !to_add in to_add := List.tl !to_add; if not (ClassMap.mem cs !p_classes) then let c = get_class class_path jclasses_map cs in p_classes := add_node class_path c !p_classes interfaces done; !p_classes with Failure _ -> !p_classes end let get_children_classes c children_classes = let cs = c.c_info.c_name in try ClassMap.find cs !children_classes with _ -> let classes = List.fold_right (fun c cmap -> if not(c.c_info.c_abstract) then ClassMap.add c.c_info.c_name c cmap else cmap ) (c :: (get_all_children_classes c)) ClassMap.empty in children_classes := ClassMap.add cs classes !children_classes; classes let static_virtual_lookup virtual_lookup_map children_classes c ms = let cs = c.c_info.c_name in try ClassMethodMap.find (make_cms cs ms) !virtual_lookup_map with | _ -> let instantiated_classes = get_children_classes c children_classes in let cmmap = JControlFlow.invoke_virtual_lookup ~c:(Some c) ms instantiated_classes in let cmset = ClassMethodMaptoSet.to_set cmmap in virtual_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !virtual_lookup_map; cmset let static_interface_lookup interface_lookup_map classes_map interfaces children_classes i ms = let cs = i.i_info.i_name in try ClassMethodMap.find (make_cms cs ms) !interface_lookup_map with | _ -> let equivalent_classes = try ClassMap.find cs interfaces with _ -> ClassSet.empty in let instantiated_classes = ClassSet.fold (fun cs cmap -> let ioc_info = ClassMap.find cs classes_map in let ioc = ioc_info in match ioc with | Interface _ -> assert false | Class c -> let classes = get_children_classes c children_classes in ClassMap.merge (fun x _ -> x) cmap classes ) equivalent_classes ClassMap.empty in let cmmap = JControlFlow.invoke_interface_lookup ~i:(Some i) ms instantiated_classes in let cmset = ClassMethodMaptoSet.to_set cmmap in interface_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !interface_lookup_map; cmset let static_static_lookup static_lookup_map c ms = let cs = c.c_info.c_name in try ClassMethodMap.find (make_cms cs ms) !static_lookup_map with | _ -> let (_,cm) = JControlFlow.invoke_static_lookup c ms in let cmset = ClassMethodSet.add cm.cm_class_method_signature ClassMethodSet.empty in static_lookup_map := ClassMethodMap.add (make_cms cs ms) cmset !static_lookup_map; cmset let static_special_lookup special_lookup_map current_class c ms = let ccs = get_name current_class in let cs = c.c_info.c_name in let ccmmap = try ClassMap.find ccs !special_lookup_map with _ -> ClassMethodMap.empty in try ClassMethodMap.find (make_cms cs ms) ccmmap with | _ -> let (_,cm) = JControlFlow.invoke_special_lookup current_class c ms in let cmset = ClassMethodSet.add cm.cm_class_method_signature ClassMethodSet.empty in special_lookup_map := ClassMap.add ccs (ClassMethodMap.add (make_cms cs ms) cmset ccmmap) !special_lookup_map; cmset let static_lookup_method = let virtual_lookup_map = ref ClassMethodMap.empty and interface_lookup_map = ref ClassMethodMap.empty and static_lookup_map = ref ClassMethodMap.empty and special_lookup_map = ref ClassMap.empty and children_classes = ref ClassMap.empty in fun classes_map interfaces cs ms pp -> let m = get_method (ClassMap.find cs classes_map) ms in match m with | AbstractMethod _ -> failwith "Can't call static_lookup on Abstract Methods" | ConcreteMethod cm -> (match cm.cm_implementation with | Native -> failwith "Can't call static_lookup on Native methods" | Java code -> let opcode = (Lazy.force code).c_code.(pp) in (match opcode with | OpInvoke (`Interface ccs, cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Class _ -> failwith "Impossible InvokeInterface" | Interface i -> i in static_interface_lookup interface_lookup_map classes_map interfaces children_classes cc cms | OpInvoke (`Virtual (TClass ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeVirtual" | Class c -> c in static_virtual_lookup virtual_lookup_map children_classes cc cms | OpInvoke (`Virtual (TArray _), cms) -> let cobj = let ioc = (ClassMap.find java_lang_object classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeVirtual" | Class c -> c in static_virtual_lookup virtual_lookup_map children_classes cobj cms | OpInvoke (`Static (_,ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeStatic" | Class c -> c in static_static_lookup static_lookup_map cc cms | OpInvoke (`Special (_,ccs), cms) -> let cc = let ioc = (ClassMap.find ccs classes_map) in match ioc with | Interface _ -> failwith "Impossible InvokeSpecial" | Class c -> c in let current_class = (ClassMap.find cs classes_map) in static_special_lookup special_lookup_map current_class cc cms | _ -> raise Not_found ) ) let default_classes = List.map make_cn ["java.lang.Class"; "java.lang.System"; "java.lang.String"; "java.lang.Thread"; "java.lang.ThreadGroup"; "java.lang.ref.Finalizer"; "java.lang.OutOfMemoryError"; "java.lang.NullPointerException"; "java.lang.ArrayStoreException"; "java.lang.ArithmeticException"; "java.lang.StackOverflowError"; "java.lang.IllegalMonitorStateException"; "java.lang.Compiler"; "java.lang.reflect.Method"; "java.lang.reflect.Field"] let parse_program ?(other_classes=default_classes) class_path names = let class_path = Javalib.class_path class_path in try let class_map = ref begin List.fold_left (fun clmap cn -> let c = Javalib.get_class class_path cn in let c_name = Javalib.get_name c in ClassMap.add c_name c clmap ) ClassMap.empty (other_classes @ names) end in let interfaces = ref ClassMap.empty in let p_classes = ClassMap.fold (fun _ c classes -> add_node class_path c classes interfaces) !class_map ClassMap.empty in let parsed_methods = ClassMap.fold (fun _ ioc_info cmmap -> let ioc = ioc_info in MethodMap.fold (fun _ cm cmmap -> ClassMethodMap.add cm.cm_class_method_signature (ioc,cm) cmmap ) (get_concrete_methods ioc) cmmap ) p_classes ClassMethodMap.empty in Javalib.close_class_path class_path; { classes = p_classes; parsed_methods = parsed_methods; static_lookup_method = static_lookup_method p_classes !interfaces } with e -> Javalib.close_class_path class_path; raise e let parse_program_bench ?(other_classes=default_classes) class_path names = let time_start = Sys.time() in ignore(parse_program ~other_classes class_path names); let time_stop = Sys.time() in Printf.printf "program parsed in %fs.\n" (time_stop-.time_start)
9f364d8b7be73fbfe4049beed2e94bcbafb0ab60f77e27482f71045d7651b6b7
ocsigen/eliom
eliom_lib.client.mli
Ocsigen * * Copyright ( C ) 2011 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2011 Grégoire Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** Eliom standard library *) open Js_of_ocaml * See { % < < a_api project="ocsigenserver"| module Ocsigen_lib_base > > % } . include module type of Ocsigen_lib_base with type poly = Ocsigen_lib_base.poly and type yesnomaybe = Ocsigen_lib_base.yesnomaybe and type ('a, 'b) leftright = ('a, 'b) Ocsigen_lib_base.leftright and type 'a Clist.t = 'a Ocsigen_lib_base.Clist.t and type 'a Clist.node = 'a Ocsigen_lib_base.Clist.node include module type of Eliom_lib_base with type 'a Int64_map.t = 'a Eliom_lib_base.Int64_map.t with type 'a String_map.t = 'a Eliom_lib_base.String_map.t with type 'a Int_map.t = 'a Eliom_lib_base.Int_map.t type file_info = File.file Js.t val to_json : ?typ:'a -> 'b -> string val of_json : ?typ:'a -> string -> 'b module Url : sig (** URL manipulation *) include module type of Url_base * See { % < < a_api project="ocsigenserver"| module Ocsigen_lib . Url_base > > % } . Ocsigen_lib.Url_base >> %}. *) include module type of Url * See { % < < a_api project="js_of_ocaml"| module . Url > > % } . val decode : string -> string val encode : ?plus:bool -> string -> string val make_encoded_parameters : (string * string) list -> string val split_path : string -> string list val get_ssl : string -> bool option val resolve : string -> string val add_get_args : string -> (string * string) list -> string val string_of_url_path : encode:bool -> string list -> string val path_of_url : url -> string list val path_of_url_string : string -> string list (** Extracts path from a URL string. Works on a best-effort basis for relative URLs *) end * Extension of { % < < a_api project="ocsigenserver"| module Ocsigen_lib_base . String_base > > % } . Ocsigen_lib_base.String_base >> %}. *) module String : sig include module type of String_base val remove_eols : string -> string end * Extension of { % < < a_api project="js_of_ocaml " subproject="js_of_ocaml - lwt " | module Lwt_log_js > > % } . module Lwt_log : sig include module type of Lwt_log_js with type level = Lwt_log_core.level and type logger = Lwt_log_core.logger and type section = Lwt_log_core.section and type template = Lwt_log_core.template and module Section = Lwt_log_core.Section val raise_error : ?inspect:'v -> ?exn:exn -> ?section:section -> ?location:string * int * int -> ?logger:logger -> string -> 'a val raise_error_f : ?inspect:'v -> ?exn:exn -> ?section:section -> ?location:string * int * int -> ?logger:logger -> ('a, unit, string, 'any) format4 -> 'a val eliom : section end val error : ('a, unit, string, 'b) format4 -> 'a (** Deprecated. Use Lwt_log.ign_raise_error_f instead *) val error_any : _ -> ('a, unit, string, 'b) format4 -> 'a * Deprecated . Use Lwt_log.ign_raise_error_f ( with ~inspect argument ) instead val debug : ('a, unit, string, unit) format4 -> 'a (** Deprecated. Use Lwt_log.ign_info_f instead *) val debug_exn : ('a, unit, string, unit) format4 -> exn -> 'a (** Deprecated. Use Lwt_log.ign_info_f instead *) val jsdebug : 'a -> unit * Deprecated . Use Lwt_log.ign_info ( with ~inspect argument ) instead val alert : ('a, unit, string, unit) format4 -> 'a val jsalert : Js.js_string Js.t -> unit val confirm : ('a, unit, string, bool) format4 -> 'a val debug_var : string -> 'a -> unit val trace : ('a, unit, string, unit) format4 -> 'a val lwt_ignore : ?message:string -> unit Lwt.t -> unit val encode_form_value : 'a -> string val unmarshal_js : Js.js_string Js.t -> 'a val encode_header_value : 'a -> string val make_cryptographic_safe_string : ?len:int -> unit -> string * Return a base-64 encoded cryptographic safe string of the given length . Not implemented client - side . Not implemented client-side. *)
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_lib.client.mli
ocaml
* Eliom standard library * URL manipulation * Extracts path from a URL string. Works on a best-effort basis for relative URLs * Deprecated. Use Lwt_log.ign_raise_error_f instead * Deprecated. Use Lwt_log.ign_info_f instead * Deprecated. Use Lwt_log.ign_info_f instead
Ocsigen * * Copyright ( C ) 2011 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2011 Grégoire Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Js_of_ocaml * See { % < < a_api project="ocsigenserver"| module Ocsigen_lib_base > > % } . include module type of Ocsigen_lib_base with type poly = Ocsigen_lib_base.poly and type yesnomaybe = Ocsigen_lib_base.yesnomaybe and type ('a, 'b) leftright = ('a, 'b) Ocsigen_lib_base.leftright and type 'a Clist.t = 'a Ocsigen_lib_base.Clist.t and type 'a Clist.node = 'a Ocsigen_lib_base.Clist.node include module type of Eliom_lib_base with type 'a Int64_map.t = 'a Eliom_lib_base.Int64_map.t with type 'a String_map.t = 'a Eliom_lib_base.String_map.t with type 'a Int_map.t = 'a Eliom_lib_base.Int_map.t type file_info = File.file Js.t val to_json : ?typ:'a -> 'b -> string val of_json : ?typ:'a -> string -> 'b module Url : sig include module type of Url_base * See { % < < a_api project="ocsigenserver"| module Ocsigen_lib . Url_base > > % } . Ocsigen_lib.Url_base >> %}. *) include module type of Url * See { % < < a_api project="js_of_ocaml"| module . Url > > % } . val decode : string -> string val encode : ?plus:bool -> string -> string val make_encoded_parameters : (string * string) list -> string val split_path : string -> string list val get_ssl : string -> bool option val resolve : string -> string val add_get_args : string -> (string * string) list -> string val string_of_url_path : encode:bool -> string list -> string val path_of_url : url -> string list val path_of_url_string : string -> string list end * Extension of { % < < a_api project="ocsigenserver"| module Ocsigen_lib_base . String_base > > % } . Ocsigen_lib_base.String_base >> %}. *) module String : sig include module type of String_base val remove_eols : string -> string end * Extension of { % < < a_api project="js_of_ocaml " subproject="js_of_ocaml - lwt " | module Lwt_log_js > > % } . module Lwt_log : sig include module type of Lwt_log_js with type level = Lwt_log_core.level and type logger = Lwt_log_core.logger and type section = Lwt_log_core.section and type template = Lwt_log_core.template and module Section = Lwt_log_core.Section val raise_error : ?inspect:'v -> ?exn:exn -> ?section:section -> ?location:string * int * int -> ?logger:logger -> string -> 'a val raise_error_f : ?inspect:'v -> ?exn:exn -> ?section:section -> ?location:string * int * int -> ?logger:logger -> ('a, unit, string, 'any) format4 -> 'a val eliom : section end val error : ('a, unit, string, 'b) format4 -> 'a val error_any : _ -> ('a, unit, string, 'b) format4 -> 'a * Deprecated . Use Lwt_log.ign_raise_error_f ( with ~inspect argument ) instead val debug : ('a, unit, string, unit) format4 -> 'a val debug_exn : ('a, unit, string, unit) format4 -> exn -> 'a val jsdebug : 'a -> unit * Deprecated . Use Lwt_log.ign_info ( with ~inspect argument ) instead val alert : ('a, unit, string, unit) format4 -> 'a val jsalert : Js.js_string Js.t -> unit val confirm : ('a, unit, string, bool) format4 -> 'a val debug_var : string -> 'a -> unit val trace : ('a, unit, string, unit) format4 -> 'a val lwt_ignore : ?message:string -> unit Lwt.t -> unit val encode_form_value : 'a -> string val unmarshal_js : Js.js_string Js.t -> 'a val encode_header_value : 'a -> string val make_cryptographic_safe_string : ?len:int -> unit -> string * Return a base-64 encoded cryptographic safe string of the given length . Not implemented client - side . Not implemented client-side. *)
2a3298e647a5157478843fd57a591228455ed5a0fb0bced1f572c7da2eedf264
funimage/funimage
project.clj
(defproject funimage "0.1.100-SNAPSHOT" :description "Functional Image Processing with ImageJ/FIJI" :url "" :license {:name "Apache v2.0" :url ""} :dependencies [[org.clojure/clojure "1.8.0"] [seesaw "1.4.4"] [ me.raynes/fs " 1.4.6 " ] ;[org.clojure/data.zip "0.1.1"] [clj-random "0.1.8"] [ cc.artifice/clj-ml " 0.8.5 " ] [random-forests-clj "0.2.0"] Java libs [net.imglib2/imglib2-algorithm "0.8.0"] [net.imglib2/imglib2-roi "0.4.6"] [net.imglib2/imglib2-ij "2.0.0-beta-37"] [net.imagej/imagej "2.0.0-rc-61" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm]] [net.imagej/imagej-ops "0.38.1-SNAPSHOT"] [net.imagej/imagej-mesh "0.1.1-SNAPSHOT"] [ome/bioformats_package "5.3.3"] [sc.fiji/Auto_Threshold "1.16.0"] ] :java-source-paths ["java"] :repositories [["imagej" "/"] ["imagej-releases" "/"] ["ome maven" "/"] ["imagej-snapshots" "/"] ["clojars2" {:url "/" :username :env/LEIN_USERNAME :password :env/LEIN_PASSWORD}]] :deploy-repositories [["releases" {:url "" Select a GPG private key to use for ;; signing. (See "How to specify a user ID " in GPG 's manual . ) GPG will otherwise pick the first private key ;; it finds in your keyring. ;; Currently only works in :deploy-repositories ;; or as a top-level (global) setting. :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}] ["snapshots" {:url "" :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}]] Try to use parent when we can : plugins [ [ - parent " 0.3.1 " ] ] :jvm-opts ["-Xmx32g" "-server" ;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init" #_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"] ;:javac-options ["-target" "1.6" "-source" "1.6"] )
null
https://raw.githubusercontent.com/funimage/funimage/397d1ed9a1c11287f8562d05c10040ce24717f04/project.clj
clojure
[org.clojure/data.zip "0.1.1"] signing. (See "How to specify a user it finds in your keyring. Currently only works in :deploy-repositories or as a top-level (global) setting. "-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init" :javac-options ["-target" "1.6" "-source" "1.6"]
(defproject funimage "0.1.100-SNAPSHOT" :description "Functional Image Processing with ImageJ/FIJI" :url "" :license {:name "Apache v2.0" :url ""} :dependencies [[org.clojure/clojure "1.8.0"] [seesaw "1.4.4"] [ me.raynes/fs " 1.4.6 " ] [clj-random "0.1.8"] [ cc.artifice/clj-ml " 0.8.5 " ] [random-forests-clj "0.2.0"] Java libs [net.imglib2/imglib2-algorithm "0.8.0"] [net.imglib2/imglib2-roi "0.4.6"] [net.imglib2/imglib2-ij "2.0.0-beta-37"] [net.imagej/imagej "2.0.0-rc-61" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm]] [net.imagej/imagej-ops "0.38.1-SNAPSHOT"] [net.imagej/imagej-mesh "0.1.1-SNAPSHOT"] [ome/bioformats_package "5.3.3"] [sc.fiji/Auto_Threshold "1.16.0"] ] :java-source-paths ["java"] :repositories [["imagej" "/"] ["imagej-releases" "/"] ["ome maven" "/"] ["imagej-snapshots" "/"] ["clojars2" {:url "/" :username :env/LEIN_USERNAME :password :env/LEIN_PASSWORD}]] :deploy-repositories [["releases" {:url "" Select a GPG private key to use for ID " in GPG 's manual . ) GPG will otherwise pick the first private key :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}] ["snapshots" {:url "" :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}]] Try to use parent when we can : plugins [ [ - parent " 0.3.1 " ] ] :jvm-opts ["-Xmx32g" "-server" #_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"] )
89c9571212a6fa089040bc73621b10855fadde7f8e9edca552c4fcc855f9bfc7
glutamate/bugpan
Database.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Database where import EvalM --import Eval import Expr import Data.Maybe import Data.List import Numbers import ImpInterpret import Compiler import Stages import Traverse import Transform import Compiler import Stages import Traverse import Transform-} import Control.Monad import Control . . List import Control.Monad.State.Lazy import System.Directory import System.Time import System.Cmd import System . Random import System . Info . MAC as MAC import Data . Digest . Pure . SHA import Data . ByteString . Internal import Data . UUID import Data . UUID.V1 import Numeric import Traverse import Transform --import Stages import Data.Ord import Data.Char import Control.Concurrent import TNUtils import PrettyPrint import ValueIO data Session = Session { baseDir :: FilePath, tSessionStart :: ClockTime } deriving (Eq, Show) withoutTrailing c [] = [] withoutTrailing c cs = if last cs == c then init cs else cs createSession rootDir t0@(TOD t1 t2) name = do let baseDir = rootDir ./ name --print baseDir createDirectory baseDir createDirectory $ baseDir./ "signals" createDirectory $ baseDir./ "events" createDirectory $ baseDir./ "durations" writeFile (baseDir./ "tStart") $ show (t1, t2) writeFile (baseDir./ "sessionFormatVersion") $ "3" return $ Session baseDir t0 getUUID :: IO String getUUID = do u <- sh "uuidgen" return $ filter (isAlphaNum) u newSession :: FilePath -> IO Session newSession rootDir = do t0@(TOD t1 t2) <- getClockTime --Just mac <- MAC.new ---rnd <- asInt `fmap` randomIO let longStr = concat [ show t1 , show t2 , show , show ] let sha = take 20 . . sha512 . BS.pack $ map c2w " foo " muuid < - ( fmap ( filter ( /='- ' ) . ) ) ` fmap ` nextUUID --print muuid --Just uuid <- return muuid uuid <- getUUID createSession rootDir t0 uuid sessEvalState s = EvalS 0 0 Nothing ( qenv s + + ( evalManyAtOnce $ sessPrelude s ) ) newSessionNamed :: String -> FilePath -> IO Session newSessionNamed nm rootDir = do t0@(TOD t1 t2) <- getClockTime putStrLn $ "creating new session called "++nm whenM ( ) $ do createSession rootDir t0 nm cloneSession :: Session -> String-> Int -> IO Session cloneSession (Session oldBasedir t0@(TOD t1 t2)) postfix newVersion = do let baseDir = withoutTrailing '/' oldBasedir ++ postfix createDirectory baseDir createDirectory $ baseDir ./ "signals" createDirectory $ baseDir ./ "events" createDirectory $ baseDir ./ "durations" writeFile (baseDir ./ "tStart") $ show (t1, t2) writeFile (baseDir ./ "sessionFormatVersion") $ show newVersion return $ Session baseDir t0 sessEvalState s = EvalS 0 0 Nothing ( qenv s + + ( evalManyAtOnce $ sessPrelude s ) ) sessionTypes :: Session -> IO [(String, T)] sessionTypes sess@(Session dir' _) = do let dir = oneTrailingSlash dir' xs <- forM ["signals", "events", "durations"] $ \kind -> do sigs <- getDirContents $ dir ./ kind --print sigs forM sigs $ \sig -> do --print (kind, sig) do fnms <- getSortedDirContents $ dir ./ kind ./ sig fTT <- fileTypeTag $ dir ./ kind ./ sig ./ (head fnms) --v<-loadUntyped $ dir./ kind./ sig --print (kind, sig, head v ) return (sig, fTT) --typeOfVal $ head v) return $ concat xs loadUntyped :: FilePath -> IO [V] loadUntyped fp = do ifM (doesDirectoryExist fp) (do fnms <- getSortedDirContents fp xs <- forM fnms $ \fn-> loadVs $ fp./ fn return $ concat xs) ((print $ "dir not found:" ++fp) >> return []) existsSession :: String -> FilePath -> IO Bool existsSession nm root = doesDirectoryExist $ root ./ nm lastSession :: FilePath -> IO Session lastSession rootDir = do sesns <- getSessionInRootDir rootDir sesnsTm <- mapM (\dirNm-> do tm <- getModificationTime (oneTrailingSlash rootDir++dirNm) return (oneTrailingSlash rootDir++dirNm, tm)) sesns let dir = fst $ maximumBy (comparing snd) sesnsTm loadExactSession dir safeLastSession :: FilePath -> IO (Maybe Session) safeLastSession rootDir = do sesns <- getSessionInRootDir rootDir if null sesns then return Nothing else Just `fmap` lastSession rootDir deleteSession :: Session -> IO () deleteSession (Session dir _) = system ("rm -rf "++ dir) >> return () resolveApproxSession :: FilePath -> String -> IO String resolveApproxSession root nm | nm == "last" = do (last . splitBy '/' . baseDir) `fmap` lastSession root | nm == "new" = do (last . splitBy '/' . baseDir) `fmap` newSession root | "new:" `isPrefixOf` nm = do let newnm = (!!1) $ splitBy ':' nm (last . splitBy '/' . baseDir) `fmap` newSessionNamed newnm root | otherwise = do sessns <- getSessionInRootDir root --print sessns case find (nm `isPrefixOf`) sessns of Just s -> return s _ -> return $ "fail_resolve" loadApproxSession :: FilePath -> String -> IO Session loadApproxSession root nm = do " asked to resolve : " + + nm sessNm <- resolveApproxSession root nm --putStrLn "done" loadExactSession $ oneTrailingSlash root++sessNm loadExactSession :: FilePath -> IO Session loadExactSession dir = do t0 <- read `fmap` readFile (dir ./ "tStart") return $ Session dir (TOD (fst t0) (snd t0)) getSessionInRootDir rootDir = do sesns <- getDirContents rootDir --mapM print sesns filterM (\objNm -> do isDir <- doesDirectoryExist $ rootDir ./ objNm return $ isDir) sesns getSortedDirContents dir = do conts <- getDirContents dir let sconts = sortBy cmpf conts --liftIO $ print sconts return sconts where cmpf f1 f2 = case (readHex f1, readHex f2) of ((n1,_):_, (n2,_):_) -> compare (idInt n1) (idInt n2) _ -> EQ loadSession :: FilePath -> String -> IO Session loadSession rootDir initnm = do sesns <- (filter (initnm `isPrefixOf`)) `fmap` getSessionInRootDir rootDir case sesns of (sess:[]) -> loadExactSession $ oneTrailingSlash rootDir++sess [] -> fail $ "No session starting with "++initnm++" in "++rootDir ss -> fail $ "Ambiguous session "++initnm ++": "++show ss orIfEmpty :: [a] -> [a] -> [a] orIfEmpty [] xs = xs orIfEmpty xs _ = xs unString :: E -> String unString (Const (StringV s)) = s unString _ = "" addRunToSession :: [Declare] -> RealNum -> RealNum -> RealNum -> [(String, V)] -> Session -> IO () addRunToSession decls t0 tmax dt ress sess@(Session basedir sesst0) = let nmsToStore = [ (nm, unString arg `orIfEmpty` nm) | SinkConnect (Var nm) ("store",arg) <- decls ] sigsToStore = catMaybes . flip map nmsToStore $ \(nm, nmStore)-> case lookup ('#':nm) ress `guardBy` isSig of Just s@(SigV _ _ _ _) -> Just (nmStore,shift t0 s) _ -> Nothing evtsToStore = reverse . catMaybes . flip map nmsToStore $ \(nm, nmStore) -> case lookup nm ress `guardBy` isEvents of Just (ListV evs) -> Just (nmStore, reverse $ map (shift t0) evs) _ -> Nothing epsToStore = catMaybes . flip map nmsToStore $ \(nm, nmStore) -> case lookup nm ress `guardBy` isEpochs of Just (ListV eps) -> Just (nmStore, map (shift t0) eps) _ -> Nothing t1 = NumV. NReal $ t0 t2 = NumV. NReal $ t0+tmax moduleName = safeHead [nm | Let (PatVar "moduleName" _) (Const (StringV nm)) <- decls] moduleEps = case moduleName of Nothing -> [] Just nm -> [("moduleName", [PairV (PairV t1 t2) (StringV (nm))]), (nm, [PairV (PairV t1 t2) Unit])] tStartEvs = [("tStart", [PairV t1 Unit]), ("tStop", [PairV t2 Unit])] progEp = [("program", [PairV (PairV t1 t2) (StringV (unlines $ map ppDecl decls))]), ("running", [PairV (PairV t1 t2) Unit])]++moduleEps saveInSubDir subdir nm obj = do let dir = (basedir ./ subdir ./ nm) createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir ./ showHex ntics "") obj Session newEvs newSigSegs ( ( t0,t0+tmax , decls):programsRun sess ) ( qenv sess ) ( sessPrelude sess ) putStrLn $ "saving session: "++show nmsToStore " from results : " + + show ress forM sigsToStore $ \(nm,sig) -> do putStrLn $"saving signal "++ nm++": "++ show sig saveInSubDir "signals" nm [sig] putStrLn "done" forM (tStartEvs++evtsToStore) $ \(nm, evs) -> do putStrLn $"saving events "++ nm saveInSubDir "events" nm evs forM (progEp++epsToStore) $ \(nm, eps) -> do putStrLn $"saving epochs "++ nm saveInSubDir "durations" nm eps print "done saving session" return () --simpler interface saveInSession sess@(Session basedir _) nm t0 dt sig@(SigV t1 t2 sigdt sf) = do let dir = basedir ./ "signals/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir./ showHex ntics "") $ [shift t0 sig] saveInSession sess@(Session basedir sesst0) nm t0 dt lst@(ListV []) = return () saveInSession sess@(Session basedir sesst0) nm t0 dt lst@(ListV evs) | isEvents lst = do let dir = basedir ./ "events/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir./ showHex ntics "") . reverse $ map (shift t0) evs | isEpochs lst = do let dir = basedir ./ "durations/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir ./ showHex ntics "") $ map (shift t0) evs isTrue (BoolV True) = True isNotFalse (BoolV False) = False isNotFalse _ = True sigInDurs s@(SigV ts1 ts2 dt sf) durs = catMaybes $ for durs $ \dur-> let (tep1,tep2) = epTs dur in cond [(ts1<tep1 && ts2>tep2, Just $ SigV tep1 tep2 dt $ \t->sf(t-(round $ tep1/dt)))] Nothing evTime (PairV nv@(NumV _) _) = unsafeVToDbl nv evTag (PairV (NumV (NReal t)) v) = v epTs (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) _) = (t1,t2) epTag (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) v) = v isEpoch (PairV (PairV (NumV _) ((NumV _))) _) = True isEpoch _ = False isEvent (PairV (NumV _) _) = True isEvent _ = False isEvents (ListV vs) = all isEvent vs isEvents _ = False isEpochs (ListV vs) = all isEpoch vs isEpochs _ = False isSig (SigV _ _ _ _) = True isSig _ = False startTime (PairV nv@(NumV _) _) = unsafeVToDbl nv startTime (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) v) = t1 startTime (SigV t1 _ _ _) = t1 sortVs :: [V] -> [V] sortVs [] = [] sortVs vs = sortBy (comparing startTime) vs guardBy : : ( MonadPlus m ) = > m a - > ( a->Bool ) - > m a guardBy :: Maybe a -> (a->Bool) -> Maybe a guardBy Nothing _ = Nothing guardBy (Just x) p | p x = Just x | otherwise = Nothing do x < - mx if p x then mx else Nothing if p x then mx else Nothing -} class Shiftable s where shift :: Double -> s -> s rebaseTime :: Double -> s -> s instance Shiftable V where shift ts (SigV t1 t2 dt sf) = SigV (t1+ts) (t2+ts) dt $ sf shift ts (PairV (NumV t) v) = (PairV (NumV $ t+(NReal ts)) v) shift ts (PairV (PairV (NumV t1) ((NumV t2))) v) = (PairV (PairV (NumV $ t1 +(NReal ts)) ((NumV $ t2 + (NReal ts)))) v) rebaseTime t (SigV t1 t2 dt sf) = SigV (t1*t) (t2*t) (dt*t) $ sf rebaseTime ts (PairV (NumV t) v) = (PairV (NumV $ t*(NReal ts)) v) rebaseTime ts (PairV (PairV (NumV t1) ((NumV t2))) v) = (PairV (PairV (NumV $ t1 *(NReal ts)) ((NumV $ t2 * (NReal ts)))) v) mkList :: V -> [V] mkList (ListV vs) = vs mkList v = [v] getDirContents dir = do objs <- liftIO $ getDirectoryContents dir return $ filter (not . (`elem` [".", ".."])) objs
null
https://raw.githubusercontent.com/glutamate/bugpan/d0983152f5afce306049262cba296df00e52264b/Database.hs
haskell
import Eval import Stages print baseDir Just mac <- MAC.new -rnd <- asInt `fmap` randomIO print muuid Just uuid <- return muuid print sigs print (kind, sig) v<-loadUntyped $ dir./ kind./ sig print (kind, sig, head v ) typeOfVal $ head v) print sessns putStrLn "done" mapM print sesns liftIO $ print sconts simpler interface
# LANGUAGE GeneralizedNewtypeDeriving # module Database where import EvalM import Expr import Data.Maybe import Data.List import Numbers import ImpInterpret import Compiler import Stages import Traverse import Transform import Compiler import Stages import Traverse import Transform-} import Control.Monad import Control . . List import Control.Monad.State.Lazy import System.Directory import System.Time import System.Cmd import System . Random import System . Info . MAC as MAC import Data . Digest . Pure . SHA import Data . ByteString . Internal import Data . UUID import Data . UUID.V1 import Numeric import Traverse import Transform import Data.Ord import Data.Char import Control.Concurrent import TNUtils import PrettyPrint import ValueIO data Session = Session { baseDir :: FilePath, tSessionStart :: ClockTime } deriving (Eq, Show) withoutTrailing c [] = [] withoutTrailing c cs = if last cs == c then init cs else cs createSession rootDir t0@(TOD t1 t2) name = do let baseDir = rootDir ./ name createDirectory baseDir createDirectory $ baseDir./ "signals" createDirectory $ baseDir./ "events" createDirectory $ baseDir./ "durations" writeFile (baseDir./ "tStart") $ show (t1, t2) writeFile (baseDir./ "sessionFormatVersion") $ "3" return $ Session baseDir t0 getUUID :: IO String getUUID = do u <- sh "uuidgen" return $ filter (isAlphaNum) u newSession :: FilePath -> IO Session newSession rootDir = do t0@(TOD t1 t2) <- getClockTime let longStr = concat [ show t1 , show t2 , show , show ] let sha = take 20 . . sha512 . BS.pack $ map c2w " foo " muuid < - ( fmap ( filter ( /='- ' ) . ) ) ` fmap ` nextUUID uuid <- getUUID createSession rootDir t0 uuid sessEvalState s = EvalS 0 0 Nothing ( qenv s + + ( evalManyAtOnce $ sessPrelude s ) ) newSessionNamed :: String -> FilePath -> IO Session newSessionNamed nm rootDir = do t0@(TOD t1 t2) <- getClockTime putStrLn $ "creating new session called "++nm whenM ( ) $ do createSession rootDir t0 nm cloneSession :: Session -> String-> Int -> IO Session cloneSession (Session oldBasedir t0@(TOD t1 t2)) postfix newVersion = do let baseDir = withoutTrailing '/' oldBasedir ++ postfix createDirectory baseDir createDirectory $ baseDir ./ "signals" createDirectory $ baseDir ./ "events" createDirectory $ baseDir ./ "durations" writeFile (baseDir ./ "tStart") $ show (t1, t2) writeFile (baseDir ./ "sessionFormatVersion") $ show newVersion return $ Session baseDir t0 sessEvalState s = EvalS 0 0 Nothing ( qenv s + + ( evalManyAtOnce $ sessPrelude s ) ) sessionTypes :: Session -> IO [(String, T)] sessionTypes sess@(Session dir' _) = do let dir = oneTrailingSlash dir' xs <- forM ["signals", "events", "durations"] $ \kind -> do sigs <- getDirContents $ dir ./ kind forM sigs $ \sig -> do do fnms <- getSortedDirContents $ dir ./ kind ./ sig fTT <- fileTypeTag $ dir ./ kind ./ sig ./ (head fnms) return $ concat xs loadUntyped :: FilePath -> IO [V] loadUntyped fp = do ifM (doesDirectoryExist fp) (do fnms <- getSortedDirContents fp xs <- forM fnms $ \fn-> loadVs $ fp./ fn return $ concat xs) ((print $ "dir not found:" ++fp) >> return []) existsSession :: String -> FilePath -> IO Bool existsSession nm root = doesDirectoryExist $ root ./ nm lastSession :: FilePath -> IO Session lastSession rootDir = do sesns <- getSessionInRootDir rootDir sesnsTm <- mapM (\dirNm-> do tm <- getModificationTime (oneTrailingSlash rootDir++dirNm) return (oneTrailingSlash rootDir++dirNm, tm)) sesns let dir = fst $ maximumBy (comparing snd) sesnsTm loadExactSession dir safeLastSession :: FilePath -> IO (Maybe Session) safeLastSession rootDir = do sesns <- getSessionInRootDir rootDir if null sesns then return Nothing else Just `fmap` lastSession rootDir deleteSession :: Session -> IO () deleteSession (Session dir _) = system ("rm -rf "++ dir) >> return () resolveApproxSession :: FilePath -> String -> IO String resolveApproxSession root nm | nm == "last" = do (last . splitBy '/' . baseDir) `fmap` lastSession root | nm == "new" = do (last . splitBy '/' . baseDir) `fmap` newSession root | "new:" `isPrefixOf` nm = do let newnm = (!!1) $ splitBy ':' nm (last . splitBy '/' . baseDir) `fmap` newSessionNamed newnm root | otherwise = do sessns <- getSessionInRootDir root case find (nm `isPrefixOf`) sessns of Just s -> return s _ -> return $ "fail_resolve" loadApproxSession :: FilePath -> String -> IO Session loadApproxSession root nm = do " asked to resolve : " + + nm sessNm <- resolveApproxSession root nm loadExactSession $ oneTrailingSlash root++sessNm loadExactSession :: FilePath -> IO Session loadExactSession dir = do t0 <- read `fmap` readFile (dir ./ "tStart") return $ Session dir (TOD (fst t0) (snd t0)) getSessionInRootDir rootDir = do sesns <- getDirContents rootDir filterM (\objNm -> do isDir <- doesDirectoryExist $ rootDir ./ objNm return $ isDir) sesns getSortedDirContents dir = do conts <- getDirContents dir let sconts = sortBy cmpf conts return sconts where cmpf f1 f2 = case (readHex f1, readHex f2) of ((n1,_):_, (n2,_):_) -> compare (idInt n1) (idInt n2) _ -> EQ loadSession :: FilePath -> String -> IO Session loadSession rootDir initnm = do sesns <- (filter (initnm `isPrefixOf`)) `fmap` getSessionInRootDir rootDir case sesns of (sess:[]) -> loadExactSession $ oneTrailingSlash rootDir++sess [] -> fail $ "No session starting with "++initnm++" in "++rootDir ss -> fail $ "Ambiguous session "++initnm ++": "++show ss orIfEmpty :: [a] -> [a] -> [a] orIfEmpty [] xs = xs orIfEmpty xs _ = xs unString :: E -> String unString (Const (StringV s)) = s unString _ = "" addRunToSession :: [Declare] -> RealNum -> RealNum -> RealNum -> [(String, V)] -> Session -> IO () addRunToSession decls t0 tmax dt ress sess@(Session basedir sesst0) = let nmsToStore = [ (nm, unString arg `orIfEmpty` nm) | SinkConnect (Var nm) ("store",arg) <- decls ] sigsToStore = catMaybes . flip map nmsToStore $ \(nm, nmStore)-> case lookup ('#':nm) ress `guardBy` isSig of Just s@(SigV _ _ _ _) -> Just (nmStore,shift t0 s) _ -> Nothing evtsToStore = reverse . catMaybes . flip map nmsToStore $ \(nm, nmStore) -> case lookup nm ress `guardBy` isEvents of Just (ListV evs) -> Just (nmStore, reverse $ map (shift t0) evs) _ -> Nothing epsToStore = catMaybes . flip map nmsToStore $ \(nm, nmStore) -> case lookup nm ress `guardBy` isEpochs of Just (ListV eps) -> Just (nmStore, map (shift t0) eps) _ -> Nothing t1 = NumV. NReal $ t0 t2 = NumV. NReal $ t0+tmax moduleName = safeHead [nm | Let (PatVar "moduleName" _) (Const (StringV nm)) <- decls] moduleEps = case moduleName of Nothing -> [] Just nm -> [("moduleName", [PairV (PairV t1 t2) (StringV (nm))]), (nm, [PairV (PairV t1 t2) Unit])] tStartEvs = [("tStart", [PairV t1 Unit]), ("tStop", [PairV t2 Unit])] progEp = [("program", [PairV (PairV t1 t2) (StringV (unlines $ map ppDecl decls))]), ("running", [PairV (PairV t1 t2) Unit])]++moduleEps saveInSubDir subdir nm obj = do let dir = (basedir ./ subdir ./ nm) createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir ./ showHex ntics "") obj Session newEvs newSigSegs ( ( t0,t0+tmax , decls):programsRun sess ) ( qenv sess ) ( sessPrelude sess ) putStrLn $ "saving session: "++show nmsToStore " from results : " + + show ress forM sigsToStore $ \(nm,sig) -> do putStrLn $"saving signal "++ nm++": "++ show sig saveInSubDir "signals" nm [sig] putStrLn "done" forM (tStartEvs++evtsToStore) $ \(nm, evs) -> do putStrLn $"saving events "++ nm saveInSubDir "events" nm evs forM (progEp++epsToStore) $ \(nm, eps) -> do putStrLn $"saving epochs "++ nm saveInSubDir "durations" nm eps print "done saving session" return () saveInSession sess@(Session basedir _) nm t0 dt sig@(SigV t1 t2 sigdt sf) = do let dir = basedir ./ "signals/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir./ showHex ntics "") $ [shift t0 sig] saveInSession sess@(Session basedir sesst0) nm t0 dt lst@(ListV []) = return () saveInSession sess@(Session basedir sesst0) nm t0 dt lst@(ListV evs) | isEvents lst = do let dir = basedir ./ "events/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir./ showHex ntics "") . reverse $ map (shift t0) evs | isEpochs lst = do let dir = basedir ./ "durations/"++nm createDirectoryIfMissing False dir let ntics = round $ t0/dt saveVs (dir ./ showHex ntics "") $ map (shift t0) evs isTrue (BoolV True) = True isNotFalse (BoolV False) = False isNotFalse _ = True sigInDurs s@(SigV ts1 ts2 dt sf) durs = catMaybes $ for durs $ \dur-> let (tep1,tep2) = epTs dur in cond [(ts1<tep1 && ts2>tep2, Just $ SigV tep1 tep2 dt $ \t->sf(t-(round $ tep1/dt)))] Nothing evTime (PairV nv@(NumV _) _) = unsafeVToDbl nv evTag (PairV (NumV (NReal t)) v) = v epTs (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) _) = (t1,t2) epTag (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) v) = v isEpoch (PairV (PairV (NumV _) ((NumV _))) _) = True isEpoch _ = False isEvent (PairV (NumV _) _) = True isEvent _ = False isEvents (ListV vs) = all isEvent vs isEvents _ = False isEpochs (ListV vs) = all isEpoch vs isEpochs _ = False isSig (SigV _ _ _ _) = True isSig _ = False startTime (PairV nv@(NumV _) _) = unsafeVToDbl nv startTime (PairV (PairV (NumV (NReal t1)) ((NumV (NReal t2)))) v) = t1 startTime (SigV t1 _ _ _) = t1 sortVs :: [V] -> [V] sortVs [] = [] sortVs vs = sortBy (comparing startTime) vs guardBy : : ( MonadPlus m ) = > m a - > ( a->Bool ) - > m a guardBy :: Maybe a -> (a->Bool) -> Maybe a guardBy Nothing _ = Nothing guardBy (Just x) p | p x = Just x | otherwise = Nothing do x < - mx if p x then mx else Nothing if p x then mx else Nothing -} class Shiftable s where shift :: Double -> s -> s rebaseTime :: Double -> s -> s instance Shiftable V where shift ts (SigV t1 t2 dt sf) = SigV (t1+ts) (t2+ts) dt $ sf shift ts (PairV (NumV t) v) = (PairV (NumV $ t+(NReal ts)) v) shift ts (PairV (PairV (NumV t1) ((NumV t2))) v) = (PairV (PairV (NumV $ t1 +(NReal ts)) ((NumV $ t2 + (NReal ts)))) v) rebaseTime t (SigV t1 t2 dt sf) = SigV (t1*t) (t2*t) (dt*t) $ sf rebaseTime ts (PairV (NumV t) v) = (PairV (NumV $ t*(NReal ts)) v) rebaseTime ts (PairV (PairV (NumV t1) ((NumV t2))) v) = (PairV (PairV (NumV $ t1 *(NReal ts)) ((NumV $ t2 * (NReal ts)))) v) mkList :: V -> [V] mkList (ListV vs) = vs mkList v = [v] getDirContents dir = do objs <- liftIO $ getDirectoryContents dir return $ filter (not . (`elem` [".", ".."])) objs
320d77632e1e22b8911b897e2cd7ec6ee1e990c6d8ed1a46273dd2e03a9b40c7
codxse/zenius-material
styles.cljs
(ns zenius-material.styles (:require [reagent.core :as r])) (def colors (js->clj (aget js/MaterialUI "colors") :keywordize-keys true)) ;; ============================================= helper fns (defn color [color_ level_] (get-in colors [color_ level_] "#000000"))
null
https://raw.githubusercontent.com/codxse/zenius-material/0e5a2c64fd3455f81b8a43ff41f407c7bcdb8ce9/src/zenius_material/styles.cljs
clojure
=============================================
(ns zenius-material.styles (:require [reagent.core :as r])) (def colors (js->clj (aget js/MaterialUI "colors") :keywordize-keys true)) helper fns (defn color [color_ level_] (get-in colors [color_ level_] "#000000"))
e9d9bcc8d2b26bad11f0a1143e693dcae1cc9875951b602fb396ff6553ba563d
metabase/metabase
sqlite.clj
(ns metabase.driver.sqlite (:require [clojure.java.io :as io] [clojure.string :as str] [java-time :as t] [metabase.config :as config] [metabase.driver :as driver] [metabase.driver.common :as driver.common] [metabase.driver.sql :as driver.sql] [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn] [metabase.driver.sql-jdbc.execute :as sql-jdbc.execute] [metabase.driver.sql-jdbc.sync :as sql-jdbc.sync] [metabase.driver.sql.parameters.substitution :as sql.params.substitution] [metabase.driver.sql.query-processor :as sql.qp] [metabase.query-processor.error-type :as qp.error-type] [metabase.util.date-2 :as u.date] [metabase.util.honey-sql-2 :as h2x] [metabase.util.i18n :refer [tru]] [schema.core :as s]) (:import (java.sql Connection ResultSet Types) (java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime) (java.time.temporal Temporal))) (set! *warn-on-reflection* true) (driver/register! :sqlite, :parent :sql-jdbc) (defmethod sql.qp/honey-sql-version :sqlite [_driver] 2) SQLite does not support a lot of features , so do not show the options in the interface (doseq [[feature supported?] {:right-join false :full-join false :regex false :percentile-aggregations false :advanced-math-expressions false :standard-deviation-aggregations false :datetime-diff true :now true}] (defmethod driver/supports? [:sqlite feature] [_ _] supported?)) SQLite ` LIKE ` clauses are case - insensitive by default , and thus can not be made case - sensitive . So let people know ;; we have this 'feature' so the frontend doesn't try to present the option to you. (defmethod driver/supports? [:sqlite :case-sensitivity-string-filter-options] [_ _] false) HACK SQLite does n't support ALTER TABLE ADD CONSTRAINT FOREIGN KEY and I do n't have all day to work around this so ;; for now we'll just skip the foreign key stuff in the tests. (defmethod driver/supports? [:sqlite :foreign-keys] [_ _] (not config/is-test?)) Every SQLite3 file starts with " SQLite Format 3 " or " * * This file contains an SQLite There is also but last 2 version was 2005 (defn- confirm-file-is-sqlite [filename] (with-open [reader (io/input-stream filename)] (let [outarr (byte-array 50)] (.read reader outarr) (let [line (String. outarr)] (or (str/includes? line "SQLite format 3") (str/includes? line "This file contains an SQLite")))))) (defmethod driver/can-connect? :sqlite [driver details] (if (confirm-file-is-sqlite (:db details)) (sql-jdbc.conn/can-connect? driver details) false)) (defmethod driver/db-start-of-week :sqlite [_] :sunday) (defmethod sql-jdbc.conn/connection-details->spec :sqlite [_ {:keys [db] :or {db "sqlite.db"} :as details}] (merge {:subprotocol "sqlite" :subname db} (dissoc details :db) disallow " FDW " ( connecting to other SQLite databases on the local filesystem ) -- see {:limit_attached 0})) We 'll do regex pattern matching here for determining Field types because SQLite types can have optional lengths , ;; e.g. NVARCHAR(100) or NUMERIC(10,5) See also (def ^:private database-type->base-type (sql-jdbc.sync/pattern-based-database-type->base-type [[#"BIGINT" :type/BigInteger] [#"BIG INT" :type/BigInteger] [#"INT" :type/Integer] [#"CHAR" :type/Text] [#"TEXT" :type/Text] [#"CLOB" :type/Text] [#"BLOB" :type/*] [#"REAL" :type/Float] [#"DOUB" :type/Float] [#"FLOA" :type/Float] [#"NUMERIC" :type/Float] [#"DECIMAL" :type/Decimal] [#"BOOLEAN" :type/Boolean] [#"TIMESTAMP" :type/DateTime] [#"DATETIME" :type/DateTime] [#"DATE" :type/Date] [#"TIME" :type/Time]])) (defmethod sql-jdbc.sync/database-type->base-type :sqlite [_ database-type] (database-type->base-type database-type)) The normal SELECT * FROM table WHERE 1 < > 1 LIMIT 0 query does n't return any information for SQLite views -- it seems to be the case that the query has to return at least one row (defmethod sql-jdbc.sync/fallback-metadata-query :sqlite [driver schema table] (sql.qp/format-honeysql driver {:select [:*] :from [[(h2x/identifier :table schema table)]] :limit 1})) (def ^:private ->date (partial conj [:date])) (def ^:private ->datetime (partial conj [:datetime])) (def ^:private ->time (partial conj [:time])) (defn- strftime [format-str expr] [:strftime (h2x/literal format-str) expr]) ;; See also the [SQLite Date and Time Functions Reference](). (defmethod sql.qp/date [:sqlite :default] [_driver _unit expr] expr) (defmethod sql.qp/date [:sqlite :second] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:%M:%S" expr))) (defmethod sql.qp/date [:sqlite :second-of-minute] [_driver _ expr] (h2x/->integer (strftime "%S" expr))) (defmethod sql.qp/date [:sqlite :minute] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:%M" expr))) (defmethod sql.qp/date [:sqlite :minute-of-hour] [_driver _ expr] (h2x/->integer (strftime "%M" expr))) (defmethod sql.qp/date [:sqlite :hour] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:00" expr))) (defmethod sql.qp/date [:sqlite :hour-of-day] [_driver _ expr] (h2x/->integer (strftime "%H" expr))) (defmethod sql.qp/date [:sqlite :day] [_driver _ expr] (->date expr)) SQLite day of week ( % w ) is Sunday = 0 < - > Saturday = 6 . We want 1 - 7 so add 1 (defmethod sql.qp/date [:sqlite :day-of-week] [_driver _ expr] (sql.qp/adjust-day-of-week :sqlite (h2x/->integer (h2x/inc (strftime "%w" expr))))) (defmethod sql.qp/date [:sqlite :day-of-month] [_driver _ expr] (h2x/->integer (strftime "%d" expr))) (defmethod sql.qp/date [:sqlite :day-of-year] [_driver _ expr] (h2x/->integer (strftime "%j" expr))) (defmethod sql.qp/date [:sqlite :week] [_ _ expr] (let [week-extract-fn (fn [expr] Move back 6 days , then forward to the next Sunday (->date expr (h2x/literal "-6 days") (h2x/literal "weekday 0")))] (sql.qp/adjust-start-of-week :sqlite week-extract-fn expr))) (defmethod sql.qp/date [:sqlite :week-of-year-iso] [driver _ expr] Maybe we can follow the algorithm here #Algorithms (throw (ex-info (tru "Sqlite doesn't support extract isoweek") {:driver driver :form expr :type qp.error-type/invalid-query}))) (defmethod sql.qp/date [:sqlite :month] [_driver _ expr] (->date expr (h2x/literal "start of month"))) (defmethod sql.qp/date [:sqlite :month-of-year] [_driver _ expr] (h2x/->integer (strftime "%m" expr))) DATE(DATE(%s , ' start of month ' ) , ' - ' || ( ( STRFTIME('%m ' , % s ) - 1 ) % 3 ) || ' months ' ) - > DATE(DATE('2015 - 11 - 16 ' , ' start of month ' ) , ' - ' || ( ( STRFTIME('%m ' , ' 2015 - 11 - 16 ' ) - 1 ) % 3 ) || ' months ' ) - > DATE('2015 - 11 - 01 ' , ' - ' || ( ( 11 - 1 ) % 3 ) || ' months ' ) - > DATE('2015 - 11 - 01 ' , ' - ' || 1 || ' months ' ) ;; -> DATE('2015-11-01', '-1 months') - > ' 2015 - 10 - 01 ' (defmethod sql.qp/date [:sqlite :quarter] [_driver _ expr] (->date (->date expr (h2x/literal "start of month")) [:|| (h2x/literal "-") (h2x/mod (h2x/dec (strftime "%m" expr)) 3) (h2x/literal " months")])) q = ( m + 2 ) / 3 (defmethod sql.qp/date [:sqlite :quarter-of-year] [_driver _ expr] (h2x// (h2x/+ (strftime "%m" expr) 2) 3)) (defmethod sql.qp/date [:sqlite :year] [_driver _ expr] (->date expr (h2x/literal "start of year"))) (defmethod sql.qp/date [:sqlite :year-of-era] [_driver _ expr] (h2x/->integer (strftime "%Y" expr))) (defmethod sql.qp/add-interval-honeysql-form :sqlite [_driver hsql-form amount unit] (let [[multiplier sqlite-unit] (case unit :second [1 "seconds"] :minute [1 "minutes"] :hour [1 "hours"] :day [1 "days"] :week [7 "days"] :month [1 "months"] :quarter [3 "months"] :year [1 "years"])] (->datetime hsql-form (h2x/literal (format "%+d %s" (* amount multiplier) sqlite-unit))))) (defmethod sql.qp/unix-timestamp->honeysql [:sqlite :seconds] [_ _ expr] (->datetime expr (h2x/literal "unixepoch"))) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->DateTime] [_driver _semantic_type expr] (->datetime expr)) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->Date] [_driver _semantic_type expr] (->date expr)) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->Time] [_driver _semantic_type expr] (->time expr)) SQLite does n't like Temporal values getting passed in as prepared statement args , so we need to convert them to ;; date literal strings instead to get things to work ;; ;; TODO - not sure why this doesn't need to be done in `->honeysql` as well? I think it's because the MBQL date values ;; are funneled through the `date` family of functions above ;; ;; TIMESTAMP FIXME — this doesn't seem like the correct thing to do for non-Dates. I think params only support dates ;; rn however (s/defmethod driver.sql/->prepared-substitution [:sqlite Temporal] :- driver.sql/PreparedStatementSubstitution [_driver date] ;; for anything that's a Temporal value convert it to a yyyy-MM-dd formatted date literal string For whatever reason the SQL generated from parameters ends up looking like ` WHERE ) = ? ` sometimes so we need to use just the date rather than a full ISO-8601 string (sql.params.substitution/make-stmt-subs "?" [(t/format "yyyy-MM-dd" date)])) SQLite does n't support ` TRUE`/`FALSE ` ; it uses ` 1`/`0 ` , respectively ; convert these booleans to numbers . (defmethod sql.qp/->honeysql [:sqlite Boolean] [_ bool] (if bool 1 0)) (defmethod sql.qp/->honeysql [:sqlite :substring] [driver [_ arg start length]] (if length [:substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver start) (sql.qp/->honeysql driver length)] [:substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver start)])) (defmethod sql.qp/->honeysql [:sqlite :concat] [driver [_ & args]] (into [:||] (mapv (partial sql.qp/->honeysql driver) args))) (defmethod sql.qp/->honeysql [:sqlite :floor] [_driver [_ arg]] [:round (h2x/- arg 0.5)]) (defmethod sql.qp/->honeysql [:sqlite :ceil] [_driver [_ arg]] [:case ;; if we're ceiling a whole number, just cast it to an integer [: ceil 1.0 ] should returns 1 [:= [:round arg] arg] (h2x/->integer arg) :else [:round (h2x/+ arg 0.5)]]) ;; See ;; MEGA HACK ;; if the time portion is zeroed out generate a date ( ) instead , because SQLite is n't smart enough to compare DATEs ;; and DATETIMEs in a way that could be considered to make any sense whatsoever, e.g. ;; date('2019 - 12 - 03 ' ) < datetime('2019 - 12 - 03 00:00 ' ) (defn- zero-time? [t] (= (t/local-time t) (t/local-time 0))) (defmethod sql.qp/->honeysql [:sqlite LocalDate] [_ t] [:date (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite LocalDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) (defmethod sql.qp/->honeysql [:sqlite LocalTime] [_ t] [:time (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite OffsetDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) (defmethod sql.qp/->honeysql [:sqlite OffsetTime] [_ t] [:time (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite ZonedDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) SQLite defaults everything to UTC (defmethod driver.common/current-db-time-date-formatters :sqlite [_] (driver.common/create-db-time-formatters "yyyy-MM-dd HH:mm:ss")) (defmethod driver.common/current-db-time-native-query :sqlite [_] "select cast(datetime('now') as text);") (defmethod driver/current-db-time :sqlite [& args] (apply driver.common/current-db-time args)) (defmethod sql-jdbc.sync/active-tables :sqlite [& args] (apply sql-jdbc.sync/post-filtered-active-tables args)) (defmethod sql.qp/current-datetime-honeysql-form :sqlite [_] [:datetime (h2x/literal :now)]) (defmethod sql.qp/datetime-diff [:sqlite :year] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :month x y) 12)) (defmethod sql.qp/datetime-diff [:sqlite :quarter] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :month x y) 3)) (defmethod sql.qp/datetime-diff [:sqlite :month] [driver _unit x y] (let [extract (fn [unit x] (sql.qp/date driver unit x)) year-diff (h2x/- (extract :year y) (extract :year x)) month-of-year-diff (h2x/- (extract :month-of-year y) (extract :month-of-year x)) total-month-diff (h2x/+ month-of-year-diff (h2x/* year-diff 12))] (h2x/+ total-month-diff total - month - diff counts month boundaries not whole months , so we need to adjust if x < y but x > y in the month calendar then subtract one month if x > y but x < y in the month calendar then add one month [:case [:and [:< x y] [:> (extract :day-of-month x) (extract :day-of-month y)]] -1 [:and [:> x y] [:< (extract :day-of-month x) (extract :day-of-month y)]] 1 :else 0]))) (defmethod sql.qp/datetime-diff [:sqlite :week] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :day x y) 7)) (defmethod sql.qp/datetime-diff [:sqlite :day] [_driver _unit x y] (h2x/->integer (h2x/- [:julianday y (h2x/literal "start of day")] [:julianday x (h2x/literal "start of day")]))) (defmethod sql.qp/datetime-diff [:sqlite :hour] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :second x y) 3600)) (defmethod sql.qp/datetime-diff [:sqlite :minute] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :second x y) 60)) (defmethod sql.qp/datetime-diff [:sqlite :second] [_driver _unit x y] ;; strftime strftime('%s', <timestring>) returns the unix time as an integer. (h2x/- (strftime "%s" y) (strftime "%s" x))) SQLite 's JDBC driver is fussy and wo n't let you change connections to read - only after you create them . So skip that step . SQLite does n't have a notion of session timezones so do n't do that either . The only thing we 're doing here from ;; the default impl is setting the transaction isolation level (defmethod sql-jdbc.execute/connection-with-timezone :sqlite [driver database _timezone-id] (let [conn (.getConnection (sql-jdbc.execute/datasource-with-diagnostic-info! driver database))] (try (sql-jdbc.execute/set-best-transaction-level! driver conn) conn (catch Throwable e (.close conn) (throw e))))) SQLite 's JDBC driver is dumb and complains if you try to call ` .setFetchDirection ` on the Connection (defmethod sql-jdbc.execute/prepared-statement :sqlite [driver ^Connection conn ^String sql params] (let [stmt (.prepareStatement conn sql ResultSet/TYPE_FORWARD_ONLY ResultSet/CONCUR_READ_ONLY ResultSet/CLOSE_CURSORS_AT_COMMIT)] (try (sql-jdbc.execute/set-parameters! driver stmt params) stmt (catch Throwable e (.close stmt) (throw e))))) SQLite has no intrinsic date / time type . The sqlite - jdbc driver provides the following de - facto mappings : ;; DATE or DATETIME => Types/DATE (only if type is int or string) ;; TIMESTAMP => Types/TIMESTAMP (only if type is int) ;; The data itself can be stored either as 1 ) integer ( unix epoch ) - this is " point in time " , so no confusion about timezone 2 ) float ( julian days ) - this is " point in time " , so no confusion about timezone 3 ) string ( ISO8601 ) - zoned or unzoned depending on content , sqlite - jdbc always treat it as local time Note that it is possible to store other invalid data in the column as SQLite does not perform any validation . (defn- sqlite-handle-timestamp [^ResultSet rs ^Integer i] (let [obj (.getObject rs i)] (cond ;; For strings, use our own parser which is more flexible than sqlite-jdbc's and handles timezones correctly (instance? String obj) (u.date/parse obj) ;; For other types, fallback to sqlite-jdbc's parser ;; Even in DATE column, it is possible to put DATETIME, so always treat as DATETIME (some? obj) (t/local-date-time (.getTimestamp rs i))))) (defmethod sql-jdbc.execute/read-column-thunk [:sqlite Types/DATE] [_ ^ResultSet rs _ ^Integer i] (fn [] (sqlite-handle-timestamp rs i))) (defmethod sql-jdbc.execute/read-column-thunk [:sqlite Types/TIMESTAMP] [_ ^ResultSet rs _ ^Integer i] (fn [] (sqlite-handle-timestamp rs i)))
null
https://raw.githubusercontent.com/metabase/metabase/80ba6b1a33e336e132d1714c0d9b3e5a6c626054/modules/drivers/sqlite/src/metabase/driver/sqlite.clj
clojure
we have this 'feature' so the frontend doesn't try to present the option to you. for now we'll just skip the foreign key stuff in the tests. e.g. NVARCHAR(100) or NUMERIC(10,5) See also See also the [SQLite Date and Time Functions Reference](). -> DATE('2015-11-01', '-1 months') date literal strings instead to get things to work TODO - not sure why this doesn't need to be done in `->honeysql` as well? I think it's because the MBQL date values are funneled through the `date` family of functions above TIMESTAMP FIXME — this doesn't seem like the correct thing to do for non-Dates. I think params only support dates rn however for anything that's a Temporal value convert it to a yyyy-MM-dd formatted date literal it uses ` 1`/`0 ` , respectively ; convert these booleans to numbers . if we're ceiling a whole number, just cast it to an integer See MEGA HACK and DATETIMEs in a way that could be considered to make any sense whatsoever, e.g. strftime strftime('%s', <timestring>) returns the unix time as an integer. the default impl is setting the transaction isolation level DATE or DATETIME => Types/DATE (only if type is int or string) TIMESTAMP => Types/TIMESTAMP (only if type is int) The data itself can be stored either as For strings, use our own parser which is more flexible than sqlite-jdbc's and handles timezones correctly For other types, fallback to sqlite-jdbc's parser Even in DATE column, it is possible to put DATETIME, so always treat as DATETIME
(ns metabase.driver.sqlite (:require [clojure.java.io :as io] [clojure.string :as str] [java-time :as t] [metabase.config :as config] [metabase.driver :as driver] [metabase.driver.common :as driver.common] [metabase.driver.sql :as driver.sql] [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn] [metabase.driver.sql-jdbc.execute :as sql-jdbc.execute] [metabase.driver.sql-jdbc.sync :as sql-jdbc.sync] [metabase.driver.sql.parameters.substitution :as sql.params.substitution] [metabase.driver.sql.query-processor :as sql.qp] [metabase.query-processor.error-type :as qp.error-type] [metabase.util.date-2 :as u.date] [metabase.util.honey-sql-2 :as h2x] [metabase.util.i18n :refer [tru]] [schema.core :as s]) (:import (java.sql Connection ResultSet Types) (java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime) (java.time.temporal Temporal))) (set! *warn-on-reflection* true) (driver/register! :sqlite, :parent :sql-jdbc) (defmethod sql.qp/honey-sql-version :sqlite [_driver] 2) SQLite does not support a lot of features , so do not show the options in the interface (doseq [[feature supported?] {:right-join false :full-join false :regex false :percentile-aggregations false :advanced-math-expressions false :standard-deviation-aggregations false :datetime-diff true :now true}] (defmethod driver/supports? [:sqlite feature] [_ _] supported?)) SQLite ` LIKE ` clauses are case - insensitive by default , and thus can not be made case - sensitive . So let people know (defmethod driver/supports? [:sqlite :case-sensitivity-string-filter-options] [_ _] false) HACK SQLite does n't support ALTER TABLE ADD CONSTRAINT FOREIGN KEY and I do n't have all day to work around this so (defmethod driver/supports? [:sqlite :foreign-keys] [_ _] (not config/is-test?)) Every SQLite3 file starts with " SQLite Format 3 " or " * * This file contains an SQLite There is also but last 2 version was 2005 (defn- confirm-file-is-sqlite [filename] (with-open [reader (io/input-stream filename)] (let [outarr (byte-array 50)] (.read reader outarr) (let [line (String. outarr)] (or (str/includes? line "SQLite format 3") (str/includes? line "This file contains an SQLite")))))) (defmethod driver/can-connect? :sqlite [driver details] (if (confirm-file-is-sqlite (:db details)) (sql-jdbc.conn/can-connect? driver details) false)) (defmethod driver/db-start-of-week :sqlite [_] :sunday) (defmethod sql-jdbc.conn/connection-details->spec :sqlite [_ {:keys [db] :or {db "sqlite.db"} :as details}] (merge {:subprotocol "sqlite" :subname db} (dissoc details :db) disallow " FDW " ( connecting to other SQLite databases on the local filesystem ) -- see {:limit_attached 0})) We 'll do regex pattern matching here for determining Field types because SQLite types can have optional lengths , (def ^:private database-type->base-type (sql-jdbc.sync/pattern-based-database-type->base-type [[#"BIGINT" :type/BigInteger] [#"BIG INT" :type/BigInteger] [#"INT" :type/Integer] [#"CHAR" :type/Text] [#"TEXT" :type/Text] [#"CLOB" :type/Text] [#"BLOB" :type/*] [#"REAL" :type/Float] [#"DOUB" :type/Float] [#"FLOA" :type/Float] [#"NUMERIC" :type/Float] [#"DECIMAL" :type/Decimal] [#"BOOLEAN" :type/Boolean] [#"TIMESTAMP" :type/DateTime] [#"DATETIME" :type/DateTime] [#"DATE" :type/Date] [#"TIME" :type/Time]])) (defmethod sql-jdbc.sync/database-type->base-type :sqlite [_ database-type] (database-type->base-type database-type)) The normal SELECT * FROM table WHERE 1 < > 1 LIMIT 0 query does n't return any information for SQLite views -- it seems to be the case that the query has to return at least one row (defmethod sql-jdbc.sync/fallback-metadata-query :sqlite [driver schema table] (sql.qp/format-honeysql driver {:select [:*] :from [[(h2x/identifier :table schema table)]] :limit 1})) (def ^:private ->date (partial conj [:date])) (def ^:private ->datetime (partial conj [:datetime])) (def ^:private ->time (partial conj [:time])) (defn- strftime [format-str expr] [:strftime (h2x/literal format-str) expr]) (defmethod sql.qp/date [:sqlite :default] [_driver _unit expr] expr) (defmethod sql.qp/date [:sqlite :second] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:%M:%S" expr))) (defmethod sql.qp/date [:sqlite :second-of-minute] [_driver _ expr] (h2x/->integer (strftime "%S" expr))) (defmethod sql.qp/date [:sqlite :minute] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:%M" expr))) (defmethod sql.qp/date [:sqlite :minute-of-hour] [_driver _ expr] (h2x/->integer (strftime "%M" expr))) (defmethod sql.qp/date [:sqlite :hour] [_driver _ expr] (->datetime (strftime "%Y-%m-%d %H:00" expr))) (defmethod sql.qp/date [:sqlite :hour-of-day] [_driver _ expr] (h2x/->integer (strftime "%H" expr))) (defmethod sql.qp/date [:sqlite :day] [_driver _ expr] (->date expr)) SQLite day of week ( % w ) is Sunday = 0 < - > Saturday = 6 . We want 1 - 7 so add 1 (defmethod sql.qp/date [:sqlite :day-of-week] [_driver _ expr] (sql.qp/adjust-day-of-week :sqlite (h2x/->integer (h2x/inc (strftime "%w" expr))))) (defmethod sql.qp/date [:sqlite :day-of-month] [_driver _ expr] (h2x/->integer (strftime "%d" expr))) (defmethod sql.qp/date [:sqlite :day-of-year] [_driver _ expr] (h2x/->integer (strftime "%j" expr))) (defmethod sql.qp/date [:sqlite :week] [_ _ expr] (let [week-extract-fn (fn [expr] Move back 6 days , then forward to the next Sunday (->date expr (h2x/literal "-6 days") (h2x/literal "weekday 0")))] (sql.qp/adjust-start-of-week :sqlite week-extract-fn expr))) (defmethod sql.qp/date [:sqlite :week-of-year-iso] [driver _ expr] Maybe we can follow the algorithm here #Algorithms (throw (ex-info (tru "Sqlite doesn't support extract isoweek") {:driver driver :form expr :type qp.error-type/invalid-query}))) (defmethod sql.qp/date [:sqlite :month] [_driver _ expr] (->date expr (h2x/literal "start of month"))) (defmethod sql.qp/date [:sqlite :month-of-year] [_driver _ expr] (h2x/->integer (strftime "%m" expr))) DATE(DATE(%s , ' start of month ' ) , ' - ' || ( ( STRFTIME('%m ' , % s ) - 1 ) % 3 ) || ' months ' ) - > DATE(DATE('2015 - 11 - 16 ' , ' start of month ' ) , ' - ' || ( ( STRFTIME('%m ' , ' 2015 - 11 - 16 ' ) - 1 ) % 3 ) || ' months ' ) - > DATE('2015 - 11 - 01 ' , ' - ' || ( ( 11 - 1 ) % 3 ) || ' months ' ) - > DATE('2015 - 11 - 01 ' , ' - ' || 1 || ' months ' ) - > ' 2015 - 10 - 01 ' (defmethod sql.qp/date [:sqlite :quarter] [_driver _ expr] (->date (->date expr (h2x/literal "start of month")) [:|| (h2x/literal "-") (h2x/mod (h2x/dec (strftime "%m" expr)) 3) (h2x/literal " months")])) q = ( m + 2 ) / 3 (defmethod sql.qp/date [:sqlite :quarter-of-year] [_driver _ expr] (h2x// (h2x/+ (strftime "%m" expr) 2) 3)) (defmethod sql.qp/date [:sqlite :year] [_driver _ expr] (->date expr (h2x/literal "start of year"))) (defmethod sql.qp/date [:sqlite :year-of-era] [_driver _ expr] (h2x/->integer (strftime "%Y" expr))) (defmethod sql.qp/add-interval-honeysql-form :sqlite [_driver hsql-form amount unit] (let [[multiplier sqlite-unit] (case unit :second [1 "seconds"] :minute [1 "minutes"] :hour [1 "hours"] :day [1 "days"] :week [7 "days"] :month [1 "months"] :quarter [3 "months"] :year [1 "years"])] (->datetime hsql-form (h2x/literal (format "%+d %s" (* amount multiplier) sqlite-unit))))) (defmethod sql.qp/unix-timestamp->honeysql [:sqlite :seconds] [_ _ expr] (->datetime expr (h2x/literal "unixepoch"))) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->DateTime] [_driver _semantic_type expr] (->datetime expr)) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->Date] [_driver _semantic_type expr] (->date expr)) (defmethod sql.qp/cast-temporal-string [:sqlite :Coercion/ISO8601->Time] [_driver _semantic_type expr] (->time expr)) SQLite does n't like Temporal values getting passed in as prepared statement args , so we need to convert them to (s/defmethod driver.sql/->prepared-substitution [:sqlite Temporal] :- driver.sql/PreparedStatementSubstitution [_driver date] string For whatever reason the SQL generated from parameters ends up looking like ` WHERE ) = ? ` sometimes so we need to use just the date rather than a full ISO-8601 string (sql.params.substitution/make-stmt-subs "?" [(t/format "yyyy-MM-dd" date)])) (defmethod sql.qp/->honeysql [:sqlite Boolean] [_ bool] (if bool 1 0)) (defmethod sql.qp/->honeysql [:sqlite :substring] [driver [_ arg start length]] (if length [:substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver start) (sql.qp/->honeysql driver length)] [:substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver start)])) (defmethod sql.qp/->honeysql [:sqlite :concat] [driver [_ & args]] (into [:||] (mapv (partial sql.qp/->honeysql driver) args))) (defmethod sql.qp/->honeysql [:sqlite :floor] [_driver [_ arg]] [:round (h2x/- arg 0.5)]) (defmethod sql.qp/->honeysql [:sqlite :ceil] [_driver [_ arg]] [:case [: ceil 1.0 ] should returns 1 [:= [:round arg] arg] (h2x/->integer arg) :else [:round (h2x/+ arg 0.5)]]) if the time portion is zeroed out generate a date ( ) instead , because SQLite is n't smart enough to compare DATEs date('2019 - 12 - 03 ' ) < datetime('2019 - 12 - 03 00:00 ' ) (defn- zero-time? [t] (= (t/local-time t) (t/local-time 0))) (defmethod sql.qp/->honeysql [:sqlite LocalDate] [_ t] [:date (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite LocalDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) (defmethod sql.qp/->honeysql [:sqlite LocalTime] [_ t] [:time (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite OffsetDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) (defmethod sql.qp/->honeysql [:sqlite OffsetTime] [_ t] [:time (h2x/literal (u.date/format-sql t))]) (defmethod sql.qp/->honeysql [:sqlite ZonedDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) [:datetime (h2x/literal (u.date/format-sql t))])) SQLite defaults everything to UTC (defmethod driver.common/current-db-time-date-formatters :sqlite [_] (driver.common/create-db-time-formatters "yyyy-MM-dd HH:mm:ss")) (defmethod driver.common/current-db-time-native-query :sqlite [_] "select cast(datetime('now') as text);") (defmethod driver/current-db-time :sqlite [& args] (apply driver.common/current-db-time args)) (defmethod sql-jdbc.sync/active-tables :sqlite [& args] (apply sql-jdbc.sync/post-filtered-active-tables args)) (defmethod sql.qp/current-datetime-honeysql-form :sqlite [_] [:datetime (h2x/literal :now)]) (defmethod sql.qp/datetime-diff [:sqlite :year] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :month x y) 12)) (defmethod sql.qp/datetime-diff [:sqlite :quarter] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :month x y) 3)) (defmethod sql.qp/datetime-diff [:sqlite :month] [driver _unit x y] (let [extract (fn [unit x] (sql.qp/date driver unit x)) year-diff (h2x/- (extract :year y) (extract :year x)) month-of-year-diff (h2x/- (extract :month-of-year y) (extract :month-of-year x)) total-month-diff (h2x/+ month-of-year-diff (h2x/* year-diff 12))] (h2x/+ total-month-diff total - month - diff counts month boundaries not whole months , so we need to adjust if x < y but x > y in the month calendar then subtract one month if x > y but x < y in the month calendar then add one month [:case [:and [:< x y] [:> (extract :day-of-month x) (extract :day-of-month y)]] -1 [:and [:> x y] [:< (extract :day-of-month x) (extract :day-of-month y)]] 1 :else 0]))) (defmethod sql.qp/datetime-diff [:sqlite :week] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :day x y) 7)) (defmethod sql.qp/datetime-diff [:sqlite :day] [_driver _unit x y] (h2x/->integer (h2x/- [:julianday y (h2x/literal "start of day")] [:julianday x (h2x/literal "start of day")]))) (defmethod sql.qp/datetime-diff [:sqlite :hour] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :second x y) 3600)) (defmethod sql.qp/datetime-diff [:sqlite :minute] [driver _unit x y] (h2x// (sql.qp/datetime-diff driver :second x y) 60)) (defmethod sql.qp/datetime-diff [:sqlite :second] [_driver _unit x y] (h2x/- (strftime "%s" y) (strftime "%s" x))) SQLite 's JDBC driver is fussy and wo n't let you change connections to read - only after you create them . So skip that step . SQLite does n't have a notion of session timezones so do n't do that either . The only thing we 're doing here from (defmethod sql-jdbc.execute/connection-with-timezone :sqlite [driver database _timezone-id] (let [conn (.getConnection (sql-jdbc.execute/datasource-with-diagnostic-info! driver database))] (try (sql-jdbc.execute/set-best-transaction-level! driver conn) conn (catch Throwable e (.close conn) (throw e))))) SQLite 's JDBC driver is dumb and complains if you try to call ` .setFetchDirection ` on the Connection (defmethod sql-jdbc.execute/prepared-statement :sqlite [driver ^Connection conn ^String sql params] (let [stmt (.prepareStatement conn sql ResultSet/TYPE_FORWARD_ONLY ResultSet/CONCUR_READ_ONLY ResultSet/CLOSE_CURSORS_AT_COMMIT)] (try (sql-jdbc.execute/set-parameters! driver stmt params) stmt (catch Throwable e (.close stmt) (throw e))))) SQLite has no intrinsic date / time type . The sqlite - jdbc driver provides the following de - facto mappings : 1 ) integer ( unix epoch ) - this is " point in time " , so no confusion about timezone 2 ) float ( julian days ) - this is " point in time " , so no confusion about timezone 3 ) string ( ISO8601 ) - zoned or unzoned depending on content , sqlite - jdbc always treat it as local time Note that it is possible to store other invalid data in the column as SQLite does not perform any validation . (defn- sqlite-handle-timestamp [^ResultSet rs ^Integer i] (let [obj (.getObject rs i)] (cond (instance? String obj) (u.date/parse obj) (some? obj) (t/local-date-time (.getTimestamp rs i))))) (defmethod sql-jdbc.execute/read-column-thunk [:sqlite Types/DATE] [_ ^ResultSet rs _ ^Integer i] (fn [] (sqlite-handle-timestamp rs i))) (defmethod sql-jdbc.execute/read-column-thunk [:sqlite Types/TIMESTAMP] [_ ^ResultSet rs _ ^Integer i] (fn [] (sqlite-handle-timestamp rs i)))
64c0836ca4fa6cf2e0741f56c5f928855aa539efaa0debfcd8a8b48da7b34e58
TrustInSoft/tis-interpreter
domain_lift.mli
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It 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 Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) module type Conversion = sig type extended_value type extended_location type internal_value type internal_location val extend_val : internal_value -> extended_value val restrict_val : extended_value -> internal_value val restrict_loc : extended_location -> internal_location end module Make (Domain: Abstract_domain.Internal) (Convert : Conversion with type internal_value := Domain.value and type internal_location := Domain.location) : Abstract_domain.Internal with type state = Domain.state and type value = Convert.extended_value and type location = Convert.extended_location and type origin = Domain.origin (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/domains/domain_lift.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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 Lesser General Public License for more details. ************************************************************************ Local Variables: compile-command: "make -C ../../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . module type Conversion = sig type extended_value type extended_location type internal_value type internal_location val extend_val : internal_value -> extended_value val restrict_val : extended_value -> internal_value val restrict_loc : extended_location -> internal_location end module Make (Domain: Abstract_domain.Internal) (Convert : Conversion with type internal_value := Domain.value and type internal_location := Domain.location) : Abstract_domain.Internal with type state = Domain.state and type value = Convert.extended_value and type location = Convert.extended_location and type origin = Domain.origin
2a351ff87566701343940f0e9b78eb1fda43a37ae345025a44e7821fb38a1f14
jjtolton/TheDevilsInterop
core.clj
(ns metal-interop.core (:gen-class) (:require [clojure.data.json :as json] [org.httpkit.client :as client] [tech.v3.datatype.ffi :as dt-ffi] [clojure.tools.logging :as log] [metal-interop.util :as utils] [camel-snake-kebab.core :as csk] reserved for future \m/ -- zero - copy data ;; libpython-clj2.python.np-array ;; [libpython-clj2.python :as python] )) (defonce return-buffer (atom nil)) (defn clear-return-buffer! [] (reset! return-buffer nil)) (defonce dispatch-registry! (atom {})) (defn register-dispatch! [k f] (swap! dispatch-registry! assoc k f)) (defn dispatch! [{name :name data :data}] (if-let [f (or (get @dispatch-registry! (symbol name)) (get @dispatch-registry! (str name)))] (apply f data) (do (log/infof "No matching function found for: %s " name) ;; use this for debug but don't include in production ;; (println "Available names:") ( doseq [ name ( map first ( seq @dispatch - registry ! ) ) ] ;; (println name)) ))) (defn return-wrapper [ptr] (let [out-str (java.io.StringWriter.) err-str (java.io.StringWriter.) out (atom nil) err (atom nil) res (atom nil)] (binding [*out* out-str] (try (reset! res (->> ptr dt-ffi/c->string ;; change this to something less aggressive if you want to be able to ;; use get/assoc directly (#(json/read-str % :key-fn csk/->kebab-case-keyword)) dispatch!)) (catch Exception e (let [message (utils/clj->json {:stdout (str out-str) :stderr (str err-str) :error (str e) :stacktrace (try (with-out-str (.printStackTrace e)) (catch Exception e1 nil))})] (throw (Exception. message)))) (finally (when-let [out-str (not-empty (str out-str))] (reset! out out-str)) (when-let [err-str (not-empty (str err-str))] (swap! err str err-str))))) (->> {:stdout @out :stderr @err :res @res} json/write-str dt-ffi/string->c (reset! return-buffer))))
null
https://raw.githubusercontent.com/jjtolton/TheDevilsInterop/e686300a52ba1d6a895086b0efdd8f503dbc6f0d/src/metal_interop/core.clj
clojure
libpython-clj2.python.np-array [libpython-clj2.python :as python] use this for debug but don't include in production (println "Available names:") (println name)) change this to something less aggressive if you want to be able to use get/assoc directly
(ns metal-interop.core (:gen-class) (:require [clojure.data.json :as json] [org.httpkit.client :as client] [tech.v3.datatype.ffi :as dt-ffi] [clojure.tools.logging :as log] [metal-interop.util :as utils] [camel-snake-kebab.core :as csk] reserved for future \m/ -- zero - copy data )) (defonce return-buffer (atom nil)) (defn clear-return-buffer! [] (reset! return-buffer nil)) (defonce dispatch-registry! (atom {})) (defn register-dispatch! [k f] (swap! dispatch-registry! assoc k f)) (defn dispatch! [{name :name data :data}] (if-let [f (or (get @dispatch-registry! (symbol name)) (get @dispatch-registry! (str name)))] (apply f data) (do (log/infof "No matching function found for: %s " name) ( doseq [ name ( map first ( seq @dispatch - registry ! ) ) ] ))) (defn return-wrapper [ptr] (let [out-str (java.io.StringWriter.) err-str (java.io.StringWriter.) out (atom nil) err (atom nil) res (atom nil)] (binding [*out* out-str] (try (reset! res (->> ptr dt-ffi/c->string (#(json/read-str % :key-fn csk/->kebab-case-keyword)) dispatch!)) (catch Exception e (let [message (utils/clj->json {:stdout (str out-str) :stderr (str err-str) :error (str e) :stacktrace (try (with-out-str (.printStackTrace e)) (catch Exception e1 nil))})] (throw (Exception. message)))) (finally (when-let [out-str (not-empty (str out-str))] (reset! out out-str)) (when-let [err-str (not-empty (str err-str))] (swap! err str err-str))))) (->> {:stdout @out :stderr @err :res @res} json/write-str dt-ffi/string->c (reset! return-buffer))))
799a563af930a919baee739d93a6b6078e6b48b72ab29746eebb615971351e46
SKA-ScienceDataProcessor/RC
DNA.hs
{-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module DNA ( -- * Definition of actors ActorDef , actor , simpleOut , rule , scatterGather , producer , startingState -- * Definition of dataflow graph , Dataflow , A , buildDataflow , use , connect -- * Compilation , compile ) where import Control.Applicative import Control.Monad.Trans.State.Strict import Data.Typeable import Data.Graph.Inductive.Graph hiding (match) import qualified Data.Traversable as T import qualified Data.Map as Map import DNA.AST import DNA.Actor import DNA.Compiler.Types import DNA.Compiler.Basic import DNA.Compiler.Scheduler ---------------------------------------------------------------- Monad for defining actors ---------------------------------------------------------------- -- | Monad for defining actor newtype ActorDef s a = ActorDef (State (ActorDefState s) a) deriving (Functor,Applicative,Monad) data ActorDefState s = ActorDefState { adsRules :: [Rule s] -- Transition rules , adsInit :: [Expr () s] -- Initial state , adsProd :: [Expr () (s -> (s,Out))] -- , adsSG :: [SG] -- , adsConns :: ConnMap -- Outbound connections } -- | Simple connection information simpleOut :: forall s a. Typeable a => ConnType -> ActorDef s (Conn a) simpleOut ct = ActorDef $ do st <- get let conns = adsConns st cid = ConnId $ Map.size conns put $! st { adsConns = Map.insert cid (ActorConn ct (typeOf (undefined :: a))) conns } return $ Conn cid ConnOne -- | Transition rule for an actor rule :: Expr () (s -> a -> (s,Out)) -> ActorDef s () rule f = ActorDef $ do modify $ \st -> st { adsRules = Rule f : adsRules st } | Producer actor . One which sends data indefinitely producer :: Expr () (s -> (s,Out)) -> ActorDef s () producer f = ActorDef $ do modify $ \st -> st { adsProd = f : adsProd st } -- | Scatter-gather actor scatterGather :: SG -> ActorDef s () scatterGather sg = ActorDef $ do modify $ \st -> st { adsSG = sg : adsSG st } -- | Set initial state for the actor startingState :: Expr () s -> ActorDef s () startingState s = ActorDef $ do modify $ \st -> st { adsInit = s : adsInit st } -- | Generate actor representation actor :: ActorDef s outs -> Actor outs actor (ActorDef m) = case s of ActorDefState [] [] [] [sg] c -> Actor outs (RealActor c (ScatterGather sg)) ActorDefState _ [] _ _ _ -> oops "No initial state specified" ActorDefState [] _ [] _ _ -> oops "No transition rules/producers" ActorDefState rs [i] [] _ c -> Actor outs (RealActor c (StateM i rs)) ActorDefState [] [i] [f] _ c -> Actor outs (RealActor c (Producer i f)) ActorDefState [] _ _ _ _ -> oops "Several producer steps specified" ActorDefState _ _ _ _ _ -> oops "Several initial states specified" where (outs,s) = runState m $ ActorDefState [] [] [] [] Map.empty oops = Invalid . pure ---------------------------------------------------------------- Dataflow graph definition ---------------------------------------------------------------- -- | Monad for building dataflow graph type Dataflow = (State (Int, [(Node,BuildNode)], [(Node,Node,ConnId)])) -- | Node of a dataflow graph which is used during graph construction data BuildNode where BuildNode :: Actor outs -> BuildNode -- | Handle for actor. newtype A = A Node -- | Construct dataflow graph from its description buildDataflow :: Dataflow () -> Compile DataflowGraph buildDataflow m = applicatively $ (\n -> mkGraph n es) <$> T.traverse validate ns where validate (_,BuildNode (Invalid errs)) = leftA errs validate (i,BuildNode (Actor _ a)) = pure (i,ANode NotSched a) (_,ns,es) = execState m (0,[],[]) -- | Bind actor as node in the dataflow graph. It returns handle to -- the node and collection of its outputs. use :: forall outs. ConnCollection outs => Actor outs -> Dataflow (A, Connected outs) use a = do (i,acts,conns) <- get put (i+1, (i,BuildNode a) : acts, conns) return (A i, case a of Invalid _ -> nullConnection (undefined :: outs) Actor o _ -> setActorId i o ) -- | Connect graphs connect :: Connection a -> A -> Dataflow () connect Failed _ = return () connect (Bound from (Conn i _)) (A to) = do (j, acts, conns) <- get put ( j , acts , (from,to, i) : conns ) ---------------------------------------------------------------- -- Compilation helpers ---------------------------------------------------------------- -- | Compile program and write generated program compile :: (DataflowGraph -> Compile a) -- ^ Code generator -> (a -> IO ()) -- ^ Action to write code -> CAD -- ^ Cluster description -> Dataflow () -- ^ Graph -> IO () compile codegen write cad gr = do let r = runCompile $ codegen =<< checkSchedule =<< schedule cad =<< checkGraph =<< buildDataflow gr case r of Left errs -> mapM_ putStrLn errs Right a -> write a
null
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS1/dna/DNA.hs
haskell
# LANGUAGE GADTs # * Definition of actors * Definition of dataflow graph * Compilation -------------------------------------------------------------- -------------------------------------------------------------- | Monad for defining actor Transition rules Initial state Outbound connections | Simple connection information | Transition rule for an actor | Scatter-gather actor | Set initial state for the actor | Generate actor representation -------------------------------------------------------------- -------------------------------------------------------------- | Monad for building dataflow graph | Node of a dataflow graph which is used during graph construction | Handle for actor. | Construct dataflow graph from its description | Bind actor as node in the dataflow graph. It returns handle to the node and collection of its outputs. | Connect graphs -------------------------------------------------------------- Compilation helpers -------------------------------------------------------------- | Compile program and write generated program ^ Code generator ^ Action to write code ^ Cluster description ^ Graph
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module DNA ( ActorDef , actor , simpleOut , rule , scatterGather , producer , startingState , Dataflow , A , buildDataflow , use , connect , compile ) where import Control.Applicative import Control.Monad.Trans.State.Strict import Data.Typeable import Data.Graph.Inductive.Graph hiding (match) import qualified Data.Traversable as T import qualified Data.Map as Map import DNA.AST import DNA.Actor import DNA.Compiler.Types import DNA.Compiler.Basic import DNA.Compiler.Scheduler Monad for defining actors newtype ActorDef s a = ActorDef (State (ActorDefState s) a) deriving (Functor,Applicative,Monad) data ActorDefState s = ActorDefState { adsRules :: [Rule s] , adsInit :: [Expr () s] , adsProd :: [Expr () (s -> (s,Out))] , adsSG :: [SG] , adsConns :: ConnMap } simpleOut :: forall s a. Typeable a => ConnType -> ActorDef s (Conn a) simpleOut ct = ActorDef $ do st <- get let conns = adsConns st cid = ConnId $ Map.size conns put $! st { adsConns = Map.insert cid (ActorConn ct (typeOf (undefined :: a))) conns } return $ Conn cid ConnOne rule :: Expr () (s -> a -> (s,Out)) -> ActorDef s () rule f = ActorDef $ do modify $ \st -> st { adsRules = Rule f : adsRules st } | Producer actor . One which sends data indefinitely producer :: Expr () (s -> (s,Out)) -> ActorDef s () producer f = ActorDef $ do modify $ \st -> st { adsProd = f : adsProd st } scatterGather :: SG -> ActorDef s () scatterGather sg = ActorDef $ do modify $ \st -> st { adsSG = sg : adsSG st } startingState :: Expr () s -> ActorDef s () startingState s = ActorDef $ do modify $ \st -> st { adsInit = s : adsInit st } actor :: ActorDef s outs -> Actor outs actor (ActorDef m) = case s of ActorDefState [] [] [] [sg] c -> Actor outs (RealActor c (ScatterGather sg)) ActorDefState _ [] _ _ _ -> oops "No initial state specified" ActorDefState [] _ [] _ _ -> oops "No transition rules/producers" ActorDefState rs [i] [] _ c -> Actor outs (RealActor c (StateM i rs)) ActorDefState [] [i] [f] _ c -> Actor outs (RealActor c (Producer i f)) ActorDefState [] _ _ _ _ -> oops "Several producer steps specified" ActorDefState _ _ _ _ _ -> oops "Several initial states specified" where (outs,s) = runState m $ ActorDefState [] [] [] [] Map.empty oops = Invalid . pure Dataflow graph definition type Dataflow = (State (Int, [(Node,BuildNode)], [(Node,Node,ConnId)])) data BuildNode where BuildNode :: Actor outs -> BuildNode newtype A = A Node buildDataflow :: Dataflow () -> Compile DataflowGraph buildDataflow m = applicatively $ (\n -> mkGraph n es) <$> T.traverse validate ns where validate (_,BuildNode (Invalid errs)) = leftA errs validate (i,BuildNode (Actor _ a)) = pure (i,ANode NotSched a) (_,ns,es) = execState m (0,[],[]) use :: forall outs. ConnCollection outs => Actor outs -> Dataflow (A, Connected outs) use a = do (i,acts,conns) <- get put (i+1, (i,BuildNode a) : acts, conns) return (A i, case a of Invalid _ -> nullConnection (undefined :: outs) Actor o _ -> setActorId i o ) connect :: Connection a -> A -> Dataflow () connect Failed _ = return () connect (Bound from (Conn i _)) (A to) = do (j, acts, conns) <- get put ( j , acts , (from,to, i) : conns ) compile -> IO () compile codegen write cad gr = do let r = runCompile $ codegen =<< checkSchedule =<< schedule cad =<< checkGraph =<< buildDataflow gr case r of Left errs -> mapM_ putStrLn errs Right a -> write a
1c0cc5cebf0c0a075f67c338d9f68fa071f0543685c0f0a39c76959396246b26
replikativ/kabel
transit.cljc
(ns kabel.middleware.transit (:require [kabel.middleware.handler :refer [handler]] #?(:clj [kabel.platform-log :refer [debug]]) #?(:cljs [kabel.util :refer [on-node?]]) #?(:clj [superv.async :refer [go-try]]) [cognitect.transit :as t] #?(:cljs [goog.crypt :as crypt]) [incognito.transit :refer [incognito-read-handler incognito-write-handler]]) #?(:clj (:import [java.io ByteArrayInputStream ByteArrayOutputStream]) :cljs (:require-macros [superv.async :refer [go-try]] [kabel.platform-log :refer [debug]]))) (defn transit "Serializes all incoming and outgoing edn datastructures in transit form." ([[S peer [in out]]] (transit :json (atom {}) (atom {}) [S peer [in out]])) ([backend read-handlers write-handlers [S peer [in out]]] (handler #(go-try S (let [{:keys [kabel/serialization kabel/payload]} %] (if (or (= serialization :transit-json) (= serialization :transit-msgpack)) (let [ir (incognito-read-handler read-handlers) v #?(:clj (with-open [bais (ByteArrayInputStream. payload)] (let [reader (t/reader bais backend {:handlers {"incognito" ir}})] (t/read reader))) :cljs (let [reader (t/reader backend {:handlers {"u" (fn [v] (cljs.core/uuid v)) "incognito" ir}}) s (if (on-node?) (.toString payload "utf8") (-> payload crypt/utf8ByteArrayToString #_(js/TextDecoder. "utf-8") #_(.decode payload)))] (try (t/read reader s) (catch js/Error e (throw (ex-info "Cannot parse transit." {:string s :error e})))))) merged (if (map? v) (merge v (dissoc % :kabel/serialization :kabel/payload)) v)] #_(debug {:event :transit-deserialized :value merged}) merged) %))) #(go-try S (if (:kabel/serialization %) ;; already serialized % (do #_(debug {:event :transit-serialize :value %}) {:kabel/serialization (keyword (str "transit-" (name backend))) :kabel/payload #?(:clj (with-open [baos (ByteArrayOutputStream.)] (let [iw (incognito-write-handler write-handlers) writer (t/writer baos backend {:handlers {java.util.Map iw}})] (t/write writer %)) (.toByteArray baos)) :cljs (if (on-node?) (let [iw (incognito-write-handler write-handlers) writer (t/writer backend {:handlers {"default" iw}})] (->> (t/write writer %) (.from js/Buffer))) (let [iw (incognito-write-handler write-handlers) writer (t/writer backend {:handlers {"default" iw}}) #_encoder #_(js/TextEncoder. "utf-8")] (->> (t/write writer %) crypt/stringToUtf8ByteArray #_(.encode encoder)))))}))) [S peer [in out]]))) (comment (require '[superv.async :refer [S <??]]) (let [in (chan) out (chan) [S _ [nin nout]] (transit [S nil [in out]])] (put! nout "hello") (prn (vec (<?? S out))) ) (let [reader (transit/reader :json {:handlers ;; remove if uuid problem is gone {"u" (fn [v] (cljs.core/uuid v)) "incognito" (incognito-read-handler read-handlers)}})] (if-not (on-node?) ;; Browser (let [fr (js/FileReader.)] (set! (.-onload fr) #(let [res (js/String. (.. % -target -result))] #_(debug "Received message: " res) (put! in (assoc (transit/read reader res) :host host)))) (.readAsText fr (.-message evt))) ;; nodejs (let [s (js/String.fromCharCode.apply nil (js/Uint8Array. (.. evt -message)))] (put! in (assoc (transit/read reader s) :host host))))) (let [i-write-handler (incognito-write-handler write-handlers) writer (transit/writer :json {:handlers {"default" i-write-handler}}) to-send (transit/write writer (assoc m :sender peer-id))] (if-not (on-node?) ( .send channel ( js / . # js [ to - send ] ) ) ; ; Browser (.send channel (js/Buffer. to-send)) ;; NodeJS )) )
null
https://raw.githubusercontent.com/replikativ/kabel/d3a75385b4ff60f2bbc406763e830483b324f936/src/kabel/middleware/transit.cljc
clojure
already serialized remove if uuid problem is gone Browser nodejs ; Browser NodeJS
(ns kabel.middleware.transit (:require [kabel.middleware.handler :refer [handler]] #?(:clj [kabel.platform-log :refer [debug]]) #?(:cljs [kabel.util :refer [on-node?]]) #?(:clj [superv.async :refer [go-try]]) [cognitect.transit :as t] #?(:cljs [goog.crypt :as crypt]) [incognito.transit :refer [incognito-read-handler incognito-write-handler]]) #?(:clj (:import [java.io ByteArrayInputStream ByteArrayOutputStream]) :cljs (:require-macros [superv.async :refer [go-try]] [kabel.platform-log :refer [debug]]))) (defn transit "Serializes all incoming and outgoing edn datastructures in transit form." ([[S peer [in out]]] (transit :json (atom {}) (atom {}) [S peer [in out]])) ([backend read-handlers write-handlers [S peer [in out]]] (handler #(go-try S (let [{:keys [kabel/serialization kabel/payload]} %] (if (or (= serialization :transit-json) (= serialization :transit-msgpack)) (let [ir (incognito-read-handler read-handlers) v #?(:clj (with-open [bais (ByteArrayInputStream. payload)] (let [reader (t/reader bais backend {:handlers {"incognito" ir}})] (t/read reader))) :cljs (let [reader (t/reader backend {:handlers {"u" (fn [v] (cljs.core/uuid v)) "incognito" ir}}) s (if (on-node?) (.toString payload "utf8") (-> payload crypt/utf8ByteArrayToString #_(js/TextDecoder. "utf-8") #_(.decode payload)))] (try (t/read reader s) (catch js/Error e (throw (ex-info "Cannot parse transit." {:string s :error e})))))) merged (if (map? v) (merge v (dissoc % :kabel/serialization :kabel/payload)) v)] #_(debug {:event :transit-deserialized :value merged}) merged) %))) #(go-try S % (do #_(debug {:event :transit-serialize :value %}) {:kabel/serialization (keyword (str "transit-" (name backend))) :kabel/payload #?(:clj (with-open [baos (ByteArrayOutputStream.)] (let [iw (incognito-write-handler write-handlers) writer (t/writer baos backend {:handlers {java.util.Map iw}})] (t/write writer %)) (.toByteArray baos)) :cljs (if (on-node?) (let [iw (incognito-write-handler write-handlers) writer (t/writer backend {:handlers {"default" iw}})] (->> (t/write writer %) (.from js/Buffer))) (let [iw (incognito-write-handler write-handlers) writer (t/writer backend {:handlers {"default" iw}}) #_encoder #_(js/TextEncoder. "utf-8")] (->> (t/write writer %) crypt/stringToUtf8ByteArray #_(.encode encoder)))))}))) [S peer [in out]]))) (comment (require '[superv.async :refer [S <??]]) (let [in (chan) out (chan) [S _ [nin nout]] (transit [S nil [in out]])] (put! nout "hello") (prn (vec (<?? S out))) ) {"u" (fn [v] (cljs.core/uuid v)) "incognito" (incognito-read-handler read-handlers)}})] (if-not (on-node?) (let [fr (js/FileReader.)] (set! (.-onload fr) #(let [res (js/String. (.. % -target -result))] #_(debug "Received message: " res) (put! in (assoc (transit/read reader res) :host host)))) (.readAsText fr (.-message evt))) (let [s (js/String.fromCharCode.apply nil (js/Uint8Array. (.. evt -message)))] (put! in (assoc (transit/read reader s) :host host))))) (let [i-write-handler (incognito-write-handler write-handlers) writer (transit/writer :json {:handlers {"default" i-write-handler}}) to-send (transit/write writer (assoc m :sender peer-id))] (if-not (on-node?) )) )
1b1b8dfd3567bad13e9c6e696e20ed91f05ac174f2e4e55ea6eb608a1439f672
arsalan0c/cdp-hs
Overlay.hs
{-# LANGUAGE OverloadedStrings, RecordWildCards, TupleSections #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleContexts # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # # LANGUAGE TypeFamilies # {- | = Overlay This domain provides various functionality related to drawing atop the inspected page. -} module CDP.Domains.Overlay (module CDP.Domains.Overlay) where import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.Loops import Control.Monad.Trans (liftIO) import qualified Data.Map as M import Data.Maybe import Data.Functor.Identity import Data.String import qualified Data.Text as T import qualified Data.List as List import qualified Data.Text.IO as TI import qualified Data.Vector as V import Data.Aeson.Types (Parser(..)) import Data.Aeson (FromJSON (..), ToJSON (..), (.:), (.:?), (.=), (.!=), (.:!)) import qualified Data.Aeson as A import qualified Network.HTTP.Simple as Http import qualified Network.URI as Uri import qualified Network.WebSockets as WS import Control.Concurrent import qualified Data.ByteString.Lazy as BS import qualified Data.Map as Map import Data.Proxy import System.Random import GHC.Generics import Data.Char import Data.Default import CDP.Internal.Utils import CDP.Domains.DOMPageNetworkEmulationSecurity as DOMPageNetworkEmulationSecurity import CDP.Domains.Runtime as Runtime -- | Type 'Overlay.SourceOrderConfig'. -- Configuration data for drawing the source order of an elements children. data OverlaySourceOrderConfig = OverlaySourceOrderConfig { -- | the color to outline the givent element in. overlaySourceOrderConfigParentOutlineColor :: DOMPageNetworkEmulationSecurity.DOMRGBA, -- | the color to outline the child elements in. overlaySourceOrderConfigChildOutlineColor :: DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlaySourceOrderConfig where parseJSON = A.withObject "OverlaySourceOrderConfig" $ \o -> OverlaySourceOrderConfig <$> o A..: "parentOutlineColor" <*> o A..: "childOutlineColor" instance ToJSON OverlaySourceOrderConfig where toJSON p = A.object $ catMaybes [ ("parentOutlineColor" A..=) <$> Just (overlaySourceOrderConfigParentOutlineColor p), ("childOutlineColor" A..=) <$> Just (overlaySourceOrderConfigChildOutlineColor p) ] -- | Type 'Overlay.GridHighlightConfig'. -- Configuration data for the highlighting of Grid elements. data OverlayGridHighlightConfig = OverlayGridHighlightConfig { -- | Whether the extension lines from grid cells to the rulers should be shown (default: false). overlayGridHighlightConfigShowGridExtensionLines :: Maybe Bool, -- | Show Positive line number labels (default: false). overlayGridHighlightConfigShowPositiveLineNumbers :: Maybe Bool, -- | Show Negative line number labels (default: false). overlayGridHighlightConfigShowNegativeLineNumbers :: Maybe Bool, -- | Show area name labels (default: false). overlayGridHighlightConfigShowAreaNames :: Maybe Bool, -- | Show line name labels (default: false). overlayGridHighlightConfigShowLineNames :: Maybe Bool, -- | Show track size labels (default: false). overlayGridHighlightConfigShowTrackSizes :: Maybe Bool, -- | The grid container border highlight color (default: transparent). overlayGridHighlightConfigGridBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The row line color (default: transparent). overlayGridHighlightConfigRowLineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The column line color (default: transparent). overlayGridHighlightConfigColumnLineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | Whether the grid border is dashed (default: false). overlayGridHighlightConfigGridBorderDash :: Maybe Bool, -- | Whether row lines are dashed (default: false). overlayGridHighlightConfigRowLineDash :: Maybe Bool, -- | Whether column lines are dashed (default: false). overlayGridHighlightConfigColumnLineDash :: Maybe Bool, -- | The row gap highlight fill color (default: transparent). overlayGridHighlightConfigRowGapColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The row gap hatching fill color (default: transparent). overlayGridHighlightConfigRowHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The column gap highlight fill color (default: transparent). overlayGridHighlightConfigColumnGapColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The column gap hatching fill color (default: transparent). overlayGridHighlightConfigColumnHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The named grid areas border color (Default: transparent). overlayGridHighlightConfigAreaBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The grid container background color (Default: transparent). overlayGridHighlightConfigGridBackgroundColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayGridHighlightConfig where parseJSON = A.withObject "OverlayGridHighlightConfig" $ \o -> OverlayGridHighlightConfig <$> o A..:? "showGridExtensionLines" <*> o A..:? "showPositiveLineNumbers" <*> o A..:? "showNegativeLineNumbers" <*> o A..:? "showAreaNames" <*> o A..:? "showLineNames" <*> o A..:? "showTrackSizes" <*> o A..:? "gridBorderColor" <*> o A..:? "rowLineColor" <*> o A..:? "columnLineColor" <*> o A..:? "gridBorderDash" <*> o A..:? "rowLineDash" <*> o A..:? "columnLineDash" <*> o A..:? "rowGapColor" <*> o A..:? "rowHatchColor" <*> o A..:? "columnGapColor" <*> o A..:? "columnHatchColor" <*> o A..:? "areaBorderColor" <*> o A..:? "gridBackgroundColor" instance ToJSON OverlayGridHighlightConfig where toJSON p = A.object $ catMaybes [ ("showGridExtensionLines" A..=) <$> (overlayGridHighlightConfigShowGridExtensionLines p), ("showPositiveLineNumbers" A..=) <$> (overlayGridHighlightConfigShowPositiveLineNumbers p), ("showNegativeLineNumbers" A..=) <$> (overlayGridHighlightConfigShowNegativeLineNumbers p), ("showAreaNames" A..=) <$> (overlayGridHighlightConfigShowAreaNames p), ("showLineNames" A..=) <$> (overlayGridHighlightConfigShowLineNames p), ("showTrackSizes" A..=) <$> (overlayGridHighlightConfigShowTrackSizes p), ("gridBorderColor" A..=) <$> (overlayGridHighlightConfigGridBorderColor p), ("rowLineColor" A..=) <$> (overlayGridHighlightConfigRowLineColor p), ("columnLineColor" A..=) <$> (overlayGridHighlightConfigColumnLineColor p), ("gridBorderDash" A..=) <$> (overlayGridHighlightConfigGridBorderDash p), ("rowLineDash" A..=) <$> (overlayGridHighlightConfigRowLineDash p), ("columnLineDash" A..=) <$> (overlayGridHighlightConfigColumnLineDash p), ("rowGapColor" A..=) <$> (overlayGridHighlightConfigRowGapColor p), ("rowHatchColor" A..=) <$> (overlayGridHighlightConfigRowHatchColor p), ("columnGapColor" A..=) <$> (overlayGridHighlightConfigColumnGapColor p), ("columnHatchColor" A..=) <$> (overlayGridHighlightConfigColumnHatchColor p), ("areaBorderColor" A..=) <$> (overlayGridHighlightConfigAreaBorderColor p), ("gridBackgroundColor" A..=) <$> (overlayGridHighlightConfigGridBackgroundColor p) ] -- | Type 'Overlay.FlexContainerHighlightConfig'. Configuration data for the highlighting of Flex container elements . data OverlayFlexContainerHighlightConfig = OverlayFlexContainerHighlightConfig { -- | The style of the container border overlayFlexContainerHighlightConfigContainerBorder :: Maybe OverlayLineStyle, -- | The style of the separator between lines overlayFlexContainerHighlightConfigLineSeparator :: Maybe OverlayLineStyle, -- | The style of the separator between items overlayFlexContainerHighlightConfigItemSeparator :: Maybe OverlayLineStyle, -- | Style of content-distribution space on the main axis (justify-content). overlayFlexContainerHighlightConfigMainDistributedSpace :: Maybe OverlayBoxStyle, -- | Style of content-distribution space on the cross axis (align-content). overlayFlexContainerHighlightConfigCrossDistributedSpace :: Maybe OverlayBoxStyle, -- | Style of empty space caused by row gaps (gap/row-gap). overlayFlexContainerHighlightConfigRowGapSpace :: Maybe OverlayBoxStyle, -- | Style of empty space caused by columns gaps (gap/column-gap). overlayFlexContainerHighlightConfigColumnGapSpace :: Maybe OverlayBoxStyle, -- | Style of the self-alignment line (align-items). overlayFlexContainerHighlightConfigCrossAlignment :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayFlexContainerHighlightConfig where parseJSON = A.withObject "OverlayFlexContainerHighlightConfig" $ \o -> OverlayFlexContainerHighlightConfig <$> o A..:? "containerBorder" <*> o A..:? "lineSeparator" <*> o A..:? "itemSeparator" <*> o A..:? "mainDistributedSpace" <*> o A..:? "crossDistributedSpace" <*> o A..:? "rowGapSpace" <*> o A..:? "columnGapSpace" <*> o A..:? "crossAlignment" instance ToJSON OverlayFlexContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerBorder" A..=) <$> (overlayFlexContainerHighlightConfigContainerBorder p), ("lineSeparator" A..=) <$> (overlayFlexContainerHighlightConfigLineSeparator p), ("itemSeparator" A..=) <$> (overlayFlexContainerHighlightConfigItemSeparator p), ("mainDistributedSpace" A..=) <$> (overlayFlexContainerHighlightConfigMainDistributedSpace p), ("crossDistributedSpace" A..=) <$> (overlayFlexContainerHighlightConfigCrossDistributedSpace p), ("rowGapSpace" A..=) <$> (overlayFlexContainerHighlightConfigRowGapSpace p), ("columnGapSpace" A..=) <$> (overlayFlexContainerHighlightConfigColumnGapSpace p), ("crossAlignment" A..=) <$> (overlayFlexContainerHighlightConfigCrossAlignment p) ] -- | Type 'Overlay.FlexItemHighlightConfig'. Configuration data for the highlighting of Flex item elements . data OverlayFlexItemHighlightConfig = OverlayFlexItemHighlightConfig { -- | Style of the box representing the item's base size overlayFlexItemHighlightConfigBaseSizeBox :: Maybe OverlayBoxStyle, -- | Style of the border around the box representing the item's base size overlayFlexItemHighlightConfigBaseSizeBorder :: Maybe OverlayLineStyle, -- | Style of the arrow representing if the item grew or shrank overlayFlexItemHighlightConfigFlexibilityArrow :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayFlexItemHighlightConfig where parseJSON = A.withObject "OverlayFlexItemHighlightConfig" $ \o -> OverlayFlexItemHighlightConfig <$> o A..:? "baseSizeBox" <*> o A..:? "baseSizeBorder" <*> o A..:? "flexibilityArrow" instance ToJSON OverlayFlexItemHighlightConfig where toJSON p = A.object $ catMaybes [ ("baseSizeBox" A..=) <$> (overlayFlexItemHighlightConfigBaseSizeBox p), ("baseSizeBorder" A..=) <$> (overlayFlexItemHighlightConfigBaseSizeBorder p), ("flexibilityArrow" A..=) <$> (overlayFlexItemHighlightConfigFlexibilityArrow p) ] | Type ' Overlay . ' . -- Style information for drawing a line. data OverlayLineStylePattern = OverlayLineStylePatternDashed | OverlayLineStylePatternDotted deriving (Ord, Eq, Show, Read) instance FromJSON OverlayLineStylePattern where parseJSON = A.withText "OverlayLineStylePattern" $ \v -> case v of "dashed" -> pure OverlayLineStylePatternDashed "dotted" -> pure OverlayLineStylePatternDotted "_" -> fail "failed to parse OverlayLineStylePattern" instance ToJSON OverlayLineStylePattern where toJSON v = A.String $ case v of OverlayLineStylePatternDashed -> "dashed" OverlayLineStylePatternDotted -> "dotted" data OverlayLineStyle = OverlayLineStyle { -- | The color of the line (default: transparent) overlayLineStyleColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The line pattern (default: solid) overlayLineStylePattern :: Maybe OverlayLineStylePattern } deriving (Eq, Show) instance FromJSON OverlayLineStyle where parseJSON = A.withObject "OverlayLineStyle" $ \o -> OverlayLineStyle <$> o A..:? "color" <*> o A..:? "pattern" instance ToJSON OverlayLineStyle where toJSON p = A.object $ catMaybes [ ("color" A..=) <$> (overlayLineStyleColor p), ("pattern" A..=) <$> (overlayLineStylePattern p) ] | Type ' Overlay . BoxStyle ' . -- Style information for drawing a box. data OverlayBoxStyle = OverlayBoxStyle { -- | The background color for the box (default: transparent) overlayBoxStyleFillColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The hatching color for the box (default: transparent) overlayBoxStyleHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayBoxStyle where parseJSON = A.withObject "OverlayBoxStyle" $ \o -> OverlayBoxStyle <$> o A..:? "fillColor" <*> o A..:? "hatchColor" instance ToJSON OverlayBoxStyle where toJSON p = A.object $ catMaybes [ ("fillColor" A..=) <$> (overlayBoxStyleFillColor p), ("hatchColor" A..=) <$> (overlayBoxStyleHatchColor p) ] | Type ' Overlay . ContrastAlgorithm ' . data OverlayContrastAlgorithm = OverlayContrastAlgorithmAa | OverlayContrastAlgorithmAaa | OverlayContrastAlgorithmApca deriving (Ord, Eq, Show, Read) instance FromJSON OverlayContrastAlgorithm where parseJSON = A.withText "OverlayContrastAlgorithm" $ \v -> case v of "aa" -> pure OverlayContrastAlgorithmAa "aaa" -> pure OverlayContrastAlgorithmAaa "apca" -> pure OverlayContrastAlgorithmApca "_" -> fail "failed to parse OverlayContrastAlgorithm" instance ToJSON OverlayContrastAlgorithm where toJSON v = A.String $ case v of OverlayContrastAlgorithmAa -> "aa" OverlayContrastAlgorithmAaa -> "aaa" OverlayContrastAlgorithmApca -> "apca" -- | Type 'Overlay.HighlightConfig'. -- Configuration data for the highlighting of page elements. data OverlayHighlightConfig = OverlayHighlightConfig { -- | Whether the node info tooltip should be shown (default: false). overlayHighlightConfigShowInfo :: Maybe Bool, -- | Whether the node styles in the tooltip (default: false). overlayHighlightConfigShowStyles :: Maybe Bool, -- | Whether the rulers should be shown (default: false). overlayHighlightConfigShowRulers :: Maybe Bool, -- | Whether the a11y info should be shown (default: true). overlayHighlightConfigShowAccessibilityInfo :: Maybe Bool, -- | Whether the extension lines from node to the rulers should be shown (default: false). overlayHighlightConfigShowExtensionLines :: Maybe Bool, -- | The content box highlight fill color (default: transparent). overlayHighlightConfigContentColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The padding highlight fill color (default: transparent). overlayHighlightConfigPaddingColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The border highlight fill color (default: transparent). overlayHighlightConfigBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The margin highlight fill color (default: transparent). overlayHighlightConfigMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The event target element highlight fill color (default: transparent). overlayHighlightConfigEventTargetColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The shape outside fill color (default: transparent). overlayHighlightConfigShapeColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The shape margin fill color (default: transparent). overlayHighlightConfigShapeMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The grid layout color (default: transparent). overlayHighlightConfigCssGridColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The color format used to format color styles (default: hex). overlayHighlightConfigColorFormat :: Maybe OverlayColorFormat, -- | The grid layout highlight configuration (default: all transparent). overlayHighlightConfigGridHighlightConfig :: Maybe OverlayGridHighlightConfig, -- | The flex container highlight configuration (default: all transparent). overlayHighlightConfigFlexContainerHighlightConfig :: Maybe OverlayFlexContainerHighlightConfig, -- | The flex item highlight configuration (default: all transparent). overlayHighlightConfigFlexItemHighlightConfig :: Maybe OverlayFlexItemHighlightConfig, -- | The contrast algorithm to use for the contrast ratio (default: aa). overlayHighlightConfigContrastAlgorithm :: Maybe OverlayContrastAlgorithm, -- | The container query container highlight configuration (default: all transparent). overlayHighlightConfigContainerQueryContainerHighlightConfig :: Maybe OverlayContainerQueryContainerHighlightConfig } deriving (Eq, Show) instance FromJSON OverlayHighlightConfig where parseJSON = A.withObject "OverlayHighlightConfig" $ \o -> OverlayHighlightConfig <$> o A..:? "showInfo" <*> o A..:? "showStyles" <*> o A..:? "showRulers" <*> o A..:? "showAccessibilityInfo" <*> o A..:? "showExtensionLines" <*> o A..:? "contentColor" <*> o A..:? "paddingColor" <*> o A..:? "borderColor" <*> o A..:? "marginColor" <*> o A..:? "eventTargetColor" <*> o A..:? "shapeColor" <*> o A..:? "shapeMarginColor" <*> o A..:? "cssGridColor" <*> o A..:? "colorFormat" <*> o A..:? "gridHighlightConfig" <*> o A..:? "flexContainerHighlightConfig" <*> o A..:? "flexItemHighlightConfig" <*> o A..:? "contrastAlgorithm" <*> o A..:? "containerQueryContainerHighlightConfig" instance ToJSON OverlayHighlightConfig where toJSON p = A.object $ catMaybes [ ("showInfo" A..=) <$> (overlayHighlightConfigShowInfo p), ("showStyles" A..=) <$> (overlayHighlightConfigShowStyles p), ("showRulers" A..=) <$> (overlayHighlightConfigShowRulers p), ("showAccessibilityInfo" A..=) <$> (overlayHighlightConfigShowAccessibilityInfo p), ("showExtensionLines" A..=) <$> (overlayHighlightConfigShowExtensionLines p), ("contentColor" A..=) <$> (overlayHighlightConfigContentColor p), ("paddingColor" A..=) <$> (overlayHighlightConfigPaddingColor p), ("borderColor" A..=) <$> (overlayHighlightConfigBorderColor p), ("marginColor" A..=) <$> (overlayHighlightConfigMarginColor p), ("eventTargetColor" A..=) <$> (overlayHighlightConfigEventTargetColor p), ("shapeColor" A..=) <$> (overlayHighlightConfigShapeColor p), ("shapeMarginColor" A..=) <$> (overlayHighlightConfigShapeMarginColor p), ("cssGridColor" A..=) <$> (overlayHighlightConfigCssGridColor p), ("colorFormat" A..=) <$> (overlayHighlightConfigColorFormat p), ("gridHighlightConfig" A..=) <$> (overlayHighlightConfigGridHighlightConfig p), ("flexContainerHighlightConfig" A..=) <$> (overlayHighlightConfigFlexContainerHighlightConfig p), ("flexItemHighlightConfig" A..=) <$> (overlayHighlightConfigFlexItemHighlightConfig p), ("contrastAlgorithm" A..=) <$> (overlayHighlightConfigContrastAlgorithm p), ("containerQueryContainerHighlightConfig" A..=) <$> (overlayHighlightConfigContainerQueryContainerHighlightConfig p) ] -- | Type 'Overlay.ColorFormat'. data OverlayColorFormat = OverlayColorFormatRgb | OverlayColorFormatHsl | OverlayColorFormatHwb | OverlayColorFormatHex deriving (Ord, Eq, Show, Read) instance FromJSON OverlayColorFormat where parseJSON = A.withText "OverlayColorFormat" $ \v -> case v of "rgb" -> pure OverlayColorFormatRgb "hsl" -> pure OverlayColorFormatHsl "hwb" -> pure OverlayColorFormatHwb "hex" -> pure OverlayColorFormatHex "_" -> fail "failed to parse OverlayColorFormat" instance ToJSON OverlayColorFormat where toJSON v = A.String $ case v of OverlayColorFormatRgb -> "rgb" OverlayColorFormatHsl -> "hsl" OverlayColorFormatHwb -> "hwb" OverlayColorFormatHex -> "hex" -- | Type 'Overlay.GridNodeHighlightConfig'. -- Configurations for Persistent Grid Highlight data OverlayGridNodeHighlightConfig = OverlayGridNodeHighlightConfig { -- | A descriptor for the highlight appearance. overlayGridNodeHighlightConfigGridHighlightConfig :: OverlayGridHighlightConfig, -- | Identifier of the node to highlight. overlayGridNodeHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayGridNodeHighlightConfig where parseJSON = A.withObject "OverlayGridNodeHighlightConfig" $ \o -> OverlayGridNodeHighlightConfig <$> o A..: "gridHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayGridNodeHighlightConfig where toJSON p = A.object $ catMaybes [ ("gridHighlightConfig" A..=) <$> Just (overlayGridNodeHighlightConfigGridHighlightConfig p), ("nodeId" A..=) <$> Just (overlayGridNodeHighlightConfigNodeId p) ] -- | Type 'Overlay.FlexNodeHighlightConfig'. data OverlayFlexNodeHighlightConfig = OverlayFlexNodeHighlightConfig { -- | A descriptor for the highlight appearance of flex containers. overlayFlexNodeHighlightConfigFlexContainerHighlightConfig :: OverlayFlexContainerHighlightConfig, -- | Identifier of the node to highlight. overlayFlexNodeHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayFlexNodeHighlightConfig where parseJSON = A.withObject "OverlayFlexNodeHighlightConfig" $ \o -> OverlayFlexNodeHighlightConfig <$> o A..: "flexContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayFlexNodeHighlightConfig where toJSON p = A.object $ catMaybes [ ("flexContainerHighlightConfig" A..=) <$> Just (overlayFlexNodeHighlightConfigFlexContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayFlexNodeHighlightConfigNodeId p) ] -- | Type 'Overlay.ScrollSnapContainerHighlightConfig'. data OverlayScrollSnapContainerHighlightConfig = OverlayScrollSnapContainerHighlightConfig { -- | The style of the snapport border (default: transparent) overlayScrollSnapContainerHighlightConfigSnapportBorder :: Maybe OverlayLineStyle, -- | The style of the snap area border (default: transparent) overlayScrollSnapContainerHighlightConfigSnapAreaBorder :: Maybe OverlayLineStyle, -- | The margin highlight fill color (default: transparent). overlayScrollSnapContainerHighlightConfigScrollMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The padding highlight fill color (default: transparent). overlayScrollSnapContainerHighlightConfigScrollPaddingColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayScrollSnapContainerHighlightConfig where parseJSON = A.withObject "OverlayScrollSnapContainerHighlightConfig" $ \o -> OverlayScrollSnapContainerHighlightConfig <$> o A..:? "snapportBorder" <*> o A..:? "snapAreaBorder" <*> o A..:? "scrollMarginColor" <*> o A..:? "scrollPaddingColor" instance ToJSON OverlayScrollSnapContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("snapportBorder" A..=) <$> (overlayScrollSnapContainerHighlightConfigSnapportBorder p), ("snapAreaBorder" A..=) <$> (overlayScrollSnapContainerHighlightConfigSnapAreaBorder p), ("scrollMarginColor" A..=) <$> (overlayScrollSnapContainerHighlightConfigScrollMarginColor p), ("scrollPaddingColor" A..=) <$> (overlayScrollSnapContainerHighlightConfigScrollPaddingColor p) ] -- | Type 'Overlay.ScrollSnapHighlightConfig'. data OverlayScrollSnapHighlightConfig = OverlayScrollSnapHighlightConfig { -- | A descriptor for the highlight appearance of scroll snap containers. overlayScrollSnapHighlightConfigScrollSnapContainerHighlightConfig :: OverlayScrollSnapContainerHighlightConfig, -- | Identifier of the node to highlight. overlayScrollSnapHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayScrollSnapHighlightConfig where parseJSON = A.withObject "OverlayScrollSnapHighlightConfig" $ \o -> OverlayScrollSnapHighlightConfig <$> o A..: "scrollSnapContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayScrollSnapHighlightConfig where toJSON p = A.object $ catMaybes [ ("scrollSnapContainerHighlightConfig" A..=) <$> Just (overlayScrollSnapHighlightConfigScrollSnapContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayScrollSnapHighlightConfigNodeId p) ] | Type ' Overlay . HingeConfig ' . -- Configuration for dual screen hinge data OverlayHingeConfig = OverlayHingeConfig { -- | A rectangle represent hinge overlayHingeConfigRect :: DOMPageNetworkEmulationSecurity.DOMRect, -- | The content box highlight fill color (default: a dark color). overlayHingeConfigContentColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The content box highlight outline color (default: transparent). overlayHingeConfigOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayHingeConfig where parseJSON = A.withObject "OverlayHingeConfig" $ \o -> OverlayHingeConfig <$> o A..: "rect" <*> o A..:? "contentColor" <*> o A..:? "outlineColor" instance ToJSON OverlayHingeConfig where toJSON p = A.object $ catMaybes [ ("rect" A..=) <$> Just (overlayHingeConfigRect p), ("contentColor" A..=) <$> (overlayHingeConfigContentColor p), ("outlineColor" A..=) <$> (overlayHingeConfigOutlineColor p) ] -- | Type 'Overlay.ContainerQueryHighlightConfig'. data OverlayContainerQueryHighlightConfig = OverlayContainerQueryHighlightConfig { -- | A descriptor for the highlight appearance of container query containers. overlayContainerQueryHighlightConfigContainerQueryContainerHighlightConfig :: OverlayContainerQueryContainerHighlightConfig, -- | Identifier of the container node to highlight. overlayContainerQueryHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayContainerQueryHighlightConfig where parseJSON = A.withObject "OverlayContainerQueryHighlightConfig" $ \o -> OverlayContainerQueryHighlightConfig <$> o A..: "containerQueryContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayContainerQueryHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerQueryContainerHighlightConfig" A..=) <$> Just (overlayContainerQueryHighlightConfigContainerQueryContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayContainerQueryHighlightConfigNodeId p) ] -- | Type 'Overlay.ContainerQueryContainerHighlightConfig'. data OverlayContainerQueryContainerHighlightConfig = OverlayContainerQueryContainerHighlightConfig { -- | The style of the container border. overlayContainerQueryContainerHighlightConfigContainerBorder :: Maybe OverlayLineStyle, -- | The style of the descendants' borders. overlayContainerQueryContainerHighlightConfigDescendantBorder :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayContainerQueryContainerHighlightConfig where parseJSON = A.withObject "OverlayContainerQueryContainerHighlightConfig" $ \o -> OverlayContainerQueryContainerHighlightConfig <$> o A..:? "containerBorder" <*> o A..:? "descendantBorder" instance ToJSON OverlayContainerQueryContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerBorder" A..=) <$> (overlayContainerQueryContainerHighlightConfigContainerBorder p), ("descendantBorder" A..=) <$> (overlayContainerQueryContainerHighlightConfigDescendantBorder p) ] -- | Type 'Overlay.IsolatedElementHighlightConfig'. data OverlayIsolatedElementHighlightConfig = OverlayIsolatedElementHighlightConfig { -- | A descriptor for the highlight appearance of an element in isolation mode. overlayIsolatedElementHighlightConfigIsolationModeHighlightConfig :: OverlayIsolationModeHighlightConfig, -- | Identifier of the isolated element to highlight. overlayIsolatedElementHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayIsolatedElementHighlightConfig where parseJSON = A.withObject "OverlayIsolatedElementHighlightConfig" $ \o -> OverlayIsolatedElementHighlightConfig <$> o A..: "isolationModeHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayIsolatedElementHighlightConfig where toJSON p = A.object $ catMaybes [ ("isolationModeHighlightConfig" A..=) <$> Just (overlayIsolatedElementHighlightConfigIsolationModeHighlightConfig p), ("nodeId" A..=) <$> Just (overlayIsolatedElementHighlightConfigNodeId p) ] -- | Type 'Overlay.IsolationModeHighlightConfig'. data OverlayIsolationModeHighlightConfig = OverlayIsolationModeHighlightConfig { -- | The fill color of the resizers (default: transparent). overlayIsolationModeHighlightConfigResizerColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The fill color for resizer handles (default: transparent). overlayIsolationModeHighlightConfigResizerHandleColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The fill color for the mask covering non-isolated elements (default: transparent). overlayIsolationModeHighlightConfigMaskColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayIsolationModeHighlightConfig where parseJSON = A.withObject "OverlayIsolationModeHighlightConfig" $ \o -> OverlayIsolationModeHighlightConfig <$> o A..:? "resizerColor" <*> o A..:? "resizerHandleColor" <*> o A..:? "maskColor" instance ToJSON OverlayIsolationModeHighlightConfig where toJSON p = A.object $ catMaybes [ ("resizerColor" A..=) <$> (overlayIsolationModeHighlightConfigResizerColor p), ("resizerHandleColor" A..=) <$> (overlayIsolationModeHighlightConfigResizerHandleColor p), ("maskColor" A..=) <$> (overlayIsolationModeHighlightConfigMaskColor p) ] -- | Type 'Overlay.InspectMode'. data OverlayInspectMode = OverlayInspectModeSearchForNode | OverlayInspectModeSearchForUAShadowDOM | OverlayInspectModeCaptureAreaScreenshot | OverlayInspectModeShowDistances | OverlayInspectModeNone deriving (Ord, Eq, Show, Read) instance FromJSON OverlayInspectMode where parseJSON = A.withText "OverlayInspectMode" $ \v -> case v of "searchForNode" -> pure OverlayInspectModeSearchForNode "searchForUAShadowDOM" -> pure OverlayInspectModeSearchForUAShadowDOM "captureAreaScreenshot" -> pure OverlayInspectModeCaptureAreaScreenshot "showDistances" -> pure OverlayInspectModeShowDistances "none" -> pure OverlayInspectModeNone "_" -> fail "failed to parse OverlayInspectMode" instance ToJSON OverlayInspectMode where toJSON v = A.String $ case v of OverlayInspectModeSearchForNode -> "searchForNode" OverlayInspectModeSearchForUAShadowDOM -> "searchForUAShadowDOM" OverlayInspectModeCaptureAreaScreenshot -> "captureAreaScreenshot" OverlayInspectModeShowDistances -> "showDistances" OverlayInspectModeNone -> "none" -- | Type of the 'Overlay.inspectNodeRequested' event. data OverlayInspectNodeRequested = OverlayInspectNodeRequested { -- | Id of the node to inspect. overlayInspectNodeRequestedBackendNodeId :: DOMPageNetworkEmulationSecurity.DOMBackendNodeId } deriving (Eq, Show) instance FromJSON OverlayInspectNodeRequested where parseJSON = A.withObject "OverlayInspectNodeRequested" $ \o -> OverlayInspectNodeRequested <$> o A..: "backendNodeId" instance Event OverlayInspectNodeRequested where eventName _ = "Overlay.inspectNodeRequested" -- | Type of the 'Overlay.nodeHighlightRequested' event. data OverlayNodeHighlightRequested = OverlayNodeHighlightRequested { overlayNodeHighlightRequestedNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayNodeHighlightRequested where parseJSON = A.withObject "OverlayNodeHighlightRequested" $ \o -> OverlayNodeHighlightRequested <$> o A..: "nodeId" instance Event OverlayNodeHighlightRequested where eventName _ = "Overlay.nodeHighlightRequested" -- | Type of the 'Overlay.screenshotRequested' event. data OverlayScreenshotRequested = OverlayScreenshotRequested { -- | Viewport to capture, in device independent pixels (dip). overlayScreenshotRequestedViewport :: DOMPageNetworkEmulationSecurity.PageViewport } deriving (Eq, Show) instance FromJSON OverlayScreenshotRequested where parseJSON = A.withObject "OverlayScreenshotRequested" $ \o -> OverlayScreenshotRequested <$> o A..: "viewport" instance Event OverlayScreenshotRequested where eventName _ = "Overlay.screenshotRequested" -- | Type of the 'Overlay.inspectModeCanceled' event. data OverlayInspectModeCanceled = OverlayInspectModeCanceled deriving (Eq, Show, Read) instance FromJSON OverlayInspectModeCanceled where parseJSON _ = pure OverlayInspectModeCanceled instance Event OverlayInspectModeCanceled where eventName _ = "Overlay.inspectModeCanceled" -- | Disables domain notifications. -- | Parameters of the 'Overlay.disable' command. data POverlayDisable = POverlayDisable deriving (Eq, Show) pOverlayDisable :: POverlayDisable pOverlayDisable = POverlayDisable instance ToJSON POverlayDisable where toJSON _ = A.Null instance Command POverlayDisable where type CommandResponse POverlayDisable = () commandName _ = "Overlay.disable" fromJSON = const . A.Success . const () -- | Enables domain notifications. -- | Parameters of the 'Overlay.enable' command. data POverlayEnable = POverlayEnable deriving (Eq, Show) pOverlayEnable :: POverlayEnable pOverlayEnable = POverlayEnable instance ToJSON POverlayEnable where toJSON _ = A.Null instance Command POverlayEnable where type CommandResponse POverlayEnable = () commandName _ = "Overlay.enable" fromJSON = const . A.Success . const () -- | For testing. -- | Parameters of the 'Overlay.getHighlightObjectForTest' command. data POverlayGetHighlightObjectForTest = POverlayGetHighlightObjectForTest { -- | Id of the node to get highlight object for. pOverlayGetHighlightObjectForTestNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId, -- | Whether to include distance info. pOverlayGetHighlightObjectForTestIncludeDistance :: Maybe Bool, -- | Whether to include style info. pOverlayGetHighlightObjectForTestIncludeStyle :: Maybe Bool, -- | The color format to get config with (default: hex). pOverlayGetHighlightObjectForTestColorFormat :: Maybe OverlayColorFormat, -- | Whether to show accessibility info (default: true). pOverlayGetHighlightObjectForTestShowAccessibilityInfo :: Maybe Bool } deriving (Eq, Show) pOverlayGetHighlightObjectForTest {- -- | Id of the node to get highlight object for. -} :: DOMPageNetworkEmulationSecurity.DOMNodeId -> POverlayGetHighlightObjectForTest pOverlayGetHighlightObjectForTest arg_pOverlayGetHighlightObjectForTestNodeId = POverlayGetHighlightObjectForTest arg_pOverlayGetHighlightObjectForTestNodeId Nothing Nothing Nothing Nothing instance ToJSON POverlayGetHighlightObjectForTest where toJSON p = A.object $ catMaybes [ ("nodeId" A..=) <$> Just (pOverlayGetHighlightObjectForTestNodeId p), ("includeDistance" A..=) <$> (pOverlayGetHighlightObjectForTestIncludeDistance p), ("includeStyle" A..=) <$> (pOverlayGetHighlightObjectForTestIncludeStyle p), ("colorFormat" A..=) <$> (pOverlayGetHighlightObjectForTestColorFormat p), ("showAccessibilityInfo" A..=) <$> (pOverlayGetHighlightObjectForTestShowAccessibilityInfo p) ] data OverlayGetHighlightObjectForTest = OverlayGetHighlightObjectForTest { -- | Highlight data for the node. overlayGetHighlightObjectForTestHighlight :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetHighlightObjectForTest where parseJSON = A.withObject "OverlayGetHighlightObjectForTest" $ \o -> OverlayGetHighlightObjectForTest <$> o A..: "highlight" instance Command POverlayGetHighlightObjectForTest where type CommandResponse POverlayGetHighlightObjectForTest = OverlayGetHighlightObjectForTest commandName _ = "Overlay.getHighlightObjectForTest" -- | For Persistent Grid testing. -- | Parameters of the 'Overlay.getGridHighlightObjectsForTest' command. data POverlayGetGridHighlightObjectsForTest = POverlayGetGridHighlightObjectsForTest { -- | Ids of the node to get highlight object for. pOverlayGetGridHighlightObjectsForTestNodeIds :: [DOMPageNetworkEmulationSecurity.DOMNodeId] } deriving (Eq, Show) pOverlayGetGridHighlightObjectsForTest {- -- | Ids of the node to get highlight object for. -} :: [DOMPageNetworkEmulationSecurity.DOMNodeId] -> POverlayGetGridHighlightObjectsForTest pOverlayGetGridHighlightObjectsForTest arg_pOverlayGetGridHighlightObjectsForTestNodeIds = POverlayGetGridHighlightObjectsForTest arg_pOverlayGetGridHighlightObjectsForTestNodeIds instance ToJSON POverlayGetGridHighlightObjectsForTest where toJSON p = A.object $ catMaybes [ ("nodeIds" A..=) <$> Just (pOverlayGetGridHighlightObjectsForTestNodeIds p) ] data OverlayGetGridHighlightObjectsForTest = OverlayGetGridHighlightObjectsForTest { -- | Grid Highlight data for the node ids provided. overlayGetGridHighlightObjectsForTestHighlights :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetGridHighlightObjectsForTest where parseJSON = A.withObject "OverlayGetGridHighlightObjectsForTest" $ \o -> OverlayGetGridHighlightObjectsForTest <$> o A..: "highlights" instance Command POverlayGetGridHighlightObjectsForTest where type CommandResponse POverlayGetGridHighlightObjectsForTest = OverlayGetGridHighlightObjectsForTest commandName _ = "Overlay.getGridHighlightObjectsForTest" -- | For Source Order Viewer testing. -- | Parameters of the 'Overlay.getSourceOrderHighlightObjectForTest' command. data POverlayGetSourceOrderHighlightObjectForTest = POverlayGetSourceOrderHighlightObjectForTest { -- | Id of the node to highlight. pOverlayGetSourceOrderHighlightObjectForTestNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) pOverlayGetSourceOrderHighlightObjectForTest {- -- | Id of the node to highlight. -} :: DOMPageNetworkEmulationSecurity.DOMNodeId -> POverlayGetSourceOrderHighlightObjectForTest pOverlayGetSourceOrderHighlightObjectForTest arg_pOverlayGetSourceOrderHighlightObjectForTestNodeId = POverlayGetSourceOrderHighlightObjectForTest arg_pOverlayGetSourceOrderHighlightObjectForTestNodeId instance ToJSON POverlayGetSourceOrderHighlightObjectForTest where toJSON p = A.object $ catMaybes [ ("nodeId" A..=) <$> Just (pOverlayGetSourceOrderHighlightObjectForTestNodeId p) ] data OverlayGetSourceOrderHighlightObjectForTest = OverlayGetSourceOrderHighlightObjectForTest { -- | Source order highlight data for the node id provided. overlayGetSourceOrderHighlightObjectForTestHighlight :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetSourceOrderHighlightObjectForTest where parseJSON = A.withObject "OverlayGetSourceOrderHighlightObjectForTest" $ \o -> OverlayGetSourceOrderHighlightObjectForTest <$> o A..: "highlight" instance Command POverlayGetSourceOrderHighlightObjectForTest where type CommandResponse POverlayGetSourceOrderHighlightObjectForTest = OverlayGetSourceOrderHighlightObjectForTest commandName _ = "Overlay.getSourceOrderHighlightObjectForTest" -- | Hides any highlight. -- | Parameters of the 'Overlay.hideHighlight' command. data POverlayHideHighlight = POverlayHideHighlight deriving (Eq, Show) pOverlayHideHighlight :: POverlayHideHighlight pOverlayHideHighlight = POverlayHideHighlight instance ToJSON POverlayHideHighlight where toJSON _ = A.Null instance Command POverlayHideHighlight where type CommandResponse POverlayHideHighlight = () commandName _ = "Overlay.hideHighlight" fromJSON = const . A.Success . const () | Highlights DOM node with given i d or with the given JavaScript object wrapper . Either nodeId or -- objectId must be specified. -- | Parameters of the 'Overlay.highlightNode' command. data POverlayHighlightNode = POverlayHighlightNode { -- | A descriptor for the highlight appearance. pOverlayHighlightNodeHighlightConfig :: OverlayHighlightConfig, -- | Identifier of the node to highlight. pOverlayHighlightNodeNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMNodeId, -- | Identifier of the backend node to highlight. pOverlayHighlightNodeBackendNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMBackendNodeId, -- | JavaScript object id of the node to be highlighted. pOverlayHighlightNodeObjectId :: Maybe Runtime.RuntimeRemoteObjectId, -- | Selectors to highlight relevant nodes. pOverlayHighlightNodeSelector :: Maybe T.Text } deriving (Eq, Show) pOverlayHighlightNode {- -- | A descriptor for the highlight appearance. -} :: OverlayHighlightConfig -> POverlayHighlightNode pOverlayHighlightNode arg_pOverlayHighlightNodeHighlightConfig = POverlayHighlightNode arg_pOverlayHighlightNodeHighlightConfig Nothing Nothing Nothing Nothing instance ToJSON POverlayHighlightNode where toJSON p = A.object $ catMaybes [ ("highlightConfig" A..=) <$> Just (pOverlayHighlightNodeHighlightConfig p), ("nodeId" A..=) <$> (pOverlayHighlightNodeNodeId p), ("backendNodeId" A..=) <$> (pOverlayHighlightNodeBackendNodeId p), ("objectId" A..=) <$> (pOverlayHighlightNodeObjectId p), ("selector" A..=) <$> (pOverlayHighlightNodeSelector p) ] instance Command POverlayHighlightNode where type CommandResponse POverlayHighlightNode = () commandName _ = "Overlay.highlightNode" fromJSON = const . A.Success . const () -- | Highlights given quad. Coordinates are absolute with respect to the main frame viewport. -- | Parameters of the 'Overlay.highlightQuad' command. data POverlayHighlightQuad = POverlayHighlightQuad { -- | Quad to highlight pOverlayHighlightQuadQuad :: DOMPageNetworkEmulationSecurity.DOMQuad, -- | The highlight fill color (default: transparent). pOverlayHighlightQuadColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The highlight outline color (default: transparent). pOverlayHighlightQuadOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) pOverlayHighlightQuad {- -- | Quad to highlight -} :: DOMPageNetworkEmulationSecurity.DOMQuad -> POverlayHighlightQuad pOverlayHighlightQuad arg_pOverlayHighlightQuadQuad = POverlayHighlightQuad arg_pOverlayHighlightQuadQuad Nothing Nothing instance ToJSON POverlayHighlightQuad where toJSON p = A.object $ catMaybes [ ("quad" A..=) <$> Just (pOverlayHighlightQuadQuad p), ("color" A..=) <$> (pOverlayHighlightQuadColor p), ("outlineColor" A..=) <$> (pOverlayHighlightQuadOutlineColor p) ] instance Command POverlayHighlightQuad where type CommandResponse POverlayHighlightQuad = () commandName _ = "Overlay.highlightQuad" fromJSON = const . A.Success . const () -- | Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. -- | Parameters of the 'Overlay.highlightRect' command. data POverlayHighlightRect = POverlayHighlightRect { -- | X coordinate pOverlayHighlightRectX :: Int, -- | Y coordinate pOverlayHighlightRectY :: Int, -- | Rectangle width pOverlayHighlightRectWidth :: Int, -- | Rectangle height pOverlayHighlightRectHeight :: Int, -- | The highlight fill color (default: transparent). pOverlayHighlightRectColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, -- | The highlight outline color (default: transparent). pOverlayHighlightRectOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) pOverlayHighlightRect {- -- | X coordinate -} :: Int {- -- | Y coordinate -} -> Int {- -- | Rectangle width -} -> Int {- -- | Rectangle height -} -> Int -> POverlayHighlightRect pOverlayHighlightRect arg_pOverlayHighlightRectX arg_pOverlayHighlightRectY arg_pOverlayHighlightRectWidth arg_pOverlayHighlightRectHeight = POverlayHighlightRect arg_pOverlayHighlightRectX arg_pOverlayHighlightRectY arg_pOverlayHighlightRectWidth arg_pOverlayHighlightRectHeight Nothing Nothing instance ToJSON POverlayHighlightRect where toJSON p = A.object $ catMaybes [ ("x" A..=) <$> Just (pOverlayHighlightRectX p), ("y" A..=) <$> Just (pOverlayHighlightRectY p), ("width" A..=) <$> Just (pOverlayHighlightRectWidth p), ("height" A..=) <$> Just (pOverlayHighlightRectHeight p), ("color" A..=) <$> (pOverlayHighlightRectColor p), ("outlineColor" A..=) <$> (pOverlayHighlightRectOutlineColor p) ] instance Command POverlayHighlightRect where type CommandResponse POverlayHighlightRect = () commandName _ = "Overlay.highlightRect" fromJSON = const . A.Success . const () | Highlights the source order of the children of the DOM node with given i d or with the given JavaScript object wrapper . Either nodeId or objectId must be specified . -- | Parameters of the 'Overlay.highlightSourceOrder' command. data POverlayHighlightSourceOrder = POverlayHighlightSourceOrder { -- | A descriptor for the appearance of the overlay drawing. pOverlayHighlightSourceOrderSourceOrderConfig :: OverlaySourceOrderConfig, -- | Identifier of the node to highlight. pOverlayHighlightSourceOrderNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMNodeId, -- | Identifier of the backend node to highlight. pOverlayHighlightSourceOrderBackendNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMBackendNodeId, -- | JavaScript object id of the node to be highlighted. pOverlayHighlightSourceOrderObjectId :: Maybe Runtime.RuntimeRemoteObjectId } deriving (Eq, Show) pOverlayHighlightSourceOrder {- -- | A descriptor for the appearance of the overlay drawing. -} :: OverlaySourceOrderConfig -> POverlayHighlightSourceOrder pOverlayHighlightSourceOrder arg_pOverlayHighlightSourceOrderSourceOrderConfig = POverlayHighlightSourceOrder arg_pOverlayHighlightSourceOrderSourceOrderConfig Nothing Nothing Nothing instance ToJSON POverlayHighlightSourceOrder where toJSON p = A.object $ catMaybes [ ("sourceOrderConfig" A..=) <$> Just (pOverlayHighlightSourceOrderSourceOrderConfig p), ("nodeId" A..=) <$> (pOverlayHighlightSourceOrderNodeId p), ("backendNodeId" A..=) <$> (pOverlayHighlightSourceOrderBackendNodeId p), ("objectId" A..=) <$> (pOverlayHighlightSourceOrderObjectId p) ] instance Command POverlayHighlightSourceOrder where type CommandResponse POverlayHighlightSourceOrder = () commandName _ = "Overlay.highlightSourceOrder" fromJSON = const . A.Success . const () -- | Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. -- Backend then generates 'inspectNodeRequested' event upon element selection. | Parameters of the ' ' command . data POverlaySetInspectMode = POverlaySetInspectMode { -- | Set an inspection mode. pOverlaySetInspectModeMode :: OverlayInspectMode, | A descriptor for the highlight appearance of hovered - over nodes . May be omitted if ` enabled -- == false`. pOverlaySetInspectModeHighlightConfig :: Maybe OverlayHighlightConfig } deriving (Eq, Show) pOverlaySetInspectMode {- -- | Set an inspection mode. -} :: OverlayInspectMode -> POverlaySetInspectMode pOverlaySetInspectMode arg_pOverlaySetInspectModeMode = POverlaySetInspectMode arg_pOverlaySetInspectModeMode Nothing instance ToJSON POverlaySetInspectMode where toJSON p = A.object $ catMaybes [ ("mode" A..=) <$> Just (pOverlaySetInspectModeMode p), ("highlightConfig" A..=) <$> (pOverlaySetInspectModeHighlightConfig p) ] instance Command POverlaySetInspectMode where type CommandResponse POverlaySetInspectMode = () commandName _ = "Overlay.setInspectMode" fromJSON = const . A.Success . const () -- | Highlights owner element of all frames detected to be ads. -- | Parameters of the 'Overlay.setShowAdHighlights' command. data POverlaySetShowAdHighlights = POverlaySetShowAdHighlights { -- | True for showing ad highlights pOverlaySetShowAdHighlightsShow :: Bool } deriving (Eq, Show) pOverlaySetShowAdHighlights {- -- | True for showing ad highlights -} :: Bool -> POverlaySetShowAdHighlights pOverlaySetShowAdHighlights arg_pOverlaySetShowAdHighlightsShow = POverlaySetShowAdHighlights arg_pOverlaySetShowAdHighlightsShow instance ToJSON POverlaySetShowAdHighlights where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowAdHighlightsShow p) ] instance Command POverlaySetShowAdHighlights where type CommandResponse POverlaySetShowAdHighlights = () commandName _ = "Overlay.setShowAdHighlights" fromJSON = const . A.Success . const () -- | Parameters of the 'Overlay.setPausedInDebuggerMessage' command. data POverlaySetPausedInDebuggerMessage = POverlaySetPausedInDebuggerMessage { -- | The message to display, also triggers resume and step over controls. pOverlaySetPausedInDebuggerMessageMessage :: Maybe T.Text } deriving (Eq, Show) pOverlaySetPausedInDebuggerMessage :: POverlaySetPausedInDebuggerMessage pOverlaySetPausedInDebuggerMessage = POverlaySetPausedInDebuggerMessage Nothing instance ToJSON POverlaySetPausedInDebuggerMessage where toJSON p = A.object $ catMaybes [ ("message" A..=) <$> (pOverlaySetPausedInDebuggerMessageMessage p) ] instance Command POverlaySetPausedInDebuggerMessage where type CommandResponse POverlaySetPausedInDebuggerMessage = () commandName _ = "Overlay.setPausedInDebuggerMessage" fromJSON = const . A.Success . const () -- | Requests that backend shows debug borders on layers | Parameters of the ' Overlay.setShowDebugBorders ' command . data POverlaySetShowDebugBorders = POverlaySetShowDebugBorders { -- | True for showing debug borders pOverlaySetShowDebugBordersShow :: Bool } deriving (Eq, Show) pOverlaySetShowDebugBorders {- -- | True for showing debug borders -} :: Bool -> POverlaySetShowDebugBorders pOverlaySetShowDebugBorders arg_pOverlaySetShowDebugBordersShow = POverlaySetShowDebugBorders arg_pOverlaySetShowDebugBordersShow instance ToJSON POverlaySetShowDebugBorders where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowDebugBordersShow p) ] instance Command POverlaySetShowDebugBorders where type CommandResponse POverlaySetShowDebugBorders = () commandName _ = "Overlay.setShowDebugBorders" fromJSON = const . A.Success . const () -- | Requests that backend shows the FPS counter -- | Parameters of the 'Overlay.setShowFPSCounter' command. data POverlaySetShowFPSCounter = POverlaySetShowFPSCounter { -- | True for showing the FPS counter pOverlaySetShowFPSCounterShow :: Bool } deriving (Eq, Show) pOverlaySetShowFPSCounter {- -- | True for showing the FPS counter -} :: Bool -> POverlaySetShowFPSCounter pOverlaySetShowFPSCounter arg_pOverlaySetShowFPSCounterShow = POverlaySetShowFPSCounter arg_pOverlaySetShowFPSCounterShow instance ToJSON POverlaySetShowFPSCounter where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowFPSCounterShow p) ] instance Command POverlaySetShowFPSCounter where type CommandResponse POverlaySetShowFPSCounter = () commandName _ = "Overlay.setShowFPSCounter" fromJSON = const . A.Success . const () -- | Highlight multiple elements with the CSS Grid overlay. -- | Parameters of the 'Overlay.setShowGridOverlays' command. data POverlaySetShowGridOverlays = POverlaySetShowGridOverlays { -- | An array of node identifiers and descriptors for the highlight appearance. pOverlaySetShowGridOverlaysGridNodeHighlightConfigs :: [OverlayGridNodeHighlightConfig] } deriving (Eq, Show) pOverlaySetShowGridOverlays {- -- | An array of node identifiers and descriptors for the highlight appearance. -} :: [OverlayGridNodeHighlightConfig] -> POverlaySetShowGridOverlays pOverlaySetShowGridOverlays arg_pOverlaySetShowGridOverlaysGridNodeHighlightConfigs = POverlaySetShowGridOverlays arg_pOverlaySetShowGridOverlaysGridNodeHighlightConfigs instance ToJSON POverlaySetShowGridOverlays where toJSON p = A.object $ catMaybes [ ("gridNodeHighlightConfigs" A..=) <$> Just (pOverlaySetShowGridOverlaysGridNodeHighlightConfigs p) ] instance Command POverlaySetShowGridOverlays where type CommandResponse POverlaySetShowGridOverlays = () commandName _ = "Overlay.setShowGridOverlays" fromJSON = const . A.Success . const () -- | Parameters of the 'Overlay.setShowFlexOverlays' command. data POverlaySetShowFlexOverlays = POverlaySetShowFlexOverlays { -- | An array of node identifiers and descriptors for the highlight appearance. pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs :: [OverlayFlexNodeHighlightConfig] } deriving (Eq, Show) pOverlaySetShowFlexOverlays {- -- | An array of node identifiers and descriptors for the highlight appearance. -} :: [OverlayFlexNodeHighlightConfig] -> POverlaySetShowFlexOverlays pOverlaySetShowFlexOverlays arg_pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs = POverlaySetShowFlexOverlays arg_pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs instance ToJSON POverlaySetShowFlexOverlays where toJSON p = A.object $ catMaybes [ ("flexNodeHighlightConfigs" A..=) <$> Just (pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs p) ] instance Command POverlaySetShowFlexOverlays where type CommandResponse POverlaySetShowFlexOverlays = () commandName _ = "Overlay.setShowFlexOverlays" fromJSON = const . A.Success . const () -- | Parameters of the 'Overlay.setShowScrollSnapOverlays' command. data POverlaySetShowScrollSnapOverlays = POverlaySetShowScrollSnapOverlays { -- | An array of node identifiers and descriptors for the highlight appearance. pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs :: [OverlayScrollSnapHighlightConfig] } deriving (Eq, Show) pOverlaySetShowScrollSnapOverlays {- -- | An array of node identifiers and descriptors for the highlight appearance. -} :: [OverlayScrollSnapHighlightConfig] -> POverlaySetShowScrollSnapOverlays pOverlaySetShowScrollSnapOverlays arg_pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs = POverlaySetShowScrollSnapOverlays arg_pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs instance ToJSON POverlaySetShowScrollSnapOverlays where toJSON p = A.object $ catMaybes [ ("scrollSnapHighlightConfigs" A..=) <$> Just (pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs p) ] instance Command POverlaySetShowScrollSnapOverlays where type CommandResponse POverlaySetShowScrollSnapOverlays = () commandName _ = "Overlay.setShowScrollSnapOverlays" fromJSON = const . A.Success . const () -- | Parameters of the 'Overlay.setShowContainerQueryOverlays' command. data POverlaySetShowContainerQueryOverlays = POverlaySetShowContainerQueryOverlays { -- | An array of node identifiers and descriptors for the highlight appearance. pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs :: [OverlayContainerQueryHighlightConfig] } deriving (Eq, Show) pOverlaySetShowContainerQueryOverlays {- -- | An array of node identifiers and descriptors for the highlight appearance. -} :: [OverlayContainerQueryHighlightConfig] -> POverlaySetShowContainerQueryOverlays pOverlaySetShowContainerQueryOverlays arg_pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs = POverlaySetShowContainerQueryOverlays arg_pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs instance ToJSON POverlaySetShowContainerQueryOverlays where toJSON p = A.object $ catMaybes [ ("containerQueryHighlightConfigs" A..=) <$> Just (pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs p) ] instance Command POverlaySetShowContainerQueryOverlays where type CommandResponse POverlaySetShowContainerQueryOverlays = () commandName _ = "Overlay.setShowContainerQueryOverlays" fromJSON = const . A.Success . const () -- | Requests that backend shows paint rectangles -- | Parameters of the 'Overlay.setShowPaintRects' command. data POverlaySetShowPaintRects = POverlaySetShowPaintRects { -- | True for showing paint rectangles pOverlaySetShowPaintRectsResult :: Bool } deriving (Eq, Show) pOverlaySetShowPaintRects {- -- | True for showing paint rectangles -} :: Bool -> POverlaySetShowPaintRects pOverlaySetShowPaintRects arg_pOverlaySetShowPaintRectsResult = POverlaySetShowPaintRects arg_pOverlaySetShowPaintRectsResult instance ToJSON POverlaySetShowPaintRects where toJSON p = A.object $ catMaybes [ ("result" A..=) <$> Just (pOverlaySetShowPaintRectsResult p) ] instance Command POverlaySetShowPaintRects where type CommandResponse POverlaySetShowPaintRects = () commandName _ = "Overlay.setShowPaintRects" fromJSON = const . A.Success . const () -- | Requests that backend shows layout shift regions -- | Parameters of the 'Overlay.setShowLayoutShiftRegions' command. data POverlaySetShowLayoutShiftRegions = POverlaySetShowLayoutShiftRegions { -- | True for showing layout shift regions pOverlaySetShowLayoutShiftRegionsResult :: Bool } deriving (Eq, Show) pOverlaySetShowLayoutShiftRegions {- -- | True for showing layout shift regions -} :: Bool -> POverlaySetShowLayoutShiftRegions pOverlaySetShowLayoutShiftRegions arg_pOverlaySetShowLayoutShiftRegionsResult = POverlaySetShowLayoutShiftRegions arg_pOverlaySetShowLayoutShiftRegionsResult instance ToJSON POverlaySetShowLayoutShiftRegions where toJSON p = A.object $ catMaybes [ ("result" A..=) <$> Just (pOverlaySetShowLayoutShiftRegionsResult p) ] instance Command POverlaySetShowLayoutShiftRegions where type CommandResponse POverlaySetShowLayoutShiftRegions = () commandName _ = "Overlay.setShowLayoutShiftRegions" fromJSON = const . A.Success . const () -- | Requests that backend shows scroll bottleneck rects -- | Parameters of the 'Overlay.setShowScrollBottleneckRects' command. data POverlaySetShowScrollBottleneckRects = POverlaySetShowScrollBottleneckRects { -- | True for showing scroll bottleneck rects pOverlaySetShowScrollBottleneckRectsShow :: Bool } deriving (Eq, Show) pOverlaySetShowScrollBottleneckRects {- -- | True for showing scroll bottleneck rects -} :: Bool -> POverlaySetShowScrollBottleneckRects pOverlaySetShowScrollBottleneckRects arg_pOverlaySetShowScrollBottleneckRectsShow = POverlaySetShowScrollBottleneckRects arg_pOverlaySetShowScrollBottleneckRectsShow instance ToJSON POverlaySetShowScrollBottleneckRects where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowScrollBottleneckRectsShow p) ] instance Command POverlaySetShowScrollBottleneckRects where type CommandResponse POverlaySetShowScrollBottleneckRects = () commandName _ = "Overlay.setShowScrollBottleneckRects" fromJSON = const . A.Success . const () -- | Request that backend shows an overlay with web vital metrics. -- | Parameters of the 'Overlay.setShowWebVitals' command. data POverlaySetShowWebVitals = POverlaySetShowWebVitals { pOverlaySetShowWebVitalsShow :: Bool } deriving (Eq, Show) pOverlaySetShowWebVitals :: Bool -> POverlaySetShowWebVitals pOverlaySetShowWebVitals arg_pOverlaySetShowWebVitalsShow = POverlaySetShowWebVitals arg_pOverlaySetShowWebVitalsShow instance ToJSON POverlaySetShowWebVitals where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowWebVitalsShow p) ] instance Command POverlaySetShowWebVitals where type CommandResponse POverlaySetShowWebVitals = () commandName _ = "Overlay.setShowWebVitals" fromJSON = const . A.Success . const () -- | Paints viewport size upon main frame resize. -- | Parameters of the 'Overlay.setShowViewportSizeOnResize' command. data POverlaySetShowViewportSizeOnResize = POverlaySetShowViewportSizeOnResize { -- | Whether to paint size or not. pOverlaySetShowViewportSizeOnResizeShow :: Bool } deriving (Eq, Show) pOverlaySetShowViewportSizeOnResize {- -- | Whether to paint size or not. -} :: Bool -> POverlaySetShowViewportSizeOnResize pOverlaySetShowViewportSizeOnResize arg_pOverlaySetShowViewportSizeOnResizeShow = POverlaySetShowViewportSizeOnResize arg_pOverlaySetShowViewportSizeOnResizeShow instance ToJSON POverlaySetShowViewportSizeOnResize where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowViewportSizeOnResizeShow p) ] instance Command POverlaySetShowViewportSizeOnResize where type CommandResponse POverlaySetShowViewportSizeOnResize = () commandName _ = "Overlay.setShowViewportSizeOnResize" fromJSON = const . A.Success . const () -- | Add a dual screen device hinge -- | Parameters of the 'Overlay.setShowHinge' command. data POverlaySetShowHinge = POverlaySetShowHinge { | hinge data , null means hideHinge pOverlaySetShowHingeHingeConfig :: Maybe OverlayHingeConfig } deriving (Eq, Show) pOverlaySetShowHinge :: POverlaySetShowHinge pOverlaySetShowHinge = POverlaySetShowHinge Nothing instance ToJSON POverlaySetShowHinge where toJSON p = A.object $ catMaybes [ ("hingeConfig" A..=) <$> (pOverlaySetShowHingeHingeConfig p) ] instance Command POverlaySetShowHinge where type CommandResponse POverlaySetShowHinge = () commandName _ = "Overlay.setShowHinge" fromJSON = const . A.Success . const () -- | Show elements in isolation mode with overlays. | Parameters of the ' Overlay.setShowIsolatedElements ' command . data POverlaySetShowIsolatedElements = POverlaySetShowIsolatedElements { -- | An array of node identifiers and descriptors for the highlight appearance. pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs :: [OverlayIsolatedElementHighlightConfig] } deriving (Eq, Show) pOverlaySetShowIsolatedElements {- -- | An array of node identifiers and descriptors for the highlight appearance. -} :: [OverlayIsolatedElementHighlightConfig] -> POverlaySetShowIsolatedElements pOverlaySetShowIsolatedElements arg_pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs = POverlaySetShowIsolatedElements arg_pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs instance ToJSON POverlaySetShowIsolatedElements where toJSON p = A.object $ catMaybes [ ("isolatedElementHighlightConfigs" A..=) <$> Just (pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs p) ] instance Command POverlaySetShowIsolatedElements where type CommandResponse POverlaySetShowIsolatedElements = () commandName _ = "Overlay.setShowIsolatedElements" fromJSON = const . A.Success . const ()
null
https://raw.githubusercontent.com/arsalan0c/cdp-hs/f946d706485b0dd16360a753321c46d6f098649d/src/CDP/Domains/Overlay.hs
haskell
# LANGUAGE OverloadedStrings, RecordWildCards, TupleSections # | = Overlay This domain provides various functionality related to drawing atop the inspected page. | Type 'Overlay.SourceOrderConfig'. Configuration data for drawing the source order of an elements children. | the color to outline the givent element in. | the color to outline the child elements in. | Type 'Overlay.GridHighlightConfig'. Configuration data for the highlighting of Grid elements. | Whether the extension lines from grid cells to the rulers should be shown (default: false). | Show Positive line number labels (default: false). | Show Negative line number labels (default: false). | Show area name labels (default: false). | Show line name labels (default: false). | Show track size labels (default: false). | The grid container border highlight color (default: transparent). | The row line color (default: transparent). | The column line color (default: transparent). | Whether the grid border is dashed (default: false). | Whether row lines are dashed (default: false). | Whether column lines are dashed (default: false). | The row gap highlight fill color (default: transparent). | The row gap hatching fill color (default: transparent). | The column gap highlight fill color (default: transparent). | The column gap hatching fill color (default: transparent). | The named grid areas border color (Default: transparent). | The grid container background color (Default: transparent). | Type 'Overlay.FlexContainerHighlightConfig'. | The style of the container border | The style of the separator between lines | The style of the separator between items | Style of content-distribution space on the main axis (justify-content). | Style of content-distribution space on the cross axis (align-content). | Style of empty space caused by row gaps (gap/row-gap). | Style of empty space caused by columns gaps (gap/column-gap). | Style of the self-alignment line (align-items). | Type 'Overlay.FlexItemHighlightConfig'. | Style of the box representing the item's base size | Style of the border around the box representing the item's base size | Style of the arrow representing if the item grew or shrank Style information for drawing a line. | The color of the line (default: transparent) | The line pattern (default: solid) Style information for drawing a box. | The background color for the box (default: transparent) | The hatching color for the box (default: transparent) | Type 'Overlay.HighlightConfig'. Configuration data for the highlighting of page elements. | Whether the node info tooltip should be shown (default: false). | Whether the node styles in the tooltip (default: false). | Whether the rulers should be shown (default: false). | Whether the a11y info should be shown (default: true). | Whether the extension lines from node to the rulers should be shown (default: false). | The content box highlight fill color (default: transparent). | The padding highlight fill color (default: transparent). | The border highlight fill color (default: transparent). | The margin highlight fill color (default: transparent). | The event target element highlight fill color (default: transparent). | The shape outside fill color (default: transparent). | The shape margin fill color (default: transparent). | The grid layout color (default: transparent). | The color format used to format color styles (default: hex). | The grid layout highlight configuration (default: all transparent). | The flex container highlight configuration (default: all transparent). | The flex item highlight configuration (default: all transparent). | The contrast algorithm to use for the contrast ratio (default: aa). | The container query container highlight configuration (default: all transparent). | Type 'Overlay.ColorFormat'. | Type 'Overlay.GridNodeHighlightConfig'. Configurations for Persistent Grid Highlight | A descriptor for the highlight appearance. | Identifier of the node to highlight. | Type 'Overlay.FlexNodeHighlightConfig'. | A descriptor for the highlight appearance of flex containers. | Identifier of the node to highlight. | Type 'Overlay.ScrollSnapContainerHighlightConfig'. | The style of the snapport border (default: transparent) | The style of the snap area border (default: transparent) | The margin highlight fill color (default: transparent). | The padding highlight fill color (default: transparent). | Type 'Overlay.ScrollSnapHighlightConfig'. | A descriptor for the highlight appearance of scroll snap containers. | Identifier of the node to highlight. Configuration for dual screen hinge | A rectangle represent hinge | The content box highlight fill color (default: a dark color). | The content box highlight outline color (default: transparent). | Type 'Overlay.ContainerQueryHighlightConfig'. | A descriptor for the highlight appearance of container query containers. | Identifier of the container node to highlight. | Type 'Overlay.ContainerQueryContainerHighlightConfig'. | The style of the container border. | The style of the descendants' borders. | Type 'Overlay.IsolatedElementHighlightConfig'. | A descriptor for the highlight appearance of an element in isolation mode. | Identifier of the isolated element to highlight. | Type 'Overlay.IsolationModeHighlightConfig'. | The fill color of the resizers (default: transparent). | The fill color for resizer handles (default: transparent). | The fill color for the mask covering non-isolated elements (default: transparent). | Type 'Overlay.InspectMode'. | Type of the 'Overlay.inspectNodeRequested' event. | Id of the node to inspect. | Type of the 'Overlay.nodeHighlightRequested' event. | Type of the 'Overlay.screenshotRequested' event. | Viewport to capture, in device independent pixels (dip). | Type of the 'Overlay.inspectModeCanceled' event. | Disables domain notifications. | Parameters of the 'Overlay.disable' command. | Enables domain notifications. | Parameters of the 'Overlay.enable' command. | For testing. | Parameters of the 'Overlay.getHighlightObjectForTest' command. | Id of the node to get highlight object for. | Whether to include distance info. | Whether to include style info. | The color format to get config with (default: hex). | Whether to show accessibility info (default: true). -- | Id of the node to get highlight object for. | Highlight data for the node. | For Persistent Grid testing. | Parameters of the 'Overlay.getGridHighlightObjectsForTest' command. | Ids of the node to get highlight object for. -- | Ids of the node to get highlight object for. | Grid Highlight data for the node ids provided. | For Source Order Viewer testing. | Parameters of the 'Overlay.getSourceOrderHighlightObjectForTest' command. | Id of the node to highlight. -- | Id of the node to highlight. | Source order highlight data for the node id provided. | Hides any highlight. | Parameters of the 'Overlay.hideHighlight' command. objectId must be specified. | Parameters of the 'Overlay.highlightNode' command. | A descriptor for the highlight appearance. | Identifier of the node to highlight. | Identifier of the backend node to highlight. | JavaScript object id of the node to be highlighted. | Selectors to highlight relevant nodes. -- | A descriptor for the highlight appearance. | Highlights given quad. Coordinates are absolute with respect to the main frame viewport. | Parameters of the 'Overlay.highlightQuad' command. | Quad to highlight | The highlight fill color (default: transparent). | The highlight outline color (default: transparent). -- | Quad to highlight | Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. | Parameters of the 'Overlay.highlightRect' command. | X coordinate | Y coordinate | Rectangle width | Rectangle height | The highlight fill color (default: transparent). | The highlight outline color (default: transparent). -- | X coordinate -- | Y coordinate -- | Rectangle width -- | Rectangle height | Parameters of the 'Overlay.highlightSourceOrder' command. | A descriptor for the appearance of the overlay drawing. | Identifier of the node to highlight. | Identifier of the backend node to highlight. | JavaScript object id of the node to be highlighted. -- | A descriptor for the appearance of the overlay drawing. | Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. Backend then generates 'inspectNodeRequested' event upon element selection. | Set an inspection mode. == false`. -- | Set an inspection mode. | Highlights owner element of all frames detected to be ads. | Parameters of the 'Overlay.setShowAdHighlights' command. | True for showing ad highlights -- | True for showing ad highlights | Parameters of the 'Overlay.setPausedInDebuggerMessage' command. | The message to display, also triggers resume and step over controls. | Requests that backend shows debug borders on layers | True for showing debug borders -- | True for showing debug borders | Requests that backend shows the FPS counter | Parameters of the 'Overlay.setShowFPSCounter' command. | True for showing the FPS counter -- | True for showing the FPS counter | Highlight multiple elements with the CSS Grid overlay. | Parameters of the 'Overlay.setShowGridOverlays' command. | An array of node identifiers and descriptors for the highlight appearance. -- | An array of node identifiers and descriptors for the highlight appearance. | Parameters of the 'Overlay.setShowFlexOverlays' command. | An array of node identifiers and descriptors for the highlight appearance. -- | An array of node identifiers and descriptors for the highlight appearance. | Parameters of the 'Overlay.setShowScrollSnapOverlays' command. | An array of node identifiers and descriptors for the highlight appearance. -- | An array of node identifiers and descriptors for the highlight appearance. | Parameters of the 'Overlay.setShowContainerQueryOverlays' command. | An array of node identifiers and descriptors for the highlight appearance. -- | An array of node identifiers and descriptors for the highlight appearance. | Requests that backend shows paint rectangles | Parameters of the 'Overlay.setShowPaintRects' command. | True for showing paint rectangles -- | True for showing paint rectangles | Requests that backend shows layout shift regions | Parameters of the 'Overlay.setShowLayoutShiftRegions' command. | True for showing layout shift regions -- | True for showing layout shift regions | Requests that backend shows scroll bottleneck rects | Parameters of the 'Overlay.setShowScrollBottleneckRects' command. | True for showing scroll bottleneck rects -- | True for showing scroll bottleneck rects | Request that backend shows an overlay with web vital metrics. | Parameters of the 'Overlay.setShowWebVitals' command. | Paints viewport size upon main frame resize. | Parameters of the 'Overlay.setShowViewportSizeOnResize' command. | Whether to paint size or not. -- | Whether to paint size or not. | Add a dual screen device hinge | Parameters of the 'Overlay.setShowHinge' command. | Show elements in isolation mode with overlays. | An array of node identifiers and descriptors for the highlight appearance. -- | An array of node identifiers and descriptors for the highlight appearance.
# LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleContexts # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # # LANGUAGE TypeFamilies # module CDP.Domains.Overlay (module CDP.Domains.Overlay) where import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.Loops import Control.Monad.Trans (liftIO) import qualified Data.Map as M import Data.Maybe import Data.Functor.Identity import Data.String import qualified Data.Text as T import qualified Data.List as List import qualified Data.Text.IO as TI import qualified Data.Vector as V import Data.Aeson.Types (Parser(..)) import Data.Aeson (FromJSON (..), ToJSON (..), (.:), (.:?), (.=), (.!=), (.:!)) import qualified Data.Aeson as A import qualified Network.HTTP.Simple as Http import qualified Network.URI as Uri import qualified Network.WebSockets as WS import Control.Concurrent import qualified Data.ByteString.Lazy as BS import qualified Data.Map as Map import Data.Proxy import System.Random import GHC.Generics import Data.Char import Data.Default import CDP.Internal.Utils import CDP.Domains.DOMPageNetworkEmulationSecurity as DOMPageNetworkEmulationSecurity import CDP.Domains.Runtime as Runtime data OverlaySourceOrderConfig = OverlaySourceOrderConfig { overlaySourceOrderConfigParentOutlineColor :: DOMPageNetworkEmulationSecurity.DOMRGBA, overlaySourceOrderConfigChildOutlineColor :: DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlaySourceOrderConfig where parseJSON = A.withObject "OverlaySourceOrderConfig" $ \o -> OverlaySourceOrderConfig <$> o A..: "parentOutlineColor" <*> o A..: "childOutlineColor" instance ToJSON OverlaySourceOrderConfig where toJSON p = A.object $ catMaybes [ ("parentOutlineColor" A..=) <$> Just (overlaySourceOrderConfigParentOutlineColor p), ("childOutlineColor" A..=) <$> Just (overlaySourceOrderConfigChildOutlineColor p) ] data OverlayGridHighlightConfig = OverlayGridHighlightConfig { overlayGridHighlightConfigShowGridExtensionLines :: Maybe Bool, overlayGridHighlightConfigShowPositiveLineNumbers :: Maybe Bool, overlayGridHighlightConfigShowNegativeLineNumbers :: Maybe Bool, overlayGridHighlightConfigShowAreaNames :: Maybe Bool, overlayGridHighlightConfigShowLineNames :: Maybe Bool, overlayGridHighlightConfigShowTrackSizes :: Maybe Bool, overlayGridHighlightConfigGridBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigRowLineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigColumnLineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigGridBorderDash :: Maybe Bool, overlayGridHighlightConfigRowLineDash :: Maybe Bool, overlayGridHighlightConfigColumnLineDash :: Maybe Bool, overlayGridHighlightConfigRowGapColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigRowHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigColumnGapColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigColumnHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigAreaBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayGridHighlightConfigGridBackgroundColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayGridHighlightConfig where parseJSON = A.withObject "OverlayGridHighlightConfig" $ \o -> OverlayGridHighlightConfig <$> o A..:? "showGridExtensionLines" <*> o A..:? "showPositiveLineNumbers" <*> o A..:? "showNegativeLineNumbers" <*> o A..:? "showAreaNames" <*> o A..:? "showLineNames" <*> o A..:? "showTrackSizes" <*> o A..:? "gridBorderColor" <*> o A..:? "rowLineColor" <*> o A..:? "columnLineColor" <*> o A..:? "gridBorderDash" <*> o A..:? "rowLineDash" <*> o A..:? "columnLineDash" <*> o A..:? "rowGapColor" <*> o A..:? "rowHatchColor" <*> o A..:? "columnGapColor" <*> o A..:? "columnHatchColor" <*> o A..:? "areaBorderColor" <*> o A..:? "gridBackgroundColor" instance ToJSON OverlayGridHighlightConfig where toJSON p = A.object $ catMaybes [ ("showGridExtensionLines" A..=) <$> (overlayGridHighlightConfigShowGridExtensionLines p), ("showPositiveLineNumbers" A..=) <$> (overlayGridHighlightConfigShowPositiveLineNumbers p), ("showNegativeLineNumbers" A..=) <$> (overlayGridHighlightConfigShowNegativeLineNumbers p), ("showAreaNames" A..=) <$> (overlayGridHighlightConfigShowAreaNames p), ("showLineNames" A..=) <$> (overlayGridHighlightConfigShowLineNames p), ("showTrackSizes" A..=) <$> (overlayGridHighlightConfigShowTrackSizes p), ("gridBorderColor" A..=) <$> (overlayGridHighlightConfigGridBorderColor p), ("rowLineColor" A..=) <$> (overlayGridHighlightConfigRowLineColor p), ("columnLineColor" A..=) <$> (overlayGridHighlightConfigColumnLineColor p), ("gridBorderDash" A..=) <$> (overlayGridHighlightConfigGridBorderDash p), ("rowLineDash" A..=) <$> (overlayGridHighlightConfigRowLineDash p), ("columnLineDash" A..=) <$> (overlayGridHighlightConfigColumnLineDash p), ("rowGapColor" A..=) <$> (overlayGridHighlightConfigRowGapColor p), ("rowHatchColor" A..=) <$> (overlayGridHighlightConfigRowHatchColor p), ("columnGapColor" A..=) <$> (overlayGridHighlightConfigColumnGapColor p), ("columnHatchColor" A..=) <$> (overlayGridHighlightConfigColumnHatchColor p), ("areaBorderColor" A..=) <$> (overlayGridHighlightConfigAreaBorderColor p), ("gridBackgroundColor" A..=) <$> (overlayGridHighlightConfigGridBackgroundColor p) ] Configuration data for the highlighting of Flex container elements . data OverlayFlexContainerHighlightConfig = OverlayFlexContainerHighlightConfig { overlayFlexContainerHighlightConfigContainerBorder :: Maybe OverlayLineStyle, overlayFlexContainerHighlightConfigLineSeparator :: Maybe OverlayLineStyle, overlayFlexContainerHighlightConfigItemSeparator :: Maybe OverlayLineStyle, overlayFlexContainerHighlightConfigMainDistributedSpace :: Maybe OverlayBoxStyle, overlayFlexContainerHighlightConfigCrossDistributedSpace :: Maybe OverlayBoxStyle, overlayFlexContainerHighlightConfigRowGapSpace :: Maybe OverlayBoxStyle, overlayFlexContainerHighlightConfigColumnGapSpace :: Maybe OverlayBoxStyle, overlayFlexContainerHighlightConfigCrossAlignment :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayFlexContainerHighlightConfig where parseJSON = A.withObject "OverlayFlexContainerHighlightConfig" $ \o -> OverlayFlexContainerHighlightConfig <$> o A..:? "containerBorder" <*> o A..:? "lineSeparator" <*> o A..:? "itemSeparator" <*> o A..:? "mainDistributedSpace" <*> o A..:? "crossDistributedSpace" <*> o A..:? "rowGapSpace" <*> o A..:? "columnGapSpace" <*> o A..:? "crossAlignment" instance ToJSON OverlayFlexContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerBorder" A..=) <$> (overlayFlexContainerHighlightConfigContainerBorder p), ("lineSeparator" A..=) <$> (overlayFlexContainerHighlightConfigLineSeparator p), ("itemSeparator" A..=) <$> (overlayFlexContainerHighlightConfigItemSeparator p), ("mainDistributedSpace" A..=) <$> (overlayFlexContainerHighlightConfigMainDistributedSpace p), ("crossDistributedSpace" A..=) <$> (overlayFlexContainerHighlightConfigCrossDistributedSpace p), ("rowGapSpace" A..=) <$> (overlayFlexContainerHighlightConfigRowGapSpace p), ("columnGapSpace" A..=) <$> (overlayFlexContainerHighlightConfigColumnGapSpace p), ("crossAlignment" A..=) <$> (overlayFlexContainerHighlightConfigCrossAlignment p) ] Configuration data for the highlighting of Flex item elements . data OverlayFlexItemHighlightConfig = OverlayFlexItemHighlightConfig { overlayFlexItemHighlightConfigBaseSizeBox :: Maybe OverlayBoxStyle, overlayFlexItemHighlightConfigBaseSizeBorder :: Maybe OverlayLineStyle, overlayFlexItemHighlightConfigFlexibilityArrow :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayFlexItemHighlightConfig where parseJSON = A.withObject "OverlayFlexItemHighlightConfig" $ \o -> OverlayFlexItemHighlightConfig <$> o A..:? "baseSizeBox" <*> o A..:? "baseSizeBorder" <*> o A..:? "flexibilityArrow" instance ToJSON OverlayFlexItemHighlightConfig where toJSON p = A.object $ catMaybes [ ("baseSizeBox" A..=) <$> (overlayFlexItemHighlightConfigBaseSizeBox p), ("baseSizeBorder" A..=) <$> (overlayFlexItemHighlightConfigBaseSizeBorder p), ("flexibilityArrow" A..=) <$> (overlayFlexItemHighlightConfigFlexibilityArrow p) ] | Type ' Overlay . ' . data OverlayLineStylePattern = OverlayLineStylePatternDashed | OverlayLineStylePatternDotted deriving (Ord, Eq, Show, Read) instance FromJSON OverlayLineStylePattern where parseJSON = A.withText "OverlayLineStylePattern" $ \v -> case v of "dashed" -> pure OverlayLineStylePatternDashed "dotted" -> pure OverlayLineStylePatternDotted "_" -> fail "failed to parse OverlayLineStylePattern" instance ToJSON OverlayLineStylePattern where toJSON v = A.String $ case v of OverlayLineStylePatternDashed -> "dashed" OverlayLineStylePatternDotted -> "dotted" data OverlayLineStyle = OverlayLineStyle { overlayLineStyleColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayLineStylePattern :: Maybe OverlayLineStylePattern } deriving (Eq, Show) instance FromJSON OverlayLineStyle where parseJSON = A.withObject "OverlayLineStyle" $ \o -> OverlayLineStyle <$> o A..:? "color" <*> o A..:? "pattern" instance ToJSON OverlayLineStyle where toJSON p = A.object $ catMaybes [ ("color" A..=) <$> (overlayLineStyleColor p), ("pattern" A..=) <$> (overlayLineStylePattern p) ] | Type ' Overlay . BoxStyle ' . data OverlayBoxStyle = OverlayBoxStyle { overlayBoxStyleFillColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayBoxStyleHatchColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayBoxStyle where parseJSON = A.withObject "OverlayBoxStyle" $ \o -> OverlayBoxStyle <$> o A..:? "fillColor" <*> o A..:? "hatchColor" instance ToJSON OverlayBoxStyle where toJSON p = A.object $ catMaybes [ ("fillColor" A..=) <$> (overlayBoxStyleFillColor p), ("hatchColor" A..=) <$> (overlayBoxStyleHatchColor p) ] | Type ' Overlay . ContrastAlgorithm ' . data OverlayContrastAlgorithm = OverlayContrastAlgorithmAa | OverlayContrastAlgorithmAaa | OverlayContrastAlgorithmApca deriving (Ord, Eq, Show, Read) instance FromJSON OverlayContrastAlgorithm where parseJSON = A.withText "OverlayContrastAlgorithm" $ \v -> case v of "aa" -> pure OverlayContrastAlgorithmAa "aaa" -> pure OverlayContrastAlgorithmAaa "apca" -> pure OverlayContrastAlgorithmApca "_" -> fail "failed to parse OverlayContrastAlgorithm" instance ToJSON OverlayContrastAlgorithm where toJSON v = A.String $ case v of OverlayContrastAlgorithmAa -> "aa" OverlayContrastAlgorithmAaa -> "aaa" OverlayContrastAlgorithmApca -> "apca" data OverlayHighlightConfig = OverlayHighlightConfig { overlayHighlightConfigShowInfo :: Maybe Bool, overlayHighlightConfigShowStyles :: Maybe Bool, overlayHighlightConfigShowRulers :: Maybe Bool, overlayHighlightConfigShowAccessibilityInfo :: Maybe Bool, overlayHighlightConfigShowExtensionLines :: Maybe Bool, overlayHighlightConfigContentColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigPaddingColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigBorderColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigEventTargetColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigShapeColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigShapeMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigCssGridColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHighlightConfigColorFormat :: Maybe OverlayColorFormat, overlayHighlightConfigGridHighlightConfig :: Maybe OverlayGridHighlightConfig, overlayHighlightConfigFlexContainerHighlightConfig :: Maybe OverlayFlexContainerHighlightConfig, overlayHighlightConfigFlexItemHighlightConfig :: Maybe OverlayFlexItemHighlightConfig, overlayHighlightConfigContrastAlgorithm :: Maybe OverlayContrastAlgorithm, overlayHighlightConfigContainerQueryContainerHighlightConfig :: Maybe OverlayContainerQueryContainerHighlightConfig } deriving (Eq, Show) instance FromJSON OverlayHighlightConfig where parseJSON = A.withObject "OverlayHighlightConfig" $ \o -> OverlayHighlightConfig <$> o A..:? "showInfo" <*> o A..:? "showStyles" <*> o A..:? "showRulers" <*> o A..:? "showAccessibilityInfo" <*> o A..:? "showExtensionLines" <*> o A..:? "contentColor" <*> o A..:? "paddingColor" <*> o A..:? "borderColor" <*> o A..:? "marginColor" <*> o A..:? "eventTargetColor" <*> o A..:? "shapeColor" <*> o A..:? "shapeMarginColor" <*> o A..:? "cssGridColor" <*> o A..:? "colorFormat" <*> o A..:? "gridHighlightConfig" <*> o A..:? "flexContainerHighlightConfig" <*> o A..:? "flexItemHighlightConfig" <*> o A..:? "contrastAlgorithm" <*> o A..:? "containerQueryContainerHighlightConfig" instance ToJSON OverlayHighlightConfig where toJSON p = A.object $ catMaybes [ ("showInfo" A..=) <$> (overlayHighlightConfigShowInfo p), ("showStyles" A..=) <$> (overlayHighlightConfigShowStyles p), ("showRulers" A..=) <$> (overlayHighlightConfigShowRulers p), ("showAccessibilityInfo" A..=) <$> (overlayHighlightConfigShowAccessibilityInfo p), ("showExtensionLines" A..=) <$> (overlayHighlightConfigShowExtensionLines p), ("contentColor" A..=) <$> (overlayHighlightConfigContentColor p), ("paddingColor" A..=) <$> (overlayHighlightConfigPaddingColor p), ("borderColor" A..=) <$> (overlayHighlightConfigBorderColor p), ("marginColor" A..=) <$> (overlayHighlightConfigMarginColor p), ("eventTargetColor" A..=) <$> (overlayHighlightConfigEventTargetColor p), ("shapeColor" A..=) <$> (overlayHighlightConfigShapeColor p), ("shapeMarginColor" A..=) <$> (overlayHighlightConfigShapeMarginColor p), ("cssGridColor" A..=) <$> (overlayHighlightConfigCssGridColor p), ("colorFormat" A..=) <$> (overlayHighlightConfigColorFormat p), ("gridHighlightConfig" A..=) <$> (overlayHighlightConfigGridHighlightConfig p), ("flexContainerHighlightConfig" A..=) <$> (overlayHighlightConfigFlexContainerHighlightConfig p), ("flexItemHighlightConfig" A..=) <$> (overlayHighlightConfigFlexItemHighlightConfig p), ("contrastAlgorithm" A..=) <$> (overlayHighlightConfigContrastAlgorithm p), ("containerQueryContainerHighlightConfig" A..=) <$> (overlayHighlightConfigContainerQueryContainerHighlightConfig p) ] data OverlayColorFormat = OverlayColorFormatRgb | OverlayColorFormatHsl | OverlayColorFormatHwb | OverlayColorFormatHex deriving (Ord, Eq, Show, Read) instance FromJSON OverlayColorFormat where parseJSON = A.withText "OverlayColorFormat" $ \v -> case v of "rgb" -> pure OverlayColorFormatRgb "hsl" -> pure OverlayColorFormatHsl "hwb" -> pure OverlayColorFormatHwb "hex" -> pure OverlayColorFormatHex "_" -> fail "failed to parse OverlayColorFormat" instance ToJSON OverlayColorFormat where toJSON v = A.String $ case v of OverlayColorFormatRgb -> "rgb" OverlayColorFormatHsl -> "hsl" OverlayColorFormatHwb -> "hwb" OverlayColorFormatHex -> "hex" data OverlayGridNodeHighlightConfig = OverlayGridNodeHighlightConfig { overlayGridNodeHighlightConfigGridHighlightConfig :: OverlayGridHighlightConfig, overlayGridNodeHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayGridNodeHighlightConfig where parseJSON = A.withObject "OverlayGridNodeHighlightConfig" $ \o -> OverlayGridNodeHighlightConfig <$> o A..: "gridHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayGridNodeHighlightConfig where toJSON p = A.object $ catMaybes [ ("gridHighlightConfig" A..=) <$> Just (overlayGridNodeHighlightConfigGridHighlightConfig p), ("nodeId" A..=) <$> Just (overlayGridNodeHighlightConfigNodeId p) ] data OverlayFlexNodeHighlightConfig = OverlayFlexNodeHighlightConfig { overlayFlexNodeHighlightConfigFlexContainerHighlightConfig :: OverlayFlexContainerHighlightConfig, overlayFlexNodeHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayFlexNodeHighlightConfig where parseJSON = A.withObject "OverlayFlexNodeHighlightConfig" $ \o -> OverlayFlexNodeHighlightConfig <$> o A..: "flexContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayFlexNodeHighlightConfig where toJSON p = A.object $ catMaybes [ ("flexContainerHighlightConfig" A..=) <$> Just (overlayFlexNodeHighlightConfigFlexContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayFlexNodeHighlightConfigNodeId p) ] data OverlayScrollSnapContainerHighlightConfig = OverlayScrollSnapContainerHighlightConfig { overlayScrollSnapContainerHighlightConfigSnapportBorder :: Maybe OverlayLineStyle, overlayScrollSnapContainerHighlightConfigSnapAreaBorder :: Maybe OverlayLineStyle, overlayScrollSnapContainerHighlightConfigScrollMarginColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayScrollSnapContainerHighlightConfigScrollPaddingColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayScrollSnapContainerHighlightConfig where parseJSON = A.withObject "OverlayScrollSnapContainerHighlightConfig" $ \o -> OverlayScrollSnapContainerHighlightConfig <$> o A..:? "snapportBorder" <*> o A..:? "snapAreaBorder" <*> o A..:? "scrollMarginColor" <*> o A..:? "scrollPaddingColor" instance ToJSON OverlayScrollSnapContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("snapportBorder" A..=) <$> (overlayScrollSnapContainerHighlightConfigSnapportBorder p), ("snapAreaBorder" A..=) <$> (overlayScrollSnapContainerHighlightConfigSnapAreaBorder p), ("scrollMarginColor" A..=) <$> (overlayScrollSnapContainerHighlightConfigScrollMarginColor p), ("scrollPaddingColor" A..=) <$> (overlayScrollSnapContainerHighlightConfigScrollPaddingColor p) ] data OverlayScrollSnapHighlightConfig = OverlayScrollSnapHighlightConfig { overlayScrollSnapHighlightConfigScrollSnapContainerHighlightConfig :: OverlayScrollSnapContainerHighlightConfig, overlayScrollSnapHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayScrollSnapHighlightConfig where parseJSON = A.withObject "OverlayScrollSnapHighlightConfig" $ \o -> OverlayScrollSnapHighlightConfig <$> o A..: "scrollSnapContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayScrollSnapHighlightConfig where toJSON p = A.object $ catMaybes [ ("scrollSnapContainerHighlightConfig" A..=) <$> Just (overlayScrollSnapHighlightConfigScrollSnapContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayScrollSnapHighlightConfigNodeId p) ] | Type ' Overlay . HingeConfig ' . data OverlayHingeConfig = OverlayHingeConfig { overlayHingeConfigRect :: DOMPageNetworkEmulationSecurity.DOMRect, overlayHingeConfigContentColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayHingeConfigOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayHingeConfig where parseJSON = A.withObject "OverlayHingeConfig" $ \o -> OverlayHingeConfig <$> o A..: "rect" <*> o A..:? "contentColor" <*> o A..:? "outlineColor" instance ToJSON OverlayHingeConfig where toJSON p = A.object $ catMaybes [ ("rect" A..=) <$> Just (overlayHingeConfigRect p), ("contentColor" A..=) <$> (overlayHingeConfigContentColor p), ("outlineColor" A..=) <$> (overlayHingeConfigOutlineColor p) ] data OverlayContainerQueryHighlightConfig = OverlayContainerQueryHighlightConfig { overlayContainerQueryHighlightConfigContainerQueryContainerHighlightConfig :: OverlayContainerQueryContainerHighlightConfig, overlayContainerQueryHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayContainerQueryHighlightConfig where parseJSON = A.withObject "OverlayContainerQueryHighlightConfig" $ \o -> OverlayContainerQueryHighlightConfig <$> o A..: "containerQueryContainerHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayContainerQueryHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerQueryContainerHighlightConfig" A..=) <$> Just (overlayContainerQueryHighlightConfigContainerQueryContainerHighlightConfig p), ("nodeId" A..=) <$> Just (overlayContainerQueryHighlightConfigNodeId p) ] data OverlayContainerQueryContainerHighlightConfig = OverlayContainerQueryContainerHighlightConfig { overlayContainerQueryContainerHighlightConfigContainerBorder :: Maybe OverlayLineStyle, overlayContainerQueryContainerHighlightConfigDescendantBorder :: Maybe OverlayLineStyle } deriving (Eq, Show) instance FromJSON OverlayContainerQueryContainerHighlightConfig where parseJSON = A.withObject "OverlayContainerQueryContainerHighlightConfig" $ \o -> OverlayContainerQueryContainerHighlightConfig <$> o A..:? "containerBorder" <*> o A..:? "descendantBorder" instance ToJSON OverlayContainerQueryContainerHighlightConfig where toJSON p = A.object $ catMaybes [ ("containerBorder" A..=) <$> (overlayContainerQueryContainerHighlightConfigContainerBorder p), ("descendantBorder" A..=) <$> (overlayContainerQueryContainerHighlightConfigDescendantBorder p) ] data OverlayIsolatedElementHighlightConfig = OverlayIsolatedElementHighlightConfig { overlayIsolatedElementHighlightConfigIsolationModeHighlightConfig :: OverlayIsolationModeHighlightConfig, overlayIsolatedElementHighlightConfigNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayIsolatedElementHighlightConfig where parseJSON = A.withObject "OverlayIsolatedElementHighlightConfig" $ \o -> OverlayIsolatedElementHighlightConfig <$> o A..: "isolationModeHighlightConfig" <*> o A..: "nodeId" instance ToJSON OverlayIsolatedElementHighlightConfig where toJSON p = A.object $ catMaybes [ ("isolationModeHighlightConfig" A..=) <$> Just (overlayIsolatedElementHighlightConfigIsolationModeHighlightConfig p), ("nodeId" A..=) <$> Just (overlayIsolatedElementHighlightConfigNodeId p) ] data OverlayIsolationModeHighlightConfig = OverlayIsolationModeHighlightConfig { overlayIsolationModeHighlightConfigResizerColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayIsolationModeHighlightConfigResizerHandleColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, overlayIsolationModeHighlightConfigMaskColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) instance FromJSON OverlayIsolationModeHighlightConfig where parseJSON = A.withObject "OverlayIsolationModeHighlightConfig" $ \o -> OverlayIsolationModeHighlightConfig <$> o A..:? "resizerColor" <*> o A..:? "resizerHandleColor" <*> o A..:? "maskColor" instance ToJSON OverlayIsolationModeHighlightConfig where toJSON p = A.object $ catMaybes [ ("resizerColor" A..=) <$> (overlayIsolationModeHighlightConfigResizerColor p), ("resizerHandleColor" A..=) <$> (overlayIsolationModeHighlightConfigResizerHandleColor p), ("maskColor" A..=) <$> (overlayIsolationModeHighlightConfigMaskColor p) ] data OverlayInspectMode = OverlayInspectModeSearchForNode | OverlayInspectModeSearchForUAShadowDOM | OverlayInspectModeCaptureAreaScreenshot | OverlayInspectModeShowDistances | OverlayInspectModeNone deriving (Ord, Eq, Show, Read) instance FromJSON OverlayInspectMode where parseJSON = A.withText "OverlayInspectMode" $ \v -> case v of "searchForNode" -> pure OverlayInspectModeSearchForNode "searchForUAShadowDOM" -> pure OverlayInspectModeSearchForUAShadowDOM "captureAreaScreenshot" -> pure OverlayInspectModeCaptureAreaScreenshot "showDistances" -> pure OverlayInspectModeShowDistances "none" -> pure OverlayInspectModeNone "_" -> fail "failed to parse OverlayInspectMode" instance ToJSON OverlayInspectMode where toJSON v = A.String $ case v of OverlayInspectModeSearchForNode -> "searchForNode" OverlayInspectModeSearchForUAShadowDOM -> "searchForUAShadowDOM" OverlayInspectModeCaptureAreaScreenshot -> "captureAreaScreenshot" OverlayInspectModeShowDistances -> "showDistances" OverlayInspectModeNone -> "none" data OverlayInspectNodeRequested = OverlayInspectNodeRequested { overlayInspectNodeRequestedBackendNodeId :: DOMPageNetworkEmulationSecurity.DOMBackendNodeId } deriving (Eq, Show) instance FromJSON OverlayInspectNodeRequested where parseJSON = A.withObject "OverlayInspectNodeRequested" $ \o -> OverlayInspectNodeRequested <$> o A..: "backendNodeId" instance Event OverlayInspectNodeRequested where eventName _ = "Overlay.inspectNodeRequested" data OverlayNodeHighlightRequested = OverlayNodeHighlightRequested { overlayNodeHighlightRequestedNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) instance FromJSON OverlayNodeHighlightRequested where parseJSON = A.withObject "OverlayNodeHighlightRequested" $ \o -> OverlayNodeHighlightRequested <$> o A..: "nodeId" instance Event OverlayNodeHighlightRequested where eventName _ = "Overlay.nodeHighlightRequested" data OverlayScreenshotRequested = OverlayScreenshotRequested { overlayScreenshotRequestedViewport :: DOMPageNetworkEmulationSecurity.PageViewport } deriving (Eq, Show) instance FromJSON OverlayScreenshotRequested where parseJSON = A.withObject "OverlayScreenshotRequested" $ \o -> OverlayScreenshotRequested <$> o A..: "viewport" instance Event OverlayScreenshotRequested where eventName _ = "Overlay.screenshotRequested" data OverlayInspectModeCanceled = OverlayInspectModeCanceled deriving (Eq, Show, Read) instance FromJSON OverlayInspectModeCanceled where parseJSON _ = pure OverlayInspectModeCanceled instance Event OverlayInspectModeCanceled where eventName _ = "Overlay.inspectModeCanceled" data POverlayDisable = POverlayDisable deriving (Eq, Show) pOverlayDisable :: POverlayDisable pOverlayDisable = POverlayDisable instance ToJSON POverlayDisable where toJSON _ = A.Null instance Command POverlayDisable where type CommandResponse POverlayDisable = () commandName _ = "Overlay.disable" fromJSON = const . A.Success . const () data POverlayEnable = POverlayEnable deriving (Eq, Show) pOverlayEnable :: POverlayEnable pOverlayEnable = POverlayEnable instance ToJSON POverlayEnable where toJSON _ = A.Null instance Command POverlayEnable where type CommandResponse POverlayEnable = () commandName _ = "Overlay.enable" fromJSON = const . A.Success . const () data POverlayGetHighlightObjectForTest = POverlayGetHighlightObjectForTest { pOverlayGetHighlightObjectForTestNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId, pOverlayGetHighlightObjectForTestIncludeDistance :: Maybe Bool, pOverlayGetHighlightObjectForTestIncludeStyle :: Maybe Bool, pOverlayGetHighlightObjectForTestColorFormat :: Maybe OverlayColorFormat, pOverlayGetHighlightObjectForTestShowAccessibilityInfo :: Maybe Bool } deriving (Eq, Show) pOverlayGetHighlightObjectForTest :: DOMPageNetworkEmulationSecurity.DOMNodeId -> POverlayGetHighlightObjectForTest pOverlayGetHighlightObjectForTest arg_pOverlayGetHighlightObjectForTestNodeId = POverlayGetHighlightObjectForTest arg_pOverlayGetHighlightObjectForTestNodeId Nothing Nothing Nothing Nothing instance ToJSON POverlayGetHighlightObjectForTest where toJSON p = A.object $ catMaybes [ ("nodeId" A..=) <$> Just (pOverlayGetHighlightObjectForTestNodeId p), ("includeDistance" A..=) <$> (pOverlayGetHighlightObjectForTestIncludeDistance p), ("includeStyle" A..=) <$> (pOverlayGetHighlightObjectForTestIncludeStyle p), ("colorFormat" A..=) <$> (pOverlayGetHighlightObjectForTestColorFormat p), ("showAccessibilityInfo" A..=) <$> (pOverlayGetHighlightObjectForTestShowAccessibilityInfo p) ] data OverlayGetHighlightObjectForTest = OverlayGetHighlightObjectForTest { overlayGetHighlightObjectForTestHighlight :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetHighlightObjectForTest where parseJSON = A.withObject "OverlayGetHighlightObjectForTest" $ \o -> OverlayGetHighlightObjectForTest <$> o A..: "highlight" instance Command POverlayGetHighlightObjectForTest where type CommandResponse POverlayGetHighlightObjectForTest = OverlayGetHighlightObjectForTest commandName _ = "Overlay.getHighlightObjectForTest" data POverlayGetGridHighlightObjectsForTest = POverlayGetGridHighlightObjectsForTest { pOverlayGetGridHighlightObjectsForTestNodeIds :: [DOMPageNetworkEmulationSecurity.DOMNodeId] } deriving (Eq, Show) pOverlayGetGridHighlightObjectsForTest :: [DOMPageNetworkEmulationSecurity.DOMNodeId] -> POverlayGetGridHighlightObjectsForTest pOverlayGetGridHighlightObjectsForTest arg_pOverlayGetGridHighlightObjectsForTestNodeIds = POverlayGetGridHighlightObjectsForTest arg_pOverlayGetGridHighlightObjectsForTestNodeIds instance ToJSON POverlayGetGridHighlightObjectsForTest where toJSON p = A.object $ catMaybes [ ("nodeIds" A..=) <$> Just (pOverlayGetGridHighlightObjectsForTestNodeIds p) ] data OverlayGetGridHighlightObjectsForTest = OverlayGetGridHighlightObjectsForTest { overlayGetGridHighlightObjectsForTestHighlights :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetGridHighlightObjectsForTest where parseJSON = A.withObject "OverlayGetGridHighlightObjectsForTest" $ \o -> OverlayGetGridHighlightObjectsForTest <$> o A..: "highlights" instance Command POverlayGetGridHighlightObjectsForTest where type CommandResponse POverlayGetGridHighlightObjectsForTest = OverlayGetGridHighlightObjectsForTest commandName _ = "Overlay.getGridHighlightObjectsForTest" data POverlayGetSourceOrderHighlightObjectForTest = POverlayGetSourceOrderHighlightObjectForTest { pOverlayGetSourceOrderHighlightObjectForTestNodeId :: DOMPageNetworkEmulationSecurity.DOMNodeId } deriving (Eq, Show) pOverlayGetSourceOrderHighlightObjectForTest :: DOMPageNetworkEmulationSecurity.DOMNodeId -> POverlayGetSourceOrderHighlightObjectForTest pOverlayGetSourceOrderHighlightObjectForTest arg_pOverlayGetSourceOrderHighlightObjectForTestNodeId = POverlayGetSourceOrderHighlightObjectForTest arg_pOverlayGetSourceOrderHighlightObjectForTestNodeId instance ToJSON POverlayGetSourceOrderHighlightObjectForTest where toJSON p = A.object $ catMaybes [ ("nodeId" A..=) <$> Just (pOverlayGetSourceOrderHighlightObjectForTestNodeId p) ] data OverlayGetSourceOrderHighlightObjectForTest = OverlayGetSourceOrderHighlightObjectForTest { overlayGetSourceOrderHighlightObjectForTestHighlight :: [(T.Text, T.Text)] } deriving (Eq, Show) instance FromJSON OverlayGetSourceOrderHighlightObjectForTest where parseJSON = A.withObject "OverlayGetSourceOrderHighlightObjectForTest" $ \o -> OverlayGetSourceOrderHighlightObjectForTest <$> o A..: "highlight" instance Command POverlayGetSourceOrderHighlightObjectForTest where type CommandResponse POverlayGetSourceOrderHighlightObjectForTest = OverlayGetSourceOrderHighlightObjectForTest commandName _ = "Overlay.getSourceOrderHighlightObjectForTest" data POverlayHideHighlight = POverlayHideHighlight deriving (Eq, Show) pOverlayHideHighlight :: POverlayHideHighlight pOverlayHideHighlight = POverlayHideHighlight instance ToJSON POverlayHideHighlight where toJSON _ = A.Null instance Command POverlayHideHighlight where type CommandResponse POverlayHideHighlight = () commandName _ = "Overlay.hideHighlight" fromJSON = const . A.Success . const () | Highlights DOM node with given i d or with the given JavaScript object wrapper . Either nodeId or data POverlayHighlightNode = POverlayHighlightNode { pOverlayHighlightNodeHighlightConfig :: OverlayHighlightConfig, pOverlayHighlightNodeNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMNodeId, pOverlayHighlightNodeBackendNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMBackendNodeId, pOverlayHighlightNodeObjectId :: Maybe Runtime.RuntimeRemoteObjectId, pOverlayHighlightNodeSelector :: Maybe T.Text } deriving (Eq, Show) pOverlayHighlightNode :: OverlayHighlightConfig -> POverlayHighlightNode pOverlayHighlightNode arg_pOverlayHighlightNodeHighlightConfig = POverlayHighlightNode arg_pOverlayHighlightNodeHighlightConfig Nothing Nothing Nothing Nothing instance ToJSON POverlayHighlightNode where toJSON p = A.object $ catMaybes [ ("highlightConfig" A..=) <$> Just (pOverlayHighlightNodeHighlightConfig p), ("nodeId" A..=) <$> (pOverlayHighlightNodeNodeId p), ("backendNodeId" A..=) <$> (pOverlayHighlightNodeBackendNodeId p), ("objectId" A..=) <$> (pOverlayHighlightNodeObjectId p), ("selector" A..=) <$> (pOverlayHighlightNodeSelector p) ] instance Command POverlayHighlightNode where type CommandResponse POverlayHighlightNode = () commandName _ = "Overlay.highlightNode" fromJSON = const . A.Success . const () data POverlayHighlightQuad = POverlayHighlightQuad { pOverlayHighlightQuadQuad :: DOMPageNetworkEmulationSecurity.DOMQuad, pOverlayHighlightQuadColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, pOverlayHighlightQuadOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) pOverlayHighlightQuad :: DOMPageNetworkEmulationSecurity.DOMQuad -> POverlayHighlightQuad pOverlayHighlightQuad arg_pOverlayHighlightQuadQuad = POverlayHighlightQuad arg_pOverlayHighlightQuadQuad Nothing Nothing instance ToJSON POverlayHighlightQuad where toJSON p = A.object $ catMaybes [ ("quad" A..=) <$> Just (pOverlayHighlightQuadQuad p), ("color" A..=) <$> (pOverlayHighlightQuadColor p), ("outlineColor" A..=) <$> (pOverlayHighlightQuadOutlineColor p) ] instance Command POverlayHighlightQuad where type CommandResponse POverlayHighlightQuad = () commandName _ = "Overlay.highlightQuad" fromJSON = const . A.Success . const () data POverlayHighlightRect = POverlayHighlightRect { pOverlayHighlightRectX :: Int, pOverlayHighlightRectY :: Int, pOverlayHighlightRectWidth :: Int, pOverlayHighlightRectHeight :: Int, pOverlayHighlightRectColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA, pOverlayHighlightRectOutlineColor :: Maybe DOMPageNetworkEmulationSecurity.DOMRGBA } deriving (Eq, Show) pOverlayHighlightRect :: Int -> Int -> Int -> Int -> POverlayHighlightRect pOverlayHighlightRect arg_pOverlayHighlightRectX arg_pOverlayHighlightRectY arg_pOverlayHighlightRectWidth arg_pOverlayHighlightRectHeight = POverlayHighlightRect arg_pOverlayHighlightRectX arg_pOverlayHighlightRectY arg_pOverlayHighlightRectWidth arg_pOverlayHighlightRectHeight Nothing Nothing instance ToJSON POverlayHighlightRect where toJSON p = A.object $ catMaybes [ ("x" A..=) <$> Just (pOverlayHighlightRectX p), ("y" A..=) <$> Just (pOverlayHighlightRectY p), ("width" A..=) <$> Just (pOverlayHighlightRectWidth p), ("height" A..=) <$> Just (pOverlayHighlightRectHeight p), ("color" A..=) <$> (pOverlayHighlightRectColor p), ("outlineColor" A..=) <$> (pOverlayHighlightRectOutlineColor p) ] instance Command POverlayHighlightRect where type CommandResponse POverlayHighlightRect = () commandName _ = "Overlay.highlightRect" fromJSON = const . A.Success . const () | Highlights the source order of the children of the DOM node with given i d or with the given JavaScript object wrapper . Either nodeId or objectId must be specified . data POverlayHighlightSourceOrder = POverlayHighlightSourceOrder { pOverlayHighlightSourceOrderSourceOrderConfig :: OverlaySourceOrderConfig, pOverlayHighlightSourceOrderNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMNodeId, pOverlayHighlightSourceOrderBackendNodeId :: Maybe DOMPageNetworkEmulationSecurity.DOMBackendNodeId, pOverlayHighlightSourceOrderObjectId :: Maybe Runtime.RuntimeRemoteObjectId } deriving (Eq, Show) pOverlayHighlightSourceOrder :: OverlaySourceOrderConfig -> POverlayHighlightSourceOrder pOverlayHighlightSourceOrder arg_pOverlayHighlightSourceOrderSourceOrderConfig = POverlayHighlightSourceOrder arg_pOverlayHighlightSourceOrderSourceOrderConfig Nothing Nothing Nothing instance ToJSON POverlayHighlightSourceOrder where toJSON p = A.object $ catMaybes [ ("sourceOrderConfig" A..=) <$> Just (pOverlayHighlightSourceOrderSourceOrderConfig p), ("nodeId" A..=) <$> (pOverlayHighlightSourceOrderNodeId p), ("backendNodeId" A..=) <$> (pOverlayHighlightSourceOrderBackendNodeId p), ("objectId" A..=) <$> (pOverlayHighlightSourceOrderObjectId p) ] instance Command POverlayHighlightSourceOrder where type CommandResponse POverlayHighlightSourceOrder = () commandName _ = "Overlay.highlightSourceOrder" fromJSON = const . A.Success . const () | Parameters of the ' ' command . data POverlaySetInspectMode = POverlaySetInspectMode { pOverlaySetInspectModeMode :: OverlayInspectMode, | A descriptor for the highlight appearance of hovered - over nodes . May be omitted if ` enabled pOverlaySetInspectModeHighlightConfig :: Maybe OverlayHighlightConfig } deriving (Eq, Show) pOverlaySetInspectMode :: OverlayInspectMode -> POverlaySetInspectMode pOverlaySetInspectMode arg_pOverlaySetInspectModeMode = POverlaySetInspectMode arg_pOverlaySetInspectModeMode Nothing instance ToJSON POverlaySetInspectMode where toJSON p = A.object $ catMaybes [ ("mode" A..=) <$> Just (pOverlaySetInspectModeMode p), ("highlightConfig" A..=) <$> (pOverlaySetInspectModeHighlightConfig p) ] instance Command POverlaySetInspectMode where type CommandResponse POverlaySetInspectMode = () commandName _ = "Overlay.setInspectMode" fromJSON = const . A.Success . const () data POverlaySetShowAdHighlights = POverlaySetShowAdHighlights { pOverlaySetShowAdHighlightsShow :: Bool } deriving (Eq, Show) pOverlaySetShowAdHighlights :: Bool -> POverlaySetShowAdHighlights pOverlaySetShowAdHighlights arg_pOverlaySetShowAdHighlightsShow = POverlaySetShowAdHighlights arg_pOverlaySetShowAdHighlightsShow instance ToJSON POverlaySetShowAdHighlights where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowAdHighlightsShow p) ] instance Command POverlaySetShowAdHighlights where type CommandResponse POverlaySetShowAdHighlights = () commandName _ = "Overlay.setShowAdHighlights" fromJSON = const . A.Success . const () data POverlaySetPausedInDebuggerMessage = POverlaySetPausedInDebuggerMessage { pOverlaySetPausedInDebuggerMessageMessage :: Maybe T.Text } deriving (Eq, Show) pOverlaySetPausedInDebuggerMessage :: POverlaySetPausedInDebuggerMessage pOverlaySetPausedInDebuggerMessage = POverlaySetPausedInDebuggerMessage Nothing instance ToJSON POverlaySetPausedInDebuggerMessage where toJSON p = A.object $ catMaybes [ ("message" A..=) <$> (pOverlaySetPausedInDebuggerMessageMessage p) ] instance Command POverlaySetPausedInDebuggerMessage where type CommandResponse POverlaySetPausedInDebuggerMessage = () commandName _ = "Overlay.setPausedInDebuggerMessage" fromJSON = const . A.Success . const () | Parameters of the ' Overlay.setShowDebugBorders ' command . data POverlaySetShowDebugBorders = POverlaySetShowDebugBorders { pOverlaySetShowDebugBordersShow :: Bool } deriving (Eq, Show) pOverlaySetShowDebugBorders :: Bool -> POverlaySetShowDebugBorders pOverlaySetShowDebugBorders arg_pOverlaySetShowDebugBordersShow = POverlaySetShowDebugBorders arg_pOverlaySetShowDebugBordersShow instance ToJSON POverlaySetShowDebugBorders where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowDebugBordersShow p) ] instance Command POverlaySetShowDebugBorders where type CommandResponse POverlaySetShowDebugBorders = () commandName _ = "Overlay.setShowDebugBorders" fromJSON = const . A.Success . const () data POverlaySetShowFPSCounter = POverlaySetShowFPSCounter { pOverlaySetShowFPSCounterShow :: Bool } deriving (Eq, Show) pOverlaySetShowFPSCounter :: Bool -> POverlaySetShowFPSCounter pOverlaySetShowFPSCounter arg_pOverlaySetShowFPSCounterShow = POverlaySetShowFPSCounter arg_pOverlaySetShowFPSCounterShow instance ToJSON POverlaySetShowFPSCounter where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowFPSCounterShow p) ] instance Command POverlaySetShowFPSCounter where type CommandResponse POverlaySetShowFPSCounter = () commandName _ = "Overlay.setShowFPSCounter" fromJSON = const . A.Success . const () data POverlaySetShowGridOverlays = POverlaySetShowGridOverlays { pOverlaySetShowGridOverlaysGridNodeHighlightConfigs :: [OverlayGridNodeHighlightConfig] } deriving (Eq, Show) pOverlaySetShowGridOverlays :: [OverlayGridNodeHighlightConfig] -> POverlaySetShowGridOverlays pOverlaySetShowGridOverlays arg_pOverlaySetShowGridOverlaysGridNodeHighlightConfigs = POverlaySetShowGridOverlays arg_pOverlaySetShowGridOverlaysGridNodeHighlightConfigs instance ToJSON POverlaySetShowGridOverlays where toJSON p = A.object $ catMaybes [ ("gridNodeHighlightConfigs" A..=) <$> Just (pOverlaySetShowGridOverlaysGridNodeHighlightConfigs p) ] instance Command POverlaySetShowGridOverlays where type CommandResponse POverlaySetShowGridOverlays = () commandName _ = "Overlay.setShowGridOverlays" fromJSON = const . A.Success . const () data POverlaySetShowFlexOverlays = POverlaySetShowFlexOverlays { pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs :: [OverlayFlexNodeHighlightConfig] } deriving (Eq, Show) pOverlaySetShowFlexOverlays :: [OverlayFlexNodeHighlightConfig] -> POverlaySetShowFlexOverlays pOverlaySetShowFlexOverlays arg_pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs = POverlaySetShowFlexOverlays arg_pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs instance ToJSON POverlaySetShowFlexOverlays where toJSON p = A.object $ catMaybes [ ("flexNodeHighlightConfigs" A..=) <$> Just (pOverlaySetShowFlexOverlaysFlexNodeHighlightConfigs p) ] instance Command POverlaySetShowFlexOverlays where type CommandResponse POverlaySetShowFlexOverlays = () commandName _ = "Overlay.setShowFlexOverlays" fromJSON = const . A.Success . const () data POverlaySetShowScrollSnapOverlays = POverlaySetShowScrollSnapOverlays { pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs :: [OverlayScrollSnapHighlightConfig] } deriving (Eq, Show) pOverlaySetShowScrollSnapOverlays :: [OverlayScrollSnapHighlightConfig] -> POverlaySetShowScrollSnapOverlays pOverlaySetShowScrollSnapOverlays arg_pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs = POverlaySetShowScrollSnapOverlays arg_pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs instance ToJSON POverlaySetShowScrollSnapOverlays where toJSON p = A.object $ catMaybes [ ("scrollSnapHighlightConfigs" A..=) <$> Just (pOverlaySetShowScrollSnapOverlaysScrollSnapHighlightConfigs p) ] instance Command POverlaySetShowScrollSnapOverlays where type CommandResponse POverlaySetShowScrollSnapOverlays = () commandName _ = "Overlay.setShowScrollSnapOverlays" fromJSON = const . A.Success . const () data POverlaySetShowContainerQueryOverlays = POverlaySetShowContainerQueryOverlays { pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs :: [OverlayContainerQueryHighlightConfig] } deriving (Eq, Show) pOverlaySetShowContainerQueryOverlays :: [OverlayContainerQueryHighlightConfig] -> POverlaySetShowContainerQueryOverlays pOverlaySetShowContainerQueryOverlays arg_pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs = POverlaySetShowContainerQueryOverlays arg_pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs instance ToJSON POverlaySetShowContainerQueryOverlays where toJSON p = A.object $ catMaybes [ ("containerQueryHighlightConfigs" A..=) <$> Just (pOverlaySetShowContainerQueryOverlaysContainerQueryHighlightConfigs p) ] instance Command POverlaySetShowContainerQueryOverlays where type CommandResponse POverlaySetShowContainerQueryOverlays = () commandName _ = "Overlay.setShowContainerQueryOverlays" fromJSON = const . A.Success . const () data POverlaySetShowPaintRects = POverlaySetShowPaintRects { pOverlaySetShowPaintRectsResult :: Bool } deriving (Eq, Show) pOverlaySetShowPaintRects :: Bool -> POverlaySetShowPaintRects pOverlaySetShowPaintRects arg_pOverlaySetShowPaintRectsResult = POverlaySetShowPaintRects arg_pOverlaySetShowPaintRectsResult instance ToJSON POverlaySetShowPaintRects where toJSON p = A.object $ catMaybes [ ("result" A..=) <$> Just (pOverlaySetShowPaintRectsResult p) ] instance Command POverlaySetShowPaintRects where type CommandResponse POverlaySetShowPaintRects = () commandName _ = "Overlay.setShowPaintRects" fromJSON = const . A.Success . const () data POverlaySetShowLayoutShiftRegions = POverlaySetShowLayoutShiftRegions { pOverlaySetShowLayoutShiftRegionsResult :: Bool } deriving (Eq, Show) pOverlaySetShowLayoutShiftRegions :: Bool -> POverlaySetShowLayoutShiftRegions pOverlaySetShowLayoutShiftRegions arg_pOverlaySetShowLayoutShiftRegionsResult = POverlaySetShowLayoutShiftRegions arg_pOverlaySetShowLayoutShiftRegionsResult instance ToJSON POverlaySetShowLayoutShiftRegions where toJSON p = A.object $ catMaybes [ ("result" A..=) <$> Just (pOverlaySetShowLayoutShiftRegionsResult p) ] instance Command POverlaySetShowLayoutShiftRegions where type CommandResponse POverlaySetShowLayoutShiftRegions = () commandName _ = "Overlay.setShowLayoutShiftRegions" fromJSON = const . A.Success . const () data POverlaySetShowScrollBottleneckRects = POverlaySetShowScrollBottleneckRects { pOverlaySetShowScrollBottleneckRectsShow :: Bool } deriving (Eq, Show) pOverlaySetShowScrollBottleneckRects :: Bool -> POverlaySetShowScrollBottleneckRects pOverlaySetShowScrollBottleneckRects arg_pOverlaySetShowScrollBottleneckRectsShow = POverlaySetShowScrollBottleneckRects arg_pOverlaySetShowScrollBottleneckRectsShow instance ToJSON POverlaySetShowScrollBottleneckRects where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowScrollBottleneckRectsShow p) ] instance Command POverlaySetShowScrollBottleneckRects where type CommandResponse POverlaySetShowScrollBottleneckRects = () commandName _ = "Overlay.setShowScrollBottleneckRects" fromJSON = const . A.Success . const () data POverlaySetShowWebVitals = POverlaySetShowWebVitals { pOverlaySetShowWebVitalsShow :: Bool } deriving (Eq, Show) pOverlaySetShowWebVitals :: Bool -> POverlaySetShowWebVitals pOverlaySetShowWebVitals arg_pOverlaySetShowWebVitalsShow = POverlaySetShowWebVitals arg_pOverlaySetShowWebVitalsShow instance ToJSON POverlaySetShowWebVitals where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowWebVitalsShow p) ] instance Command POverlaySetShowWebVitals where type CommandResponse POverlaySetShowWebVitals = () commandName _ = "Overlay.setShowWebVitals" fromJSON = const . A.Success . const () data POverlaySetShowViewportSizeOnResize = POverlaySetShowViewportSizeOnResize { pOverlaySetShowViewportSizeOnResizeShow :: Bool } deriving (Eq, Show) pOverlaySetShowViewportSizeOnResize :: Bool -> POverlaySetShowViewportSizeOnResize pOverlaySetShowViewportSizeOnResize arg_pOverlaySetShowViewportSizeOnResizeShow = POverlaySetShowViewportSizeOnResize arg_pOverlaySetShowViewportSizeOnResizeShow instance ToJSON POverlaySetShowViewportSizeOnResize where toJSON p = A.object $ catMaybes [ ("show" A..=) <$> Just (pOverlaySetShowViewportSizeOnResizeShow p) ] instance Command POverlaySetShowViewportSizeOnResize where type CommandResponse POverlaySetShowViewportSizeOnResize = () commandName _ = "Overlay.setShowViewportSizeOnResize" fromJSON = const . A.Success . const () data POverlaySetShowHinge = POverlaySetShowHinge { | hinge data , null means hideHinge pOverlaySetShowHingeHingeConfig :: Maybe OverlayHingeConfig } deriving (Eq, Show) pOverlaySetShowHinge :: POverlaySetShowHinge pOverlaySetShowHinge = POverlaySetShowHinge Nothing instance ToJSON POverlaySetShowHinge where toJSON p = A.object $ catMaybes [ ("hingeConfig" A..=) <$> (pOverlaySetShowHingeHingeConfig p) ] instance Command POverlaySetShowHinge where type CommandResponse POverlaySetShowHinge = () commandName _ = "Overlay.setShowHinge" fromJSON = const . A.Success . const () | Parameters of the ' Overlay.setShowIsolatedElements ' command . data POverlaySetShowIsolatedElements = POverlaySetShowIsolatedElements { pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs :: [OverlayIsolatedElementHighlightConfig] } deriving (Eq, Show) pOverlaySetShowIsolatedElements :: [OverlayIsolatedElementHighlightConfig] -> POverlaySetShowIsolatedElements pOverlaySetShowIsolatedElements arg_pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs = POverlaySetShowIsolatedElements arg_pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs instance ToJSON POverlaySetShowIsolatedElements where toJSON p = A.object $ catMaybes [ ("isolatedElementHighlightConfigs" A..=) <$> Just (pOverlaySetShowIsolatedElementsIsolatedElementHighlightConfigs p) ] instance Command POverlaySetShowIsolatedElements where type CommandResponse POverlaySetShowIsolatedElements = () commandName _ = "Overlay.setShowIsolatedElements" fromJSON = const . A.Success . const ()
5eece28e126625e0647b15d490f2f2bb901513747c74b1678635840fdbbff391
spawnfest/eep49ers
mac2.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1998 - 2016 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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. %% %% %CopyrightEnd% %% -ifndef(p). -define(p, 1). -endif. -ifndef('p'). -define('p', 2). -endif. -ifndef(P). -define(P, 3). -endif. -ifndef('P'). -define('P', 4). -endif. -plupp({?p, ?'p', ?P, ?'P'}).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/test/epp_SUITE_data/mac2.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. %CopyrightEnd%
Copyright Ericsson AB 1998 - 2016 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -ifndef(p). -define(p, 1). -endif. -ifndef('p'). -define('p', 2). -endif. -ifndef(P). -define(P, 3). -endif. -ifndef('P'). -define('P', 4). -endif. -plupp({?p, ?'p', ?P, ?'P'}).
ad15874b17dd59faa1887291b7cfe0062c67d36c19e7de97f799761c89590259
returntocorp/semgrep
Xpattern_match_spacegrep.ml
* * Copyright ( C ) 2021 - 2022 r2c * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file LICENSE . * * This library 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 file * LICENSE for more details . * * Copyright (C) 2021-2022 r2c * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file LICENSE. * * This library 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 file * LICENSE for more details. *) open Xpattern_matcher module PI = Parse_info let logger = Logging.get_logger [ __MODULE__ ] let lexing_pos_to_loc file x str = almost like Spacegrep . Semgrep.semgrep_pos ( ) let line = x.Lexing.pos_lnum in let charpos = x.Lexing.pos_cnum in bugfix : not +1 here , Parse_info.column is 0 - based . * JSON_report.json_range does . * JSON_report.json_range does the adjust_column + 1. *) let column = x.Lexing.pos_cnum - x.Lexing.pos_bol in { PI.str; charpos; file; line; column } let spacegrep_matcher (xconfig : Match_env.xconfig) (doc, src) file pat = let search_param = Spacegrep.Match.create_search_param ~ellipsis_max_span:xconfig.config.generic_ellipsis_max_span () in let matches = Spacegrep.Match.search search_param src pat doc in matches |> Common.map (fun m -> let (pos1, _), (_, pos2) = m.Spacegrep.Match.region in let { Spacegrep.Match.value = str; _ } = m.Spacegrep.Match.capture in let env = m.Spacegrep.Match.named_captures |> Common.map (fun (s, capture) -> let mvar = "$" ^ s in let { Spacegrep.Match.value = str; loc = pos, _ } = capture in let loc = lexing_pos_to_loc file pos str in let t = info_of_token_location loc in let mval = mval_of_string str t in (mvar, mval)) in let loc1 = lexing_pos_to_loc file pos1 str in let loc2 = lexing_pos_to_loc file pos2 "" in ((loc1, loc2), env)) Preprocess spacegrep pattern or target to remove comments let preprocess_spacegrep (xconfig : Match_env.xconfig) src = match xconfig.config.generic_comment_style with | None -> src | Some style -> let style = match style with | `C -> Spacegrep.Comment.c_style | `Cpp -> Spacegrep.Comment.cpp_style | `Shell -> Spacegrep.Comment.shell_style in Spacegrep.Comment.remove_comments_from_src style src let matches_of_spacegrep (xconfig : Match_env.xconfig) spacegreps file = matches_of_matcher spacegreps { init = (fun _ -> if xconfig.nested_formula then If we are in a nested call to the search engine ( i.e. within a * ` metavariable - pattern ` operator ) then the rule is * explicitly * * requesting that Spacegrep analyzes this piece of text . We must * do so even if the text looks like gibberish . It can e.g. be * an RSA key . * `metavariable-pattern` operator) then the rule is *explicitly* * requesting that Spacegrep analyzes this piece of text. We must * do so even if the text looks like gibberish. It can e.g. be * an RSA key. *) let src = file |> Spacegrep.Src_file.of_file |> preprocess_spacegrep xconfig in Some (Spacegrep.Parse_doc.of_src src, src) else (* coupling: mostly copypaste of Spacegrep_main.run_all *) We inspect the first 4096 bytes to guess whether the file type . This saves time on large files , by reading typically just one block from the file system . We inspect the first 4096 bytes to guess whether the file type. This saves time on large files, by reading typically just one block from the file system. *) let peek_length = 4096 in let partial_doc_src = Spacegrep.Src_file.of_file ~max_len:peek_length file in let doc_type = Spacegrep.File_type.classify partial_doc_src in match doc_type with | Minified | Binary -> logger#info "ignoring gibberish file: %s\n%!" file; None | Text | Short -> let src = if Spacegrep.Src_file.length partial_doc_src < peek_length (* it's actually complete, no need to re-input the file *) then partial_doc_src else Spacegrep.Src_file.of_file file in let src = preprocess_spacegrep xconfig src in (* pr (Spacegrep.Doc_AST.show doc); *) Some (Spacegrep.Parse_doc.of_src src, src)); matcher = spacegrep_matcher xconfig; } file [@@profiling]
null
https://raw.githubusercontent.com/returntocorp/semgrep/af76564cf0b6b1bc5e281eb2121b32d3186fbf05/src/engine/Xpattern_match_spacegrep.ml
ocaml
coupling: mostly copypaste of Spacegrep_main.run_all it's actually complete, no need to re-input the file pr (Spacegrep.Doc_AST.show doc);
* * Copyright ( C ) 2021 - 2022 r2c * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file LICENSE . * * This library 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 file * LICENSE for more details . * * Copyright (C) 2021-2022 r2c * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file LICENSE. * * This library 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 file * LICENSE for more details. *) open Xpattern_matcher module PI = Parse_info let logger = Logging.get_logger [ __MODULE__ ] let lexing_pos_to_loc file x str = almost like Spacegrep . Semgrep.semgrep_pos ( ) let line = x.Lexing.pos_lnum in let charpos = x.Lexing.pos_cnum in bugfix : not +1 here , Parse_info.column is 0 - based . * JSON_report.json_range does . * JSON_report.json_range does the adjust_column + 1. *) let column = x.Lexing.pos_cnum - x.Lexing.pos_bol in { PI.str; charpos; file; line; column } let spacegrep_matcher (xconfig : Match_env.xconfig) (doc, src) file pat = let search_param = Spacegrep.Match.create_search_param ~ellipsis_max_span:xconfig.config.generic_ellipsis_max_span () in let matches = Spacegrep.Match.search search_param src pat doc in matches |> Common.map (fun m -> let (pos1, _), (_, pos2) = m.Spacegrep.Match.region in let { Spacegrep.Match.value = str; _ } = m.Spacegrep.Match.capture in let env = m.Spacegrep.Match.named_captures |> Common.map (fun (s, capture) -> let mvar = "$" ^ s in let { Spacegrep.Match.value = str; loc = pos, _ } = capture in let loc = lexing_pos_to_loc file pos str in let t = info_of_token_location loc in let mval = mval_of_string str t in (mvar, mval)) in let loc1 = lexing_pos_to_loc file pos1 str in let loc2 = lexing_pos_to_loc file pos2 "" in ((loc1, loc2), env)) Preprocess spacegrep pattern or target to remove comments let preprocess_spacegrep (xconfig : Match_env.xconfig) src = match xconfig.config.generic_comment_style with | None -> src | Some style -> let style = match style with | `C -> Spacegrep.Comment.c_style | `Cpp -> Spacegrep.Comment.cpp_style | `Shell -> Spacegrep.Comment.shell_style in Spacegrep.Comment.remove_comments_from_src style src let matches_of_spacegrep (xconfig : Match_env.xconfig) spacegreps file = matches_of_matcher spacegreps { init = (fun _ -> if xconfig.nested_formula then If we are in a nested call to the search engine ( i.e. within a * ` metavariable - pattern ` operator ) then the rule is * explicitly * * requesting that Spacegrep analyzes this piece of text . We must * do so even if the text looks like gibberish . It can e.g. be * an RSA key . * `metavariable-pattern` operator) then the rule is *explicitly* * requesting that Spacegrep analyzes this piece of text. We must * do so even if the text looks like gibberish. It can e.g. be * an RSA key. *) let src = file |> Spacegrep.Src_file.of_file |> preprocess_spacegrep xconfig in Some (Spacegrep.Parse_doc.of_src src, src) else We inspect the first 4096 bytes to guess whether the file type . This saves time on large files , by reading typically just one block from the file system . We inspect the first 4096 bytes to guess whether the file type. This saves time on large files, by reading typically just one block from the file system. *) let peek_length = 4096 in let partial_doc_src = Spacegrep.Src_file.of_file ~max_len:peek_length file in let doc_type = Spacegrep.File_type.classify partial_doc_src in match doc_type with | Minified | Binary -> logger#info "ignoring gibberish file: %s\n%!" file; None | Text | Short -> let src = if Spacegrep.Src_file.length partial_doc_src < peek_length then partial_doc_src else Spacegrep.Src_file.of_file file in let src = preprocess_spacegrep xconfig src in Some (Spacegrep.Parse_doc.of_src src, src)); matcher = spacegrep_matcher xconfig; } file [@@profiling]
aaef7d46aa8da6248fba734301e89be92d325fae4edfd385ff4957cb0995bc58
lasp-lang/lasp
lasp_throughput_client.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -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. %% %% ------------------------------------------------------------------- -module(lasp_throughput_client). -author("Vitor Enes Duarte <"). -behaviour(gen_server). %% API -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("lasp.hrl"). State record . -record(state, {actor, events, batch_start, batch_events}). %%%=================================================================== %%% API %%%=================================================================== %% @doc Start and link to calling process. -spec start_link() -> {ok, pid()} | ignore | {error, term()}. start_link() -> gen_server:start_link(?MODULE, [], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== @private -spec init([term()]) -> {ok, #state{}}. init([]) -> lager:info("Throughput client initialized."), %% Generate actor identifier. Actor = lasp_support:mynode(), %% Schedule event. schedule_event(), {ok, #state{actor=Actor, events=0, batch_start=undefined, batch_events=0}}. @private -spec handle_call(term(), {pid(), term()}, #state{}) -> {reply, term(), #state{}}. handle_call(Msg, _From, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {reply, ok, State}. @private -spec handle_cast(term(), #state{}) -> {noreply, #state{}}. handle_cast(Msg, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {noreply, State}. @private -spec handle_info(term(), #state{}) -> {noreply, #state{}}. handle_info(event, #state{actor=Actor, batch_start=BatchStart0, batch_events=BatchEvents0, events=Events0}=State) -> lasp_marathon_simulations:log_message_queue_size("event"), %% Start the batch for every event, if it isn't started yet. BatchStart1 = case BatchStart0 of undefined -> erlang:timestamp(); _ -> BatchStart0 end, {LocalEvents, BatchStart, BatchEvents} = case lasp_workflow:is_task_completed(convergence, 1) of true -> Events1 = Events0 + 1, %% If we hit the batch size, restart the batch. {BatchStart2, BatchEvents1} = case BatchEvents0 + 1 == ?BATCH_EVENTS of true -> BatchEnd = erlang:timestamp(), lager:info("Events done: ~p, Batch finished! ~p, Node: ~p", [Events1, ?BATCH_EVENTS, Actor]), log_batch(BatchStart1, BatchEnd, ?BATCH_EVENTS), {undefined, 0}; false -> {BatchStart1, BatchEvents0 + 1} end, Element = atom_to_list(Actor), {Duration, _} = timer:tc(fun() -> perform_update(Element, Actor, Events1) end), log_event(Duration), case Events1 == max_events() of true -> lager:info("All events done. Node: ~p", [Actor]), %% Update Simulation Status Instance lasp_workflow:task_completed(events, lasp_support:mynode()), log_convergence(), schedule_check_simulation_end(); false -> schedule_event() end, {Events1, BatchStart2, BatchEvents1}; false -> schedule_event(), {Events0, undefined, 0} end, {noreply, State#state{batch_events=BatchEvents, batch_start=BatchStart, events=LocalEvents}}; handle_info(check_simulation_end, #state{actor=Actor}=State) -> lasp_marathon_simulations:log_message_queue_size("check_simulation_end"), case lasp_workflow:is_task_completed(events) of true -> lager:info("All nodes did all events. Node ~p", [Actor]), lasp_instrumentation:stop(), lasp_support:push_logs(), lasp_workflow:task_completed(logs, lasp_support:mynode()); false -> schedule_check_simulation_end() end, {noreply, State}; handle_info(Msg, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {noreply, State}. @private -spec terminate(term(), #state{}) -> term(). terminate(_Reason, _State) -> ok. @private -spec code_change(term() | {down, term()}, #state{}, term()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== @private schedule_event() -> Interval = lasp_config:get(event_interval, 0), timer:send_after(Interval, event). @private schedule_check_simulation_end() -> timer:send_after(?STATUS_INTERVAL, check_simulation_end). @private log_convergence() -> case lasp_config:get(instrumentation, false) of true -> lasp_instrumentation:convergence(); false -> ok end. @private log_batch(Start, End, Events) -> case lasp_config:get(instrumentation, false) of true -> lasp_instrumentation:batch(Start, End, Events); false -> ok end. @private log_event(Duration) -> case lasp_config:get(event_logging, false) of true -> lasp_instrumentation:event(Duration); false -> ok end. @private max_events() -> lasp_config:get(max_events, ?MAX_EVENTS_DEFAULT). @private perform_update(Element, Actor, Events1) -> UniqueElement = Element ++ integer_to_list(Events1), case lasp_config:get(throughput_type, gset) of twopset -> lasp:update(?SIMPLE_TWOPSET, {add, UniqueElement}, Actor); boolean -> lasp:update(?SIMPLE_BOOLEAN, true, Actor); gset -> lasp:update(?SIMPLE_BAG, {add, Element}, Actor); awset_ps -> lasp:update(?PROVENANCE_SET, {add, UniqueElement}, Actor); gcounter -> lasp:update(?SIMPLE_COUNTER, increment, Actor) end.
null
https://raw.githubusercontent.com/lasp-lang/lasp/1701c8af77e193738dfc4ef4a5a703d205da41a1/src/lasp_throughput_client.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- API gen_server callbacks =================================================================== API =================================================================== @doc Start and link to calling process. =================================================================== gen_server callbacks =================================================================== Generate actor identifier. Schedule event. Start the batch for every event, if it isn't started yet. If we hit the batch size, restart the batch. Update Simulation Status Instance =================================================================== ===================================================================
Copyright ( c ) 2016 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(lasp_throughput_client). -author("Vitor Enes Duarte <"). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("lasp.hrl"). State record . -record(state, {actor, events, batch_start, batch_events}). -spec start_link() -> {ok, pid()} | ignore | {error, term()}. start_link() -> gen_server:start_link(?MODULE, [], []). @private -spec init([term()]) -> {ok, #state{}}. init([]) -> lager:info("Throughput client initialized."), Actor = lasp_support:mynode(), schedule_event(), {ok, #state{actor=Actor, events=0, batch_start=undefined, batch_events=0}}. @private -spec handle_call(term(), {pid(), term()}, #state{}) -> {reply, term(), #state{}}. handle_call(Msg, _From, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {reply, ok, State}. @private -spec handle_cast(term(), #state{}) -> {noreply, #state{}}. handle_cast(Msg, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {noreply, State}. @private -spec handle_info(term(), #state{}) -> {noreply, #state{}}. handle_info(event, #state{actor=Actor, batch_start=BatchStart0, batch_events=BatchEvents0, events=Events0}=State) -> lasp_marathon_simulations:log_message_queue_size("event"), BatchStart1 = case BatchStart0 of undefined -> erlang:timestamp(); _ -> BatchStart0 end, {LocalEvents, BatchStart, BatchEvents} = case lasp_workflow:is_task_completed(convergence, 1) of true -> Events1 = Events0 + 1, {BatchStart2, BatchEvents1} = case BatchEvents0 + 1 == ?BATCH_EVENTS of true -> BatchEnd = erlang:timestamp(), lager:info("Events done: ~p, Batch finished! ~p, Node: ~p", [Events1, ?BATCH_EVENTS, Actor]), log_batch(BatchStart1, BatchEnd, ?BATCH_EVENTS), {undefined, 0}; false -> {BatchStart1, BatchEvents0 + 1} end, Element = atom_to_list(Actor), {Duration, _} = timer:tc(fun() -> perform_update(Element, Actor, Events1) end), log_event(Duration), case Events1 == max_events() of true -> lager:info("All events done. Node: ~p", [Actor]), lasp_workflow:task_completed(events, lasp_support:mynode()), log_convergence(), schedule_check_simulation_end(); false -> schedule_event() end, {Events1, BatchStart2, BatchEvents1}; false -> schedule_event(), {Events0, undefined, 0} end, {noreply, State#state{batch_events=BatchEvents, batch_start=BatchStart, events=LocalEvents}}; handle_info(check_simulation_end, #state{actor=Actor}=State) -> lasp_marathon_simulations:log_message_queue_size("check_simulation_end"), case lasp_workflow:is_task_completed(events) of true -> lager:info("All nodes did all events. Node ~p", [Actor]), lasp_instrumentation:stop(), lasp_support:push_logs(), lasp_workflow:task_completed(logs, lasp_support:mynode()); false -> schedule_check_simulation_end() end, {noreply, State}; handle_info(Msg, State) -> lager:warning("Unhandled messages: ~p", [Msg]), {noreply, State}. @private -spec terminate(term(), #state{}) -> term(). terminate(_Reason, _State) -> ok. @private -spec code_change(term() | {down, term()}, #state{}, term()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions @private schedule_event() -> Interval = lasp_config:get(event_interval, 0), timer:send_after(Interval, event). @private schedule_check_simulation_end() -> timer:send_after(?STATUS_INTERVAL, check_simulation_end). @private log_convergence() -> case lasp_config:get(instrumentation, false) of true -> lasp_instrumentation:convergence(); false -> ok end. @private log_batch(Start, End, Events) -> case lasp_config:get(instrumentation, false) of true -> lasp_instrumentation:batch(Start, End, Events); false -> ok end. @private log_event(Duration) -> case lasp_config:get(event_logging, false) of true -> lasp_instrumentation:event(Duration); false -> ok end. @private max_events() -> lasp_config:get(max_events, ?MAX_EVENTS_DEFAULT). @private perform_update(Element, Actor, Events1) -> UniqueElement = Element ++ integer_to_list(Events1), case lasp_config:get(throughput_type, gset) of twopset -> lasp:update(?SIMPLE_TWOPSET, {add, UniqueElement}, Actor); boolean -> lasp:update(?SIMPLE_BOOLEAN, true, Actor); gset -> lasp:update(?SIMPLE_BAG, {add, Element}, Actor); awset_ps -> lasp:update(?PROVENANCE_SET, {add, UniqueElement}, Actor); gcounter -> lasp:update(?SIMPLE_COUNTER, increment, Actor) end.
d2e9c8d832ad8f1ee98cf47d8885c99d0019be4fa1a489eff29f31bfdfee416b
mirage/cactus
main.ml
* Copyright ( c ) 2021 Tarides < > * Copyright ( c ) 2021 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2021 Tarides <> * Copyright (c) 2021 Gabriel Belouze <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) let () = Printexc.record_backtrace true let make_suites version = [ Migration.suite version; Treetest.suite version; Integritytest.suite version; Replaytest.suite version; ] let () = Alcotest.run "Btree storage" ([ Utilstest.suite; Oracletest.suite ] @ make_suites `V0) (* let () = Demo.snapshot () *)
null
https://raw.githubusercontent.com/mirage/cactus/3eb2a4abee79bf8f20de5b4b12a57c3421c3e2fe/tests/main.ml
ocaml
let () = Demo.snapshot ()
* Copyright ( c ) 2021 Tarides < > * Copyright ( c ) 2021 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2021 Tarides <> * Copyright (c) 2021 Gabriel Belouze <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) let () = Printexc.record_backtrace true let make_suites version = [ Migration.suite version; Treetest.suite version; Integritytest.suite version; Replaytest.suite version; ] let () = Alcotest.run "Btree storage" ([ Utilstest.suite; Oracletest.suite ] @ make_suites `V0)
e18d99d2023ed73c35985b4222db077a475b0621cf37245c9c8148e8223e5a5a
bobzhang/fan
env_plc.mli
(** An environment mapping variables to identifiers, and capable of generating fresh identifiers. *) (** The type of environments. *) type t (** [empty f] returns an empty environment with naming function [f]. *) val empty : (int -> string) -> t (** [lookup env var] returns the identifier for [var] in [env], or raises [Not_found] if unbound. *) val lookup : t -> string -> string (** [bind env var id] returns a new environment where [var] is bound to [id]. *) val bind : t -> string -> string -> t (** [bound env var] checks whether [var] is bound in [env]. *) val bound : t -> string -> bool (** [fresh_id env] allocates a fresh identifier in [env]. *) val fresh_id : t -> t * string (** [dispatch env v f1 f2] will return [f1 id] when [v] is bound to [id] in [env]; it will return [f2 id env] otherwise, where [id] is fresh and [env] is extended with the binding of [v] to [id]. *) val dispatch : t -> string -> (string -> 'a) -> (t -> string -> 'a) -> 'a (** [bind_or_test env tst var id] binds [var] to [id] in enviroment, or extends [tst] with the pair [id,id'] if [var] is already bound to [id']. *) val bind_or_test : t -> (string * string) list -> string -> string -> t * (string * string) list (** [gen_bind_or_test env tst var] returns a fresh identifier, and binds [var] to this identifier in [env] or extends [tst] with the pair [id,id'] when [var] is already bound to [id']. *) val gen_bind_or_test : t -> (string * string) list -> string -> t * (string * string) list * string * [ unify env tst var1 var2 ] unifies [ var1 ] and [ var2 ] : if one of both is bound , the other is bound as well ; if both are bound , [ tst ] is extended with a pair of their identifiers ; if both are unbound , [ Not_found ] is raised . bound, the other is bound as well; if both are bound, [tst] is extended with a pair of their identifiers; if both are unbound, [Not_found] is raised. *) val unify : t -> (string * string) list -> string -> string -> t * (string * string) list
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/thirdparty/plc/env_plc.mli
ocaml
* An environment mapping variables to identifiers, and capable of generating fresh identifiers. * The type of environments. * [empty f] returns an empty environment with naming function [f]. * [lookup env var] returns the identifier for [var] in [env], or raises [Not_found] if unbound. * [bind env var id] returns a new environment where [var] is bound to [id]. * [bound env var] checks whether [var] is bound in [env]. * [fresh_id env] allocates a fresh identifier in [env]. * [dispatch env v f1 f2] will return [f1 id] when [v] is bound to [id] in [env]; it will return [f2 id env] otherwise, where [id] is fresh and [env] is extended with the binding of [v] to [id]. * [bind_or_test env tst var id] binds [var] to [id] in enviroment, or extends [tst] with the pair [id,id'] if [var] is already bound to [id']. * [gen_bind_or_test env tst var] returns a fresh identifier, and binds [var] to this identifier in [env] or extends [tst] with the pair [id,id'] when [var] is already bound to [id'].
type t val empty : (int -> string) -> t val lookup : t -> string -> string val bind : t -> string -> string -> t val bound : t -> string -> bool val fresh_id : t -> t * string val dispatch : t -> string -> (string -> 'a) -> (t -> string -> 'a) -> 'a val bind_or_test : t -> (string * string) list -> string -> string -> t * (string * string) list val gen_bind_or_test : t -> (string * string) list -> string -> t * (string * string) list * string * [ unify env tst var1 var2 ] unifies [ var1 ] and [ var2 ] : if one of both is bound , the other is bound as well ; if both are bound , [ tst ] is extended with a pair of their identifiers ; if both are unbound , [ Not_found ] is raised . bound, the other is bound as well; if both are bound, [tst] is extended with a pair of their identifiers; if both are unbound, [Not_found] is raised. *) val unify : t -> (string * string) list -> string -> string -> t * (string * string) list
4955b8bcc70d7fe37e42c9d40360e21e681f6be3743e5997535a3c220119802c
jellelicht/guix
download.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 , 2013 < > Copyright © 2014 , 2015 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . ;;; ;;; Download a binary file from an external source. ;;; (use-modules (ice-9 match) (web uri) (web client) (rnrs io ports) (srfi srfi-11) (guix utils) (guix hash)) (define %url-base "" ;; Alternately: " /~lcourtes/software/guix/packages " ) XXX : Work around < > , present in up to 2.0.7 . (module-define! (resolve-module '(web client)) 'shutdown (const #f)) (define (file-name->uri file) "Return the URI for FILE." (match (string-tokenize file (char-set-complement (char-set #\/))) ((_ ... system basename) (string->uri (string-append %url-base "/" system (match system ("armhf-linux" "/20150101/") (_ "/20131110/")) basename))))) (match (command-line) ((_ file expected-hash) (let ((uri (file-name->uri file))) (format #t "downloading file `~a'~%from `~a'...~%" file (uri->string uri)) (let*-values (((resp data) (http-get uri #:decode-body? #f)) ((hash) (bytevector->base16-string (sha256 data))) ((part) (string-append file ".part"))) (if (string=? expected-hash hash) (begin (call-with-output-file part (lambda (port) (put-bytevector port data))) (rename-file part file)) (begin (format (current-error-port) "file at `~a' has SHA256 ~a; expected ~a~%" (uri->string uri) hash expected-hash) (exit 1)))))))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/build-aux/download.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Download a binary file from an external source. Alternately:
Copyright © 2012 , 2013 < > Copyright © 2014 , 2015 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (use-modules (ice-9 match) (web uri) (web client) (rnrs io ports) (srfi srfi-11) (guix utils) (guix hash)) (define %url-base "" " /~lcourtes/software/guix/packages " ) XXX : Work around < > , present in up to 2.0.7 . (module-define! (resolve-module '(web client)) 'shutdown (const #f)) (define (file-name->uri file) "Return the URI for FILE." (match (string-tokenize file (char-set-complement (char-set #\/))) ((_ ... system basename) (string->uri (string-append %url-base "/" system (match system ("armhf-linux" "/20150101/") (_ "/20131110/")) basename))))) (match (command-line) ((_ file expected-hash) (let ((uri (file-name->uri file))) (format #t "downloading file `~a'~%from `~a'...~%" file (uri->string uri)) (let*-values (((resp data) (http-get uri #:decode-body? #f)) ((hash) (bytevector->base16-string (sha256 data))) ((part) (string-append file ".part"))) (if (string=? expected-hash hash) (begin (call-with-output-file part (lambda (port) (put-bytevector port data))) (rename-file part file)) (begin (format (current-error-port) "file at `~a' has SHA256 ~a; expected ~a~%" (uri->string uri) hash expected-hash) (exit 1)))))))
ca73b383f48429ca491c2b5ad990384a2d9e3dbe8cb75fef1735b07e06aad17c
jordanthayer/ocaml-search
recording_tqs_v2.ml
* Tool for recording the executions of three queue search type fp_values = { h : float; d : float; h_err : float; d_err : float; g : float; f : float; est_f : float; est_d : float; } type int_vals = { mutable clean_pos : int; mutable open_pos : int; depth : int; } type 'a node = { data : 'a; parent: 'a node; mutable geqe : 'a node Geq.entry; ints : int_vals; fp : fp_values; } (**************** Ordering Predicates *********************) let open_sort a b = let afp = a.fp and bfp = b.fp in let aef = afp.est_f and bef = bfp.est_f and ag = afp.g and bg = bfp.g in (aef < bef) || (* sort by fhat *) ((aef = bef) && ((ag >= bg) || (* break ties on low d *) ((ag = bg) && (afp.d < bfp.d)))) (* break ties on high g *) let focal_sort a b = let afp = a.fp and bfp = b.fp in let aed = afp.est_d and bed = bfp.est_d and aef = afp.est_f and bef = bfp.est_f in (aed < bed) || ((aed = bed) && ((aef < bef) || ((aef = bef) && (afp.g >= bfp.g)))) let clean_sort a b = let afp = a.fp and bfp = b.fp in let af = afp.f and bf= bfp.f in af < bf || (af = bf && afp.g >= bfp.g) let make_close_enough bound = let close_enough a b = (b.fp.est_f <= (a.fp.est_f *. bound)) in close_enough let better_p a b = (a.fp.f) <= (b.fp.f) (*************** Utility functions **************) let unwrap_sol = function | Limit.Incumbent (q, n) -> Some (n.data, n.fp.g) | _ -> None let wrap fn = (fun n -> fn n.data) let on_fhat = ref 0 and on_dhat = ref 0 and on_f = ref 0 and delayed = ref 0 let reset () = on_fhat := 0; on_dhat := 0; on_f := 0; delayed := 0 let incr r = r := !r + 1 let alt_col_name = "served" let output_col_hd () = Datafile.write_alt_colnames stdout alt_col_name ["on_fhat"; "on_dhat"; "on_f"; "delayed";] let output_row () = Datafile.write_alt_row_prefix stdout alt_col_name; Verb.pr Verb.always "%i\t%i\t%i\t%i\n" !on_fhat !on_dhat !on_f !delayed let output_geometric_sched ?(duration = 2) output = output_col_hd (); let i = ref 0 and next = ref duration in (fun force -> if !i >= !next || force then (i := !i + 1; next := (!next * 15) / 10; output ()) else i := !i + 1) let set_open n i = n.ints.open_pos <- i and set_clean n i = n.ints.clean_pos <- i and set_geqe n ge = n.geqe <- ge and get_open n = n.ints.open_pos and get_clean n = n.ints.clean_pos and get_geqe n = n.geqe (************** Search functions **************) let make_initial initial hd = let np = Dpq.no_position in let h, d = neg_infinity, neg_infinity in let fp = { h = h; d = d; h_err = 0.; d_err = 0.; g = 0.; f = h; est_f = h; est_d = d;} and iv = {clean_pos = np; open_pos = np; depth = 0;} in let rec n = { data = initial; parent = n; geqe = Geq.make_dummy_entry (); ints = iv; fp = fp; } in n let make_expand recorder expand hd = let init = Geq.make_dummy_entry() in let no_pos = Dpq.no_position in let expand n = let nfp = n.fp in let nd = n.ints.depth + 1 and pf = nfp.f -. nfp.h_err and pd = nfp.d -. 1. -. nfp.d_err in let fnd = float nd in let children = List.map (fun (s, g) -> let h,d = hd s in let f = g +. h in let h_err = f -. pf and d_err = d -. pd in let h_err = if Math.finite_p h_err then h_err else n.fp.h_err and d_err = if Math.finite_p d_err then d_err else n.fp.d_err in let dstep = d_err /. fnd in let est_d = Math.fmax d (if dstep >= 1. then d /. 0.00001 else d /. (1. -. dstep)) in let est_h = h +. (Math.fmax 0. ((h_err /. fnd) *. est_d)) in let est_f = g +. est_h in let fp = { h = h; d = d; h_err = h_err; d_err = d_err; g = g; f = f; est_f = est_f; est_d = est_d;} and ints = { clean_pos = no_pos; open_pos = no_pos; depth = nd;} in assert (est_d >= 0.); assert (est_f >= f); { data = s; parent = n; geqe = init; ints = ints; fp = fp;}) (expand n.data nfp.g) in recorder n n.parent children; children in expand let make_get_node bound f_q geq i = let get_node () = let best_f = Dpq.peek_first f_q and best_fh = Geq.peek_doset geq and best_d = Geq.peek_best geq in let wf = (best_f.fp.f) *. bound in if best_d.fp.est_f <= wf then (incr on_dhat; best_d) else (if best_fh.fp.est_f <= wf then (incr on_fhat; best_fh) else (incr on_f; best_f)) in get_node let search op_rec clean_rec i key hash equals goal expand initial bound = let max_guess = truncate initial.fp.d in let openlist = (Geq.create_with open_sort focal_sort (make_close_enough bound) set_open get_open initial) and clean = Dpq.create clean_sort set_clean max_guess initial and closed = Htable.create hash equals max_guess in let get_node = make_get_node bound clean openlist i in let insert node state = Dpq.insert clean node; let ge = Geq.insert openlist node in set_geqe node ge; Htable.replace closed state node in let add_node n = Limit.incr_gen i; if not (Limit.promising_p i n) then Limit.incr_prune i else (let state = key n in try (let prev = Htable.find closed state in Limit.incr_dups i; if prev.fp.f > n.fp.f then (if prev.ints.clean_pos <> Dpq.no_position then (Dpq.remove clean prev.ints.clean_pos; Geq.remove openlist prev.geqe; insert n state) else insert n state)) with Not_found -> (* new state *) insert n state) in let do_expand n = Limit.incr_exp i; Geq.remove openlist (get_geqe n); Dpq.remove clean (n.ints.clean_pos); set_open n Dpq.no_position; set_clean n Dpq.no_position; if not (Limit.promising_p i n) then (Limit.incr_prune i; []) else expand n in let rec do_loop () = if not (Limit.halt_p i) && ((Geq.count openlist) > 0) then (op_rec i openlist; clean_rec i clean; let n = get_node () in if goal n then Limit.new_incumbent i (Limit.Incumbent (bound, n)) else (let children = do_expand n in List.iter add_node children; Limit.curr_q i (Geq.count openlist); do_loop())) in (* this is the part that actually does the search *) Dpq.insert clean initial; set_geqe initial (Geq.insert openlist initial); Htable.add closed (key initial) initial; do_loop (); i let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.fp.g) (fun n -> n.ints.depth) (fun n -> n.fp.est_f) let focal_rec key_printer key = Recorders.geq_focal_recorder key_printer (wrap key) let geq_rec key_printer key = Recorders.geq_all_recorder key_printer (wrap key) let dups sface args = let module SI = Search_interface in let exp = exp_rec sface.SI.key_printer (sface.SI.key) in let frec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec frec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_focal sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec = focal_rec sface.SI.key_printer (sface.SI.key) in let crec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_geq sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec = geq_rec sface.SI.key_printer (sface.SI.key) in let crec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_clean sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec _ _ = () in let crec = Recorders.dpq_recorder sface.SI.key_printer (wrap sface.SI.key) in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/recording/recording_tqs_v2.ml
ocaml
*************** Ordering Predicates ******************** sort by fhat break ties on low d break ties on high g ************** Utility functions ************* ************* Search functions ************* new state this is the part that actually does the search
* Tool for recording the executions of three queue search type fp_values = { h : float; d : float; h_err : float; d_err : float; g : float; f : float; est_f : float; est_d : float; } type int_vals = { mutable clean_pos : int; mutable open_pos : int; depth : int; } type 'a node = { data : 'a; parent: 'a node; mutable geqe : 'a node Geq.entry; ints : int_vals; fp : fp_values; } let open_sort a b = let afp = a.fp and bfp = b.fp in let aef = afp.est_f and bef = bfp.est_f and ag = afp.g and bg = bfp.g in ((aef = bef) && ((ag >= bg) ((ag = bg) && let focal_sort a b = let afp = a.fp and bfp = b.fp in let aed = afp.est_d and bed = bfp.est_d and aef = afp.est_f and bef = bfp.est_f in (aed < bed) || ((aed = bed) && ((aef < bef) || ((aef = bef) && (afp.g >= bfp.g)))) let clean_sort a b = let afp = a.fp and bfp = b.fp in let af = afp.f and bf= bfp.f in af < bf || (af = bf && afp.g >= bfp.g) let make_close_enough bound = let close_enough a b = (b.fp.est_f <= (a.fp.est_f *. bound)) in close_enough let better_p a b = (a.fp.f) <= (b.fp.f) let unwrap_sol = function | Limit.Incumbent (q, n) -> Some (n.data, n.fp.g) | _ -> None let wrap fn = (fun n -> fn n.data) let on_fhat = ref 0 and on_dhat = ref 0 and on_f = ref 0 and delayed = ref 0 let reset () = on_fhat := 0; on_dhat := 0; on_f := 0; delayed := 0 let incr r = r := !r + 1 let alt_col_name = "served" let output_col_hd () = Datafile.write_alt_colnames stdout alt_col_name ["on_fhat"; "on_dhat"; "on_f"; "delayed";] let output_row () = Datafile.write_alt_row_prefix stdout alt_col_name; Verb.pr Verb.always "%i\t%i\t%i\t%i\n" !on_fhat !on_dhat !on_f !delayed let output_geometric_sched ?(duration = 2) output = output_col_hd (); let i = ref 0 and next = ref duration in (fun force -> if !i >= !next || force then (i := !i + 1; next := (!next * 15) / 10; output ()) else i := !i + 1) let set_open n i = n.ints.open_pos <- i and set_clean n i = n.ints.clean_pos <- i and set_geqe n ge = n.geqe <- ge and get_open n = n.ints.open_pos and get_clean n = n.ints.clean_pos and get_geqe n = n.geqe let make_initial initial hd = let np = Dpq.no_position in let h, d = neg_infinity, neg_infinity in let fp = { h = h; d = d; h_err = 0.; d_err = 0.; g = 0.; f = h; est_f = h; est_d = d;} and iv = {clean_pos = np; open_pos = np; depth = 0;} in let rec n = { data = initial; parent = n; geqe = Geq.make_dummy_entry (); ints = iv; fp = fp; } in n let make_expand recorder expand hd = let init = Geq.make_dummy_entry() in let no_pos = Dpq.no_position in let expand n = let nfp = n.fp in let nd = n.ints.depth + 1 and pf = nfp.f -. nfp.h_err and pd = nfp.d -. 1. -. nfp.d_err in let fnd = float nd in let children = List.map (fun (s, g) -> let h,d = hd s in let f = g +. h in let h_err = f -. pf and d_err = d -. pd in let h_err = if Math.finite_p h_err then h_err else n.fp.h_err and d_err = if Math.finite_p d_err then d_err else n.fp.d_err in let dstep = d_err /. fnd in let est_d = Math.fmax d (if dstep >= 1. then d /. 0.00001 else d /. (1. -. dstep)) in let est_h = h +. (Math.fmax 0. ((h_err /. fnd) *. est_d)) in let est_f = g +. est_h in let fp = { h = h; d = d; h_err = h_err; d_err = d_err; g = g; f = f; est_f = est_f; est_d = est_d;} and ints = { clean_pos = no_pos; open_pos = no_pos; depth = nd;} in assert (est_d >= 0.); assert (est_f >= f); { data = s; parent = n; geqe = init; ints = ints; fp = fp;}) (expand n.data nfp.g) in recorder n n.parent children; children in expand let make_get_node bound f_q geq i = let get_node () = let best_f = Dpq.peek_first f_q and best_fh = Geq.peek_doset geq and best_d = Geq.peek_best geq in let wf = (best_f.fp.f) *. bound in if best_d.fp.est_f <= wf then (incr on_dhat; best_d) else (if best_fh.fp.est_f <= wf then (incr on_fhat; best_fh) else (incr on_f; best_f)) in get_node let search op_rec clean_rec i key hash equals goal expand initial bound = let max_guess = truncate initial.fp.d in let openlist = (Geq.create_with open_sort focal_sort (make_close_enough bound) set_open get_open initial) and clean = Dpq.create clean_sort set_clean max_guess initial and closed = Htable.create hash equals max_guess in let get_node = make_get_node bound clean openlist i in let insert node state = Dpq.insert clean node; let ge = Geq.insert openlist node in set_geqe node ge; Htable.replace closed state node in let add_node n = Limit.incr_gen i; if not (Limit.promising_p i n) then Limit.incr_prune i else (let state = key n in try (let prev = Htable.find closed state in Limit.incr_dups i; if prev.fp.f > n.fp.f then (if prev.ints.clean_pos <> Dpq.no_position then (Dpq.remove clean prev.ints.clean_pos; Geq.remove openlist prev.geqe; insert n state) else insert n state)) insert n state) in let do_expand n = Limit.incr_exp i; Geq.remove openlist (get_geqe n); Dpq.remove clean (n.ints.clean_pos); set_open n Dpq.no_position; set_clean n Dpq.no_position; if not (Limit.promising_p i n) then (Limit.incr_prune i; []) else expand n in let rec do_loop () = if not (Limit.halt_p i) && ((Geq.count openlist) > 0) then (op_rec i openlist; clean_rec i clean; let n = get_node () in if goal n then Limit.new_incumbent i (Limit.Incumbent (bound, n)) else (let children = do_expand n in List.iter add_node children; Limit.curr_q i (Geq.count openlist); do_loop())) in Dpq.insert clean initial; set_geqe initial (Geq.insert openlist initial); Htable.add closed (key initial) initial; do_loop (); i let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.fp.g) (fun n -> n.ints.depth) (fun n -> n.fp.est_f) let focal_rec key_printer key = Recorders.geq_focal_recorder key_printer (wrap key) let geq_rec key_printer key = Recorders.geq_all_recorder key_printer (wrap key) let dups sface args = let module SI = Search_interface in let exp = exp_rec sface.SI.key_printer (sface.SI.key) in let frec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec frec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_focal sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec = focal_rec sface.SI.key_printer (sface.SI.key) in let crec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_geq sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec = geq_rec sface.SI.key_printer (sface.SI.key) in let crec _ _ = () in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) let dups_clean sface args = let module SI = Search_interface in let exp _ _ _ _ = () in let frec _ _ = () in let crec = Recorders.dpq_recorder sface.SI.key_printer (wrap sface.SI.key) in let key = wrap sface.SI.key and hash = sface.SI.hash and equals = sface.SI.equals and goal = wrap sface.SI.goal_p and hd = sface.Search_interface.hd in let i = (Limit.make Limit.Nothing sface.SI.halt_on better_p (Limit.make_default_logger (fun n -> n.fp.g) (fun n -> n.ints.depth))) in let initial = make_initial sface.SI.initial hd and expand = make_expand (exp i) sface.SI.domain_expand hd in let bound = Search_args.get_float "Tqs_rewrite.dups" args 0 in reset(); let i = search frec crec i key hash equals goal expand initial bound in Limit.unwrap_sol6 unwrap_sol (Limit.results6 i) EOF
7b07b70f14c3fa91785680ffad8bde89d655cc93d84acc16b9c9f2da14c7dc9a
avatar29A/hs-aitubots-api
Errors.hs
module Aitu.Bot.Types.Errors ( ClientError , stringToClientError , coerceToClientError , coerceEitherStringToEitherCE ) where import qualified Data.ByteString.Lazy.Char8 as BC type HttpCode = Int type ClientError = (HttpCode, BC.ByteString) stringToClientError :: String -> ClientError stringToClientError s = (500, BC.pack s) coerceToClientError :: (e -> ClientError) -> Either e r -> Either ClientError r coerceToClientError f either = case either of Left msg -> Left $ f msg Right r -> Right r coerceEitherStringToEitherCE :: Either String r -> Either ClientError r coerceEitherStringToEitherCE = coerceToClientError stringToClientError
null
https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/src/Aitu/Bot/Types/Errors.hs
haskell
module Aitu.Bot.Types.Errors ( ClientError , stringToClientError , coerceToClientError , coerceEitherStringToEitherCE ) where import qualified Data.ByteString.Lazy.Char8 as BC type HttpCode = Int type ClientError = (HttpCode, BC.ByteString) stringToClientError :: String -> ClientError stringToClientError s = (500, BC.pack s) coerceToClientError :: (e -> ClientError) -> Either e r -> Either ClientError r coerceToClientError f either = case either of Left msg -> Left $ f msg Right r -> Right r coerceEitherStringToEitherCE :: Either String r -> Either ClientError r coerceEitherStringToEitherCE = coerceToClientError stringToClientError
dd4a821e05509bc61557d47f3530130ac0ff3f0ec4a8af3c06a4075b6e31e6f3
Dasudian/DSDIN
dsdhttp_api_validate.erl
-module(dsdhttp_api_validate). -export([request/4]). -export([response/5]). -export([validator/0]). -spec validator() -> jesse_state:state(). validator() -> {ok, AppName} = application:get_application(?MODULE), Filename = filename:join(code:priv_dir(AppName), "swagger.json"), R = jsx:decode(element(2, file:read_file(Filename))), jesse_state:new(R, [{default_schema_ver, <<"-schema.org/draft-04/schema#">>}]). -spec response( OperationId :: atom(), Methohd :: binary(), Code :: 200..599, Response :: jesse:json_term(), Validator :: jesse_state:state() ) -> ok | no_return(). response(OperationId, Method0, Code, Response, Validator) -> Method = to_method(Method0), #{responses := Resps} = maps:get(Method, endpoints:operation(OperationId)), case maps:get(Code, Resps, not_found) of undefined -> ok; not_found -> throw({error, {Code, unspecified_response_code}}); #{<<"$ref">> := Ref} -> Schema = #{<<"$ref">> => <<"#", Ref/binary>>}, _ = jesse_schema_validator:validate_with_state(Schema, Response, Validator), ok; #{<<"items">> := #{<<"$ref">> := Ref}, <<"type">> := <<"array">>} -> Schema = #{<<"$ref">> => <<"#", Ref/binary>>}, [ _ = jesse_schema_validator:validate_with_state(Schema, Acc, Validator) || Acc <- Response ], ok; Schema -> _ = jesse_schema_validator:validate_with_state(Schema, Response, Validator), ok end. -spec request( OperationId :: atom(), Methohd :: binary(), Req :: cowboy_req:req(), Validator :: jesse_state:state() ) -> {ok, Model :: #{}, cowboy_req:req()} | {error, Reason :: any(), cowboy_req:req()}. request(OperationId, Method0, Req, Validator) -> Method = to_method(Method0), #{parameters := Params} = maps:get(Method, endpoints:operation(OperationId)), params(Params, #{}, Req, Validator). params([], Model, Req, _) -> {ok, Model, Req}; params([Param | Params], Model, Req0, Validator) -> case populate_param(Param, Req0, Validator) of {ok, K, V, Req} -> NewModel = maps:put(to_atom(K), V, Model), params(Params, NewModel, Req, Validator); Error -> Error end. populate_param(Param, Req, Validator) -> In = proplists:get_value("in", Param), Name = proplists:get_value("name", Param), case get_param_value(In, Name, Req) of {ok, Value, Req1} -> case prepare_param(Param, Value, Name, Validator) of {ok, NewName, NewValue} -> {ok, NewName, NewValue, Req1}; {error, Reason} -> {error, Reason, Req1} end; Error -> Error end. prepare_param([], Value, Name, _) -> {ok, Name, Value}; prepare_param([ Rule | Rules ], Value, Name, Validator) -> case prepare_param_(Rule, Value, Name, Validator) of ok -> prepare_param(Rules, Value, Name, Validator); {ok, NewValue} -> prepare_param(Rules, NewValue, Name, Validator); {ok, NewValue, NewName} -> prepare_param(Rules, NewValue, NewName, Validator); Error -> Error end. % unused rules prepare_param_({"in", _}, _, _, _) -> ok; prepare_param_({"name", _}, _, _, _) -> ok; prepare_param_({"description", _}, _, _, _) -> ok; prepare_param_({"default", _}, _, _, _) -> ok; % required prepare_param_({"required",true}, undefined, Name, _) -> param_error(required, Name); prepare_param_({"required",_}, _, _, _) -> ok; prepare_param_(_, undefined, _, _) -> ok; % {type, _} prepare_param_({"type", "binary"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "boolean"}, Value, _, _) when is_boolean(Value) -> ok; prepare_param_({"type", "boolean"}, Value, Name, _) -> V = list_to_binary(string:to_lower(to_list(Value))), try case binary_to_existing_atom(V, utf8) of B when is_boolean(B) -> {ok, B}; _ -> param_error({type, Value}, Name) end catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "date"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "datetime"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "float"}, Value, Name, _) -> try {ok, to_float(Value)} catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "integer"}, Value, Name, _) -> try {ok, to_int(Value)} catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "string"}, _, _, _) -> ok; % schema prepare_param_({"schema", #{<<"$ref">> := <<"/definitions/", Ref/binary>>}}, Value, Name, Validator) -> try Schema = #{<<"$ref">> => <<"#/definitions/", Ref/binary>>}, jesse_schema_validator:validate_with_state(Schema, Value, Validator), {ok, Value, Ref} catch throw:[ Reason | _] -> Info0 = jesse_error:reason_to_jsx(Reason), Info1 = proplists:delete(schema, Info0), Info2 = proplists:delete(invalid, Info1), param_error({schema, Info2}, Name) end; prepare_param_({"schema",#{<<"type">> := _}}, _, _, _) -> ok; % enum prepare_param_({"enum", Values0}, Value0, Name, _) -> try Values = [ to_atom(Acc) || Acc <- Values0 ], Value = to_existing_atom(Value0), case lists:member(Value, Values) of true -> {ok, Value}; false -> param_error({enum, Value0}, Name) end catch error:badarg -> param_error({enum, Value0}, Name) end; % arythmetic prepare_param_({"minimum", Min}, Value, Name, _) -> case Value >= Min of true -> ok; false -> param_error({not_in_range, Value}, Name) end; prepare_param_({"maximum", Max}, Value, Name, _) -> case Value =< Max of true -> ok; false -> param_error({not_in_range, Value}, Name) end. get_param_value("body", _, Req0) -> case cowboy_req:read_body(Req0) of {ok, <<>>, Req} -> {ok, <<>>, Req}; {ok, Body, Req} -> try Value = jsx:decode(Body, [return_maps]), {ok, Value, Req} catch error:_ -> {error, Reason} = param_error({body, Body}, <<>>), {error, Reason, Req} end end; get_param_value("query", Name, Req) -> QS = cowboy_req:parse_qs(Req), Value = get_opt(to_qs(Name), QS), {ok, Value, Req}; get_param_value("header", Name, Req) -> Value = cowboy_req:header(to_header(Name), Req), {ok, Value, Req}; get_param_value("path", Name, Req) -> Value = cowboy_req:binding(to_binding(Name), Req), {ok, Value, Req}. param_error({enum, Value}, Name) -> param_error_(Name, #{error => not_in_enum, data => Value}); param_error({not_in_range, Value}, Name) -> param_error_(Name, #{error => not_in_range, data => Value}); param_error(required, Name) -> param_error_(Name, #{error => missing_required_property}); param_error({schema, Info}, Name) -> param_error_(Name, Info); param_error({type, Value}, Name) -> param_error_(Name, #{error => wrong_type, data => Value}); param_error({body, Value}, Name) -> param_error_(Name, #{error => invalid_body, data => Value}). param_error_(Name, Info) -> {error, {validation_error, to_binary(Name), Info}}. %%==================================================================== Utils %%==================================================================== -spec to_atom(binary() | list()) -> atom(). to_atom(Bin) when is_binary(Bin) -> binary_to_atom(Bin, utf8); to_atom(List) when is_list(List) -> list_to_atom(List). -spec to_existing_atom(binary() | list()) -> atom(). to_existing_atom(Bin) when is_binary(Bin) -> binary_to_existing_atom(Bin, utf8); to_existing_atom(List) when is_list(List) -> list_to_existing_atom(List). -spec to_float(iodata()) -> number(). to_float(V) -> Data = iolist_to_binary([V]), case binary:split(Data, <<$.>>) of [Data] -> binary_to_integer(Data); [<<>>, _] -> binary_to_float(<<$0, Data/binary>>); _ -> binary_to_float(Data) end. -spec to_int(integer() | binary() | list()) -> integer(). to_int(Data) when is_integer(Data) -> Data; to_int(Data) when is_binary(Data) -> binary_to_integer(Data); to_int(Data) when is_list(Data) -> list_to_integer(Data). -spec to_list(iodata() | atom() | number()) -> string(). to_list(V) when is_list(V) -> V; to_list(V) -> binary_to_list(to_binary(V)). -spec to_binary(iodata() | atom() | number()) -> binary(). to_binary(V) when is_binary(V) -> V; to_binary(V) when is_list(V) -> iolist_to_binary(V); to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); to_binary(V) when is_integer(V) -> integer_to_binary(V); to_binary(V) when is_float(V) -> float_to_binary(V). -spec get_opt(any(), []) -> any(). get_opt(Key, Opts) -> get_opt(Key, Opts, undefined). -spec get_opt(any(), [], any()) -> any(). get_opt(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; false -> Default end. -spec to_qs(iodata() | atom() | number()) -> binary(). to_qs(Name) -> to_binary(Name). -spec to_header(iodata() | atom() | number()) -> binary(). to_header(Name) -> string:lowercase(to_binary(Name)). -spec to_binding(iodata() | atom() | number()) -> atom(). to_binding(Name) -> Prepared = to_binary(Name), binary_to_atom(Prepared, utf8). -spec to_method(binary()) -> atom(). to_method(Method) -> to_existing_atom(string:lowercase(Method)).
null
https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdhttp/src/dsdhttp_api_validate.erl
erlang
unused rules required {type, _} schema enum arythmetic ==================================================================== ====================================================================
-module(dsdhttp_api_validate). -export([request/4]). -export([response/5]). -export([validator/0]). -spec validator() -> jesse_state:state(). validator() -> {ok, AppName} = application:get_application(?MODULE), Filename = filename:join(code:priv_dir(AppName), "swagger.json"), R = jsx:decode(element(2, file:read_file(Filename))), jesse_state:new(R, [{default_schema_ver, <<"-schema.org/draft-04/schema#">>}]). -spec response( OperationId :: atom(), Methohd :: binary(), Code :: 200..599, Response :: jesse:json_term(), Validator :: jesse_state:state() ) -> ok | no_return(). response(OperationId, Method0, Code, Response, Validator) -> Method = to_method(Method0), #{responses := Resps} = maps:get(Method, endpoints:operation(OperationId)), case maps:get(Code, Resps, not_found) of undefined -> ok; not_found -> throw({error, {Code, unspecified_response_code}}); #{<<"$ref">> := Ref} -> Schema = #{<<"$ref">> => <<"#", Ref/binary>>}, _ = jesse_schema_validator:validate_with_state(Schema, Response, Validator), ok; #{<<"items">> := #{<<"$ref">> := Ref}, <<"type">> := <<"array">>} -> Schema = #{<<"$ref">> => <<"#", Ref/binary>>}, [ _ = jesse_schema_validator:validate_with_state(Schema, Acc, Validator) || Acc <- Response ], ok; Schema -> _ = jesse_schema_validator:validate_with_state(Schema, Response, Validator), ok end. -spec request( OperationId :: atom(), Methohd :: binary(), Req :: cowboy_req:req(), Validator :: jesse_state:state() ) -> {ok, Model :: #{}, cowboy_req:req()} | {error, Reason :: any(), cowboy_req:req()}. request(OperationId, Method0, Req, Validator) -> Method = to_method(Method0), #{parameters := Params} = maps:get(Method, endpoints:operation(OperationId)), params(Params, #{}, Req, Validator). params([], Model, Req, _) -> {ok, Model, Req}; params([Param | Params], Model, Req0, Validator) -> case populate_param(Param, Req0, Validator) of {ok, K, V, Req} -> NewModel = maps:put(to_atom(K), V, Model), params(Params, NewModel, Req, Validator); Error -> Error end. populate_param(Param, Req, Validator) -> In = proplists:get_value("in", Param), Name = proplists:get_value("name", Param), case get_param_value(In, Name, Req) of {ok, Value, Req1} -> case prepare_param(Param, Value, Name, Validator) of {ok, NewName, NewValue} -> {ok, NewName, NewValue, Req1}; {error, Reason} -> {error, Reason, Req1} end; Error -> Error end. prepare_param([], Value, Name, _) -> {ok, Name, Value}; prepare_param([ Rule | Rules ], Value, Name, Validator) -> case prepare_param_(Rule, Value, Name, Validator) of ok -> prepare_param(Rules, Value, Name, Validator); {ok, NewValue} -> prepare_param(Rules, NewValue, Name, Validator); {ok, NewValue, NewName} -> prepare_param(Rules, NewValue, NewName, Validator); Error -> Error end. prepare_param_({"in", _}, _, _, _) -> ok; prepare_param_({"name", _}, _, _, _) -> ok; prepare_param_({"description", _}, _, _, _) -> ok; prepare_param_({"default", _}, _, _, _) -> ok; prepare_param_({"required",true}, undefined, Name, _) -> param_error(required, Name); prepare_param_({"required",_}, _, _, _) -> ok; prepare_param_(_, undefined, _, _) -> ok; prepare_param_({"type", "binary"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "boolean"}, Value, _, _) when is_boolean(Value) -> ok; prepare_param_({"type", "boolean"}, Value, Name, _) -> V = list_to_binary(string:to_lower(to_list(Value))), try case binary_to_existing_atom(V, utf8) of B when is_boolean(B) -> {ok, B}; _ -> param_error({type, Value}, Name) end catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "date"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "datetime"}, Value, Name, _) -> case is_binary(Value) of true -> ok; false -> param_error({type, Value}, Name) end; prepare_param_({"type", "float"}, Value, Name, _) -> try {ok, to_float(Value)} catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "integer"}, Value, Name, _) -> try {ok, to_int(Value)} catch error:badarg -> param_error({type, Value}, Name) end; prepare_param_({"type", "string"}, _, _, _) -> ok; prepare_param_({"schema", #{<<"$ref">> := <<"/definitions/", Ref/binary>>}}, Value, Name, Validator) -> try Schema = #{<<"$ref">> => <<"#/definitions/", Ref/binary>>}, jesse_schema_validator:validate_with_state(Schema, Value, Validator), {ok, Value, Ref} catch throw:[ Reason | _] -> Info0 = jesse_error:reason_to_jsx(Reason), Info1 = proplists:delete(schema, Info0), Info2 = proplists:delete(invalid, Info1), param_error({schema, Info2}, Name) end; prepare_param_({"schema",#{<<"type">> := _}}, _, _, _) -> ok; prepare_param_({"enum", Values0}, Value0, Name, _) -> try Values = [ to_atom(Acc) || Acc <- Values0 ], Value = to_existing_atom(Value0), case lists:member(Value, Values) of true -> {ok, Value}; false -> param_error({enum, Value0}, Name) end catch error:badarg -> param_error({enum, Value0}, Name) end; prepare_param_({"minimum", Min}, Value, Name, _) -> case Value >= Min of true -> ok; false -> param_error({not_in_range, Value}, Name) end; prepare_param_({"maximum", Max}, Value, Name, _) -> case Value =< Max of true -> ok; false -> param_error({not_in_range, Value}, Name) end. get_param_value("body", _, Req0) -> case cowboy_req:read_body(Req0) of {ok, <<>>, Req} -> {ok, <<>>, Req}; {ok, Body, Req} -> try Value = jsx:decode(Body, [return_maps]), {ok, Value, Req} catch error:_ -> {error, Reason} = param_error({body, Body}, <<>>), {error, Reason, Req} end end; get_param_value("query", Name, Req) -> QS = cowboy_req:parse_qs(Req), Value = get_opt(to_qs(Name), QS), {ok, Value, Req}; get_param_value("header", Name, Req) -> Value = cowboy_req:header(to_header(Name), Req), {ok, Value, Req}; get_param_value("path", Name, Req) -> Value = cowboy_req:binding(to_binding(Name), Req), {ok, Value, Req}. param_error({enum, Value}, Name) -> param_error_(Name, #{error => not_in_enum, data => Value}); param_error({not_in_range, Value}, Name) -> param_error_(Name, #{error => not_in_range, data => Value}); param_error(required, Name) -> param_error_(Name, #{error => missing_required_property}); param_error({schema, Info}, Name) -> param_error_(Name, Info); param_error({type, Value}, Name) -> param_error_(Name, #{error => wrong_type, data => Value}); param_error({body, Value}, Name) -> param_error_(Name, #{error => invalid_body, data => Value}). param_error_(Name, Info) -> {error, {validation_error, to_binary(Name), Info}}. Utils -spec to_atom(binary() | list()) -> atom(). to_atom(Bin) when is_binary(Bin) -> binary_to_atom(Bin, utf8); to_atom(List) when is_list(List) -> list_to_atom(List). -spec to_existing_atom(binary() | list()) -> atom(). to_existing_atom(Bin) when is_binary(Bin) -> binary_to_existing_atom(Bin, utf8); to_existing_atom(List) when is_list(List) -> list_to_existing_atom(List). -spec to_float(iodata()) -> number(). to_float(V) -> Data = iolist_to_binary([V]), case binary:split(Data, <<$.>>) of [Data] -> binary_to_integer(Data); [<<>>, _] -> binary_to_float(<<$0, Data/binary>>); _ -> binary_to_float(Data) end. -spec to_int(integer() | binary() | list()) -> integer(). to_int(Data) when is_integer(Data) -> Data; to_int(Data) when is_binary(Data) -> binary_to_integer(Data); to_int(Data) when is_list(Data) -> list_to_integer(Data). -spec to_list(iodata() | atom() | number()) -> string(). to_list(V) when is_list(V) -> V; to_list(V) -> binary_to_list(to_binary(V)). -spec to_binary(iodata() | atom() | number()) -> binary(). to_binary(V) when is_binary(V) -> V; to_binary(V) when is_list(V) -> iolist_to_binary(V); to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); to_binary(V) when is_integer(V) -> integer_to_binary(V); to_binary(V) when is_float(V) -> float_to_binary(V). -spec get_opt(any(), []) -> any(). get_opt(Key, Opts) -> get_opt(Key, Opts, undefined). -spec get_opt(any(), [], any()) -> any(). get_opt(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; false -> Default end. -spec to_qs(iodata() | atom() | number()) -> binary(). to_qs(Name) -> to_binary(Name). -spec to_header(iodata() | atom() | number()) -> binary(). to_header(Name) -> string:lowercase(to_binary(Name)). -spec to_binding(iodata() | atom() | number()) -> atom(). to_binding(Name) -> Prepared = to_binary(Name), binary_to_atom(Prepared, utf8). -spec to_method(binary()) -> atom(). to_method(Method) -> to_existing_atom(string:lowercase(Method)).
9011ada681e15b76ea8176ae56976c9657fe0df52d96f63276a56808dcbeddf7
racket/readline
rep.rkt
;; This is a wrapper around "rep-start.rkt" -- use it if we're using a terminal #lang racket/base (require racket/runtime-path racket/file) (define-runtime-path rep-start "rep-start.rkt") (provide install-readline! pre-readline-input-port) (define pre-readline-input-port (let ([inp (current-input-port)] [outp (current-output-port)]) (and (eq? 'stdin (object-name inp)) (terminal-port? inp) (dynamic-require rep-start 'pre-readline-input-port)))) (define readline-init-expr '(require readline/rep)) (define (install-readline!) (define file (find-system-path 'init-file)) (define (add! msg) (call-with-output-file* file #:exists 'append (lambda (o) (fprintf o "\n;; load readline support ~a\n~s\n" "(added by `install-readline!')" readline-init-expr))) (printf msg file)) (cond [(not (file-exists? file)) (add! "\"~a\" created and readline initialization added.\n")] [(with-handlers ([exn:fail? (lambda (exn) (error 'install-readline! "trouble reading existing ~e: ~a" file (exn-message exn)))]) (not (member readline-init-expr (file->list file)))) (add! "Readline initialization added to \"~a\".\n")] [else (printf "Readline already installed in \"~a\".\n" file)]))
null
https://raw.githubusercontent.com/racket/readline/f2c01b705853dd26c51691a1fc78ee743605c8bd/readline-lib/readline/rep.rkt
racket
This is a wrapper around "rep-start.rkt" -- use it if we're using a terminal
#lang racket/base (require racket/runtime-path racket/file) (define-runtime-path rep-start "rep-start.rkt") (provide install-readline! pre-readline-input-port) (define pre-readline-input-port (let ([inp (current-input-port)] [outp (current-output-port)]) (and (eq? 'stdin (object-name inp)) (terminal-port? inp) (dynamic-require rep-start 'pre-readline-input-port)))) (define readline-init-expr '(require readline/rep)) (define (install-readline!) (define file (find-system-path 'init-file)) (define (add! msg) (call-with-output-file* file #:exists 'append (lambda (o) (fprintf o "\n;; load readline support ~a\n~s\n" "(added by `install-readline!')" readline-init-expr))) (printf msg file)) (cond [(not (file-exists? file)) (add! "\"~a\" created and readline initialization added.\n")] [(with-handlers ([exn:fail? (lambda (exn) (error 'install-readline! "trouble reading existing ~e: ~a" file (exn-message exn)))]) (not (member readline-init-expr (file->list file)))) (add! "Readline initialization added to \"~a\".\n")] [else (printf "Readline already installed in \"~a\".\n" file)]))
c9186b6caedfd7784d4eec0afda6a2e6e7c10d0062c1c7c5698984190dfda863
Bogdanp/racket-kafka
info.rkt
#lang info (define license 'BSD-3-Clause) (define version "0.2.1") (define collection "confluent") (define deps '("base" "http-easy-lib" "threading-lib"))
null
https://raw.githubusercontent.com/Bogdanp/racket-kafka/30b0254e7d66e9e5e321494a1754207e18459466/confluent-schema-registry-lib/info.rkt
racket
#lang info (define license 'BSD-3-Clause) (define version "0.2.1") (define collection "confluent") (define deps '("base" "http-easy-lib" "threading-lib"))
e119dcf21718e2f352a417fc0f71f9c9fcc7e00372e679ca46a4b53554bb07f6
dongcarl/guix
proxy.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu installer proxy) #:use-module (gnu installer utils) #:use-module (gnu services herd) #:export (set-http-proxy clear-http-proxy)) (define (set-http-proxy proxy) (with-silent-shepherd (with-shepherd-action 'guix-daemon ('set-http-proxy proxy) result result))) (define (clear-http-proxy) (with-silent-shepherd (with-shepherd-action 'guix-daemon ('set-http-proxy) result result))) ;; Local Variables: ;; eval: (put 'with-silent-shepherd 'scheme-indent-function 0) ;; End:
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/installer/proxy.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Local Variables: eval: (put 'with-silent-shepherd 'scheme-indent-function 0) End:
Copyright © 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu installer proxy) #:use-module (gnu installer utils) #:use-module (gnu services herd) #:export (set-http-proxy clear-http-proxy)) (define (set-http-proxy proxy) (with-silent-shepherd (with-shepherd-action 'guix-daemon ('set-http-proxy proxy) result result))) (define (clear-http-proxy) (with-silent-shepherd (with-shepherd-action 'guix-daemon ('set-http-proxy) result result)))
823c70e34c9e7f66aab4e92ddcaea744cd6871d0996a13035aa53fd458ff6345
PeterDWhite/Osker
MVarInfo.hs
Copyright ( c ) , 2003 module MVarInfo Information about MVar in threader state Mapping MVar i d to MVar information , mvarsStats -- Statistics about an MVars structure , MVarGen -- Handle to generate MVars Print out an MVar , clobbers -- Clobber evidence of a tid from collection of MVars , addTaker -- Make another tid waiting on full , addPutter -- Make another tid waiting on empty Look up MVinfo associated with an mvar i d L hjgymmmmook up MVinfo associated with an mvar i d Update the value associated with an MVar Update the information associated with an MVar Make up a new MVar info Remove an MVar from the map Add a new MVar to the map , mvarsToList -- Convert MVars to list , sizeMVars -- How many MVars are there? Check if MVar has a value Check if MVar is empty Take the value from the mvar , and first putter Put the value in , return first taker ) where ---------------------------------------------------------------------- -- Information about MVars in the threader state ---------------------------------------------------------------------- -- Haskell imports import Dynamic (Dynamic) import FiniteMap (FiniteMap, emptyFM, lookupFM, addToFM, fmToList, sizeFM, mapFM, delFromFM) import List import Maybe -- Utility imports import Null Osker imports import qualified BraidMVar as MV -- Resumption imports import ThreadId Data for waiting on an MVar to become empty data WaitEmpty = WaitEmpty {putter :: ThreadId, val :: Dynamic} deriving (Show) instance Eq WaitEmpty where we1 == we2 = putter we1 == putter we2 The stuff associated with the mvar in the MVar state . data MVarInfo = MVarInfo { waitingEmpty :: [WaitEmpty] -- Threads waiting on empty , waitingFull :: [ThreadId] -- Threads waiting on full MVar value , Nothing when empty Who created the MVar } deriving (Show) type Transerver a = MVarInfo -> (MVarInfo, a) -- The collection of MVars in the threader state data MVars = MVars (FiniteMap MV.MVarId MVarInfo) Take a value from the MVar , and also the first putter , if there is one takeValPutter :: Transerver (Maybe ThreadId) takeValPutter mvinfo = case waitingEmpty mvinfo of [] -> ( mvinfo { value = Nothing }, Nothing ) (w:ws) -> ( mvinfo { value = Nothing, waitingEmpty = ws } , Just ( putter w ) ) Put a value from the MVar , and return the first taker , if there is one putValTaker :: Dynamic -> Transerver (Maybe ThreadId) putValTaker dyn mvinfo = case waitingFull mvinfo of [] -> ( mvinfo { value = Just dyn }, Nothing ) (w:ws) -> ( mvinfo { value = Just dyn, waitingFull = ws }, Just w ) instance Null MVars where mkNull = MVars emptyFM See if an MVar has a value hasValue :: Maybe MVarInfo -> Bool hasValue Nothing = False hasValue (Just mvinfo) = isJust ( value mvinfo ) See if an MVar is empty isEmpty :: Maybe MVarInfo -> Bool isEmpty Nothing = False isEmpty (Just mvinfo) = isNothing ( value mvinfo ) -- Lookup a value from the mvar collection lookupMVarHard :: MVars -> MV.MVarId -> MVarInfo lookupMVarHard mvars mvid = case lookupMVar mvars mvid of Nothing -> error ("lookupMVarHard: " ++ show mvid) Just mvinfo -> mvinfo -- Lookup a value from the mvar collection lookupMVar :: MVars -> MV.MVarId -> Maybe MVarInfo lookupMVar (MVars mvars) mvid = lookupFM mvars mvid Update the value associated with an MVar updateMVar :: MVars -> MV.MVarId -> Maybe Dynamic -> MVars updateMVar mvars mvid mdyn = let mvinfo' = ( lookupMVarHard mvars mvid ) { value = mdyn } in updateMVarInfo mvars mvid mvinfo' Add a new MVar to the map addMVar :: MVars -> MV.MVarId -> MVarInfo -> MVars addMVar = updateMVarInfo Update the info associated with an MVar updateMVarInfo :: MVars -> MV.MVarId -> MVarInfo -> MVars updateMVarInfo (MVars mvmap) mvid mvinfo = MVars (addToFM mvmap mvid mvinfo) -- Convert MVars to list mvarsToList :: MVars -> [(MV.MVarId, MVarInfo)] mvarsToList (MVars mvars) = fmToList mvars -- Find out how many MVars there are sizeMVars :: MVars -> Int sizeMVars (MVars mvars) = sizeFM mvars Get statistics about a single MVar mvarStats :: MVarInfo -> (Int, Int) mvarStats mvinfo = ( length (waitingEmpty mvinfo) , length (waitingFull mvinfo) ) Combine the statistics of two MVars into a summary statistic combineMvarStats :: (Int, Int) -> (Int, Int) -> (Int, Int) combineMvarStats (m1, n1) (m2, n2) = (m1 + m2, n1 + n2) -- Get stats about a list of mvars with Ids. mvarsStats :: MVars -> (Int, Int) mvarsStats (MVars mvars) = let lmvars = fmToList mvars in foldr combineMvarStats (0, 0) (map (mvarStats . snd) lmvars) A handle to generate new MVars . type MVarGen = Int Print out an MVarId , outMVarP :: (MV.MVarId, MVarInfo) -> String outMVarP (mvid, mvinfo) = let empties = waitingEmpty mvinfo fulls = waitingFull mvinfo mval = value mvinfo tidout = if null empties && null fulls then "None Waiting" else "E=" ++ show empties ++ ",F=" ++ show fulls valout = case mval of Nothing -> "Empty" Just _ -> "Full " in "\t MVar= " ++ show mvid ++ " | " ++ valout ++ " |< " ++ tidout ++ " >|\n" -- Delete entry for a tid from a list of wait empties. deleteTid :: ThreadId -> [WaitEmpty] -> [WaitEmpty] deleteTid _tid [] = [] deleteTid tid (we:wes) = if (putter we == tid) then wes else we:deleteTid tid wes Get rid of information about an thread from an MVar . clobber :: ThreadId -> MVarInfo -> MVarInfo clobber tid mvinfo = mvinfo { waitingEmpty = deleteTid tid (waitingEmpty mvinfo) , waitingFull = delete tid (waitingFull mvinfo) } -- Clobber all information about a tid from a collection of MVars clobbers :: ThreadId -> MVars -> MVars clobbers tid (MVars mvars) = MVars (mapFM (\_mvid mvar -> clobber tid mvar) mvars) Make up a new MVar info newMVar :: ThreadId -> Maybe Dynamic -> MVarInfo newMVar tid mdyn = MVarInfo { waitingEmpty = [] , waitingFull = [] , value = mdyn , creator = tid } Remove an MVar from the map deleteMVar :: MVars -> MV.MVarId -> MVars deleteMVar (MVars mvars) mvid = MVars (delFromFM mvars mvid) -- Make a new tid waiting on full addTaker :: ThreadId -> MV.MVarId -> MVars -> MVars addTaker tid mvid mvars = let mvinfo = lookupMVarHard mvars mvid mvinfo' = mvinfo { waitingFull = nub ((waitingFull mvinfo) ++ [tid]) , value = Nothing } in updateMVarInfo mvars mvid mvinfo' -- Make a new tid waiting on empty addPutter :: ThreadId -> MV.MVarId -> Dynamic -> MVars -> MVars addPutter tid mvid dyn mvars = let mvinfo = lookupMVarHard mvars mvid waitE = WaitEmpty { putter = tid, val = dyn } mvinfo' = mvinfo { waitingEmpty = nub (waitingEmpty mvinfo ++ [waitE] ) } in updateMVarInfo mvars mvid mvinfo' ---------------------------------------------------------------------- -- Inline some functions ---------------------------------------------------------------------- {-# INLINE takeValPutter #-} {-# INLINE putValTaker #-} # INLINE hasValue # {-# INLINE isEmpty #-} {-# INLINE lookupMVarHard #-} {-# INLINE lookupMVar #-} {-# INLINE updateMVar #-} {-# INLINE addMVar #-} # INLINE updateMVarInfo # {-# INLINE mvarsToList #-} # INLINE sizeMVars # # INLINE mvarStats # {-# INLINE combineMvarStats #-} {-# INLINE clobber #-} # INLINE clobbers # {-# INLINE newMVar #-} {-# INLINE deleteMVar #-} # INLINE addTaker #
null
https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Braid/MVarInfo.hs
haskell
Statistics about an MVars structure Handle to generate MVars Clobber evidence of a tid from collection of MVars Make another tid waiting on full Make another tid waiting on empty Convert MVars to list How many MVars are there? -------------------------------------------------------------------- Information about MVars in the threader state -------------------------------------------------------------------- Haskell imports Utility imports Resumption imports Threads waiting on empty Threads waiting on full The collection of MVars in the threader state Lookup a value from the mvar collection Lookup a value from the mvar collection Convert MVars to list Find out how many MVars there are Get stats about a list of mvars with Ids. Delete entry for a tid from a list of wait empties. Clobber all information about a tid from a collection of MVars Make a new tid waiting on full Make a new tid waiting on empty -------------------------------------------------------------------- Inline some functions -------------------------------------------------------------------- # INLINE takeValPutter # # INLINE putValTaker # # INLINE isEmpty # # INLINE lookupMVarHard # # INLINE lookupMVar # # INLINE updateMVar # # INLINE addMVar # # INLINE mvarsToList # # INLINE combineMvarStats # # INLINE clobber # # INLINE newMVar # # INLINE deleteMVar #
Copyright ( c ) , 2003 module MVarInfo Information about MVar in threader state Mapping MVar i d to MVar information Print out an MVar Look up MVinfo associated with an mvar i d L hjgymmmmook up MVinfo associated with an mvar i d Update the value associated with an MVar Update the information associated with an MVar Make up a new MVar info Remove an MVar from the map Add a new MVar to the map Check if MVar has a value Check if MVar is empty Take the value from the mvar , and first putter Put the value in , return first taker ) where import Dynamic (Dynamic) import FiniteMap (FiniteMap, emptyFM, lookupFM, addToFM, fmToList, sizeFM, mapFM, delFromFM) import List import Maybe import Null Osker imports import qualified BraidMVar as MV import ThreadId Data for waiting on an MVar to become empty data WaitEmpty = WaitEmpty {putter :: ThreadId, val :: Dynamic} deriving (Show) instance Eq WaitEmpty where we1 == we2 = putter we1 == putter we2 The stuff associated with the mvar in the MVar state . data MVarInfo = MVarInfo MVar value , Nothing when empty Who created the MVar } deriving (Show) type Transerver a = MVarInfo -> (MVarInfo, a) data MVars = MVars (FiniteMap MV.MVarId MVarInfo) Take a value from the MVar , and also the first putter , if there is one takeValPutter :: Transerver (Maybe ThreadId) takeValPutter mvinfo = case waitingEmpty mvinfo of [] -> ( mvinfo { value = Nothing }, Nothing ) (w:ws) -> ( mvinfo { value = Nothing, waitingEmpty = ws } , Just ( putter w ) ) Put a value from the MVar , and return the first taker , if there is one putValTaker :: Dynamic -> Transerver (Maybe ThreadId) putValTaker dyn mvinfo = case waitingFull mvinfo of [] -> ( mvinfo { value = Just dyn }, Nothing ) (w:ws) -> ( mvinfo { value = Just dyn, waitingFull = ws }, Just w ) instance Null MVars where mkNull = MVars emptyFM See if an MVar has a value hasValue :: Maybe MVarInfo -> Bool hasValue Nothing = False hasValue (Just mvinfo) = isJust ( value mvinfo ) See if an MVar is empty isEmpty :: Maybe MVarInfo -> Bool isEmpty Nothing = False isEmpty (Just mvinfo) = isNothing ( value mvinfo ) lookupMVarHard :: MVars -> MV.MVarId -> MVarInfo lookupMVarHard mvars mvid = case lookupMVar mvars mvid of Nothing -> error ("lookupMVarHard: " ++ show mvid) Just mvinfo -> mvinfo lookupMVar :: MVars -> MV.MVarId -> Maybe MVarInfo lookupMVar (MVars mvars) mvid = lookupFM mvars mvid Update the value associated with an MVar updateMVar :: MVars -> MV.MVarId -> Maybe Dynamic -> MVars updateMVar mvars mvid mdyn = let mvinfo' = ( lookupMVarHard mvars mvid ) { value = mdyn } in updateMVarInfo mvars mvid mvinfo' Add a new MVar to the map addMVar :: MVars -> MV.MVarId -> MVarInfo -> MVars addMVar = updateMVarInfo Update the info associated with an MVar updateMVarInfo :: MVars -> MV.MVarId -> MVarInfo -> MVars updateMVarInfo (MVars mvmap) mvid mvinfo = MVars (addToFM mvmap mvid mvinfo) mvarsToList :: MVars -> [(MV.MVarId, MVarInfo)] mvarsToList (MVars mvars) = fmToList mvars sizeMVars :: MVars -> Int sizeMVars (MVars mvars) = sizeFM mvars Get statistics about a single MVar mvarStats :: MVarInfo -> (Int, Int) mvarStats mvinfo = ( length (waitingEmpty mvinfo) , length (waitingFull mvinfo) ) Combine the statistics of two MVars into a summary statistic combineMvarStats :: (Int, Int) -> (Int, Int) -> (Int, Int) combineMvarStats (m1, n1) (m2, n2) = (m1 + m2, n1 + n2) mvarsStats :: MVars -> (Int, Int) mvarsStats (MVars mvars) = let lmvars = fmToList mvars in foldr combineMvarStats (0, 0) (map (mvarStats . snd) lmvars) A handle to generate new MVars . type MVarGen = Int Print out an MVarId , outMVarP :: (MV.MVarId, MVarInfo) -> String outMVarP (mvid, mvinfo) = let empties = waitingEmpty mvinfo fulls = waitingFull mvinfo mval = value mvinfo tidout = if null empties && null fulls then "None Waiting" else "E=" ++ show empties ++ ",F=" ++ show fulls valout = case mval of Nothing -> "Empty" Just _ -> "Full " in "\t MVar= " ++ show mvid ++ " | " ++ valout ++ " |< " ++ tidout ++ " >|\n" deleteTid :: ThreadId -> [WaitEmpty] -> [WaitEmpty] deleteTid _tid [] = [] deleteTid tid (we:wes) = if (putter we == tid) then wes else we:deleteTid tid wes Get rid of information about an thread from an MVar . clobber :: ThreadId -> MVarInfo -> MVarInfo clobber tid mvinfo = mvinfo { waitingEmpty = deleteTid tid (waitingEmpty mvinfo) , waitingFull = delete tid (waitingFull mvinfo) } clobbers :: ThreadId -> MVars -> MVars clobbers tid (MVars mvars) = MVars (mapFM (\_mvid mvar -> clobber tid mvar) mvars) Make up a new MVar info newMVar :: ThreadId -> Maybe Dynamic -> MVarInfo newMVar tid mdyn = MVarInfo { waitingEmpty = [] , waitingFull = [] , value = mdyn , creator = tid } Remove an MVar from the map deleteMVar :: MVars -> MV.MVarId -> MVars deleteMVar (MVars mvars) mvid = MVars (delFromFM mvars mvid) addTaker :: ThreadId -> MV.MVarId -> MVars -> MVars addTaker tid mvid mvars = let mvinfo = lookupMVarHard mvars mvid mvinfo' = mvinfo { waitingFull = nub ((waitingFull mvinfo) ++ [tid]) , value = Nothing } in updateMVarInfo mvars mvid mvinfo' addPutter :: ThreadId -> MV.MVarId -> Dynamic -> MVars -> MVars addPutter tid mvid dyn mvars = let mvinfo = lookupMVarHard mvars mvid waitE = WaitEmpty { putter = tid, val = dyn } mvinfo' = mvinfo { waitingEmpty = nub (waitingEmpty mvinfo ++ [waitE] ) } in updateMVarInfo mvars mvid mvinfo' # INLINE hasValue # # INLINE updateMVarInfo # # INLINE sizeMVars # # INLINE mvarStats # # INLINE clobbers # # INLINE addTaker #
102740edacc620e870f609e7621ed8e3177b46bec56842c440eafdbe12457b3d
skanev/playground
16.scm
SICP exercise 4.16 ; ; In this exercise we implement the method just described for interpreting ; internal definitions. We assume that the evaluator supports let (see exercise 4.6 ) . ; a. Change the lookup - variable - value ( section 4.1.3 ) to singal an error if the ; value it finds is the symbol *unassigned*. ; ; b. Write a procedure scan-out-defines that takes a procedure body and returns ; an equivalent one that has no internal definitions, by making the ; transformation described above. ; ; c. Install scan-out-defines in the interpreter, either in make-procedure or ; in procedure-body (see section 4.1.3). Which place is better? Why? (require r5rs/init) ; a. Here is the modified procedure: (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (let ((value (car vals))) (if (eq? value '*unassigned*) (error "Unassigned variable" var) value))) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) ; b. Here's scan-out-defines: (define (scan-out-defines body) (define (definitions-in body) (cond ((null? body) '()) ((definition? (car body)) (cons (car body) (definitions-in (cdr body)))) (else (definitions-in (cdr body))))) (define (body-without-definitions body) (cond ((null? body) '()) ((definition? (car body)) (body-without-definitions (cdr body))) (else (cons (car body) (body-without-definitions (cdr body)))))) (define (definition->unassigned-pair definition) (list (definition-variable definition) ''*unassigned*)) (define (definition->set! definition) (list 'set! (definition-variable definition) (definition-value definition))) (define (defines->let definitions body) (list (cons 'let (cons (map definition->unassigned-pair definitions) (append (map definition->set! definitions) body))))) (let ((internal-definitions (definitions-in body))) (if (null? internal-definitions) body (defines->let internal-definitions (body-without-definitions body))))) ; c. And finally, we install it in. We do it in make-procedure, because that is ; more efficient - it is called once for each procedure. Otherwise, it will be ; called on every procedure invocation (define (make-procedure parameters body env) (list 'procedure parameters (scan-out-defines body) env)) ; The rest of the interpreter. Note that I added a primitive procedure list to ; enable an easier test case. (define (evaluate exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (evaluate (cond->if exp) env)) ((let? exp) (evaluate (let->combination exp) env)) ((application? exp) (apply-procedure (evaluate (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type - EVALUATE" exp)))) (define (apply-procedure procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "Unknown procedure type - APPLY-PROCEDURE" procedure)))) (define (list-of-values exps env) (if (no-operands? exps) '() (cons (evaluate (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (evaluate (if-predicate exp) env)) (evaluate (if-consequent exp) env) (evaluate (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (evaluate (first-exp exps) env)) (else (evaluate (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (evaluate (assignment-value exp) env) env) 'ok) (define (eval-definition exp env) (define-variable! (definition-variable exp) (evaluate (definition-value exp) env) env) 'ok) (define (self-evaluating? exp) (cond ((number? exp) true) ((string? exp) true) (else false))) (define (variable? exp) (symbol? exp)) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp) (cadr exp)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false)) (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-lambda parameters body) (cons 'lambda (cons parameters body))) (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false)) (define (make-if predicate consequent alternative) (list 'if predicate consequent alternative)) (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions exp) (cdr exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin seq) (cons 'begin seq)) (define (application? exp) (pair? exp)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp)) (define (no-operands? ops) (null? ops)) (define (first-operand ops) (car ops)) (define (rest-operands ops) (cdr ops)) (define (let? exp) (tagged-list? exp 'let)) (define (let->combination exp) (let ((names (map car (cadr exp))) (values (map cadr (cadr exp))) (body (cddr exp))) (cons (cons 'lambda (cons names body)) values))) (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) 'false (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last - COND->IF" clauses)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) (define (true? x) (not (eq? x false))) (define (false? x) (eq? x false)) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define (procedure-parameters p) (cadr p)) (define (procedure-body p) (caddr p)) (define (procedure-environment p) (cadddr p)) (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) (define (make-frame variables values) (cons variables values)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable - SET!" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) (list 'pair? pair?) (list 'list list) (list '= =) (list '+ +) (list '- -) (list '* *) (list '/ /))) (define (primitive-procedure-names) (map car primitive-procedures)) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (define apply-in-underlying-scheme apply) (define (apply-primitive-procedure proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true true initial-env) (define-variable! 'false false initial-env) initial-env)) (define the-global-environment (setup-environment)) (define input-prompt ";;; M-Eval input:") (define output-prompt ";;; M-Eval value:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (evaluate input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) (define (announce-output string) (newline) (display string) (newline)) (define (user-print object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object)))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/04/16.scm
scheme
In this exercise we implement the method just described for interpreting internal definitions. We assume that the evaluator supports let (see exercise value it finds is the symbol *unassigned*. b. Write a procedure scan-out-defines that takes a procedure body and returns an equivalent one that has no internal definitions, by making the transformation described above. c. Install scan-out-defines in the interpreter, either in make-procedure or in procedure-body (see section 4.1.3). Which place is better? Why? a. Here is the modified procedure: b. Here's scan-out-defines: c. And finally, we install it in. We do it in make-procedure, because that is more efficient - it is called once for each procedure. Otherwise, it will be called on every procedure invocation The rest of the interpreter. Note that I added a primitive procedure list to enable an easier test case.
SICP exercise 4.16 4.6 ) . a. Change the lookup - variable - value ( section 4.1.3 ) to singal an error if the (require r5rs/init) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (let ((value (car vals))) (if (eq? value '*unassigned*) (error "Unassigned variable" var) value))) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (scan-out-defines body) (define (definitions-in body) (cond ((null? body) '()) ((definition? (car body)) (cons (car body) (definitions-in (cdr body)))) (else (definitions-in (cdr body))))) (define (body-without-definitions body) (cond ((null? body) '()) ((definition? (car body)) (body-without-definitions (cdr body))) (else (cons (car body) (body-without-definitions (cdr body)))))) (define (definition->unassigned-pair definition) (list (definition-variable definition) ''*unassigned*)) (define (definition->set! definition) (list 'set! (definition-variable definition) (definition-value definition))) (define (defines->let definitions body) (list (cons 'let (cons (map definition->unassigned-pair definitions) (append (map definition->set! definitions) body))))) (let ((internal-definitions (definitions-in body))) (if (null? internal-definitions) body (defines->let internal-definitions (body-without-definitions body))))) (define (make-procedure parameters body env) (list 'procedure parameters (scan-out-defines body) env)) (define (evaluate exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (evaluate (cond->if exp) env)) ((let? exp) (evaluate (let->combination exp) env)) ((application? exp) (apply-procedure (evaluate (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type - EVALUATE" exp)))) (define (apply-procedure procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "Unknown procedure type - APPLY-PROCEDURE" procedure)))) (define (list-of-values exps env) (if (no-operands? exps) '() (cons (evaluate (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (evaluate (if-predicate exp) env)) (evaluate (if-consequent exp) env) (evaluate (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (evaluate (first-exp exps) env)) (else (evaluate (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (evaluate (assignment-value exp) env) env) 'ok) (define (eval-definition exp env) (define-variable! (definition-variable exp) (evaluate (definition-value exp) env) env) 'ok) (define (self-evaluating? exp) (cond ((number? exp) true) ((string? exp) true) (else false))) (define (variable? exp) (symbol? exp)) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp) (cadr exp)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false)) (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-lambda parameters body) (cons 'lambda (cons parameters body))) (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false)) (define (make-if predicate consequent alternative) (list 'if predicate consequent alternative)) (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions exp) (cdr exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin seq) (cons 'begin seq)) (define (application? exp) (pair? exp)) (define (operator exp) (car exp)) (define (operands exp) (cdr exp)) (define (no-operands? ops) (null? ops)) (define (first-operand ops) (car ops)) (define (rest-operands ops) (cdr ops)) (define (let? exp) (tagged-list? exp 'let)) (define (let->combination exp) (let ((names (map car (cadr exp))) (values (map cadr (cadr exp))) (body (cddr exp))) (cons (cons 'lambda (cons names body)) values))) (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) 'false (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last - COND->IF" clauses)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) (define (true? x) (not (eq? x false))) (define (false? x) (eq? x false)) (define (compound-procedure? p) (tagged-list? p 'procedure)) (define (procedure-parameters p) (cadr p)) (define (procedure-body p) (caddr p)) (define (procedure-environment p) (cadddr p)) (define (enclosing-environment env) (cdr env)) (define (first-frame env) (car env)) (define the-empty-environment '()) (define (make-frame variables values) (cons variables values)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (define (set-variable-value! var val env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable - SET!" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) (list 'pair? pair?) (list 'list list) (list '= =) (list '+ +) (list '- -) (list '* *) (list '/ /))) (define (primitive-procedure-names) (map car primitive-procedures)) (define (primitive-procedure-objects) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (define apply-in-underlying-scheme apply) (define (apply-primitive-procedure proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true true initial-env) (define-variable! 'false false initial-env) initial-env)) (define the-global-environment (setup-environment)) (define input-prompt ";;; M-Eval input:") (define output-prompt ";;; M-Eval value:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (evaluate input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) (define (announce-output string) (newline) (display string) (newline)) (define (user-print object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object)))
298137b72daab015a7a84a5fe46bf535b2c3d209728df2708614bf67935d1a4b
mbj/stratosphere
StreamSelectionProperty.hs
module Stratosphere.MediaPackage.OriginEndpoint.StreamSelectionProperty ( StreamSelectionProperty(..), mkStreamSelectionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StreamSelectionProperty = StreamSelectionProperty {maxVideoBitsPerSecond :: (Prelude.Maybe (Value Prelude.Integer)), minVideoBitsPerSecond :: (Prelude.Maybe (Value Prelude.Integer)), streamOrder :: (Prelude.Maybe (Value Prelude.Text))} mkStreamSelectionProperty :: StreamSelectionProperty mkStreamSelectionProperty = StreamSelectionProperty {maxVideoBitsPerSecond = Prelude.Nothing, minVideoBitsPerSecond = Prelude.Nothing, streamOrder = Prelude.Nothing} instance ToResourceProperties StreamSelectionProperty where toResourceProperties StreamSelectionProperty {..} = ResourceProperties {awsType = "AWS::MediaPackage::OriginEndpoint.StreamSelection", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "MaxVideoBitsPerSecond" Prelude.<$> maxVideoBitsPerSecond, (JSON..=) "MinVideoBitsPerSecond" Prelude.<$> minVideoBitsPerSecond, (JSON..=) "StreamOrder" Prelude.<$> streamOrder])} instance JSON.ToJSON StreamSelectionProperty where toJSON StreamSelectionProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "MaxVideoBitsPerSecond" Prelude.<$> maxVideoBitsPerSecond, (JSON..=) "MinVideoBitsPerSecond" Prelude.<$> minVideoBitsPerSecond, (JSON..=) "StreamOrder" Prelude.<$> streamOrder])) instance Property "MaxVideoBitsPerSecond" StreamSelectionProperty where type PropertyType "MaxVideoBitsPerSecond" StreamSelectionProperty = Value Prelude.Integer set newValue StreamSelectionProperty {..} = StreamSelectionProperty {maxVideoBitsPerSecond = Prelude.pure newValue, ..} instance Property "MinVideoBitsPerSecond" StreamSelectionProperty where type PropertyType "MinVideoBitsPerSecond" StreamSelectionProperty = Value Prelude.Integer set newValue StreamSelectionProperty {..} = StreamSelectionProperty {minVideoBitsPerSecond = Prelude.pure newValue, ..} instance Property "StreamOrder" StreamSelectionProperty where type PropertyType "StreamOrder" StreamSelectionProperty = Value Prelude.Text set newValue StreamSelectionProperty {..} = StreamSelectionProperty {streamOrder = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/mediapackage/gen/Stratosphere/MediaPackage/OriginEndpoint/StreamSelectionProperty.hs
haskell
module Stratosphere.MediaPackage.OriginEndpoint.StreamSelectionProperty ( StreamSelectionProperty(..), mkStreamSelectionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StreamSelectionProperty = StreamSelectionProperty {maxVideoBitsPerSecond :: (Prelude.Maybe (Value Prelude.Integer)), minVideoBitsPerSecond :: (Prelude.Maybe (Value Prelude.Integer)), streamOrder :: (Prelude.Maybe (Value Prelude.Text))} mkStreamSelectionProperty :: StreamSelectionProperty mkStreamSelectionProperty = StreamSelectionProperty {maxVideoBitsPerSecond = Prelude.Nothing, minVideoBitsPerSecond = Prelude.Nothing, streamOrder = Prelude.Nothing} instance ToResourceProperties StreamSelectionProperty where toResourceProperties StreamSelectionProperty {..} = ResourceProperties {awsType = "AWS::MediaPackage::OriginEndpoint.StreamSelection", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "MaxVideoBitsPerSecond" Prelude.<$> maxVideoBitsPerSecond, (JSON..=) "MinVideoBitsPerSecond" Prelude.<$> minVideoBitsPerSecond, (JSON..=) "StreamOrder" Prelude.<$> streamOrder])} instance JSON.ToJSON StreamSelectionProperty where toJSON StreamSelectionProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "MaxVideoBitsPerSecond" Prelude.<$> maxVideoBitsPerSecond, (JSON..=) "MinVideoBitsPerSecond" Prelude.<$> minVideoBitsPerSecond, (JSON..=) "StreamOrder" Prelude.<$> streamOrder])) instance Property "MaxVideoBitsPerSecond" StreamSelectionProperty where type PropertyType "MaxVideoBitsPerSecond" StreamSelectionProperty = Value Prelude.Integer set newValue StreamSelectionProperty {..} = StreamSelectionProperty {maxVideoBitsPerSecond = Prelude.pure newValue, ..} instance Property "MinVideoBitsPerSecond" StreamSelectionProperty where type PropertyType "MinVideoBitsPerSecond" StreamSelectionProperty = Value Prelude.Integer set newValue StreamSelectionProperty {..} = StreamSelectionProperty {minVideoBitsPerSecond = Prelude.pure newValue, ..} instance Property "StreamOrder" StreamSelectionProperty where type PropertyType "StreamOrder" StreamSelectionProperty = Value Prelude.Text set newValue StreamSelectionProperty {..} = StreamSelectionProperty {streamOrder = Prelude.pure newValue, ..}
e99405484f5815942b0103117360c79463fc39da60cf28428386fdd04a545894
mlabs-haskell/bot-plutus-interface
ChainIndex.hs
# LANGUAGE NamedFieldPuns # module BotPlutusInterface.ChainIndex ( handleChainIndexReq, ) where import BotPlutusInterface.Types ( ContractEnvironment (ContractEnvironment, cePABConfig), PABConfig, ) import Data.Kind (Type) import Network.HTTP.Client ( ManagerSettings (managerResponseTimeout), defaultManagerSettings, newManager, responseTimeoutNone, ) import Network.HTTP.Types (Status (statusCode)) import Plutus.ChainIndex.Api ( QueryAtAddressRequest (QueryAtAddressRequest), TxoAtAddressRequest (TxoAtAddressRequest), TxosResponse, UtxoAtAddressRequest (UtxoAtAddressRequest), UtxoWithCurrencyRequest (UtxoWithCurrencyRequest), UtxosResponse, ) import Plutus.ChainIndex.Client qualified as ChainIndexClient import Plutus.Contract.Effects (ChainIndexQuery (..), ChainIndexResponse (..)) import Servant.Client ( ClientError (FailureResponse), ClientM, ResponseF (Response, responseStatusCode), mkClientEnv, runClientM, ) import Prelude handleChainIndexReq :: forall (w :: Type). ContractEnvironment w -> ChainIndexQuery -> IO ChainIndexResponse handleChainIndexReq contractEnv@ContractEnvironment {cePABConfig} = \case -- TODO: Implement DatumsAtAddress -- -haskell/bot-plutus-interface/issues/164 DatumsAtAddress _ _ -> error "Not implemented ChainIndex.DatumsAtAddress" DatumFromHash datumHash -> DatumHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getDatum datumHash) ValidatorFromHash validatorHash -> ValidatorHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getValidator validatorHash) MintingPolicyFromHash mintingPolicyHash -> MintingPolicyHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getMintingPolicy mintingPolicyHash) StakeValidatorFromHash stakeValidatorHash -> StakeValidatorHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getStakeValidator stakeValidatorHash) RedeemerFromHash _ -> pure $ RedeemerHashResponse Nothing -- RedeemerFromHash redeemerHash -> -- pure $ RedeemerHashResponse (Maybe Redeemer) TxOutFromRef txOutRef -> TxOutRefResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getTxOut txOutRef) UnspentTxOutFromRef txOutRef -> UnspentTxOutResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getUnspentTxOut txOutRef) UnspentTxOutSetAtAddress page credential -> UnspentTxOutsAtResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getUnspentTxOutsAtAddress (QueryAtAddressRequest (Just page) credential)) TxFromTxId txId -> TxIdResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getTx txId) UtxoSetMembership txOutRef -> UtxoSetMembershipResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getIsUtxo txOutRef) UtxoSetAtAddress page credential -> UtxoSetAtResponse <$> chainIndexUtxoQuery contractEnv (ChainIndexClient.getUtxoSetAtAddress (UtxoAtAddressRequest (Just page) credential)) UtxoSetWithCurrency page assetClass -> UtxoSetWithCurrencyResponse <$> chainIndexUtxoQuery contractEnv (ChainIndexClient.getUtxoSetWithCurrency (UtxoWithCurrencyRequest (Just page) assetClass)) GetTip -> GetTipResponse <$> chainIndexQueryMany cePABConfig ChainIndexClient.getTip TxsFromTxIds txIds -> TxIdsResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getTxs txIds) TxoSetAtAddress page credential -> TxoSetAtResponse <$> chainIndexTxoQuery contractEnv (ChainIndexClient.getTxoSetAtAddress (TxoAtAddressRequest (Just page) credential)) chainIndexQuery' :: forall (a :: Type). PABConfig -> ClientM a -> IO (Either ClientError a) chainIndexQuery' pabConf endpoint = do manager' <- newManager defaultManagerSettings {managerResponseTimeout = responseTimeoutNone} runClientM endpoint $ mkClientEnv manager' pabConf.pcChainIndexUrl chainIndexQueryMany :: forall (a :: Type). PABConfig -> ClientM a -> IO a chainIndexQueryMany pabConf endpoint = either (error . show) id <$> chainIndexQuery' pabConf endpoint chainIndexQueryOne :: forall (a :: Type). PABConfig -> ClientM a -> IO (Maybe a) chainIndexQueryOne pabConf endpoint = do res <- chainIndexQuery' pabConf endpoint case res of Right result -> pure $ Just result Left failureResp@(FailureResponse _ Response {responseStatusCode}) | statusCode responseStatusCode == 404 -> pure Nothing | otherwise -> error (show failureResp) Left failureResp -> error (show failureResp) | Query for 's . chainIndexUtxoQuery :: forall (w :: Type). ContractEnvironment w -> ClientM UtxosResponse -> IO UtxosResponse chainIndexUtxoQuery contractEnv query = do chainIndexQueryMany contractEnv.cePABConfig query -- | Query for txo's. chainIndexTxoQuery :: forall (w :: Type). ContractEnvironment w -> ClientM TxosResponse -> IO TxosResponse chainIndexTxoQuery contractEnv query = do chainIndexQueryMany contractEnv.cePABConfig query
null
https://raw.githubusercontent.com/mlabs-haskell/bot-plutus-interface/a1f1d0ec7112b5ecde5ac31471c1a75b67b9dd9d/src/BotPlutusInterface/ChainIndex.hs
haskell
TODO: Implement DatumsAtAddress -haskell/bot-plutus-interface/issues/164 RedeemerFromHash redeemerHash -> pure $ RedeemerHashResponse (Maybe Redeemer) | Query for txo's.
# LANGUAGE NamedFieldPuns # module BotPlutusInterface.ChainIndex ( handleChainIndexReq, ) where import BotPlutusInterface.Types ( ContractEnvironment (ContractEnvironment, cePABConfig), PABConfig, ) import Data.Kind (Type) import Network.HTTP.Client ( ManagerSettings (managerResponseTimeout), defaultManagerSettings, newManager, responseTimeoutNone, ) import Network.HTTP.Types (Status (statusCode)) import Plutus.ChainIndex.Api ( QueryAtAddressRequest (QueryAtAddressRequest), TxoAtAddressRequest (TxoAtAddressRequest), TxosResponse, UtxoAtAddressRequest (UtxoAtAddressRequest), UtxoWithCurrencyRequest (UtxoWithCurrencyRequest), UtxosResponse, ) import Plutus.ChainIndex.Client qualified as ChainIndexClient import Plutus.Contract.Effects (ChainIndexQuery (..), ChainIndexResponse (..)) import Servant.Client ( ClientError (FailureResponse), ClientM, ResponseF (Response, responseStatusCode), mkClientEnv, runClientM, ) import Prelude handleChainIndexReq :: forall (w :: Type). ContractEnvironment w -> ChainIndexQuery -> IO ChainIndexResponse handleChainIndexReq contractEnv@ContractEnvironment {cePABConfig} = \case DatumsAtAddress _ _ -> error "Not implemented ChainIndex.DatumsAtAddress" DatumFromHash datumHash -> DatumHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getDatum datumHash) ValidatorFromHash validatorHash -> ValidatorHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getValidator validatorHash) MintingPolicyFromHash mintingPolicyHash -> MintingPolicyHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getMintingPolicy mintingPolicyHash) StakeValidatorFromHash stakeValidatorHash -> StakeValidatorHashResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getStakeValidator stakeValidatorHash) RedeemerFromHash _ -> pure $ RedeemerHashResponse Nothing TxOutFromRef txOutRef -> TxOutRefResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getTxOut txOutRef) UnspentTxOutFromRef txOutRef -> UnspentTxOutResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getUnspentTxOut txOutRef) UnspentTxOutSetAtAddress page credential -> UnspentTxOutsAtResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getUnspentTxOutsAtAddress (QueryAtAddressRequest (Just page) credential)) TxFromTxId txId -> TxIdResponse <$> chainIndexQueryOne cePABConfig (ChainIndexClient.getTx txId) UtxoSetMembership txOutRef -> UtxoSetMembershipResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getIsUtxo txOutRef) UtxoSetAtAddress page credential -> UtxoSetAtResponse <$> chainIndexUtxoQuery contractEnv (ChainIndexClient.getUtxoSetAtAddress (UtxoAtAddressRequest (Just page) credential)) UtxoSetWithCurrency page assetClass -> UtxoSetWithCurrencyResponse <$> chainIndexUtxoQuery contractEnv (ChainIndexClient.getUtxoSetWithCurrency (UtxoWithCurrencyRequest (Just page) assetClass)) GetTip -> GetTipResponse <$> chainIndexQueryMany cePABConfig ChainIndexClient.getTip TxsFromTxIds txIds -> TxIdsResponse <$> chainIndexQueryMany cePABConfig (ChainIndexClient.getTxs txIds) TxoSetAtAddress page credential -> TxoSetAtResponse <$> chainIndexTxoQuery contractEnv (ChainIndexClient.getTxoSetAtAddress (TxoAtAddressRequest (Just page) credential)) chainIndexQuery' :: forall (a :: Type). PABConfig -> ClientM a -> IO (Either ClientError a) chainIndexQuery' pabConf endpoint = do manager' <- newManager defaultManagerSettings {managerResponseTimeout = responseTimeoutNone} runClientM endpoint $ mkClientEnv manager' pabConf.pcChainIndexUrl chainIndexQueryMany :: forall (a :: Type). PABConfig -> ClientM a -> IO a chainIndexQueryMany pabConf endpoint = either (error . show) id <$> chainIndexQuery' pabConf endpoint chainIndexQueryOne :: forall (a :: Type). PABConfig -> ClientM a -> IO (Maybe a) chainIndexQueryOne pabConf endpoint = do res <- chainIndexQuery' pabConf endpoint case res of Right result -> pure $ Just result Left failureResp@(FailureResponse _ Response {responseStatusCode}) | statusCode responseStatusCode == 404 -> pure Nothing | otherwise -> error (show failureResp) Left failureResp -> error (show failureResp) | Query for 's . chainIndexUtxoQuery :: forall (w :: Type). ContractEnvironment w -> ClientM UtxosResponse -> IO UtxosResponse chainIndexUtxoQuery contractEnv query = do chainIndexQueryMany contractEnv.cePABConfig query chainIndexTxoQuery :: forall (w :: Type). ContractEnvironment w -> ClientM TxosResponse -> IO TxosResponse chainIndexTxoQuery contractEnv query = do chainIndexQueryMany contractEnv.cePABConfig query
5b055669124c2b297de6df44db96230c82512fba751c021d55ffda23c9967449
ds-wizard/engine-backend
LocaleDetailSM.hs
module Wizard.Api.Resource.Locale.LocaleDetailSM where import Data.Swagger import Shared.Util.Swagger import Wizard.Api.Resource.Locale.LocaleDetailDTO import Wizard.Api.Resource.Locale.LocaleDetailJM () import Wizard.Api.Resource.Locale.LocaleStateSM () import Wizard.Api.Resource.Registry.RegistryOrganizationSM () import Wizard.Database.Migration.Development.Locale.Data.Locales instance ToSchema LocaleDetailDTO where declareNamedSchema = toSwagger localeNlDetailDto
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-wizard/src/Wizard/Api/Resource/Locale/LocaleDetailSM.hs
haskell
module Wizard.Api.Resource.Locale.LocaleDetailSM where import Data.Swagger import Shared.Util.Swagger import Wizard.Api.Resource.Locale.LocaleDetailDTO import Wizard.Api.Resource.Locale.LocaleDetailJM () import Wizard.Api.Resource.Locale.LocaleStateSM () import Wizard.Api.Resource.Registry.RegistryOrganizationSM () import Wizard.Database.Migration.Development.Locale.Data.Locales instance ToSchema LocaleDetailDTO where declareNamedSchema = toSwagger localeNlDetailDto
fc08e8ce029d05d9b1d185305d264517c7011a5237d1b4b01927bd3e58e1c13f
isaksamsten/erlang-csv
csv.erl
%% %% Very basic CSV parser of limited use. %% It can only handle one type of separators ( , ) %% and simple strings %% Version 0.2 : %% - comment (line starting with %) and %% annotation support (line starting with %@key value) Version 0.1 : %% - initial release Author : < > %% -module(csv). -compile(export_all). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. reader(File) -> {?MODULE, {csv_reader, spawn_link(?MODULE, spawn_parser, [File])}}. binary_reader(File, Opts) -> Annotations = proplists:get_value(annotations, Opts, false), {?MODULE, {csv_reader, spawn_link(?MODULE, spawn_binary_parser, [File, Annotations])}}. binary_reader(File) -> binary_reader(File, []). spawn_binary_parser(File, Annot) -> case file:read_file(File) of {ok, Bin} -> parse_binary_incremental(Bin, 1, Annot); _ -> throw({error, file_not_found}) end. parse_binary_incremental(Bin, Counter, Annot) -> Eof = binary_eof(Bin), case Eof of true -> receive {Any, Parent} when Any == more; Any == raw -> Parent ! {eof, Parent}, parse_binary_incremental(<<>>, Counter + 1, Annot); {exit, Parent} -> Parent ! exit end; false -> receive {more, Parent} -> case parse_binary_line(Bin, Annot) of {item, {Item, Rest}} -> Parent ! {row, Parent, Item, Counter}, parse_binary_incremental(Rest, Counter + 1, Annot); {annotation, {Kv, Rest}} -> Parent ! {annotation, Parent, Kv}, parse_binary_incremental(Rest, Counter, Annot) end; {raw, Parent} -> note : only check for EOF Parent ! {raw, Parent, Line, Counter}, parse_binary_incremental(Rest, Counter + 1, Annot); {exit, Parent} -> Parent ! exit end end. spawn_parser(File) -> case file:open(File, [read, read_ahead]) of {ok, Io} -> parse_incremental(Io, 1); _ -> throw({error, file_not_found}) end. parse_incremental(Io, Counter) -> case file:read_line(Io) of {ok, Line} -> Item = parse_line(Line, []), receive {more, Parent} -> Parent ! {ok, Parent, Item, Counter}, parse_incremental(Io, Counter + 1); {exit, Parent} -> Parent ! exit end; eof -> receive {more, Parent} -> Parent ! {eof, Parent}, parse_incremental(Io, Counter); {exit, Parent} -> Parent ! exit end; {error, Reason} -> throw({error, Reason}) end. kill({csv_reader, Pid}) -> Ref = monitor(process, Pid), Pid ! {exit, self()}, receive exit -> ok; {'DOWN', Ref, _, _, _} -> demonitor(Ref), ok end. next_line(Reader) -> get_next_line(Reader). get_next_line({csv_reader, Pid}) -> Self = self(), Ref = monitor(process, Pid), Pid ! {more, Self}, receive {row, Self, Item, Id} -> demonitor(Ref), {row, Item, Id}; {annotation, Self, Kv} -> demonitor(Ref), {annotation, Kv}; {eof, Self} -> demonitor(Ref), eof; {'DOWN', Ref, _, _, _} -> demonitor(Ref), eof end. get_next_raw({csv_reader, Pid}) -> Self = self(), Ref = monitor(process, Pid), Pid ! {raw, Self}, receive {raw, Self, Item, Id} -> demonitor(Ref), {ok, Item, Id}; {eof, Self} -> demonitor(Ref), eof; {'DOWN', Ref, _, _, _} -> demonitor(Ref), eof end. binary_eof(<<>>) -> true; binary_eof(_) -> false. binary_next_line(<<>>, _) -> {eof, <<>>}; binary_next_line(<<$\n, Rest/binary>>, Acc) -> {<<Acc/binary, $\n>>, Rest}; NOTE : skip \r binary_next_line(Rest, Acc); binary_next_line(<<Any, Rest/binary>>, Acc) -> binary_next_line(Rest, <<Acc/binary, Any>>). parse_binary_line(Binary, Annot) -> case parse_binary_line(Binary, <<>>, []) of {comment, Rest} -> parse_binary_line(Rest, Annot); {annotation, {Kv, Rest}} -> if not(Annot) -> parse_binary_line(Rest, Annot); true -> {annotation, {Kv, Rest}} end; Other -> {item, Other} end. end_of_line(Rest, Str, Acc) -> Acc0 = case Str of <<>> -> Acc; _ -> [string:strip(binary_to_list(Str))|Acc] end, case Acc0 of [] -> {comment, Rest}; FinalAcc -> {lists:reverse(FinalAcc), Rest} end. parse_binary_line(<<$%, Annotation, Rest/binary>>, _, _) -> case is_annotation(Annotation) of true -> {annotation, parse_annotation(Rest)}; false -> {comment, skip_line(Rest)} end; parse_binary_line(<<$\n, Rest/binary>>, Str, Acc) -> end_of_line(Rest, Str, Acc); parse_binary_line(<<>>, Str, Acc) -> end_of_line(<<>>, Str, Acc); NOTE : skip \r parse_binary_line(Rest, Str, Acc); parse_binary_line(<<$", $,, Rest/binary>>, _Str, Acc) -> parse_binary_line(Rest, <<>>, ["\""|Acc]); parse_binary_line(<<$", Rest/binary>>, Str, Acc) -> parse_binary_string(Rest, Str, Acc); parse_binary_line(<<$,, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_line(<<I, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<Str/binary, I>>, Acc). parse_binary_string(<<$", $,, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_string(<<$", Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_string(<<I, Rest/binary>>, Str, Acc) -> parse_binary_string(Rest, <<Str/binary, I>>, Acc). skip_line(<<$\r, Rest/binary>>) -> skip_line(Rest); skip_line(<<$\n, Rest/binary>>) -> Rest; skip_line(<<_, Rest/binary>>) -> skip_line(Rest). is_annotation(A) when A == $@ -> true; is_annotation(_) -> false. parse_annotation(A) -> {Key, Rest0} = parse_annotation_key(A, <<>>), {Value, Rest1} = parse_annotation_value(Rest0, <<>>), {{Key, Value}, Rest1}. parse_annotation_key(<<$ , Rest/binary>>, Acc) -> {Acc, Rest}; parse_annotation_key(<<C, Rest/binary>>, Acc) -> parse_annotation_key(Rest, <<Acc/binary,C>>). parse_annotation_value(<<$\r, Rest/binary>>, Acc) -> parse_annotation_value(Rest, Acc); parse_annotation_value(<<$\n, Rest/binary>>, Acc) -> {Acc, Rest}; parse_annotation_value(<<C, Rest/binary>>, Acc) -> parse_annotation_value(Rest, <<Acc/binary,C>>). parse_line(Line, Acc) -> lists:reverse(parse_line(Line, [], Acc)). parse_line([End], Str, Acc) -> Str0 = case End of $\n -> Str; _ -> % NOTE: The last line of the file [End|Str] end, case Str0 of [] -> Acc; _ -> [string:strip(lists:reverse(Str0))|Acc] end; | _ ] , _ , ) - > Acc; parse_line([$", $,|R], _, Acc) -> parse_line(R, [], ["\""|Acc]); parse_line([$"|R], Str, Acc) -> parse_string(R, Str, Acc); parse_line([$,|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_line([I|R], Str, Acc) -> parse_line(R, [I|Str], Acc). parse_string([$", $,|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_string([$"|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_string([I|R], Str, Acc) -> parse_string(R, [I|Str], Acc). -ifdef(TEST). annotation_test() -> {_, Csv} = binary_reader("../test/csv_comment.csv", [{annotations, true}]), {annotation, {Url, Http}} = next_line(Csv), ?assertEqual(<<"url">>, Url), ?assertEqual(<<"/~isak-kar">>, Http), {annotation, {Name, TheName}} = next_line(Csv), ?assertEqual(<<"name">>, Name), ?assertEqual(<<"Hello World">>, TheName), {row, Line, Count} = next_line(Csv), ?assertEqual(["hello", "world"], Line), ?assertEqual(1, Count). ignore_annotation_test() -> {_, Csv} = binary_reader("../test/csv_comment.csv", [{annotations, false}]), {row, Line, Count} = next_line(Csv), ?assertEqual(["hello", "world"], Line), ?assertEqual(1, Count). -endif.
null
https://raw.githubusercontent.com/isaksamsten/erlang-csv/253d2dd4da23b9245d4494d18d7198e1a5fceef9/src/csv.erl
erlang
Very basic CSV parser of limited use. and simple strings - comment (line starting with %) and annotation support (line starting with %@key value) - initial release , Annotation, Rest/binary>>, _, _) -> NOTE: The last line of the file
It can only handle one type of separators ( , ) Version 0.2 : Version 0.1 : Author : < > -module(csv). -compile(export_all). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. reader(File) -> {?MODULE, {csv_reader, spawn_link(?MODULE, spawn_parser, [File])}}. binary_reader(File, Opts) -> Annotations = proplists:get_value(annotations, Opts, false), {?MODULE, {csv_reader, spawn_link(?MODULE, spawn_binary_parser, [File, Annotations])}}. binary_reader(File) -> binary_reader(File, []). spawn_binary_parser(File, Annot) -> case file:read_file(File) of {ok, Bin} -> parse_binary_incremental(Bin, 1, Annot); _ -> throw({error, file_not_found}) end. parse_binary_incremental(Bin, Counter, Annot) -> Eof = binary_eof(Bin), case Eof of true -> receive {Any, Parent} when Any == more; Any == raw -> Parent ! {eof, Parent}, parse_binary_incremental(<<>>, Counter + 1, Annot); {exit, Parent} -> Parent ! exit end; false -> receive {more, Parent} -> case parse_binary_line(Bin, Annot) of {item, {Item, Rest}} -> Parent ! {row, Parent, Item, Counter}, parse_binary_incremental(Rest, Counter + 1, Annot); {annotation, {Kv, Rest}} -> Parent ! {annotation, Parent, Kv}, parse_binary_incremental(Rest, Counter, Annot) end; {raw, Parent} -> note : only check for EOF Parent ! {raw, Parent, Line, Counter}, parse_binary_incremental(Rest, Counter + 1, Annot); {exit, Parent} -> Parent ! exit end end. spawn_parser(File) -> case file:open(File, [read, read_ahead]) of {ok, Io} -> parse_incremental(Io, 1); _ -> throw({error, file_not_found}) end. parse_incremental(Io, Counter) -> case file:read_line(Io) of {ok, Line} -> Item = parse_line(Line, []), receive {more, Parent} -> Parent ! {ok, Parent, Item, Counter}, parse_incremental(Io, Counter + 1); {exit, Parent} -> Parent ! exit end; eof -> receive {more, Parent} -> Parent ! {eof, Parent}, parse_incremental(Io, Counter); {exit, Parent} -> Parent ! exit end; {error, Reason} -> throw({error, Reason}) end. kill({csv_reader, Pid}) -> Ref = monitor(process, Pid), Pid ! {exit, self()}, receive exit -> ok; {'DOWN', Ref, _, _, _} -> demonitor(Ref), ok end. next_line(Reader) -> get_next_line(Reader). get_next_line({csv_reader, Pid}) -> Self = self(), Ref = monitor(process, Pid), Pid ! {more, Self}, receive {row, Self, Item, Id} -> demonitor(Ref), {row, Item, Id}; {annotation, Self, Kv} -> demonitor(Ref), {annotation, Kv}; {eof, Self} -> demonitor(Ref), eof; {'DOWN', Ref, _, _, _} -> demonitor(Ref), eof end. get_next_raw({csv_reader, Pid}) -> Self = self(), Ref = monitor(process, Pid), Pid ! {raw, Self}, receive {raw, Self, Item, Id} -> demonitor(Ref), {ok, Item, Id}; {eof, Self} -> demonitor(Ref), eof; {'DOWN', Ref, _, _, _} -> demonitor(Ref), eof end. binary_eof(<<>>) -> true; binary_eof(_) -> false. binary_next_line(<<>>, _) -> {eof, <<>>}; binary_next_line(<<$\n, Rest/binary>>, Acc) -> {<<Acc/binary, $\n>>, Rest}; NOTE : skip \r binary_next_line(Rest, Acc); binary_next_line(<<Any, Rest/binary>>, Acc) -> binary_next_line(Rest, <<Acc/binary, Any>>). parse_binary_line(Binary, Annot) -> case parse_binary_line(Binary, <<>>, []) of {comment, Rest} -> parse_binary_line(Rest, Annot); {annotation, {Kv, Rest}} -> if not(Annot) -> parse_binary_line(Rest, Annot); true -> {annotation, {Kv, Rest}} end; Other -> {item, Other} end. end_of_line(Rest, Str, Acc) -> Acc0 = case Str of <<>> -> Acc; _ -> [string:strip(binary_to_list(Str))|Acc] end, case Acc0 of [] -> {comment, Rest}; FinalAcc -> {lists:reverse(FinalAcc), Rest} end. case is_annotation(Annotation) of true -> {annotation, parse_annotation(Rest)}; false -> {comment, skip_line(Rest)} end; parse_binary_line(<<$\n, Rest/binary>>, Str, Acc) -> end_of_line(Rest, Str, Acc); parse_binary_line(<<>>, Str, Acc) -> end_of_line(<<>>, Str, Acc); NOTE : skip \r parse_binary_line(Rest, Str, Acc); parse_binary_line(<<$", $,, Rest/binary>>, _Str, Acc) -> parse_binary_line(Rest, <<>>, ["\""|Acc]); parse_binary_line(<<$", Rest/binary>>, Str, Acc) -> parse_binary_string(Rest, Str, Acc); parse_binary_line(<<$,, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_line(<<I, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<Str/binary, I>>, Acc). parse_binary_string(<<$", $,, Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_string(<<$", Rest/binary>>, Str, Acc) -> parse_binary_line(Rest, <<>>, [string:strip(binary_to_list(Str))|Acc]); parse_binary_string(<<I, Rest/binary>>, Str, Acc) -> parse_binary_string(Rest, <<Str/binary, I>>, Acc). skip_line(<<$\r, Rest/binary>>) -> skip_line(Rest); skip_line(<<$\n, Rest/binary>>) -> Rest; skip_line(<<_, Rest/binary>>) -> skip_line(Rest). is_annotation(A) when A == $@ -> true; is_annotation(_) -> false. parse_annotation(A) -> {Key, Rest0} = parse_annotation_key(A, <<>>), {Value, Rest1} = parse_annotation_value(Rest0, <<>>), {{Key, Value}, Rest1}. parse_annotation_key(<<$ , Rest/binary>>, Acc) -> {Acc, Rest}; parse_annotation_key(<<C, Rest/binary>>, Acc) -> parse_annotation_key(Rest, <<Acc/binary,C>>). parse_annotation_value(<<$\r, Rest/binary>>, Acc) -> parse_annotation_value(Rest, Acc); parse_annotation_value(<<$\n, Rest/binary>>, Acc) -> {Acc, Rest}; parse_annotation_value(<<C, Rest/binary>>, Acc) -> parse_annotation_value(Rest, <<Acc/binary,C>>). parse_line(Line, Acc) -> lists:reverse(parse_line(Line, [], Acc)). parse_line([End], Str, Acc) -> Str0 = case End of $\n -> Str; [End|Str] end, case Str0 of [] -> Acc; _ -> [string:strip(lists:reverse(Str0))|Acc] end; | _ ] , _ , ) - > Acc; parse_line([$", $,|R], _, Acc) -> parse_line(R, [], ["\""|Acc]); parse_line([$"|R], Str, Acc) -> parse_string(R, Str, Acc); parse_line([$,|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_line([I|R], Str, Acc) -> parse_line(R, [I|Str], Acc). parse_string([$", $,|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_string([$"|R], Str, Acc) -> parse_line(R, [], [string:strip(lists:reverse(Str))|Acc]); parse_string([I|R], Str, Acc) -> parse_string(R, [I|Str], Acc). -ifdef(TEST). annotation_test() -> {_, Csv} = binary_reader("../test/csv_comment.csv", [{annotations, true}]), {annotation, {Url, Http}} = next_line(Csv), ?assertEqual(<<"url">>, Url), ?assertEqual(<<"/~isak-kar">>, Http), {annotation, {Name, TheName}} = next_line(Csv), ?assertEqual(<<"name">>, Name), ?assertEqual(<<"Hello World">>, TheName), {row, Line, Count} = next_line(Csv), ?assertEqual(["hello", "world"], Line), ?assertEqual(1, Count). ignore_annotation_test() -> {_, Csv} = binary_reader("../test/csv_comment.csv", [{annotations, false}]), {row, Line, Count} = next_line(Csv), ?assertEqual(["hello", "world"], Line), ?assertEqual(1, Count). -endif.
c70b063da7dd1e51c6caf6138f112f41ff8d881ddb7bfc00eeab381ff0764d58
realworldocaml/book
ast_pattern.ml
open! Import include Ast_pattern0 let save_context ctx = ctx.matched let restore_context ctx backup = ctx.matched <- backup let incr_matched c = c.matched <- c.matched + 1 let parse_res (T f) loc ?on_error x k = try Ok (f { matched = 0 } loc x k) with Expected (loc, expected) -> ( match on_error with | None -> Error (Location.Error.createf ~loc "%s expected" expected, []) | Some f -> Ok (f ())) let parse (T f) loc ?on_error x k = match parse_res (T f) loc ?on_error x k with | Ok r -> r | Error (r, _) -> Location.Error.raise r module Packed = struct type ('a, 'b) t = T : ('a, 'b, 'c) Ast_pattern0.t * 'b -> ('a, 'c) t let create t f = T (t, f) let parse_res (T (t, f)) loc x = parse_res t loc x f let parse (T (t, f)) loc x = parse t loc x f end let __ = T (fun ctx _loc x k -> incr_matched ctx; k x) let __' = T (fun ctx loc x k -> incr_matched ctx; k { loc; txt = x }) let drop = T (fun ctx _loc _ k -> incr_matched ctx; k) let as__ (T f1) = T (fun ctx loc x k -> let k = f1 ctx loc x (k x) in k) let cst ~to_string ?(equal = Poly.equal) v = T (fun ctx loc x k -> if equal x v then ( incr_matched ctx; k) else fail loc (to_string v)) let int v = cst ~to_string:Int.to_string v let char v = cst ~to_string:(Printf.sprintf "%C") v let string v = cst ~to_string:(Printf.sprintf "%S") v let float v = cst ~to_string:Float.to_string v let int32 v = cst ~to_string:Int32.to_string v let int64 v = cst ~to_string:Int64.to_string v let nativeint v = cst ~to_string:Nativeint.to_string v let bool v = cst ~to_string:Bool.to_string v let false_ = T (fun ctx loc x k -> match x with | false -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "false") let true_ = T (fun ctx loc x k -> match x with | true -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "true") let nil = T (fun ctx loc x k -> match x with | [] -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "[]") let ( ^:: ) (T f0) (T f1) = T (fun ctx loc x k -> match x with | x0 :: x1 -> ctx.matched <- ctx.matched + 1; let k = f0 ctx loc x0 k in let k = f1 ctx loc x1 k in k | _ -> fail loc "::") let none = T (fun ctx loc x k -> match x with | None -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "None") let some (T f0) = T (fun ctx loc x k -> match x with | Some x0 -> ctx.matched <- ctx.matched + 1; let k = f0 ctx loc x0 k in k | _ -> fail loc "Some") let pair (T f1) (T f2) = T (fun ctx loc (x1, x2) k -> let k = f1 ctx loc x1 k in let k = f2 ctx loc x2 k in k) let ( ** ) = pair let triple (T f1) (T f2) (T f3) = T (fun ctx loc (x1, x2, x3) k -> let k = f1 ctx loc x1 k in let k = f2 ctx loc x2 k in let k = f3 ctx loc x3 k in k) let alt (T f1) (T f2) = T (fun ctx loc x k -> let backup = save_context ctx in try f1 ctx loc x k with e1 -> ( let m1 = save_context ctx in restore_context ctx backup; try f2 ctx loc x k with e2 -> let m2 = save_context ctx in if m1 >= m2 then ( restore_context ctx m1; raise e1) else raise e2)) let ( ||| ) = alt let map (T func) ~f = T (fun ctx loc x k -> func ctx loc x (f k)) let map' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (f loc k)) let map_result (T func) ~f = T (fun ctx loc x k -> f (func ctx loc x k)) let ( >>| ) t f = map t ~f let map0 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (k f)) let map1 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a -> k (f a))) let map2 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a b -> k (f a b))) let map0' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (k (f loc))) let map1' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a -> k (f loc a))) let map2' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a b -> k (f loc a b))) let alt_option some none = alt (map1 some ~f:(fun x -> Some x)) (map0 none ~f:None) let many (T f) = T (fun ctx loc l k -> let rec aux accu = function | [] -> k (List.rev accu) | x :: xs -> f ctx loc x (fun x -> aux (x :: accu) xs) in aux [] l) let loc (T f) = T (fun ctx _loc (x : _ Loc.t) k -> f ctx x.loc x.txt k) let pack0 t = map t ~f:(fun f -> f ()) let pack2 t = map t ~f:(fun f x y -> f (x, y)) let pack3 t = map t ~f:(fun f x y z -> f (x, y, z)) include Ast_pattern_generated let echar t = pexp_constant (pconst_char t) let estring t = pexp_constant (pconst_string t drop drop) let efloat t = pexp_constant (pconst_float t drop) let pchar t = ppat_constant (pconst_char t) let pstring t = ppat_constant (pconst_string t drop drop) let pfloat t = ppat_constant (pconst_float t drop) let int' (T f) = T (fun ctx loc x k -> f ctx loc (int_of_string x) k) let int32' (T f) = T (fun ctx loc x k -> f ctx loc (Int32.of_string x) k) let int64' (T f) = T (fun ctx loc x k -> f ctx loc (Int64.of_string x) k) let nativeint' (T f) = T (fun ctx loc x k -> f ctx loc (Nativeint.of_string x) k) let const_int t = pconst_integer (int' t) none let const_int32 t = pconst_integer (int32' t) (some (char 'l')) let const_int64 t = pconst_integer (int64' t) (some (char 'L')) let const_nativeint t = pconst_integer (nativeint' t) (some (char 'n')) let eint t = pexp_constant (const_int t) let eint32 t = pexp_constant (const_int32 t) let eint64 t = pexp_constant (const_int64 t) let enativeint t = pexp_constant (const_nativeint t) let pint t = ppat_constant (const_int t) let pint32 t = ppat_constant (const_int32 t) let pint64 t = ppat_constant (const_int64 t) let pnativeint t = ppat_constant (const_nativeint t) let single_expr_payload t = pstr (pstr_eval t nil ^:: nil) let no_label t = cst Asttypes.Nolabel ~to_string:(fun _ -> "Nolabel") ** t let extension (T f1) (T f2) = T (fun ctx loc ((name : _ Loc.t), payload) k -> let k = f1 ctx name.loc name.txt k in let k = f2 ctx loc payload k in k) let rec parse_elist (e : Parsetree.expression) acc = Common.assert_no_attributes e.pexp_attributes; match e.pexp_desc with | Pexp_construct ({ txt = Lident "[]"; _ }, None) -> List.rev acc | Pexp_construct ({ txt = Lident "::"; _ }, Some arg) -> ( Common.assert_no_attributes arg.pexp_attributes; match arg.pexp_desc with | Pexp_tuple [ hd; tl ] -> parse_elist tl (hd :: acc) | _ -> fail arg.pexp_loc "list") | _ -> fail e.pexp_loc "list" let elist (T f) = T (fun ctx _loc e k -> let l = parse_elist e [] in incr_matched ctx; k (List.map l ~f:(fun x -> f ctx x.Parsetree.pexp_loc x (fun x -> x)))) let esequence (T f) = T (fun ctx _loc e k -> let rec parse_seq expr acc = match expr.pexp_desc with | Pexp_sequence (expr, next) -> parse_seq next (expr :: acc) | _ -> expr :: acc in k (List.rev_map (parse_seq e []) ~f:(fun expr -> f ctx expr.pexp_loc expr (fun x -> x)))) let of_func f = T f let to_func (T f) = f
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppxlib/src/ast_pattern.ml
ocaml
open! Import include Ast_pattern0 let save_context ctx = ctx.matched let restore_context ctx backup = ctx.matched <- backup let incr_matched c = c.matched <- c.matched + 1 let parse_res (T f) loc ?on_error x k = try Ok (f { matched = 0 } loc x k) with Expected (loc, expected) -> ( match on_error with | None -> Error (Location.Error.createf ~loc "%s expected" expected, []) | Some f -> Ok (f ())) let parse (T f) loc ?on_error x k = match parse_res (T f) loc ?on_error x k with | Ok r -> r | Error (r, _) -> Location.Error.raise r module Packed = struct type ('a, 'b) t = T : ('a, 'b, 'c) Ast_pattern0.t * 'b -> ('a, 'c) t let create t f = T (t, f) let parse_res (T (t, f)) loc x = parse_res t loc x f let parse (T (t, f)) loc x = parse t loc x f end let __ = T (fun ctx _loc x k -> incr_matched ctx; k x) let __' = T (fun ctx loc x k -> incr_matched ctx; k { loc; txt = x }) let drop = T (fun ctx _loc _ k -> incr_matched ctx; k) let as__ (T f1) = T (fun ctx loc x k -> let k = f1 ctx loc x (k x) in k) let cst ~to_string ?(equal = Poly.equal) v = T (fun ctx loc x k -> if equal x v then ( incr_matched ctx; k) else fail loc (to_string v)) let int v = cst ~to_string:Int.to_string v let char v = cst ~to_string:(Printf.sprintf "%C") v let string v = cst ~to_string:(Printf.sprintf "%S") v let float v = cst ~to_string:Float.to_string v let int32 v = cst ~to_string:Int32.to_string v let int64 v = cst ~to_string:Int64.to_string v let nativeint v = cst ~to_string:Nativeint.to_string v let bool v = cst ~to_string:Bool.to_string v let false_ = T (fun ctx loc x k -> match x with | false -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "false") let true_ = T (fun ctx loc x k -> match x with | true -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "true") let nil = T (fun ctx loc x k -> match x with | [] -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "[]") let ( ^:: ) (T f0) (T f1) = T (fun ctx loc x k -> match x with | x0 :: x1 -> ctx.matched <- ctx.matched + 1; let k = f0 ctx loc x0 k in let k = f1 ctx loc x1 k in k | _ -> fail loc "::") let none = T (fun ctx loc x k -> match x with | None -> ctx.matched <- ctx.matched + 1; k | _ -> fail loc "None") let some (T f0) = T (fun ctx loc x k -> match x with | Some x0 -> ctx.matched <- ctx.matched + 1; let k = f0 ctx loc x0 k in k | _ -> fail loc "Some") let pair (T f1) (T f2) = T (fun ctx loc (x1, x2) k -> let k = f1 ctx loc x1 k in let k = f2 ctx loc x2 k in k) let ( ** ) = pair let triple (T f1) (T f2) (T f3) = T (fun ctx loc (x1, x2, x3) k -> let k = f1 ctx loc x1 k in let k = f2 ctx loc x2 k in let k = f3 ctx loc x3 k in k) let alt (T f1) (T f2) = T (fun ctx loc x k -> let backup = save_context ctx in try f1 ctx loc x k with e1 -> ( let m1 = save_context ctx in restore_context ctx backup; try f2 ctx loc x k with e2 -> let m2 = save_context ctx in if m1 >= m2 then ( restore_context ctx m1; raise e1) else raise e2)) let ( ||| ) = alt let map (T func) ~f = T (fun ctx loc x k -> func ctx loc x (f k)) let map' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (f loc k)) let map_result (T func) ~f = T (fun ctx loc x k -> f (func ctx loc x k)) let ( >>| ) t f = map t ~f let map0 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (k f)) let map1 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a -> k (f a))) let map2 (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a b -> k (f a b))) let map0' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (k (f loc))) let map1' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a -> k (f loc a))) let map2' (T func) ~f = T (fun ctx loc x k -> func ctx loc x (fun a b -> k (f loc a b))) let alt_option some none = alt (map1 some ~f:(fun x -> Some x)) (map0 none ~f:None) let many (T f) = T (fun ctx loc l k -> let rec aux accu = function | [] -> k (List.rev accu) | x :: xs -> f ctx loc x (fun x -> aux (x :: accu) xs) in aux [] l) let loc (T f) = T (fun ctx _loc (x : _ Loc.t) k -> f ctx x.loc x.txt k) let pack0 t = map t ~f:(fun f -> f ()) let pack2 t = map t ~f:(fun f x y -> f (x, y)) let pack3 t = map t ~f:(fun f x y z -> f (x, y, z)) include Ast_pattern_generated let echar t = pexp_constant (pconst_char t) let estring t = pexp_constant (pconst_string t drop drop) let efloat t = pexp_constant (pconst_float t drop) let pchar t = ppat_constant (pconst_char t) let pstring t = ppat_constant (pconst_string t drop drop) let pfloat t = ppat_constant (pconst_float t drop) let int' (T f) = T (fun ctx loc x k -> f ctx loc (int_of_string x) k) let int32' (T f) = T (fun ctx loc x k -> f ctx loc (Int32.of_string x) k) let int64' (T f) = T (fun ctx loc x k -> f ctx loc (Int64.of_string x) k) let nativeint' (T f) = T (fun ctx loc x k -> f ctx loc (Nativeint.of_string x) k) let const_int t = pconst_integer (int' t) none let const_int32 t = pconst_integer (int32' t) (some (char 'l')) let const_int64 t = pconst_integer (int64' t) (some (char 'L')) let const_nativeint t = pconst_integer (nativeint' t) (some (char 'n')) let eint t = pexp_constant (const_int t) let eint32 t = pexp_constant (const_int32 t) let eint64 t = pexp_constant (const_int64 t) let enativeint t = pexp_constant (const_nativeint t) let pint t = ppat_constant (const_int t) let pint32 t = ppat_constant (const_int32 t) let pint64 t = ppat_constant (const_int64 t) let pnativeint t = ppat_constant (const_nativeint t) let single_expr_payload t = pstr (pstr_eval t nil ^:: nil) let no_label t = cst Asttypes.Nolabel ~to_string:(fun _ -> "Nolabel") ** t let extension (T f1) (T f2) = T (fun ctx loc ((name : _ Loc.t), payload) k -> let k = f1 ctx name.loc name.txt k in let k = f2 ctx loc payload k in k) let rec parse_elist (e : Parsetree.expression) acc = Common.assert_no_attributes e.pexp_attributes; match e.pexp_desc with | Pexp_construct ({ txt = Lident "[]"; _ }, None) -> List.rev acc | Pexp_construct ({ txt = Lident "::"; _ }, Some arg) -> ( Common.assert_no_attributes arg.pexp_attributes; match arg.pexp_desc with | Pexp_tuple [ hd; tl ] -> parse_elist tl (hd :: acc) | _ -> fail arg.pexp_loc "list") | _ -> fail e.pexp_loc "list" let elist (T f) = T (fun ctx _loc e k -> let l = parse_elist e [] in incr_matched ctx; k (List.map l ~f:(fun x -> f ctx x.Parsetree.pexp_loc x (fun x -> x)))) let esequence (T f) = T (fun ctx _loc e k -> let rec parse_seq expr acc = match expr.pexp_desc with | Pexp_sequence (expr, next) -> parse_seq next (expr :: acc) | _ -> expr :: acc in k (List.rev_map (parse_seq e []) ~f:(fun expr -> f ctx expr.pexp_loc expr (fun x -> x)))) let of_func f = T f let to_func (T f) = f
5589e57462b09f72c607c45d8702cc08ce37d6572f9d5ba74a843cf61ab71e7a
alekcz/fire
utils.clj
(ns fire.utils (:require [cheshire.core :as json] [clojure.string :as str]) (:gen-class)) (set! *warn-on-reflection* true) (def firebase-root "firebaseio.com") (def storage-upload-root "") (def storage-download-root "") (def vision-root ":annotate") (defn now [] (quot (inst-ms (java.util.Date.)) 1000)) (defn encode [m] (json/encode m)) (defn decode [json-string] (json/decode json-string true)) (defn escape "Surround all strings in query with quotes" [query] (apply merge (for [[k v] query] {k (if (string? v) (str "\"" v "\"") v)}))) (defn recursive-merge "Recursively merge hash maps." [a b] (if (and (map? a) (map? b)) (merge-with recursive-merge a b) (if (map? a) a b))) (defn clean-env-var [env-var] (-> env-var (name) (str) (str/lower-case) (str/replace "_" "-") (str/replace "." "-") (keyword)))
null
https://raw.githubusercontent.com/alekcz/fire/d47f47414c0efc8cac3b049a15053d8e58bf8773/src/fire/utils.clj
clojure
(ns fire.utils (:require [cheshire.core :as json] [clojure.string :as str]) (:gen-class)) (set! *warn-on-reflection* true) (def firebase-root "firebaseio.com") (def storage-upload-root "") (def storage-download-root "") (def vision-root ":annotate") (defn now [] (quot (inst-ms (java.util.Date.)) 1000)) (defn encode [m] (json/encode m)) (defn decode [json-string] (json/decode json-string true)) (defn escape "Surround all strings in query with quotes" [query] (apply merge (for [[k v] query] {k (if (string? v) (str "\"" v "\"") v)}))) (defn recursive-merge "Recursively merge hash maps." [a b] (if (and (map? a) (map? b)) (merge-with recursive-merge a b) (if (map? a) a b))) (defn clean-env-var [env-var] (-> env-var (name) (str) (str/lower-case) (str/replace "_" "-") (str/replace "." "-") (keyword)))
840ac629fb258fd5b8e91ef594274f26c239987d3f246c9c2dc40699f1c5ce85
lemmaandrew/CodingBatHaskell
loneSum.hs
From Given 3 int values , a b c , return their sum . However , if one of the values is the same as another of the values , it does not count towards the sum . Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. -} import Test.Hspec ( hspec, describe, it, shouldBe ) loneSum :: Int -> Int -> Int -> Int loneSum a b c = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "6" $ loneSum 1 2 3 `shouldBe` 6 it "2" $ loneSum 3 2 3 `shouldBe` 2 it "0" $ loneSum 3 3 3 `shouldBe` 0 it "9" $ loneSum 9 2 2 `shouldBe` 9 it "9" $ loneSum 2 2 9 `shouldBe` 9 it "9" $ loneSum 2 9 2 `shouldBe` 9 it "14" $ loneSum 2 9 3 `shouldBe` 14 it "9" $ loneSum 4 2 3 `shouldBe` 9 it "3" $ loneSum 1 3 1 `shouldBe` 3
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Logic-2/loneSum.hs
haskell
From Given 3 int values , a b c , return their sum . However , if one of the values is the same as another of the values , it does not count towards the sum . Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. -} import Test.Hspec ( hspec, describe, it, shouldBe ) loneSum :: Int -> Int -> Int -> Int loneSum a b c = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "6" $ loneSum 1 2 3 `shouldBe` 6 it "2" $ loneSum 3 2 3 `shouldBe` 2 it "0" $ loneSum 3 3 3 `shouldBe` 0 it "9" $ loneSum 9 2 2 `shouldBe` 9 it "9" $ loneSum 2 2 9 `shouldBe` 9 it "9" $ loneSum 2 9 2 `shouldBe` 9 it "14" $ loneSum 2 9 3 `shouldBe` 14 it "9" $ loneSum 4 2 3 `shouldBe` 9 it "3" $ loneSum 1 3 1 `shouldBe` 3
b3f04e4e4af5fd5296374b61325a0bfdfcc1517dafc69e0e51f7adc3c5cf9a2a
ndmitchell/catch
ConstLift.hs
-- If a function is a constant then inline it -- If a function only calls constant functions, then inline it module Hite.ConstLift(cmd) where import Hite.Type import General.General import Data.List import Data.Maybe import Hite.Normalise cmd = cmdHitePure (const constLift) "const-lift" "Lift all constants" constLift :: Hite -> Hite constLift = resultConst . dropWrappers . normalise resultConst :: Hite -> Hite resultConst hite = fixp hite [] where fixp hite done = if null res then hite else fixp (mapExpr (g res) hite) done2 where done2 = map fst res ++ done res = concatMap isConst $ filter (\x -> not $ funcName x `elem` done) $ funcs hite g res x@(Call (CallFunc n) xs) = case lookup n res of Nothing -> x Just i -> i g res x = x isConst (Func name _ body _) = [(name,body) | all f $ allExpr body] where f (Make _ _) = True f (Msg _) = True f _ = False -- if f x = x then drop all calls to f x with x -- mainly targets primString etc dropWrappers :: Hite -> Hite dropWrappers hite = mapExpr g hite where g x@(Call (CallFunc n) xs) = case lookup n res of Just i | length xs > i -> xs !! i _ -> x g x = x res = concatMap f (funcs hite) f (Func name args (Var i) _) = [(name, fromJust $ elemIndex i args)] f _ = []
null
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/src/Hite/ConstLift.hs
haskell
If a function is a constant then inline it If a function only calls constant functions, then inline it if f x = x then drop all calls to f x with x mainly targets primString etc
module Hite.ConstLift(cmd) where import Hite.Type import General.General import Data.List import Data.Maybe import Hite.Normalise cmd = cmdHitePure (const constLift) "const-lift" "Lift all constants" constLift :: Hite -> Hite constLift = resultConst . dropWrappers . normalise resultConst :: Hite -> Hite resultConst hite = fixp hite [] where fixp hite done = if null res then hite else fixp (mapExpr (g res) hite) done2 where done2 = map fst res ++ done res = concatMap isConst $ filter (\x -> not $ funcName x `elem` done) $ funcs hite g res x@(Call (CallFunc n) xs) = case lookup n res of Nothing -> x Just i -> i g res x = x isConst (Func name _ body _) = [(name,body) | all f $ allExpr body] where f (Make _ _) = True f (Msg _) = True f _ = False dropWrappers :: Hite -> Hite dropWrappers hite = mapExpr g hite where g x@(Call (CallFunc n) xs) = case lookup n res of Just i | length xs > i -> xs !! i _ -> x g x = x res = concatMap f (funcs hite) f (Func name args (Var i) _) = [(name, fromJust $ elemIndex i args)] f _ = []
9070540d60d5ec725a45c9712b45c1497f01e35c60206347e0f089de4fe2acc3
orbitz/oort
mdb_bhv_answer.erl
File : mdb_bhv_answer.erl Author : < > %%% Purpose : Created : 12 Aug 2003 by < > %%%---------------------------------------------------------------------- %%% This file is part of Manderlbot . %%% Manderlbot 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 2 of the License , or %%% (at your option) any later version. %%% Manderlbot 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. %%% %%% See LICENSE for detailled license %%% %%% In addition, as a special exception, you have the permission to %%% link the code of this program with any library released under the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception %%% to your version of the file, but you are not obligated to do %%% so. If you do not wish to do so, delete this exception %%% statement from your version. %%% %%%---------------------------------------------------------------------- -module(mdb_bhv_answer). -vc('$Id: mdb_bhv_answer.erl,v 1.2 2003/08/20 16:26:27 nico Exp $ '). -author(''). -export([behaviour/5]). % MDB behaviour API -include("mdb.hrl"). %%%---------------------------------------------------------------------- %%% Function: behaviour/5 %%% Purpose: Answer the given (config) data to the one who talk %%%---------------------------------------------------------------------- behaviour(Input = #data{header_to=BotName}, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, String, NickFrom) end, Data); behaviour(Input, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, NickFrom ++ ": " ++ String) end, Data).
null
https://raw.githubusercontent.com/orbitz/oort/a61ec85508917ae9a3f6672a0b708d47c23bb260/manderlbot-0.9.2/src/mdb_bhv_answer.erl
erlang
Purpose : ---------------------------------------------------------------------- (at your option) any later version. 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. See LICENSE for detailled license In addition, as a special exception, you have the permission to link the code of this program with any library released under to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. ---------------------------------------------------------------------- MDB behaviour API ---------------------------------------------------------------------- Function: behaviour/5 Purpose: Answer the given (config) data to the one who talk ----------------------------------------------------------------------
File : mdb_bhv_answer.erl Author : < > Created : 12 Aug 2003 by < > This file is part of Manderlbot . Manderlbot 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 2 of the License , or Manderlbot is distributed in the hope that it will be useful , the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception -module(mdb_bhv_answer). -vc('$Id: mdb_bhv_answer.erl,v 1.2 2003/08/20 16:26:27 nico Exp $ '). -author(''). -include("mdb.hrl"). behaviour(Input = #data{header_to=BotName}, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, String, NickFrom) end, Data); behaviour(Input, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, NickFrom ++ ": " ++ String) end, Data).
3f39165a3624d6b35a6598c47531b2bbf4810b6274529200f30a00368d4be3fc
AndrasKovacs/ELTE-func-lang
Notes06.hs
{-# language MonadComprehensions #-} {-# language DeriveFunctor, DeriveFoldable, DeriveTraversable #-} Lista monád , list comprehension , sublists , guard ( Alternative ) két class : Foldable , Parser monád Nagyobb példa : parser + interpreter minimális nyelvre ( " while " nyelv , int , bool + while ciklus , if - then - else , változó értékadás ) -------------------------------------------------------------------------------- {-# language DeriveFunctor #-} import Data.Traversable import Control.Applicative import Control.Monad newtype State s a = State {runState :: s -> (a, s)} deriving Functor instance Applicative (State s) where pure = return (<*>) = ap instance Monad (State s) where return a = State (\s -> (a, s)) State f >>= g = State (\s -> case f s of (a, s') -> runState (g a) s') get :: State s s get = State (\s -> (s, s)) put :: s -> State s () put s = State (\_ -> ((), s)) modify :: (s -> s) -> State s () modify f = do {s <- get; put (f s)} evalState :: State s a -> s -> a evalState ma = fst . runState ma execState :: State s a -> s -> s execState ma = snd . runState ma lista monád -------------------------------------------------------------------------------- instance [ ] where -- return a = [a] -- as >>= f = concatMap f as -- -- (>>=) = flip concatMap -- (<*>) :: [a -> b] -> [a] -> [b] példa : list1 :: [(Int, Int)] list1 = do legyen x bármilyen szám a listából ( nem - determinisztikus értékadás ) legyen y bármilyen a listából pure (x, y) -- BSc stílusban list1' :: [(Int, Int)] list1' = [(x, y) | x <- [0..10], y <- [0..x]] concatMap - el : list1'' :: [(Int, Int)] list1'' = concatMap (\x -> concatMap (\y -> [(x, y)]) [0..x]) [0..10] lista : lista monád instance - ra ! lista kifejezésben : szűrőfeltétel , ( + lokális let - definíció ) list2 :: [(Int, Int)] list2 = [(x, y) | x <- [0..10], let foo = x * x, y <- [0..x], even y] list2' :: [(Int, Int)] list2' = do x <- [0..10] let foo = x * x y <- [0..x] if even y then pure () -- (pure () == [()]) és (concatMap f [a] == f a) minden f,a-ra bármelyik sorban ha [ ] szerepel , a is [ ] ( concatMap f [ ] = = [ ] ) pure (x, y) emlékezzünk : pure ( ): nincs mellékhatása -- (pure () >> ma) == ma Lista monádban : egy elemű listával concatMap : hossza 1 - el szorzódik ( " mellékhatás " nélküli lista ) filter' :: (a -> Bool) -> [a] -> [a] filter' f as = [a | a <- as, f a] filter'' :: (a -> Bool) -> [a] -> [a] filter'' f as = do a <- as if f a then pure a else [] filter '' f as = concatMap ( \a - > if f a then [ a ] else [ ] ) as list3 :: [Int] minden lehetséges kombinációra alkalmazza a ( + ) -t do x < - [ 0 .. 10 ] y < - [ 0 .. 10 ] -- pure (x + y) példa függvényekre -- mapM :: (a -> m b) -> [a] -> m [b] -- mapM :: (a -> [b]) -> [a] -> [[b]] list4 :: [[Int]] ( a mapM definíciót , + lista monád definíciót ) list5 :: [[Int]] [ x , x*(-1 ) ] összes lehetséges kombinációja végeredmény klasszikus példa : összes lehetséges részlista megadása ( ) összes lehetséges mód , hogy 0 vagy több / elhagyjak a listából sublists as = filterM (\a -> [True, False]) as szűrőfeltétel és hamis is ( be ) filterM : : ( a - > m ) - > [ a ] - > m [ a ] ( a filterM / lista monád definíciót , hogy látszódjon a működés ) -- Alternative -------------------------------------------------------------------------------- a Control . Applicative - ban -- class Applicative f => Alternative f where -- empty :: f a -- (<|>) :: f a -> f a -> f a Monoid , viszont , hanem ( f : : * - > * ) konstruktorokra -- Alternative f : tetszőleges "a" típusra "f a" Monoid. -- instance Monoid (f a) where Alternative f = > ... ( " a"-ra Monoid ( f a ) ) -- Monoid (f a) => ... (konkrét "a"-ra Monoid (f a)) -- instance Alternative [] where -- empty = [] -- (<|>) = (++) : -- instance Alternative Maybe where -- empty = Nothing Just a < | > _ = Just a -- első Just - ot visszaadja ( ha iterált ( < | > ) ) -- _ <|> m = m -- Általánosítja a list szűrőfeltételt: -- guard :: Alternative f => Bool -> f () -- guard b = if b then pure () else empty guard megfelel a korábban látott szűrésnek ( do ) list2'' :: [(Int, Int)] list2'' = do x <- [0..10] let foo = x * x y <- [0..x] konkrét fordítása a szűrő kifejezésnek pure (x, y) miért guard - ra fordul a lista kifejezés , ha csak a lista guard - ot szeretnénk ? válasz : csak lista , hanem " monád kifejezés " { - # language MonadComprehensions # - } io1 :: IO String io1 = [xs ++ ys | xs <- getLine, ys <- getLine] -- do {xs <- getLine; ys <- getLine; pure (xs ++ ys)} -- Foldable -------------------------------------------------------------------------------- -- class Foldable t where -- foldr :: (a -> b -> b) -> b -> t a -> b Minden olyan " t"-re adható instance , ekvivalens : toList : : t a - > [ a ] -- (standard: Data.Foldable) toList :: Foldable t => t a -> [a] toList ta = foldr (:) [] ta foldr' :: (t a -> [a]) -> (a -> b -> b) -> b -> t a -> b foldr' toList f b ta = foldr f b (toList ta) hatékonyabb , ha köztes lista nélkül fold - olunk data T a = T a a a instance Foldable T where foldr f b (T x y z) = f x (f y (f z b)) -- generikus Foldable függvények: length, sum, product, elem, find ( : írjunk foldr - t fákra ) data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show, Functor) instance Foldable Tree where -- nem könnyű foldr = undefined -------------------------------------------------------------------------------- class ( Functor t , Foldable t ) = > t where -- traverse :: Applicative f => (a -> f b) -> t a -> f (t b) -- először néztük mapM :: ... -- mapA :: Applicative f => (a -> f b) -> [a] -> f [b] traverse : : ( t , Applicative f ) = > ( a - > f b ) - > t a - > f ( t b ) mapM túlterhelése , működik instance Traversable Tree where hajtsuk végre a " a"-n a Leaf - ekben , -- az eredmény értékek fáját traverse f (Leaf a) = Leaf <$> f a traverse f (Node l r) = Node <$> traverse f l <*> traverse f r -- IO példa: traverse (\_ -> getLine) (Node (Leaf 0) (Leaf 10)) State példa : -- korábbi label függvény definíciója -- label :: Tree a -> Tree (a, Int) -- label t = evalState (traverse go t) 0 where -- go :: a -> State Int (a, Int) -- go a = do -- n <- get -- put (n + 1) -- pure (a, n) osztályok : -- Functor: fmap -- Foldable: sum, length, foldr, foldl, .... : traverse ( map - elés + mellékhatás ) három : derive - olható ! -- {-# language DeriveFunctor, DeriveFoldable, DeriveTraversable #-} data Tree2 a = Leaf2 a | Node2A (Tree2 a) (Tree2 a) | Node2B (Tree2 a) (Tree2 a) (Tree2 a) deriving (Eq, Show, Functor, Foldable, Traversable) általánosított label : működik Tree , Tree2 , lista , stb ... label :: Traversable t => t a -> t (a, Int) label t = evalState (traverse go t) 0 where go :: a -> State Int (a, Int) go a = do n <- get put (n + 1) pure (a, n) mikor * * / Foldable ? ( viszont Functor ) : függvény Functor , / Foldable ( Foldable / : probléma , hogy minden lehetséges String input - ra meg kéne hívnom a függvényt ) newtype StringFun a = StringFun (String -> a) deriving (Functor) Első házi : héttől : ( )
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2020-21-1/ea/Notes06.hs
haskell
# language MonadComprehensions # # language DeriveFunctor, DeriveFoldable, DeriveTraversable # ------------------------------------------------------------------------------ # language DeriveFunctor # ------------------------------------------------------------------------------ return a = [a] as >>= f = concatMap f as -- (>>=) = flip concatMap (<*>) :: [a -> b] -> [a] -> [b] BSc stílusban (pure () == [()]) és (concatMap f [a] == f a) minden f,a-ra (pure () >> ma) == ma pure (x + y) mapM :: (a -> m b) -> [a] -> m [b] mapM :: (a -> [b]) -> [a] -> [[b]] Alternative ------------------------------------------------------------------------------ class Applicative f => Alternative f where empty :: f a (<|>) :: f a -> f a -> f a Alternative f : tetszőleges "a" típusra "f a" Monoid. instance Monoid (f a) where Monoid (f a) => ... (konkrét "a"-ra Monoid (f a)) instance Alternative [] where empty = [] (<|>) = (++) instance Alternative Maybe where empty = Nothing első Just - ot visszaadja ( ha iterált ( < | > ) ) _ <|> m = m Általánosítja a list szűrőfeltételt: guard :: Alternative f => Bool -> f () guard b = if b then pure () else empty do {xs <- getLine; ys <- getLine; pure (xs ++ ys)} Foldable ------------------------------------------------------------------------------ class Foldable t where foldr :: (a -> b -> b) -> b -> t a -> b (standard: Data.Foldable) generikus Foldable függvények: length, sum, product, elem, find nem könnyű ------------------------------------------------------------------------------ traverse :: Applicative f => (a -> f b) -> t a -> f (t b) először néztük mapM :: ... mapA :: Applicative f => (a -> f b) -> [a] -> f [b] az eredmény értékek fáját IO példa: traverse (\_ -> getLine) (Node (Leaf 0) (Leaf 10)) korábbi label függvény definíciója label :: Tree a -> Tree (a, Int) label t = evalState (traverse go t) 0 where go :: a -> State Int (a, Int) go a = do n <- get put (n + 1) pure (a, n) Functor: fmap Foldable: sum, length, foldr, foldl, .... {-# language DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
Lista monád , list comprehension , sublists , guard ( Alternative ) két class : Foldable , Parser monád Nagyobb példa : parser + interpreter minimális nyelvre ( " while " nyelv , int , bool + while ciklus , if - then - else , változó értékadás ) import Data.Traversable import Control.Applicative import Control.Monad newtype State s a = State {runState :: s -> (a, s)} deriving Functor instance Applicative (State s) where pure = return (<*>) = ap instance Monad (State s) where return a = State (\s -> (a, s)) State f >>= g = State (\s -> case f s of (a, s') -> runState (g a) s') get :: State s s get = State (\s -> (s, s)) put :: s -> State s () put s = State (\_ -> ((), s)) modify :: (s -> s) -> State s () modify f = do {s <- get; put (f s)} evalState :: State s a -> s -> a evalState ma = fst . runState ma execState :: State s a -> s -> s execState ma = snd . runState ma lista monád instance [ ] where példa : list1 :: [(Int, Int)] list1 = do legyen x bármilyen szám a listából ( nem - determinisztikus értékadás ) legyen y bármilyen a listából pure (x, y) list1' :: [(Int, Int)] list1' = [(x, y) | x <- [0..10], y <- [0..x]] concatMap - el : list1'' :: [(Int, Int)] list1'' = concatMap (\x -> concatMap (\y -> [(x, y)]) [0..x]) [0..10] lista : lista monád instance - ra ! lista kifejezésben : szűrőfeltétel , ( + lokális let - definíció ) list2 :: [(Int, Int)] list2 = [(x, y) | x <- [0..10], let foo = x * x, y <- [0..x], even y] list2' :: [(Int, Int)] list2' = do x <- [0..10] let foo = x * x y <- [0..x] bármelyik sorban ha [ ] szerepel , a is [ ] ( concatMap f [ ] = = [ ] ) pure (x, y) emlékezzünk : pure ( ): nincs mellékhatása Lista monádban : egy elemű listával concatMap : hossza 1 - el szorzódik ( " mellékhatás " nélküli lista ) filter' :: (a -> Bool) -> [a] -> [a] filter' f as = [a | a <- as, f a] filter'' :: (a -> Bool) -> [a] -> [a] filter'' f as = do a <- as if f a then pure a else [] filter '' f as = concatMap ( \a - > if f a then [ a ] else [ ] ) as list3 :: [Int] minden lehetséges kombinációra alkalmazza a ( + ) -t do x < - [ 0 .. 10 ] y < - [ 0 .. 10 ] példa függvényekre list4 :: [[Int]] ( a mapM definíciót , + lista monád definíciót ) list5 :: [[Int]] [ x , x*(-1 ) ] összes lehetséges kombinációja végeredmény klasszikus példa : összes lehetséges részlista megadása ( ) összes lehetséges mód , hogy 0 vagy több / elhagyjak a listából sublists as = filterM (\a -> [True, False]) as szűrőfeltétel és hamis is ( be ) filterM : : ( a - > m ) - > [ a ] - > m [ a ] ( a filterM / lista monád definíciót , hogy látszódjon a működés ) a Control . Applicative - ban Monoid , viszont , hanem ( f : : * - > * ) konstruktorokra Alternative f = > ... ( " a"-ra Monoid ( f a ) ) : guard megfelel a korábban látott szűrésnek ( do ) list2'' :: [(Int, Int)] list2'' = do x <- [0..10] let foo = x * x y <- [0..x] konkrét fordítása a szűrő kifejezésnek pure (x, y) miért guard - ra fordul a lista kifejezés , ha csak a lista guard - ot szeretnénk ? válasz : csak lista , hanem " monád kifejezés " { - # language MonadComprehensions # - } io1 :: IO String io1 = [xs ++ ys | xs <- getLine, ys <- getLine] Minden olyan " t"-re adható instance , ekvivalens : toList : : t a - > [ a ] toList :: Foldable t => t a -> [a] toList ta = foldr (:) [] ta foldr' :: (t a -> [a]) -> (a -> b -> b) -> b -> t a -> b foldr' toList f b ta = foldr f b (toList ta) hatékonyabb , ha köztes lista nélkül fold - olunk data T a = T a a a instance Foldable T where foldr f b (T x y z) = f x (f y (f z b)) ( : írjunk foldr - t fákra ) data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show, Functor) foldr = undefined class ( Functor t , Foldable t ) = > t where traverse : : ( t , Applicative f ) = > ( a - > f b ) - > t a - > f ( t b ) mapM túlterhelése , működik instance Traversable Tree where hajtsuk végre a " a"-n a Leaf - ekben , traverse f (Leaf a) = Leaf <$> f a traverse f (Node l r) = Node <$> traverse f l <*> traverse f r State példa : osztályok : : traverse ( map - elés + mellékhatás ) három : derive - olható ! data Tree2 a = Leaf2 a | Node2A (Tree2 a) (Tree2 a) | Node2B (Tree2 a) (Tree2 a) (Tree2 a) deriving (Eq, Show, Functor, Foldable, Traversable) általánosított label : működik Tree , Tree2 , lista , stb ... label :: Traversable t => t a -> t (a, Int) label t = evalState (traverse go t) 0 where go :: a -> State Int (a, Int) go a = do n <- get put (n + 1) pure (a, n) mikor * * / Foldable ? ( viszont Functor ) : függvény Functor , / Foldable ( Foldable / : probléma , hogy minden lehetséges String input - ra meg kéne hívnom a függvényt ) newtype StringFun a = StringFun (String -> a) deriving (Functor) Első házi : héttől : ( )